@aituber-onair/chat 0.50.0 → 0.51.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 (67) hide show
  1. package/README.ja.md +22 -7
  2. package/README.md +22 -7
  3. package/dist/cjs/backend.d.ts +20 -0
  4. package/dist/cjs/backend.d.ts.map +1 -0
  5. package/dist/cjs/backend.js +115 -0
  6. package/dist/cjs/backend.js.map +1 -0
  7. package/dist/cjs/constants/xai.d.ts +6 -1
  8. package/dist/cjs/constants/xai.d.ts.map +1 -1
  9. package/dist/cjs/constants/xai.js +29 -7
  10. package/dist/cjs/constants/xai.js.map +1 -1
  11. package/dist/cjs/index.d.ts +1 -0
  12. package/dist/cjs/index.d.ts.map +1 -1
  13. package/dist/cjs/index.js +1 -0
  14. package/dist/cjs/index.js.map +1 -1
  15. package/dist/cjs/services/ChatServiceFactory.d.ts.map +1 -1
  16. package/dist/cjs/services/ChatServiceFactory.js +9 -18
  17. package/dist/cjs/services/ChatServiceFactory.js.map +1 -1
  18. package/dist/cjs/services/providers/gemini/GeminiChatService.d.ts.map +1 -1
  19. package/dist/cjs/services/providers/gemini/GeminiChatService.js +3 -0
  20. package/dist/cjs/services/providers/gemini/GeminiChatService.js.map +1 -1
  21. package/dist/cjs/services/providers/gemini/geminiMessageConverter.d.ts +5 -0
  22. package/dist/cjs/services/providers/gemini/geminiMessageConverter.d.ts.map +1 -1
  23. package/dist/cjs/services/providers/gemini/geminiMessageConverter.js +16 -0
  24. package/dist/cjs/services/providers/gemini/geminiMessageConverter.js.map +1 -1
  25. package/dist/cjs/services/providers/openai/openaiRequestBuilder.d.ts.map +1 -1
  26. package/dist/cjs/services/providers/openai/openaiRequestBuilder.js +27 -5
  27. package/dist/cjs/services/providers/openai/openaiRequestBuilder.js.map +1 -1
  28. package/dist/cjs/services/providers/openai/responsesParser.d.ts.map +1 -1
  29. package/dist/cjs/services/providers/openai/responsesParser.js +71 -6
  30. package/dist/cjs/services/providers/openai/responsesParser.js.map +1 -1
  31. package/dist/cjs/services/providers/xai/XAIChatServiceProvider.d.ts.map +1 -1
  32. package/dist/cjs/services/providers/xai/XAIChatServiceProvider.js +1 -0
  33. package/dist/cjs/services/providers/xai/XAIChatServiceProvider.js.map +1 -1
  34. package/dist/esm/backend.d.ts +20 -0
  35. package/dist/esm/backend.d.ts.map +1 -0
  36. package/dist/esm/backend.js +111 -0
  37. package/dist/esm/backend.js.map +1 -0
  38. package/dist/esm/constants/xai.d.ts +6 -1
  39. package/dist/esm/constants/xai.d.ts.map +1 -1
  40. package/dist/esm/constants/xai.js +27 -6
  41. package/dist/esm/constants/xai.js.map +1 -1
  42. package/dist/esm/index.d.ts +1 -0
  43. package/dist/esm/index.d.ts.map +1 -1
  44. package/dist/esm/index.js +1 -0
  45. package/dist/esm/index.js.map +1 -1
  46. package/dist/esm/services/ChatServiceFactory.d.ts.map +1 -1
  47. package/dist/esm/services/ChatServiceFactory.js +9 -18
  48. package/dist/esm/services/ChatServiceFactory.js.map +1 -1
  49. package/dist/esm/services/providers/gemini/GeminiChatService.d.ts.map +1 -1
  50. package/dist/esm/services/providers/gemini/GeminiChatService.js +4 -1
  51. package/dist/esm/services/providers/gemini/GeminiChatService.js.map +1 -1
  52. package/dist/esm/services/providers/gemini/geminiMessageConverter.d.ts +5 -0
  53. package/dist/esm/services/providers/gemini/geminiMessageConverter.d.ts.map +1 -1
  54. package/dist/esm/services/providers/gemini/geminiMessageConverter.js +15 -0
  55. package/dist/esm/services/providers/gemini/geminiMessageConverter.js.map +1 -1
  56. package/dist/esm/services/providers/openai/openaiRequestBuilder.d.ts.map +1 -1
  57. package/dist/esm/services/providers/openai/openaiRequestBuilder.js +27 -5
  58. package/dist/esm/services/providers/openai/openaiRequestBuilder.js.map +1 -1
  59. package/dist/esm/services/providers/openai/responsesParser.d.ts.map +1 -1
  60. package/dist/esm/services/providers/openai/responsesParser.js +71 -6
  61. package/dist/esm/services/providers/openai/responsesParser.js.map +1 -1
  62. package/dist/esm/services/providers/xai/XAIChatServiceProvider.d.ts.map +1 -1
  63. package/dist/esm/services/providers/xai/XAIChatServiceProvider.js +2 -1
  64. package/dist/esm/services/providers/xai/XAIChatServiceProvider.js.map +1 -1
  65. package/dist/umd/aituber-onair-chat.js +249 -32
  66. package/dist/umd/aituber-onair-chat.min.js +9 -9
  67. package/package.json +6 -1
