@wengine-ai/llms 2.3.2427 → 2.3.2428
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/cjs/server.cjs +2 -2
- package/dist/cjs/server.cjs.map +2 -2
- package/dist/esm/server.mjs +2 -2
- package/dist/esm/server.mjs.map +2 -2
- package/package.json +2 -2
package/dist/esm/server.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "node:module"; import { fileURL
|
|
|
2
2
|
var _o=Object.defineProperty;var il=Object.getOwnPropertyDescriptor;var al=Object.getOwnPropertyNames;var cl=Object.prototype.hasOwnProperty;var rt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var bo=(n,e)=>{for(var t in e)_o(n,t,{get:e[t],enumerable:!0})},ll=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of al(e))!cl.call(n,r)&&r!==t&&_o(n,r,{get:()=>e[r],enumerable:!(o=il(e,r))||o.enumerable});return n};var ul=n=>ll(_o({},"__esModule",{value:!0}),n);import{Agent as dl,ProxyAgent as pl}from"undici";function ml(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(fl.test(e))return{ok:!0};try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:`Unsupported proxy protocol: ${t.protocol}. Only http:// and https:// are allowed.`}:{ok:!0}}catch{return{ok:!1,error:`Invalid proxy URL: ${e}`}}}function Rs(n){let e=[];for(let t of[...Cs,Ss]){let o=n[t];if(o==null)continue;let r=ml(o);r.ok||e.push({key:t,error:r.error})}return e}function To(){return ko||(ko=new dl({connect:{timeout:15e3}})),ko}function ws(n){let e=n.get(Ss);return(typeof e=="string"?e.trim():"")||void 0}function Ps(n){return n?K(n):To()}function Ht(n){for(let e of Cs){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Es(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=Ht(n);if(t)return Es(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function K(n){let e=gl(n),t=jt.get(e);if(t)return t;let o=new pl(e);return jt.set(e,o),o}async function vo(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function gl(n){let e=n.trim();if(!e)throw new TypeError("Proxy URL must not be empty");let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new TypeError(`Unsupported proxy protocol: ${t.protocol}`);return t.toString()}var Cs,Ss,fl,jt,ko,q=w(()=>{"use strict";Cs=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Ss="SUBSCRIPTION_PROXY_URL",fl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as hl,existsSync as As}from"fs";import{join as Os}from"path";import{config as yl}from"dotenv";import _l from"json5";var Ie,xo=w(()=>{"use strict";q();Ie=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Os(process.cwd(),this.options.jsonPath);if(As(e))try{let t=hl(e,"utf-8"),o=_l.parse(t);this.config={...this.config,...o},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Os(process.cwd(),this.options.envPath);if(As(e))try{let t=yl({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return Ht(this)}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}}});function B(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Is(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var zt=w(()=>{"use strict"});function So(n){Co=n}function Bt(){return Co}function Jt(n){return Co||n.get("DEBUG_LOG")===!0}function Ns(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Me:{maxBodyLength:e.maxBodyLength??Me.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Me.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();bl.has(r)||kl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Kt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function $s(n,e,t){let o=typeof t.body=="string"?t.body:JSON.stringify(t.body);n.info({debug_log:!0,reqId:e,phase:"provider_request",url:t.url,headers:Wt(t.headers),body:Kt(o,Me.maxBodyLength)})}function Fs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Wt(t.headers),...t.body!==void 0?{body:Kt(t.body,Me.maxBodyLength)}:{}})}function Ms(n,e,t,o){let r=Tl(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Me.maxBodyLength)})}function Tl(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Kt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Ls(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Us(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:c}=await r.read();if(i)break;a+=c;let l=a.split(`
|
|
3
3
|
|
|
4
4
|
`);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?Ms(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Ms(e,t,s,a.trim()),s++),Ls(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Ls(e,t,s)}finally{r.releaseLock()}})()}var bl,kl,Me,Co,st=w(()=>{"use strict";bl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),kl=/token|secret|credential|passwd|password/i,Me={maxBodyLength:4096,maxStreamChunks:100},Co=!1});function Ds(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([l,u])=>{u&&s.set(l,u)});let a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let l=new AbortController,u=()=>l.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=l.signal}else a=i;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?c.dispatcher=t.dispatcher:t.httpsProxy&&(c.dispatcher=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:vl(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function vl(n){if(!(typeof n!="string"||!n.trim()))try{let e=new URL(n);return e.username||e.password?(e.username="",e.password="",`${e.toString()} (credentials redacted)`):e.toString()}catch{return"[invalid proxy URL]"}}var js=w(()=>{q();st()});function Cl(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Hs(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Ro(n){if(Hs(n))return"pending";let e=!1,t=!1;for(let o of n.split(`
|
|
5
|
-
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(xl.some(s=>r.includes(s))){e=!0;break}Sl.some(s=>r.includes(s))&&(t=!0)}}return e||Cl(n)?"content":t?"empty":"pending"}async function zs(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=c-Date.now(),p=Symbol("timeout"),d,f=o.read(),h=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),h===p)return l(Ro(a)==="content"?"content":"pending",Gt(o,f));if(h.done){a+=r.decode();let m=Ro(a);return l(m==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let g=Ro(a);if(g==="content")return l("content",Gt(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(Hs(a)||i>=e)return l("pending",Gt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Gt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Bs(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var xl,Sl,Js=w(()=>{"use strict";xl=["content_block_start","content_block_delta","content_block_stop"];Sl=["message_stop","response.completed","response.incomplete","[DONE]"]});function Rl(n,e){return`${n.name}|${e?.name??""}`}function wo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function Le(n,e,t){let o=wo(n),r=Rl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Po(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(Le(n,e,o).terminalError=t,!0)}var Ws=w(()=>{"use strict"});var Eo=w(()=>{"use strict"});import wl from"fastify";function Ks(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var it,Pl,Oo,Vt=w(()=>{"use strict";Eo();it=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let g of this.plugins.values()){for(let m of s.runtimes.keys())if(g.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(g.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([m,y])=>{if(g.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:g,name:m,value:g.preparePluginTransformer(y)}})),h=[];try{for(let g of f)h.push(g),g.service.registerTransformer(g.name,g.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(g){for(let m of h)m.service.removeTransformer(m.name);throw a="aborted",g}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:d??p}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=wl({logger:!1});try{for(let i of e){let c=i(s);c!==s&&await c}for(let i of this.plugins.values())for(let c of i.preparedRoutes)a.route(c);for(let i of r){let c=Array.isArray(i.method)?i.method:[i.method];for(let l of c)if(t.hasRoute({method:l,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${l} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},Pl=new it,Oo=()=>Pl});function Gs(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function Te(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?El(r):{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(i)}catch{}let c=Ks(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function El(n){let e=[n?.causeCode,n?.causeDetail].filter(Boolean).join(" ");return{code:"plugin_network_error",message:e?`Provider plugin network failure (${e}).`:n?.errorName?`Provider plugin network failure (${n.errorName}).`:"Provider plugin network failure.",httpStatus:502,retryable:!0}}var Vs=w(()=>{"use strict";Vt()});var Qt,Io=w(()=>{Qt="2.3.2427"});var Qs={};bo(Qs,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>Il});function Ne(n){return ve||(ve=new Mo,n&&ve.configure(n)),ve}function Il(){ve&&(ve.clearAll(),ve=null)}var Ol,Mo,ve,Yt=w(()=>{"use strict";se();Ol=600*1e3,Mo=class{promotions=new Map;enabled=!0;ttlMs=Ol;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!j().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},ve=null});import{existsSync as Zs,mkdirSync as Ml,readFileSync as Ll,writeFileSync as Nl}from"fs";import{join as qs}from"path";import{HOME_DIR as $l}from"@wengine-ai/claude-code-router-shared";function jl(n){try{if(!Zs($o))return;let e=JSON.parse(Ll($o,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Xs(n){try{let e=n.getAllStates();if(e.length===0)return;Zs(No)||Ml(No,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Nl($o,JSON.stringify(t,null,2),"utf-8")}catch{}}function Fo(){if(Ys)return;Ys=!0;let n=j();jl(n),Dl=setInterval(()=>Xs(n),6e4),process.on("exit",()=>Xs(n))}function j(n){return Lo||(Lo=new Xt(n)),Lo}var Fl,Ul,Xt,No,$o,Ys,Dl,Lo,se=w(()=>{"use strict";Fl=120,Ul={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ul,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),ul(Qs));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t,o=!1){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let s=this.getState(e,t);return s?s.status==="open"&&s.rateLimitUntil?!(Date.now()<s.rateLimitUntil):s.status==="open"&&o&&Date.now()-Math.max(s.lastFailureTime,s.lastProbeTime)>=this.config.probeIntervalMinutes*6e4?(s.status="half-open",s.successCount=0,s.lastProbeTime=Date.now(),!0):s.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}recordProbeAttempt(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.lastProbeTime=Date.now())}markParkedUntil(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s&&(!Number.isFinite(o)||o<=Date.now()||s.rateLimitUntil&&s.rateLimitUntil>=o||(s.rateLimitUntil=o))}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??Fl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},No=qs($l,"runtime"),$o=qs(No,"provider-health.json"),Ys=!1,Dl=null;Lo=null});import{existsSync as ri,mkdirSync as Hl,readFileSync as zl,writeFileSync as Bl}from"fs";import{join as si}from"path";import{HOME_DIR as Jl}from"@wengine-ai/claude-code-router-shared";function at(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let c=Object.keys(t).find(l=>l.toLowerCase()===i);return c?t[c]:null},r=Uo(o,Wl),s=Uo(o,Kl),a=Uo(o,Gl);(r||s||a)&&$e.set(n,{provider:n,remaining:ni(r),limit:ni(s),reset:Ql(a),capturedAt:Date.now()})}function Vl(n){return $e.get(n)}function Ho(){return Array.from($e.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Uo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ni(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Ql(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):t>1e9?Math.floor(t):Math.floor(Date.now()/1e3+t);let o=Date.parse(e);if(Number.isFinite(o))return Math.floor(o/1e3);let r=Yl(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Yl(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function Xl(){try{if(!ri(jo))return;let n=JSON.parse(zl(jo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;$e.set(t.provider,t)}}catch{}}function oi(){try{if($e.size===0)return;ri(Do)||Hl(Do,{recursive:!0}),Bl(jo,JSON.stringify(Array.from($e.values()),null,2),"utf-8")}catch{}}function ct(){ei||(ei=!0,Xl(),ti=setInterval(oi,6e4),ti.unref?.(),process.on("exit",oi))}var Do,jo,$e,ei,ti,Wl,Kl,Gl,xe=w(()=>{"use strict";Do=si(Jl,"runtime"),jo=si(Do,"rate-limit.json"),$e=new Map,ei=!1,ti=null,Wl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Kl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Gl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return zo||(zo=new Jo),zo}function Ko(){return Bo||(Bo=new Wo),Bo}function Zl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function ii(n){let e=Zl(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function ai(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Go(n){let e=n?.[qt];e&&en().release(e)}function ci(n,e){let t=ii(n),o=n?.[qt],r=t?Ko().get(t)!==void 0:!1;!o&&!r||(t&&Ko().bind(t,e),ai(n,e))}function ql(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function li(n,e,t){let o=ii(n),r=Ko(),s=en(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let c=r.get(o);if(c&&c!==e){let l=t.resolve(c);l?(i=l,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${l}`)):r.unbind(o)}else c&&(i=e)}if(!i){let c=s.count(e);if(c>=a){let l=ql(e,t.fallbackModels,t.resolve);l&&(i=l,t.log?.(`Concurrency priority: model ${e} has ${c} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${l}`))}i=i||e,o&&r.bind(o,i)}return ai(n,i),i}var Jo,Wo,zo,Bo,qt,tn=w(()=>{"use strict";Jo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},Wo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},zo=null,Bo=null;qt="__concurrencyLease"});async function D(n){let e=await n.text();return eu(e,n.status)}function eu(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function ui(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function lt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:c}=await o.read();if(c||(i&&(s+=r.decode(i,{stream:!0})),lt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:lt(s)}}async function me(n){try{let e=await n.text();if(lt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var Q=w(()=>{"use strict"});function tu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function nn(n){for(let e of tu(n))if(e.startsWith("response."))return!0;return!1}var Fe,Vo=w(()=>{"use strict";Q();Fe=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await D(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",c=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=c.decode(p,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",c,l,u,p,d="",f=new Map,h=new Map,g=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(R,E=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[{index:0,delta:R,finish_reason:E}]})}
|
|
5
|
+
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(xl.some(s=>r.includes(s))){e=!0;break}Sl.some(s=>r.includes(s))&&(t=!0)}}return e||Cl(n)?"content":t?"empty":"pending"}async function zs(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=c-Date.now(),p=Symbol("timeout"),d,f=o.read(),h=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),h===p)return l(Ro(a)==="content"?"content":"pending",Gt(o,f));if(h.done){a+=r.decode();let m=Ro(a);return l(m==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let g=Ro(a);if(g==="content")return l("content",Gt(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(Hs(a)||i>=e)return l("pending",Gt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Gt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Bs(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var xl,Sl,Js=w(()=>{"use strict";xl=["content_block_start","content_block_delta","content_block_stop"];Sl=["message_stop","response.completed","response.incomplete","[DONE]"]});function Rl(n,e){return`${n.name}|${e?.name??""}`}function wo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function Le(n,e,t){let o=wo(n),r=Rl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Po(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(Le(n,e,o).terminalError=t,!0)}var Ws=w(()=>{"use strict"});var Eo=w(()=>{"use strict"});import wl from"fastify";function Ks(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var it,Pl,Oo,Vt=w(()=>{"use strict";Eo();it=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let g of this.plugins.values()){for(let m of s.runtimes.keys())if(g.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(g.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([m,y])=>{if(g.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:g,name:m,value:g.preparePluginTransformer(y)}})),h=[];try{for(let g of f)h.push(g),g.service.registerTransformer(g.name,g.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(g){for(let m of h)m.service.removeTransformer(m.name);throw a="aborted",g}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:d??p}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=wl({logger:!1});try{for(let i of e){let c=i(s);c!==s&&await c}for(let i of this.plugins.values())for(let c of i.preparedRoutes)a.route(c);for(let i of r){let c=Array.isArray(i.method)?i.method:[i.method];for(let l of c)if(t.hasRoute({method:l,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${l} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},Pl=new it,Oo=()=>Pl});function Gs(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function Te(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?El(r):{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(i)}catch{}let c=Ks(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function El(n){let e=[n?.causeCode,n?.causeDetail].filter(Boolean).join(" ");return{code:"plugin_network_error",message:e?`Provider plugin network failure (${e}).`:n?.errorName?`Provider plugin network failure (${n.errorName}).`:"Provider plugin network failure.",httpStatus:502,retryable:!0}}var Vs=w(()=>{"use strict";Vt()});var Qt,Io=w(()=>{Qt="2.3.2428"});var Qs={};bo(Qs,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>Il});function Ne(n){return ve||(ve=new Mo,n&&ve.configure(n)),ve}function Il(){ve&&(ve.clearAll(),ve=null)}var Ol,Mo,ve,Yt=w(()=>{"use strict";se();Ol=600*1e3,Mo=class{promotions=new Map;enabled=!0;ttlMs=Ol;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!j().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},ve=null});import{existsSync as Zs,mkdirSync as Ml,readFileSync as Ll,writeFileSync as Nl}from"fs";import{join as qs}from"path";import{HOME_DIR as $l}from"@wengine-ai/claude-code-router-shared";function jl(n){try{if(!Zs($o))return;let e=JSON.parse(Ll($o,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Xs(n){try{let e=n.getAllStates();if(e.length===0)return;Zs(No)||Ml(No,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Nl($o,JSON.stringify(t,null,2),"utf-8")}catch{}}function Fo(){if(Ys)return;Ys=!0;let n=j();jl(n),Dl=setInterval(()=>Xs(n),6e4),process.on("exit",()=>Xs(n))}function j(n){return Lo||(Lo=new Xt(n)),Lo}var Fl,Ul,Xt,No,$o,Ys,Dl,Lo,se=w(()=>{"use strict";Fl=120,Ul={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ul,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),ul(Qs));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t,o=!1){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let s=this.getState(e,t);return s?s.status==="open"&&s.rateLimitUntil?!(Date.now()<s.rateLimitUntil):s.status==="open"&&o&&Date.now()-Math.max(s.lastFailureTime,s.lastProbeTime)>=this.config.probeIntervalMinutes*6e4?(s.status="half-open",s.successCount=0,s.lastProbeTime=Date.now(),!0):s.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}recordProbeAttempt(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.lastProbeTime=Date.now())}markParkedUntil(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s&&(!Number.isFinite(o)||o<=Date.now()||s.rateLimitUntil&&s.rateLimitUntil>=o||(s.rateLimitUntil=o))}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??Fl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},No=qs($l,"runtime"),$o=qs(No,"provider-health.json"),Ys=!1,Dl=null;Lo=null});import{existsSync as ri,mkdirSync as Hl,readFileSync as zl,writeFileSync as Bl}from"fs";import{join as si}from"path";import{HOME_DIR as Jl}from"@wengine-ai/claude-code-router-shared";function at(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let c=Object.keys(t).find(l=>l.toLowerCase()===i);return c?t[c]:null},r=Uo(o,Wl),s=Uo(o,Kl),a=Uo(o,Gl);(r||s||a)&&$e.set(n,{provider:n,remaining:ni(r),limit:ni(s),reset:Ql(a),capturedAt:Date.now()})}function Vl(n){return $e.get(n)}function Ho(){return Array.from($e.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Uo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ni(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Ql(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):t>1e9?Math.floor(t):Math.floor(Date.now()/1e3+t);let o=Date.parse(e);if(Number.isFinite(o))return Math.floor(o/1e3);let r=Yl(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Yl(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function Xl(){try{if(!ri(jo))return;let n=JSON.parse(zl(jo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;$e.set(t.provider,t)}}catch{}}function oi(){try{if($e.size===0)return;ri(Do)||Hl(Do,{recursive:!0}),Bl(jo,JSON.stringify(Array.from($e.values()),null,2),"utf-8")}catch{}}function ct(){ei||(ei=!0,Xl(),ti=setInterval(oi,6e4),ti.unref?.(),process.on("exit",oi))}var Do,jo,$e,ei,ti,Wl,Kl,Gl,xe=w(()=>{"use strict";Do=si(Jl,"runtime"),jo=si(Do,"rate-limit.json"),$e=new Map,ei=!1,ti=null,Wl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Kl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Gl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return zo||(zo=new Jo),zo}function Ko(){return Bo||(Bo=new Wo),Bo}function Zl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function ii(n){let e=Zl(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function ai(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Go(n){let e=n?.[qt];e&&en().release(e)}function ci(n,e){let t=ii(n),o=n?.[qt],r=t?Ko().get(t)!==void 0:!1;!o&&!r||(t&&Ko().bind(t,e),ai(n,e))}function ql(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function li(n,e,t){let o=ii(n),r=Ko(),s=en(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let c=r.get(o);if(c&&c!==e){let l=t.resolve(c);l?(i=l,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${l}`)):r.unbind(o)}else c&&(i=e)}if(!i){let c=s.count(e);if(c>=a){let l=ql(e,t.fallbackModels,t.resolve);l&&(i=l,t.log?.(`Concurrency priority: model ${e} has ${c} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${l}`))}i=i||e,o&&r.bind(o,i)}return ai(n,i),i}var Jo,Wo,zo,Bo,qt,tn=w(()=>{"use strict";Jo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},Wo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},zo=null,Bo=null;qt="__concurrencyLease"});async function D(n){let e=await n.text();return eu(e,n.status)}function eu(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function ui(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function lt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:c}=await o.read();if(c||(i&&(s+=r.decode(i,{stream:!0})),lt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:lt(s)}}async function me(n){try{let e=await n.text();if(lt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var Q=w(()=>{"use strict"});function tu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function nn(n){for(let e of tu(n))if(e.startsWith("response."))return!0;return!1}var Fe,Vo=w(()=>{"use strict";Q();Fe=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await D(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",c=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=c.decode(p,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",c,l,u,p,d="",f=new Map,h=new Map,g=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(R,E=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[{index:0,delta:R,finish_reason:E}]})}
|
|
6
6
|
|
|
7
7
|
`))},v=R=>{if(!R)return;let E=_.getCacheReadInputTokens(R),I=typeof R.input_tokens=="number"?R.input_tokens:void 0,O=_.getCacheCreationInputTokens(R);T.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[],usage:{prompt_tokens:I,completion_tokens:typeof R.output_tokens=="number"?R.output_tokens:void 0,total_tokens:R.total_tokens,prompt_tokens_details:{cached_tokens:E,cache_creation_tokens:O},cache_read_input_tokens:E,cache_creation_input_tokens:O}})}
|
|
8
8
|
|
|
@@ -288,7 +288,7 @@ ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return
|
|
|
288
288
|
error: ${t.message}
|
|
289
289
|
stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
290
290
|
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Ea).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});import{get_encoding as Pd}from"tiktoken";var _t,Oa=w(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Pd(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(c=>{if(c.type==="text")o+=t.encode(c.text).length;else if(c.type==="tool_use")o+=t.encode(JSON.stringify(c.input)).length;else if(c.type==="tool_result"){let l=c.content;if(Array.isArray(l))for(let u of l)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof l=="string"?l:JSON.stringify(l);o+=t.encode(u).length}}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(c=>{o+=t.encode(c||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Bn}from"path";import{homedir as Ed}from"os";import{existsSync as pr,mkdirSync as Ad}from"fs";import{promises as Jn}from"fs";import{Tokenizer as Od}from"@huggingface/tokenizers";var Wn,Ia=w(()=>{"use strict";Wn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||Bn(Ed(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Bn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Bn(e,"tokenizer.json"),tokenizerConfig:Bn(e,"tokenizer_config.json")}}ensureDir(e){pr(e)||Ad(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!pr(e.tokenizerJson)||!pr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Jn.readFile(e.tokenizerJson,"utf-8"),Jn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,c]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Jn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Jn.writeFile(e.tokenizerConfig,JSON.stringify(c,null,2))]),{tokenizerJson:i,tokenizerConfig:c}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new Od(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let c of i.content)c?.type!=="image"&&t.push(c?.type==="text"?String(c.text??""):JSON.stringify(c));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Kn,Ma=w(()=>{"use strict";q();Kn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},i=this.options.resolveProxyUrl?.();i&&(a.dispatcher=K(i));let c=await fetch(this.config.url,a);if(clearTimeout(s),!c.ok)throw new Error(`API tokenizer request failed: ${c.status} ${c.statusText}`);let l=await c.json();return this.extractTokenCount(l)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
|
|
291
|
-
`):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Xe,fr=w(()=>{"use strict";Oa();Ia();Ma();q();Xe=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new _t("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Wn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Kn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function La(n){if(!n||typeof n!="object"||Ud(n))return null;for(let t of Fd(n)){let o=$d(t);if(o)return o}return null}function $d(n){if(!n||typeof n!="object")return null;let e={},t=Gn(n,Id);if(t!==void 0){let a=Na(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Gn(n,Md);if(o!==void 0){let a=Na(o);e.usedBalance=a,e.totalBalance=100}let r=Gn(n,Ld);if(r!==void 0){let a=$a(r);a&&(e.resetTime=a)}let s=Gn(n,Nd);if(s!==void 0){let a=$a(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function Na(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Gn(n,e){for(let t of e){let o=F(n?.[t]);if(o!==void 0)return o}}function Fd(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function Ud(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function $a(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Sr(n){let e=Rr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Kd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Gd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Dd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?jd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Hd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?zd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Bd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Jd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Wd:null:null}function Vd(n){let e=Rr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Qd(n,e){let t=xr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function xr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>xr(e)):Object.values(n).flatMap(e=>xr(e))}function Cr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Rr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function F(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var ie,mr,gr,hr,yr,_r,Id,Md,Ld,Nd,br,kr,Tr,vr,Dd,jd,Hd,zd,Bd,Jd,Wd,Kd,Gd,wr=w(()=>{"use strict";q();ie=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=K(r));let c=await fetch(e,i);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},mr=class extends ie{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>F(c?.total_balance)!==void 0);if(!a)return null;let i=F(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},gr=class extends ie{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=F(s.limit),c=F(s.limit_remaining),l=F(s.usage),u=F(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},hr=class extends ie{async queryQuota(e,t,o){let r=Vd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=F(a.totalBalance),l=F(a.balance);return c!==void 0&&(i.totalBalance=c),l!==void 0&&(i.remainingBalance=l),c!==void 0&&l!==void 0&&(i.usedBalance=Math.max(0,c-l)),this.hasQuotaData(i)?i:null}},yr=class extends ie{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),c=Array.isArray(i?.data?.limits)?i.data.limits:[],l=null,u=null,p=null;for(let f of c)f.type==="TOKENS_LIMIT"?f.unit===3?l=f:f.unit===6?u=f:l||(l=f):f.type==="TIME_LIMIT"&&(p=f);let d={};if(l){let f=F(l.currentValue),h=F(l.usage),g=F(l.remaining),m=F(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),h!==void 0?d.limitDaily=h:f!==void 0&&g!==void 0&&(d.limitDaily=f+g),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=F(u.currentValue),h=F(u.usage),g=F(u.remaining),m=F(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),h!==void 0?d.totalBalance=h:f!==void 0&&g!==void 0&&(d.totalBalance=f+g),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=F(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=F(p.usage),h=F(p.currentValue),g=F(p.remaining);f!==void 0?d.limitDaily=f:h!==void 0&&g!==void 0&&(d.limitDaily=h+g)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},_r=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=K(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let l=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(l)||l.length===0)return null;let u=l[0]?.codingPlanQuotaInfo;if(!u)return null;let p={},d=F(u.per5HourUsedQuota),f=F(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let h=F(u.perWeekUsedQuota),g=F(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),g!==void 0&&(p.totalBalance=g),this.hasQuotaData(p)?p:null}catch{return null}}};Id=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Md=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Ld=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Nd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];br=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Cr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=K(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,l);if(!u.ok)return null;let p=await u.json();return La(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=K(o));let c=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!c.ok)return null;let l=await c.json();return La(l)}catch{return null}}},kr=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Cr(e.quotaToken,"atp-auth-token")||Cr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let c=Qd(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=F(l.rp5hUsage),d=F(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=F(l.rpwUsage),h=F(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,h-f)),this.hasQuotaData(u)?u:null}catch{return null}}},Tr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),c={},l=Array.isArray(i?.limits)?i.limits:[];if(l.length>0&&l[0]?.detail){let p=l[0].detail,d=F(p.limit),f=F(p.remaining),h=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),h&&(c.resetTime=new Date(h).toISOString())}let u=i?.usage;if(u){let p=F(u.limit),d=F(u.remaining),f=F(u.used),h=u.resetTime;p!==void 0&&(c.totalBalance=p,f!==void 0?c.usedBalance=f:d!==void 0&&(c.usedBalance=Math.max(0,p-d),c.remainingBalance=d)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},vr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Rr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let k of i)if(c=await this.fetchJson(k,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let k=c.base_resp.status_code;if(k!==void 0&&k!==0)return null}let l=Array.isArray(c?.model_remains)?c.model_remains:[];if(l.length===0)return null;let u=l[0],p={},d=F(u.current_interval_total_count),f=F(u.current_interval_usage_count),h=F(u.current_interval_remaining_percent),g=F(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),g&&(p.resetTime=new Date(g).toISOString());let m=F(u.current_weekly_total_count),y=F(u.current_weekly_usage_count),b=F(u.current_weekly_remaining_percent),_=F(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Dd=new mr,jd=new gr,Hd=new hr,zd=new yr,Bd=new _r,Jd=new br,Wd=new kr,Kd=new Tr,Gd=new vr});function Fa(n){return{[Yd]:n,[Xd]:Qt}}function Ee(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function qd(n){return n===!0||n==="true"||n===1||n==="1"}function ep(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function tp(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function np(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Pr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Ee(n))return{success:!1,skipped:!0,error:Er,latencyMs:r()};let s=tp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=K(t));let i=await fetch(s,a);if(i.headers&&at(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let c=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${c.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",c=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:c?"timeout":"network"}}}async function op(n,e,t,o){if(Ee(n))return{success:!1,skipped:!0,error:Er};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Fa("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=K(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function rp(n,e,t,o,r){if(Ee(n))return{success:!1,skipped:!0,error:Er};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Fa("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=K(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function Ua(n,e,t,o,r,s){return _e||(_e=new Vn(n,e,t,o,r,s)),_e}function bt(n,e,t,o,r,s){let a=Ua(n,e,t,o,r,s);return a.start(),a}function Ar(){_e&&_e.stop()}function Or(){_e&&(_e.stop(),_e=null)}var Yd,Xd,Zd,Er,Vn,_e,Qn=w(()=>{"use strict";se();xe();wr();De();Io();q();Yd="x-claude-code-router-source",Xd="x-claude-code-router-version";Zd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Er="Managed provider requires its plugin's authenticated model sync";Vn=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,a){this.config={...Zd,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),c={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,c),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),c}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.managedProbeTimer=setInterval(()=>this.runManagedRecoveryProbe(),this.config.quotaProbeIntervalMinutes*60*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.managedProbeTimer&&(clearInterval(this.managedProbeTimer),this.managedProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!Ee(s)&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let a=Sr(s.baseUrl),i=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let l;try{l=new URL(s.baseUrl).hostname}catch{l=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(l?` (host: ${l})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(l=>{if(l){Zo(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,p=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.totalBalance})`;for(let f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),np(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Pr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=j(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Ee(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Pr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let l of i)e.recordFailure(s.name,l,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let c of i)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=j();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let c=o.get(s)??[];c.push(i),o.set(s,c)}for(let[r,s]of o){let a=this.getProviders().find(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let c=s[0],l=e.getState(r,c);!l||l.status!=="open"||l.rateLimitUntil&&Date.now()<l.rateLimitUntil||Date.now()-(l.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,c,s,e)||await this.probeManagedLiveness(r,i,a,c,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=this.config.probeTimeoutMs,c={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},l=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(c),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:l,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:l,requestBody:c,config:u,provider:o}):await l();if(p?.ok){for(let d of s)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=j(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&Ee(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await rp(p,c,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!Ee(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=ep(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),p=parseInt(l,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,h=(p*60+d)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(f||g)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),op(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?qd(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Pr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)j().recordSuccess(o.name,i);else for(let i of a)j().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},_e=null});var Da=w(()=>{"use strict"});var Ir,kt,ja=w(()=>{"use strict";Ir=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},kt=new Ir});var ae,Mr=w(()=>{"use strict";ae=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
291
|
+
`):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Xe,fr=w(()=>{"use strict";Oa();Ia();Ma();q();Xe=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new _t("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Wn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Kn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function La(n){if(!n||typeof n!="object"||Ud(n))return null;for(let t of Fd(n)){let o=$d(t);if(o)return o}return null}function $d(n){if(!n||typeof n!="object")return null;let e={},t=Gn(n,Id);if(t!==void 0){let a=Na(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Gn(n,Md);if(o!==void 0){let a=Na(o);e.usedBalance=a,e.totalBalance=100}let r=Gn(n,Ld);if(r!==void 0){let a=$a(r);a&&(e.resetTime=a)}let s=Gn(n,Nd);if(s!==void 0){let a=$a(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function Na(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Gn(n,e){for(let t of e){let o=F(n?.[t]);if(o!==void 0)return o}}function Fd(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function Ud(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function $a(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Sr(n){let e=Rr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Kd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Gd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Dd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?jd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Hd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?zd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Bd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Jd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Wd:null:null}function Vd(n){let e=Rr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Qd(n,e){let t=xr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function xr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>xr(e)):Object.values(n).flatMap(e=>xr(e))}function Cr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Rr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function F(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var ie,mr,gr,hr,yr,_r,Id,Md,Ld,Nd,br,kr,Tr,vr,Dd,jd,Hd,zd,Bd,Jd,Wd,Kd,Gd,wr=w(()=>{"use strict";q();ie=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=K(r));let c=await fetch(e,i);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},mr=class extends ie{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>F(c?.total_balance)!==void 0);if(!a)return null;let i=F(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},gr=class extends ie{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=F(s.limit),c=F(s.limit_remaining),l=F(s.usage),u=F(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},hr=class extends ie{async queryQuota(e,t,o){let r=Vd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=F(a.totalBalance),l=F(a.balance);return c!==void 0&&(i.totalBalance=c),l!==void 0&&(i.remainingBalance=l),c!==void 0&&l!==void 0&&(i.usedBalance=Math.max(0,c-l)),this.hasQuotaData(i)?i:null}},yr=class extends ie{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),c=Array.isArray(i?.data?.limits)?i.data.limits:[],l=null,u=null,p=null;for(let f of c)f.type==="TOKENS_LIMIT"?f.unit===3?l=f:f.unit===6?u=f:l||(l=f):f.type==="TIME_LIMIT"&&(p=f);let d={};if(l){let f=F(l.currentValue),h=F(l.usage),g=F(l.remaining),m=F(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),h!==void 0?d.limitDaily=h:f!==void 0&&g!==void 0&&(d.limitDaily=f+g),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=F(u.currentValue),h=F(u.usage),g=F(u.remaining),m=F(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),h!==void 0?d.totalBalance=h:f!==void 0&&g!==void 0&&(d.totalBalance=f+g),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=F(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=F(p.usage),h=F(p.currentValue),g=F(p.remaining);f!==void 0?d.limitDaily=f:h!==void 0&&g!==void 0&&(d.limitDaily=h+g)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},_r=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=K(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let l=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(l)||l.length===0)return null;let u=l[0]?.codingPlanQuotaInfo;if(!u)return null;let p={},d=F(u.per5HourUsedQuota),f=F(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let h=F(u.perWeekUsedQuota),g=F(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),g!==void 0&&(p.totalBalance=g),this.hasQuotaData(p)?p:null}catch{return null}}};Id=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Md=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Ld=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Nd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];br=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Cr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=K(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,l);if(!u.ok)return null;let p=await u.json();return La(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=K(o));let c=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!c.ok)return null;let l=await c.json();return La(l)}catch{return null}}},kr=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Cr(e.quotaToken,"atp-auth-token")||Cr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let c=Qd(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=F(l.rp5hUsage),d=F(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=F(l.rpwUsage),h=F(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,h-f)),this.hasQuotaData(u)?u:null}catch{return null}}},Tr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),c={},l=Array.isArray(i?.limits)?i.limits:[];if(l.length>0&&l[0]?.detail){let p=l[0].detail,d=F(p.limit),f=F(p.remaining),h=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),h&&(c.resetTime=new Date(h).toISOString())}let u=i?.usage;if(u){let p=F(u.limit),d=F(u.remaining),f=F(u.used),h=u.resetTime;p!==void 0&&(c.totalBalance=p,f!==void 0?c.usedBalance=f:d!==void 0&&(c.usedBalance=Math.max(0,p-d),c.remainingBalance=d)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},vr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Rr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let k of i)if(c=await this.fetchJson(k,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let k=c.base_resp.status_code;if(k!==void 0&&k!==0)return null}let l=Array.isArray(c?.model_remains)?c.model_remains:[];if(l.length===0)return null;let u=l[0],p={},d=F(u.current_interval_total_count),f=F(u.current_interval_usage_count),h=F(u.current_interval_remaining_percent),g=F(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),g&&(p.resetTime=new Date(g).toISOString());let m=F(u.current_weekly_total_count),y=F(u.current_weekly_usage_count),b=F(u.current_weekly_remaining_percent),_=F(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Dd=new mr,jd=new gr,Hd=new hr,zd=new yr,Bd=new _r,Jd=new br,Wd=new kr,Kd=new Tr,Gd=new vr});function Fa(n){return{[Yd]:n,[Xd]:Qt}}function Ee(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function qd(n){return n===!0||n==="true"||n===1||n==="1"}function ep(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function tp(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function np(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Pr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Ee(n))return{success:!1,skipped:!0,error:Er,latencyMs:r()};let s=tp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=K(t));let i=await fetch(s,a);if(i.headers&&at(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let c=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${c.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",c=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:c?"timeout":"network"}}}async function op(n,e,t,o){if(Ee(n))return{success:!1,skipped:!0,error:Er};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Fa("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=K(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function rp(n,e,t,o,r){if(Ee(n))return{success:!1,skipped:!0,error:Er};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Fa("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=K(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function Ua(n,e,t,o,r,s){return _e||(_e=new Vn(n,e,t,o,r,s)),_e}function bt(n,e,t,o,r,s){let a=Ua(n,e,t,o,r,s);return a.start(),a}function Ar(){_e&&_e.stop()}function Or(){_e&&(_e.stop(),_e=null)}var Yd,Xd,Zd,Er,Vn,_e,Qn=w(()=>{"use strict";se();xe();wr();De();Io();q();Yd="x-claude-code-router-source",Xd="x-claude-code-router-version";Zd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Er="Managed provider requires its plugin's authenticated model sync";Vn=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,a){this.config={...Zd,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),c={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,c),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),c}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.managedProbeTimer=setInterval(()=>this.runManagedRecoveryProbe(),this.config.quotaProbeIntervalMinutes*60*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.managedProbeTimer&&(clearInterval(this.managedProbeTimer),this.managedProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!Ee(s)&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let a=Sr(s.baseUrl),i=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let l;try{l=new URL(s.baseUrl).hostname}catch{l=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(l?` (host: ${l})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(l=>{if(l){Zo(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,p=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.totalBalance})`;for(let f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),np(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Pr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=j(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Ee(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Pr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let l of i)e.recordFailure(s.name,l,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let c of i)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=j();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let c=o.get(s)??[];c.push(i),o.set(s,c)}for(let[r,s]of o){let a=this.getProviders().find(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let c=s[0],l=e.getState(r,c);!l||l.status!=="open"||l.rateLimitUntil&&Date.now()<l.rateLimitUntil||Date.now()-(l.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,c,s,e)||await this.probeManagedLiveness(r,i,a,c,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=this.config.probeTimeoutMs,c={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},l=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(c),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:l,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:l,requestBody:c,config:u,provider:o}):await l();if(p?.ok){for(let d of s)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=j(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&Ee(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await rp(p,c,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!Ee(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=ep(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),p=parseInt(l,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,h=(p*60+d)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(f||g)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),op(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?qd(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Pr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)j().recordSuccess(o.name,i);else for(let i of a)j().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},_e=null});var Da=w(()=>{"use strict"});var Ir,kt,ja=w(()=>{"use strict";Ir=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},kt=new Ir});var ae,Mr=w(()=>{"use strict";ae=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
292
292
|
`);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Ze,Lr=w(()=>{"use strict";Ze=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
293
293
|
`),e.id&&(o+=`id: ${e.id}
|
|
294
294
|
`),e.retry&&(o+=`retry: ${e.retry}
|