@@ -1,4 +1,4 @@
1
- "use strict";var AITuberOnAirChat=(()=>{var Bo=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Zi=Object.prototype.hasOwnProperty;var Yi=(n,e)=>{for(var t in e)Bo(n,t,{get:e[t],enumerable:!0})},Qi=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ji(e))!Zi.call(n,i)&&i!==t&&Bo(n,i,{get:()=>e[i],enumerable:!(o=Xi(e,i))||o.enumerable});return n};var er=n=>Qi(Bo({},"__esModule",{value:!0}),n);var is={};Yi(is,{CHAT_RESPONSE_LENGTH:()=>S,CLAUDE_VISION_SUPPORTED_MODELS:()=>ht,ChatServiceFactory:()=>Ye,ChatServiceHttpClient:()=>E,ClaudeChatService:()=>ye,ClaudeChatServiceProvider:()=>xe,DEEPSEEK_API_BASE_URL:()=>ci,DEEPSEEK_DEPRECATED_MODELS:()=>Mr,DEEPSEEK_SUPPORTED_MODELS:()=>Pn,DEFAULT_MAX_TOKENS:()=>Un,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>Sr,DEFAULT_VISION_PROMPT:()=>vr,DeepSeekChatService:()=>Ie,DeepSeekChatServiceProvider:()=>De,EMOTION_TAG_CLEANUP_REGEX:()=>Bn,EMOTION_TAG_REGEX:()=>Si,ENDPOINT_CLAUDE_API:()=>rn,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>vt,ENDPOINT_GEMINI_API:()=>Xo,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>ve,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Ct,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>j,ENDPOINT_OPENAI_RESPONSES_API:()=>A,ENDPOINT_OPENROUTER_API:()=>dt,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>Pt,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>Lt,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>ft,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>gt,EmotionParser:()=>Re,GEMINI_DEPRECATED_MODELS:()=>ti,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Hn,GEMINI_RECOMMENDED_MODELS:()=>kt,GEMINI_VISION_SUPPORTED_MODELS:()=>nt,GPT5_PRESETS:()=>Kn,GPT_5_MODELS:()=>jn,GeminiChatService:()=>Ae,GeminiChatServiceProvider:()=>be,GeminiNanoChatService:()=>Ne,GeminiNanoChatServiceProvider:()=>we,HttpError:()=>q,KIMI_THINKING_REQUIRED_MODELS:()=>pi,KIMI_VISION_SUPPORTED_MODELS:()=>li,KimiChatService:()=>ke,KimiChatServiceProvider:()=>Ge,MAX_TOKENS_BY_LENGTH:()=>Vo,MISTRAL_API_BASE_URL:()=>mi,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>gi,MISTRAL_SUPPORTED_MODELS:()=>wn,MISTRAL_VISION_SUPPORTED_MODELS:()=>fi,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>ln,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>ho,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>mo,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>lo,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>co,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>po,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>uo,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>ao,MODEL_CLAUDE_3_5_HAIKU:()=>sr,MODEL_CLAUDE_3_5_SONNET:()=>ar,MODEL_CLAUDE_3_7_SONNET:()=>lr,MODEL_CLAUDE_3_HAIKU:()=>Ft,MODEL_CLAUDE_4_5_HAIKU:()=>b,MODEL_CLAUDE_4_5_OPUS:()=>rt,MODEL_CLAUDE_4_5_SONNET:()=>Ht,MODEL_CLAUDE_4_6_OPUS:()=>at,MODEL_CLAUDE_4_6_SONNET:()=>st,MODEL_CLAUDE_4_7_OPUS:()=>lt,MODEL_CLAUDE_4_8_OPUS:()=>pt,MODEL_CLAUDE_4_OPUS:()=>Kt,MODEL_CLAUDE_4_SONNET:()=>Ut,MODEL_CLAUDE_5_OPUS:()=>ut,MODEL_CLAUDE_5_SONNET:()=>ct,MODEL_DEEPSEEK_CHAT:()=>ui,MODEL_DEEPSEEK_REASONER:()=>hi,MODEL_DEEPSEEK_V4_FLASH:()=>re,MODEL_DEEPSEEK_V4_PRO:()=>ko,MODEL_FUGU:()=>Le,MODEL_FUGU_ULTRA:()=>Ei,MODEL_FUGU_ULTRA_20260615:()=>Oi,MODEL_GEMINI_2_5_FLASH:()=>Yn,MODEL_GEMINI_2_5_FLASH_LITE:()=>Qn,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>ei,MODEL_GEMINI_2_5_PRO:()=>Zn,MODEL_GEMINI_3_1_FLASH_LITE:()=>$,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>en,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Qo,MODEL_GEMINI_3_5_FLASH:()=>Zo,MODEL_GEMINI_3_5_FLASH_LITE:()=>Yo,MODEL_GEMINI_3_6_FLASH:()=>Jo,MODEL_GEMINI_3_FLASH_PREVIEW:()=>on,MODEL_GEMINI_3_PRO_PREVIEW:()=>tn,MODEL_GEMINI_NANO:()=>se,MODEL_GEMMA_4_26B_A4B_IT:()=>Jn,MODEL_GEMMA_4_31B_IT:()=>Xn,MODEL_GLM_4_6:()=>Sn,MODEL_GLM_4_6V:()=>yo,MODEL_GLM_4_6V_FLASH:()=>ne,MODEL_GLM_4_6V_FLASHX:()=>xo,MODEL_GLM_4_7:()=>On,MODEL_GLM_4_7_FLASH:()=>vn,MODEL_GLM_4_7_FLASHX:()=>Mn,MODEL_GLM_5:()=>_n,MODEL_GLM_5V_TURBO:()=>Ro,MODEL_GLM_5_1:()=>fn,MODEL_GLM_5_2:()=>fe,MODEL_GLM_5_TURBO:()=>En,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>Mo,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>vo,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Oo,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>Eo,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>_o,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>fo,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>go,MODEL_GPT_4O:()=>bt,MODEL_GPT_4O_MINI:()=>ee,MODEL_GPT_4_1:()=>It,MODEL_GPT_4_1_MINI:()=>Dt,MODEL_GPT_4_1_NANO:()=>At,MODEL_GPT_5:()=>pe,MODEL_GPT_5_1:()=>ce,MODEL_GPT_5_4:()=>J,MODEL_GPT_5_4_MINI:()=>Y,MODEL_GPT_5_4_NANO:()=>Q,MODEL_GPT_5_4_PRO:()=>W,MODEL_GPT_5_5:()=>Z,MODEL_GPT_5_6:()=>U,MODEL_GPT_5_6_LUNA:()=>B,MODEL_GPT_5_6_SOL:()=>K,MODEL_GPT_5_6_TERRA:()=>H,MODEL_GPT_5_MINI:()=>le,MODEL_GPT_5_NANO:()=>X,MODEL_GPT_OSS_20B_FREE:()=>w,MODEL_GROK_4_1_FAST_NON_REASONING:()=>k,MODEL_GROK_4_1_FAST_REASONING:()=>Ao,MODEL_GROK_4_20_NON_REASONING:()=>Do,MODEL_GROK_4_20_REASONING:()=>Io,MODEL_GROK_4_3:()=>Oe,MODEL_GROK_4_5:()=>Ee,MODEL_KIMI_K2_5:()=>wo,MODEL_KIMI_K2_6:()=>G,MODEL_KIMI_K2_7_CODE:()=>Et,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>Ot,MODEL_KIMI_K3:()=>Se,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>un,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>hn,MODEL_MINISTRAL_14B_2512:()=>In,MODEL_MINISTRAL_3B_2512:()=>yn,MODEL_MINISTRAL_8B_2512:()=>xn,MODEL_MISTRAL_LARGE_2512:()=>Nn,MODEL_MISTRAL_LARGE_LATEST:()=>bn,MODEL_MISTRAL_MEDIUM_2508:()=>An,MODEL_MISTRAL_MEDIUM_3_5:()=>Go,MODEL_MISTRAL_SMALL_2603:()=>Dn,MODEL_MISTRAL_SMALL_LATEST:()=>V,MODEL_MOONSHOTAI_KIMI_K2_5:()=>$t,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>Wt,MODEL_MOONSHOTAI_KIMI_K3:()=>Bt,MODEL_MOONSHOTAI_KIMI_LATEST:()=>zt,MODEL_O1:()=>zo,MODEL_O1_MINI:()=>$o,MODEL_O3_MINI:()=>Wo,MODEL_OPENAI_GPT_4O:()=>io,MODEL_OPENAI_GPT_4_1_MINI:()=>ro,MODEL_OPENAI_GPT_4_1_NANO:()=>so,MODEL_OPENAI_GPT_5_1_CHAT:()=>eo,MODEL_OPENAI_GPT_5_1_CODEX:()=>to,MODEL_OPENAI_GPT_5_5:()=>Qt,MODEL_OPENAI_GPT_5_5_PRO:()=>Yt,MODEL_OPENAI_GPT_5_6_LUNA:()=>Zt,MODEL_OPENAI_GPT_5_6_SOL:()=>Xt,MODEL_OPENAI_GPT_5_6_TERRA:()=>Jt,MODEL_OPENAI_GPT_5_MINI:()=>oo,MODEL_OPENAI_GPT_5_NANO:()=>no,MODEL_OPENAI_GPT_LATEST:()=>qt,MODEL_OPENAI_GPT_MINI_LATEST:()=>jt,MODEL_OPENROUTER_AUTO:()=>mt,MODEL_OPENROUTER_AUTO_BETA:()=>ue,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>de,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>me,MODEL_OPENROUTER_FUSION:()=>an,MODEL_PLAMO_2_2_PRIME:()=>vi,MODEL_PLAMO_3_0_PRIME:()=>Pe,MODEL_XAI_GROK_4_5:()=>To,MODEL_XAI_GROK_LATEST:()=>Co,MODEL_ZAI_GLM_4_5_AIR:()=>cn,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>So,MODEL_ZAI_GLM_4_7_FLASH:()=>pn,MODEL_ZAI_GLM_5_2:()=>he,MistralChatService:()=>Ve,MistralChatServiceProvider:()=>Fe,OPENROUTER_CREDITS_THRESHOLD:()=>fr,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>gr,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>mr,OPENROUTER_FREE_MODELS:()=>dn,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>mn,OPENROUTER_VISION_SUPPORTED_MODELS:()=>ri,OpenAIChatService:()=>L,OpenAIChatServiceProvider:()=>Ke,OpenAICompatibleChatServiceProvider:()=>Ue,OpenRouterChatService:()=>He,OpenRouterChatServiceProvider:()=>Be,PLAMO_API_BASE_URL:()=>Mi,PLAMO_SUPPORTED_MODELS:()=>Fn,PlamoChatService:()=>We,PlamoChatServiceProvider:()=>$e,SAKANA_API_BASE_URL:()=>_i,SAKANA_SUPPORTED_MODELS:()=>Vn,SakanaChatService:()=>ze,SakanaChatServiceProvider:()=>qe,StreamTextAccumulator:()=>O,VISION_SUPPORTED_MODELS:()=>Qe,XAIChatService:()=>je,XAIChatServiceProvider:()=>Xe,XAI_VISION_SUPPORTED_MODELS:()=>ai,ZAIChatService:()=>Je,ZAIChatServiceProvider:()=>Ze,ZAI_VISION_SUPPORTED_MODELS:()=>si,allowsReasoningLow:()=>wt,allowsReasoningMax:()=>jo,allowsReasoningMinimal:()=>tt,allowsReasoningNone:()=>et,allowsReasoningXHigh:()=>Nt,buildOpenAICompatibleTools:()=>D,getClaudeSupportedReasoningEfforts:()=>N,getDeepSeekSupportedReasoningEfforts:()=>St,getDefaultClaudeReasoningEffort:()=>ii,getDefaultDeepSeekReasoningEffort:()=>Ln,getDefaultGeminiReasoningEffort:()=>rr,getDefaultKimiReasoningEffort:()=>Te,getDefaultOpenRouterReasoningEffort:()=>Po,getDefaultReasoningEffortForGPT5Model:()=>ot,getDefaultXaiReasoningEffort:()=>No,getGeminiSupportedReasoningEfforts:()=>Gt,getKimiSupportedReasoningEfforts:()=>z,getMaxTokensForResponseLength:()=>T,getOpenRouterSupportedReasoningEfforts:()=>Lo,installGASFetch:()=>qi,isClaudeReasoningEffortModel:()=>ni,isDeepSeekReasoningEffortModel:()=>di,isGPT5Model:()=>te,isGeminiReasoningEffortModel:()=>nn,isKimiReasoningEffortModel:()=>ie,isKimiThinkingRequiredModel:()=>Mt,isKimiVisionModel:()=>Ce,isMistralReasoningEffort:()=>kn,isMistralReasoningEffortModel:()=>Tt,isMistralVisionModel:()=>Gn,isOpenRouterFreeModel:()=>oe,isOpenRouterVisionModel:()=>ge,isResponsesOnlyGPT5Model:()=>qo,isXaiReasoningEffortModel:()=>bo,isXaiReasoningEffortNoneModel:()=>Tn,isXaiVisionModel:()=>Me,isZaiToolStreamModel:()=>Cn,isZaiVisionModel:()=>_e,normalizeClaudeReasoningEffort:()=>cr,normalizeDeepSeekReasoningEffort:()=>Rn,normalizeGeminiReasoningEffort:()=>it,normalizeOpenRouterReasoningEffort:()=>gn,normalizeXaiReasoningEffort:()=>_t,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>F,parseOpenAICompatibleToolStream:()=>x,processChatWithOptionalTools:()=>M,refreshOpenRouterFreeModels:()=>kr,resolveVisionModel:()=>C,runOnceText:()=>Pr,safeJsonParse:()=>Ti,safeParseToolCallInput:()=>ae,screenplayToText:()=>Lr,textToScreenplay:()=>Ci,textsToScreenplay:()=>Tr});var j="https://api.openai.com/v1/chat/completions",A="https://api.openai.com/v1/responses",X="gpt-5-nano",le="gpt-5-mini",pe="gpt-5",ce="gpt-5.1",J="gpt-5.4",Z="gpt-5.5",U="gpt-5.6",K="gpt-5.6-sol",H="gpt-5.6-terra",B="gpt-5.6-luna",Y="gpt-5.4-mini",Q="gpt-5.4-nano",W="gpt-5.4-pro",It="gpt-4.1",Dt="gpt-4.1-mini",At="gpt-4.1-nano",ee="gpt-4o-mini",bt="gpt-4o",Wo="o3-mini",$o="o1-mini",zo="o1",Qe=[X,le,pe,ce,J,Z,U,K,H,B,Y,Q,W,It,Dt,At,ee,bt,"o1"],jn=[X,le,pe,ce,J,Z,U,K,H,B,Y,Q,W];function te(n){return jn.includes(n)}function qo(n){return n===W}function Nt(n){return n===U||n===K||n===H||n===B||n===Z||n===J||n===Y||n===Q||n===W}function jo(n){return n===U||n===K||n===H||n===B}function et(n){return n===U||n===K||n===H||n===B||n===ce||n===J||n===Z||n===Y||n===Q}function tt(n){return n===X||n===le||n===pe}function wt(n){return n!==W}function ot(n){return et(n)?"none":tt(n)?"minimal":"medium"}var Xo="https://generativelanguage.googleapis.com",Xn="gemma-4-31b-it",Jn="gemma-4-26b-a4b-it",Jo="gemini-3.6-flash",Zo="gemini-3.5-flash",Yo="gemini-3.5-flash-lite",Qo="gemini-3.1-pro-preview",$="gemini-3.1-flash-lite",en="gemini-3.1-flash-lite-preview",tn="gemini-3-pro-preview",on="gemini-3-flash-preview",Zn="gemini-2.5-pro",Yn="gemini-2.5-flash",Qn="gemini-2.5-flash-lite",ei="gemini-2.5-flash-lite-preview-06-17",kt=[Jo,Zo,Yo,$,Qo,on,Zn,Yn,Qn,Xn,Jn],ti=[en,tn,ei],nt=[...kt,...ti],tr=["minimal","low","medium","high"],or=["low","medium","high"],nr=[Jo,Zo,Yo,$,en,on],ir=[Qo,tn];function Gt(n){return nr.includes(n)?tr:ir.includes(n)?or:[]}function nn(n){return Gt(n).length>0}function rr(n){return Gt(n)[0]}function it(n,e){let t=Gt(n);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var rn="https://api.anthropic.com/v1/messages",Ft="claude-3-haiku-20240307",sr="claude-3-5-haiku-20241022",ar="claude-3-5-sonnet-20241022",lr="claude-3-7-sonnet-20250219",Ut="claude-sonnet-4-20250514",Kt="claude-opus-4-20250514",Ht="claude-sonnet-4-5-20250929",b="claude-haiku-4-5-20251001",rt="claude-opus-4-5-20251101",st="claude-sonnet-4-6",at="claude-opus-4-6",lt="claude-opus-4-7",pt="claude-opus-4-8",ct="claude-sonnet-5",ut="claude-opus-5",sn=["low","medium","high"],oi=[...sn,"max"],Vt=[...sn,"xhigh","max"],pr={[rt]:sn,[st]:oi,[at]:oi,[lt]:Vt,[pt]:Vt,[ct]:Vt,[ut]:Vt},ht=[Ft,Ut,Kt,Ht,b,rt,st,at,lt,pt,ct,ut];function N(n){return pr[n]??[]}function ni(n){return N(n).length>0}function ii(n){return ni(n)?"high":void 0}function cr(n,e){let t=N(n);if(t.length!==0)return e?t.includes(e)?e:"high":ii(n)}var dt="https://openrouter.ai/api/v1/chat/completions",mt="openrouter/auto",ue="openrouter/auto-beta",an="openrouter/fusion",w="openai/gpt-oss-20b:free",Bt="moonshotai/kimi-k3",Wt="moonshotai/kimi-k2.7-code",$t="moonshotai/kimi-k2.5",zt="~moonshotai/kimi-latest",qt="~openai/gpt-latest",jt="~openai/gpt-mini-latest",Xt="openai/gpt-5.6-sol",Jt="openai/gpt-5.6-terra",Zt="openai/gpt-5.6-luna",Yt="openai/gpt-5.5-pro",Qt="openai/gpt-5.5",eo="openai/gpt-5.1-chat",to="openai/gpt-5.1-codex",oo="openai/gpt-5-mini",no="openai/gpt-5-nano",io="openai/gpt-4o",ro="openai/gpt-4.1-mini",so="openai/gpt-4.1-nano",ao="~anthropic/claude-sonnet-latest",lo="~anthropic/claude-haiku-latest",po="anthropic/claude-opus-5",co="anthropic/claude-opus-4",uo="anthropic/claude-sonnet-4",ho="anthropic/claude-3.7-sonnet",ln="anthropic/claude-3.5-sonnet",mo="anthropic/claude-haiku-4.5",go="~google/gemini-pro-latest",fo="~google/gemini-flash-latest",_o="google/gemini-3.6-flash",Eo="google/gemini-3.5-flash-lite",Oo="google/gemini-2.5-pro",Mo="google/gemini-2.5-flash",vo="google/gemini-2.5-flash-lite-preview-09-2025",he="z-ai/glm-5.2",pn="z-ai/glm-4.7-flash",cn="z-ai/glm-4.5-air",So="z-ai/glm-4.5-air:free",un="kwaipilot/kat-coder-air-v2.5",hn="kwaipilot/kat-coder-pro-v2.5",Co="~x-ai/grok-latest",To="x-ai/grok-4.5",de="deepseek/deepseek-v4-flash",me="deepseek/deepseek-v4-flash-0731",ur=["none","minimal","low","medium","high"],hr=["none","high","xhigh"],dr=["none","low","high","max"],dn=[w,So],ri=[ue,Bt,zt,qt,jt,Xt,Jt,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,mo,go,fo,_o,Eo,Oo,Mo,vo,Wt,$t,Co,To],mn=20,mr=50,gr=1e3,fr=10;function oe(n){return n.trim().endsWith(":free")}function ge(n){return ri.some(e=>n.includes(e))}function Lo(n){let e=n.trim();return e===de?hr:e===me?dr:ur}function Po(n){let e=n.trim();return e===he||e===de||e===me?"none":void 0}function gn(n,e){let t=n.trim(),o=e??Po(n);if(!o)return;if(Lo(n).includes(o))return o;if(t===de)return o==="max"?"xhigh":"none";if(t===me){if(o==="minimal"||o==="medium")return"low";if(o==="xhigh")return"high"}return o}var gt="https://api.z.ai/api/paas/v4/chat/completions",fe="glm-5.2",fn="glm-5.1",_n="glm-5",En="glm-5-turbo",Ro="glm-5v-turbo",On="glm-4.7",Mn="glm-4.7-FlashX",vn="glm-4.7-Flash",Sn="glm-4.6",yo="glm-4.6V",xo="glm-4.6V-FlashX",ne="glm-4.6V-Flash",si=[Ro,yo,xo,ne];function _e(n){return si.includes(n)}function Cn(n){return n.toLowerCase().startsWith("glm-4.6")}var ft="https://api.x.ai/v1/chat/completions",Ee="grok-4.5",Oe="grok-4.3",Io="grok-4.20-0309-reasoning",Do="grok-4.20-0309-non-reasoning",Ao="grok-4-1-fast-reasoning",k="grok-4-1-fast-non-reasoning",ai=[Ee,Oe,Io,Do,Ao,k];function Me(n){return ai.includes(n)}function bo(n){return n===Ee||n===Oe}function Tn(n){return n===Oe}function No(n){return n===Ee?"low":Tn(n)?"none":void 0}function _t(n,e){if(bo(n))return e==="none"&&!Tn(n)?"low":e??No(n)}var ve="https://api.moonshot.ai/v1/chat/completions",Se="kimi-k3",Et="kimi-k2.7-code",Ot="kimi-k2.7-code-highspeed",G="kimi-k2.6",wo="kimi-k2.5",_r={[Se]:["low","high","max"]},li=[Se,Et,Ot,G,wo],pi=[Et,Ot];function Ce(n){return li.includes(n)}function Mt(n){return pi.includes(n)}function z(n){return _r[n]??[]}function Te(n){return n===Se?"max":void 0}function ie(n){return z(n).length>0}var ci="https://api.deepseek.com",vt=`${ci}/chat/completions`,re="deepseek-v4-flash",ko="deepseek-v4-pro",Er=["none","low","high","max"],Or=["none","high","max"],ui="deepseek-chat",hi="deepseek-reasoner",Pn=[re,ko],Mr=[ui,hi];function St(n){return n===re?Er:n===ko?Or:[]}function di(n){return St(n).length>0}function Ln(n){return di(n)?"none":void 0}function Rn(n,e){let t=St(n);if(t.length===0)return;let o=e??Ln(n);return o&&t.includes(o)?o:n===ko&&o==="low"?"high":Ln(n)}var mi="https://api.mistral.ai/v1",Ct=`${mi}/chat/completions`,yn="ministral-3b-2512",xn="ministral-8b-2512",In="ministral-14b-2512",V="mistral-small-latest",Dn="mistral-small-2603",Go="mistral-medium-3-5",An="mistral-medium-2508",bn="mistral-large-latest",Nn="mistral-large-2512",wn=[V,yn,xn,In,Go,bn,Nn,Dn,An],gi=[V,Go],fi=[V,yn,xn,In,Dn,Go,An,bn,Nn];function Tt(n){return gi.includes(n)}function kn(n){return n==="none"||n==="high"}function Gn(n){return fi.includes(n)}var _i="https://api.sakana.ai/v1",Lt=`${_i}/chat/completions`,Le="fugu",Ei="fugu-ultra",Oi="fugu-ultra-20260615",Vn=[Le,Ei,Oi];var Mi="https://api.platform.preferredai.jp/v1",Pt=`${Mi}/chat/completions`,Pe="plamo-3.0-prime",vi="plamo-2.2-prime",Fn=[Pe,vi];var S={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Vo={[S.VERY_SHORT]:40,[S.SHORT]:100,[S.MEDIUM]:200,[S.LONG]:300,[S.VERY_LONG]:1e3,[S.DEEP]:5e3},Un=5e3,Kn={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 T(n){return n?Vo[n]??Un:Un}var vr="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",Sr=`You are a skilled summarizing assistant.
1
+ "use strict";var AITuberOnAirChat=(()=>{var jo=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var rr=(n,e)=>{for(var t in e)jo(n,t,{get:e[t],enumerable:!0})},sr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nr(e))!ir.call(n,i)&&i!==t&&jo(n,i,{get:()=>e[i],enumerable:!(o=or(e,i))||o.enumerable});return n};var ar=n=>sr(jo({},"__esModule",{value:!0}),n);var fs={};rr(fs,{CHAT_RESPONSE_LENGTH:()=>O,CLAUDE_VISION_SUPPORTED_MODELS:()=>gt,ChatServiceFactory:()=>tt,ChatServiceHttpClient:()=>_,ClaudeChatService:()=>De,ClaudeChatServiceProvider:()=>Ae,DEEPSEEK_API_BASE_URL:()=>mi,DEEPSEEK_DEPRECATED_MODELS:()=>Pr,DEEPSEEK_SUPPORTED_MODELS:()=>xn,DEFAULT_MAX_TOKENS:()=>Bn,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>xr,DEFAULT_VISION_PROMPT:()=>Rr,DeepSeekChatService:()=>be,DeepSeekChatServiceProvider:()=>Ne,EMOTION_TAG_CLEANUP_REGEX:()=>zn,EMOTION_TAG_REGEX:()=>yi,ENDPOINT_CLAUDE_API:()=>pn,ENDPOINT_DEEPSEEK_CHAT_COMPLETIONS_API:()=>Lt,ENDPOINT_GEMINI_API:()=>Qo,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>Te,ENDPOINT_MISTRAL_CHAT_COMPLETIONS_API:()=>Pt,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>J,ENDPOINT_OPENAI_RESPONSES_API:()=>A,ENDPOINT_OPENROUTER_API:()=>ft,ENDPOINT_PLAMO_CHAT_COMPLETIONS_API:()=>It,ENDPOINT_SAKANA_CHAT_COMPLETIONS_API:()=>xt,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>Mt,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Et,EmotionParser:()=>Ie,GEMINI_DEPRECATED_MODELS:()=>ii,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>$n,GEMINI_RECOMMENDED_MODELS:()=>Ut,GEMINI_VISION_SUPPORTED_MODELS:()=>st,GPT5_PRESETS:()=>Wn,GPT_5_MODELS:()=>Zn,GeminiChatService:()=>we,GeminiChatServiceProvider:()=>ke,GeminiNanoChatService:()=>Ge,GeminiNanoChatServiceProvider:()=>Ve,HttpError:()=>X,KIMI_THINKING_REQUIRED_MODELS:()=>di,KIMI_VISION_SUPPORTED_MODELS:()=>hi,KimiChatService:()=>Fe,KimiChatServiceProvider:()=>Ue,MAX_TOKENS_BY_LENGTH:()=>Ho,MISTRAL_API_BASE_URL:()=>Ei,MISTRAL_REASONING_EFFORT_SUPPORTED_MODELS:()=>Mi,MISTRAL_SUPPORTED_MODELS:()=>Vn,MISTRAL_VISION_SUPPORTED_MODELS:()=>Oi,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>hn,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>_o,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>Eo,MODEL_ANTHROPIC_CLAUDE_HAIKU_LATEST:()=>ho,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>go,MODEL_ANTHROPIC_CLAUDE_OPUS_5:()=>mo,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>fo,MODEL_ANTHROPIC_CLAUDE_SONNET_LATEST:()=>uo,MODEL_CLAUDE_3_5_HAIKU:()=>dr,MODEL_CLAUDE_3_5_SONNET:()=>mr,MODEL_CLAUDE_3_7_SONNET:()=>gr,MODEL_CLAUDE_3_HAIKU:()=>Bt,MODEL_CLAUDE_4_5_HAIKU:()=>b,MODEL_CLAUDE_4_5_OPUS:()=>lt,MODEL_CLAUDE_4_5_SONNET:()=>zt,MODEL_CLAUDE_4_6_OPUS:()=>ct,MODEL_CLAUDE_4_6_SONNET:()=>pt,MODEL_CLAUDE_4_7_OPUS:()=>ut,MODEL_CLAUDE_4_8_OPUS:()=>ht,MODEL_CLAUDE_4_OPUS:()=>$t,MODEL_CLAUDE_4_SONNET:()=>Wt,MODEL_CLAUDE_5_OPUS:()=>mt,MODEL_CLAUDE_5_SONNET:()=>dt,MODEL_DEEPSEEK_CHAT:()=>gi,MODEL_DEEPSEEK_REASONER:()=>fi,MODEL_DEEPSEEK_V4_FLASH:()=>ae,MODEL_DEEPSEEK_V4_PRO:()=>Uo,MODEL_FUGU:()=>Re,MODEL_FUGU_ULTRA:()=>Si,MODEL_FUGU_ULTRA_20260615:()=>Ci,MODEL_GEMINI_2_5_FLASH:()=>ti,MODEL_GEMINI_2_5_FLASH_LITE:()=>oi,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>ni,MODEL_GEMINI_2_5_PRO:()=>ei,MODEL_GEMINI_3_1_FLASH_LITE:()=>j,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>rn,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>nn,MODEL_GEMINI_3_5_FLASH:()=>tn,MODEL_GEMINI_3_5_FLASH_LITE:()=>on,MODEL_GEMINI_3_6_FLASH:()=>en,MODEL_GEMINI_3_FLASH_PREVIEW:()=>an,MODEL_GEMINI_3_PRO_PREVIEW:()=>sn,MODEL_GEMINI_NANO:()=>le,MODEL_GEMMA_4_26B_A4B_IT:()=>Qn,MODEL_GEMMA_4_31B_IT:()=>Yn,MODEL_GLM_4_6:()=>yn,MODEL_GLM_4_6V:()=>Ao,MODEL_GLM_4_6V_FLASH:()=>re,MODEL_GLM_4_6V_FLASHX:()=>bo,MODEL_GLM_4_7:()=>Cn,MODEL_GLM_4_7_FLASH:()=>Ln,MODEL_GLM_4_7_FLASHX:()=>Tn,MODEL_GLM_5:()=>vn,MODEL_GLM_5V_TURBO:()=>Do,MODEL_GLM_5_1:()=>On,MODEL_GLM_5_2:()=>Ee,MODEL_GLM_5_TURBO:()=>Sn,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>To,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>Lo,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>Co,MODEL_GOOGLE_GEMINI_3_5_FLASH_LITE:()=>So,MODEL_GOOGLE_GEMINI_3_6_FLASH:()=>vo,MODEL_GOOGLE_GEMINI_FLASH_LATEST:()=>Oo,MODEL_GOOGLE_GEMINI_PRO_LATEST:()=>Mo,MODEL_GPT_4O:()=>Gt,MODEL_GPT_4O_MINI:()=>oe,MODEL_GPT_4_1:()=>Nt,MODEL_GPT_4_1_MINI:()=>wt,MODEL_GPT_4_1_NANO:()=>kt,MODEL_GPT_5:()=>ue,MODEL_GPT_5_1:()=>he,MODEL_GPT_5_4:()=>Y,MODEL_GPT_5_4_MINI:()=>ee,MODEL_GPT_5_4_NANO:()=>te,MODEL_GPT_5_4_PRO:()=>z,MODEL_GPT_5_5:()=>Q,MODEL_GPT_5_6:()=>H,MODEL_GPT_5_6_LUNA:()=>$,MODEL_GPT_5_6_SOL:()=>B,MODEL_GPT_5_6_TERRA:()=>W,MODEL_GPT_5_MINI:()=>ce,MODEL_GPT_5_NANO:()=>Z,MODEL_GPT_OSS_20B_FREE:()=>G,MODEL_GROK_4_1_FAST_NON_REASONING:()=>V,MODEL_GROK_4_1_FAST_REASONING:()=>ko,MODEL_GROK_4_20_NON_REASONING:()=>wo,MODEL_GROK_4_20_REASONING:()=>No,MODEL_GROK_4_3:()=>Ot,MODEL_GROK_4_5:()=>ve,MODEL_GROK_4_6:()=>Oe,MODEL_KIMI_K2_5:()=>Fo,MODEL_KIMI_K2_6:()=>F,MODEL_KIMI_K2_7_CODE:()=>St,MODEL_KIMI_K2_7_CODE_HIGHSPEED:()=>Ct,MODEL_KIMI_K3:()=>Le,MODEL_KWAIPILOT_KAT_CODER_AIR_V2_5:()=>gn,MODEL_KWAIPILOT_KAT_CODER_PRO_V2_5:()=>fn,MODEL_MINISTRAL_14B_2512:()=>bn,MODEL_MINISTRAL_3B_2512:()=>Dn,MODEL_MINISTRAL_8B_2512:()=>An,MODEL_MISTRAL_LARGE_2512:()=>Gn,MODEL_MISTRAL_LARGE_LATEST:()=>kn,MODEL_MISTRAL_MEDIUM_2508:()=>wn,MODEL_MISTRAL_MEDIUM_3_5:()=>Ko,MODEL_MISTRAL_SMALL_2603:()=>Nn,MODEL_MISTRAL_SMALL_LATEST:()=>U,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Xt,MODEL_MOONSHOTAI_KIMI_K2_7_CODE:()=>qt,MODEL_MOONSHOTAI_KIMI_K3:()=>jt,MODEL_MOONSHOTAI_KIMI_LATEST:()=>Jt,MODEL_O1:()=>Jo,MODEL_O1_MINI:()=>Xo,MODEL_O3_MINI:()=>qo,MODEL_OPENAI_GPT_4O:()=>lo,MODEL_OPENAI_GPT_4_1_MINI:()=>po,MODEL_OPENAI_GPT_4_1_NANO:()=>co,MODEL_OPENAI_GPT_5_1_CHAT:()=>io,MODEL_OPENAI_GPT_5_1_CODEX:()=>ro,MODEL_OPENAI_GPT_5_5:()=>no,MODEL_OPENAI_GPT_5_5_PRO:()=>oo,MODEL_OPENAI_GPT_5_6_LUNA:()=>to,MODEL_OPENAI_GPT_5_6_SOL:()=>Qt,MODEL_OPENAI_GPT_5_6_TERRA:()=>eo,MODEL_OPENAI_GPT_5_MINI:()=>so,MODEL_OPENAI_GPT_5_NANO:()=>ao,MODEL_OPENAI_GPT_LATEST:()=>Zt,MODEL_OPENAI_GPT_MINI_LATEST:()=>Yt,MODEL_OPENROUTER_AUTO:()=>_t,MODEL_OPENROUTER_AUTO_BETA:()=>de,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH:()=>ge,MODEL_OPENROUTER_DEEPSEEK_V4_FLASH_0731:()=>fe,MODEL_OPENROUTER_FUSION:()=>un,MODEL_PLAMO_2_2_PRIME:()=>Li,MODEL_PLAMO_3_0_PRIME:()=>xe,MODEL_XAI_GROK_4_5:()=>Ro,MODEL_XAI_GROK_LATEST:()=>Po,MODEL_ZAI_GLM_4_5_AIR:()=>mn,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>yo,MODEL_ZAI_GLM_4_7_FLASH:()=>dn,MODEL_ZAI_GLM_5_2:()=>me,MistralChatService:()=>Ke,MistralChatServiceProvider:()=>He,OPENROUTER_CREDITS_THRESHOLD:()=>Cr,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Sr,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>vr,OPENROUTER_FREE_MODELS:()=>_n,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>En,OPENROUTER_VISION_SUPPORTED_MODELS:()=>li,OpenAIChatService:()=>y,OpenAIChatServiceProvider:()=>We,OpenAICompatibleChatServiceProvider:()=>Be,OpenRouterChatService:()=>$e,OpenRouterChatServiceProvider:()=>ze,PLAMO_API_BASE_URL:()=>Ti,PLAMO_SUPPORTED_MODELS:()=>Hn,PlamoChatService:()=>je,PlamoChatServiceProvider:()=>qe,SAKANA_API_BASE_URL:()=>vi,SAKANA_SUPPORTED_MODELS:()=>Kn,SakanaChatService:()=>Xe,SakanaChatServiceProvider:()=>Je,StreamTextAccumulator:()=>E,VISION_SUPPORTED_MODELS:()=>ot,XAIChatService:()=>Ze,XAIChatServiceProvider:()=>Ye,XAI_VISION_SUPPORTED_MODELS:()=>ci,ZAIChatService:()=>Qe,ZAIChatServiceProvider:()=>et,ZAI_VISION_SUPPORTED_MODELS:()=>pi,allowsReasoningLow:()=>Ft,allowsReasoningMax:()=>Yo,allowsReasoningMinimal:()=>it,allowsReasoningNone:()=>nt,allowsReasoningXHigh:()=>Vt,buildOpenAICompatibleTools:()=>D,buildToolContinuationMessages:()=>cs,getChatBackendProviderCapabilities:()=>Jn,getClaudeSupportedReasoningEfforts:()=>k,getDeepSeekSupportedReasoningEfforts:()=>yt,getDefaultClaudeReasoningEffort:()=>ai,getDefaultDeepSeekReasoningEffort:()=>Rn,getDefaultGeminiReasoningEffort:()=>hr,getDefaultKimiReasoningEffort:()=>Pe,getDefaultOpenRouterReasoningEffort:()=>Io,getDefaultReasoningEffortForGPT5Model:()=>rt,getDefaultXaiReasoningEffort:()=>Vo,getGeminiSupportedReasoningEfforts:()=>Kt,getKimiSupportedReasoningEfforts:()=>q,getMaxTokensForResponseLength:()=>L,getOpenRouterSupportedReasoningEfforts:()=>xo,getXaiSupportedReasoningEfforts:()=>Ce,installGASFetch:()=>er,isClaudeReasoningEffortModel:()=>si,isDeepSeekReasoningEffortModel:()=>_i,isGPT5Model:()=>ne,isGeminiReasoningEffortModel:()=>ln,isKimiReasoningEffortModel:()=>se,isKimiThinkingRequiredModel:()=>Tt,isKimiVisionModel:()=>ye,isMistralReasoningEffort:()=>Fn,isMistralReasoningEffortModel:()=>Rt,isMistralVisionModel:()=>Un,isOpenRouterFreeModel:()=>ie,isOpenRouterVisionModel:()=>_e,isResponsesOnlyGPT5Model:()=>Zo,isXaiReasoningEffortModel:()=>Go,isXaiReasoningEffortNoneModel:()=>ui,isXaiVisionModel:()=>Se,isZaiToolStreamModel:()=>Pn,isZaiVisionModel:()=>Me,normalizeClaudeReasoningEffort:()=>_r,normalizeDeepSeekReasoningEffort:()=>In,normalizeGeminiReasoningEffort:()=>at,normalizeOpenRouterReasoningEffort:()=>Mn,normalizeXaiReasoningEffort:()=>vt,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>K,parseOpenAICompatibleToolStream:()=>x,processChatWithOptionalTools:()=>M,refreshOpenRouterFreeModels:()=>Br,resolveVisionModel:()=>T,runOnceText:()=>br,safeJsonParse:()=>Ri,safeParseToolCallInput:()=>pe,screenplayToText:()=>Ar,textToScreenplay:()=>Pi,textsToScreenplay:()=>Dr});var J="https://api.openai.com/v1/chat/completions",A="https://api.openai.com/v1/responses",Z="gpt-5-nano",ce="gpt-5-mini",ue="gpt-5",he="gpt-5.1",Y="gpt-5.4",Q="gpt-5.5",H="gpt-5.6",B="gpt-5.6-sol",W="gpt-5.6-terra",$="gpt-5.6-luna",ee="gpt-5.4-mini",te="gpt-5.4-nano",z="gpt-5.4-pro",Nt="gpt-4.1",wt="gpt-4.1-mini",kt="gpt-4.1-nano",oe="gpt-4o-mini",Gt="gpt-4o",qo="o3-mini",Xo="o1-mini",Jo="o1",ot=[Z,ce,ue,he,Y,Q,H,B,W,$,ee,te,z,Nt,wt,kt,oe,Gt,"o1"],Zn=[Z,ce,ue,he,Y,Q,H,B,W,$,ee,te,z];function ne(n){return Zn.includes(n)}function Zo(n){return n===z}function Vt(n){return n===H||n===B||n===W||n===$||n===Q||n===Y||n===ee||n===te||n===z}function Yo(n){return n===H||n===B||n===W||n===$}function nt(n){return n===H||n===B||n===W||n===$||n===he||n===Y||n===Q||n===ee||n===te}function it(n){return n===Z||n===ce||n===ue}function Ft(n){return n!==z}function rt(n){return nt(n)?"none":it(n)?"minimal":"medium"}var Qo="https://generativelanguage.googleapis.com",Yn="gemma-4-31b-it",Qn="gemma-4-26b-a4b-it",en="gemini-3.6-flash",tn="gemini-3.5-flash",on="gemini-3.5-flash-lite",nn="gemini-3.1-pro-preview",j="gemini-3.1-flash-lite",rn="gemini-3.1-flash-lite-preview",sn="gemini-3-pro-preview",an="gemini-3-flash-preview",ei="gemini-2.5-pro",ti="gemini-2.5-flash",oi="gemini-2.5-flash-lite",ni="gemini-2.5-flash-lite-preview-06-17",Ut=[en,tn,on,j,nn,an,ei,ti,oi,Yn,Qn],ii=[rn,sn,ni],st=[...Ut,...ii],lr=["minimal","low","medium","high"],pr=["low","medium","high"],cr=[en,tn,on,j,rn,an],ur=[nn,sn];function Kt(n){return cr.includes(n)?lr:ur.includes(n)?pr:[]}function ln(n){return Kt(n).length>0}function hr(n){return Kt(n)[0]}function at(n,e){let t=Kt(n);if(t.length!==0)return e&&t.includes(e)?e:t[0]}var pn="https://api.anthropic.com/v1/messages",Bt="claude-3-haiku-20240307",dr="claude-3-5-haiku-20241022",mr="claude-3-5-sonnet-20241022",gr="claude-3-7-sonnet-20250219",Wt="claude-sonnet-4-20250514",$t="claude-opus-4-20250514",zt="claude-sonnet-4-5-20250929",b="claude-haiku-4-5-20251001",lt="claude-opus-4-5-20251101",pt="claude-sonnet-4-6",ct="claude-opus-4-6",ut="claude-opus-4-7",ht="claude-opus-4-8",dt="claude-sonnet-5",mt="claude-opus-5",cn=["low","medium","high"],ri=[...cn,"max"],Ht=[...cn,"xhigh","max"],fr={[lt]:cn,[pt]:ri,[ct]:ri,[ut]:Ht,[ht]:Ht,[dt]:Ht,[mt]:Ht},gt=[Bt,Wt,$t,zt,b,lt,pt,ct,ut,ht,dt,mt];function k(n){return fr[n]??[]}function si(n){return k(n).length>0}function ai(n){return si(n)?"high":void 0}function _r(n,e){let t=k(n);if(t.length!==0)return e?t.includes(e)?e:"high":ai(n)}var ft="https://openrouter.ai/api/v1/chat/completions",_t="openrouter/auto",de="openrouter/auto-beta",un="openrouter/fusion",G="openai/gpt-oss-20b:free",jt="moonshotai/kimi-k3",qt="moonshotai/kimi-k2.7-code",Xt="moonshotai/kimi-k2.5",Jt="~moonshotai/kimi-latest",Zt="~openai/gpt-latest",Yt="~openai/gpt-mini-latest",Qt="openai/gpt-5.6-sol",eo="openai/gpt-5.6-terra",to="openai/gpt-5.6-luna",oo="openai/gpt-5.5-pro",no="openai/gpt-5.5",io="openai/gpt-5.1-chat",ro="openai/gpt-5.1-codex",so="openai/gpt-5-mini",ao="openai/gpt-5-nano",lo="openai/gpt-4o",po="openai/gpt-4.1-mini",co="openai/gpt-4.1-nano",uo="~anthropic/claude-sonnet-latest",ho="~anthropic/claude-haiku-latest",mo="anthropic/claude-opus-5",go="anthropic/claude-opus-4",fo="anthropic/claude-sonnet-4",_o="anthropic/claude-3.7-sonnet",hn="anthropic/claude-3.5-sonnet",Eo="anthropic/claude-haiku-4.5",Mo="~google/gemini-pro-latest",Oo="~google/gemini-flash-latest",vo="google/gemini-3.6-flash",So="google/gemini-3.5-flash-lite",Co="google/gemini-2.5-pro",To="google/gemini-2.5-flash",Lo="google/gemini-2.5-flash-lite-preview-09-2025",me="z-ai/glm-5.2",dn="z-ai/glm-4.7-flash",mn="z-ai/glm-4.5-air",yo="z-ai/glm-4.5-air:free",gn="kwaipilot/kat-coder-air-v2.5",fn="kwaipilot/kat-coder-pro-v2.5",Po="~x-ai/grok-latest",Ro="x-ai/grok-4.5",ge="deepseek/deepseek-v4-flash",fe="deepseek/deepseek-v4-flash-0731",Er=["none","minimal","low","medium","high"],Mr=["none","high","xhigh"],Or=["none","low","high","max"],_n=[G,yo],li=[de,jt,Jt,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,mo,go,fo,_o,Eo,Mo,Oo,vo,So,Co,To,Lo,qt,Xt,Po,Ro],En=20,vr=50,Sr=1e3,Cr=10;function ie(n){return n.trim().endsWith(":free")}function _e(n){return li.some(e=>n.includes(e))}function xo(n){let e=n.trim();return e===ge?Mr:e===fe?Or:Er}function Io(n){let e=n.trim();return e===me||e===ge||e===fe?"none":void 0}function Mn(n,e){let t=n.trim(),o=e??Io(n);if(!o)return;if(xo(n).includes(o))return o;if(t===ge)return o==="max"?"xhigh":"none";if(t===fe){if(o==="minimal"||o==="medium")return"low";if(o==="xhigh")return"high"}return o}var Et="https://api.z.ai/api/paas/v4/chat/completions",Ee="glm-5.2",On="glm-5.1",vn="glm-5",Sn="glm-5-turbo",Do="glm-5v-turbo",Cn="glm-4.7",Tn="glm-4.7-FlashX",Ln="glm-4.7-Flash",yn="glm-4.6",Ao="glm-4.6V",bo="glm-4.6V-FlashX",re="glm-4.6V-Flash",pi=[Do,Ao,bo,re];function Me(n){return pi.includes(n)}function Pn(n){return n.toLowerCase().startsWith("glm-4.6")}var Mt="https://api.x.ai/v1/chat/completions",Oe="grok-4.6",ve="grok-4.5",Ot="grok-4.3",No="grok-4.20-0309-reasoning",wo="grok-4.20-0309-non-reasoning",ko="grok-4-1-fast-reasoning",V="grok-4-1-fast-non-reasoning",ci=[Oe,ve,Ot,No,wo,ko,V];function Se(n){return ci.includes(n)}function Go(n){return Ce(n).length>0}function Ce(n){return n===Oe?["low","medium","high","xhigh"]:n===ve?["low","medium","high"]:n===Ot?["none","low","medium","high"]:[]}function ui(n){return Ce(n).includes("none")}function Vo(n){return n===Oe||n===ve?"low":ui(n)?"none":void 0}function vt(n,e){return Go(n)?e===void 0?Vo(n):Ce(n).includes(e)?e:e==="none"?"low":"high":void 0}var Te="https://api.moonshot.ai/v1/chat/completions",Le="kimi-k3",St="kimi-k2.7-code",Ct="kimi-k2.7-code-highspeed",F="kimi-k2.6",Fo="kimi-k2.5",Tr={[Le]:["low","high","max"]},hi=[Le,St,Ct,F,Fo],di=[St,Ct];function ye(n){return hi.includes(n)}function Tt(n){return di.includes(n)}function q(n){return Tr[n]??[]}function Pe(n){return n===Le?"max":void 0}function se(n){return q(n).length>0}var mi="https://api.deepseek.com",Lt=`${mi}/chat/completions`,ae="deepseek-v4-flash",Uo="deepseek-v4-pro",Lr=["none","low","high","max"],yr=["none","high","max"],gi="deepseek-chat",fi="deepseek-reasoner",xn=[ae,Uo],Pr=[gi,fi];function yt(n){return n===ae?Lr:n===Uo?yr:[]}function _i(n){return yt(n).length>0}function Rn(n){return _i(n)?"none":void 0}function In(n,e){let t=yt(n);if(t.length===0)return;let o=e??Rn(n);return o&&t.includes(o)?o:n===Uo&&o==="low"?"high":Rn(n)}var Ei="https://api.mistral.ai/v1",Pt=`${Ei}/chat/completions`,Dn="ministral-3b-2512",An="ministral-8b-2512",bn="ministral-14b-2512",U="mistral-small-latest",Nn="mistral-small-2603",Ko="mistral-medium-3-5",wn="mistral-medium-2508",kn="mistral-large-latest",Gn="mistral-large-2512",Vn=[U,Dn,An,bn,Ko,kn,Gn,Nn,wn],Mi=[U,Ko],Oi=[U,Dn,An,bn,Nn,Ko,wn,kn,Gn];function Rt(n){return Mi.includes(n)}function Fn(n){return n==="none"||n==="high"}function Un(n){return Oi.includes(n)}var vi="https://api.sakana.ai/v1",xt=`${vi}/chat/completions`,Re="fugu",Si="fugu-ultra",Ci="fugu-ultra-20260615",Kn=[Re,Si,Ci];var Ti="https://api.platform.preferredai.jp/v1",It=`${Ti}/chat/completions`,xe="plamo-3.0-prime",Li="plamo-2.2-prime",Hn=[xe,Li];var O={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Ho={[O.VERY_SHORT]:40,[O.SHORT]:100,[O.MEDIUM]:200,[O.LONG]:300,[O.VERY_LONG]:1e3,[O.DEEP]:5e3},Bn=5e3,Wn={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 L(n){return n?Ho[n]??Bn:Bn}var Rr="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",xr=`You are a skilled summarizing assistant.
2
2
  Analyze the following conversation and produce a summary in the **same language** as the majority of the conversation:
3
3
  - Summaries should highlight key points
4
4
  - Stay concise (around {maxLength} characters if possible)
@@ -7,13 +7,13 @@ Analyze the following conversation and produce a summary in the **same language*
7
7
  If the conversation is in Japanese, summarize in Japanese.
8
8
  If it's in English, summarize in English.
9
9
  If it's in another language, summarize in that language.
10
- `;var se="gemini-nano",Hn=20;var q=class extends Error{constructor(t,o,i){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=i;this.name="HttpError"}},Rt=class Rt{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},i={}){let{timeout:r=3e4,retries:s=0,retryDelay:l=1e3}=i,c={...{"Content-Type":"application/json"},...o},d=null;for(let u=0;u<=s;u++)try{let m=typeof AbortController<"u",g=m?new AbortController:void 0,a=m?setTimeout(()=>g.abort(),r):void 0,h=await Rt.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...g?{signal:g.signal}:{}});if(a&&clearTimeout(a),!h.ok){let v=await h.text();throw new q(h.status,h.statusText,v)}return h}catch(m){if(d=m,m instanceof q&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);u<s&&await new Promise(g=>setTimeout(g,l*(u+1)))}throw d||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new q(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=o,l=null;for(let p=0;p<=r;p++)try{let c=typeof AbortController<"u",d=c?new AbortController:void 0,u=c?setTimeout(()=>d.abort(),i):void 0,m=await Rt.fetchImpl(e,{method:"GET",headers:t,...d?{signal:d.signal}:{}});if(u&&clearTimeout(u),!m.ok){let g=await m.text();throw new q(m.status,m.statusText,g)}return m}catch(c){if(l=c,c instanceof q&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);p<r&&await new Promise(d=>setTimeout(d,s*(p+1)))}throw l||new Error("Request failed")}};Rt.fetchImpl=(e,t)=>fetch(e,t);var E=Rt;var O=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 Cr=["happy","sad","angry","surprised","neutral"],Si=/\[([a-z]+)\]/i,Bn=/\[[a-z]+\]\s*/gi,Re=class{static extractEmotion(e){let t=e.match(Si);if(t){let o=t[1].toLowerCase(),i=e.replace(Bn,"").trim();return{emotion:o,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return Cr.includes(e)}static cleanEmotionTags(e){return e.replace(Bn,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Ci(n){let{emotion:e,cleanText:t}=Re.extractEmotion(n);return e?{emotion:e,text:t}:{text:t}}function Tr(n){return n.map(e=>Ci(e))}function Lr(n){return n.emotion?Re.addEmotionTag(n.emotion,n.text):n.text}async function Pr(n,e){let{blocks:t}=await n.chatOnce(e,!1,()=>{});return O.getFullText(t)}var Ti=(n,e,t)=>{try{return JSON.parse(n)}catch(o){return t?.(n,o),e}},ae=(n,e)=>n?Ti(n,{},e):{};var Li=(n,e)=>{try{return JSON.parse(n)}catch(t){if(e){e(n,t);return}throw t}},Fo=n=>typeof n=="string"?n:Array.isArray(n)?n.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",Wn=n=>{let e=n.choices?.[0],t=n.error??e?.error;if(!t&&e?.finish_reason!=="error")return;let o=typeof t=="string"?t:typeof t?.message=="string"?t.message:"The provider ended the response with an error.";throw new Error(`Provider response error: ${o}`)},Pi=async(n,e)=>{let t=n.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,i="",r=!1;for(;!r;){let{done:s,value:l}=await t.read();if(s)break;i+=o.decode(l,{stream:!0});let p=i.split(`
11
- `);i=p.pop()||"";for(let c of p){let d=c.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let u=d.slice(5).trim();if(u==="[DONE]"){r=!0;break}e(u)}}};async function F(n,e,t={}){let o="";return await Pi(n,i=>{let r=Li(i,t.onJsonError);if(!r)return;t.throwOnApiError&&Wn(r);let s=Fo(r.choices?.[0]?.delta?.content);s&&(e(s),o+=s)}),o}async function x(n,e,t={}){let o=[],i=new Map,r="",s="",l,p,c=t.appendTextBlock??O.append;await Pi(n,a=>{let h=Li(a,t.onJsonError);if(!h)return;t.throwOnApiError&&Wn(h);let v=h.choices?.[0];typeof v?.finish_reason=="string"&&(l=v.finish_reason),h.usage&&(p=h.usage);let R=v?.delta,P=Fo(R?.content);P&&(e(P),c(o,P),r+=P);let f=Fo(R?.reasoning_content);f&&(s+=f),R?.tool_calls&&R.tool_calls.forEach(_=>{let y=i.get(_.index)??{id:_.id,type:_.type,name:_.function?.name,args:""};_.id&&(y.id=_.id),_.type&&(y.type=_.type),_.function?.name&&(y.name=_.function.name),y.args+=_.function?.arguments||"",i.set(_.index,y)})});let d=Array.from(i.entries()).sort((a,h)=>a[0]-h[0]).map(([a,h])=>({type:"tool_use",id:h.id,name:h.name,input:ae(h.args,t.onJsonError)})),u=[...o,...d],m=Array.from(i.entries()).sort((a,h)=>a[0]-h[0]).map(([a,h])=>({id:h.id,type:"function",function:{name:h.name,arguments:h.args}})),g={role:"assistant",content:r,...s?{reasoning_content:s}:{},...m.length>0?{tool_calls:m}:{}};return{blocks:u,stop_reason:d.length?"tool_use":"end",truncated:l==="length",finish_reason:l,usage:p,...t.preserveAssistantMessage?{assistant_message:g}:{}}}function I(n,e={}){e.throwOnApiError&&Wn(n);let t=n?.choices?.[0],o=[],i=Fo(t?.message?.content);t?.message?.tool_calls?.length?t.message.tool_calls.forEach(s=>o.push({type:"tool_use",id:s.id,name:s.function?.name,input:ae(s.function?.arguments,e.onJsonError)})):i&&o.push({type:"text",text:i});let r=t?.message?{...t.message,role:"assistant",content:i}:void 0;return{blocks:o,stop_reason:t?.finish_reason==="tool_calls"||o.some(s=>s.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:n?.usage,...e.preserveAssistantMessage?{assistant_message:r}:{}}}var D=(n,e="chat-completions")=>n.length===0?[]:e==="responses"?n.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):n.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function M(n){if(!n.hasTools){let t=await n.runWithoutTools();if(typeof t=="string"){await n.onCompleteResponse(t);return}let o=O.getFullText(t.blocks);await n.onCompleteResponse(o,t);return}let e=await n.runWithTools();if(n.onToolBlocks&&n.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=O.getFullText(e.blocks);await n.onCompleteResponse(t,e);return}throw new Error(n.toolErrorMessage)}var C=n=>{let e=n.model??n.defaultModel,t=n.visionModel??(n.supportsVisionForModel(e)?e:n.defaultVisionModel);if(n.validate==="explicit"&&n.visionModel&&!n.supportsVisionForModel(n.visionModel))throw new Error(`Model ${n.visionModel} does not support vision capabilities.`);if(n.validate==="resolved"&&!n.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var Rr="https://openrouter.ai/api/v1/models",yr=2,xr=12e3,Ir=1,Dr=10;function $n(n){return n instanceof Error?n.message:String(n)}function Uo(n,e){return typeof n!="number"||!Number.isFinite(n)?e:Math.max(1,Math.floor(n))}function Ar(n){let e=new Set,t=[];for(let o of n){let i=o.trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}async function Ri(n,e,t){if(!(typeof AbortController<"u"))return fetch(n,e);let i=new AbortController,r=setTimeout(()=>i.abort(),t);try{return await fetch(n,{...e,signal:i.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error(`Timeout after ${t}ms`):s}finally{clearTimeout(r)}}async function yi(n){let e=`HTTP ${n.status} ${n.statusText}`.trim(),t="";try{t=await n.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function br(n){if(!n||typeof n!="object")throw new Error("Invalid models response shape");let e=n,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(i=>i.id).filter(i=>typeof i=="string");return Ar(o)}async function Nr({modelId:n,apiKey:e,endpoint:t,timeoutMs:o,appName:i,appUrl:r}){let s={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};i&&(s["X-Title"]=i),r&&(s["HTTP-Referer"]=r);try{let l=await Ri(t,{method:"POST",headers:s,body:JSON.stringify({model:n,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!l.ok)return{id:n,ok:!1,reason:await yi(l)};try{await l.json()}catch(p){return{id:n,ok:!1,reason:`JSON parse failed: ${$n(p)}`}}return{id:n,ok:!0}}catch(l){return{id:n,ok:!1,reason:$n(l)}}}async function wr(n,e,t){if(n.length===0)return[];let o=new Array(n.length),i=0,r=Math.min(e,n.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<n.length;){let s=i;i+=1,o[s]=await t(n[s])}})),o}async function kr(n){let e=n.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=n.modelsEndpoint||Rr,o=n.endpoint||dt,i=Uo(n.timeoutMs,xr),r=Uo(n.concurrency,yr),s=Uo(n.maxCandidates,Ir),l=Uo(n.maxWorking,Dr),p=await Ri(t,{method:"GET"},i);if(!p.ok)throw new Error(await yi(p));let c;try{c=await p.json()}catch(a){throw new Error(`JSON parse failed: ${$n(a)}`)}let d=br(c).filter(a=>oe(a)).slice(0,s),u=await wr(d,r,a=>Nr({modelId:a,apiKey:e,endpoint:o,timeoutMs:i,appName:n.appName,appUrl:n.appUrl})),m=u.filter(a=>a.ok).map(a=>a.id).slice(0,l),g=u.filter(a=>!a.ok).map(a=>({id:a.id,reason:a.reason||"Unknown error"}));return{working:m,failed:g,fetchedAt:Date.now()}}function xi(n){return n.map(e=>({role:yt(e.role),content:e.provider_content??e.content}))}function Ii(n){return n.map(e=>{if(e.provider_content)return{role:yt(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:yt(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:Gr(o.image_url.url)}}}return o}).filter(o=>o);return{role:yt(e.role),content:t}}return{role:yt(e.role),content:[]}})}function yt(n){switch(n){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Gr(n){switch(n.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 ye=class{constructor(e,t=b,o=b,i=[],r=[],s,l){this.provider="claude";if(this.apiKey=e,this.model=t||b,this.visionModel=o||b,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=l,!ht.includes(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`)}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e)}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e)}hasMCPServers(){return this.mcpServers.length>0}async processChat(e,t,o){await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let 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 M({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 r=e.find(u=>u.role==="system")?.content??"",s=e.filter(u=>u.role!=="system"),l=s.some(u=>Array.isArray(u.content)&&u.content.some(m=>m.type==="image_url"||m.type==="image")),p={model:t,system:r,messages:l?Ii(s):xi(s),stream:o,max_tokens:i!==void 0?i:T(this.responseLength)};this.reasoningEffort!==void 0&&N(t).includes(this.reasoningEffort)&&(p.output_config={effort:this.reasoningEffort}),this.tools.length&&(p.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),p.tool_choice={type:"auto"}),this.mcpServers.length>0&&(p.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 E.post(rn,p,c)}async parseStream(e,t){let o=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,l=new Map,p="";for(;;){let{done:c,value:d}=await o.read();if(c)break;p+=i.decode(d,{stream:!0});let u;for(;(u=p.indexOf(`
12
- `))!==-1;){let m=p.slice(0,u).trim();if(p=p.slice(u+1),!m.startsWith("data:"))continue;let g=m.slice(5).trim();if(g==="[DONE]")break;let a=JSON.parse(g);if(a.type==="content_block_start"&&a.content_block&&typeof a.index=="number"&&s.set(a.index,{...a.content_block}),a.type==="content_block_delta"&&a.delta?.type==="text_delta"){t(a.delta.text),r.push({type:"text",text:a.delta.text});let h=s.get(a.index);h?.type==="text"&&(h.text=`${h.text??""}${a.delta.text}`)}if(a.type==="content_block_delta"&&a.delta?.type==="thinking_delta"){let h=s.get(a.index);h?.type==="thinking"&&(h.thinking=`${h.thinking??""}${a.delta.thinking??""}`)}if(a.type==="content_block_delta"&&a.delta?.type==="signature_delta"){let h=s.get(a.index);h?.type==="thinking"&&(h.signature=`${h.signature??""}${a.delta.signature??""}`)}if(a.type==="content_block_start"&&a.content_block?.type==="tool_use"?l.set(a.index,{id:a.content_block.id,name:a.content_block.name,args:""}):a.type==="content_block_start"&&a.content_block?.type==="mcp_tool_use"?l.set(a.index,{id:a.content_block.id,name:a.content_block.name,args:"",server_name:a.content_block.server_name}):a.type==="content_block_start"&&a.content_block?.type==="tool_result"?r.push({type:"tool_result",tool_use_id:a.content_block.tool_use_id,content:a.content_block.content??""}):a.type==="content_block_start"&&a.content_block?.type==="mcp_tool_result"&&r.push({type:"mcp_tool_result",tool_use_id:a.content_block.tool_use_id,is_error:a.content_block.is_error??!1,content:a.content_block.content??[]}),a.type==="content_block_delta"&&a.delta?.type==="input_json_delta"){let h=l.get(a.index);h&&(h.args+=a.delta.partial_json||"")}if(a.type==="content_block_stop"&&l.has(a.index)){let{id:h,name:v,args:R,server_name:P}=l.get(a.index),f=JSON.parse(R||"{}"),_=s.get(a.index);_&&(_.input=f),P?r.push({type:"mcp_tool_use",id:h,name:v,server_name:P,input:f}):r.push({type:"tool_use",id:h,name:v,input:f}),l.delete(a.index)}}}return{blocks:r,providerContent:[...s.entries()].sort(([c],[d])=>c-d).map(([,c])=>c),stop_reason:r.some(c=>c.type==="tool_use"||c.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,providerContent:(e.content??[]).map(o=>({...o})),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 r=await this.callClaude(e,this.model,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callClaude(e,this.visionModel,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){let t=e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result");return{blocks:t,stop_reason:e.stop_reason,assistant_message:{role:"assistant",content:t.filter(o=>o.type==="text").map(o=>o.text).join(""),provider_content:e.providerContent}}}};var xe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=N(t);if(e.reasoning_effort!==void 0&&!o.includes(e.reasoning_effort)){let r=o.length>0?`Supported values: ${o.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Claude reasoning_effort: ${e.reasoning_effort}. ${r}`)}let i=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"resolved"});return new ye(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[Ut,Kt,Ht,b,rt,st,at,lt,pt,ct,ut,Ft]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ht.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function Ko(n,e,t={}){let o=n.body.getReader(),i=new TextDecoder,r=[],s=new Map,l,p,c,d="";for(;;){let{done:m,value:g}=await o.read();if(m)break;d+=i.decode(g,{stream:!0});let a="",h="",v=d.split(`
13
- `);d=v.pop()||"";for(let R=0;R<v.length;R++){let P=v[R].trim();if(P.startsWith("event:"))a=P.slice(6).trim();else if(P.startsWith("data:"))h=P.slice(5).trim();else if(P===""&&a&&h){try{let f=JSON.parse(h);Vr(a,f,e,r,s,t,_=>{_.responseStatus!==void 0&&(l=_.responseStatus),_.incompleteDetails!==void 0&&(p=_.incompleteDetails),_.usage!==void 0&&(c=_.usage)})}catch(f){t.onJsonError?.(h,f),console.warn("Failed to parse SSE data:",h)}a="",h=""}}}let u=Array.from(s.values()).map(m=>({type:"tool_use",id:m.id,name:m.name,input:m.input||{}}));return{blocks:[...r,...u],stop_reason:u.length?"tool_use":"end",truncated:l==="incomplete",response_status:l,incomplete_details:p,usage:c}}function Vr(n,e,t,o,i,r,s){switch(n){case"response.output_item.added":e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(l=>{l.type==="output_text"&&l.text&&(t(l.text),O.append(o,l.text))}):e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.id,name:e.item.name,input:ae(e.item.arguments,r.onJsonError)});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),O.append(o,e.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let l=typeof e.delta=="string"?e.delta:e.delta?.text??"";l&&(t(l),O.append(o,l));break}case"response.output_text.done":case"response.content_part.done":case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;case"response.completed":s(Di(e,"completed"));break;case"response.incomplete":s(Di(e,"incomplete"));break;default:break}}function Di(n,e){let t=n?.response??n;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function Ai(n,e={}){let t=[];return n.output&&Array.isArray(n.output)&&n.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(i=>{i.type==="output_text"&&i.text&&t.push({type:"text",text:i.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:ae(o.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:n?.status==="incomplete",response_status:n?.status,incomplete_details:n?.incomplete_details??null,usage:n?.usage}}function bi({tools:n,mcpServers:e,isResponsesAPI:t}){let o=[];return n.length>0&&o.push(...D(n,t?"responses":"chat-completions")),e.length>0&&t&&o.push(...Fr(e)),o}function Fr(n){return n.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 Ur={[S.VERY_SHORT]:800,[S.SHORT]:1200,[S.MEDIUM]:2e3,[S.LONG]:3e3,[S.VERY_LONG]:8e3,[S.DEEP]:25e3},Kr={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},Hr=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function Br(n){return n.type!=="json_schema"?n:{type:n.type,...n.json_schema}}function Ni({provider:n,endpoint:e,messages:t,model:o,stream:i,tools:r,mcpServers:s,responseLength:l,verbosity:p,reasoning_effort:c,enableReasoningSummary:d,responseFormat:u,maxTokens:m}){let g=e===A;$r(e,s);let a={model:o,stream:i},h=Wr({provider:n,model:o,responseLength:l,reasoning_effort:c,maxTokens:m});g?h!==void 0&&(a.max_output_tokens=h):h!==void 0&&(wi(n)?a.max_tokens=h:a.max_completion_tokens=h),g?a.input=zr(t):a.messages=n==="mistral"?qr(t):t,te(o)&&(g?(c&&(a.reasoning={...a.reasoning,effort:c},d&&(a.reasoning.summary="auto")),p&&(a.text={...a.text,format:{type:"text"},verbosity:p})):(c&&(a.reasoning_effort=c),p&&(a.verbosity=p))),u&&(g?a.text={...a.text,format:Br(u)}:a.response_format=u),n==="mistral"&&Tt(o)&&c&&kn(c)&&(a.reasoning_effort=c),n==="plamo"&&c&&(a.reasoning_effort=c),n==="deepseek"&&c&&(a.thinking={type:c==="none"?"disabled":"enabled"},c!=="none"&&(a.reasoning_effort=c));let v=bi({tools:r,mcpServers:s,isResponsesAPI:g});return v.length>0&&(a.tools=v,g||(a.tool_choice="auto")),a}function Wr({provider:n,model:e,responseLength:t,reasoning_effort:o,maxTokens:i}){if(i!==void 0)return i;let r=wi(n)?t!==void 0?T(t):void 0:T(t);if(n!=="openai"||!te(e)||t===void 0)return r;let s=o??ot(e);return Math.max(r??0,Ur[t],Kr[s])}function $r(n,e){if(e.length>0&&n===j)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${n}. Please use OpenAI Responses API endpoint: ${A}. MCP tools are only available in the Responses API endpoint.`)}function zr(n){return n.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 qr(n){return n.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 wi(n){return Hr.has(n)}var L=class{constructor(e,t=ee,o=ee,i,r=j,s=[],l,p,c,d=!1,u="openai",m=!0,g){if(this.provider=u,this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.mcpServers=s,this.responseLength=l,this.verbosity=p,this.reasoning_effort=c,this.enableReasoningSummary=d,this.responseFormat=g,m&&!Qe.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.model,!0),r=this.endpoint===A;try{if(r){let s=await Ko(i,t);return O.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 M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===A;try{if(r){let s=await Ko(i,t);return O.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 r=await this.callOpenAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callOpenAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return this.endpoint===A?t?Ko(e,o):Ai(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,i){let r=Ni({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,responseFormat:this.responseFormat,maxTokens:i}),s={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(s.Authorization=`Bearer ${this.apiKey}`),await E.post(this.endpoint,r,s)}async handleStream(e,t){return F(e,t)}async parseStream(e,t){return x(e,t,{appendTextBlock:O.addTextBlock})}parseOneShot(e){return I(e)}};var Ie=class extends L{constructor(e,t=re,o=t,i,r=vt,s,l){let p=Rn(t,l);if(super(e,t,o,i,r,[],s,void 0,p,!1,"deepseek",!1),i?.length&&p!==void 0&&p!=="none")throw new Error("DeepSeek thinking with tools is not supported yet. Use reasoning_effort: 'none' for tool calling.")}};var De=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new Ie(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...Pn]}getDefaultModel(){return re}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 vt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var ki=(n,e)=>({name:`mcp_${n.name}_search`,description:e==="schema-fetch-failed"?`Search using ${n.name} MCP server (schema fetch failed)`:`Search using ${n.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),Ho=class{static async fetchToolSchemas(e){return(await this.fetchToolSchemasWithStatus(e)).schemas}static async fetchToolSchemasWithStatus(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let i=await(await E.post(`${e.url}/tools`,{},t)).json();return Array.isArray(i.tools)?{schemas:i.tools.map(r=>({name:`mcp_${e.name}_${r.name}`,description:r.description||`Tool from ${e.name} MCP server`,parameters:r.inputSchema||{type:"object",properties:{},required:[]}})),failures:[]}:{schemas:[ki(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[ki(e,"schema-fetch-failed")],failures:[{server:e,error:t}]}}}static async fetchAllToolSchemas(e){return(await this.fetchAllToolSchemasWithStatus(e)).schemas}static async fetchAllToolSchemasWithStatus(e){let t=[],o=[];for(let i of e)try{let r=await this.fetchToolSchemasWithStatus(i);t.push(...r.schemas),o.push(...r.failures)}catch(r){console.error(`Failed to fetch schemas from ${i.name}:`,r),o.push({server:i,error:r})}return{schemas:t,failures:o}}};function Gi(n){switch(n){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function Vi(n,e={}){let t=[],o=null,i=[],r=()=>{o&&i.length&&(t.push({role:o,parts:[...i]}),i=[]),o=null};for(let s of n){let l=Gi(s.role);if(s.tool_calls){r();let p=s.tool_calls.map(c=>Ui(c,e));p.length>0&&t.push({role:"model",parts:p});continue}if(s.role==="tool"){r(),Hi(t,Ki(s,e));continue}l!==o&&r(),o=l,i.push({text:s.content})}return r(),t}async function Fi(n,e={}){let t=e.imageFetcher??E.get,o=e.blobToBase64??Jr,i=[],r=null,s=[],l=()=>{r&&s.length>0&&(i.push({role:r,parts:[...s]}),s=[]),r=null};for(let p of n){let c=Gi(p.role);if(p.tool_calls){l();let d=p.tool_calls.map(u=>Ui(u,e));d.length>0&&i.push({role:"model",parts:d});continue}if(p.role==="tool"){l(),Hi(i,Ki(p,e));continue}if(c!==r&&s.length>0&&l(),r=c,typeof p.content=="string")s.push({text:p.content});else if(Array.isArray(p.content)){for(let d of p.content)if(d.type==="text")s.push({text:d.text});else if(d.type==="image_url")try{let m=await(await t(d.image_url.url)).blob(),g=await o(m);s.push({inlineData:{mimeType:m.type||"image/jpeg",data:g.split(",")[1]}})}catch(u){throw console.error("Error processing image:",u),new Error(`Failed to process image: ${u.message}`)}}}return l(),i}function Ui(n,e){e.callIdMap?.set(n.id,n.function.name);let t=e.functionCallContextMap?.get(n.id),o={functionCall:{...t?.providerCallId?{id:t.providerCallId}:{},name:n.function.name,args:JSON.parse(n.function.arguments||"{}")}};return t?.thoughtSignature&&(o.thoughtSignature=t.thoughtSignature),o}function Ki(n,e){let t=n.tool_call_id,o=e.functionCallContextMap?.get(t);return{functionResponse:{...o?.providerCallId?{id:o.providerCallId}:{},name:n.name??o?.name??e.callIdMap?.get(t)??"result",response:Xr(jr(n.content))}}}function Hi(n,e){let t=n[n.length-1];if(t?.role==="user"&&t.parts.every(i=>i.functionResponse)){t.parts.push(e);return}n.push({role:"user",parts:[e]})}function jr(n){try{return JSON.parse(n)}catch{return n}}function Xr(n){return n===null?{content:null}:typeof n=="object"?n:{content:n}}function Jr(n){return new Promise((e,t)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=t,o.readAsDataURL(n)})}function Zr(n,e){return[...n,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Bi(n,e){let t=Zr(n,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function Wi(n){return n.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 Ae=class{constructor(e,t=$,o=$,i=[],r=[],s,l){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;this.functionCallContextMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=s,this.reasoningEffort=l,!nt.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=i,this.mcpServers=r}isGemma4Model(e){return/^gemma-4-/.test(e)}resolveThinkingConfig(e){let t=it(e,this.reasoningEffort);if(t)return{includeThoughts:!1,thinkingLevel:t.toUpperCase()};if(this.isGemma4Model(e))return{includeThoughts:!1,thinkingLevel:"MINIMAL"}}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}adaptKeysForApi(e){let t={toolConfig:"tool_config",functionCallingConfig:"function_calling_config",functionDeclarations:"function_declarations",functionCall:"function_call",functionResponse:"function_response",thoughtSignature:"thought_signature"};return Array.isArray(e)?e.map(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,this.mcpSchemaInitializationError=void 0}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1,this.mcpSchemaInitializationError=void 0}hasMCPServers(){return this.mcpServers.length>0}getMCPSchemaInitializationError(){return this.mcpSchemaInitializationError}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((i,r)=>setTimeout(()=>r(new Error("MCP schema fetch timeout")),5e3)),t=Ho.fetchAllToolSchemasWithStatus(this.mcpServers),o=await Promise.race([t,e]);this.mcpToolSchemas=o.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=o.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=Wi(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.model,!0),{blocks:r}=await this.parseStream(i,t,this.model);return O.getFullText(r)},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 M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.visionModel,!0),{blocks:r}=await this.parseStream(i,t,this.visionModel);return O.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:i=>{i.filter(r=>r.type==="text").forEach(r=>t(r.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 l={contents:e.some(f=>Array.isArray(f.content)&&f.content.some(_=>_?.type==="image_url"||_?.inlineData))?await Fi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):Vi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:T(this.responseLength)}},p=this.resolveThinkingConfig(t);p&&(l.generationConfig.thinkingConfig=p);let c=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),c=this.mcpToolSchemas}catch(f){console.warn("MCP initialization failed, skipping MCP tools:",f)}let d=Bi(this.tools,c);d&&Object.assign(l,d);let u=async(f,_)=>{let y=o?"streamGenerateContent":"generateContent",qn=o?"?alt=sse":"",ji=`${Xo}/${f}/models/${t}:${y}${qn}${qn?"&":"?"}key=${this.apiKey}`;return E.post(ji,_)},m=/flash[-_]lite/.test(t),g=this.isGemma4Model(t),a=/gemini-2\.5/.test(t),h=/^gemini-3(?:\.[0-9]+)?-/.test(t),v=m||g||a||h,R=v?"v1beta":"v1",P=async()=>{try{let f=R==="v1"?l:this.adaptKeysForApi(l);return await u(R,f)}catch(f){let _=/Unknown name|Cannot find field|404/.test(f?.message||"")||f?.status===404;if(!v&&_)try{return await u("v1beta",this.adaptKeysForApi(l))}catch(y){throw y instanceof Error&&(y.cause=f),y}throw f}};try{return await P()}catch(f){throw f.body&&(console.error("Gemini API Error Details:",f.body),console.error("Request Body:",JSON.stringify(l,null,2))),f}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let o=t.id??this.genUUID();return this.callIdMap.set(o,t.name),this.functionCallContextMap.set(o,{name:t.name,providerCallId:t.id,thoughtSignature:e.thoughtSignature??e.thought_signature}),{type:"tool_use",id:o,name:t.name,input:t.args??{}}}createFunctionResponseBlock(e){let t=e.functionResponse??e.function_response;if(t)return{type:"tool_result",tool_use_id:t.id??t.name,content:JSON.stringify(t.response)}}async parseStream(e,t,o){let i=e.body.getReader(),r=new TextDecoder,s=[],l=[],p="",c=u=>{if(!u||u==="[DONE]")return;let m;try{m=JSON.parse(u)}catch{return}for(let g of m.candidates??[])for(let a of g.content?.parts??[]){this.shouldExposeTextPart(a,o)&&(t(a.text),O.addTextBlock(s,a.text));let h=this.createFunctionCallBlock(a);h&&l.push(h);let v=this.createFunctionResponseBlock(a);v&&l.push(v)}};for(;;){let{done:u,value:m}=await i.read();if(u)break;p+=r.decode(m,{stream:!0});let g;for(;(g=p.indexOf(`
14
- `))!==-1;){let a=p.slice(0,g);if(p=p.slice(g+1),a.endsWith("\r")&&(a=a.slice(0,-1)),!a.trim()){c("");continue}a.startsWith("data:")&&(a=a.slice(5).trim()),a&&c(a)}}return p&&c(p),{blocks:[...s,...l],stop_reason:l.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],i=[];for(let s of e.candidates??[])for(let l of s.content?.parts??[]){this.shouldExposeTextPart(l,t)&&o.push({type:"text",text:l.text});let p=this.createFunctionCallBlock(l);p&&i.push(p);let c=this.createFunctionResponseBlock(l);c&&i.push(c)}return{blocks:[...o,...i],stop_reason:i.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callGemini(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callGemini(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}genUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};var be=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!nn(t))throw new Error(`Model ${t} does not support Gemini reasoning_effort. Use it with Gemini 3 thinkingLevel models; Gemini 2.5 models use thinkingBudget instead.`);let o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"resolved"});return new Ae(e.apiKey,t,o,e.tools||[],e.mcpServers||[],e.responseLength,it(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...kt]}getDefaultModel(){return $}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return nt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Yr(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var Ne=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja","en"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this.initialPrompts=(e.initialPrompts??[]).map(t=>({...t})),this._responseLength=e.responseLength}getModel(){return se}getVisionModel(){return se}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 r=await this.generateResponse(e);return o(r),{blocks:[{type:"text",text:r}],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=Yr();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 148+ on a supported desktop device is required for web pages.");let o=this.getModelOptions(),i=await t.availability(o);if(i!=="available"&&i!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${i}". Expected "available" or "downloadable".`);let s=e.filter(u=>u.role==="system").map(u=>u.content).join(`
15
- `),l=e.filter(u=>u.role==="user"||u.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(l);if(p===-1)throw new Error("No user message found in the provided messages.");let c=l[p],d=await this.createSession(t,s,l.slice(0,p),o);try{return await d.prompt(c.content)}finally{try{d.destroy()}catch{}}}async createSession(e,t,o,i){let r=this.buildInitialPrompts(t,o),s={...i,...r.length>0?{initialPrompts:r}:{}};return e.create(s)}getModelOptions(){return{expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]}}buildInitialPrompts(e,t){let o=this.initialPrompts.filter(s=>s.role==="system").map(s=>s.content),i=this.buildSystemPrompt([e,...o].filter(Boolean).join(`
10
+ `;var le="gemini-nano",$n=20;var X=class extends Error{constructor(t,o,i){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=i;this.name="HttpError"}},Dt=class Dt{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},i={}){let{timeout:r=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",f=m?new AbortController:void 0,l=m?setTimeout(()=>f.abort(),r):void 0,h=await Dt.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...f?{signal:f.signal}:{}});if(l&&clearTimeout(l),!h.ok){let v=await h.text();throw new X(h.status,h.statusText,v)}return h}catch(m){if(d=m,m instanceof X&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);u<s&&await new Promise(f=>setTimeout(f,a*(u+1)))}throw d||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new X(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:i=3e4,retries:r=0,retryDelay:s=1e3}=o,a=null;for(let p=0;p<=r;p++)try{let c=typeof AbortController<"u",d=c?new AbortController:void 0,u=c?setTimeout(()=>d.abort(),i):void 0,m=await Dt.fetchImpl(e,{method:"GET",headers:t,...d?{signal:d.signal}:{}});if(u&&clearTimeout(u),!m.ok){let f=await m.text();throw new X(m.status,m.statusText,f)}return m}catch(c){if(a=c,c instanceof X&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);p<r&&await new Promise(d=>setTimeout(d,s*(p+1)))}throw a||new Error("Request failed")}};Dt.fetchImpl=(e,t)=>fetch(e,t);var _=Dt;var E=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 Ir=["happy","sad","angry","surprised","neutral"],yi=/\[([a-z]+)\]/i,zn=/\[[a-z]+\]\s*/gi,Ie=class{static extractEmotion(e){let t=e.match(yi);if(t){let o=t[1].toLowerCase(),i=e.replace(zn,"").trim();return{emotion:o,cleanText:i}}return{cleanText:e}}static isValidEmotion(e){return Ir.includes(e)}static cleanEmotionTags(e){return e.replace(zn,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Pi(n){let{emotion:e,cleanText:t}=Ie.extractEmotion(n);return e?{emotion:e,text:t}:{text:t}}function Dr(n){return n.map(e=>Pi(e))}function Ar(n){return n.emotion?Ie.addEmotionTag(n.emotion,n.text):n.text}async function br(n,e){let{blocks:t}=await n.chatOnce(e,!1,()=>{});return E.getFullText(t)}var Ri=(n,e,t)=>{try{return JSON.parse(n)}catch(o){return t?.(n,o),e}},pe=(n,e)=>n?Ri(n,{},e):{};var xi=(n,e)=>{try{return JSON.parse(n)}catch(t){if(e){e(n,t);return}throw t}},Bo=n=>typeof n=="string"?n:Array.isArray(n)?n.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"?e.text:"").join(""):"",jn=n=>{let e=n.choices?.[0],t=n.error??e?.error;if(!t&&e?.finish_reason!=="error")return;let o=typeof t=="string"?t:typeof t?.message=="string"?t.message:"The provider ended the response with an error.";throw new Error(`Provider response error: ${o}`)},Ii=async(n,e)=>{let t=n.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,i="",r=!1;for(;!r;){let{done:s,value:a}=await t.read();if(s)break;i+=o.decode(a,{stream:!0});let p=i.split(`
11
+ `);i=p.pop()||"";for(let c of p){let d=c.trim();if(!d||d.startsWith(":")||!d.startsWith("data:"))continue;let u=d.slice(5).trim();if(u==="[DONE]"){r=!0;break}e(u)}}};async function K(n,e,t={}){let o="";return await Ii(n,i=>{let r=xi(i,t.onJsonError);if(!r)return;t.throwOnApiError&&jn(r);let s=Bo(r.choices?.[0]?.delta?.content);s&&(e(s),o+=s)}),o}async function x(n,e,t={}){let o=[],i=new Map,r="",s="",a,p,c=t.appendTextBlock??E.append;await Ii(n,l=>{let h=xi(l,t.onJsonError);if(!h)return;t.throwOnApiError&&jn(h);let v=h.choices?.[0];typeof v?.finish_reason=="string"&&(a=v.finish_reason),h.usage&&(p=h.usage);let P=v?.delta,C=Bo(P?.content);C&&(e(C),c(o,C),r+=C);let R=Bo(P?.reasoning_content);R&&(s+=R),P?.tool_calls&&P.tool_calls.forEach(g=>{let S=i.get(g.index)??{id:g.id,type:g.type,name:g.function?.name,args:""};g.id&&(S.id=g.id),g.type&&(S.type=g.type),g.function?.name&&(S.name=g.function.name),S.args+=g.function?.arguments||"",i.set(g.index,S)})});let d=Array.from(i.entries()).sort((l,h)=>l[0]-h[0]).map(([l,h])=>({type:"tool_use",id:h.id,name:h.name,input:pe(h.args,t.onJsonError)})),u=[...o,...d],m=Array.from(i.entries()).sort((l,h)=>l[0]-h[0]).map(([l,h])=>({id:h.id,type:"function",function:{name:h.name,arguments:h.args}})),f={role:"assistant",content:r,...s?{reasoning_content:s}:{},...m.length>0?{tool_calls:m}:{}};return{blocks:u,stop_reason:d.length?"tool_use":"end",truncated:a==="length",finish_reason:a,usage:p,...t.preserveAssistantMessage?{assistant_message:f}:{}}}function I(n,e={}){e.throwOnApiError&&jn(n);let t=n?.choices?.[0],o=[],i=Bo(t?.message?.content);t?.message?.tool_calls?.length?t.message.tool_calls.forEach(s=>o.push({type:"tool_use",id:s.id,name:s.function?.name,input:pe(s.function?.arguments,e.onJsonError)})):i&&o.push({type:"text",text:i});let r=t?.message?{...t.message,role:"assistant",content:i}:void 0;return{blocks:o,stop_reason:t?.finish_reason==="tool_calls"||o.some(s=>s.type==="tool_use")?"tool_use":"end",truncated:t?.finish_reason==="length",finish_reason:t?.finish_reason,usage:n?.usage,...e.preserveAssistantMessage?{assistant_message:r}:{}}}var D=(n,e="chat-completions")=>n.length===0?[]:e==="responses"?n.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):n.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function M(n){if(!n.hasTools){let t=await n.runWithoutTools();if(typeof t=="string"){await n.onCompleteResponse(t);return}let o=E.getFullText(t.blocks);await n.onCompleteResponse(o,t);return}let e=await n.runWithTools();if(n.onToolBlocks&&n.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=E.getFullText(e.blocks);await n.onCompleteResponse(t,e);return}throw new Error(n.toolErrorMessage)}var T=n=>{let e=n.model??n.defaultModel,t=n.visionModel??(n.supportsVisionForModel(e)?e:n.defaultVisionModel);if(n.validate==="explicit"&&n.visionModel&&!n.supportsVisionForModel(n.visionModel))throw new Error(`Model ${n.visionModel} does not support vision capabilities.`);if(n.validate==="resolved"&&!n.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var Nr="https://openrouter.ai/api/v1/models",wr=2,kr=12e3,Gr=1,Vr=10;function qn(n){return n instanceof Error?n.message:String(n)}function Wo(n,e){return typeof n!="number"||!Number.isFinite(n)?e:Math.max(1,Math.floor(n))}function Fr(n){let e=new Set,t=[];for(let o of n){let i=o.trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}async function Di(n,e,t){if(!(typeof AbortController<"u"))return fetch(n,e);let i=new AbortController,r=setTimeout(()=>i.abort(),t);try{return await fetch(n,{...e,signal:i.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error(`Timeout after ${t}ms`):s}finally{clearTimeout(r)}}async function Ai(n){let e=`HTTP ${n.status} ${n.statusText}`.trim(),t="";try{t=await n.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Ur(n){if(!n||typeof n!="object")throw new Error("Invalid models response shape");let e=n,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(i=>i.id).filter(i=>typeof i=="string");return Fr(o)}async function Kr({modelId:n,apiKey:e,endpoint:t,timeoutMs:o,appName:i,appUrl:r}){let s={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};i&&(s["X-Title"]=i),r&&(s["HTTP-Referer"]=r);try{let a=await Di(t,{method:"POST",headers:s,body:JSON.stringify({model:n,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:n,ok:!1,reason:await Ai(a)};try{await a.json()}catch(p){return{id:n,ok:!1,reason:`JSON parse failed: ${qn(p)}`}}return{id:n,ok:!0}}catch(a){return{id:n,ok:!1,reason:qn(a)}}}async function Hr(n,e,t){if(n.length===0)return[];let o=new Array(n.length),i=0,r=Math.min(e,n.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<n.length;){let s=i;i+=1,o[s]=await t(n[s])}})),o}async function Br(n){let e=n.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=n.modelsEndpoint||Nr,o=n.endpoint||ft,i=Wo(n.timeoutMs,kr),r=Wo(n.concurrency,wr),s=Wo(n.maxCandidates,Gr),a=Wo(n.maxWorking,Vr),p=await Di(t,{method:"GET"},i);if(!p.ok)throw new Error(await Ai(p));let c;try{c=await p.json()}catch(l){throw new Error(`JSON parse failed: ${qn(l)}`)}let d=Ur(c).filter(l=>ie(l)).slice(0,s),u=await Hr(d,r,l=>Kr({modelId:l,apiKey:e,endpoint:o,timeoutMs:i,appName:n.appName,appUrl:n.appUrl})),m=u.filter(l=>l.ok).map(l=>l.id).slice(0,a),f=u.filter(l=>!l.ok).map(l=>({id:l.id,reason:l.reason||"Unknown error"}));return{working:m,failed:f,fetchedAt:Date.now()}}function bi(n){return n.map(e=>({role:At(e.role),content:e.provider_content??e.content}))}function Ni(n){return n.map(e=>{if(e.provider_content)return{role:At(e.role),content:e.provider_content};if(typeof e.content=="string")return{role:At(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:Wr(o.image_url.url)}}}return o}).filter(o=>o);return{role:At(e.role),content:t}}return{role:At(e.role),content:[]}})}function At(n){switch(n){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}function Wr(n){switch(n.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 De=class{constructor(e,t=b,o=b,i=[],r=[],s,a){this.provider="claude";if(this.apiKey=e,this.model=t||b,this.visionModel=o||b,this.tools=i,this.mcpServers=r,this.responseLength=s,this.reasoningEffort=a,!gt.includes(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`)}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e)}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e)}hasMCPServers(){return this.mcpServers.length>0}async processChat(e,t,o){await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let 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 M({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 r=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")),p={model:t,system:r,messages:a?Ni(s):bi(s),stream:o,max_tokens:i!==void 0?i:L(this.responseLength)};this.reasoningEffort!==void 0&&k(t).includes(this.reasoningEffort)&&(p.output_config={effort:this.reasoningEffort}),this.tools.length&&(p.tools=this.tools.map(u=>({name:u.name,description:u.description,input_schema:u.parameters})),p.tool_choice={type:"auto"}),this.mcpServers.length>0&&(p.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(pn,p,c)}async parseStream(e,t){let o=e.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,p="";for(;;){let{done:c,value:d}=await o.read();if(c)break;p+=i.decode(d,{stream:!0});let u;for(;(u=p.indexOf(`
12
+ `))!==-1;){let m=p.slice(0,u).trim();if(p=p.slice(u+1),!m.startsWith("data:"))continue;let f=m.slice(5).trim();if(f==="[DONE]")break;let l=JSON.parse(f);if(l.type==="content_block_start"&&l.content_block&&typeof l.index=="number"&&s.set(l.index,{...l.content_block}),l.type==="content_block_delta"&&l.delta?.type==="text_delta"){t(l.delta.text),r.push({type:"text",text:l.delta.text});let h=s.get(l.index);h?.type==="text"&&(h.text=`${h.text??""}${l.delta.text}`)}if(l.type==="content_block_delta"&&l.delta?.type==="thinking_delta"){let h=s.get(l.index);h?.type==="thinking"&&(h.thinking=`${h.thinking??""}${l.delta.thinking??""}`)}if(l.type==="content_block_delta"&&l.delta?.type==="signature_delta"){let h=s.get(l.index);h?.type==="thinking"&&(h.signature=`${h.signature??""}${l.delta.signature??""}`)}if(l.type==="content_block_start"&&l.content_block?.type==="tool_use"?a.set(l.index,{id:l.content_block.id,name:l.content_block.name,args:""}):l.type==="content_block_start"&&l.content_block?.type==="mcp_tool_use"?a.set(l.index,{id:l.content_block.id,name:l.content_block.name,args:"",server_name:l.content_block.server_name}):l.type==="content_block_start"&&l.content_block?.type==="tool_result"?r.push({type:"tool_result",tool_use_id:l.content_block.tool_use_id,content:l.content_block.content??""}):l.type==="content_block_start"&&l.content_block?.type==="mcp_tool_result"&&r.push({type:"mcp_tool_result",tool_use_id:l.content_block.tool_use_id,is_error:l.content_block.is_error??!1,content:l.content_block.content??[]}),l.type==="content_block_delta"&&l.delta?.type==="input_json_delta"){let h=a.get(l.index);h&&(h.args+=l.delta.partial_json||"")}if(l.type==="content_block_stop"&&a.has(l.index)){let{id:h,name:v,args:P,server_name:C}=a.get(l.index),R=JSON.parse(P||"{}"),g=s.get(l.index);g&&(g.input=R),C?r.push({type:"mcp_tool_use",id:h,name:v,server_name:C,input:R}):r.push({type:"tool_use",id:h,name:v,input:R}),a.delete(l.index)}}}return{blocks:r,providerContent:[...s.entries()].sort(([c],[d])=>c-d).map(([,c])=>c),stop_reason:r.some(c=>c.type==="tool_use"||c.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,providerContent:(e.content??[]).map(o=>({...o})),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 r=await this.callClaude(e,this.model,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callClaude(e,this.visionModel,t,i),s=t?await this.parseStream(r,o):this.parseOneShot(await r.json());return this.convertToStandardCompletion(s)}convertToStandardCompletion(e){let t=e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result");return{blocks:t,stop_reason:e.stop_reason,assistant_message:{role:"assistant",content:t.filter(o=>o.type==="text").map(o=>o.text).join(""),provider_content:e.providerContent}}}};var Ae=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=k(t);if(e.reasoning_effort!==void 0&&!o.includes(e.reasoning_effort)){let r=o.length>0?`Supported values: ${o.join(", ")}.`:"This model does not expose configurable effort.";throw new Error(`Model ${t} does not support Claude reasoning_effort: ${e.reasoning_effort}. ${r}`)}let i=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"resolved"});return new De(e.apiKey,t,i,e.tools??[],e.mcpServers??[],e.responseLength,e.reasoning_effort)}getProviderName(){return"claude"}getSupportedModels(){return[Wt,$t,zt,b,lt,pt,ct,ut,ht,dt,mt,Bt]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return gt.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};async function $o(n,e,t={}){let o=n.body.getReader(),i=new TextDecoder,r=[],s=new Map,a=new Map,p,c,d,u="";for(;;){let{done:h,value:v}=await o.read();if(h)break;u+=i.decode(v,{stream:!0});let P="",C="",R=u.split(`
13
+ `);u=R.pop()||"";for(let g=0;g<R.length;g++){let S=R[g].trim();if(S.startsWith("event:"))P=S.slice(6).trim();else if(S.startsWith("data:"))C=S.slice(5).trim();else if(S===""&&P&&C){try{let N=JSON.parse(C);$r(P,N,e,r,s,a,w=>{w.responseStatus!==void 0&&(p=w.responseStatus),w.incompleteDetails!==void 0&&(c=w.incompleteDetails),w.usage!==void 0&&(d=w.usage)})}catch(N){t.onJsonError?.(C,N),console.warn("Failed to parse SSE data:",C)}P="",C=""}}}let m=Array.from(s.values()).map(h=>({type:"tool_use",id:h.id,name:h.name,input:pe(h.arguments,t.onJsonError)})),f=Array.from(a.values()),l=E.getFullText(r);return{blocks:[...r,...m],stop_reason:m.length?"tool_use":"end",truncated:p==="incomplete",response_status:p,incomplete_details:c,usage:d,...f.length>0?{assistant_message:{role:"assistant",content:l,provider_content:f}}:{}}}function $r(n,e,t,o,i,r,s){switch(n){case"response.output_item.added":wi(r,e.item),e.item?.type==="message"&&Array.isArray(e.item.content)?e.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(t(a.text),E.append(o,a.text))}):e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.function_call_arguments.delta":{let a=i.get(e.item_id);a&&typeof e.delta=="string"&&(a.arguments+=e.delta);let p=r.get(e.item_id);p&&typeof e.delta=="string"&&(p.arguments=`${p.arguments??""}${e.delta}`);break}case"response.function_call_arguments.done":{let a=i.get(e.item_id);a&&typeof e.arguments=="string"&&(a.arguments=e.arguments);let p=r.get(e.item_id);p&&typeof e.arguments=="string"&&(p.arguments=e.arguments);break}case"response.output_item.done":wi(r,e.item),e.item?.type==="function_call"&&i.set(e.item.id,{id:e.item.call_id??e.item.id,name:e.item.name,arguments:e.item.arguments??""});break;case"response.content_part.added":e.part?.type==="output_text"&&typeof e.part.text=="string"&&(t(e.part.text),E.append(o,e.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let a=typeof e.delta=="string"?e.delta:e.delta?.text??"";a&&(t(a),E.append(o,a));break}case"response.output_text.done":case"response.content_part.done":case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;case"response.completed":s(ki(e,"completed"));break;case"response.incomplete":s(ki(e,"incomplete"));break;default:break}}function wi(n,e){if(!e||typeof e!="object")return;let t=typeof e.id=="string"&&e.id?e.id:`output-item-${n.size}`;n.set(t,{...e})}function ki(n,e){let t=n?.response??n;return{responseStatus:t?.status??e,incompleteDetails:t?.incomplete_details??null,usage:t?.usage}}function Gi(n,e={}){let t=[];return n.output&&Array.isArray(n.output)&&n.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(i=>{i.type==="output_text"&&i.text&&t.push({type:"text",text:i.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.call_id??o.id,name:o.name,input:pe(o.arguments,e.onJsonError)})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end",truncated:n?.status==="incomplete",response_status:n?.status,incomplete_details:n?.incomplete_details??null,usage:n?.usage,...Array.isArray(n?.output)&&n.output.length>0?{assistant_message:{role:"assistant",content:t.filter(o=>o.type==="text").map(o=>o.text).join(""),provider_content:n.output}}:{}}}function Vi({tools:n,mcpServers:e,isResponsesAPI:t}){let o=[];return n.length>0&&o.push(...D(n,t?"responses":"chat-completions")),e.length>0&&t&&o.push(...zr(e)),o}function zr(n){return n.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 jr={[O.VERY_SHORT]:800,[O.SHORT]:1200,[O.MEDIUM]:2e3,[O.LONG]:3e3,[O.VERY_LONG]:8e3,[O.DEEP]:25e3},qr={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3,max:25e3},Xr=new Set(["openai-compatible","deepseek","mistral","sakana","plamo"]);function Jr(n){return n.type!=="json_schema"?n:{type:n.type,...n.json_schema}}function Fi({provider:n,endpoint:e,messages:t,model:o,stream:i,tools:r,mcpServers:s,responseLength:a,verbosity:p,reasoning_effort:c,enableReasoningSummary:d,responseFormat:u,maxTokens:m}){let f=e===A;Yr(e,s);let l={model:o,stream:i},h=Zr({provider:n,model:o,responseLength:a,reasoning_effort:c,maxTokens:m});f?h!==void 0&&(l.max_output_tokens=h):h!==void 0&&(Ui(n)?l.max_tokens=h:l.max_completion_tokens=h),f?l.input=Qr(t):l.messages=n==="mistral"?es(t):t,ne(o)&&(f?(c&&(l.reasoning={...l.reasoning,effort:c},d&&(l.reasoning.summary="auto")),p&&(l.text={...l.text,format:{type:"text"},verbosity:p})):(c&&(l.reasoning_effort=c),p&&(l.verbosity=p))),u&&(f?l.text={...l.text,format:Jr(u)}:l.response_format=u),n==="mistral"&&Rt(o)&&c&&Fn(c)&&(l.reasoning_effort=c),n==="plamo"&&c&&(l.reasoning_effort=c),n==="deepseek"&&c&&(l.thinking={type:c==="none"?"disabled":"enabled"},c!=="none"&&(l.reasoning_effort=c));let v=Vi({tools:r,mcpServers:s,isResponsesAPI:f});return v.length>0&&(l.tools=v,f||(l.tool_choice="auto")),l}function Zr({provider:n,model:e,responseLength:t,reasoning_effort:o,maxTokens:i}){if(i!==void 0)return i;let r=Ui(n)?t!==void 0?L(t):void 0:L(t);if(n!=="openai"||!ne(e)||t===void 0)return r;let s=o??rt(e);return Math.max(r??0,jr[t],qr[s])}function Yr(n,e){if(e.length>0&&n===J)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${n}. Please use OpenAI Responses API endpoint: ${A}. MCP tools are only available in the Responses API endpoint.`)}function Qr(n){return n.flatMap(e=>{if(e.role==="assistant"&&e.provider_content?.length)return e.provider_content;if(e.role==="tool"&&e.tool_call_id)return[{type:"function_call_output",call_id:e.tool_call_id,output:e.content}];let t=[],o={role:e.role==="tool"?"user":e.role};return typeof e.content=="string"?o.content=e.content:Array.isArray(e.content)?o.content=e.content.map(r=>r.type==="text"?{type:"input_text",text:r.text}:r.type==="image_url"?{type:"input_image",image_url:r.image_url.url}:r):o.content=e.content,(typeof o.content!="string"||o.content.length>0)&&t.push(o),e.role==="assistant"&&e.tool_calls&&t.push(...e.tool_calls.map(r=>({type:"function_call",call_id:r.id,name:r.function.name,arguments:r.function.arguments}))),t})}function es(n){return n.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 Ui(n){return Xr.has(n)}var y=class{constructor(e,t=oe,o=oe,i,r=J,s=[],a,p,c,d=!1,u="openai",m=!0,f){if(this.provider=u,this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.mcpServers=s,this.responseLength=a,this.verbosity=p,this.reasoning_effort=c,this.enableReasoningSummary=d,this.responseFormat=f,m&&!ot.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.model,!0),r=this.endpoint===A;try{if(r){let s=await $o(i,t);return E.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 M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenAI(e,this.visionModel,!0),r=this.endpoint===A;try{if(r){let s=await $o(i,t);return E.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 r=await this.callOpenAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callOpenAI(e,this.visionModel,t,i);return this.parseResponse(r,t,o)}async parseResponse(e,t,o){return this.endpoint===A?t?$o(e,o):Gi(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,i){let r=Fi({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,responseFormat:this.responseFormat,maxTokens:i}),s={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(s.Authorization=`Bearer ${this.apiKey}`),await _.post(this.endpoint,r,s)}async handleStream(e,t){return K(e,t)}async parseStream(e,t){return x(e,t,{appendTextBlock:E.addTextBlock})}parseOneShot(e){return I(e)}};var be=class extends y{constructor(e,t=ae,o=t,i,r=Lt,s,a){let p=In(t,a);if(super(e,t,o,i,r,[],s,void 0,p,!1,"deepseek",!1),i?.length&&p!==void 0&&p!=="none")throw new Error("DeepSeek thinking with tools is not supported yet. Use reasoning_effort: 'none' for tool calling.")}};var Ne=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new be(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"deepseek"}getSupportedModels(){return[...xn]}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 Lt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ki=(n,e)=>({name:`mcp_${n.name}_search`,description:e==="schema-fetch-failed"?`Search using ${n.name} MCP server (schema fetch failed)`:`Search using ${n.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}),zo=class{static async fetchToolSchemas(e){return(await this.fetchToolSchemasWithStatus(e)).schemas}static async fetchToolSchemasWithStatus(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let i=await(await _.post(`${e.url}/tools`,{},t)).json();return Array.isArray(i.tools)?{schemas:i.tools.map(r=>({name:`mcp_${e.name}_${r.name}`,description:r.description||`Tool from ${e.name} MCP server`,parameters:r.inputSchema||{type:"object",properties:{},required:[]}})),failures:[]}:{schemas:[Ki(e)],failures:[]}}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),{schemas:[Ki(e,"schema-fetch-failed")],failures:[{server:e,error:t}]}}}static async fetchAllToolSchemas(e){return(await this.fetchAllToolSchemasWithStatus(e)).schemas}static async fetchAllToolSchemasWithStatus(e){let t=[],o=[];for(let i of e)try{let r=await this.fetchToolSchemasWithStatus(i);t.push(...r.schemas),o.push(...r.failures)}catch(r){console.error(`Failed to fetch schemas from ${i.name}:`,r),o.push({server:i,error:r})}return{schemas:t,failures:o}}};function Hi(n){switch(n){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}function Bi(n,e={}){let t=[],o=null,i=[],r=()=>{o&&i.length&&(t.push({role:o,parts:[...i]}),i=[]),o=null};for(let s of n){if(s.role==="system")continue;let a=Hi(s.role);if(s.tool_calls){r();let p=s.tool_calls.map(c=>zi(c,e));p.length>0&&t.push({role:"model",parts:p});continue}if(s.role==="tool"){r(),qi(t,ji(s,e));continue}a!==o&&r(),o=a,i.push({text:s.content})}return r(),t}async function Wi(n,e={}){let t=e.imageFetcher??_.get,o=e.blobToBase64??ns,i=[],r=null,s=[],a=()=>{r&&s.length>0&&(i.push({role:r,parts:[...s]}),s=[]),r=null};for(let p of n){if(p.role==="system")continue;let c=Hi(p.role);if(p.tool_calls){a();let d=p.tool_calls.map(u=>zi(u,e));d.length>0&&i.push({role:"model",parts:d});continue}if(p.role==="tool"){a(),qi(i,ji(p,e));continue}if(c!==r&&s.length>0&&a(),r=c,typeof p.content=="string")s.push({text:p.content});else if(Array.isArray(p.content)){for(let d of p.content)if(d.type==="text")s.push({text:d.text});else if(d.type==="image_url")try{let m=await(await t(d.image_url.url)).blob(),f=await o(m);s.push({inlineData:{mimeType:m.type||"image/jpeg",data:f.split(",")[1]}})}catch(u){throw console.error("Error processing image:",u),new Error(`Failed to process image: ${u.message}`)}}}return a(),i}function $i(n){let e=n.flatMap(t=>t.role!=="system"?[]:typeof t.content=="string"?t.content?[{text:t.content}]:[]:t.content.flatMap(o=>o.type==="text"&&o.text?[{text:o.text}]:[]));return e.length>0?{parts:e}:void 0}function zi(n,e){e.callIdMap?.set(n.id,n.function.name);let t=e.functionCallContextMap?.get(n.id),o={functionCall:{...t?.providerCallId?{id:t.providerCallId}:{},name:n.function.name,args:JSON.parse(n.function.arguments||"{}")}};return t?.thoughtSignature&&(o.thoughtSignature=t.thoughtSignature),o}function ji(n,e){let t=n.tool_call_id,o=e.functionCallContextMap?.get(t);return{functionResponse:{...o?.providerCallId?{id:o.providerCallId}:{},name:n.name??o?.name??e.callIdMap?.get(t)??"result",response:os(ts(n.content))}}}function qi(n,e){let t=n[n.length-1];if(t?.role==="user"&&t.parts.every(i=>i.functionResponse)){t.parts.push(e);return}n.push({role:"user",parts:[e]})}function ts(n){try{return JSON.parse(n)}catch{return n}}function os(n){return n===null?{content:null}:typeof n=="object"?n:{content:n}}function ns(n){return new Promise((e,t)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=t,o.readAsDataURL(n)})}function is(n,e){return[...n,...e].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}function Xi(n,e){let t=is(n,e);if(t.length!==0)return{tools:[{functionDeclarations:t}],toolConfig:{functionCallingConfig:{mode:"AUTO"}}}}function Ji(n){return n.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 we=class{constructor(e,t=j,o=j,i=[],r=[],s,a){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;this.functionCallContextMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=s,this.reasoningEffort=a,!st.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=i,this.mcpServers=r}isGemma4Model(e){return/^gemma-4-/.test(e)}resolveThinkingConfig(e){let t=at(e,this.reasoningEffort);if(t)return{includeThoughts:!1,thinkingLevel:t.toUpperCase()};if(this.isGemma4Model(e))return{includeThoughts:!1,thinkingLevel:"MINIMAL"}}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}adaptKeysForApi(e){let t={toolConfig:"tool_config",functionCallingConfig:"function_calling_config",functionDeclarations:"function_declarations",functionCall:"function_call",functionResponse:"function_response",thoughtSignature:"thought_signature"};return Array.isArray(e)?e.map(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,this.mcpSchemaInitializationError=void 0}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1,this.mcpSchemaInitializationError=void 0}hasMCPServers(){return this.mcpServers.length>0}getMCPSchemaInitializationError(){return this.mcpSchemaInitializationError}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((i,r)=>setTimeout(()=>r(new Error("MCP schema fetch timeout")),5e3)),t=zo.fetchAllToolSchemasWithStatus(this.mcpServers),o=await Promise.race([t,e]);this.mcpToolSchemas=o.schemas,this.mcpSchemasInitialized=!0,this.mcpSchemaInitializationError=o.failures[0]?.error}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpSchemaInitializationError=e,this.mcpToolSchemas=Ji(this.mcpServers),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.model,!0),{blocks:r}=await this.parseStream(i,t,this.model);return E.getFullText(r)},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 M({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let i=await this.callGemini(e,this.visionModel,!0),{blocks:r}=await this.parseStream(i,t,this.visionModel);return E.getFullText(r)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:i=>{i.filter(r=>r.type==="text").forEach(r=>t(r.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(g=>Array.isArray(g.content)&&g.content.some(S=>S?.type==="image_url"||S?.inlineData))?await Wi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}):Bi(e,{callIdMap:this.callIdMap,functionCallContextMap:this.functionCallContextMap}),generationConfig:{maxOutputTokens:i!==void 0?i:L(this.responseLength)}},p=$i(e);p&&(a.systemInstruction=p);let c=this.resolveThinkingConfig(t);c&&(a.generationConfig.thinkingConfig=c);let d=[];if(this.mcpServers.length>0)try{await this.initializeMCPSchemas(),d=this.mcpToolSchemas}catch(g){console.warn("MCP initialization failed, skipping MCP tools:",g)}let u=Xi(this.tools,d);u&&Object.assign(a,u);let m=async(g,S)=>{let N=o?"streamGenerateContent":"generateContent",w=o?"?alt=sse":"",tr=`${Qo}/${g}/models/${t}:${N}${w}${w?"&":"?"}key=${this.apiKey}`;return _.post(tr,S)},f=/flash[-_]lite/.test(t),l=this.isGemma4Model(t),h=/gemini-2\.5/.test(t),v=/^gemini-3(?:\.[0-9]+)?-/.test(t),P=f||l||h||v,C=P?"v1beta":"v1",R=async()=>{try{let g=C==="v1"?a:this.adaptKeysForApi(a);return await m(C,g)}catch(g){let S=/Unknown name|Cannot find field|404/.test(g?.message||"")||g?.status===404;if(!P&&S)try{return await m("v1beta",this.adaptKeysForApi(a))}catch(N){throw N instanceof Error&&(N.cause=g),N}throw g}};try{return await R()}catch(g){throw g.body&&(console.error("Gemini API Error Details:",g.body),console.error("Request Body:",JSON.stringify(a,null,2))),g}}createFunctionCallBlock(e){let t=e.functionCall??e.function_call;if(!t)return;let o=t.id??this.genUUID();return this.callIdMap.set(o,t.name),this.functionCallContextMap.set(o,{name:t.name,providerCallId:t.id,thoughtSignature:e.thoughtSignature??e.thought_signature}),{type:"tool_use",id:o,name:t.name,input:t.args??{}}}createFunctionResponseBlock(e){let t=e.functionResponse??e.function_response;if(t)return{type:"tool_result",tool_use_id:t.id??t.name,content:JSON.stringify(t.response)}}async parseStream(e,t,o){let i=e.body.getReader(),r=new TextDecoder,s=[],a=[],p="",c=u=>{if(!u||u==="[DONE]")return;let m;try{m=JSON.parse(u)}catch{return}for(let f of m.candidates??[])for(let l of f.content?.parts??[]){this.shouldExposeTextPart(l,o)&&(t(l.text),E.addTextBlock(s,l.text));let h=this.createFunctionCallBlock(l);h&&a.push(h);let v=this.createFunctionResponseBlock(l);v&&a.push(v)}};for(;;){let{done:u,value:m}=await i.read();if(u)break;p+=r.decode(m,{stream:!0});let f;for(;(f=p.indexOf(`
14
+ `))!==-1;){let l=p.slice(0,f);if(p=p.slice(f+1),l.endsWith("\r")&&(l=l.slice(0,-1)),!l.trim()){c("");continue}l.startsWith("data:")&&(l=l.slice(5).trim()),l&&c(l)}}return p&&c(p),{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});let p=this.createFunctionCallBlock(a);p&&i.push(p);let c=this.createFunctionResponseBlock(a);c&&i.push(c)}return{blocks:[...o,...i],stop_reason:i.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},i){let r=await this.callGemini(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){let r=await this.callGemini(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}genUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};var ke=class{createChatService(e){let t=e.model||this.getDefaultModel();if(e.reasoning_effort!==void 0&&!ln(t))throw new Error(`Model ${t} does not support Gemini reasoning_effort. Use it with Gemini 3 thinkingLevel models; Gemini 2.5 models use thinkingBudget instead.`);let o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"resolved"});return new we(e.apiKey,t,o,e.tools||[],e.mcpServers||[],e.responseLength,at(t,e.reasoning_effort))}getProviderName(){return"gemini"}getSupportedModels(){return[...Ut]}getDefaultModel(){return j}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return st.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function rs(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var Ge=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja","en"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this.initialPrompts=(e.initialPrompts??[]).map(t=>({...t})),this._responseLength=e.responseLength}getModel(){return le}getVisionModel(){return le}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 r=await this.generateResponse(e);return o(r),{blocks:[{type:"text",text:r}],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=rs();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 148+ on a supported desktop device is required for web pages.");let o=this.getModelOptions(),i=await t.availability(o);if(i!=="available"&&i!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${i}". Expected "available" or "downloadable".`);let s=e.filter(u=>u.role==="system").map(u=>u.content).join(`
15
+ `),a=e.filter(u=>u.role==="user"||u.role==="assistant").slice(-20),p=this.findLastUserMessageIndex(a);if(p===-1)throw new Error("No user message found in the provided messages.");let c=a[p],d=await this.createSession(t,s,a.slice(0,p),o);try{return await d.prompt(c.content)}finally{try{d.destroy()}catch{}}}async createSession(e,t,o,i){let r=this.buildInitialPrompts(t,o),s={...i,...r.length>0?{initialPrompts:r}:{}};return e.create(s)}getModelOptions(){return{expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]}}buildInitialPrompts(e,t){let o=this.initialPrompts.filter(s=>s.role==="system").map(s=>s.content),i=this.buildSystemPrompt([e,...o].filter(Boolean).join(`
16
16
 
17
- `)),r=[];return i&&r.push({role:"system",content:i}),r.push(...this.initialPrompts.filter(s=>s.role!=="system").map(s=>({...s})),...t.filter(s=>s.role==="user"||s.role==="assistant").map(({role:s,content:l})=>({role:s,content:l}))),r}findLastUserMessageIndex(e){for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="user")return t;return-1}buildSystemPrompt(e){let t=[];e&&t.push(e);let o=this.getResponseLengthInstruction();return o&&t.push(o),t.join(`
17
+ `)),r=[];return i&&r.push({role:"system",content:i}),r.push(...this.initialPrompts.filter(s=>s.role!=="system").map(s=>({...s})),...t.filter(s=>s.role==="user"||s.role==="assistant").map(({role:s,content:a})=>({role:s,content:a}))),r}findLastUserMessageIndex(e){for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="user")return t;return-1}buildSystemPrompt(e){let t=[];e&&t.push(e);let o=this.getResponseLengthInstruction();return o&&t.push(o),t.join(`
18
18
 
19
- `)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Vo[this._responseLength];if(e)switch(this._responseLength){case S.VERY_SHORT:return`Reply in no more than one concise sentence. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Stay within approximately ${e} tokens.`;case S.SHORT:return`Reply in no more than two concise sentences. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Use natural conversational language. Stay within approximately ${e} tokens.`;case S.MEDIUM:return`Reply in no more than three concise sentences. Answer directly and include only the context needed to understand the answer. Do not use a preamble, summary, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case S.LONG:return`Reply in no more than five sentences. Explain the important details clearly, but avoid unnecessary preambles, repetition, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case S.VERY_LONG:return`Reply in no more than ten sentences. Give a thorough but focused answer. Use short plain-text paragraphs when helpful, and avoid unnecessary repetition, bullet points, or Markdown. Stay within approximately ${e} tokens.`;case S.DEEP:return`Give a detailed response and organize it in the way that best fits the request. No sentence-count limit applies at this level. Stay within approximately ${e} tokens.`}}};var we=class{createChatService(e){return new Ne({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[se]}getDefaultModel(){return se}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var ke=class{constructor(e,t=G,o=G,i,r=ve,s,l,p,c){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=l,this.thinking=p;let d=z(t);if(c!==void 0&&!d.includes(c))throw new Error(`Model ${t} does not support reasoning_effort: ${c}.`);this.reasoningEffort=c??Te(t),this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:()=>this.chatOnce(e,!0,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(!Ce(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:()=>this.visionChatOnce(e,!0,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 r=await this.callKimi(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!Ce(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callKimi(e,this.visionModel,t,i);return this.parseResponse(r,t,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 r=this.buildRequestBody(e,t,o,i);return await E.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:T(this.responseLength);s!==void 0&&(ie(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),ie(t)&&(r.reasoning_effort=this.reasoningEffort??Te(t));let l=this.resolveEffectiveThinking(t);l&&(this.isSelfHostedEndpoint()?l.type==="disabled"&&(r.chat_template_kwargs={thinking:!1}):r.thinking=l);let p=this.buildToolsDefinition();return p.length>0&&(r.tools=p,r.tool_choice="auto"),r}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(ve)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(ie(e)){if(this.thinking)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Mt(e)){if(this.thinking?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return this.thinking??{type:"enabled"}}return this.tools.length>0?{type:"disabled"}:this.thinking??{type:"enabled"}}buildToolsDefinition(){return D(this.tools,"chat-completions")}async parseStream(e,t){return x(e,t,{preserveAssistantMessage:!0,onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e,{preserveAssistantMessage:!0})}};var Ge=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),i=C({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:p=>this.supportsVisionForModel(p),validate:"explicit"}),r=e.tools,s=this.resolveThinking(o,r,e.thinking),l=this.resolveReasoningEffort(o,e.reasoning_effort);return new ke(e.apiKey,o,i,r,t,e.responseLength,e.responseFormat,s,l)}getProviderName(){return"kimi"}getSupportedModels(){return[Se,Et,Ot,G,wo]}getDefaultModel(){return G}getDefaultVisionModel(){return G}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Ce(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 ve}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,o){if(ie(e)){if(o)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Mt(e)){if(o?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return o??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:o??this.defaultThinking}resolveReasoningEffort(e,t){let o=z(e);if(o.length===0){if(t!==void 0)throw new Error(`Model ${e} does not support the reasoning_effort option.`);return}let i=t??Te(e)??o[0];if(!o.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${o.join(", ")}.`);return i}};var Ve=class extends L{constructor(e,t=V,o=t,i,r=Ct,s,l){super(e,t,o,i,r,[],s,void 0,l,!1,"mistral",!1)}};var Fe=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=Tt(t)?e.reasoning_effort:void 0;return new Ve(e.apiKey,t,o,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...wn]}getDefaultModel(){return V}getDefaultVisionModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Gn(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 Ct}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ue=class{createChatService(e){this.validateRequiredOptions(e);let t=[e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1];return e.responseFormat!==void 0&&t.push(e.responseFormat),new L(...t)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let 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 Ke=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=C({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:d=>this.supportsVisionForModel(d),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),l=!1;r.length>0||qo(s)?l=!0:te(s)&&(l=(t.gpt5EndpointPreference||"chat")==="responses");let p=t.endpoint||(l?A:j),c=[t.apiKey,s,o,i,p,r,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName()];return t.responseFormat!==void 0&&c.push(!0,t.responseFormat),new L(...c)}getProviderName(){return"openai"}getSupportedModels(){return[X,le,pe,ce,J,Z,U,K,H,B,Y,Q,W,It,Dt,At,ee,bt,Wo,$o,"o1"]}getDefaultModel(){return X}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Qe.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!te(t))return e;let o={...e};if(e.gpt5Preset){let i=Kn[e.gpt5Preset];o.reasoning_effort=i.reasoning_effort,o.verbosity=i.verbosity}else e.reasoning_effort||(o.reasoning_effort=ot(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!et(e)||t==="minimal"&&!tt(e)?t==="minimal"&&et(e)?"none":t==="none"&&tt(e)?"minimal":wt(e)?"low":"medium":t==="low"&&!wt(e)?"medium":t==="xhigh"&&!Nt(e)?"high":t==="max"&&!jo(e)?Nt(e)?"xhigh":"high":t}};var xt=n=>[mt,ue].includes(n.trim()),Qr=n=>[w,he].includes(n.trim()),zn=(n,e)=>{if(xt(n)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},$i=n=>n.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),He=class{constructor(e,t=w,o=w,i,r=dt,s,l,p,c,d,u){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.appName=l,this.appUrl=p,this.reasoning_effort=c,this.includeReasoning=d,this.reasoningMaxTokens=u,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!oe(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=mn){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 M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.model,!0);return this.handleStream(i,t,this.model)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!ge(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(i,t,this.visionModel)},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 r=await this.callOpenRouter(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!ge(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}async callOpenRouter(e,t,o=!1,i){let r=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 E.post(this.endpoint,r,s)}buildRequestBody(e,t,o,i){let r={model:t,messages:e,stream:o},s=i!==void 0?i:T(this.responseLength),l=Qr(t)||xt(t)&&i===void 0;s&&l?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(r.max_tokens=s);let p=Po(t),c=gn(t,this.reasoning_effort);if(c!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||p){if(r.reasoning={},c){let d=c==="minimal"?"low":c;r.reasoning.effort=d}else p&&(r.reasoning.effort=p);(c==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),this.reasoningMaxTokens&&(r.reasoning.max_tokens=this.reasoningMaxTokens)}else r.reasoning={exclude:!0};return this.tools.length>0&&(r.tools=D(this.tools,"chat-completions"),r.tool_choice="auto"),r}async handleStream(e,t,o){let i=await F(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:xt(o)});return zn(o,i.trim().length>0),i}async parseStream(e,t,o){let i=await x(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:xt(o)});return zn(o,$i(i)),i}parseOneShot(e,t){let o=I(e,{throwOnApiError:xt(t)});return zn(t,$i(o)),o}};var Be=class{createChatService(e){let t=C({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,r=e.appUrl;return new He(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,i,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[mt,ue,an,w,So,qt,jt,Xt,Jt,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,ln,mo,go,fo,_o,Eo,Oo,Mo,vo,he,pn,cn,Co,To,me,de,zt,Bt,Wt,$t,un,hn]}getDefaultModel(){return w}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return ge(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return dn}isModelFree(e){return oe(e)}};var We=class extends L{constructor(e,t=Pe,o=t,i,r=Pt,s,l){super(e,t,o,i,r,[],s,void 0,l,!1,"plamo",!1)}};var $e=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new We(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Fn]}getDefaultModel(){return Pe}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("plamo provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Pt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var ze=class extends L{constructor(e,t=Le,o=t,i,r=Lt,s){super(e,t,o,i,r,[],s,void 0,void 0,!1,"sakana",!1)}};var qe=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new ze(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"sakana"}getSupportedModels(){return[...Vn]}getDefaultModel(){return Le}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("sakana provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Lt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var je=class{constructor(e,t=k,o=k,i,r=ft,s,l){this.provider="xai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.visionModel=o,this.reasoningEffort=l}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({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(!Me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({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 r=await this.callXAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!Me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callXAI(e,this.visionModel,t,i);return this.parseResponse(r,t,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 r=this.buildRequestBody(e,t,o,i);return await E.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:T(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&bo(t)&&(r.reasoning_effort=_t(t,this.reasoningEffort));let l=this.buildToolsDefinition();return l.length>0&&(r.tools=l,r.tool_choice="auto"),r}buildToolsDefinition(){return D(this.tools,"chat-completions")}async handleStream(e,t){return F(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Xe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new je(e.apiKey,t,o,i,e.endpoint||ft,e.responseLength,_t(t,e.reasoning_effort??No(t)))}getProviderName(){return"xai"}getSupportedModels(){return[Ee,Oe,Io,Do,Ao,k]}getDefaultModel(){return k}getDefaultVisionModel(){return k}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Me(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Je=class{constructor(e,t=fe,o=ne,i,r=gt,s,l,p){this.provider="zai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=l,this.thinking=p??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let 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(!_e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({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 r=await this.callZAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!_e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callZAI(e,this.visionModel,t,i);return this.parseResponse(r,t,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 r=this.buildRequestBody(e,t,o,i);return await E.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:T(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking);let l=this.buildToolsDefinition();return l.length>0&&(r.tools=l,r.tool_choice="auto",o&&Cn(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return D(this.tools,"chat-completions")}async handleStream(e,t){return F(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Ze=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=C({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=e.thinking??{type:"disabled"};return new Je(e.apiKey,t,o,i,e.endpoint||gt,e.responseLength,e.responseFormat,r)}getProviderName(){return"zai"}getSupportedModels(){return[fe,fn,_n,En,Ro,On,Mn,vn,Sn,yo,xo,ne]}getDefaultModel(){return fe}getDefaultVisionModel(){return ne}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return _e(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var zi=[new Ke,new Ue,new be,new we,new xe,new Be,new Ze,new Xe,new Ge,new De,new Fe,new qe,new $e];var es=new Set(["openai","openai-compatible","openrouter","gemini","claude","zai","xai","kimi","deepseek","mistral","sakana","plamo"]),ts=new Set(["openai","gemini","claude"]),os=new Set(["openai","openai-compatible","zai","kimi"]),ns={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high","xhigh","max"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high"],deepseek:["none","low","high","max"]},Ye=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 getProviderCapabilities(e,t){let o=this.providers.get(e);if(!o)return;let i=t?this.getVisionSupportLevelForModel(e,t):o.getVisionSupportLevel();return{provider:e,models:o.getSupportedModels(),defaultModel:typeof o.getDefaultModel=="function"?o.getDefaultModel():void 0,text:!0,streaming:!0,vision:i,tools:es.has(e),mcp:ts.has(e),jsonMode:os.has(e),responseLength:!0,reasoningEffort:e==="claude"&&t?[...N(t)]:e==="kimi"&&t?[...z(t)]:e==="deepseek"&&t?[...St(t)]:e==="openrouter"&&t?[...Lo(t)]:ns[e]??[]}}static getAllProviderCapabilities(){return this.getAvailableProviders().map(e=>this.getProviderCapabilities(e)).filter(e=>e!==void 0)}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Ye.providers=new Map;zi.forEach(n=>Ye.registerProvider(n));function qi(){E.setFetch(async(n,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 r={method:t,headers:i,muteHttpExceptions:!0},s=e.body;typeof s=="string"?r.payload=s:s!=null&&(i["Content-Type"]||(i["Content-Type"]="application/json"),r.payload=JSON.stringify(s));let l=UrlFetchApp.fetch(n,r),p=l.getResponseCode(),c=l.getContentText();return{ok:p>=200&&p<300,status:p,statusText:String(p),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return er(is);})();
19
+ `)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=Ho[this._responseLength];if(e)switch(this._responseLength){case O.VERY_SHORT:return`Reply in no more than one concise sentence. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Stay within approximately ${e} tokens.`;case O.SHORT:return`Reply in no more than two concise sentences. Do not use a preamble, summary, bullet points, or Markdown. Keep the reaction and answer short enough to read in one breath. Use natural conversational language. Stay within approximately ${e} tokens.`;case O.MEDIUM:return`Reply in no more than three concise sentences. Answer directly and include only the context needed to understand the answer. Do not use a preamble, summary, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case O.LONG:return`Reply in no more than five sentences. Explain the important details clearly, but avoid unnecessary preambles, repetition, bullet points, or Markdown. Use natural conversational language. Stay within approximately ${e} tokens.`;case O.VERY_LONG:return`Reply in no more than ten sentences. Give a thorough but focused answer. Use short plain-text paragraphs when helpful, and avoid unnecessary repetition, bullet points, or Markdown. Stay within approximately ${e} tokens.`;case O.DEEP:return`Give a detailed response and organize it in the way that best fits the request. No sentence-count limit applies at this level. Stay within approximately ${e} tokens.`}}};var Ve=class{createChatService(e){return new Ge({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,initialPrompts:e.initialPrompts,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[le]}getDefaultModel(){return le}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var Fe=class{constructor(e,t=F,o=F,i,r=Te,s,a,p,c){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=a,this.thinking=p;let d=q(t);if(c!==void 0&&!d.includes(c))throw new Error(`Model ${t} does not support reasoning_effort: ${c}.`);this.reasoningEffort=c??Pe(t),this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({hasTools:this.tools.length>0,runWithoutTools:()=>this.chatOnce(e,!0,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(!ye(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({hasTools:this.tools.length>0,runWithoutTools:()=>this.visionChatOnce(e,!0,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 r=await this.callKimi(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!ye(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callKimi(e,this.visionModel,t,i);return this.parseResponse(r,t,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 r=this.buildRequestBody(e,t,o,i);return await _.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:L(this.responseLength);s!==void 0&&(se(t)?r.max_completion_tokens=s:r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),se(t)&&(r.reasoning_effort=this.reasoningEffort??Pe(t));let a=this.resolveEffectiveThinking(t);a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(r.chat_template_kwargs={thinking:!1}):r.thinking=a);let p=this.buildToolsDefinition();return p.length>0&&(r.tools=p,r.tool_choice="auto"),r}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(Te)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveEffectiveThinking(e){if(se(e)){if(this.thinking)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Tt(e)){if(this.thinking?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return this.thinking??{type:"enabled"}}return this.tools.length>0?{type:"disabled"}:this.thinking??{type:"enabled"}}buildToolsDefinition(){return D(this.tools,"chat-completions")}async parseStream(e,t){return x(e,t,{preserveAssistantMessage:!0,onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e,{preserveAssistantMessage:!0})}};var Ue=class{constructor(){this.defaultThinking={type:"enabled"}}createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),i=T({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:p=>this.supportsVisionForModel(p),validate:"explicit"}),r=e.tools,s=this.resolveThinking(o,r,e.thinking),a=this.resolveReasoningEffort(o,e.reasoning_effort);return new Fe(e.apiKey,o,i,r,t,e.responseLength,e.responseFormat,s,a)}getProviderName(){return"kimi"}getSupportedModels(){return[Le,St,Ct,F,Fo]}getDefaultModel(){return F}getDefaultVisionModel(){return F}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ye(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 Te}normalizeEndpoint(e){return e.replace(/\/+$/,"")}resolveThinking(e,t,o){if(se(e)){if(o)throw new Error(`Model ${e} uses reasoning_effort and does not support the K2.x thinking option.`);return}if(Tt(e)){if(o?.type==="disabled")throw new Error(`Model ${e} requires thinking mode and does not support thinking: disabled.`);return o??this.defaultThinking}return t&&t.length>0?{type:"disabled"}:o??this.defaultThinking}resolveReasoningEffort(e,t){let o=q(e);if(o.length===0){if(t!==void 0)throw new Error(`Model ${e} does not support the reasoning_effort option.`);return}let i=t??Pe(e)??o[0];if(!o.includes(i))throw new Error(`Model ${e} supports reasoning_effort values: ${o.join(", ")}.`);return i}};var Ke=class extends y{constructor(e,t=U,o=t,i,r=Pt,s,a){super(e,t,o,i,r,[],s,void 0,a,!1,"mistral",!1)}};var He=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=Rt(t)?e.reasoning_effort:void 0;return new Ke(e.apiKey,t,o,i,this.resolveEndpoint(e),e.responseLength,r)}getProviderName(){return"mistral"}getSupportedModels(){return[...Vn]}getDefaultModel(){return U}getDefaultVisionModel(){return U}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Un(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 Pt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Be=class{createChatService(e){this.validateRequiredOptions(e);let t=[e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1];return e.responseFormat!==void 0&&t.push(e.responseFormat),new y(...t)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let 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 We=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=T({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:d=>this.supportsVisionForModel(d),validate:"resolved"}),i=t.tools,r=t.mcpServers??[],s=t.model||this.getDefaultModel(),a=!1;r.length>0||Zo(s)?a=!0:ne(s)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let p=t.endpoint||(a?A:J),c=[t.apiKey,s,o,i,p,r,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName()];return t.responseFormat!==void 0&&c.push(!0,t.responseFormat),new y(...c)}getProviderName(){return"openai"}getSupportedModels(){return[Z,ce,ue,he,Y,Q,H,B,W,$,ee,te,z,Nt,wt,kt,oe,Gt,qo,Xo,"o1"]}getDefaultModel(){return Z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return ot.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!ne(t))return e;let o={...e};if(e.gpt5Preset){let i=Wn[e.gpt5Preset];o.reasoning_effort=i.reasoning_effort,o.verbosity=i.verbosity}else e.reasoning_effort||(o.reasoning_effort=rt(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!nt(e)||t==="minimal"&&!it(e)?t==="minimal"&&nt(e)?"none":t==="none"&&it(e)?"minimal":Ft(e)?"low":"medium":t==="low"&&!Ft(e)?"medium":t==="xhigh"&&!Vt(e)?"high":t==="max"&&!Yo(e)?Vt(e)?"xhigh":"high":t}};var bt=n=>[_t,de].includes(n.trim()),ss=n=>[G,me].includes(n.trim()),Xn=(n,e)=>{if(bt(n)&&!e)throw new Error("OpenRouter Auto Router returned no visible content. Please retry.")},Zi=n=>n.blocks.some(e=>e.type!=="text"||e.text.trim().length>0),$e=class{constructor(e,t=G,o=G,i,r=ft,s,a,p,c,d,u){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.appName=a,this.appUrl=p,this.reasoning_effort=c,this.includeReasoning=d,this.reasoningMaxTokens=u,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!ie(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=En){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 M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.model,!0);return this.handleStream(i,t,this.model)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!_e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await M({hasTools:this.tools.length>0,runWithoutTools:async()=>{let i=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(i,t,this.visionModel)},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 r=await this.callOpenRouter(e,this.model,t,i);return t?this.parseStream(r,o,this.model):this.parseOneShot(await r.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!_e(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let r=await this.callOpenRouter(e,this.visionModel,t,i);return t?this.parseStream(r,o,this.visionModel):this.parseOneShot(await r.json(),this.visionModel)}async callOpenRouter(e,t,o=!1,i){let r=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,r,s)}buildRequestBody(e,t,o,i){let r={model:t,messages:e,stream:o},s=i!==void 0?i:L(this.responseLength),a=ss(t)||bt(t)&&i===void 0;s&&a?console.warn(`OpenRouter: Token limits are disabled for ${t} because this model can return empty content when a token limit is set.`):s&&(r.max_tokens=s);let p=Io(t),c=Mn(t,this.reasoning_effort);if(c!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens||p){if(r.reasoning={},c){let d=c==="minimal"?"low":c;r.reasoning.effort=d}else p&&(r.reasoning.effort=p);(c==="none"||this.includeReasoning!==!0)&&(r.reasoning.exclude=!0),this.reasoningMaxTokens&&(r.reasoning.max_tokens=this.reasoningMaxTokens)}else r.reasoning={exclude:!0};return this.tools.length>0&&(r.tools=D(this.tools,"chat-completions"),r.tool_choice="auto"),r}async handleStream(e,t,o){let i=await K(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:bt(o)});return Xn(o,i.trim().length>0),i}async parseStream(e,t,o){let i=await x(e,t,{onJsonError:r=>console.debug("Failed to parse SSE data:",r),throwOnApiError:bt(o)});return Xn(o,Zi(i)),i}parseOneShot(e,t){let o=I(e,{throwOnApiError:bt(t)});return Xn(t,Zi(o)),o}};var ze=class{createChatService(e){let t=T({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),o=e.tools,i=e.appName,r=e.appUrl;return new $e(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,i,r,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[_t,de,un,G,yo,Zt,Yt,Qt,eo,to,oo,no,io,ro,so,ao,lo,po,co,uo,ho,mo,go,fo,_o,hn,Eo,Mo,Oo,vo,So,Co,To,Lo,me,dn,mn,Po,Ro,fe,ge,Jt,jt,qt,Xt,gn,fn]}getDefaultModel(){return G}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return _e(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return _n}isModelFree(e){return ie(e)}};var je=class extends y{constructor(e,t=xe,o=t,i,r=It,s,a){super(e,t,o,i,r,[],s,void 0,a,!1,"plamo",!1)}};var qe=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new je(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength,e.reasoning_effort)}getProviderName(){return"plamo"}getSupportedModels(){return[...Hn]}getDefaultModel(){return xe}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("plamo provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return It}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Xe=class extends y{constructor(e,t=Re,o=t,i,r=xt,s){super(e,t,o,i,r,[],s,void 0,void 0,!1,"sakana",!1)}};var Je=class{createChatService(e){this.validateRequiredOptions(e);let t=e.model||this.getDefaultModel(),o=e.tools;return new Xe(e.apiKey,t,e.visionModel??t,o,this.resolveEndpoint(e),e.responseLength)}getProviderName(){return"sakana"}getSupportedModels(){return[...Kn]}getDefaultModel(){return Re}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}supportsVisionForModel(e){return!1}getVisionSupportLevelForModel(e){return"unsupported"}validateRequiredOptions(e){if(!e.apiKey?.trim())throw new Error("sakana provider requires apiKey.")}resolveEndpoint(e){if(e.endpoint)return this.normalizeUrl(e.endpoint);if(e.baseUrl){let t=this.normalizeUrl(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return xt}normalizeUrl(e){return e.trim().replace(/\/+$/,"")}};var Ze=class{constructor(e,t=V,o=V,i,r=Mt,s,a){this.provider="xai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.visionModel=o,this.reasoningEffort=a}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({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(!Se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({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 r=await this.callXAI(e,this.model,t,i);return this.parseResponse(r,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 r=await this.callXAI(e,this.visionModel,t,i);return this.parseResponse(r,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 r=this.buildRequestBody(e,t,o,i);return await _.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:L(this.responseLength);s!==void 0&&(r.max_tokens=s),this.reasoningEffort&&Go(t)&&(r.reasoning_effort=vt(t,this.reasoningEffort));let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto"),r}buildToolsDefinition(){return D(this.tools,"chat-completions")}async handleStream(e,t){return K(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var Ye=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:r=>this.supportsVisionForModel(r),validate:"explicit"}),i=e.tools;return new Ze(e.apiKey,t,o,i,e.endpoint||Mt,e.responseLength,vt(t,e.reasoning_effort??Vo(t)))}getProviderName(){return"xai"}getSupportedModels(){return[Oe,ve,Ot,No,wo,ko,V]}getDefaultModel(){return V}getDefaultVisionModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Se(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Qe=class{constructor(e,t=Ee,o=re,i,r=Et,s,a,p){this.provider="zai";this.apiKey=e,this.model=t,this.tools=i||[],this.endpoint=r,this.responseLength=s,this.responseFormat=a,this.thinking=p??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await M({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(!Me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await M({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 r=await this.callZAI(e,this.model,t,i);return this.parseResponse(r,t,o)}async visionChatOnce(e,t=!1,o=()=>{},i){if(!Me(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let r=await this.callZAI(e,this.visionModel,t,i);return this.parseResponse(r,t,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 r=this.buildRequestBody(e,t,o,i);return await _.post(this.endpoint,r,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,i){let r={model:t,stream:o,messages:e},s=i!==void 0?i:L(this.responseLength);s!==void 0&&(r.max_tokens=s),this.responseFormat&&(r.response_format=this.responseFormat),this.thinking&&(r.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(r.tools=a,r.tool_choice="auto",o&&Pn(t)&&(r.tool_stream=!0)),r}buildToolsDefinition(){return D(this.tools,"chat-completions")}async handleStream(e,t){return K(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var et=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=T({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:s=>this.supportsVisionForModel(s),validate:"explicit"}),i=e.tools,r=e.thinking??{type:"disabled"};return new Qe(e.apiKey,t,o,i,e.endpoint||Et,e.responseLength,e.responseFormat,r)}getProviderName(){return"zai"}getSupportedModels(){return[Ee,On,vn,Sn,Do,Cn,Tn,Ln,yn,Ao,bo,re]}getDefaultModel(){return Ee}getDefaultVisionModel(){return re}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Me(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Yi=[new We,new Be,new ke,new Ve,new Ae,new ze,new et,new Ye,new Ue,new Ne,new He,new Je,new qe];var as=new Set(["claude","claude-agent-sdk","codex-sdk","copilot-sdk","deepseek","gemini","gemini-nano","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),ls=new Set(["claude","deepseek","gemini","kimi","mistral","openai","openai-compatible","openrouter","plamo","sakana","xai","zai"]),ps=new Set(["codex-sdk"]);function Jn(n){if(as.has(n))return{text:!0,streaming:!ps.has(n),tools:ls.has(n)}}function cs(n){let e=n.provider==="claude",t=n.messages.filter(r=>!Qi(e,r)),o=n.completion.blocks.filter(r=>r.type==="tool_use"),i=n.completion.assistant_message??us(e,o);return Qi(e,i)||t.push({...i}),t.push(...hs(e,n.toolResults)),t}function Qi(n,e){if(!n||e.role!=="assistant")return!1;let t=e.content;return Array.isArray(t)&&t.length===0}function us(n,e){return n?{role:"assistant",content:e.map(t=>({type:"tool_use",id:t.id,name:t.name,input:t.input??{}}))}:{role:"assistant",content:[],tool_calls:e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.input??{})}}))}}function hs(n,e){return n?e.map(t=>({role:"user",content:[{type:"tool_result",tool_use_id:t.tool_use_id,content:t.content}]})):e.map(t=>({role:"tool",tool_call_id:t.tool_use_id,content:t.content}))}var ds=new Set(["openai","gemini","claude"]),ms=new Set(["openai","openai-compatible","zai","kimi"]),gs={openai:["none","minimal","low","medium","high","xhigh","max"],claude:["low","medium","high","xhigh","max"],gemini:["minimal","low","medium","high"],openrouter:["none","minimal","low","medium","high","xhigh","max"],kimi:["low","high","max"],mistral:["low","medium","high"],plamo:["none","medium"],xai:["none","low","medium","high","xhigh"],deepseek:["none","low","high","max"]},tt=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 getProviderCapabilities(e,t){let o=this.providers.get(e);if(!o)return;let i=t?this.getVisionSupportLevelForModel(e,t):o.getVisionSupportLevel(),r=Jn(e);return{provider:e,models:o.getSupportedModels(),defaultModel:typeof o.getDefaultModel=="function"?o.getDefaultModel():void 0,text:!0,streaming:r?.streaming??!0,vision:i,tools:r?.tools??!1,mcp:ds.has(e),jsonMode:ms.has(e),responseLength:!0,reasoningEffort:e==="claude"&&t?[...k(t)]:e==="kimi"&&t?[...q(t)]:e==="deepseek"&&t?[...yt(t)]:e==="openrouter"&&t?[...xo(t)]:e==="xai"&&t?[...Ce(t)]:gs[e]??[]}}static getAllProviderCapabilities(){return this.getAvailableProviders().map(e=>this.getProviderCapabilities(e)).filter(e=>e!==void 0)}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};tt.providers=new Map;Yi.forEach(n=>tt.registerProvider(n));function er(){_.setFetch(async(n,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 r={method:t,headers:i,muteHttpExceptions:!0},s=e.body;typeof s=="string"?r.payload=s:s!=null&&(i["Content-Type"]||(i["Content-Type"]="application/json"),r.payload=JSON.stringify(s));let a=UrlFetchApp.fetch(n,r),p=a.getResponseCode(),c=a.getContentText();return{ok:p>=200&&p<300,status:p,statusText:String(p),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return ar(fs);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aituber-onair/chat",
3
- "version": "0.50.0",
3
+ "version": "0.51.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",
@@ -17,6 +17,11 @@
17
17
  "import": "./dist/esm/agent.js",
18
18
  "require": "./dist/cjs/agent.js"
19
19
  },
20
+ "./backend": {
21
+ "types": "./dist/cjs/backend.d.ts",
22
+ "import": "./dist/cjs/backend.js",
23
+ "require": "./dist/cjs/backend.js"
24
+ },
20
25
  "./dist/cjs/*": "./dist/cjs/*",
21
26
  "./dist/esm/*": "./dist/esm/*",
22
27
  "./umd": "./dist/umd/aituber-onair-chat.js"