@wengine-ai/claude-code-router-next 2.1.34 → 2.1.35
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/dist/cli.js +4 -4
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -631,7 +631,7 @@ ${this.toMarkdown(R,x+1)}`:`${F}- ${R}`).join(`
|
|
|
631
631
|
${this.toMarkdown(M,x+1)}`:`${F}${R}: ${M}`).join(`
|
|
632
632
|
`):`${F}${p}`}async output(p,x={}){try{let F=this.formatData(p,x);switch(this.config.level||"log"){case"info":console.info(F);break;case"warn":console.warn(F);break;case"error":console.error(F);break;case"debug":console.debug(F);break;case"log":default:console.log(F);break}return!0}catch(F){return console.error("[ConsoleOutputHandler] Output failed:",F),!1}}}}),dc,zA=u(()=>{"use strict";dc=class{type="webhook";config;defaultTimeout=3e4;constructor(p){if(!p.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...p}}buildHeaders(){let p={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(p.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let x=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");p.Authorization=`Basic ${x}`}break;case"custom":this.config.auth.custom&&(p[this.config.auth.custom.header]=this.config.auth.custom.value);break}return p}buildBody(p,x){let{format:F="json",timestamp:R=!0,prefix:M,metadata:O}=x||{},G={data:p};return R&&(G.timestamp=new Date().toISOString()),M&&(G.prefix=M),O&&Object.keys(O).length>0&&(G.metadata=O),G}async sendRequest(p,x,F,R,M){let O=new AbortController,G=setTimeout(()=>O.abort(),M);try{let J=await fetch(p,{method:x,headers:F,body:JSON.stringify(R),signal:O.signal});if(clearTimeout(G),!J.ok)throw new Error(`HTTP ${J.status}: ${J.statusText}`);return J}catch(J){throw clearTimeout(G),J}}delay(p){return new Promise(x=>setTimeout(x,p))}async sendWithRetry(p,x,F,R,M,O){let G=null;for(let J=1;J<=O.maxAttempts;J++)try{return await this.sendRequest(p,x,F,R,M)}catch(ne){if(G=ne,J===O.maxAttempts)break;let z=O.backoffMs*Math.pow(2,J-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${J}/${O.maxAttempts}), retrying in ${z}ms...`,ne.message),await this.delay(z)}throw G}async output(p,x={}){let F=x.timeout||this.defaultTimeout;try{let R=this.buildHeaders(),M=this.buildBody(p,x),O=await this.sendWithRetry(this.config.url,this.config.method,R,M,F,this.config.retry);return!0}catch(R){let M=R instanceof Error?R.message:String(R);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${M}`),!1;throw new Error(`Webhook output failed: ${M}`)}}}}),yd,Zh,WA,KA,ZA=u(()=>{"use strict";yd=require("fs"),Zh=require("path"),WA=require("os"),KA=class{type="temp-file";config;baseDir;constructor(p={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...p};let x=(0,WA.tmpdir)();this.baseDir=(0,Zh.join)(x,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,yd.existsSync)(this.baseDir)||(0,yd.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(p){try{let x=p.match(/_session_([a-f0-9-]+)/i);return x?x[1]:null}catch{return null}}getFilePath(p){let x=this.config.prefix||"session",F=this.config.extension?`.${this.config.extension}`:"",R;if(this.config.includeTimestamp){let M=Date.now();R=`${x}-${p}-${M}${F}`}else R=`${x}-${p}${F}`;return(0,Zh.join)(this.baseDir,R)}async output(p,x={}){try{let F=x.metadata?.sessionId;if(!F)return!1;let R={...p,timestamp:Date.now(),sessionId:F},M=this.getFilePath(F);return(0,yd.writeFileSync)(M,JSON.stringify(R,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}}),Xh,hc,_m=u(()=>{"use strict";pa(),zA(),ZA(),Xh=class{handlers=new Map;defaultOptions={};registerHandler(p,x){this.handlers.set(p,x)}registerHandlers(p){for(let x of p)if(x.enabled!==!1)try{let F=this.createHandler(x),R=x.type+"_"+Date.now();this.registerHandler(R,F)}catch(F){console.error(`[OutputManager] Failed to register ${x.type} handler:`,F)}}createHandler(p){switch(p.type){case"console":return new fs(p.config);case"webhook":return new dc(p.config);case"temp-file":return new KA(p.config);default:throw new Error(`Unknown output handler type: ${p.type}`)}}unregisterHandler(p){return this.handlers.delete(p)}getHandler(p){return this.handlers.get(p)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(p){this.defaultOptions={...this.defaultOptions,...p}}getDefaultOptions(){return{...this.defaultOptions}}async output(p,x){let F={...this.defaultOptions,...x},R={success:[],failed:[]},M=Array.from(this.handlers.entries()).map(async([O,G])=>{try{await G.output(p,F)?R.success.push(O):R.failed.push(O)}catch(J){console.error(`[OutputManager] Handler ${O} failed:`,J),R.failed.push(O)}});return await Promise.all(M),R}async outputTo(p,x,F){let R={...this.defaultOptions,...F},M={success:[],failed:[]},O=p.map(async G=>{let J=this.handlers.get(G);if(!J){console.warn(`[OutputManager] Handler ${G} not found`),M.failed.push(G);return}try{await J.output(x,R)?M.success.push(G):M.failed.push(G)}catch(ne){console.error(`[OutputManager] Handler ${G} failed:`,ne),M.failed.push(G)}});return await Promise.all(O),M}async outputToType(p,x,F){let R=Array.from(this.handlers.entries()).filter(([M,O])=>O.type===p).map(([M])=>M);return this.outputTo(R,x,F)}},hc=new Xh}),Yi={};c(Yi,{ActiveProbeService:()=>Tw,ConfigService:()=>Su,ProviderHealthStore:()=>Z,ProviderService:()=>Cn,SSEParserTransform:()=>Ow,SSESerializerTransform:()=>O6,TokenizerService:()=>qm,TransformerService:()=>Um,calculateTokenCount:()=>Iw,default:()=>j6,getActiveProbeService:()=>Rw,getAllQuotaResults:()=>n6,getAllRateLimitInfo:()=>Nm,getHealthStore:()=>Q,getQuotaAdapter:()=>kw,getQuotaResult:()=>Dw,getRateLimitInfo:()=>Qm,getRuntimeDebugLog:()=>bd,initProviderHealthPersistence:()=>k,initQuotaStorePersistence:()=>ww,initRateLimitPersistence:()=>Tu,pluginManager:()=>Q6,resetActiveProbeService:()=>T6,rewriteStream:()=>L6,router:()=>zm,searchProjectBySession:()=>Fw,sessionUsageCache:()=>gw,setRuntimeDebugLog:()=>r0,startActiveProbe:()=>Qw,stopActiveProbe:()=>Nw,storeQuotaResult:()=>Cw,tokenSpeedPlugin:()=>M6}),t.exports=h(Yi);var fc=f(gx(),1),XA=f(mx(),1),Ac=require("fs"),ga=require("path"),Wa=Ex(),Is=f(D(),1),Su=class{config={};options;constructor(p={jsonPath:"./config.json"}){this.options={envPath:p.envPath||".env",jsonPath:p.jsonPath,useEnvFile:!1,useJsonFile:p.useJsonFile!==!1,useEnvironmentVariables:p.useEnvironmentVariables!==!1,...p},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 p=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,ga.join)(process.cwd(),this.options.jsonPath);if((0,Ac.existsSync)(p))try{let x=(0,Ac.readFileSync)(p,"utf-8"),F=Is.default.parse(x);this.config={...this.config,...F},console.log(`Loaded JSON config from: ${p}`)}catch(x){console.warn(`Failed to load JSON config from ${p}:`,x)}else console.warn(`JSON config file not found: ${p}`)}loadEnvConfig(){let p=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,ga.join)(process.cwd(),this.options.envPath);if((0,Ac.existsSync)(p))try{let x=(0,Wa.config)({path:p});x.parsed&&(this.config={...this.config,...this.parseEnvConfig(x.parsed)})}catch(x){console.warn(`Failed to load .env config from ${p}:`,x)}}loadEnvironmentVariables(){let p=this.parseEnvConfig(process.env);this.config={...this.config,...p}}parseEnvConfig(p){let x={};return Object.assign(x,p),x}isAbsolutePath(p){return p.startsWith("/")||p.includes(":")}get(p,x){let F=this.config[p];return F!==void 0?F:x}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(p){return this.config[p]!==void 0}set(p,x){this.config[p]=x}reload(){this.config={},this.loadConfig()}getConfigSummary(){let p=[];return this.options.initialConfig&&p.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&p.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&p.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&p.push("Environment Variables"),`Config sources: ${p.join(", ")}`}};function $i(p,x=500,F="internal_error",R="api_error"){let M=new Error(p);return M.statusCode=x,M.code=F,M.type=R,M}async function Fu(p,x,F){x.log.error(p);let R=p.statusCode||500;if(p.rawBody)try{let O=JSON.parse(p.rawBody);return F.code(R).send(O)}catch{return F.code(R).send(p.rawBody)}let M={error:{message:p.message+(p.stack||"Internal Server Error"),type:p.type||"api_error",code:p.code||"internal_error"}};return F.code(R).send(M)}var e0=Po();function t0(p,x,F,R,M){let O=new Headers({"Content-Type":"application/json"});F.headers&&Object.entries(F.headers).forEach(([z,te])=>{te&&O.set(z,te)});let G,J=AbortSignal.timeout(F.TIMEOUT??60*1e3*60);if(F.signal){let z=new AbortController,te=()=>z.abort();F.signal.addEventListener("abort",te),J.addEventListener("abort",te),G=z.signal}else G=J;let ne={method:"POST",headers:O,body:JSON.stringify(x),signal:G};return F.httpsProxy&&(ne.dispatcher=new e0.ProxyAgent(new URL(F.httpsProxy).toString())),M?.debug({reqId:R.req.id,request:ne,headers:Object.fromEntries(O.entries()),requestUrl:typeof p=="string"?p:p.toString(),useProxy:F.httpsProxy},"final request"),fetch(typeof p=="string"?p:p.toString(),ne)}var Cd=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),ku={maxBodyLength:4096,maxStreamChunks:100},Dd=!1;function r0(p){Dd=p}function bd(){return Dd}function wd(p){return Dd||p.get("DEBUG_LOG")===!0}function n0(p){let x=p.get("DEBUG_LOG_OPTIONS");return!x||typeof x!="object"?ku:{maxBodyLength:x.maxBodyLength??ku.maxBodyLength,maxStreamChunks:x.maxStreamChunks??ku.maxStreamChunks}}function i0(p){let x={};for(let[F,R]of Object.entries(p))Cd.has(F.toLowerCase())?x[F]="***MASKED***":x[F]=R;return x}function ef(p,x){return p.length<=x?p:p.slice(0,x)+`...[truncated, total ${p.length} bytes]`}function Sm(p,x,F){let R=typeof F.body=="string"?F.body:JSON.stringify(F.body);p.info({debug_log:!0,reqId:x,phase:"provider_request",url:F.url,headers:i0(F.headers),body:ef(R,ku.maxBodyLength)})}function Fm(p,x,F){p.info({debug_log:!0,reqId:x,phase:"provider_response",status:F.status,headers:i0(F.headers),...F.body!==void 0?{body:ef(F.body,ku.maxBodyLength)}:{}})}function o0(p,x,F,R){p.info({debug_log:!0,reqId:x,phase:"provider_stream_chunk",chunkIndex:F,data:ef(R,ku.maxBodyLength)})}function pc(p,x,F){p.info({debug_log:!0,reqId:x,phase:"provider_stream_end",totalChunks:F})}function km(p,x,F,R){(async()=>{let M=p.pipeThrough(new TextDecoderStream).getReader(),O=0;try{let G="";for(;;){let{done:J,value:ne}=await M.read();if(J)break;G+=ne;let z=G.split(`
|
|
633
633
|
|
|
634
|
-
`);G=z.pop()||"";for(let te of z)te.trim()&&(O<R.maxStreamChunks?o0(x,F,O,te):O===R.maxStreamChunks&&x.info({debug_log:!0,reqId:F,phase:"provider_stream_chunk_omitted",message:`[chunks after #${O} omitted, maxStreamChunks=${R.maxStreamChunks}]`}),O++)}G.trim()&&(O<R.maxStreamChunks&&o0(x,F,O,G.trim()),O++),pc(x,F,O)}catch(G){console.error(`[debug_log] Error reading debug stream for reqId=${F}:`,G),pc(x,F,O)}finally{M.releaseLock()}})()}var s0="2.1.
|
|
634
|
+
`);G=z.pop()||"";for(let te of z)te.trim()&&(O<R.maxStreamChunks?o0(x,F,O,te):O===R.maxStreamChunks&&x.info({debug_log:!0,reqId:F,phase:"provider_stream_chunk_omitted",message:`[chunks after #${O} omitted, maxStreamChunks=${R.maxStreamChunks}]`}),O++)}G.trim()&&(O<R.maxStreamChunks&&o0(x,F,O,G.trim()),O++),pc(x,F,O)}catch(G){console.error(`[debug_log] Error reading debug stream for reqId=${F}:`,G),pc(x,F,O)}finally{M.releaseLock()}})()}var s0="2.1.34";de();var pl=require("fs"),Id=require("path"),tf=Qa(),gl=(0,Id.join)(tf.HOME_DIR,"runtime"),Hs=(0,Id.join)(gl,"rate-limit.json"),ma=new Map,a0=!1,Tm=null,vd=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],u0=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Rm=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Bd(p,x,F){let R=J=>{if(F instanceof Headers)return F.get(J);let ne=Object.keys(F).find(z=>z.toLowerCase()===J);return ne?F[ne]:null},M=rf(R,vd),O=rf(R,u0),G=rf(R,Rm);(M||O||G)&&ma.set(p,{provider:p,remaining:l0(M),limit:l0(O),reset:Om(G),capturedAt:Date.now()})}function Qm(p){return ma.get(p)}function Nm(){return Array.from(ma.values())}function rf(p,x){for(let F of x){let R=p(F);if(R)return R}return null}function l0(p){if(!p)return null;let x=Number(p.trim().replace(/,/g,""));return Number.isFinite(x)?x:null}function Om(p){if(!p)return null;let x=p.trim();if(!x)return null;let F=Number(x);if(Number.isFinite(F))return F>1e12?Math.floor(F/1e3):F>1e9?Math.floor(F):Math.floor(Date.now()/1e3+F);let R=Date.parse(x);if(Number.isFinite(R))return Math.floor(R/1e3);let M=Lm(x);return M===null?null:Math.floor((Date.now()+M)/1e3)}function Lm(p){let x=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,F=0,R=!1;for(let M of p.matchAll(x)){R=!0;let O=Number(M[1]),G=M[2].toLowerCase();if(Number.isFinite(O))switch(G){case"ms":F+=O;break;case"s":F+=O*1e3;break;case"m":F+=O*60*1e3;break;case"h":F+=O*60*60*1e3;break;case"d":F+=O*24*60*60*1e3;break}}return R?F:null}function xd(){try{if(!(0,pl.existsSync)(Hs))return;let p=JSON.parse((0,pl.readFileSync)(Hs,"utf-8"));if(!Array.isArray(p))return;let x=Date.now();for(let F of p)if(F&&F.provider){if(F.capturedAt&&x-F.capturedAt>3600*1e3)continue;ma.set(F.provider,F)}}catch{}}function _d(){try{if(ma.size===0)return;(0,pl.existsSync)(gl)||(0,pl.mkdirSync)(gl,{recursive:!0}),(0,pl.writeFileSync)(Hs,JSON.stringify(Array.from(ma.values()),null,2),"utf-8")}catch{}}function Tu(){a0||(a0=!0,xd(),Tm=setInterval(_d,6e4),process.on("exit",_d))}I();var nf=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(p){delete p.temperature,delete p.max_tokens,p.reasoning&&(p.reasoning={effort:p.reasoning.effort,summary:"detailed"});let x=[],F=p.messages.filter(R=>R.role==="system");if(F.length>0){let R=F[0];Array.isArray(R.content)?R.content.forEach(M=>{let O="";typeof M=="string"?O=M:M&&typeof M=="object"&&"text"in M&&(O=M.text),x.push({role:"system",content:O})}):p.instructions=R.content}if(p.messages.forEach(R=>{if(R.role!=="system"){if(Array.isArray(R.content)){let M=R.content.map(O=>this.normalizeRequestContent(O,R.role)).filter(O=>O!==null);M.length>0?R.content=M:delete R.content}if(R.role==="tool"){let M={...R};M.type="function_call_output",M.call_id=R.tool_call_id,M.output=R.content,delete M.cache_control,delete M.role,delete M.tool_call_id,delete M.content,x.push(M);return}if(R.role==="assistant"&&Array.isArray(R.tool_calls)){R.tool_calls.forEach(M=>{x.push({type:"function_call",arguments:M.function.arguments,name:M.function.name,call_id:M.id})});return}x.push(R)}}),p.input=x,delete p.messages,Array.isArray(p.tools)){let R=p.tools.find(M=>M.function.name==="web_search");p.tools=p.tools.filter(M=>M.function.name!=="web_search").map(M=>(M.function.name==="WebSearch"&&delete M.function.parameters.properties.allowed_domains,M.function.name==="Edit"?{type:M.type,name:M.function.name,description:M.function.description,parameters:{...M.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:M.type,name:M.function.name,description:M.function.description,parameters:M.function.parameters})),R&&p.tools.push({type:"web_search"})}return p.parallel_tool_calls=!1,p}async transformResponseOut(p){let x=p.headers.get("Content-Type")||"";if(x.includes("application/json")){let F=await p.json();if(F.object==="response"&&F.output){let R=this.convertResponseToChat(F);return new Response(JSON.stringify(R),{status:p.status,statusText:p.statusText,headers:p.headers})}return new Response(JSON.stringify(F),{status:p.status,statusText:p.statusText,headers:p.headers})}else if(x.includes("text/event-stream")){if(!p.body)return p;let F=new TextDecoder,R=new TextEncoder,M="",O=!1,G=this,J=new ReadableStream({async start(ne){let z=p.body.getReader(),te=-1,ie="",ce=X=>(X!==ie&&(te++,ie=X),te);try{for(;;){let{done:X,value:le}=await z.read();if(X){O||ne.enqueue(R.encode(`data: [DONE]
|
|
635
635
|
|
|
636
636
|
`));break}let pe=F.decode(le,{stream:!0});M+=pe;let De=M.split(/\r?\n/);M=De.pop()||"";for(let be of De)if(be.trim())try{if(be.startsWith("event: "))continue;if(be.startsWith("data: ")){let Be=be.slice(5).trim();if(Be==="[DONE]"){O=!0,ne.enqueue(R.encode(`data: [DONE]
|
|
637
637
|
|
|
@@ -948,7 +948,7 @@ ${R.content}`),delete R.thinking)});let F=p.messages[p.messages.length-1];return
|
|
|
948
948
|
error: ${x.message}
|
|
949
949
|
stack: ${x.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(p){this.logger.error(`TransformerService init error: ${p.message}
|
|
950
950
|
Stack: ${p.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(PQ).forEach(p=>{if("TransformerName"in p&&typeof p.TransformerName=="string")this.registerTransformer(p.TransformerName,p);else{let x=new p;x&&typeof x=="object"&&(x.logger=this.logger),this.registerTransformer(x.name,x)}})}catch(p){this.logger.error({error:p},"transformer regist error:")}}async loadFromConfig(){let p=this.configService.get("transformers",[]);for(let x of p)await this.registerTransformerFromConfig(x)}},MQ=Mp(),nw=class{type="tiktoken";name;encoding;constructor(p="cl100k_base"){this.name=`tiktoken-${p}`;try{this.encoding=(0,MQ.get_encoding)(p)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${p}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(p){let x=this.encoding;if(!x)throw new Error("Encoding not initialized");let F=0,{messages:R,system:M,tools:O}=p;return Array.isArray(R)&&R.forEach(G=>{typeof G.content=="string"?F+=x.encode(G.content).length:Array.isArray(G.content)&&G.content.forEach(J=>{if(J.type==="text")F+=x.encode(J.text).length;else if(J.type==="tool_use")F+=x.encode(JSON.stringify(J.input)).length;else if(J.type==="tool_result"){let ne=typeof J.content=="string"?J.content:JSON.stringify(J.content);F+=x.encode(ne).length}})}),typeof M=="string"?F+=x.encode(M).length:Array.isArray(M)&&M.forEach(G=>{G.type==="text"&&(typeof G.text=="string"?F+=x.encode(G.text).length:Array.isArray(G.text)&&G.text.forEach(J=>{F+=x.encode(J||"").length}))}),O&&O.forEach(G=>{G.description&&(F+=x.encode(G.name+G.description).length),G.input_schema&&(F+=x.encode(JSON.stringify(G.input_schema)).length)}),F}isInitialized(){return this.encoding!==void 0}encodeText(p){let x=this.encoding;if(!x)throw new Error("Encoding not initialized");return Array.from(x.encode(p))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}},h0=require("path"),UQ=require("os"),f0=require("fs"),A0=require("fs"),$Q=class{constructor(p){this.trie=this._build_trie(p)}_build_trie(p){let x=Object.create(null);for(let F of p){let R=x;for(let M=0;M<F.length;++M){let O=F[M];R=R[O]??=Object.create(null)}R.end=F}return x}split(p){let x=[],F=p.length,R=0,M=0;for(;M<F;){let O=this.trie,G=null,J=M;for(;J<F&&(O=O[p[J]]);)O.end&&(G=O.end),++J;G?(M>R&&x.push(p.slice(R,M)),x.push(G),M+=G.length,R=M):++M}return R<F&&x.push(p.slice(R)),x}},jQ=$Q,HQ=class{constructor(p){this.content=p.content,this.id=p.id,this.single_word=p.single_word??!1,this.lstrip=p.lstrip??!1,this.rstrip=p.rstrip??!1,this.special=p.special??!1,this.normalized=p.normalized??null}},qQ=HQ,iw=(()=>{let p=[...Array.from({length:94},(M,O)=>O+33),...Array.from({length:12},(M,O)=>O+161),...Array.from({length:82},(M,O)=>O+174)],x=p.slice(),F=0;for(let M=0;M<256;++M)p.includes(M)||(p.push(M),x.push(256+F),F+=1);let R=x.map(M=>String.fromCharCode(M));return Object.fromEntries(p.map((M,O)=>[M,R[O]]))})(),GQ=p=>Object.fromEntries(Object.entries(p).map(([x,F])=>[F,x])),VQ=GQ(iw),ow=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",JQ=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${ow}])]+`,` ?[^\\s${ow}]+`]]),uf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",IW=new RegExp(`^[${uf}]+$`,"gu"),$m=p=>p.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),p0=(p,x=!0)=>{if(p.Regex!==void 0){let F=p.Regex.replace(/\\([#&~])/g,"$1");for(let[R,M]of JQ)F=F.replaceAll(R,M);return new RegExp(F,"gu")}else if(p.String!==void 0){let F=YQ(p.String);return new RegExp(x?F:`(${F})`,"gu")}else return console.warn("Unknown pattern type:",p),null},YQ=p=>p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),zQ=(p,x,F)=>{let R=[],M=0;for(;M<p.length;){if(R.push(p[M]),(x.get(p[M])??F)!==F){++M;continue}for(;++M<p.length&&(x.get(p[M])??F)===F;)x.get(R.at(-1))!==F&&(R[R.length-1]+=p[M])}return R},WQ=p=>p>=19968&&p<=40959||p>=13312&&p<=19903||p>=131072&&p<=173791||p>=173824&&p<=177983||p>=177984&&p<=178207||p>=178208&&p<=183983||p>=63744&&p<=64255||p>=194560&&p<=195103,KQ=p=>Number.isInteger(p)||typeof p=="bigint",ZQ=p=>{let x=0;for(let F of p)++x;return x},XQ=p=>sw(p.toLowerCase()),qs=(...p)=>Array.prototype.concat.apply([],p),jm=p=>new Map(Object.entries(p)),eN=(p,x)=>{let F=[],R=0;for(let M of p.matchAll(x)){let O=M[0];R<M.index&&F.push(p.slice(R,M.index)),O.length>0&&F.push(O),R=M.index+O.length}return R<p.length&&F.push(p.slice(R)),F},sw=p=>p.replace(new RegExp("\\p{M}","gu"),""),aw=(p,x,F=[])=>{if(!p||Array.isArray(p)||typeof p!="object")return`${x} must be a valid object`;for(let R of F)if(!(R in p))return`${x} must contain a "${R}" property`;return null},tN=p=>p.match(/\S+/g)||[],rN=class{constructor(){let p=function(...x){return p._call(...x)};return Object.setPrototypeOf(p,new.target.prototype)}},lf=rN,nN=class extends lf{constructor(p){super(),this.config=p}_call(p){return this.normalize(p)}},Qu=nN,iN=class extends Qu{tokenize_chinese_chars(p){let x=[];for(let F=0;F<p.length;++F){let R=p[F],M=R.charCodeAt(0);WQ(M)?(x.push(" "),x.push(R),x.push(" ")):x.push(R)}return x.join("")}strip_accents(p){return p.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(p){switch(p){case" ":case`
|
|
951
|
-
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(p)}}clean_text(p){let x=[];for(let F of p){let R=F.charCodeAt(0);R===0||R===65533||this.is_control(F)||(/^\s$/.test(F)?x.push(" "):x.push(F))}return x.join("")}normalize(p){return this.config.clean_text&&(p=this.clean_text(p)),this.config.handle_chinese_chars&&(p=this.tokenize_chinese_chars(p)),this.config.lowercase?(p=p.toLowerCase(),this.config.strip_accents!==!1&&(p=this.strip_accents(p))):this.config.strip_accents&&(p=this.strip_accents(p)),p}},oN=iN,sN=class extends Qu{constructor(p){super(p),this.charsmap=p.precompiled_charsmap??null}normalize(p){return p=p.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),p=p.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),p.includes("\uFF5E")?p=p.split("\uFF5E").map(x=>x.normalize("NFKC")).join("\uFF5E"):p=p.normalize("NFKC"),p}},aN=sN,uN=class extends Qu{constructor(p){super(p),this.normalizers=(p.normalizers??[]).map(x=>uw(x))}normalize(p){return this.normalizers.reduce((x,F)=>F?F.normalize(x):x,p)}},lN=uN,cN=class extends Qu{normalize(p){let x=p0(this.config.pattern??{});return x===null?p:p.replaceAll(x,this.config.content??"")}},dN=cN,hN=class extends Qu{constructor(){super(...arguments),this.form="NFC"}normalize(p){return p=p.normalize(this.form),p}},g0=hN,fN=class extends g0{constructor(){super(...arguments),this.form="NFC"}},AN=fN,pN=class extends g0{constructor(){super(...arguments),this.form="NFD"}},gN=pN,mN=class extends g0{constructor(){super(...arguments),this.form="NFKC"}},EN=mN,yN=class extends g0{constructor(){super(...arguments),this.form="NFKD"}},CN=yN,DN=class extends Qu{normalize(p){return this.config.strip_left&&this.config.strip_right?p=p.trim():(this.config.strip_left&&(p=p.trimStart()),this.config.strip_right&&(p=p.trimEnd())),p}},bN=DN,wN=class extends Qu{normalize(p){return sw(p)}},IN=wN,vN=class extends Qu{normalize(p){return p.toLowerCase()}},BN=vN,xN=class extends Qu{normalize(p){return p=this.config.prepend+p,p}},_N=xN;function SN(p){if(p===null)return null;switch(p.type){case"BertNormalizer":return new oN(p);case"Precompiled":return new aN(p);case"Sequence":return new lN(p);case"Replace":return new dN(p);case"NFC":return new AN(p);case"NFD":return new gN(p);case"NFKC":return new EN(p);case"NFKD":return new CN(p);case"Strip":return new bN(p);case"StripAccents":return new IN(p);case"Lowercase":return new BN(p);case"Prepend":return new _N(p);default:throw new Error(`Unknown Normalizer type: ${p.type}`)}}var uw=SN,FN=class extends lf{pre_tokenize(p,x){return(Array.isArray(p)?p.map(F=>this.pre_tokenize_text(F,x)):this.pre_tokenize_text(p,x)).flat()}_call(p,x){return this.pre_tokenize(p,x)}},Za=FN,kN=class extends Za{constructor(p){super(),this.config=p,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=iw,this.text_encoder=new TextEncoder}pre_tokenize_text(p,x){return this.add_prefix_space&&!p.startsWith(" ")&&(p=" "+p),(this.use_regex?p.match(this.pattern)||[]:[p]).map(F=>Array.from(this.text_encoder.encode(F),R=>this.byte_encoder[R]).join(""))}},TN=kN,RN=class extends Za{pre_tokenize_text(p,x){return p.match(/\w+|[^\w\s]+/g)||[]}},QN=RN,NN=class extends Za{constructor(p){super(),this.replacement=p.replacement??"\u2581",this.str_rep=p.str_rep||this.replacement,this.prepend_scheme=p.prepend_scheme??"always"}pre_tokenize_text(p,x){let{section_index:F=void 0}=x??{},R=p.replaceAll(" ",this.str_rep);return!R.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&F===0)&&(R=this.str_rep+R),[R]}},ON=NN,LN=class extends Za{constructor(p){super(),this.config=p,this.pattern=p0(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(p){return this.pattern===null?[]:this.config.invert?p.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?p.split(this.pattern).filter(x=>x):eN(p,this.pattern)}},PN=LN,MN=class extends Za{constructor(p){super(),this.config=p,this.pattern=new RegExp(`[^${uf}]+|[${uf}]+`,"gu")}pre_tokenize_text(p){return p.match(this.pattern)||[]}},UN=MN,$N=class extends Za{constructor(p){super(),this.config=p;let x=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(x,"gu")}pre_tokenize_text(p){return p.match(this.pattern)||[]}},jN=$N,HN=class extends Za{constructor(){super(),this.pattern=new RegExp(`[^\\s${uf}]+|[${uf}]`,"gu")}pre_tokenize_text(p,x){return p.trim().match(this.pattern)||[]}},qN=HN,GN=class extends Za{constructor(p){super(),this.config=p,this.pattern=p0(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(p){return this.pattern===null?[p]:[p.replaceAll(this.pattern,this.config.content??"")]}},VN=GN,JN=class extends Za{constructor(p){super(),this.tokenizers=(p.pretokenizers??[]).map(x=>lw(x))}pre_tokenize_text(p,x){return this.tokenizers.reduce((F,R)=>R?R.pre_tokenize(F,x):F,[p])}},YN=JN,zN=class extends Za{pre_tokenize_text(p){return tN(p)}},WN=zN;function KN(p){if(p===null)return null;switch(p.type){case"BertPreTokenizer":return new qN;case"Sequence":return new YN(p);case"Whitespace":return new QN;case"WhitespaceSplit":return new WN;case"Metaspace":return new ON(p);case"ByteLevel":return new TN(p);case"Split":return new PN(p);case"Punctuation":return new UN(p);case"Digits":return new jN(p);case"Replace":return new VN(p);default:throw new Error(`Unknown PreTokenizer type: ${p.type}`)}}var lw=KN,ZN=class extends lf{constructor(p){super(),this.config=p,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(p){let x=this.encode(p);return this.fuse_unk&&(x=zQ(x,this.tokens_to_ids,this.unk_token_id)),x}convert_tokens_to_ids(p){return p.map(x=>this.tokens_to_ids.get(x)??this.unk_token_id)}convert_ids_to_tokens(p){return p.map(x=>this.vocab[Number(x)]??this.unk_token)}},m0=ZN,XN=class extends m0{constructor(p){super(p),this.max_input_chars_per_word=100,this.tokens_to_ids=jm(p.vocab),this.unk_token_id=this.tokens_to_ids.get(p.unk_token),this.unk_token=p.unk_token,this.max_input_chars_per_word=p.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[x,F]of this.tokens_to_ids)this.vocab[F]=x}encode(p){let x=[];for(let F of p){let R=[...F];if(R.length>this.max_input_chars_per_word){x.push(this.unk_token);continue}let M=!1,O=0,G=[];for(;O<R.length;){let J=R.length,ne=null;for(;O<J;){let z=R.slice(O,J).join("");if(O>0&&(z=this.config.continuing_subword_prefix+z),this.tokens_to_ids.has(z)){ne=z;break}--J}if(ne===null){M=!0;break}G.push(ne),O=J}M?x.push(this.unk_token):x.push(...G)}return x}},cw=XN,dw=class E_{constructor(x,F){this.is_leaf=x,this.children=F}static default(){return new E_(!1,new Map)}},eO=class{constructor(){this.root=dw.default()}extend(p){for(let x of p)this.push(x)}push(p){let x=this.root;for(let F of p){let R=x.children.get(F);R===void 0&&(R=dw.default(),x.children.set(F,R)),x=R}x.is_leaf=!0}*common_prefix_search(p){let x=this.root;if(x===void 0)return;let F="";for(let R of p){if(F+=R,x=x.children.get(R),x===void 0)return;x.is_leaf&&(yield F)}}},tO=eO,Hm=class y_{constructor(x,F,R,M,O){this.token_id=x,this.node_id=F,this.pos=R,this.length=M,this.score=O,this.prev=null,this.backtrace_score=0}clone(){let x=new y_(this.token_id,this.node_id,this.pos,this.length,this.score);return x.prev=this.prev,x.backtrace_score=this.backtrace_score,x}},rO=class{constructor(p,x,F){this.chars=Array.from(p),this.len=this.chars.length,this.bos_token_id=x,this.eos_token_id=F,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let R=new Hm(this.bos_token_id??0,0,0,0,0),M=new Hm(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(R.clone()),this.nodes.push(M.clone()),this.begin_nodes[this.len].push(M),this.end_nodes[0].push(R)}insert(p,x,F,R){let M=this.nodes.length,O=new Hm(R,M,p,x,F);this.begin_nodes[p].push(O),this.end_nodes[p+x].push(O),this.nodes.push(O)}viterbi(){let p=this.len,x=0;for(;x<=p;){if(this.begin_nodes[x].length==0)return[];for(let O of this.begin_nodes[x]){O.prev=null;let G=0,J=null;for(let ne of this.end_nodes[x]){let z=ne.backtrace_score+O.score;(J===null||z>G)&&(J=ne.clone(),G=z)}if(J!==null)O.prev=J,O.backtrace_score=G;else return[]}++x}let F=[],R=this.begin_nodes[p][0].prev;if(R===null)return[];let M=R.clone();for(;M.prev!==null;)F.push(M.clone()),M=M.clone().prev.clone();return F.reverse(),F}piece(p){return this.chars.slice(p.pos,p.pos+p.length).join("")}tokens(){return this.viterbi().map(p=>this.piece(p))}token_ids(){return this.viterbi().map(p=>p.token_id)}},nO=rO;function iO(p){if(p.length===0)throw new Error("Array must not be empty");let x=p[0],F=0;for(let R=1;R<p.length;++R)p[R]<x&&(x=p[R],F=R);return[x,F]}var oO=class extends m0{constructor(p,x){super(p);let F=p.vocab.length;this.vocab=new Array(F),this.scores=new Array(F);for(let R=0;R<F;++R)[this.vocab[R],this.scores[R]]=p.vocab[R];this.unk_token_id=p.unk_id,this.unk_token=this.vocab[p.unk_id],this.tokens_to_ids=new Map(this.vocab.map((R,M)=>[R,M])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=x,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=iO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new tO,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(p){let x=p.chars,F=1,R=0;for(;R<x.length;){let M=!1,O=[],G=x.slice(R).join(""),J=this.trie.common_prefix_search(G);for(let ne of J){O.push(ne);let z=this.tokens_to_ids.get(ne),te=this.scores[z],ie=ZQ(ne);p.insert(R,ie,te,z),!M&&ie===F&&(M=!0)}M||p.insert(R,F,this.unk_score,this.unk_token_id),R+=F}}tokenize(p){let x=new nO(p,this.bos_token_id,this.eos_token_id);return this.populate_nodes(x),x.tokens()}encode(p){let x=[];for(let F of p){let R=this.tokenize(F);x.push(...R)}return x}},hw=oO,sO=class{constructor(p=(F,R)=>F>R,x=1/0){this._heap=[],this._comparator=p,this._max_size=x}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...p){return this.extend(p)}extend(p){for(let x of p)if(this.size<this._max_size)this._heap.push(x),this._sift_up();else{let F=this._smallest();this._comparator(x,this._heap[F])&&(this._heap[F]=x,this._sift_up_from(F))}return this.size}pop(){let p=this.peek(),x=this.size-1;return x>0&&this._swap(0,x),this._heap.pop(),this._sift_down(),p}replace(p){let x=this.peek();return this._heap[0]=p,this._sift_down(),x}_parent(p){return(p+1>>>1)-1}_left(p){return(p<<1)+1}_right(p){return p+1<<1}_greater(p,x){return this._comparator(this._heap[p],this._heap[x])}_swap(p,x){let F=this._heap[p];this._heap[p]=this._heap[x],this._heap[x]=F}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(p){for(;p>0&&this._greater(p,this._parent(p));)this._swap(p,this._parent(p)),p=this._parent(p)}_sift_down(){let p=0;for(;this._left(p)<this.size&&this._greater(this._left(p),p)||this._right(p)<this.size&&this._greater(this._right(p),p);){let x=this._right(p)<this.size&&this._greater(this._right(p),this._left(p))?this._right(p):this._left(p);this._swap(p,x),p=x}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},aO=sO,uO=class{constructor(p){this.capacity=p,this.cache=new Map}get(p){if(!this.cache.has(p))return;let x=this.cache.get(p);return this.cache.delete(p),this.cache.set(p,x),x}put(p,x){this.cache.has(p)&&this.cache.delete(p),this.cache.set(p,x),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},lO=uO,cO=class extends m0{constructor(p){super(p),this.tokens_to_ids=jm(p.vocab),this.unk_token_id=this.tokens_to_ids.get(p.unk_token),this.unk_token=p.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[F,R]of this.tokens_to_ids)this.vocab[R]=F;let x=Array.isArray(p.merges[0]);this.merges=x?p.merges:p.merges.map(F=>F.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((F,R)=>[JSON.stringify(F),R])),this.end_of_word_suffix=p.end_of_word_suffix,this.continuing_subword_suffix=p.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new lO(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(p){if(p.length===0)return[];let x=this.cache.get(p);if(x!==void 0)return x;let F=Array.from(p);this.end_of_word_suffix&&(F[F.length-1]+=this.end_of_word_suffix);let R=[];if(F.length>1){let M=new aO((J,ne)=>J.score<ne.score),O={token:F[0],bias:0,prev:null,next:null},G=O;for(let J=1;J<F.length;++J){let ne={bias:J/F.length,token:F[J],prev:G,next:null};G.next=ne,this.add_node(M,G),G=ne}for(;!M.is_empty();){let J=M.pop();if(J.deleted||!J.next||J.next.deleted)continue;if(J.deleted=!0,J.next.deleted=!0,J.prev){let z={...J.prev};J.prev.deleted=!0,J.prev=z,z.prev?z.prev.next=z:O=z}let ne={token:J.token+J.next.token,bias:J.bias,prev:J.prev,next:J.next.next};ne.prev?(ne.prev.next=ne,this.add_node(M,ne.prev)):O=ne,ne.next&&(ne.next.prev=ne,this.add_node(M,ne))}for(let J=O;J!==null;J=J.next)R.push(J.token)}else R=F;if(this.continuing_subword_suffix)for(let M=0;M<R.length-1;++M)R[M]+=this.continuing_subword_suffix;return p.length<this.max_length_to_cache&&this.cache.put(p,R),R}add_node(p,x){let F=this.bpe_ranks.get(JSON.stringify([x.token,x.next.token]));F!==void 0&&(x.score=F+x.bias,p.push(x))}encode(p){let x=[];for(let F of p){if(this.ignore_merges&&this.tokens_to_ids.has(F)){x.push(F);continue}let R=this.bpe(F);for(let M of R)if(this.tokens_to_ids.has(M))x.push(M);else if(this.byte_fallback){let O=Array.from(this.text_encoder.encode(M)).map(G=>`<0x${G.toString(16).toUpperCase().padStart(2,"0")}>`);O.every(G=>this.tokens_to_ids.has(G))?x.push(...O):x.push(this.unk_token)}else x.push(this.unk_token)}return x}},fw=cO,dO=class extends m0{constructor(p,x){super(p);let F=p.vocab;this.tokens_to_ids=jm(x.target_lang?F[x.target_lang]:F),this.bos_token=x.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=x.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=x.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=x.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[R,M]of this.tokens_to_ids)this.vocab[M]=R}encode(p){return p}},hO=dO;function fO(p,x){switch(p.type){case"WordPiece":return new cw(p);case"Unigram":return new hw(p,x.eos_token);case"BPE":return new fw(p);default:if(p.vocab)return Array.isArray(p.vocab)?new hw(p,x.eos_token):Object.hasOwn(p,"continuing_subword_prefix")&&Object.hasOwn(p,"unk_token")?Object.hasOwn(p,"merges")?new fw(p):new cw(p):new hO(p,{target_lang:x.target_lang,bos_token:x.bos_token,eos_token:x.eos_token,pad_token:x.pad_token,unk_token:x.unk_token});throw new Error(`Unknown TokenizerModel type: ${p?.type}`)}}var AO=fO,pO=class extends lf{constructor(p){super(),this.config=p}_call(p,...x){return this.post_process(p,...x)}},cf=pO,gO=class extends cf{post_process(p,x=null,F=!0){let R=x===null?this.config.single:this.config.pair,M=[],O=[];for(let G of R)"SpecialToken"in G?F&&(M.push(G.SpecialToken.id),O.push(G.SpecialToken.type_id)):"Sequence"in G&&(G.Sequence.id==="A"?(M=qs(M,p),O=qs(O,new Array(p.length).fill(G.Sequence.type_id))):G.Sequence.id==="B"&&(M=qs(M,x),O=qs(O,new Array(x.length).fill(G.Sequence.type_id))));return{tokens:M,token_type_ids:O}}},mO=gO,EO=class extends cf{post_process(p,x=null){return{tokens:x?qs(p,x):p}}},yO=EO,CO=class extends cf{constructor(p){super(p),this.sep=p.sep,this.cls=p.cls}post_process(p,x=null,F=!0){F&&(p=qs([this.cls[0]],p,[this.sep[0]]));let R=new Array(p.length).fill(0);if(x){let M=[],O=F?[this.sep[0]]:[];p=qs(p,M,x,O),R=qs(R,new Array(x.length+M.length+O.length).fill(1))}return{tokens:p,token_type_ids:R}}},DO=CO,bO=class extends cf{constructor(p){super(p),this.sep=p.sep,this.cls=p.cls}post_process(p,x,F=!0){F&&(p=qs([this.cls[0]],p,[this.sep[0]]));let R=new Array(p.length).fill(0);if(x){let M=F?[this.sep[0]]:[],O=F?[this.sep[0]]:[];p=qs(p,M,x,O),R=qs(R,new Array(x.length+M.length+O.length).fill(1))}return{tokens:p,token_type_ids:R}}},wO=bO,IO=class extends cf{constructor(p){super(p),this.processors=(p.processors??[]).map(x=>Aw(x))}post_process(p,x=null,F=!0){let R={tokens:p};for(let M of this.processors)R=M.post_process(R.tokens,x,F);return R}},vO=IO;function BO(p){if(p===null)return null;switch(p.type){case"TemplateProcessing":return new mO(p);case"ByteLevel":return new yO(p);case"BertProcessing":return new DO(p);case"RobertaProcessing":return new wO(p);case"Sequence":return new vO(p);default:throw new Error(`Unknown PostProcessor type: ${p.type}`)}}var Aw=BO,xO=class extends lf{constructor(p){super(),this.config=p,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in p?p.trim_offsets:!1}_call(p){return this.decode(p)}decode(p){return this.decode_chain(p).join("")}},Xa=xO,_O=class extends Xa{constructor(p){super(p),this.byte_decoder=VQ,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(p){let x=p.join(""),F=new Uint8Array([...x].map(R=>this.byte_decoder[R]));return this.text_decoder.decode(F)}decode_chain(p){let x=[],F=[];for(let R of p)this.added_tokens.find(M=>M.content===R)!==void 0?(F.length>0&&(x.push(this.convert_tokens_to_string(F)),F=[]),x.push(R)):F.push(R);return F.length>0&&x.push(this.convert_tokens_to_string(F)),x}},SO=_O,FO=class extends Xa{constructor(p){super(p),this.cleanup=p.cleanup}decode_chain(p){return p.map((x,F)=>{if(F!==0){let R=this.config.prefix;R&&x.startsWith(R)?x=x.replace(R,""):x=" "+x}return this.cleanup&&(x=$m(x)),x})}},kO=FO,TO=class extends Xa{constructor(p){super(p),this.replacement=p.replacement??"\u2581"}decode_chain(p){let x=[];for(let F=0;F<p.length;++F){let R=p[F].replaceAll(this.replacement," ");F==0&&R.startsWith(" ")&&(R=R.substring(1)),x.push(R)}return x}},RO=TO,QO=class extends Xa{constructor(p){super(p),this.suffix=p.suffix??""}decode_chain(p){return p.map((x,F)=>x.replaceAll(this.suffix,F===p.length-1?"":" "))}},NO=QO,OO=class extends Xa{constructor(p){super(p),this.pad_token=p.pad_token??"",this.word_delimiter_token=p.word_delimiter_token??"",this.cleanup=p.cleanup}convert_tokens_to_string(p){if(p.length===0)return"";let x=[p[0]];for(let R=1;R<p.length;++R)p[R]!==x.at(-1)&&x.push(p[R]);let F=x.filter(R=>R!==this.pad_token).join("");return this.cleanup&&(F=$m(F).replaceAll(this.word_delimiter_token," ").trim()),F}decode_chain(p){return[this.convert_tokens_to_string(p)]}},LO=OO,PO=class extends Xa{constructor(p){super(p),this.decoders=(p.decoders??[]).map(x=>pw(x))}decode_chain(p){return this.decoders.reduce((x,F)=>F.decode_chain(x),p)}},MO=PO,UO=class extends Xa{decode_chain(p){let x=p0(this.config.pattern),F=this.config.content??"";return x===null?p:p.map(R=>R.replaceAll(x,F))}},$O=UO,jO=class extends Xa{decode_chain(p){return[p.join("")]}},HO=jO,qO=class extends Xa{constructor(p){super(p),this.content=p.content??"",this.start=p.start??0,this.stop=p.stop??0}decode_chain(p){return p.map(x=>{let F=0;for(let M=0;M<this.start&&x[M]===this.content;++M)F=M+1;let R=x.length;for(let M=0;M<this.stop;++M){let O=x.length-M-1;if(x[O]===this.content){R=O;continue}else break}return x.slice(F,R)})}},GO=qO,VO=class extends Xa{constructor(p){super(p),this.text_decoder=new TextDecoder}decode_chain(p){let x=[],F=[];for(let R of p){let M=null;if(R.length===6&&R.startsWith("<0x")&&R.endsWith(">")){let O=parseInt(R.slice(3,5),16);isNaN(O)||(M=O)}if(M!==null)F.push(M);else{if(F.length>0){let O=this.text_decoder.decode(Uint8Array.from(F));x.push(O),F=[]}x.push(R)}}if(F.length>0){let R=this.text_decoder.decode(Uint8Array.from(F));x.push(R),F=[]}return x}},JO=VO;function YO(p){if(p===null)return null;switch(p.type){case"ByteLevel":return new SO(p);case"WordPiece":return new kO(p);case"Metaspace":return new RO(p);case"BPEDecoder":return new NO(p);case"CTC":return new LO(p);case"Sequence":return new MO(p);case"Replace":return new $O(p);case"Fuse":return new HO(p);case"Strip":return new GO(p);case"ByteFallback":return new JO(p);default:throw new Error(`Unknown Decoder type: ${p.type}`)}}var pw=YO,zO=class{constructor(p,x){let F=aw(p,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(F)throw new Error(F);let R=aw(x,"Config");if(R)throw new Error(R);this.tokenizer=p,this.config=x,this.normalizer=uw(this.tokenizer.normalizer),this.pre_tokenizer=lw(this.tokenizer.pre_tokenizer),this.model=AO(this.tokenizer.model,this.config),this.post_processor=Aw(this.tokenizer.post_processor),this.decoder=pw(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(M=>{let O=new qQ(M);this.added_tokens.push(O),this.model.tokens_to_ids.set(O.content,O.id),this.model.vocab[O.id]=O.content,O.special&&(this.special_tokens.push(O.content),this.all_special_ids.push(O.id))}),(this.config.additional_special_tokens??[]).forEach(M=>{this.special_tokens.includes(M)||this.special_tokens.push(M)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new jQ(this.added_tokens.map(M=>M.content)),this.added_tokens_map=new Map(this.added_tokens.map(M=>[M.content,M])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(p,{text_pair:x=null,add_special_tokens:F=!0,return_token_type_ids:R=null}={}){let{tokens:M,token_type_ids:O}=this.tokenize_helper(p,{text_pair:x,add_special_tokens:F}),G=this.model.convert_tokens_to_ids(M),J={ids:G,tokens:M,attention_mask:new Array(G.length).fill(1)};return R&&O&&(J.token_type_ids=O),J}decode(p,x={}){if(!Array.isArray(p)||p.length===0||!KQ(p[0]))throw Error("token_ids must be a non-empty array of integers.");let F=this.model.convert_ids_to_tokens(p);x.skip_special_tokens&&(F=F.filter(M=>!this.special_tokens.includes(M)));let R=this.decoder?this.decoder(F):F.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(R=R.replaceAll(this.decoder.end_of_word_suffix," "),x.skip_special_tokens&&(R=R.trim())),(x.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(R=$m(R)),R}tokenize(p,{text_pair:x=null,add_special_tokens:F=!1}={}){return this.tokenize_helper(p,{text_pair:x,add_special_tokens:F}).tokens}encode_text(p){if(p===null)return null;let x=this.added_tokens_splitter.split(p);return x.forEach((F,R)=>{let M=this.added_tokens_map.get(F);M&&(M.lstrip&&R>0&&(x[R-1]=x[R-1].trimEnd()),M.rstrip&&R<x.length-1&&(x[R+1]=x[R+1].trimStart()))}),x.flatMap((F,R)=>{if(F.length===0)return[];if(this.added_tokens_map.has(F))return[F];if(this.remove_space===!0&&(F=F.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(F=XQ(F)),this.normalizer!==null&&(F=this.normalizer(F)),F.length===0)return[];let M=this.pre_tokenizer!==null?this.pre_tokenizer(F,{section_index:R}):[F];return this.model(M)})}tokenize_helper(p,{text_pair:x=null,add_special_tokens:F=!0}){let R=this.encode_text(p),M=this.encode_text(x||null);return this.post_processor?this.post_processor(R,M,F):{tokens:qs(R??[],M??[])}}token_to_id(p){return this.model.tokens_to_ids.get(p)}id_to_token(p){return this.model.vocab[p]}get_added_tokens_decoder(){let p=new Map;for(let x of this.added_tokens)p.set(x.id,x);return p}},WO=zO,KO=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(p,x,F={}){this.modelId=p,this.logger=x,this.options=F,this.cacheDir=F.cacheDir||(0,h0.join)((0,UQ.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=p.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${p.split("/").pop()}`}getCachePaths(){let p=(0,h0.join)(this.cacheDir,this.safeModelName);return{modelDir:p,tokenizerJson:(0,h0.join)(p,"tokenizer.json"),tokenizerConfig:(0,h0.join)(p,"tokenizer_config.json")}}ensureDir(p){(0,f0.existsSync)(p)||(0,f0.mkdirSync)(p,{recursive:!0})}async loadFromCache(){try{let p=this.getCachePaths();if(!(0,f0.existsSync)(p.tokenizerJson)||!(0,f0.existsSync)(p.tokenizerConfig))return null;let[x,F]=await Promise.all([A0.promises.readFile(p.tokenizerJson,"utf-8"),A0.promises.readFile(p.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(x),tokenizerConfig:JSON.parse(F)}}catch(p){return this.logger?.warn(`Failed to load from cache: ${p.message}`),null}}async downloadAndCache(){let p=this.getCachePaths(),x={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 F=new AbortController,R=setTimeout(()=>F.abort(),this.options.timeout||3e4);try{let[M,O]=await Promise.all([fetch(x.json,{signal:F.signal}),fetch(x.config,{signal:F.signal})]);if(!M.ok)throw new Error(`Failed to fetch tokenizer.json: ${M.statusText}`);let[G,J]=await Promise.all([M.json(),O.ok?O.json():Promise.resolve({})]);return this.ensureDir(p.modelDir),await Promise.all([A0.promises.writeFile(p.tokenizerJson,JSON.stringify(G,null,2)),A0.promises.writeFile(p.tokenizerConfig,JSON.stringify(J,null,2))]),{tokenizerJson:G,tokenizerConfig:J}}finally{clearTimeout(R)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let p=this.getCachePaths();this.ensureDir(this.cacheDir);let x=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new WO(x.tokenizerJson,x.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(p){throw this.logger?.error(`Failed to initialize tokenizer: ${p.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${p.message}`)}}async countTokens(p){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let x=this.extractTextFromRequest(p);return this.tokenizer.encode(x).ids.length}catch(x){throw this.logger?.error(`Error counting tokens: ${x.message}`),x}}isInitialized(){return this.tokenizer!==null}encodeText(p){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(p).ids}dispose(){this.tokenizer=null}extractTextFromRequest(p){let x=[],{messages:F,system:R,tools:M}=p;if(Array.isArray(F)){for(let O of F)if(typeof O.content=="string")x.push(O.content);else if(Array.isArray(O.content))for(let G of O.content)G.type==="text"&&G.text?x.push(G.text):G.type==="tool_use"&&G.input?x.push(JSON.stringify(G.input)):G.type==="tool_result"&&x.push(typeof G.content=="string"?G.content:JSON.stringify(G.content))}if(typeof R=="string")x.push(R);else if(Array.isArray(R)){for(let O of R)if(O.type==="text"){if(typeof O.text=="string")x.push(O.text);else if(Array.isArray(O.text))for(let G of O.text)G&&x.push(G)}}if(M)for(let O of M)O.name&&x.push(O.name),O.description&&x.push(O.description),O.input_schema&&x.push(JSON.stringify(O.input_schema));return x.join(" ")}},ZO=class{type="api";name;config;logger;options;constructor(p,x,F={}){if(!p.url||!p.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:p.url,apiKey:p.apiKey,requestFormat:p.requestFormat||"standard",responseField:p.responseField||"token_count",headers:p.headers||{}},this.logger=x,this.options=F;try{let R=new URL(p.url);this.name=`api-${R.hostname}`}catch{this.name=`api-${p.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(p){try{let x=this.formatRequestBody(p),F={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},R=new AbortController,M=setTimeout(()=>R.abort(),this.options.timeout||3e4),O=await fetch(this.config.url,{method:"POST",headers:F,body:JSON.stringify(x),signal:R.signal});if(clearTimeout(M),!O.ok)throw new Error(`API tokenizer request failed: ${O.status} ${O.statusText}`);let G=await O.json();return this.extractTokenCount(G)}catch(x){throw x.name==="AbortError"?new Error("API tokenizer request timed out"):x}}isInitialized(){return!0}dispose(){}formatRequestBody(p){switch(this.config.requestFormat){case"standard":return p;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(p)};case"anthropic":return{messages:p.messages||[],system:p.system,tools:p.tools};case"custom":return{text:this.extractConcatenatedText(p)};default:return p}}extractMessagesAsOpenAIFormat(p){return p.messages?p.messages.map(x=>({role:x.role,content:this.extractTextFromMessage(x)})):[]}extractTextFromMessage(p){return typeof p.content=="string"?p.content:Array.isArray(p.content)?p.content.map(x=>x.type==="text"&&x.text?x.text:x.type==="tool_use"&&x.input?JSON.stringify(x.input):x.type==="tool_result"?typeof x.content=="string"?x.content:JSON.stringify(x.content):"").join(" "):""}extractConcatenatedText(p){let x=[];return p.messages&&p.messages.forEach(F=>{x.push(this.extractTextFromMessage(F))}),typeof p.system=="string"?x.push(p.system):Array.isArray(p.system)&&p.system.forEach(F=>{F.type==="text"&&(typeof F.text=="string"?x.push(F.text):Array.isArray(F.text)&&F.text.forEach(R=>{R&&x.push(R)}))}),p.tools&&p.tools.forEach(F=>{F.name&&x.push(F.name),F.description&&x.push(F.description),F.input_schema&&x.push(JSON.stringify(F.input_schema))}),x.join(" ")}extractTokenCount(p){try{let x=this.config.responseField,F=x.split("."),R=p;for(let M of F){if(R==null)throw new Error(`Field path '${x}' not found in response`);R=R[M]}if(typeof R!="number")throw new Error(`Expected number at field path '${x}', got ${typeof R}`);return R}catch(x){throw this.logger?.error(`Failed to extract token count from API response: ${x.message}. Response: ${JSON.stringify(p)}`),new Error(`Invalid response from API tokenizer: ${x.message}`)}}},qm=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(p,x,F={}){this.configService=p,this.logger=x,this.options={timeout:F.timeout??3e4,...F}}async initialize(){try{this.fallbackTokenizer=new nw("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(p){throw this.logger?.error(`TokenizerService initialization error: ${p.message}`),p}}async getTokenizer(p){let x=this.getCacheKey(p);if(this.tokenizers.has(x))return this.tokenizers.get(x);let F;try{switch(p.type){case"tiktoken":F=new nw(p.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${p.model}`),F=new KO(p.model,this.logger,{timeout:this.options.timeout});break;case"api":F=new ZO(p,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${p.type}`)}return this.logger?.info(`Calling initialize() on ${p.type} tokenizer...`),await F.initialize(),this.tokenizers.set(x,F),this.logger?.info(`Tokenizer initialized successfully: ${p.type} (${x})`),F}catch(R){return this.logger?.error(`Failed to initialize ${p.type} tokenizer: ${R.message}`),this.logger?.error(`Error stack: ${R.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(p,x){let F=x?await this.getTokenizer(x):this.fallbackTokenizer;return{tokenCount:await F.countTokens(p),tokenizerUsed:F.name,cached:!1}}getTokenizerConfigForModel(p,x){let F=(this.configService.get("providers")||[]).find(R=>R.name===p);if(F?.tokenizer)return F.tokenizer.models?.[x]?F.tokenizer.models[x]:F.tokenizer.default}dispose(){this.tokenizers.forEach(p=>{try{p.dispose()}catch(x){this.logger?.error(`Error disposing tokenizer: ${x}`)}}),this.tokenizers.clear()}getCacheKey(p){switch(p.type){case"tiktoken":return`tiktoken:${p.encoding||"cl100k_base"}`;case"huggingface":return`hf:${p.model}`;case"api":return`api:${p.url}`;default:return`unknown:${JSON.stringify(p)}`}}},XO=Mp(),e6=class{capacity;cache;constructor(p){this.capacity=p,this.cache=new Map}get(p){if(!this.cache.has(p))return;let x=this.cache.get(p);return this.cache.delete(p),this.cache.set(p,x),x}put(p,x){if(this.cache.has(p))this.cache.delete(p);else if(this.cache.size>=this.capacity){let F=this.cache.keys().next().value;F!==void 0&&this.cache.delete(F)}this.cache.set(p,x)}values(){return Array.from(this.cache.values())}},gw=new e6(100),Gm=require("fs/promises"),mw=require("fs/promises"),Vm=require("path"),E0=Qa();de();var df=require("fs"),Ew=require("path"),t6=Qa(),Jm=(0,Ew.join)(t6.HOME_DIR,"runtime"),Ym=(0,Ew.join)(Jm,"quota-store.json"),Fd=new Map,yw=!1,r6=null;function Cw(p,x){p&&Fd.set(p,{...x,provider:p,capturedAt:Date.now()})}function Dw(p){let x=Fd.get(p);return x?{...x}:void 0}function n6(){return Array.from(Fd.values()).map(p=>({...p}))}function i6(){try{if(!(0,df.existsSync)(Ym))return;let p=JSON.parse((0,df.readFileSync)(Ym,"utf-8"));if(!Array.isArray(p))return;let x=Date.now();for(let F of p)if(F&&F.provider){if(F.capturedAt&&x-F.capturedAt>1440*60*1e3)continue;Fd.set(F.provider,F)}}catch{}}function bw(){try{if(Fd.size===0)return;(0,df.existsSync)(Jm)||(0,df.mkdirSync)(Jm,{recursive:!0}),(0,df.writeFileSync)(Ym,JSON.stringify(Array.from(Fd.values()),null,2),"utf-8")}catch{}}function ww(){yw||(yw=!0,i6(),r6=setInterval(bw,6e4),process.on("exit",bw))}I();var Nu=(0,XO.get_encoding)("cl100k_base"),Iw=(p,x,F)=>{let R=0;return Array.isArray(p)&&p.forEach(M=>{typeof M.content=="string"?R+=Nu.encode(M.content).length:Array.isArray(M.content)&&M.content.forEach(O=>{O.type==="text"?R+=Nu.encode(O.text).length:O.type==="tool_use"?R+=Nu.encode(JSON.stringify(O.input)).length:O.type==="tool_result"&&(R+=Nu.encode(typeof O.content=="string"?O.content:JSON.stringify(O.content)).length)})}),typeof x=="string"?R+=Nu.encode(x).length:Array.isArray(x)&&x.forEach(M=>{M.type==="text"&&(typeof M.text=="string"?R+=Nu.encode(M.text).length:Array.isArray(M.text)&&M.text.forEach(O=>{R+=Nu.encode(O||"").length}))}),F&&F.forEach(M=>{M.description&&(R+=Nu.encode(M.name+M.description).length),M.input_schema&&(R+=Nu.encode(JSON.stringify(M.input_schema)).length)}),R},vw=async(p,x)=>{if(p.sessionId){let F=await Fw(p.sessionId);if(F){let R=(0,Vm.join)(E0.HOME_DIR,F,"config.json"),M=(0,Vm.join)(E0.HOME_DIR,F,`${p.sessionId}.json`);try{let O=JSON.parse(await(0,Gm.readFile)(M,"utf8"));if(O&&O.Router)return O.Router}catch{}try{let O=JSON.parse(await(0,Gm.readFile)(R,"utf8"));if(O&&O.Router)return O.Router}catch{}}}};function y0(p){let x=p||"";return x.includes(",")&&(x=x.split(",").pop()||x),x.includes("/")&&(x=x.split("/").pop()||x),x.includes(":")&&(x=x.split(":")[0]),x.trim().toLowerCase()}function Bw(p){let x=y0(p),F=x.includes("[1m]")||x.endsWith("[1m"),R=x.replace(/\[1m\]|\[1m$/g,""),M=R.match(/^ccr-(opus|sonnet|haiku)$/i);if(M)return{family:M[1].toLowerCase(),extended:F};let O=R.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||R.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return O?{family:O[1].toLowerCase(),extended:F}:{family:null,extended:F}}function o6(p,x){if(!x||!p)return null;let F=y0(p);if(x[p])return x[p];if(x[F])return x[F];let{family:R}=Bw(p);if(R&&x[R])return x[R];for(let[M,O]of Object.entries(x)){let G=y0(M);if(G&&F.includes(G))return O}return null}function xw(p){return p?(p.input_tokens||0)+(p.cache_read_input_tokens||0)+(p.cache_creation_input_tokens||0):0}function _w(p){if(!p?.includes(","))return null;let[x,...F]=p.split(","),R=x.trim(),M=F.join(",").trim();return!R||!M?null:{providerName:R,routeModel:M}}function Wo(p,x,F,R){let M=_w(p);if(!M)return p;let{providerName:O,routeModel:G}=M,J=x.find(te=>te.name.toLowerCase()===O.toLowerCase());if(J&&J.enabled===!1)return null;if(R&&!F){let te=C(),ie=te.getPromotion(O,G,R,x);if(ie){let ce=_w(ie);if(ce){let X=x.find(pe=>pe.name.toLowerCase()===ce.providerName.toLowerCase()),le=X?.models?.find(pe=>String(pe).toLowerCase()===ce.routeModel.toLowerCase());if(X&&le)return`${X.name},${le}`}te.clear(O,G,R)}}if(!F&&!Q().isAvailable(O,G))return null;let ne=Dw(O);if(ne){let te=ne.limitDaily!==void 0&&ne.usedDailyBalance!==void 0&&ne.usedDailyBalance>=ne.limitDaily,ie=ne.totalBalance!==void 0&&ne.usedBalance!==void 0&&ne.usedBalance>=ne.totalBalance;if(te||ie)return null}let z=J?.models?.find(te=>String(te).toLowerCase()===G.toLowerCase());return J&&z?`${J.name},${z}`:p}function ya(p,x,F,R,M){let O=Q(),G=[F?.[p],R?.[p]];for(let J of G)if(!(!Array.isArray(J)||J.length===0))for(let ne of J){let z=Wo(ne,x);if(z)return z}return null}function s6(p){return p.body.messages?.some(x=>x.role==="user"&&Array.isArray(x.content)&&x.content.some(F=>F.type==="image"||F.type==="image_url"||Array.isArray(F?.content)&&F.content.some(R=>R.type==="image"||R.type==="image_url")))}function a6(p){let x=y0(p);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(F=>F.test(x))}function u6(p,x,F,R,M,O,G){let J=F.longContextThreshold||6e4,ne=Math.max(x,xw(M)),z=p.modelFamily;if((O||ne>2e5)&&F.extendedContext){let te=Wo(F.extendedContext,R,!1,"extendedContext");if(te)return p.log.info(`Family: using extended context model (1M+), tokens: ${ne}, estimated: ${x}, explicit: ${O}`),{model:te,scenarioType:"extendedContext",isFallback:!1};let ie=ya("extendedContext",R,F.fallback,G,z);if(ie)return p.log.info(`Family: using extended context fallback model (1M+), tokens: ${ne}, estimated: ${x}, explicit: ${O}`),{model:ie,scenarioType:"extendedContext",isFallback:!0};p.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(ne>J&&(F.longContext||F.fallback?.longContext?.length||G?.longContext?.length)){let te=F.longContext?Wo(F.longContext,R,!1,"longContext"):null;if(te)return p.log.info(`Family: using long context model, tokens: ${ne}, estimated: ${x}`),{model:te,scenarioType:"longContext",isFallback:!1};let ie=ya("longContext",R,F.fallback,G,z);if(ie)return p.log.info(`Family: using long context fallback model, tokens: ${ne}, estimated: ${x}`),{model:ie,scenarioType:"longContext",isFallback:!0};p.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(p.body.tools)&&p.body.tools.some(te=>te.type?.startsWith("web_search"))&&F.webSearch){let te=Wo(F.webSearch,R,!1,"webSearch");if(te)return{model:te,scenarioType:"webSearch",isFallback:!1};let ie=ya("webSearch",R,F.fallback,G,z);if(ie)return p.log.info("Family: using webSearch fallback model"),{model:ie,scenarioType:"webSearch",isFallback:!0};p.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(p.body.thinking&&F.think){let te=Wo(F.think,R,!1,"think");if(te)return{model:te,scenarioType:"think",isFallback:!1};let ie=ya("think",R,F.fallback,G,z);if(ie)return p.log.info("Family: using think fallback model"),{model:ie,scenarioType:"think",isFallback:!0};p.log.warn("Family: think model unavailable (fail pool), skipping")}if(F.default){let te=Wo(F.default,R,!1,"default");if(te)return{model:te,scenarioType:"default",isFallback:!1};let ie=ya("default",R,F.fallback,G,z);if(ie)return p.log.info("Family: using default fallback model"),{model:ie,scenarioType:"default",isFallback:!0};p.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var l6=async(p,x,F,R)=>{let M=await vw(p,F),O=F.get("providers")||[],G=M||F.get("Router"),J=F.get("fallback");if(p.body.model.includes(",")){let De=Wo(p.body.model,O,!1,"default");if(De)return{model:De,scenarioType:"default"};p.log.warn(`Explicit model ${p.body.model} unavailable (fail pool), trying fallback`);let be=ya("default",O,void 0,J);if(be)return p.log.info(`Using fallback for explicit model: ${be}`),{model:be,scenarioType:"default"};p.log.warn(`No fallback available for explicit model ${p.body.model}, continuing through routing logic`)}let{family:ne,extended:z}=Bw(p.body.model),te=G?.families?.[ne||""];if(te&&G?.enableFamilyRouting){p.log.info(`Using model family routing for: ${ne}${z?" (1M)":""}`),p.modelFamily=ne,p.familyFallback=te.fallback;let De=u6(p,x,te,O,R,z,J);if(De)return{model:De.model,scenarioType:De.scenarioType}}let ie=o6(p.body.model,G?.models);if(ie){let De=Wo(ie,O,!1,"modelMapping");if(De)return p.log.info(`Using mapped model for ${p.body.model}: ${ie}`),{model:De,scenarioType:"modelMapping"};p.log.warn(`Mapped model ${ie} unavailable (fail pool), skipping`)}let ce=Math.max(x,xw(R)),X=G?.extendedContextThreshold||2e5;if(ce>X&&G?.extendedContext){p.log.info(`Using extended context (1M) model due to token count: ${ce}, estimated: ${x}, threshold: ${X}`);let De=Wo(G.extendedContext,O,!1,"extendedContext");if(De)return{model:De,scenarioType:"extendedContext"};p.log.warn(`Extended context model ${G.extendedContext} unavailable (fail pool), trying fallback`);let be=ya("extendedContext",O,void 0,J);if(be)return{model:be,scenarioType:"extendedContext"}}let le=G?.longContextThreshold||6e4;if(ce>le&&G?.longContext){p.log.info(`Using long context model due to token count: ${ce}, estimated: ${x}, threshold: ${le}`);let De=Wo(G.longContext,O,!1,"longContext");if(De)return{model:De,scenarioType:"longContext"};p.log.warn(`Long context model ${G.longContext} unavailable (fail pool), trying fallback`);let be=ya("longContext",O,void 0,J);if(be)return{model:be,scenarioType:"longContext"}}if(p.body?.system?.length>1&&p.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let De=p.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(De)return p.body.system[1].text=p.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${De[1]}</CCR-SUBAGENT-MODEL>`,""),{model:De[1],scenarioType:"default"}}let pe=F.get("Router");if(p.body.model?.includes("claude")&&p.body.model?.includes("haiku")&&pe?.background){p.log.info(`Using background model for ${p.body.model}`);let De=Wo(pe.background,O,!1,"background");if(De)return{model:De,scenarioType:"background"};p.log.warn(`Background model ${pe.background} unavailable (fail pool), falling through`)}if(Array.isArray(p.body.tools)&&p.body.tools.some(De=>De.type?.startsWith("web_search"))&&G?.webSearch){let De=Wo(G.webSearch,O,!1,"webSearch");if(De)return{model:De,scenarioType:"webSearch"};p.log.warn(`WebSearch model ${G.webSearch} unavailable (fail pool), trying fallback`);let be=ya("webSearch",O,void 0,J);if(be)return{model:be,scenarioType:"webSearch"}}if(p.body.thinking&&G?.think){p.log.info(`Using think model for ${p.body.thinking}`);let De=Wo(G.think,O,!1,"think");if(De)return{model:De,scenarioType:"think"};p.log.warn(`Think model ${G.think} unavailable (fail pool), trying fallback`);let be=ya("think",O,void 0,J);if(be)return{model:be,scenarioType:"think"}}if(G?.default){let De=Wo(G.default,O,!1,"default");if(De)return{model:De,scenarioType:"default"};p.log.warn(`Default model ${G.default} unavailable (fail pool), trying fallback`);let be=ya("default",O,void 0,J);if(be)return{model:be,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},zm=async(p,x,F)=>{let{configService:R,event:M}=F;if(p.originalModel=p.body.model,p.body.metadata?.user_id){let ce=p.body.metadata.user_id.split("_session_");ce.length>1&&(p.sessionId=ce[1])}let O=await vw(p,R)||R.get("Router"),G=R.get("providers")||[],J=gw.get(p.sessionId),{messages:ne,system:z=[],tools:te}=p.body,ie=R.get("REWRITE_SYSTEM_PROMPT");if(ie&&z.length>1&&z[1]?.text?.includes("<env>")){let ce=await(0,Gm.readFile)(ie,"utf-8");z[1].text=`${ce}<env>${z[1].text.split("<env>").pop()}`}try{let[ce,X]=p.body.model.split(","),le=F.tokenizerService?.getTokenizerConfigForModel(ce,X),pe;F.tokenizerService?pe=(await F.tokenizerService.countTokens({messages:ne,system:z,tools:te},le)).tokenCount:pe=Iw(ne,z,te),p.tokenCount=pe;let De,be=R.get("CUSTOM_ROUTER_PATH");if(be)try{De=await require(be)(p,R.getAll(),{event:M})}catch(Be){p.log.error(`failed to load custom router: ${Be.message}`)}if(De)p.scenarioType="default";else{let Be=await l6(p,pe,R,J);De=Be.model,p.scenarioType=Be.scenarioType}if(O?.image&&De!==O.image&&s6(p)&&!a6(De)){let Be=Wo(O.image,G,!1,"image");Be?(p.log.info(`Using image model fallback for ${De}`),De=Be,p.scenarioType="image"):(p.log.warn(`Image model ${O.image} unavailable (fail pool), keeping ${De}`),p.scenarioType="image")}p.body.model=De}catch(ce){p.log.error(`Error in router middleware: ${ce.message}`),p.body.model=O?.default,p.scenarioType="default"}},Ou=new Map,Sw=1e3;function Wm(){if(Ou.size<=Sw)return;let p=[...Ou.keys()].slice(0,Ou.size-Sw);for(let x of p)Ou.delete(x)}var Fw=async p=>{if(Ou.has(p)){let x=Ou.get(p);return!x||x===""?null:x}try{let x=await(0,mw.opendir)(E0.CLAUDE_PROJECTS_DIR),F=[];for await(let O of x)O.isDirectory()&&F.push(O.name);let R=F.map(async O=>{let G=(0,Vm.join)(E0.CLAUDE_PROJECTS_DIR,O,`${p}.jsonl`);try{return(await(0,mw.stat)(G)).isFile()?O:null}catch{return null}}),M=await Promise.all(R);for(let O of M)if(O)return Ou.set(p,O),Wm(),O;return Ou.set(p,""),Wm(),null}catch(x){return console.error("Error searching for project by session:",x),Ou.set(p,""),Wm(),null}};de();var Ec=class{async fetchJson(p,x,F,R,M){let O=M||x.apiKey;if(!O)return null;let G={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${O}`},signal:AbortSignal.timeout(F)};if(R)try{let{ProxyAgent:J}=await Promise.resolve().then(()=>Sn(Po()));G.dispatcher=new J(new URL(R).toString())}catch{}try{let J=await fetch(p,G);return J.ok?await J.json():null}catch{return null}}hasQuotaData(p){return p.totalBalance!==void 0||p.usedBalance!==void 0||p.remainingBalance!==void 0||p.usedDailyBalance!==void 0||p.limitDaily!==void 0||p.resetTime!==void 0}},c6=class extends Ec{async queryQuota(p,x,F){let R=await this.fetchJson("https://api.deepseek.com/user/balance",p,x,F),M=(Array.isArray(R?.balance_infos)?R.balance_infos:[]).find(G=>Ln(G?.total_balance)!==void 0);if(!M)return null;let O=Ln(M.total_balance);return O===void 0?null:{totalBalance:O,currency:typeof M.currency=="string"?M.currency:void 0}}},d6=class extends Ec{async queryQuota(p,x,F){let R=(await this.fetchJson("https://openrouter.ai/api/v1/key",p,x,F))?.data;if(!R||typeof R!="object")return null;let M={},O=Ln(R.limit),G=Ln(R.limit_remaining),J=Ln(R.usage),ne=Ln(R.usage_daily);return O!==void 0&&(M.totalBalance=O),G!==void 0&&(M.remainingBalance=G),J!==void 0&&(M.usedBalance=J),ne!==void 0&&(M.usedDailyBalance=ne),this.hasQuotaData(M)?M:null}},h6=class extends Ec{async queryQuota(p,x,F){let R=I6(p.baseUrl),M=(await this.fetchJson(R,p,x,F))?.data;if(!M||typeof M!="object")return null;let O={},G=Ln(M.totalBalance),J=Ln(M.balance);return G!==void 0&&(O.totalBalance=G),J!==void 0&&(O.remainingBalance=J),G!==void 0&&J!==void 0&&(O.usedBalance=Math.max(0,G-J)),this.hasQuotaData(O)?O:null}},f6=class extends Ec{async queryQuota(p,x,F){if(!p.apiKey)return null;let R={method:"GET",headers:{Accept:"application/json",Authorization:p.apiKey.trim()},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:M}=await Promise.resolve().then(()=>Sn(Po()));R.dispatcher=new M(new URL(F).toString())}catch{}try{let M=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",R);if(!M.ok)return null;let O=await M.json(),G=Array.isArray(O?.data?.limits)?O.data.limits:[],J=null,ne=null,z=null;for(let ie of G)ie.type==="TOKENS_LIMIT"?ie.unit===3?J=ie:ie.unit===6?ne=ie:J||(J=ie):ie.type==="TIME_LIMIT"&&(z=ie);let te={};if(J){let ie=Ln(J.currentValue),ce=Ln(J.usage),X=Ln(J.remaining),le=Ln(J.percentage);ie!==void 0?te.usedDailyBalance=ie:le!==void 0&&(te.usedDailyBalance=le,te.limitDaily=100),ce!==void 0?te.limitDaily=ce:ie!==void 0&&X!==void 0&&(te.limitDaily=ie+X),J.nextResetTime&&(te.resetTime=new Date(J.nextResetTime).toISOString())}if(ne){let ie=Ln(ne.currentValue),ce=Ln(ne.usage),X=Ln(ne.remaining),le=Ln(ne.percentage);ie!==void 0?te.usedBalance=ie:le!==void 0&&(te.usedBalance=le,te.totalBalance=100),ce!==void 0?te.totalBalance=ce:ie!==void 0&&X!==void 0&&(te.totalBalance=ie+X),ne.nextResetTime&&!te.resetTime&&(te.resetTime=new Date(ne.nextResetTime).toISOString())}if(z){if(te.usedDailyBalance===void 0){let ie=Ln(z.currentValue);ie!==void 0&&(te.usedDailyBalance=ie)}if(te.limitDaily===void 0){let ie=Ln(z.usage),ce=Ln(z.currentValue),X=Ln(z.remaining);ie!==void 0?te.limitDaily=ie:ce!==void 0&&X!==void 0&&(te.limitDaily=ce+X)}z.nextResetTime&&!te.resetTime&&(te.resetTime=new Date(z.nextResetTime).toISOString())}return this.hasQuotaData(te)?te:null}catch{return null}}},A6=class extends Ec{async queryQuota(p,x,F){if(!p.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:p.quotaToken},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:G}=await Promise.resolve().then(()=>Sn(Po()));R.dispatcher=new G(new URL(F).toString())}catch{}let M=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"}}}),O=new URLSearchParams({params:M,region:"cn-beijing"}).toString();try{let G=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...R,body:O});if(!G.ok)return null;let J=(await G.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(J)||J.length===0)return null;let ne=J[0]?.codingPlanQuotaInfo;if(!ne)return null;let z={},te=Ln(ne.per5HourUsedQuota),ie=Ln(ne.per5HourTotalQuota);te!==void 0&&(z.usedDailyBalance=te),ie!==void 0&&(z.limitDaily=ie);let ce=Ln(ne.perWeekUsedQuota),X=Ln(ne.perWeekTotalQuota);return ce!==void 0&&(z.usedBalance=ce),X!==void 0&&(z.totalBalance=X),this.hasQuotaData(z)?z:null}catch{return null}}},p6=class extends Ec{async queryQuota(p,x,F){let R=p.quotaToken||p.apiKey;if(!R)return null;let M={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${R.trim()}`},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:O}=await Promise.resolve().then(()=>Sn(Po()));M.dispatcher=new O(new URL(F).toString())}catch{}try{let O=await fetch("https://api.kimi.com/coding/v1/usages",M);if(!O.ok)return null;let G=await O.json(),J={},ne=Array.isArray(G?.limits)?G.limits:[];if(ne.length>0&&ne[0]?.detail){let te=ne[0].detail,ie=Ln(te.limit),ce=Ln(te.remaining),X=te.resetTime;ie!==void 0&&ce!==void 0&&(J.usedDailyBalance=Math.max(0,ie-ce),J.limitDaily=ie),X&&(J.resetTime=new Date(X).toISOString())}let z=G?.usage;if(z){let te=Ln(z.limit),ie=Ln(z.remaining),ce=Ln(z.used),X=z.resetTime;te!==void 0&&(J.totalBalance=te,ce!==void 0?J.usedBalance=ce:ie!==void 0&&(J.usedBalance=Math.max(0,te-ie),J.remainingBalance=ie)),X&&(J.resetTime7d=new Date(X).toISOString(),J.resetTime||(J.resetTime=J.resetTime7d))}return this.hasQuotaData(J)?J:null}catch{return null}}},g6=class extends Ec{async queryQuota(p,x,F){let R=p.quotaToken||p.apiKey;if(!R)return null;let M=Km(p.baseUrl)||"api.minimaxi.com",O=M.endsWith(".minimax.io")||M==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let G=[`https://${O}/v1/token_plan/remains`,`https://${O}/v1/api/openplatform/coding_plan/remains`],J=null;for(let we of G)if(J=await this.fetchJson(we,p,x,F,R.trim()),J)break;if(!J)return null;if(J?.base_resp){let we=J.base_resp.status_code;if(we!==void 0&&we!==0)return null}let ne=Array.isArray(J?.model_remains)?J.model_remains:[];if(ne.length===0)return null;let z=ne[0],te={},ie=Ln(z.current_interval_total_count),ce=Ln(z.current_interval_usage_count),X=Ln(z.current_interval_remaining_percent),le=Ln(z.end_time);ie!==void 0&&ce!==void 0&&ie>0?(te.usedDailyBalance=Math.max(0,ie-ce),te.limitDaily=ie):X!==void 0&&(te.limitDaily=100,te.usedDailyBalance=Math.max(0,100-X)),le&&(te.resetTime=new Date(le).toISOString());let pe=Ln(z.current_weekly_total_count),De=Ln(z.current_weekly_usage_count),be=Ln(z.current_weekly_remaining_percent),Be=Ln(z.weekly_end_time);return pe!==void 0&&De!==void 0&&pe>0?(te.usedBalance=Math.max(0,pe-De),te.remainingBalance=De,te.totalBalance=pe):be!==void 0&&(te.totalBalance=100,te.usedBalance=Math.max(0,100-be),te.remainingBalance=be),Be&&!te.resetTime&&(te.resetTime=new Date(Be).toISOString()),this.hasQuotaData(te)?te:null}catch{return null}}},m6=new c6,E6=new d6,y6=new h6,C6=new f6,D6=new A6,b6=new p6,w6=new g6;function kw(p){let x=Km(p);return x?x==="kimi.com"||x.endsWith(".kimi.com")||x==="moonshot.cn"||x.endsWith(".moonshot.cn")?b6:x==="minimaxi.com"||x.endsWith(".minimaxi.com")||x==="minimax.io"||x.endsWith(".minimax.io")?w6:x==="deepseek.com"||x.endsWith(".deepseek.com")?m6:x==="openrouter.ai"||x.endsWith(".openrouter.ai")?E6:x==="siliconflow.com"||x.endsWith(".siliconflow.com")||x==="siliconflow.cn"||x.endsWith(".siliconflow.cn")?y6:x==="bigmodel.cn"||x.endsWith(".bigmodel.cn")?C6:x==="dashscope.aliyuncs.com"||x.endsWith(".dashscope.aliyuncs.com")?D6:null:null}function I6(p){let x=Km(p);return x?.endsWith(".siliconflow.cn")||x==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Km(p){try{return new URL(p).hostname.toLowerCase()}catch{return null}}function Ln(p){if(typeof p=="number")return Number.isFinite(p)?p:void 0;if(typeof p!="string")return;let x=p.trim().replace(/,/g,"");if(!x)return;let F=Number(x);return Number.isFinite(F)?F:void 0}var v6={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function B6(p){return p===!0||p==="true"||p===1||p==="1"}function x6(p){let x=p.getFullYear(),F=String(p.getMonth()+1).padStart(2,"0"),R=String(p.getDate()).padStart(2,"0");return`${x}-${F}-${R}`}function _6(p){try{let x=new URL(p),F=x.pathname;return F.endsWith("/v1/messages")?F=F.slice(0,-12):F.endsWith("/messages")?F=F.slice(0,-9):F.endsWith("/v1/chat/completions")?F=F.slice(0,-20):F.endsWith("/chat/completions")&&(F=F.slice(0,-17)),F.endsWith("/v1")||(F=F.endsWith("/")?`${F}v1`:`${F}/v1`),x.pathname=`${F}/models`,x.toString()}catch{return null}}function S6(p){try{let x=new URL(p).hostname.toLowerCase();return x.includes("moonshot")||x.includes("kimi")}catch{return!1}}async function Zm(p,x,F){let R=_6(p.baseUrl);if(!R)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let M={method:"GET",headers:{Authorization:`Bearer ${p.apiKey}`},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:J}=await Promise.resolve().then(()=>Sn(Po()));M.dispatcher=new J(new URL(F).toString())}catch{}let O=await fetch(R,M);if(O.headers&&Bd(p.name,p.baseUrl,O.headers),O.ok)return{success:!0,headers:O.headers};if(O.status===429)return{success:!1,error:`HTTP 429: ${(await O.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:O.headers};if(O.status>=400&&O.status<500)return{success:!0,headers:O.headers};let G=await O.text().catch(()=>"");return{success:!1,error:`HTTP ${O.status}: ${G.slice(0,100)}`,headers:O.headers}}catch(M){return{success:!1,error:M?.message||M?.toString()||"Unknown probe error"}}}async function F6(p,x,F,R){let M=p.wakeupModel||(Array.isArray(p.models)?p.models[0]:void 0);if(!M)return{success:!1,error:"No models configured for provider"};let O=p.baseUrl.includes("anthropic")||M.includes("claude"),G=O?p.baseUrl.includes("/messages")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/v1/messages`:p.baseUrl.includes("/chat/completions")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let J={"Content-Type":"application/json"};O?(J["x-api-key"]=p.apiKey,J["anthropic-version"]="2023-06-01"):J.Authorization=`Bearer ${p.apiKey}`;let ne={method:"POST",headers:J,body:JSON.stringify({model:M,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:ie}=await Promise.resolve().then(()=>Sn(Po()));ne.dispatcher=new ie(new URL(F).toString())}catch{}R?.info(`Sending scheduled wake-up call to provider ${p.name} using model ${M}...`);let z=await fetch(G,ne);if(z.ok)return{success:!0};let te=await z.text().catch(()=>"");return{success:!1,error:`HTTP ${z.status}: ${te.slice(0,200)||"Unknown error"}`}}catch(J){return{success:!1,error:J?.message||J?.toString()||"Unknown wake-up error"}}}async function k6(p,x,F,R,M){let O=p.baseUrl.includes("anthropic")||x.includes("claude"),G=O?p.baseUrl.includes("/messages")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/v1/messages`:p.baseUrl.includes("/chat/completions")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let J={"Content-Type":"application/json"};O?(J["x-api-key"]=p.apiKey,J["anthropic-version"]="2023-06-01"):J.Authorization=`Bearer ${p.apiKey}`;let ne={method:"POST",headers:J,body:JSON.stringify({model:x,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(F)};if(R)try{let{ProxyAgent:ie}=await Promise.resolve().then(()=>Sn(Po()));ne.dispatcher=new ie(new URL(R).toString())}catch{}M?.debug?.(`Sending independent ping to rate-limited model ${p.name} (${x})...`);let z=await fetch(G,ne);if(z.ok)return{success:!0};let te=await z.text().catch(()=>"");return{success:!1,error:`HTTP ${z.status}: ${te.slice(0,200)||"Unknown error"}`}}catch(J){return{success:!1,error:J?.message||J?.toString()||"Unknown ping error"}}}var Tw=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(p,x,F,R,M){this.config={...v6,...x},this.getProviders=p,this.getHttpsProxy=F,this.logger=R,this.getConfig=M}start(){if(this.running)return;let p=this.isWakeupGloballyEnabled();!this.config.enabled&&!p||(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.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.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 p=this.getProviders().filter(O=>O?.name&&O.enabled!==!1&&!this.config.excludeProviders.includes(O.name)),x=this.getHttpsProxy?.(),F=Q();if(p.length===0)return;let R=[];for(let O of p){let G=kw(O.baseUrl),J=Array.isArray(O.models)?O.models:[];G&&R.push({provider:O.name,models:J,type:"quota-adapter",promise:G.queryQuota(O,this.config.probeTimeoutMs,x).then(ne=>{if(ne){Cw(O.name,ne),this.logger?.debug?.(`Stored quota probe result for ${O.name}`);let z=ne.limitDaily!==void 0&&ne.usedDailyBalance!==void 0&&ne.usedDailyBalance>=ne.limitDaily,te=ne.totalBalance!==void 0&&ne.usedBalance!==void 0&&ne.usedBalance>=ne.totalBalance;if(z||te){let ie=z?`Quota exhausted: 5h limit reached (${ne.usedDailyBalance}/${ne.limitDaily})`:`Quota exhausted: 7d balance depleted (${ne.usedBalance}/${ne.totalBalance})`;for(let ce of J){if(F.getState(O.name,ce)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${O.name} (${ce}): already rate-limited with active cooldown`);continue}F.forceOpen(O.name,ce,ie)}this.logger?.warn?.(`${ie} for ${O.name}, marked as unhealthy`)}else for(let ie of J){let ce=F.getState(O.name,ie);ce&&ce.status==="open"&&ce.lastError?.includes("Quota exhausted")&&(F.recover(O.name,ie),this.logger?.info?.(`Quota recovered for ${O.name} (${ie}), marked as healthy`))}}})}),S6(O.baseUrl)&&R.push({provider:O.name,models:J,type:"rate-limit-headers",promise:Zm(O,this.config.probeTimeoutMs,x).then(()=>{})})}if(R.length===0)return;this.logger?.debug?.(`Running quota probe with ${R.length} tasks for ${p.length} providers`);let M=await Promise.allSettled(R.map(O=>O.promise));for(let O=0;O<R.length;O++){let G=M[O];if(G.status==="rejected"){let J=R[O];this.logger?.warn?.(`Quota probe failed for ${J.provider} (${J.type}): ${G.reason}`)}}}async runHealthProbe(){let p=Q(),x=this.getProviders().filter(M=>M?.name&&M.enabled!==!1&&!this.config.excludeProviders.includes(M.name)),F=this.getHttpsProxy?.();if(x.length===0)return;this.logger?.debug?.(`Running health probe for ${x.length} providers`);let R=await Promise.allSettled(x.map(M=>Zm(M,this.config.probeTimeoutMs,F)));for(let M=0;M<x.length;M++){let O=x[M],G=R[M],J=Array.isArray(O.models)?O.models:[];if(G.status==="fulfilled"){let ne=G.value;if(ne.success){let z=0;for(let te of J){let ie=p.getState(O.name,te);if(ie&&ie.status==="open"){let ce=ie.lastError?.includes("Quota exhausted"),X=ie.rateLimitUntil||ie.lastError&&(ie.lastError.includes("429")||ie.lastError.toLowerCase().includes("rate limit")||ie.lastError.toLowerCase().includes("rate_limit")||ie.lastError.toLowerCase().includes("too many requests")||ie.lastError.toLowerCase().includes("\u9650\u6D41"));if(ce){this.logger?.debug?.(`Skipping health probe recovery for ${O.name} (${te}) because quota is exhausted`);continue}if(X||ie.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${O.name} (${te})`);continue}}p.recordSuccess(O.name,te),z++}z>0&&this.logger?.info?.(`Health probe succeeded for ${O.name}`)}else{for(let z of J)p.recordFailure(O.name,z,ne.error);this.logger?.warn?.(`Health probe failed for ${O.name}: ${ne.error}`)}}else{for(let ne of J)p.recordFailure(O.name,ne,G.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${O.name}: ${G.reason}`)}}}async runRateLimitProbe(){let p=Q(),x=p.getRateLimitedModels();if(x.length===0)return;let F=this.getProviders(),R=this.getHttpsProxy?.(),M=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${x.length} model(s)`);for(let O of x){let[G,...J]=O.split(","),ne=J.join(",");if(!G||!ne)continue;let z=p.getState(G,ne);if(!z||!z.rateLimitUntil)continue;if(Date.now()>=z.rateLimitUntil){p.recover(G,ne),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${O}`);continue}let te=F.find(ie=>ie?.name===G&&ie.enabled!==!1);if(!te){this.logger?.warn?.(`Provider ${G} not found or disabled for rate-limit probe`);continue}try{let ie=await k6(te,ne,M,R,this.logger);if(ie.success)this.logger?.info?.(`Rate-limit probe succeeded for ${O}, recovering model`),p.recover(G,ne);else if(ie.error&&(ie.error.includes("429")||ie.error.toLowerCase().includes("rate limit")||ie.error.toLowerCase().includes("rate_limit")||ie.error.toLowerCase().includes("too many requests")||ie.error.toLowerCase().includes("\u9650\u6D41"))){let ce=Date.now();z.rateLimitUntil&&z.rateLimitUntil>ce?z.rateLimitUntil+=120*1e3:z.rateLimitUntil=ce+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${O} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${O} returned non-rate-limit error: ${ie.error?.slice(0,100)}`)}catch(ie){this.logger?.warn?.(`Rate-limit probe exception for ${O}: ${ie?.message||ie}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let p=this.getProviders().filter(J=>J?.name&&J.enabled!==!1&&J.wakeupEnabled===!0);if(p.length===0)return;let x=new Date,F=x.getHours(),R=x.getMinutes(),M=x6(x),O=this.getHttpsProxy?.(),G=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let J of p){let ne=J.wakeupTime||G,[z,te]=ne.split(":"),ie=parseInt(z,10),ce=parseInt(te,10);isNaN(ie)||isNaN(ce)||F===ie&&R===ce&&this.lastWakeupDate.get(J.name)!==M&&(this.lastWakeupDate.set(J.name,M),this.logger?.info?.(`Scheduled wake-up triggered for provider ${J.name} at ${ne}`),F6(J,3e4,O,this.logger).then(X=>{X.success?this.logger?.info?.(`Successfully woke up provider ${J.name}`):this.logger?.error?.(`Failed to wake up provider ${J.name}: ${X.error}`)}).catch(X=>{this.logger?.error?.(`Error in wake-up task for ${J.name}: ${X}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?B6(this.getConfig("WAKEUP_ENABLED")):!1}async probeProviderManually(p){let x=this.getProviders().find(O=>O.name===p);if(!x)return this.logger?.warn?.(`Provider ${p} not found for manual probe`),!1;if(x.enabled===!1)return this.logger?.warn?.(`Provider ${p} is disabled, skipping manual probe`),!1;let F=this.getHttpsProxy?.(),R=await Zm(x,this.config.probeTimeoutMs,F),M=Array.isArray(x.models)?x.models:[];if(R.success)for(let O of M)Q().recordSuccess(x.name,O);else for(let O of M)Q().recordFailure(x.name,O,R.error);return R.success}},yl=null;function Rw(p,x,F,R,M){return yl||(yl=new Tw(p,x,F,R,M)),yl}function Qw(p,x,F,R,M){let O=Rw(p,x,F,R,M);return O.start(),O}function Nw(){yl&&yl.stop()}function T6(){yl&&(yl.stop(),yl=null)}de();var R6=class{plugins=new Map;pluginInstances=new Map;registerPlugin(p,x={}){this.pluginInstances.set(p.name,p),this.plugins.set(p.name,{name:p.name,enabled:x.enabled!==!1,options:x})}async enablePlugin(p,x){let F=this.plugins.get(p),R=this.pluginInstances.get(p);if(!F||!R)throw new Error(`Plugin ${p} not found`);F.enabled&&await x.register(R.register,F.options)}async enablePlugins(p){for(let[x,F]of this.plugins)if(F.enabled)try{await this.enablePlugin(x,p)}catch(R){let M=R instanceof Error?R.message:String(R);p.log?.error(`Failed to enable plugin ${x}: ${M}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(p){return this.pluginInstances.get(p)}hasPlugin(p){return this.pluginInstances.has(p)}isPluginEnabled(p){return this.plugins.get(p)?.enabled||!1}setPluginEnabled(p,x){let F=this.plugins.get(p);F&&(F.enabled=x)}removePlugin(p){this.plugins.delete(p),this.pluginInstances.delete(p)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Q6=new R6,N6=f(Ui(),1),Ow=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(p,x)=>{this.buffer+=p;let F=this.buffer.split(`
|
|
951
|
+
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(p)}}clean_text(p){let x=[];for(let F of p){let R=F.charCodeAt(0);R===0||R===65533||this.is_control(F)||(/^\s$/.test(F)?x.push(" "):x.push(F))}return x.join("")}normalize(p){return this.config.clean_text&&(p=this.clean_text(p)),this.config.handle_chinese_chars&&(p=this.tokenize_chinese_chars(p)),this.config.lowercase?(p=p.toLowerCase(),this.config.strip_accents!==!1&&(p=this.strip_accents(p))):this.config.strip_accents&&(p=this.strip_accents(p)),p}},oN=iN,sN=class extends Qu{constructor(p){super(p),this.charsmap=p.precompiled_charsmap??null}normalize(p){return p=p.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),p=p.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),p.includes("\uFF5E")?p=p.split("\uFF5E").map(x=>x.normalize("NFKC")).join("\uFF5E"):p=p.normalize("NFKC"),p}},aN=sN,uN=class extends Qu{constructor(p){super(p),this.normalizers=(p.normalizers??[]).map(x=>uw(x))}normalize(p){return this.normalizers.reduce((x,F)=>F?F.normalize(x):x,p)}},lN=uN,cN=class extends Qu{normalize(p){let x=p0(this.config.pattern??{});return x===null?p:p.replaceAll(x,this.config.content??"")}},dN=cN,hN=class extends Qu{constructor(){super(...arguments),this.form="NFC"}normalize(p){return p=p.normalize(this.form),p}},g0=hN,fN=class extends g0{constructor(){super(...arguments),this.form="NFC"}},AN=fN,pN=class extends g0{constructor(){super(...arguments),this.form="NFD"}},gN=pN,mN=class extends g0{constructor(){super(...arguments),this.form="NFKC"}},EN=mN,yN=class extends g0{constructor(){super(...arguments),this.form="NFKD"}},CN=yN,DN=class extends Qu{normalize(p){return this.config.strip_left&&this.config.strip_right?p=p.trim():(this.config.strip_left&&(p=p.trimStart()),this.config.strip_right&&(p=p.trimEnd())),p}},bN=DN,wN=class extends Qu{normalize(p){return sw(p)}},IN=wN,vN=class extends Qu{normalize(p){return p.toLowerCase()}},BN=vN,xN=class extends Qu{normalize(p){return p=this.config.prepend+p,p}},_N=xN;function SN(p){if(p===null)return null;switch(p.type){case"BertNormalizer":return new oN(p);case"Precompiled":return new aN(p);case"Sequence":return new lN(p);case"Replace":return new dN(p);case"NFC":return new AN(p);case"NFD":return new gN(p);case"NFKC":return new EN(p);case"NFKD":return new CN(p);case"Strip":return new bN(p);case"StripAccents":return new IN(p);case"Lowercase":return new BN(p);case"Prepend":return new _N(p);default:throw new Error(`Unknown Normalizer type: ${p.type}`)}}var uw=SN,FN=class extends lf{pre_tokenize(p,x){return(Array.isArray(p)?p.map(F=>this.pre_tokenize_text(F,x)):this.pre_tokenize_text(p,x)).flat()}_call(p,x){return this.pre_tokenize(p,x)}},Za=FN,kN=class extends Za{constructor(p){super(),this.config=p,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=iw,this.text_encoder=new TextEncoder}pre_tokenize_text(p,x){return this.add_prefix_space&&!p.startsWith(" ")&&(p=" "+p),(this.use_regex?p.match(this.pattern)||[]:[p]).map(F=>Array.from(this.text_encoder.encode(F),R=>this.byte_encoder[R]).join(""))}},TN=kN,RN=class extends Za{pre_tokenize_text(p,x){return p.match(/\w+|[^\w\s]+/g)||[]}},QN=RN,NN=class extends Za{constructor(p){super(),this.replacement=p.replacement??"\u2581",this.str_rep=p.str_rep||this.replacement,this.prepend_scheme=p.prepend_scheme??"always"}pre_tokenize_text(p,x){let{section_index:F=void 0}=x??{},R=p.replaceAll(" ",this.str_rep);return!R.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&F===0)&&(R=this.str_rep+R),[R]}},ON=NN,LN=class extends Za{constructor(p){super(),this.config=p,this.pattern=p0(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(p){return this.pattern===null?[]:this.config.invert?p.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?p.split(this.pattern).filter(x=>x):eN(p,this.pattern)}},PN=LN,MN=class extends Za{constructor(p){super(),this.config=p,this.pattern=new RegExp(`[^${uf}]+|[${uf}]+`,"gu")}pre_tokenize_text(p){return p.match(this.pattern)||[]}},UN=MN,$N=class extends Za{constructor(p){super(),this.config=p;let x=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(x,"gu")}pre_tokenize_text(p){return p.match(this.pattern)||[]}},jN=$N,HN=class extends Za{constructor(){super(),this.pattern=new RegExp(`[^\\s${uf}]+|[${uf}]`,"gu")}pre_tokenize_text(p,x){return p.trim().match(this.pattern)||[]}},qN=HN,GN=class extends Za{constructor(p){super(),this.config=p,this.pattern=p0(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(p){return this.pattern===null?[p]:[p.replaceAll(this.pattern,this.config.content??"")]}},VN=GN,JN=class extends Za{constructor(p){super(),this.tokenizers=(p.pretokenizers??[]).map(x=>lw(x))}pre_tokenize_text(p,x){return this.tokenizers.reduce((F,R)=>R?R.pre_tokenize(F,x):F,[p])}},YN=JN,zN=class extends Za{pre_tokenize_text(p){return tN(p)}},WN=zN;function KN(p){if(p===null)return null;switch(p.type){case"BertPreTokenizer":return new qN;case"Sequence":return new YN(p);case"Whitespace":return new QN;case"WhitespaceSplit":return new WN;case"Metaspace":return new ON(p);case"ByteLevel":return new TN(p);case"Split":return new PN(p);case"Punctuation":return new UN(p);case"Digits":return new jN(p);case"Replace":return new VN(p);default:throw new Error(`Unknown PreTokenizer type: ${p.type}`)}}var lw=KN,ZN=class extends lf{constructor(p){super(),this.config=p,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(p){let x=this.encode(p);return this.fuse_unk&&(x=zQ(x,this.tokens_to_ids,this.unk_token_id)),x}convert_tokens_to_ids(p){return p.map(x=>this.tokens_to_ids.get(x)??this.unk_token_id)}convert_ids_to_tokens(p){return p.map(x=>this.vocab[Number(x)]??this.unk_token)}},m0=ZN,XN=class extends m0{constructor(p){super(p),this.max_input_chars_per_word=100,this.tokens_to_ids=jm(p.vocab),this.unk_token_id=this.tokens_to_ids.get(p.unk_token),this.unk_token=p.unk_token,this.max_input_chars_per_word=p.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[x,F]of this.tokens_to_ids)this.vocab[F]=x}encode(p){let x=[];for(let F of p){let R=[...F];if(R.length>this.max_input_chars_per_word){x.push(this.unk_token);continue}let M=!1,O=0,G=[];for(;O<R.length;){let J=R.length,ne=null;for(;O<J;){let z=R.slice(O,J).join("");if(O>0&&(z=this.config.continuing_subword_prefix+z),this.tokens_to_ids.has(z)){ne=z;break}--J}if(ne===null){M=!0;break}G.push(ne),O=J}M?x.push(this.unk_token):x.push(...G)}return x}},cw=XN,dw=class E_{constructor(x,F){this.is_leaf=x,this.children=F}static default(){return new E_(!1,new Map)}},eO=class{constructor(){this.root=dw.default()}extend(p){for(let x of p)this.push(x)}push(p){let x=this.root;for(let F of p){let R=x.children.get(F);R===void 0&&(R=dw.default(),x.children.set(F,R)),x=R}x.is_leaf=!0}*common_prefix_search(p){let x=this.root;if(x===void 0)return;let F="";for(let R of p){if(F+=R,x=x.children.get(R),x===void 0)return;x.is_leaf&&(yield F)}}},tO=eO,Hm=class y_{constructor(x,F,R,M,O){this.token_id=x,this.node_id=F,this.pos=R,this.length=M,this.score=O,this.prev=null,this.backtrace_score=0}clone(){let x=new y_(this.token_id,this.node_id,this.pos,this.length,this.score);return x.prev=this.prev,x.backtrace_score=this.backtrace_score,x}},rO=class{constructor(p,x,F){this.chars=Array.from(p),this.len=this.chars.length,this.bos_token_id=x,this.eos_token_id=F,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let R=new Hm(this.bos_token_id??0,0,0,0,0),M=new Hm(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(R.clone()),this.nodes.push(M.clone()),this.begin_nodes[this.len].push(M),this.end_nodes[0].push(R)}insert(p,x,F,R){let M=this.nodes.length,O=new Hm(R,M,p,x,F);this.begin_nodes[p].push(O),this.end_nodes[p+x].push(O),this.nodes.push(O)}viterbi(){let p=this.len,x=0;for(;x<=p;){if(this.begin_nodes[x].length==0)return[];for(let O of this.begin_nodes[x]){O.prev=null;let G=0,J=null;for(let ne of this.end_nodes[x]){let z=ne.backtrace_score+O.score;(J===null||z>G)&&(J=ne.clone(),G=z)}if(J!==null)O.prev=J,O.backtrace_score=G;else return[]}++x}let F=[],R=this.begin_nodes[p][0].prev;if(R===null)return[];let M=R.clone();for(;M.prev!==null;)F.push(M.clone()),M=M.clone().prev.clone();return F.reverse(),F}piece(p){return this.chars.slice(p.pos,p.pos+p.length).join("")}tokens(){return this.viterbi().map(p=>this.piece(p))}token_ids(){return this.viterbi().map(p=>p.token_id)}},nO=rO;function iO(p){if(p.length===0)throw new Error("Array must not be empty");let x=p[0],F=0;for(let R=1;R<p.length;++R)p[R]<x&&(x=p[R],F=R);return[x,F]}var oO=class extends m0{constructor(p,x){super(p);let F=p.vocab.length;this.vocab=new Array(F),this.scores=new Array(F);for(let R=0;R<F;++R)[this.vocab[R],this.scores[R]]=p.vocab[R];this.unk_token_id=p.unk_id,this.unk_token=this.vocab[p.unk_id],this.tokens_to_ids=new Map(this.vocab.map((R,M)=>[R,M])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=x,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=iO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new tO,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(p){let x=p.chars,F=1,R=0;for(;R<x.length;){let M=!1,O=[],G=x.slice(R).join(""),J=this.trie.common_prefix_search(G);for(let ne of J){O.push(ne);let z=this.tokens_to_ids.get(ne),te=this.scores[z],ie=ZQ(ne);p.insert(R,ie,te,z),!M&&ie===F&&(M=!0)}M||p.insert(R,F,this.unk_score,this.unk_token_id),R+=F}}tokenize(p){let x=new nO(p,this.bos_token_id,this.eos_token_id);return this.populate_nodes(x),x.tokens()}encode(p){let x=[];for(let F of p){let R=this.tokenize(F);x.push(...R)}return x}},hw=oO,sO=class{constructor(p=(F,R)=>F>R,x=1/0){this._heap=[],this._comparator=p,this._max_size=x}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...p){return this.extend(p)}extend(p){for(let x of p)if(this.size<this._max_size)this._heap.push(x),this._sift_up();else{let F=this._smallest();this._comparator(x,this._heap[F])&&(this._heap[F]=x,this._sift_up_from(F))}return this.size}pop(){let p=this.peek(),x=this.size-1;return x>0&&this._swap(0,x),this._heap.pop(),this._sift_down(),p}replace(p){let x=this.peek();return this._heap[0]=p,this._sift_down(),x}_parent(p){return(p+1>>>1)-1}_left(p){return(p<<1)+1}_right(p){return p+1<<1}_greater(p,x){return this._comparator(this._heap[p],this._heap[x])}_swap(p,x){let F=this._heap[p];this._heap[p]=this._heap[x],this._heap[x]=F}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(p){for(;p>0&&this._greater(p,this._parent(p));)this._swap(p,this._parent(p)),p=this._parent(p)}_sift_down(){let p=0;for(;this._left(p)<this.size&&this._greater(this._left(p),p)||this._right(p)<this.size&&this._greater(this._right(p),p);){let x=this._right(p)<this.size&&this._greater(this._right(p),this._left(p))?this._right(p):this._left(p);this._swap(p,x),p=x}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},aO=sO,uO=class{constructor(p){this.capacity=p,this.cache=new Map}get(p){if(!this.cache.has(p))return;let x=this.cache.get(p);return this.cache.delete(p),this.cache.set(p,x),x}put(p,x){this.cache.has(p)&&this.cache.delete(p),this.cache.set(p,x),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},lO=uO,cO=class extends m0{constructor(p){super(p),this.tokens_to_ids=jm(p.vocab),this.unk_token_id=this.tokens_to_ids.get(p.unk_token),this.unk_token=p.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[F,R]of this.tokens_to_ids)this.vocab[R]=F;let x=Array.isArray(p.merges[0]);this.merges=x?p.merges:p.merges.map(F=>F.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((F,R)=>[JSON.stringify(F),R])),this.end_of_word_suffix=p.end_of_word_suffix,this.continuing_subword_suffix=p.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new lO(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(p){if(p.length===0)return[];let x=this.cache.get(p);if(x!==void 0)return x;let F=Array.from(p);this.end_of_word_suffix&&(F[F.length-1]+=this.end_of_word_suffix);let R=[];if(F.length>1){let M=new aO((J,ne)=>J.score<ne.score),O={token:F[0],bias:0,prev:null,next:null},G=O;for(let J=1;J<F.length;++J){let ne={bias:J/F.length,token:F[J],prev:G,next:null};G.next=ne,this.add_node(M,G),G=ne}for(;!M.is_empty();){let J=M.pop();if(J.deleted||!J.next||J.next.deleted)continue;if(J.deleted=!0,J.next.deleted=!0,J.prev){let z={...J.prev};J.prev.deleted=!0,J.prev=z,z.prev?z.prev.next=z:O=z}let ne={token:J.token+J.next.token,bias:J.bias,prev:J.prev,next:J.next.next};ne.prev?(ne.prev.next=ne,this.add_node(M,ne.prev)):O=ne,ne.next&&(ne.next.prev=ne,this.add_node(M,ne))}for(let J=O;J!==null;J=J.next)R.push(J.token)}else R=F;if(this.continuing_subword_suffix)for(let M=0;M<R.length-1;++M)R[M]+=this.continuing_subword_suffix;return p.length<this.max_length_to_cache&&this.cache.put(p,R),R}add_node(p,x){let F=this.bpe_ranks.get(JSON.stringify([x.token,x.next.token]));F!==void 0&&(x.score=F+x.bias,p.push(x))}encode(p){let x=[];for(let F of p){if(this.ignore_merges&&this.tokens_to_ids.has(F)){x.push(F);continue}let R=this.bpe(F);for(let M of R)if(this.tokens_to_ids.has(M))x.push(M);else if(this.byte_fallback){let O=Array.from(this.text_encoder.encode(M)).map(G=>`<0x${G.toString(16).toUpperCase().padStart(2,"0")}>`);O.every(G=>this.tokens_to_ids.has(G))?x.push(...O):x.push(this.unk_token)}else x.push(this.unk_token)}return x}},fw=cO,dO=class extends m0{constructor(p,x){super(p);let F=p.vocab;this.tokens_to_ids=jm(x.target_lang?F[x.target_lang]:F),this.bos_token=x.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=x.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=x.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=x.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[R,M]of this.tokens_to_ids)this.vocab[M]=R}encode(p){return p}},hO=dO;function fO(p,x){switch(p.type){case"WordPiece":return new cw(p);case"Unigram":return new hw(p,x.eos_token);case"BPE":return new fw(p);default:if(p.vocab)return Array.isArray(p.vocab)?new hw(p,x.eos_token):Object.hasOwn(p,"continuing_subword_prefix")&&Object.hasOwn(p,"unk_token")?Object.hasOwn(p,"merges")?new fw(p):new cw(p):new hO(p,{target_lang:x.target_lang,bos_token:x.bos_token,eos_token:x.eos_token,pad_token:x.pad_token,unk_token:x.unk_token});throw new Error(`Unknown TokenizerModel type: ${p?.type}`)}}var AO=fO,pO=class extends lf{constructor(p){super(),this.config=p}_call(p,...x){return this.post_process(p,...x)}},cf=pO,gO=class extends cf{post_process(p,x=null,F=!0){let R=x===null?this.config.single:this.config.pair,M=[],O=[];for(let G of R)"SpecialToken"in G?F&&(M.push(G.SpecialToken.id),O.push(G.SpecialToken.type_id)):"Sequence"in G&&(G.Sequence.id==="A"?(M=qs(M,p),O=qs(O,new Array(p.length).fill(G.Sequence.type_id))):G.Sequence.id==="B"&&(M=qs(M,x),O=qs(O,new Array(x.length).fill(G.Sequence.type_id))));return{tokens:M,token_type_ids:O}}},mO=gO,EO=class extends cf{post_process(p,x=null){return{tokens:x?qs(p,x):p}}},yO=EO,CO=class extends cf{constructor(p){super(p),this.sep=p.sep,this.cls=p.cls}post_process(p,x=null,F=!0){F&&(p=qs([this.cls[0]],p,[this.sep[0]]));let R=new Array(p.length).fill(0);if(x){let M=[],O=F?[this.sep[0]]:[];p=qs(p,M,x,O),R=qs(R,new Array(x.length+M.length+O.length).fill(1))}return{tokens:p,token_type_ids:R}}},DO=CO,bO=class extends cf{constructor(p){super(p),this.sep=p.sep,this.cls=p.cls}post_process(p,x,F=!0){F&&(p=qs([this.cls[0]],p,[this.sep[0]]));let R=new Array(p.length).fill(0);if(x){let M=F?[this.sep[0]]:[],O=F?[this.sep[0]]:[];p=qs(p,M,x,O),R=qs(R,new Array(x.length+M.length+O.length).fill(1))}return{tokens:p,token_type_ids:R}}},wO=bO,IO=class extends cf{constructor(p){super(p),this.processors=(p.processors??[]).map(x=>Aw(x))}post_process(p,x=null,F=!0){let R={tokens:p};for(let M of this.processors)R=M.post_process(R.tokens,x,F);return R}},vO=IO;function BO(p){if(p===null)return null;switch(p.type){case"TemplateProcessing":return new mO(p);case"ByteLevel":return new yO(p);case"BertProcessing":return new DO(p);case"RobertaProcessing":return new wO(p);case"Sequence":return new vO(p);default:throw new Error(`Unknown PostProcessor type: ${p.type}`)}}var Aw=BO,xO=class extends lf{constructor(p){super(),this.config=p,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in p?p.trim_offsets:!1}_call(p){return this.decode(p)}decode(p){return this.decode_chain(p).join("")}},Xa=xO,_O=class extends Xa{constructor(p){super(p),this.byte_decoder=VQ,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(p){let x=p.join(""),F=new Uint8Array([...x].map(R=>this.byte_decoder[R]));return this.text_decoder.decode(F)}decode_chain(p){let x=[],F=[];for(let R of p)this.added_tokens.find(M=>M.content===R)!==void 0?(F.length>0&&(x.push(this.convert_tokens_to_string(F)),F=[]),x.push(R)):F.push(R);return F.length>0&&x.push(this.convert_tokens_to_string(F)),x}},SO=_O,FO=class extends Xa{constructor(p){super(p),this.cleanup=p.cleanup}decode_chain(p){return p.map((x,F)=>{if(F!==0){let R=this.config.prefix;R&&x.startsWith(R)?x=x.replace(R,""):x=" "+x}return this.cleanup&&(x=$m(x)),x})}},kO=FO,TO=class extends Xa{constructor(p){super(p),this.replacement=p.replacement??"\u2581"}decode_chain(p){let x=[];for(let F=0;F<p.length;++F){let R=p[F].replaceAll(this.replacement," ");F==0&&R.startsWith(" ")&&(R=R.substring(1)),x.push(R)}return x}},RO=TO,QO=class extends Xa{constructor(p){super(p),this.suffix=p.suffix??""}decode_chain(p){return p.map((x,F)=>x.replaceAll(this.suffix,F===p.length-1?"":" "))}},NO=QO,OO=class extends Xa{constructor(p){super(p),this.pad_token=p.pad_token??"",this.word_delimiter_token=p.word_delimiter_token??"",this.cleanup=p.cleanup}convert_tokens_to_string(p){if(p.length===0)return"";let x=[p[0]];for(let R=1;R<p.length;++R)p[R]!==x.at(-1)&&x.push(p[R]);let F=x.filter(R=>R!==this.pad_token).join("");return this.cleanup&&(F=$m(F).replaceAll(this.word_delimiter_token," ").trim()),F}decode_chain(p){return[this.convert_tokens_to_string(p)]}},LO=OO,PO=class extends Xa{constructor(p){super(p),this.decoders=(p.decoders??[]).map(x=>pw(x))}decode_chain(p){return this.decoders.reduce((x,F)=>F.decode_chain(x),p)}},MO=PO,UO=class extends Xa{decode_chain(p){let x=p0(this.config.pattern),F=this.config.content??"";return x===null?p:p.map(R=>R.replaceAll(x,F))}},$O=UO,jO=class extends Xa{decode_chain(p){return[p.join("")]}},HO=jO,qO=class extends Xa{constructor(p){super(p),this.content=p.content??"",this.start=p.start??0,this.stop=p.stop??0}decode_chain(p){return p.map(x=>{let F=0;for(let M=0;M<this.start&&x[M]===this.content;++M)F=M+1;let R=x.length;for(let M=0;M<this.stop;++M){let O=x.length-M-1;if(x[O]===this.content){R=O;continue}else break}return x.slice(F,R)})}},GO=qO,VO=class extends Xa{constructor(p){super(p),this.text_decoder=new TextDecoder}decode_chain(p){let x=[],F=[];for(let R of p){let M=null;if(R.length===6&&R.startsWith("<0x")&&R.endsWith(">")){let O=parseInt(R.slice(3,5),16);isNaN(O)||(M=O)}if(M!==null)F.push(M);else{if(F.length>0){let O=this.text_decoder.decode(Uint8Array.from(F));x.push(O),F=[]}x.push(R)}}if(F.length>0){let R=this.text_decoder.decode(Uint8Array.from(F));x.push(R),F=[]}return x}},JO=VO;function YO(p){if(p===null)return null;switch(p.type){case"ByteLevel":return new SO(p);case"WordPiece":return new kO(p);case"Metaspace":return new RO(p);case"BPEDecoder":return new NO(p);case"CTC":return new LO(p);case"Sequence":return new MO(p);case"Replace":return new $O(p);case"Fuse":return new HO(p);case"Strip":return new GO(p);case"ByteFallback":return new JO(p);default:throw new Error(`Unknown Decoder type: ${p.type}`)}}var pw=YO,zO=class{constructor(p,x){let F=aw(p,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(F)throw new Error(F);let R=aw(x,"Config");if(R)throw new Error(R);this.tokenizer=p,this.config=x,this.normalizer=uw(this.tokenizer.normalizer),this.pre_tokenizer=lw(this.tokenizer.pre_tokenizer),this.model=AO(this.tokenizer.model,this.config),this.post_processor=Aw(this.tokenizer.post_processor),this.decoder=pw(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(M=>{let O=new qQ(M);this.added_tokens.push(O),this.model.tokens_to_ids.set(O.content,O.id),this.model.vocab[O.id]=O.content,O.special&&(this.special_tokens.push(O.content),this.all_special_ids.push(O.id))}),(this.config.additional_special_tokens??[]).forEach(M=>{this.special_tokens.includes(M)||this.special_tokens.push(M)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new jQ(this.added_tokens.map(M=>M.content)),this.added_tokens_map=new Map(this.added_tokens.map(M=>[M.content,M])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(p,{text_pair:x=null,add_special_tokens:F=!0,return_token_type_ids:R=null}={}){let{tokens:M,token_type_ids:O}=this.tokenize_helper(p,{text_pair:x,add_special_tokens:F}),G=this.model.convert_tokens_to_ids(M),J={ids:G,tokens:M,attention_mask:new Array(G.length).fill(1)};return R&&O&&(J.token_type_ids=O),J}decode(p,x={}){if(!Array.isArray(p)||p.length===0||!KQ(p[0]))throw Error("token_ids must be a non-empty array of integers.");let F=this.model.convert_ids_to_tokens(p);x.skip_special_tokens&&(F=F.filter(M=>!this.special_tokens.includes(M)));let R=this.decoder?this.decoder(F):F.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(R=R.replaceAll(this.decoder.end_of_word_suffix," "),x.skip_special_tokens&&(R=R.trim())),(x.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(R=$m(R)),R}tokenize(p,{text_pair:x=null,add_special_tokens:F=!1}={}){return this.tokenize_helper(p,{text_pair:x,add_special_tokens:F}).tokens}encode_text(p){if(p===null)return null;let x=this.added_tokens_splitter.split(p);return x.forEach((F,R)=>{let M=this.added_tokens_map.get(F);M&&(M.lstrip&&R>0&&(x[R-1]=x[R-1].trimEnd()),M.rstrip&&R<x.length-1&&(x[R+1]=x[R+1].trimStart()))}),x.flatMap((F,R)=>{if(F.length===0)return[];if(this.added_tokens_map.has(F))return[F];if(this.remove_space===!0&&(F=F.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(F=XQ(F)),this.normalizer!==null&&(F=this.normalizer(F)),F.length===0)return[];let M=this.pre_tokenizer!==null?this.pre_tokenizer(F,{section_index:R}):[F];return this.model(M)})}tokenize_helper(p,{text_pair:x=null,add_special_tokens:F=!0}){let R=this.encode_text(p),M=this.encode_text(x||null);return this.post_processor?this.post_processor(R,M,F):{tokens:qs(R??[],M??[])}}token_to_id(p){return this.model.tokens_to_ids.get(p)}id_to_token(p){return this.model.vocab[p]}get_added_tokens_decoder(){let p=new Map;for(let x of this.added_tokens)p.set(x.id,x);return p}},WO=zO,KO=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(p,x,F={}){this.modelId=p,this.logger=x,this.options=F,this.cacheDir=F.cacheDir||(0,h0.join)((0,UQ.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=p.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${p.split("/").pop()}`}getCachePaths(){let p=(0,h0.join)(this.cacheDir,this.safeModelName);return{modelDir:p,tokenizerJson:(0,h0.join)(p,"tokenizer.json"),tokenizerConfig:(0,h0.join)(p,"tokenizer_config.json")}}ensureDir(p){(0,f0.existsSync)(p)||(0,f0.mkdirSync)(p,{recursive:!0})}async loadFromCache(){try{let p=this.getCachePaths();if(!(0,f0.existsSync)(p.tokenizerJson)||!(0,f0.existsSync)(p.tokenizerConfig))return null;let[x,F]=await Promise.all([A0.promises.readFile(p.tokenizerJson,"utf-8"),A0.promises.readFile(p.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(x),tokenizerConfig:JSON.parse(F)}}catch(p){return this.logger?.warn(`Failed to load from cache: ${p.message}`),null}}async downloadAndCache(){let p=this.getCachePaths(),x={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 F=new AbortController,R=setTimeout(()=>F.abort(),this.options.timeout||3e4);try{let[M,O]=await Promise.all([fetch(x.json,{signal:F.signal}),fetch(x.config,{signal:F.signal})]);if(!M.ok)throw new Error(`Failed to fetch tokenizer.json: ${M.statusText}`);let[G,J]=await Promise.all([M.json(),O.ok?O.json():Promise.resolve({})]);return this.ensureDir(p.modelDir),await Promise.all([A0.promises.writeFile(p.tokenizerJson,JSON.stringify(G,null,2)),A0.promises.writeFile(p.tokenizerConfig,JSON.stringify(J,null,2))]),{tokenizerJson:G,tokenizerConfig:J}}finally{clearTimeout(R)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let p=this.getCachePaths();this.ensureDir(this.cacheDir);let x=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new WO(x.tokenizerJson,x.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(p){throw this.logger?.error(`Failed to initialize tokenizer: ${p.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${p.message}`)}}async countTokens(p){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let x=this.extractTextFromRequest(p);return this.tokenizer.encode(x).ids.length}catch(x){throw this.logger?.error(`Error counting tokens: ${x.message}`),x}}isInitialized(){return this.tokenizer!==null}encodeText(p){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(p).ids}dispose(){this.tokenizer=null}extractTextFromRequest(p){let x=[],{messages:F,system:R,tools:M}=p;if(Array.isArray(F)){for(let O of F)if(typeof O.content=="string")x.push(O.content);else if(Array.isArray(O.content))for(let G of O.content)G.type==="text"&&G.text?x.push(G.text):G.type==="tool_use"&&G.input?x.push(JSON.stringify(G.input)):G.type==="tool_result"&&x.push(typeof G.content=="string"?G.content:JSON.stringify(G.content))}if(typeof R=="string")x.push(R);else if(Array.isArray(R)){for(let O of R)if(O.type==="text"){if(typeof O.text=="string")x.push(O.text);else if(Array.isArray(O.text))for(let G of O.text)G&&x.push(G)}}if(M)for(let O of M)O.name&&x.push(O.name),O.description&&x.push(O.description),O.input_schema&&x.push(JSON.stringify(O.input_schema));return x.join(" ")}},ZO=class{type="api";name;config;logger;options;constructor(p,x,F={}){if(!p.url||!p.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:p.url,apiKey:p.apiKey,requestFormat:p.requestFormat||"standard",responseField:p.responseField||"token_count",headers:p.headers||{}},this.logger=x,this.options=F;try{let R=new URL(p.url);this.name=`api-${R.hostname}`}catch{this.name=`api-${p.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(p){try{let x=this.formatRequestBody(p),F={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},R=new AbortController,M=setTimeout(()=>R.abort(),this.options.timeout||3e4),O=await fetch(this.config.url,{method:"POST",headers:F,body:JSON.stringify(x),signal:R.signal});if(clearTimeout(M),!O.ok)throw new Error(`API tokenizer request failed: ${O.status} ${O.statusText}`);let G=await O.json();return this.extractTokenCount(G)}catch(x){throw x.name==="AbortError"?new Error("API tokenizer request timed out"):x}}isInitialized(){return!0}dispose(){}formatRequestBody(p){switch(this.config.requestFormat){case"standard":return p;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(p)};case"anthropic":return{messages:p.messages||[],system:p.system,tools:p.tools};case"custom":return{text:this.extractConcatenatedText(p)};default:return p}}extractMessagesAsOpenAIFormat(p){return p.messages?p.messages.map(x=>({role:x.role,content:this.extractTextFromMessage(x)})):[]}extractTextFromMessage(p){return typeof p.content=="string"?p.content:Array.isArray(p.content)?p.content.map(x=>x.type==="text"&&x.text?x.text:x.type==="tool_use"&&x.input?JSON.stringify(x.input):x.type==="tool_result"?typeof x.content=="string"?x.content:JSON.stringify(x.content):"").join(" "):""}extractConcatenatedText(p){let x=[];return p.messages&&p.messages.forEach(F=>{x.push(this.extractTextFromMessage(F))}),typeof p.system=="string"?x.push(p.system):Array.isArray(p.system)&&p.system.forEach(F=>{F.type==="text"&&(typeof F.text=="string"?x.push(F.text):Array.isArray(F.text)&&F.text.forEach(R=>{R&&x.push(R)}))}),p.tools&&p.tools.forEach(F=>{F.name&&x.push(F.name),F.description&&x.push(F.description),F.input_schema&&x.push(JSON.stringify(F.input_schema))}),x.join(" ")}extractTokenCount(p){try{let x=this.config.responseField,F=x.split("."),R=p;for(let M of F){if(R==null)throw new Error(`Field path '${x}' not found in response`);R=R[M]}if(typeof R!="number")throw new Error(`Expected number at field path '${x}', got ${typeof R}`);return R}catch(x){throw this.logger?.error(`Failed to extract token count from API response: ${x.message}. Response: ${JSON.stringify(p)}`),new Error(`Invalid response from API tokenizer: ${x.message}`)}}},qm=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(p,x,F={}){this.configService=p,this.logger=x,this.options={timeout:F.timeout??3e4,...F}}async initialize(){try{this.fallbackTokenizer=new nw("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(p){throw this.logger?.error(`TokenizerService initialization error: ${p.message}`),p}}async getTokenizer(p){let x=this.getCacheKey(p);if(this.tokenizers.has(x))return this.tokenizers.get(x);let F;try{switch(p.type){case"tiktoken":F=new nw(p.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${p.model}`),F=new KO(p.model,this.logger,{timeout:this.options.timeout});break;case"api":F=new ZO(p,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${p.type}`)}return this.logger?.info(`Calling initialize() on ${p.type} tokenizer...`),await F.initialize(),this.tokenizers.set(x,F),this.logger?.info(`Tokenizer initialized successfully: ${p.type} (${x})`),F}catch(R){return this.logger?.error(`Failed to initialize ${p.type} tokenizer: ${R.message}`),this.logger?.error(`Error stack: ${R.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(p,x){let F=x?await this.getTokenizer(x):this.fallbackTokenizer;return{tokenCount:await F.countTokens(p),tokenizerUsed:F.name,cached:!1}}getTokenizerConfigForModel(p,x){let F=(this.configService.get("providers")||[]).find(R=>R.name===p);if(F?.tokenizer)return F.tokenizer.models?.[x]?F.tokenizer.models[x]:F.tokenizer.default}dispose(){this.tokenizers.forEach(p=>{try{p.dispose()}catch(x){this.logger?.error(`Error disposing tokenizer: ${x}`)}}),this.tokenizers.clear()}getCacheKey(p){switch(p.type){case"tiktoken":return`tiktoken:${p.encoding||"cl100k_base"}`;case"huggingface":return`hf:${p.model}`;case"api":return`api:${p.url}`;default:return`unknown:${JSON.stringify(p)}`}}},XO=Mp(),e6=class{capacity;cache;constructor(p){this.capacity=p,this.cache=new Map}get(p){if(!this.cache.has(p))return;let x=this.cache.get(p);return this.cache.delete(p),this.cache.set(p,x),x}put(p,x){if(this.cache.has(p))this.cache.delete(p);else if(this.cache.size>=this.capacity){let F=this.cache.keys().next().value;F!==void 0&&this.cache.delete(F)}this.cache.set(p,x)}values(){return Array.from(this.cache.values())}},gw=new e6(100),Gm=require("fs/promises"),mw=require("fs/promises"),Vm=require("path"),E0=Qa();de();var df=require("fs"),Ew=require("path"),t6=Qa(),Jm=(0,Ew.join)(t6.HOME_DIR,"runtime"),Ym=(0,Ew.join)(Jm,"quota-store.json"),Fd=new Map,yw=!1,r6=null;function Cw(p,x){p&&Fd.set(p,{...x,provider:p,capturedAt:Date.now()})}function Dw(p){let x=Fd.get(p);return x?{...x}:void 0}function n6(){return Array.from(Fd.values()).map(p=>({...p}))}function i6(){try{if(!(0,df.existsSync)(Ym))return;let p=JSON.parse((0,df.readFileSync)(Ym,"utf-8"));if(!Array.isArray(p))return;let x=Date.now();for(let F of p)if(F&&F.provider){if(F.capturedAt&&x-F.capturedAt>1440*60*1e3)continue;Fd.set(F.provider,F)}}catch{}}function bw(){try{if(Fd.size===0)return;(0,df.existsSync)(Jm)||(0,df.mkdirSync)(Jm,{recursive:!0}),(0,df.writeFileSync)(Ym,JSON.stringify(Array.from(Fd.values()),null,2),"utf-8")}catch{}}function ww(){yw||(yw=!0,i6(),r6=setInterval(bw,6e4),process.on("exit",bw))}I();var Nu=(0,XO.get_encoding)("cl100k_base"),Iw=(p,x,F)=>{let R=0;return Array.isArray(p)&&p.forEach(M=>{typeof M.content=="string"?R+=Nu.encode(M.content).length:Array.isArray(M.content)&&M.content.forEach(O=>{O.type==="text"?R+=Nu.encode(O.text).length:O.type==="tool_use"?R+=Nu.encode(JSON.stringify(O.input)).length:O.type==="tool_result"&&(R+=Nu.encode(typeof O.content=="string"?O.content:JSON.stringify(O.content)).length)})}),typeof x=="string"?R+=Nu.encode(x).length:Array.isArray(x)&&x.forEach(M=>{M.type==="text"&&(typeof M.text=="string"?R+=Nu.encode(M.text).length:Array.isArray(M.text)&&M.text.forEach(O=>{R+=Nu.encode(O||"").length}))}),F&&F.forEach(M=>{M.description&&(R+=Nu.encode(M.name+M.description).length),M.input_schema&&(R+=Nu.encode(JSON.stringify(M.input_schema)).length)}),R},vw=async(p,x)=>{if(p.sessionId){let F=await Fw(p.sessionId);if(F){let R=(0,Vm.join)(E0.HOME_DIR,F,"config.json"),M=(0,Vm.join)(E0.HOME_DIR,F,`${p.sessionId}.json`);try{let O=JSON.parse(await(0,Gm.readFile)(M,"utf8"));if(O&&O.Router)return O.Router}catch{}try{let O=JSON.parse(await(0,Gm.readFile)(R,"utf8"));if(O&&O.Router)return O.Router}catch{}}}};function y0(p){let x=p||"";return x.includes(",")&&(x=x.split(",").pop()||x),x.includes("/")&&(x=x.split("/").pop()||x),x.includes(":")&&(x=x.split(":")[0]),x.trim().toLowerCase()}function Bw(p){let x=y0(p),F=x.includes("[1m]")||x.endsWith("[1m"),R=x.replace(/\[1m\]|\[1m$/g,""),M=R.match(/^ccr-(opus|sonnet|haiku)$/i);if(M)return{family:M[1].toLowerCase(),extended:F};let O=R.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||R.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return O?{family:O[1].toLowerCase(),extended:F}:{family:null,extended:F}}function o6(p,x){if(!x||!p)return null;let F=y0(p);if(x[p])return x[p];if(x[F])return x[F];let{family:R}=Bw(p);if(R&&x[R])return x[R];for(let[M,O]of Object.entries(x)){let G=y0(M);if(G&&F.includes(G))return O}return null}function xw(p){return p?(p.input_tokens||0)+(p.cache_read_input_tokens||0)+(p.cache_creation_input_tokens||0):0}function _w(p){if(!p?.includes(","))return null;let[x,...F]=p.split(","),R=x.trim(),M=F.join(",").trim();return!R||!M?null:{providerName:R,routeModel:M}}function Wo(p,x,F,R){let M=_w(p);if(!M)return p;let{providerName:O,routeModel:G}=M,J=x.find(te=>te.name.toLowerCase()===O.toLowerCase());if(J&&J.enabled===!1)return null;if(R&&!F){let te=C(),ie=te.getPromotion(O,G,R,x);if(ie){let ce=_w(ie);if(ce){let X=x.find(pe=>pe.name.toLowerCase()===ce.providerName.toLowerCase()),le=X?.models?.find(pe=>String(pe).toLowerCase()===ce.routeModel.toLowerCase());if(X&&le)return`${X.name},${le}`}te.clear(O,G,R)}}if(!F&&!Q().isAvailable(O,G))return null;let ne=Dw(O);if(ne){let te=ne.limitDaily!==void 0&&ne.usedDailyBalance!==void 0&&ne.usedDailyBalance>=ne.limitDaily,ie=ne.totalBalance!==void 0&&ne.usedBalance!==void 0&&ne.usedBalance>=ne.totalBalance;if(te||ie)return null}let z=J?.models?.find(te=>String(te).toLowerCase()===G.toLowerCase());return J&&z?`${J.name},${z}`:p}function ya(p,x,F,R,M){let O=Q(),G=[F?.[p],R?.[p]];for(let J of G)if(!(!Array.isArray(J)||J.length===0))for(let ne of J){let z=Wo(ne,x);if(z)return z}return null}function s6(p){return p.body.messages?.some(x=>x.role==="user"&&Array.isArray(x.content)&&x.content.some(F=>F.type==="image"||F.type==="image_url"||Array.isArray(F?.content)&&F.content.some(R=>R.type==="image"||R.type==="image_url")))}function a6(p){let x=y0(p);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(F=>F.test(x))}function u6(p,x,F,R,M,O,G){let J=F.longContextThreshold||6e4,ne=Math.max(x,xw(M)),z=p.modelFamily;if((O||ne>2e5)&&F.extendedContext){let te=Wo(F.extendedContext,R,!1,"extendedContext");if(te)return p.log.info(`Family: using extended context model (1M+), tokens: ${ne}, estimated: ${x}, explicit: ${O}`),{model:te,scenarioType:"extendedContext",isFallback:!1};let ie=ya("extendedContext",R,F.fallback,G,z);if(ie)return p.log.info(`Family: using extended context fallback model (1M+), tokens: ${ne}, estimated: ${x}, explicit: ${O}`),{model:ie,scenarioType:"extendedContext",isFallback:!0};p.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(ne>J&&(F.longContext||F.fallback?.longContext?.length||G?.longContext?.length)){let te=F.longContext?Wo(F.longContext,R,!1,"longContext"):null;if(te)return p.log.info(`Family: using long context model, tokens: ${ne}, estimated: ${x}`),{model:te,scenarioType:"longContext",isFallback:!1};let ie=ya("longContext",R,F.fallback,G,z);if(ie)return p.log.info(`Family: using long context fallback model, tokens: ${ne}, estimated: ${x}`),{model:ie,scenarioType:"longContext",isFallback:!0};p.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(p.body.tools)&&p.body.tools.some(te=>te.type?.startsWith("web_search"))&&F.webSearch){let te=Wo(F.webSearch,R,!1,"webSearch");if(te)return{model:te,scenarioType:"webSearch",isFallback:!1};let ie=ya("webSearch",R,F.fallback,G,z);if(ie)return p.log.info("Family: using webSearch fallback model"),{model:ie,scenarioType:"webSearch",isFallback:!0};p.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(p.body.thinking&&F.think){let te=Wo(F.think,R,!1,"think");if(te)return{model:te,scenarioType:"think",isFallback:!1};let ie=ya("think",R,F.fallback,G,z);if(ie)return p.log.info("Family: using think fallback model"),{model:ie,scenarioType:"think",isFallback:!0};p.log.warn("Family: think model unavailable (fail pool), skipping")}if(F.default){let te=Wo(F.default,R,!1,"default");if(te)return{model:te,scenarioType:"default",isFallback:!1};let ie=ya("default",R,F.fallback,G,z);if(ie)return p.log.info("Family: using default fallback model"),{model:ie,scenarioType:"default",isFallback:!0};p.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var l6=async(p,x,F,R)=>{let M=await vw(p,F),O=F.get("providers")||[],G=M||F.get("Router"),J=F.get("fallback");if(p.body.model.includes(",")){let De=Wo(p.body.model,O,!1,"default");if(De)return{model:De,scenarioType:"default"};p.log.warn(`Explicit model ${p.body.model} unavailable (fail pool), trying fallback`);let be=ya("default",O,void 0,J);if(be)return p.log.info(`Using fallback for explicit model: ${be}`),{model:be,scenarioType:"default"};p.log.warn(`No fallback available for explicit model ${p.body.model}, continuing through routing logic`)}let{family:ne,extended:z}=Bw(p.body.model),te=G?.families?.[ne||""];if(te&&G?.enableFamilyRouting){p.log.info(`Using model family routing for: ${ne}${z?" (1M)":""}`),p.modelFamily=ne,p.familyFallback=te.fallback;let De=u6(p,x,te,O,R,z,J);if(De)return{model:De.model,scenarioType:De.scenarioType}}let ie=o6(p.body.model,G?.models);if(ie){let De=Wo(ie,O,!1,"modelMapping");if(De)return p.log.info(`Using mapped model for ${p.body.model}: ${ie}`),{model:De,scenarioType:"modelMapping"};p.log.warn(`Mapped model ${ie} unavailable (fail pool), skipping`)}let ce=Math.max(x,xw(R)),X=G?.extendedContextThreshold||2e5;if(ce>X&&G?.extendedContext){p.log.info(`Using extended context (1M) model due to token count: ${ce}, estimated: ${x}, threshold: ${X}`);let De=Wo(G.extendedContext,O,!1,"extendedContext");if(De)return{model:De,scenarioType:"extendedContext"};p.log.warn(`Extended context model ${G.extendedContext} unavailable (fail pool), trying fallback`);let be=ya("extendedContext",O,void 0,J);if(be)return{model:be,scenarioType:"extendedContext"}}let le=G?.longContextThreshold||6e4;if(ce>le&&G?.longContext){p.log.info(`Using long context model due to token count: ${ce}, estimated: ${x}, threshold: ${le}`);let De=Wo(G.longContext,O,!1,"longContext");if(De)return{model:De,scenarioType:"longContext"};p.log.warn(`Long context model ${G.longContext} unavailable (fail pool), trying fallback`);let be=ya("longContext",O,void 0,J);if(be)return{model:be,scenarioType:"longContext"}}if(p.body?.system?.length>1&&p.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let De=p.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(De)return p.body.system[1].text=p.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${De[1]}</CCR-SUBAGENT-MODEL>`,""),{model:De[1],scenarioType:"default"}}let pe=F.get("Router");if(p.body.model?.includes("claude")&&p.body.model?.includes("haiku")&&pe?.background){p.log.info(`Using background model for ${p.body.model}`);let De=Wo(pe.background,O,!1,"background");if(De)return{model:De,scenarioType:"background"};p.log.warn(`Background model ${pe.background} unavailable (fail pool), falling through`)}if(Array.isArray(p.body.tools)&&p.body.tools.some(De=>De.type?.startsWith("web_search"))&&G?.webSearch){let De=Wo(G.webSearch,O,!1,"webSearch");if(De)return{model:De,scenarioType:"webSearch"};p.log.warn(`WebSearch model ${G.webSearch} unavailable (fail pool), trying fallback`);let be=ya("webSearch",O,void 0,J);if(be)return{model:be,scenarioType:"webSearch"}}if(p.body.thinking&&G?.think){p.log.info(`Using think model for ${p.body.thinking}`);let De=Wo(G.think,O,!1,"think");if(De)return{model:De,scenarioType:"think"};p.log.warn(`Think model ${G.think} unavailable (fail pool), trying fallback`);let be=ya("think",O,void 0,J);if(be)return{model:be,scenarioType:"think"}}if(G?.default){let De=Wo(G.default,O,!1,"default");if(De)return{model:De,scenarioType:"default"};p.log.warn(`Default model ${G.default} unavailable (fail pool), trying fallback`);let be=ya("default",O,void 0,J);if(be)return{model:be,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},zm=async(p,x,F)=>{let{configService:R,event:M}=F;if(p.originalModel=p.body.model,p.body.metadata?.user_id){let ce=p.body.metadata.user_id.split("_session_");ce.length>1&&(p.sessionId=ce[1])}let O=await vw(p,R)||R.get("Router"),G=R.get("providers")||[],J=gw.get(p.sessionId),{messages:ne,system:z=[],tools:te}=p.body,ie=R.get("REWRITE_SYSTEM_PROMPT");if(ie&&z.length>1&&z[1]?.text?.includes("<env>")){let ce=await(0,Gm.readFile)(ie,"utf-8");z[1].text=`${ce}<env>${z[1].text.split("<env>").pop()}`}try{let[ce,X]=p.body.model.split(","),le=F.tokenizerService?.getTokenizerConfigForModel(ce,X),pe;F.tokenizerService?pe=(await F.tokenizerService.countTokens({messages:ne,system:z,tools:te},le)).tokenCount:pe=Iw(ne,z,te),p.tokenCount=pe;let De,be=R.get("CUSTOM_ROUTER_PATH");if(be)try{De=await require(be)(p,R.getAll(),{event:M})}catch(Be){p.log.error(`failed to load custom router: ${Be.message}`)}if(De)p.scenarioType="default";else{let Be=await l6(p,pe,R,J);De=Be.model,p.scenarioType=Be.scenarioType}if(O?.image&&De!==O.image&&s6(p)&&!a6(De)){let Be=Wo(O.image,G,!1,"image");Be?(p.log.info(`Using image model fallback for ${De}`),De=Be,p.scenarioType="image"):(p.log.warn(`Image model ${O.image} unavailable (fail pool), keeping ${De}`),p.scenarioType="image")}p.body.model=De}catch(ce){p.log.error(`Error in router middleware: ${ce.message}`),p.body.model=O?.default,p.scenarioType="default"}},Ou=new Map,Sw=1e3;function Wm(){if(Ou.size<=Sw)return;let p=[...Ou.keys()].slice(0,Ou.size-Sw);for(let x of p)Ou.delete(x)}var Fw=async p=>{if(Ou.has(p)){let x=Ou.get(p);return!x||x===""?null:x}try{let x=await(0,mw.opendir)(E0.CLAUDE_PROJECTS_DIR),F=[];for await(let O of x)O.isDirectory()&&F.push(O.name);let R=F.map(async O=>{let G=(0,Vm.join)(E0.CLAUDE_PROJECTS_DIR,O,`${p}.jsonl`);try{return(await(0,mw.stat)(G)).isFile()?O:null}catch{return null}}),M=await Promise.all(R);for(let O of M)if(O)return Ou.set(p,O),Wm(),O;return Ou.set(p,""),Wm(),null}catch(x){return console.error("Error searching for project by session:",x),Ou.set(p,""),Wm(),null}};de();var Ec=class{async fetchJson(p,x,F,R,M){let O=M||x.apiKey;if(!O)return null;let G={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${O}`},signal:AbortSignal.timeout(F)};if(R)try{let{ProxyAgent:J}=await Promise.resolve().then(()=>Sn(Po()));G.dispatcher=new J(new URL(R).toString())}catch{}try{let J=await fetch(p,G);return J.ok?await J.json():null}catch{return null}}hasQuotaData(p){return p.totalBalance!==void 0||p.usedBalance!==void 0||p.remainingBalance!==void 0||p.usedDailyBalance!==void 0||p.limitDaily!==void 0||p.resetTime!==void 0}},c6=class extends Ec{async queryQuota(p,x,F){let R=await this.fetchJson("https://api.deepseek.com/user/balance",p,x,F),M=(Array.isArray(R?.balance_infos)?R.balance_infos:[]).find(G=>Ln(G?.total_balance)!==void 0);if(!M)return null;let O=Ln(M.total_balance);return O===void 0?null:{totalBalance:O,currency:typeof M.currency=="string"?M.currency:void 0}}},d6=class extends Ec{async queryQuota(p,x,F){let R=(await this.fetchJson("https://openrouter.ai/api/v1/key",p,x,F))?.data;if(!R||typeof R!="object")return null;let M={},O=Ln(R.limit),G=Ln(R.limit_remaining),J=Ln(R.usage),ne=Ln(R.usage_daily);return O!==void 0&&(M.totalBalance=O),G!==void 0&&(M.remainingBalance=G),J!==void 0&&(M.usedBalance=J),ne!==void 0&&(M.usedDailyBalance=ne),this.hasQuotaData(M)?M:null}},h6=class extends Ec{async queryQuota(p,x,F){let R=I6(p.baseUrl),M=(await this.fetchJson(R,p,x,F))?.data;if(!M||typeof M!="object")return null;let O={},G=Ln(M.totalBalance),J=Ln(M.balance);return G!==void 0&&(O.totalBalance=G),J!==void 0&&(O.remainingBalance=J),G!==void 0&&J!==void 0&&(O.usedBalance=Math.max(0,G-J)),this.hasQuotaData(O)?O:null}},f6=class extends Ec{async queryQuota(p,x,F){if(!p.apiKey)return null;let R={method:"GET",headers:{Accept:"application/json",Authorization:p.apiKey.trim()},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:M}=await Promise.resolve().then(()=>Sn(Po()));R.dispatcher=new M(new URL(F).toString())}catch{}try{let M=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",R);if(!M.ok)return null;let O=await M.json(),G=Array.isArray(O?.data?.limits)?O.data.limits:[],J=null,ne=null,z=null;for(let ie of G)ie.type==="TOKENS_LIMIT"?ie.unit===3?J=ie:ie.unit===6?ne=ie:J||(J=ie):ie.type==="TIME_LIMIT"&&(z=ie);let te={};if(J){let ie=Ln(J.currentValue),ce=Ln(J.usage),X=Ln(J.remaining),le=Ln(J.percentage);ie!==void 0?te.usedDailyBalance=ie:le!==void 0&&(te.usedDailyBalance=le,te.limitDaily=100),ce!==void 0?te.limitDaily=ce:ie!==void 0&&X!==void 0&&(te.limitDaily=ie+X),J.nextResetTime&&(te.resetTime=new Date(J.nextResetTime).toISOString())}if(ne){let ie=Ln(ne.currentValue),ce=Ln(ne.usage),X=Ln(ne.remaining),le=Ln(ne.percentage);ie!==void 0?te.usedBalance=ie:le!==void 0&&(te.usedBalance=le,te.totalBalance=100),ce!==void 0?te.totalBalance=ce:ie!==void 0&&X!==void 0&&(te.totalBalance=ie+X),ne.nextResetTime&&!te.resetTime&&(te.resetTime=new Date(ne.nextResetTime).toISOString())}if(z){if(te.usedDailyBalance===void 0){let ie=Ln(z.currentValue);ie!==void 0&&(te.usedDailyBalance=ie)}if(te.limitDaily===void 0){let ie=Ln(z.usage),ce=Ln(z.currentValue),X=Ln(z.remaining);ie!==void 0?te.limitDaily=ie:ce!==void 0&&X!==void 0&&(te.limitDaily=ce+X)}z.nextResetTime&&!te.resetTime&&(te.resetTime=new Date(z.nextResetTime).toISOString())}return this.hasQuotaData(te)?te:null}catch{return null}}},A6=class extends Ec{async queryQuota(p,x,F){if(!p.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:p.quotaToken},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:G}=await Promise.resolve().then(()=>Sn(Po()));R.dispatcher=new G(new URL(F).toString())}catch{}let M=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"}}}),O=new URLSearchParams({params:M,region:"cn-beijing"}).toString();try{let G=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...R,body:O});if(!G.ok)return null;let J=(await G.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(J)||J.length===0)return null;let ne=J[0]?.codingPlanQuotaInfo;if(!ne)return null;let z={},te=Ln(ne.per5HourUsedQuota),ie=Ln(ne.per5HourTotalQuota);te!==void 0&&(z.usedDailyBalance=te),ie!==void 0&&(z.limitDaily=ie);let ce=Ln(ne.perWeekUsedQuota),X=Ln(ne.perWeekTotalQuota);return ce!==void 0&&(z.usedBalance=ce),X!==void 0&&(z.totalBalance=X),this.hasQuotaData(z)?z:null}catch{return null}}},p6=class extends Ec{async queryQuota(p,x,F){let R=p.quotaToken||p.apiKey;if(!R)return null;let M={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${R.trim()}`},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:O}=await Promise.resolve().then(()=>Sn(Po()));M.dispatcher=new O(new URL(F).toString())}catch{}try{let O=await fetch("https://api.kimi.com/coding/v1/usages",M);if(!O.ok)return null;let G=await O.json(),J={},ne=Array.isArray(G?.limits)?G.limits:[];if(ne.length>0&&ne[0]?.detail){let te=ne[0].detail,ie=Ln(te.limit),ce=Ln(te.remaining),X=te.resetTime;ie!==void 0&&ce!==void 0&&(J.usedDailyBalance=Math.max(0,ie-ce),J.limitDaily=ie),X&&(J.resetTime=new Date(X).toISOString())}let z=G?.usage;if(z){let te=Ln(z.limit),ie=Ln(z.remaining),ce=Ln(z.used),X=z.resetTime;te!==void 0&&(J.totalBalance=te,ce!==void 0?J.usedBalance=ce:ie!==void 0&&(J.usedBalance=Math.max(0,te-ie),J.remainingBalance=ie)),X&&(J.resetTime7d=new Date(X).toISOString(),J.resetTime||(J.resetTime=J.resetTime7d))}return this.hasQuotaData(J)?J:null}catch{return null}}},g6=class extends Ec{async queryQuota(p,x,F){let R=p.quotaToken||p.apiKey;if(!R)return null;let M=Km(p.baseUrl)||"api.minimaxi.com",O=M.endsWith(".minimax.io")||M==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let G=[`https://${O}/v1/token_plan/remains`,`https://${O}/v1/api/openplatform/coding_plan/remains`],J=null;for(let we of G)if(J=await this.fetchJson(we,p,x,F,R.trim()),J)break;if(!J)return null;if(J?.base_resp){let we=J.base_resp.status_code;if(we!==void 0&&we!==0)return null}let ne=Array.isArray(J?.model_remains)?J.model_remains:[];if(ne.length===0)return null;let z=ne[0],te={},ie=Ln(z.current_interval_total_count),ce=Ln(z.current_interval_usage_count),X=Ln(z.current_interval_remaining_percent),le=Ln(z.end_time);ie!==void 0&&ce!==void 0&&ie>0?(te.usedDailyBalance=Math.max(0,ie-ce),te.limitDaily=ie):X!==void 0&&(te.limitDaily=100,te.usedDailyBalance=Math.max(0,100-X)),le&&(te.resetTime=new Date(le).toISOString());let pe=Ln(z.current_weekly_total_count),De=Ln(z.current_weekly_usage_count),be=Ln(z.current_weekly_remaining_percent),Be=Ln(z.weekly_end_time);return pe!==void 0&&De!==void 0&&pe>0?(te.usedBalance=Math.max(0,pe-De),te.remainingBalance=De,te.totalBalance=pe):be!==void 0&&(te.totalBalance=100,te.usedBalance=Math.max(0,100-be),te.remainingBalance=be),Be&&!te.resetTime&&(te.resetTime=new Date(Be).toISOString()),this.hasQuotaData(te)?te:null}catch{return null}}},m6=new c6,E6=new d6,y6=new h6,C6=new f6,D6=new A6,b6=new p6,w6=new g6;function kw(p){let x=Km(p);return x?x==="kimi.com"||x.endsWith(".kimi.com")||x==="moonshot.cn"||x.endsWith(".moonshot.cn")?b6:x==="minimaxi.com"||x.endsWith(".minimaxi.com")||x==="minimax.io"||x.endsWith(".minimax.io")?w6:x==="deepseek.com"||x.endsWith(".deepseek.com")?m6:x==="openrouter.ai"||x.endsWith(".openrouter.ai")?E6:x==="siliconflow.com"||x.endsWith(".siliconflow.com")||x==="siliconflow.cn"||x.endsWith(".siliconflow.cn")?y6:x==="bigmodel.cn"||x.endsWith(".bigmodel.cn")?C6:x==="dashscope.aliyuncs.com"||x.endsWith(".dashscope.aliyuncs.com")?D6:null:null}function I6(p){let x=Km(p);return x?.endsWith(".siliconflow.cn")||x==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Km(p){try{return new URL(p).hostname.toLowerCase()}catch{return null}}function Ln(p){if(typeof p=="number")return Number.isFinite(p)?p:void 0;if(typeof p!="string")return;let x=p.trim().replace(/,/g,"");if(!x)return;let F=Number(x);return Number.isFinite(F)?F:void 0}var v6={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function B6(p){return p===!0||p==="true"||p===1||p==="1"}function x6(p){let x=p.getFullYear(),F=String(p.getMonth()+1).padStart(2,"0"),R=String(p.getDate()).padStart(2,"0");return`${x}-${F}-${R}`}function _6(p){try{let x=new URL(p),F=x.pathname;return F.endsWith("/v1/messages")?F=F.slice(0,-12):F.endsWith("/messages")?F=F.slice(0,-9):F.endsWith("/v1/chat/completions")?F=F.slice(0,-20):F.endsWith("/chat/completions")&&(F=F.slice(0,-17)),F.endsWith("/v1")||(F=F.endsWith("/")?`${F}v1`:`${F}/v1`),x.pathname=`${F}/models`,x.toString()}catch{return null}}function S6(p){try{let x=new URL(p).hostname.toLowerCase();return x.includes("moonshot")||x.includes("kimi")}catch{return!1}}async function Zm(p,x,F){let R=_6(p.baseUrl);if(!R)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let M={method:"GET",headers:{Authorization:`Bearer ${p.apiKey}`},signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:J}=await Promise.resolve().then(()=>Sn(Po()));M.dispatcher=new J(new URL(F).toString())}catch{}let O=await fetch(R,M);if(O.headers&&Bd(p.name,p.baseUrl,O.headers),O.ok)return{success:!0,headers:O.headers};if(O.status===429)return{success:!1,error:`HTTP 429: ${(await O.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:O.headers};if(O.status>=400&&O.status<500)return{success:!0,headers:O.headers};let G=await O.text().catch(()=>"");return{success:!1,error:`HTTP ${O.status}: ${G.slice(0,100)}`,headers:O.headers}}catch(M){return{success:!1,error:M?.message||M?.toString()||"Unknown probe error"}}}async function F6(p,x,F,R){let M=p.wakeupModel||(Array.isArray(p.models)?p.models[0]:void 0);if(!M)return{success:!1,error:"No models configured for provider"};let O=p.baseUrl.includes("anthropic")||M.includes("claude"),G=O?p.baseUrl.includes("/messages")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/v1/messages`:p.baseUrl.includes("/chat/completions")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let J={"Content-Type":"application/json"};O?(J["x-api-key"]=p.apiKey,J["anthropic-version"]="2023-06-01"):J.Authorization=`Bearer ${p.apiKey}`;let ne={method:"POST",headers:J,body:JSON.stringify({model:M,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(x)};if(F)try{let{ProxyAgent:ie}=await Promise.resolve().then(()=>Sn(Po()));ne.dispatcher=new ie(new URL(F).toString())}catch{}R?.info(`Sending scheduled wake-up call to provider ${p.name} using model ${M}...`);let z=await fetch(G,ne);if(z.ok)return{success:!0};let te=await z.text().catch(()=>"");return{success:!1,error:`HTTP ${z.status}: ${te.slice(0,200)||"Unknown error"}`}}catch(J){return{success:!1,error:J?.message||J?.toString()||"Unknown wake-up error"}}}async function k6(p,x,F,R,M){let O=p.baseUrl.includes("anthropic")||x.includes("claude"),G=O?p.baseUrl.includes("/messages")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/v1/messages`:p.baseUrl.includes("/chat/completions")?p.baseUrl:`${p.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let J={"Content-Type":"application/json"};O?(J["x-api-key"]=p.apiKey,J["anthropic-version"]="2023-06-01"):J.Authorization=`Bearer ${p.apiKey}`;let ne={method:"POST",headers:J,body:JSON.stringify({model:x,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(F)};if(R)try{let{ProxyAgent:ie}=await Promise.resolve().then(()=>Sn(Po()));ne.dispatcher=new ie(new URL(R).toString())}catch{}M?.debug?.(`Sending independent ping to rate-limited model ${p.name} (${x})...`);let z=await fetch(G,ne);if(z.ok)return{success:!0};let te=await z.text().catch(()=>"");return{success:!1,error:`HTTP ${z.status}: ${te.slice(0,200)||"Unknown error"}`}}catch(J){return{success:!1,error:J?.message||J?.toString()||"Unknown ping error"}}}var Tw=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(p,x,F,R,M){this.config={...v6,...x},this.getProviders=p,this.getHttpsProxy=F,this.logger=R,this.getConfig=M}start(){if(this.running)return;let p=this.isWakeupGloballyEnabled();!this.config.enabled&&!p||(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.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.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 p=this.getProviders().filter(O=>O?.name&&O.enabled!==!1&&!this.config.excludeProviders.includes(O.name)),x=this.getHttpsProxy?.(),F=Q();if(p.length===0)return;let R=[];for(let O of p){let G=kw(O.baseUrl),J=Array.isArray(O.models)?O.models:[];G&&R.push({provider:O.name,models:J,type:"quota-adapter",promise:G.queryQuota(O,this.config.probeTimeoutMs,x).then(ne=>{if(ne){Cw(O.name,ne),this.logger?.debug?.(`Stored quota probe result for ${O.name}`);let z=ne.limitDaily!==void 0&&ne.usedDailyBalance!==void 0&&ne.usedDailyBalance>=ne.limitDaily,te=ne.totalBalance!==void 0&&ne.usedBalance!==void 0&&ne.usedBalance>=ne.totalBalance;if(z||te){let ie=z?`Quota exhausted: 5h limit reached (${ne.usedDailyBalance}/${ne.limitDaily})`:`Quota exhausted: 7d balance depleted (${ne.usedBalance}/${ne.totalBalance})`;for(let ce of J){if(F.getState(O.name,ce)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${O.name} (${ce}): already rate-limited with active cooldown`);continue}F.forceOpen(O.name,ce,ie)}this.logger?.warn?.(`${ie} for ${O.name}, marked as unhealthy`)}else for(let ie of J){let ce=F.getState(O.name,ie);ce&&ce.status==="open"&&ce.lastError?.includes("Quota exhausted")&&(F.recover(O.name,ie),this.logger?.info?.(`Quota recovered for ${O.name} (${ie}), marked as healthy`))}}})}),S6(O.baseUrl)&&R.push({provider:O.name,models:J,type:"rate-limit-headers",promise:Zm(O,this.config.probeTimeoutMs,x).then(()=>{})})}if(R.length===0)return;this.logger?.debug?.(`Running quota probe with ${R.length} tasks for ${p.length} providers`);let M=await Promise.allSettled(R.map(O=>O.promise));for(let O=0;O<R.length;O++){let G=M[O];if(G.status==="rejected"){let J=R[O];this.logger?.warn?.(`Quota probe failed for ${J.provider} (${J.type}): ${G.reason}`)}}}async runHealthProbe(){let p=Q(),x=this.getProviders().filter(M=>M?.name&&M.enabled!==!1&&!this.config.excludeProviders.includes(M.name)),F=this.getHttpsProxy?.();if(x.length===0)return;this.logger?.debug?.(`Running health probe for ${x.length} providers`);let R=await Promise.allSettled(x.map(M=>Zm(M,this.config.probeTimeoutMs,F)));for(let M=0;M<x.length;M++){let O=x[M],G=R[M],J=Array.isArray(O.models)?O.models:[];if(G.status==="fulfilled"){let ne=G.value;if(ne.success){let z=0;for(let te of J){let ie=p.getState(O.name,te);if(ie&&ie.status==="open"){let ce=ie.lastError?.includes("Quota exhausted"),X=ie.rateLimitUntil||ie.lastError&&(ie.lastError.includes("429")||ie.lastError.toLowerCase().includes("rate limit")||ie.lastError.toLowerCase().includes("rate_limit")||ie.lastError.toLowerCase().includes("too many requests")||ie.lastError.toLowerCase().includes("\u9650\u6D41"));if(ce){this.logger?.debug?.(`Skipping health probe recovery for ${O.name} (${te}) because quota is exhausted`);continue}if(X||ie.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${O.name} (${te})`);continue}}p.recordSuccess(O.name,te),z++}z>0&&this.logger?.info?.(`Health probe succeeded for ${O.name}`)}else{for(let z of J)p.recordFailure(O.name,z,ne.error);this.logger?.warn?.(`Health probe failed for ${O.name}: ${ne.error}`)}}else{for(let ne of J)p.recordFailure(O.name,ne,G.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${O.name}: ${G.reason}`)}}}async runRateLimitProbe(){let p=Q(),x=p.getRateLimitedModels();if(x.length===0)return;let F=this.getProviders(),R=this.getHttpsProxy?.(),M=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${x.length} model(s)`);for(let O of x){let[G,...J]=O.split(","),ne=J.join(",");if(!G||!ne)continue;let z=p.getState(G,ne);if(!z||!z.rateLimitUntil)continue;if(Date.now()>=z.rateLimitUntil){p.recover(G,ne),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${O}`);continue}let te=F.find(ie=>ie?.name===G&&ie.enabled!==!1);if(!te){this.logger?.warn?.(`Provider ${G} not found or disabled for rate-limit probe`);continue}try{let ie=await k6(te,ne,M,R,this.logger);if(ie.success)this.logger?.info?.(`Rate-limit probe succeeded for ${O}, recovering model`),p.recover(G,ne);else if(ie.error&&(ie.error.includes("429")||ie.error.toLowerCase().includes("rate limit")||ie.error.toLowerCase().includes("rate_limit")||ie.error.toLowerCase().includes("too many requests")||ie.error.toLowerCase().includes("\u9650\u6D41"))){let ce=Date.now();z.rateLimitUntil&&z.rateLimitUntil>ce?z.rateLimitUntil+=120*1e3:z.rateLimitUntil=ce+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${O} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${O} returned non-rate-limit error: ${ie.error?.slice(0,100)}`)}catch(ie){this.logger?.warn?.(`Rate-limit probe exception for ${O}: ${ie?.message||ie}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let p=this.getProviders().filter(J=>J?.name&&J.enabled!==!1&&J.wakeupEnabled===!0);if(p.length===0)return;let x=new Date,F=x.getHours(),R=x.getMinutes(),M=x6(x),O=this.getHttpsProxy?.(),G=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let J of p){let ne=J.wakeupTime||G,[z,te]=ne.split(":"),ie=parseInt(z,10),ce=parseInt(te,10);if(isNaN(ie)||isNaN(ce))continue;let X=F>ie||F===ie&&R>=ce,le=(ie*60+ce)*6e4-(F*60+R)*6e4,pe=le>0&&le<=300*1e3;(X||pe)&&!this.hasWakeupFiredToday(J.name,M)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${J.name} at ${ne}`),F6(J,3e4,O,this.logger).then(De=>{De.success?this.logger?.info?.(`Successfully woke up provider ${J.name}`):this.logger?.error?.(`Failed to wake up provider ${J.name}: ${De.error}`)}).catch(De=>{this.logger?.error?.(`Error in wake-up task for ${J.name}: ${De}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?B6(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(p,x){return this.lastWakeupDate.get(p)===x?!0:(this.lastWakeupDate.set(p,x),!1)}async probeProviderManually(p){let x=this.getProviders().find(O=>O.name===p);if(!x)return this.logger?.warn?.(`Provider ${p} not found for manual probe`),!1;if(x.enabled===!1)return this.logger?.warn?.(`Provider ${p} is disabled, skipping manual probe`),!1;let F=this.getHttpsProxy?.(),R=await Zm(x,this.config.probeTimeoutMs,F),M=Array.isArray(x.models)?x.models:[];if(R.success)for(let O of M)Q().recordSuccess(x.name,O);else for(let O of M)Q().recordFailure(x.name,O,R.error);return R.success}},yl=null;function Rw(p,x,F,R,M){return yl||(yl=new Tw(p,x,F,R,M)),yl}function Qw(p,x,F,R,M){let O=Rw(p,x,F,R,M);return O.start(),O}function Nw(){yl&&yl.stop()}function T6(){yl&&(yl.stop(),yl=null)}de();var R6=class{plugins=new Map;pluginInstances=new Map;registerPlugin(p,x={}){this.pluginInstances.set(p.name,p),this.plugins.set(p.name,{name:p.name,enabled:x.enabled!==!1,options:x})}async enablePlugin(p,x){let F=this.plugins.get(p),R=this.pluginInstances.get(p);if(!F||!R)throw new Error(`Plugin ${p} not found`);F.enabled&&await x.register(R.register,F.options)}async enablePlugins(p){for(let[x,F]of this.plugins)if(F.enabled)try{await this.enablePlugin(x,p)}catch(R){let M=R instanceof Error?R.message:String(R);p.log?.error(`Failed to enable plugin ${x}: ${M}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(p){return this.pluginInstances.get(p)}hasPlugin(p){return this.pluginInstances.has(p)}isPluginEnabled(p){return this.plugins.get(p)?.enabled||!1}setPluginEnabled(p,x){let F=this.plugins.get(p);F&&(F.enabled=x)}removePlugin(p){this.plugins.delete(p),this.pluginInstances.delete(p)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Q6=new R6,N6=f(Ui(),1),Ow=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(p,x)=>{this.buffer+=p;let F=this.buffer.split(`
|
|
952
952
|
`);this.buffer=F.pop()||"";for(let R of F){let M=this.processLine(R);M&&x.enqueue(M)}},flush:p=>{if(this.buffer.trim()){let x=[];this.processLine(this.buffer.trim(),x),x.forEach(F=>p.enqueue(F))}Object.keys(this.currentEvent).length>0&&p.enqueue(this.currentEvent)}})}processLine(p,x){if(!p.trim()){if(Object.keys(this.currentEvent).length>0){let F={...this.currentEvent};return this.currentEvent={},x?(x.push(F),null):F}return null}if(p.startsWith("event:"))this.currentEvent.event=p.slice(6).trim();else if(p.startsWith("data:")){let F=p.slice(5).trim();if(F==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(F)}catch{this.currentEvent.data={raw:F,error:"JSON parse failed"}}}else p.startsWith("id:")?this.currentEvent.id=p.slice(3).trim():p.startsWith("retry:")&&(this.currentEvent.retry=parseInt(p.slice(6).trim()));return null}},O6=class extends TransformStream{constructor(){super({transform:(p,x)=>{let F="";p.event&&(F+=`event: ${p.event}
|
|
953
953
|
`),p.id&&(F+=`id: ${p.id}
|
|
954
954
|
`),p.retry&&(F+=`retry: ${p.retry}
|
|
@@ -1028,7 +1028,7 @@ ${this.toMarkdown(n,t+1)}`:`${r}- ${n}`).join(`
|
|
|
1028
1028
|
${this.toMarkdown(i,t+1)}`:`${r}${n}: ${i}`).join(`
|
|
1029
1029
|
`):`${r}${e}`}async output(e,t={}){try{let r=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}}),HS,qS=Ci(()=>{"use strict";HS=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:r="json",timestamp:n=!0,prefix:i,metadata:o}=t||{},s={data:e};return n&&(s.timestamp=new Date().toISOString()),i&&(s.prefix=i),o&&Object.keys(o).length>0&&(s.metadata=o),s}async sendRequest(e,t,r,n,i){let o=new AbortController,s=setTimeout(()=>o.abort(),i);try{let a=await fetch(e,{method:t,headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);return a}catch(a){throw clearTimeout(s),a}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,r,n,i,o){let s=null;for(let a=1;a<=o.maxAttempts;a++)try{return await this.sendRequest(e,t,r,n,i)}catch(u){if(s=u,a===o.maxAttempts)break;let l=o.backoffMs*Math.pow(2,a-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${a}/${o.maxAttempts}), retrying in ${l}ms...`,u.message),await this.delay(l)}throw s}async output(e,t={}){let r=t.timeout||this.defaultTimeout;try{let n=this.buildHeaders(),i=this.buildBody(e,t),o=await this.sendWithRetry(this.config.url,this.config.method,n,i,r,this.config.retry);return!0}catch(n){let i=n instanceof Error?n.message:String(n);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}}),GS,VS=Ci(()=>{"use strict";GS=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let t=(0,t$.tmpdir)();this.baseDir=(0,YI.join)(t,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,ty.existsSync)(this.baseDir)||(0,ty.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let t=e.match(/_session_([a-f0-9-]+)/i);return t?t[1]:null}catch{return null}}getFilePath(e){let t=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",n;if(this.config.includeTimestamp){let i=Date.now();n=`${t}-${e}-${i}${r}`}else n=`${t}-${e}${r}`;return(0,YI.join)(this.baseDir,n)}async output(e,t={}){try{let r=t.metadata?.sessionId;if(!r)return!1;let n={...e,timestamp:Date.now(),sessionId:r},i=this.getFilePath(r);return(0,ty.writeFileSync)(i,JSON.stringify(n,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}}),Cv,Yf,kj=Ci(()=>{"use strict";jS(),qS(),VS(),Cv=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let r=this.createHandler(t),n=t.type+"_"+Date.now();this.registerHandler(n,r)}catch(r){console.error(`[OutputManager] Failed to register ${t.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new $S(e.config);case"webhook":return new HS(e.config);case"temp-file":return new GS(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let r={...this.defaultOptions,...t},n={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([o,s])=>{try{await s.output(e,r)?n.success.push(o):n.failed.push(o)}catch(a){console.error(`[OutputManager] Handler ${o} failed:`,a),n.failed.push(o)}});return await Promise.all(i),n}async outputTo(e,t,r){let n={...this.defaultOptions,...r},i={success:[],failed:[]},o=e.map(async s=>{let a=this.handlers.get(s);if(!a){console.warn(`[OutputManager] Handler ${s} not found`),i.failed.push(s);return}try{await a.output(t,n)?i.success.push(s):i.failed.push(s)}catch(u){console.error(`[OutputManager] Handler ${s} failed:`,u),i.failed.push(s)}});return await Promise.all(o),i}async outputToType(e,t,r){let n=Array.from(this.handlers.entries()).filter(([i,o])=>o.type===e).map(([i])=>i);return this.outputTo(n,t,r)}},Yf=new Cv}),Tj=Ul(x_(),1),Dv=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:(0,zI.join)(process.cwd(),this.options.jsonPath);if((0,ry.existsSync)(e))try{let t=(0,ry.readFileSync)(e,"utf-8"),r=Tj.default.parse(t);this.config={...this.config,...r},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:(0,zI.join)(process.cwd(),this.options.envPath);if((0,ry.existsSync)(e))try{let t=(0,i$.config)({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 r=this.config[e];return r!==void 0?r:t}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}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 yo(e,t=500,r="internal_error",n="api_error"){let i=new Error(e);return i.statusCode=t,i.code=r,i.type=n,i}async function Rj(e,t,r){t.log.error(e);let n=e.statusCode||500;if(e.rawBody)try{let o=JSON.parse(e.rawBody);return r.code(n).send(o)}catch{return r.code(n).send(e.rawBody)}let i={error:{message:e.message+(e.stack||"Internal Server Error"),type:e.type||"api_error",code:e.code||"internal_error"}};return r.code(n).send(i)}function Qj(e,t,r,n,i){let o=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([l,c])=>{c&&o.set(l,c)});let s,a=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let l=new AbortController,c=()=>l.abort();r.signal.addEventListener("abort",c),a.addEventListener("abort",c),s=l.signal}else s=a;let u={method:"POST",headers:o,body:JSON.stringify(t),signal:s};return r.httpsProxy&&(u.dispatcher=new o$.ProxyAgent(new URL(r.httpsProxy).toString())),i?.debug({reqId:n.req.id,request:u,headers:Object.fromEntries(o.entries()),requestUrl:typeof e=="string"?e:e.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof e=="string"?e:e.toString(),u)}var Nj=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),oh={maxBodyLength:4096,maxStreamChunks:100},ZC=!1;function Oj(e){ZC=e}function bv(){return ZC}function Jy(e){return ZC||e.get("DEBUG_LOG")===!0}function Lj(e){let t=e.get("DEBUG_LOG_OPTIONS");return!t||typeof t!="object"?oh:{maxBodyLength:t.maxBodyLength??oh.maxBodyLength,maxStreamChunks:t.maxStreamChunks??oh.maxStreamChunks}}function JS(e){let t={};for(let[r,n]of Object.entries(e))Nj.has(r.toLowerCase())?t[r]="***MASKED***":t[r]=n;return t}function XC(e,t){return e.length<=t?e:e.slice(0,t)+`...[truncated, total ${e.length} bytes]`}function Pj(e,t,r){let n=typeof r.body=="string"?r.body:JSON.stringify(r.body);e.info({debug_log:!0,reqId:t,phase:"provider_request",url:r.url,headers:JS(r.headers),body:XC(n,oh.maxBodyLength)})}function Mj(e,t,r){e.info({debug_log:!0,reqId:t,phase:"provider_response",status:r.status,headers:JS(r.headers),...r.body!==void 0?{body:XC(r.body,oh.maxBodyLength)}:{}})}function wv(e,t,r,n){e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk",chunkIndex:r,data:XC(n,oh.maxBodyLength)})}function Iv(e,t,r){e.info({debug_log:!0,reqId:t,phase:"provider_stream_end",totalChunks:r})}function Uj(e,t,r,n){(async()=>{let i=e.pipeThrough(new TextDecoderStream).getReader(),o=0;try{let s="";for(;;){let{done:a,value:u}=await i.read();if(a)break;s+=u;let l=s.split(`
|
|
1030
1030
|
|
|
1031
|
-
`);s=l.pop()||"";for(let c of l)c.trim()&&(o<n.maxStreamChunks?wv(t,r,o,c):o===n.maxStreamChunks&&t.info({debug_log:!0,reqId:r,phase:"provider_stream_chunk_omitted",message:`[chunks after #${o} omitted, maxStreamChunks=${n.maxStreamChunks}]`}),o++)}s.trim()&&(o<n.maxStreamChunks&&wv(t,r,o,s.trim()),o++),Iv(t,r,o)}catch(s){console.error(`[debug_log] Error reading debug stream for reqId=${r}:`,s),Iv(t,r,o)}finally{i.releaseLock()}})()}var $j="2.1.
|
|
1031
|
+
`);s=l.pop()||"";for(let c of l)c.trim()&&(o<n.maxStreamChunks?wv(t,r,o,c):o===n.maxStreamChunks&&t.info({debug_log:!0,reqId:r,phase:"provider_stream_chunk_omitted",message:`[chunks after #${o} omitted, maxStreamChunks=${n.maxStreamChunks}]`}),o++)}s.trim()&&(o<n.maxStreamChunks&&wv(t,r,o,s.trim()),o++),Iv(t,r,o)}catch(s){console.error(`[debug_log] Error reading debug stream for reqId=${r}:`,s),Iv(t,r,o)}finally{i.releaseLock()}})()}var $j="2.1.34";$c();var Yy=(0,w_.join)(s$.HOME_DIR,"runtime"),zy=(0,w_.join)(Yy,"rate-limit.json"),eA=new Map,vv=!1,jj=null,Hj=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],qj=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Gj=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function eD(e,t,r){let n=a=>{if(r instanceof Headers)return r.get(a);let u=Object.keys(r).find(l=>l.toLowerCase()===a);return u?r[u]:null},i=dy(n,Hj),o=dy(n,qj),s=dy(n,Gj);(i||o||s)&&eA.set(e,{provider:e,remaining:Bv(i),limit:Bv(o),reset:Jj(s),capturedAt:Date.now()})}function Vj(){return Array.from(eA.values())}function dy(e,t){for(let r of t){let n=e(r);if(n)return n}return null}function Bv(e){if(!e)return null;let t=Number(e.trim().replace(/,/g,""));return Number.isFinite(t)?t:null}function Jj(e){if(!e)return null;let t=e.trim();if(!t)return null;let r=Number(t);if(Number.isFinite(r))return r>1e12?Math.floor(r/1e3):r>1e9?Math.floor(r):Math.floor(Date.now()/1e3+r);let n=Date.parse(t);if(Number.isFinite(n))return Math.floor(n/1e3);let i=Yj(t);return i===null?null:Math.floor((Date.now()+i)/1e3)}function Yj(e){let t=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,r=0,n=!1;for(let i of e.matchAll(t)){n=!0;let o=Number(i[1]),s=i[2].toLowerCase();if(Number.isFinite(o))switch(s){case"ms":r+=o;break;case"s":r+=o*1e3;break;case"m":r+=o*60*1e3;break;case"h":r+=o*60*60*1e3;break;case"d":r+=o*24*60*60*1e3;break}}return n?r:null}function zj(){try{if(!(0,Vf.existsSync)(zy))return;let e=JSON.parse((0,Vf.readFileSync)(zy,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let r of e)if(r&&r.provider){if(r.capturedAt&&t-r.capturedAt>3600*1e3)continue;eA.set(r.provider,r)}}catch{}}function xv(){try{if(eA.size===0)return;(0,Vf.existsSync)(Yy)||(0,Vf.mkdirSync)(Yy,{recursive:!0}),(0,Vf.writeFileSync)(zy,JSON.stringify(Array.from(eA.values()),null,2),"utf-8")}catch{}}function Wj(){vv||(vv=!0,zj(),jj=setInterval(xv,6e4),process.on("exit",xv))}jC();var YS=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let t=[],r=e.messages.filter(n=>n.role==="system");if(r.length>0){let n=r[0];Array.isArray(n.content)?n.content.forEach(i=>{let o="";typeof i=="string"?o=i:i&&typeof i=="object"&&"text"in i&&(o=i.text),t.push({role:"system",content:o})}):e.instructions=n.content}if(e.messages.forEach(n=>{if(n.role!=="system"){if(Array.isArray(n.content)){let i=n.content.map(o=>this.normalizeRequestContent(o,n.role)).filter(o=>o!==null);i.length>0?n.content=i:delete n.content}if(n.role==="tool"){let i={...n};i.type="function_call_output",i.call_id=n.tool_call_id,i.output=n.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){n.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}t.push(n)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let n=e.tools.find(i=>i.function.name==="web_search");e.tools=e.tools.filter(i=>i.function.name!=="web_search").map(i=>(i.function.name==="WebSearch"&&delete i.function.parameters.properties.allowed_domains,i.function.name==="Edit"?{type:i.type,name:i.function.name,description:i.function.description,parameters:{...i.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:i.type,name:i.function.name,description:i.function.description,parameters:i.function.parameters})),n&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let t=e.headers.get("Content-Type")||"";if(t.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let n=this.convertResponseToChat(r);return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,i="",o=!1,s=this,a=new ReadableStream({async start(u){let l=e.body.getReader(),c=-1,d="",f=h=>(h!==d&&(c++,d=h),c);try{for(;;){let{done:h,value:A}=await l.read();if(h){o||u.enqueue(n.encode(`data: [DONE]
|
|
1032
1032
|
|
|
1033
1033
|
`));break}let g=r.decode(A,{stream:!0});i+=g;let m=i.split(/\r?\n/);i=m.pop()||"";for(let E of m)if(E.trim())try{if(E.startsWith("event: "))continue;if(E.startsWith("data: ")){let D=E.slice(5).trim();if(D==="[DONE]"){o=!0,u.enqueue(n.encode(`data: [DONE]
|
|
1034
1034
|
|
|
@@ -1345,7 +1345,7 @@ ${n.content}`),delete n.thinking)});let r=e.messages[e.messages.length-1];return
|
|
|
1345
1345
|
error: ${t.message}
|
|
1346
1346
|
stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
1347
1347
|
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(K7).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)}},$v=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,l$.get_encoding)(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 r=0,{messages:n,system:i,tools:o}=e;return Array.isArray(n)&&n.forEach(s=>{typeof s.content=="string"?r+=t.encode(s.content).length:Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="text")r+=t.encode(a.text).length;else if(a.type==="tool_use")r+=t.encode(JSON.stringify(a.input)).length;else if(a.type==="tool_result"){let u=typeof a.content=="string"?a.content:JSON.stringify(a.content);r+=t.encode(u).length}})}),typeof i=="string"?r+=t.encode(i).length:Array.isArray(i)&&i.forEach(s=>{s.type==="text"&&(typeof s.text=="string"?r+=t.encode(s.text).length:Array.isArray(s.text)&&s.text.forEach(a=>{r+=t.encode(a||"").length}))}),o&&o.forEach(s=>{s.description&&(r+=t.encode(s.name+s.description).length),s.input_schema&&(r+=t.encode(JSON.stringify(s.input_schema)).length)}),r}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)}},Z7=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let r of e){let n=t;for(let i=0;i<r.length;++i){let o=r[i];n=n[o]??=Object.create(null)}n.end=r}return t}split(e){let t=[],r=e.length,n=0,i=0;for(;i<r;){let o=this.trie,s=null,a=i;for(;a<r&&(o=o[e[a]]);)o.end&&(s=o.end),++a;s?(i>n&&t.push(e.slice(n,i)),t.push(s),i+=s.length,n=i):++i}return n<r&&t.push(e.slice(n)),t}},X7=Z7,eH=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??null}},tH=eH,nF=(()=>{let e=[...Array.from({length:94},(i,o)=>o+33),...Array.from({length:12},(i,o)=>o+161),...Array.from({length:82},(i,o)=>o+174)],t=e.slice(),r=0;for(let i=0;i<256;++i)e.includes(i)||(e.push(i),t.push(256+r),r+=1);let n=t.map(i=>String.fromCharCode(i));return Object.fromEntries(e.map((i,o)=>[i,n[o]]))})(),rH=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),nH=rH(nF),jv=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",iH=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${jv}])]+`,` ?[^\\s${jv}]+`]]),tA="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",TW=new RegExp(`^[${tA}]+$`,"gu"),tD=e=>e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),Ig=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");for(let[n,i]of iH)r=r.replaceAll(n,i);return new RegExp(r,"gu")}else if(e.String!==void 0){let r=oH(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},oH=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),sH=(e,t,r)=>{let n=[],i=0;for(;i<e.length;){if(n.push(e[i]),(t.get(e[i])??r)!==r){++i;continue}for(;++i<e.length&&(t.get(e[i])??r)===r;)t.get(n.at(-1))!==r&&(n[n.length-1]+=e[i])}return n},aH=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,uH=e=>Number.isInteger(e)||typeof e=="bigint",lH=e=>{let t=0;for(let r of e)++t;return t},cH=e=>iF(e.toLowerCase()),Ks=(...e)=>Array.prototype.concat.apply([],e),rD=e=>new Map(Object.entries(e)),dH=(e,t)=>{let r=[],n=0;for(let i of e.matchAll(t)){let o=i[0];n<i.index&&r.push(e.slice(n,i.index)),o.length>0&&r.push(o),n=i.index+o.length}return n<e.length&&r.push(e.slice(n)),r},iF=e=>e.replace(new RegExp("\\p{M}","gu"),""),Hv=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(let n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},hH=e=>e.match(/\S+/g)||[],fH=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},EA=fH,AH=class extends EA{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},tl=AH,pH=class extends tl{tokenize_chinese_chars(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r],i=n.charCodeAt(0);aH(i)?(t.push(" "),t.push(n),t.push(" ")):t.push(n)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(e){switch(e){case" ":case`
|
|
1348
|
-
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(e)}}clean_text(e){let t=[];for(let r of e){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},gH=pH,mH=class extends tl{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("\uFF5E")?e=e.split("\uFF5E").map(t=>t.normalize("NFKC")).join("\uFF5E"):e=e.normalize("NFKC"),e}},EH=mH,yH=class extends tl{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>oF(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},CH=yH,DH=class extends tl{normalize(e){let t=Ig(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},bH=DH,wH=class extends tl{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},vg=wH,IH=class extends vg{constructor(){super(...arguments),this.form="NFC"}},vH=IH,BH=class extends vg{constructor(){super(...arguments),this.form="NFD"}},xH=BH,_H=class extends vg{constructor(){super(...arguments),this.form="NFKC"}},SH=_H,FH=class extends vg{constructor(){super(...arguments),this.form="NFKD"}},kH=FH,TH=class extends tl{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},RH=TH,QH=class extends tl{normalize(e){return iF(e)}},NH=QH,OH=class extends tl{normalize(e){return e.toLowerCase()}},LH=OH,PH=class extends tl{normalize(e){return e=this.config.prepend+e,e}},MH=PH;function UH(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new gH(e);case"Precompiled":return new EH(e);case"Sequence":return new CH(e);case"Replace":return new bH(e);case"NFC":return new vH(e);case"NFD":return new xH(e);case"NFKC":return new SH(e);case"NFKD":return new kH(e);case"Strip":return new RH(e);case"StripAccents":return new NH(e);case"Lowercase":return new LH(e);case"Prepend":return new MH(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var oF=UH,$H=class extends EA{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},au=$H,jH=class extends au{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=nF,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},HH=jH,qH=class extends au{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},GH=qH,VH=class extends au{constructor(e){super(),this.replacement=e.replacement??"\u2581",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){let{section_index:r=void 0}=t??{},n=e.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},JH=VH,YH=class extends au{constructor(e){super(),this.config=e,this.pattern=Ig(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):dH(e,this.pattern)}},zH=YH,WH=class extends au{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${tA}]+|[${tA}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},KH=WH,ZH=class extends au{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},XH=ZH,eq=class extends au{constructor(){super(),this.pattern=new RegExp(`[^\\s${tA}]+|[${tA}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},tq=eq,rq=class extends au{constructor(e){super(),this.config=e,this.pattern=Ig(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},nq=rq,iq=class extends au{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>sF(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},oq=iq,sq=class extends au{pre_tokenize_text(e){return hH(e)}},aq=sq;function uq(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new tq;case"Sequence":return new oq(e);case"Whitespace":return new GH;case"WhitespaceSplit":return new aq;case"Metaspace":return new JH(e);case"ByteLevel":return new HH(e);case"Split":return new zH(e);case"Punctuation":return new KH(e);case"Digits":return new XH(e);case"Replace":return new nq(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var sF=uq,lq=class extends EA{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=sH(t,this.tokens_to_ids,this.unk_token_id)),t}convert_tokens_to_ids(e){return e.map(t=>this.tokens_to_ids.get(t)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(t=>this.vocab[Number(t)]??this.unk_token)}},Bg=lq,cq=class extends Bg{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=rD(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){let t=[];for(let r of e){let n=[...r];if(n.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let i=!1,o=0,s=[];for(;o<n.length;){let a=n.length,u=null;for(;o<a;){let l=n.slice(o,a).join("");if(o>0&&(l=this.config.continuing_subword_prefix+l),this.tokens_to_ids.has(l)){u=l;break}--a}if(u===null){i=!0;break}s.push(u),o=a}i?t.push(this.unk_token):t.push(...s)}return t}},qv=cq,Gv=class aF{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new aF(!1,new Map)}},dq=class{constructor(){this.root=Gv.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let r of e){let n=t.children.get(r);n===void 0&&(n=Gv.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(let n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},hq=dq,fy=class uF{constructor(t,r,n,i,o){this.token_id=t,this.node_id=r,this.pos=n,this.length=i,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let t=new uF(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},fq=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new fy(this.bos_token_id??0,0,0,0,0),i=new fy(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(n)}insert(e,t,r,n){let i=this.nodes.length,o=new fy(n,i,e,t,r);this.begin_nodes[e].push(o),this.end_nodes[e+t].push(o),this.nodes.push(o)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let o of this.begin_nodes[t]){o.prev=null;let s=0,a=null;for(let u of this.end_nodes[t]){let l=u.backtrace_score+o.score;(a===null||l>s)&&(a=u.clone(),s=l)}if(a!==null)o.prev=a,o.backtrace_score=s;else return[]}++t}let r=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let i=n.clone();for(;i.prev!==null;)r.push(i.clone()),i=i.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},Aq=fq;function pq(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}var gq=class extends Bg{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=e.vocab[n];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,i)=>[n,i])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=pq(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new hq,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,r=1,n=0;for(;n<t.length;){let i=!1,o=[],s=t.slice(n).join(""),a=this.trie.common_prefix_search(s);for(let u of a){o.push(u);let l=this.tokens_to_ids.get(u),c=this.scores[l],d=lH(u);e.insert(n,d,c,l),!i&&d===r&&(i=!0)}i||e.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(e){let t=new Aq(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let r of e){let n=this.tokenize(r);t.push(...n)}return t}},Vv=gq,mq=class{constructor(e=(r,n)=>r>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},Eq=mq,yq=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},Cq=yq,Dq=class extends Bg{constructor(e){super(e),this.tokens_to_ids=rD(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new Cq(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let i=new Eq((a,u)=>a.score<u.score),o={token:r[0],bias:0,prev:null,next:null},s=o;for(let a=1;a<r.length;++a){let u={bias:a/r.length,token:r[a],prev:s,next:null};s.next=u,this.add_node(i,s),s=u}for(;!i.is_empty();){let a=i.pop();if(a.deleted||!a.next||a.next.deleted)continue;if(a.deleted=!0,a.next.deleted=!0,a.prev){let l={...a.prev};a.prev.deleted=!0,a.prev=l,l.prev?l.prev.next=l:o=l}let u={token:a.token+a.next.token,bias:a.bias,prev:a.prev,next:a.next.next};u.prev?(u.prev.next=u,this.add_node(i,u.prev)):o=u,u.next&&(u.next.prev=u,this.add_node(i,u))}for(let a=o;a!==null;a=a.next)n.push(a.token)}else n=r;if(this.continuing_subword_suffix)for(let i=0;i<n.length-1;++i)n[i]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){let r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){let t=[];for(let r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}let n=this.bpe(r);for(let i of n)if(this.tokens_to_ids.has(i))t.push(i);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(i)).map(s=>`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(s=>this.tokens_to_ids.has(s))?t.push(...o):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},Jv=Dq,bq=class extends Bg{constructor(e,t){super(e);let r=e.vocab;this.tokens_to_ids=rD(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,i]of this.tokens_to_ids)this.vocab[i]=n}encode(e){return e}},wq=bq;function Iq(e,t){switch(e.type){case"WordPiece":return new qv(e);case"Unigram":return new Vv(e,t.eos_token);case"BPE":return new Jv(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Vv(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Jv(e):new qv(e):new wq(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var vq=Iq,Bq=class extends EA{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},yA=Bq,xq=class extends yA{post_process(e,t=null,r=!0){let n=t===null?this.config.single:this.config.pair,i=[],o=[];for(let s of n)"SpecialToken"in s?r&&(i.push(s.SpecialToken.id),o.push(s.SpecialToken.type_id)):"Sequence"in s&&(s.Sequence.id==="A"?(i=Ks(i,e),o=Ks(o,new Array(e.length).fill(s.Sequence.type_id))):s.Sequence.id==="B"&&(i=Ks(i,t),o=Ks(o,new Array(t.length).fill(s.Sequence.type_id))));return{tokens:i,token_type_ids:o}}},_q=xq,Sq=class extends yA{post_process(e,t=null){return{tokens:t?Ks(e,t):e}}},Fq=Sq,kq=class extends yA{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Ks([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){let i=[],o=r?[this.sep[0]]:[];e=Ks(e,i,t,o),n=Ks(n,new Array(t.length+i.length+o.length).fill(1))}return{tokens:e,token_type_ids:n}}},Tq=kq,Rq=class extends yA{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Ks([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){let i=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];e=Ks(e,i,t,o),n=Ks(n,new Array(t.length+i.length+o.length).fill(1))}return{tokens:e,token_type_ids:n}}},Qq=Rq,Nq=class extends yA{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>lF(t))}post_process(e,t=null,r=!0){let n={tokens:e};for(let i of this.processors)n=i.post_process(n.tokens,t,r);return n}},Oq=Nq;function Lq(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new _q(e);case"ByteLevel":return new Fq(e);case"BertProcessing":return new Tq(e);case"RobertaProcessing":return new Qq(e);case"Sequence":return new Oq(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var lF=Lq,Pq=class extends EA{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},uu=Pq,Mq=class extends uu{constructor(e){super(e),this.byte_decoder=nH,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let n of e)this.added_tokens.find(i=>i.content===n)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},Uq=Mq,$q=class extends uu{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){let n=this.config.prefix;n&&t.startsWith(n)?t=t.replace(n,""):t=" "+t}return this.cleanup&&(t=tD(t)),t})}},jq=$q,Hq=class extends uu{constructor(e){super(e),this.replacement=e.replacement??"\u2581"}decode_chain(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}},qq=Hq,Gq=class extends uu{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},Vq=Gq,Jq=class extends uu{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let r=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=tD(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Yq=Jq,zq=class extends uu{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>cF(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},Wq=zq,Kq=class extends uu{decode_chain(e){let t=Ig(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},Zq=Kq,Xq=class extends uu{decode_chain(e){return[e.join("")]}},eG=Xq,tG=class extends uu{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let i=0;i<this.start&&t[i]===this.content;++i)r=i+1;let n=t.length;for(let i=0;i<this.stop;++i){let o=t.length-i-1;if(t[o]===this.content){n=o;continue}else break}return t.slice(r,n)})}},rG=tG,nG=class extends uu{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let n of e){let i=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let o=parseInt(n.slice(3,5),16);isNaN(o)||(i=o)}if(i!==null)r.push(i);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));t.push(o),r=[]}t.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},iG=nG;function oG(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new Uq(e);case"WordPiece":return new jq(e);case"Metaspace":return new qq(e);case"BPEDecoder":return new Vq(e);case"CTC":return new Yq(e);case"Sequence":return new Wq(e);case"Replace":return new Zq(e);case"Fuse":return new eG(e);case"Strip":return new rG(e);case"ByteFallback":return new iG(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var cF=oG,sG=class{constructor(e,t){let r=Hv(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Hv(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=oF(this.tokenizer.normalizer),this.pre_tokenizer=sF(this.tokenizer.pre_tokenizer),this.model=vq(this.tokenizer.model,this.config),this.post_processor=lF(this.tokenizer.post_processor),this.decoder=cF(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(i=>{let o=new tH(i);this.added_tokens.push(o),this.model.tokens_to_ids.set(o.content,o.id),this.model.vocab[o.id]=o.content,o.special&&(this.special_tokens.push(o.content),this.all_special_ids.push(o.id))}),(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new X7(this.added_tokens.map(i=>i.content)),this.added_tokens_map=new Map(this.added_tokens.map(i=>[i.content,i])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:i,token_type_ids:o}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),s=this.model.convert_tokens_to_ids(i),a={ids:s,tokens:i,attention_mask:new Array(s.length).fill(1)};return n&&o&&(a.token_type_ids=o),a}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!uH(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(e);t.skip_special_tokens&&(r=r.filter(i=>!this.special_tokens.includes(i)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(n=n.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=tD(n)),n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;let t=this.added_tokens_splitter.split(e);return t.forEach((r,n)=>{let i=this.added_tokens_map.get(r);i&&(i.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),i.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=cH(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let i=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(i)})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){let n=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(n,i,r):{tokens:Ks(n??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}},aG=sG,uG=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,r={}){this.modelId=e,this.logger=t,this.options=r,this.cacheDir=r.cacheDir||(0,mp.join)((0,c$.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,mp.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,mp.join)(e,"tokenizer.json"),tokenizerConfig:(0,mp.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Ep.existsSync)(e)||(0,Ep.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Ep.existsSync)(e.tokenizerJson)||!(0,Ep.existsSync)(e.tokenizerConfig))return null;let[t,r]=await Promise.all([yp.promises.readFile(e.tokenizerJson,"utf-8"),yp.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(r)}}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 r=new AbortController,n=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[i,o]=await Promise.all([fetch(t.json,{signal:r.signal}),fetch(t.config,{signal:r.signal})]);if(!i.ok)throw new Error(`Failed to fetch tokenizer.json: ${i.statusText}`);let[s,a]=await Promise.all([i.json(),o.ok?o.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([yp.promises.writeFile(e.tokenizerJson,JSON.stringify(s,null,2)),yp.promises.writeFile(e.tokenizerConfig,JSON.stringify(a,null,2))]),{tokenizerJson:s,tokenizerConfig:a}}finally{clearTimeout(n)}}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 aG(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:r,system:n,tools:i}=e;if(Array.isArray(r)){for(let o of r)if(typeof o.content=="string")t.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&s.text?t.push(s.text):s.type==="tool_use"&&s.input?t.push(JSON.stringify(s.input)):s.type==="tool_result"&&t.push(typeof s.content=="string"?s.content:JSON.stringify(s.content))}if(typeof n=="string")t.push(n);else if(Array.isArray(n)){for(let o of n)if(o.type==="text"){if(typeof o.text=="string")t.push(o.text);else if(Array.isArray(o.text))for(let s of o.text)s&&t.push(s)}}if(i)for(let o of i)o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema));return t.join(" ")}},lG=class{type="api";name;config;logger;options;constructor(e,t,r={}){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=r;try{let n=new URL(e.url);this.name=`api-${n.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),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},n=new AbortController,i=setTimeout(()=>n.abort(),this.options.timeout||3e4),o=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(t),signal:n.signal});if(clearTimeout(i),!o.ok)throw new Error(`API tokenizer request failed: ${o.status} ${o.statusText}`);let s=await o.json();return this.extractTokenCount(s)}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"?typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(r=>{t.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?t.push(r.text):Array.isArray(r.text)&&r.text.forEach(n=>{n&&t.push(n)}))}),e.tools&&e.tools.forEach(r=>{r.name&&t.push(r.name),r.description&&t.push(r.description),r.input_schema&&t.push(JSON.stringify(r.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,r=t.split("."),n=e;for(let i of r){if(n==null)throw new Error(`Field path '${t}' not found in response`);n=n[i]}if(typeof n!="number")throw new Error(`Expected number at field path '${t}', got ${typeof n}`);return n}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}`)}}},Yv=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,r={}){this.configService=e,this.logger=t,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new $v("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){let t=this.getCacheKey(e);if(this.tokenizers.has(t))return this.tokenizers.get(t);let r;try{switch(e.type){case"tiktoken":r=new $v(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new uG(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new lG(e,this.logger,{timeout:this.options.timeout});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(t,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${t})`),r}catch(n){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${n.message}`),this.logger?.error(`Error stack: ${n.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t){let r=t?await this.getTokenizer(t):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(n=>n.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){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}},cG=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}},Ql=new cG(100);$c();var Ky=(0,I_.join)(h$.HOME_DIR,"runtime"),Zy=(0,I_.join)(Ky,"quota-store.json"),uh=new Map,zv=!1,dG=null;function hG(e,t){e&&uh.set(e,{...t,provider:e,capturedAt:Date.now()})}function fG(e){let t=uh.get(e);return t?{...t}:void 0}function AG(){return Array.from(uh.values()).map(e=>({...e}))}function pG(){try{if(!(0,Jf.existsSync)(Zy))return;let e=JSON.parse((0,Jf.readFileSync)(Zy,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let r of e)if(r&&r.provider){if(r.capturedAt&&t-r.capturedAt>1440*60*1e3)continue;uh.set(r.provider,r)}}catch{}}function Wv(){try{if(uh.size===0)return;(0,Jf.existsSync)(Ky)||(0,Jf.mkdirSync)(Ky,{recursive:!0}),(0,Jf.writeFileSync)(Zy,JSON.stringify(Array.from(uh.values()),null,2),"utf-8")}catch{}}function gG(){zv||(zv=!0,pG(),dG=setInterval(Wv,6e4),process.on("exit",Wv))}jC();var Wu=(0,d$.get_encoding)("cl100k_base"),dF=(e,t,r)=>{let n=0;return Array.isArray(e)&&e.forEach(i=>{typeof i.content=="string"?n+=Wu.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(o=>{o.type==="text"?n+=Wu.encode(o.text).length:o.type==="tool_use"?n+=Wu.encode(JSON.stringify(o.input)).length:o.type==="tool_result"&&(n+=Wu.encode(typeof o.content=="string"?o.content:JSON.stringify(o.content)).length)})}),typeof t=="string"?n+=Wu.encode(t).length:Array.isArray(t)&&t.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?n+=Wu.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(o=>{n+=Wu.encode(o||"").length}))}),r&&r.forEach(i=>{i.description&&(n+=Wu.encode(i.name+i.description).length),i.input_schema&&(n+=Wu.encode(JSON.stringify(i.input_schema)).length)}),n},hF=async(e,t)=>{if(e.sessionId){let r=await bG(e.sessionId);if(r){let n=(0,Ly.join)(Up.HOME_DIR,r,"config.json"),i=(0,Ly.join)(Up.HOME_DIR,r,`${e.sessionId}.json`);try{let o=JSON.parse(await(0,Oy.readFile)(i,"utf8"));if(o&&o.Router)return o.Router}catch{}try{let o=JSON.parse(await(0,Oy.readFile)(n,"utf8"));if(o&&o.Router)return o.Router}catch{}}}};function qp(e){let t=e||"";return t.includes(",")&&(t=t.split(",").pop()||t),t.includes("/")&&(t=t.split("/").pop()||t),t.includes(":")&&(t=t.split(":")[0]),t.trim().toLowerCase()}function fF(e){let t=qp(e),r=t.includes("[1m]")||t.endsWith("[1m"),n=t.replace(/\[1m\]|\[1m$/g,""),i=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(i)return{family:i[1].toLowerCase(),extended:r};let o=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return o?{family:o[1].toLowerCase(),extended:r}:{family:null,extended:r}}function mG(e,t){if(!t||!e)return null;let r=qp(e);if(t[e])return t[e];if(t[r])return t[r];let{family:n}=fF(e);if(n&&t[n])return t[n];for(let[i,o]of Object.entries(t)){let s=qp(i);if(s&&r.includes(s))return o}return null}function AF(e){return e?(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0):0}function Kv(e){if(!e?.includes(","))return null;let[t,...r]=e.split(","),n=t.trim(),i=r.join(",").trim();return!n||!i?null:{providerName:n,routeModel:i}}function is(e,t,r,n){let i=Kv(e);if(!i)return e;let{providerName:o,routeModel:s}=i,a=t.find(c=>c.name.toLowerCase()===o.toLowerCase());if(a&&a.enabled===!1)return null;if(n&&!r){let c=$C(),d=c.getPromotion(o,s,n,t);if(d){let f=Kv(d);if(f){let h=t.find(g=>g.name.toLowerCase()===f.providerName.toLowerCase()),A=h?.models?.find(g=>String(g).toLowerCase()===f.routeModel.toLowerCase());if(h&&A)return`${h.name},${A}`}c.clear(o,s,n)}}if(!r&&!os().isAvailable(o,s))return null;let u=fG(o);if(u){let c=u.limitDaily!==void 0&&u.usedDailyBalance!==void 0&&u.usedDailyBalance>=u.limitDaily,d=u.totalBalance!==void 0&&u.usedBalance!==void 0&&u.usedBalance>=u.totalBalance;if(c||d)return null}let l=a?.models?.find(c=>String(c).toLowerCase()===s.toLowerCase());return a&&l?`${a.name},${l}`:e}function Ra(e,t,r,n,i){let o=os(),s=[r?.[e],n?.[e]];for(let a of s)if(!(!Array.isArray(a)||a.length===0))for(let u of a){let l=is(u,t);if(l)return l}return null}function EG(e){return e.body.messages?.some(t=>t.role==="user"&&Array.isArray(t.content)&&t.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function yG(e){let t=qp(e);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(r=>r.test(t))}function CG(e,t,r,n,i,o,s){let a=r.longContextThreshold||6e4,u=Math.max(t,AF(i)),l=e.modelFamily;if((o||u>2e5)&&r.extendedContext){let c=is(r.extendedContext,n,!1,"extendedContext");if(c)return e.log.info(`Family: using extended context model (1M+), tokens: ${u}, estimated: ${t}, explicit: ${o}`),{model:c,scenarioType:"extendedContext",isFallback:!1};let d=Ra("extendedContext",n,r.fallback,s,l);if(d)return e.log.info(`Family: using extended context fallback model (1M+), tokens: ${u}, estimated: ${t}, explicit: ${o}`),{model:d,scenarioType:"extendedContext",isFallback:!0};e.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(u>a&&(r.longContext||r.fallback?.longContext?.length||s?.longContext?.length)){let c=r.longContext?is(r.longContext,n,!1,"longContext"):null;if(c)return e.log.info(`Family: using long context model, tokens: ${u}, estimated: ${t}`),{model:c,scenarioType:"longContext",isFallback:!1};let d=Ra("longContext",n,r.fallback,s,l);if(d)return e.log.info(`Family: using long context fallback model, tokens: ${u}, estimated: ${t}`),{model:d,scenarioType:"longContext",isFallback:!0};e.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(e.body.tools)&&e.body.tools.some(c=>c.type?.startsWith("web_search"))&&r.webSearch){let c=is(r.webSearch,n,!1,"webSearch");if(c)return{model:c,scenarioType:"webSearch",isFallback:!1};let d=Ra("webSearch",n,r.fallback,s,l);if(d)return e.log.info("Family: using webSearch fallback model"),{model:d,scenarioType:"webSearch",isFallback:!0};e.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(e.body.thinking&&r.think){let c=is(r.think,n,!1,"think");if(c)return{model:c,scenarioType:"think",isFallback:!1};let d=Ra("think",n,r.fallback,s,l);if(d)return e.log.info("Family: using think fallback model"),{model:d,scenarioType:"think",isFallback:!0};e.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let c=is(r.default,n,!1,"default");if(c)return{model:c,scenarioType:"default",isFallback:!1};let d=Ra("default",n,r.fallback,s,l);if(d)return e.log.info("Family: using default fallback model"),{model:d,scenarioType:"default",isFallback:!0};e.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var DG=async(e,t,r,n)=>{let i=await hF(e,r),o=r.get("providers")||[],s=i||r.get("Router"),a=r.get("fallback");if(e.body.model.includes(",")){let m=is(e.body.model,o,!1,"default");if(m)return{model:m,scenarioType:"default"};e.log.warn(`Explicit model ${e.body.model} unavailable (fail pool), trying fallback`);let E=Ra("default",o,void 0,a);if(E)return e.log.info(`Using fallback for explicit model: ${E}`),{model:E,scenarioType:"default"};e.log.warn(`No fallback available for explicit model ${e.body.model}, continuing through routing logic`)}let{family:u,extended:l}=fF(e.body.model),c=s?.families?.[u||""];if(c&&s?.enableFamilyRouting){e.log.info(`Using model family routing for: ${u}${l?" (1M)":""}`),e.modelFamily=u,e.familyFallback=c.fallback;let m=CG(e,t,c,o,n,l,a);if(m)return{model:m.model,scenarioType:m.scenarioType}}let d=mG(e.body.model,s?.models);if(d){let m=is(d,o,!1,"modelMapping");if(m)return e.log.info(`Using mapped model for ${e.body.model}: ${d}`),{model:m,scenarioType:"modelMapping"};e.log.warn(`Mapped model ${d} unavailable (fail pool), skipping`)}let f=Math.max(t,AF(n)),h=s?.extendedContextThreshold||2e5;if(f>h&&s?.extendedContext){e.log.info(`Using extended context (1M) model due to token count: ${f}, estimated: ${t}, threshold: ${h}`);let m=is(s.extendedContext,o,!1,"extendedContext");if(m)return{model:m,scenarioType:"extendedContext"};e.log.warn(`Extended context model ${s.extendedContext} unavailable (fail pool), trying fallback`);let E=Ra("extendedContext",o,void 0,a);if(E)return{model:E,scenarioType:"extendedContext"}}let A=s?.longContextThreshold||6e4;if(f>A&&s?.longContext){e.log.info(`Using long context model due to token count: ${f}, estimated: ${t}, threshold: ${A}`);let m=is(s.longContext,o,!1,"longContext");if(m)return{model:m,scenarioType:"longContext"};e.log.warn(`Long context model ${s.longContext} unavailable (fail pool), trying fallback`);let E=Ra("longContext",o,void 0,a);if(E)return{model:E,scenarioType:"longContext"}}if(e.body?.system?.length>1&&e.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let m=e.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(m)return e.body.system[1].text=e.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${m[1]}</CCR-SUBAGENT-MODEL>`,""),{model:m[1],scenarioType:"default"}}let g=r.get("Router");if(e.body.model?.includes("claude")&&e.body.model?.includes("haiku")&&g?.background){e.log.info(`Using background model for ${e.body.model}`);let m=is(g.background,o,!1,"background");if(m)return{model:m,scenarioType:"background"};e.log.warn(`Background model ${g.background} unavailable (fail pool), falling through`)}if(Array.isArray(e.body.tools)&&e.body.tools.some(m=>m.type?.startsWith("web_search"))&&s?.webSearch){let m=is(s.webSearch,o,!1,"webSearch");if(m)return{model:m,scenarioType:"webSearch"};e.log.warn(`WebSearch model ${s.webSearch} unavailable (fail pool), trying fallback`);let E=Ra("webSearch",o,void 0,a);if(E)return{model:E,scenarioType:"webSearch"}}if(e.body.thinking&&s?.think){e.log.info(`Using think model for ${e.body.thinking}`);let m=is(s.think,o,!1,"think");if(m)return{model:m,scenarioType:"think"};e.log.warn(`Think model ${s.think} unavailable (fail pool), trying fallback`);let E=Ra("think",o,void 0,a);if(E)return{model:E,scenarioType:"think"}}if(s?.default){let m=is(s.default,o,!1,"default");if(m)return{model:m,scenarioType:"default"};e.log.warn(`Default model ${s.default} unavailable (fail pool), trying fallback`);let E=Ra("default",o,void 0,a);if(E)return{model:E,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Zv=async(e,t,r)=>{let{configService:n,event:i}=r;if(e.originalModel=e.body.model,e.body.metadata?.user_id){let f=e.body.metadata.user_id.split("_session_");f.length>1&&(e.sessionId=f[1])}let o=await hF(e,n)||n.get("Router"),s=n.get("providers")||[],a=Ql.get(e.sessionId),{messages:u,system:l=[],tools:c}=e.body,d=n.get("REWRITE_SYSTEM_PROMPT");if(d&&l.length>1&&l[1]?.text?.includes("<env>")){let f=await(0,Oy.readFile)(d,"utf-8");l[1].text=`${f}<env>${l[1].text.split("<env>").pop()}`}try{let[f,h]=e.body.model.split(","),A=r.tokenizerService?.getTokenizerConfigForModel(f,h),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:u,system:l,tools:c},A)).tokenCount:g=dF(u,l,c),e.tokenCount=g;let m,E=n.get("CUSTOM_ROUTER_PATH");if(E)try{m=await Vr(E)(e,n.getAll(),{event:i})}catch(D){e.log.error(`failed to load custom router: ${D.message}`)}if(m)e.scenarioType="default";else{let D=await DG(e,g,n,a);m=D.model,e.scenarioType=D.scenarioType}if(o?.image&&m!==o.image&&EG(e)&&!yG(m)){let D=is(o.image,s,!1,"image");D?(e.log.info(`Using image model fallback for ${m}`),m=D,e.scenarioType="image"):(e.log.warn(`Image model ${o.image} unavailable (fail pool), keeping ${m}`),e.scenarioType="image")}e.body.model=m}catch(f){e.log.error(`Error in router middleware: ${f.message}`),e.body.model=o?.default,e.scenarioType="default"}},Zu=new Map,Xv=1e3;function Ay(){if(Zu.size<=Xv)return;let e=[...Zu.keys()].slice(0,Zu.size-Xv);for(let t of e)Zu.delete(t)}var bG=async e=>{if(Zu.has(e)){let t=Zu.get(e);return!t||t===""?null:t}try{let t=await(0,WI.opendir)(Up.CLAUDE_PROJECTS_DIR),r=[];for await(let o of t)o.isDirectory()&&r.push(o.name);let n=r.map(async o=>{let s=(0,Ly.join)(Up.CLAUDE_PROJECTS_DIR,o,`${e}.jsonl`);try{return(await(0,WI.stat)(s)).isFile()?o:null}catch{return null}}),i=await Promise.all(n);for(let o of i)if(o)return Zu.set(e,o),Ay(),o;return Zu.set(e,""),Ay(),null}catch(t){return console.error("Error searching for project by session:",t),Zu.set(e,""),Ay(),null}};$c();var Hc=class{async fetchJson(e,t,r,n,i){let o=i||t.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:a}=await Promise.resolve().then(()=>Sn(Po(),1));s.dispatcher=new a(new URL(n).toString())}catch{}try{let a=await fetch(e,s);return a.ok?await a.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}},wG=class extends Hc{async queryQuota(e,t,r){let n=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,r),i=(Array.isArray(n?.balance_infos)?n.balance_infos:[]).find(s=>Pn(s?.total_balance)!==void 0);if(!i)return null;let o=Pn(i.total_balance);return o===void 0?null:{totalBalance:o,currency:typeof i.currency=="string"?i.currency:void 0}}},IG=class extends Hc{async queryQuota(e,t,r){let n=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,r))?.data;if(!n||typeof n!="object")return null;let i={},o=Pn(n.limit),s=Pn(n.limit_remaining),a=Pn(n.usage),u=Pn(n.usage_daily);return o!==void 0&&(i.totalBalance=o),s!==void 0&&(i.remainingBalance=s),a!==void 0&&(i.usedBalance=a),u!==void 0&&(i.usedDailyBalance=u),this.hasQuotaData(i)?i:null}},vG=class extends Hc{async queryQuota(e,t,r){let n=PG(e.baseUrl),i=(await this.fetchJson(n,e,t,r))?.data;if(!i||typeof i!="object")return null;let o={},s=Pn(i.totalBalance),a=Pn(i.balance);return s!==void 0&&(o.totalBalance=s),a!==void 0&&(o.remainingBalance=a),s!==void 0&&a!==void 0&&(o.usedBalance=Math.max(0,s-a)),this.hasQuotaData(o)?o:null}},BG=class extends Hc{async queryQuota(e,t,r){if(!e.apiKey)return null;let n={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:i}=await Promise.resolve().then(()=>Sn(Po(),1));n.dispatcher=new i(new URL(r).toString())}catch{}try{let i=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",n);if(!i.ok)return null;let o=await i.json(),s=Array.isArray(o?.data?.limits)?o.data.limits:[],a=null,u=null,l=null;for(let d of s)d.type==="TOKENS_LIMIT"?d.unit===3?a=d:d.unit===6?u=d:a||(a=d):d.type==="TIME_LIMIT"&&(l=d);let c={};if(a){let d=Pn(a.currentValue),f=Pn(a.usage),h=Pn(a.remaining),A=Pn(a.percentage);d!==void 0?c.usedDailyBalance=d:A!==void 0&&(c.usedDailyBalance=A,c.limitDaily=100),f!==void 0?c.limitDaily=f:d!==void 0&&h!==void 0&&(c.limitDaily=d+h),a.nextResetTime&&(c.resetTime=new Date(a.nextResetTime).toISOString())}if(u){let d=Pn(u.currentValue),f=Pn(u.usage),h=Pn(u.remaining),A=Pn(u.percentage);d!==void 0?c.usedBalance=d:A!==void 0&&(c.usedBalance=A,c.totalBalance=100),f!==void 0?c.totalBalance=f:d!==void 0&&h!==void 0&&(c.totalBalance=d+h),u.nextResetTime&&!c.resetTime&&(c.resetTime=new Date(u.nextResetTime).toISOString())}if(l){if(c.usedDailyBalance===void 0){let d=Pn(l.currentValue);d!==void 0&&(c.usedDailyBalance=d)}if(c.limitDaily===void 0){let d=Pn(l.usage),f=Pn(l.currentValue),h=Pn(l.remaining);d!==void 0?c.limitDaily=d:f!==void 0&&h!==void 0&&(c.limitDaily=f+h)}l.nextResetTime&&!c.resetTime&&(c.resetTime=new Date(l.nextResetTime).toISOString())}return this.hasQuotaData(c)?c:null}catch{return null}}},xG=class extends Hc{async queryQuota(e,t,r){if(!e.quotaToken)return null;let n={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)};if(r)try{let{ProxyAgent:s}=await Promise.resolve().then(()=>Sn(Po(),1));n.dispatcher=new s(new URL(r).toString())}catch{}let i=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"}}}),o=new URLSearchParams({params:i,region:"cn-beijing"}).toString();try{let s=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...n,body:o});if(!s.ok)return null;let a=(await s.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(a)||a.length===0)return null;let u=a[0]?.codingPlanQuotaInfo;if(!u)return null;let l={},c=Pn(u.per5HourUsedQuota),d=Pn(u.per5HourTotalQuota);c!==void 0&&(l.usedDailyBalance=c),d!==void 0&&(l.limitDaily=d);let f=Pn(u.perWeekUsedQuota),h=Pn(u.perWeekTotalQuota);return f!==void 0&&(l.usedBalance=f),h!==void 0&&(l.totalBalance=h),this.hasQuotaData(l)?l:null}catch{return null}}},_G=class extends Hc{async queryQuota(e,t,r){let n=e.quotaToken||e.apiKey;if(!n)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${n.trim()}`},signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:o}=await Promise.resolve().then(()=>Sn(Po(),1));i.dispatcher=new o(new URL(r).toString())}catch{}try{let o=await fetch("https://api.kimi.com/coding/v1/usages",i);if(!o.ok)return null;let s=await o.json(),a={},u=Array.isArray(s?.limits)?s.limits:[];if(u.length>0&&u[0]?.detail){let c=u[0].detail,d=Pn(c.limit),f=Pn(c.remaining),h=c.resetTime;d!==void 0&&f!==void 0&&(a.usedDailyBalance=Math.max(0,d-f),a.limitDaily=d),h&&(a.resetTime=new Date(h).toISOString())}let l=s?.usage;if(l){let c=Pn(l.limit),d=Pn(l.remaining),f=Pn(l.used),h=l.resetTime;c!==void 0&&(a.totalBalance=c,f!==void 0?a.usedBalance=f:d!==void 0&&(a.usedBalance=Math.max(0,c-d),a.remainingBalance=d)),h&&(a.resetTime7d=new Date(h).toISOString(),a.resetTime||(a.resetTime=a.resetTime7d))}return this.hasQuotaData(a)?a:null}catch{return null}}},SG=class extends Hc{async queryQuota(e,t,r){let n=e.quotaToken||e.apiKey;if(!n)return null;let i=nD(e.baseUrl)||"api.minimaxi.com",o=i.endsWith(".minimax.io")||i==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let s=[`https://${o}/v1/token_plan/remains`,`https://${o}/v1/api/openplatform/coding_plan/remains`],a=null;for(let y of s)if(a=await this.fetchJson(y,e,t,r,n.trim()),a)break;if(!a)return null;if(a?.base_resp){let y=a.base_resp.status_code;if(y!==void 0&&y!==0)return null}let u=Array.isArray(a?.model_remains)?a.model_remains:[];if(u.length===0)return null;let l=u[0],c={},d=Pn(l.current_interval_total_count),f=Pn(l.current_interval_usage_count),h=Pn(l.current_interval_remaining_percent),A=Pn(l.end_time);d!==void 0&&f!==void 0&&d>0?(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d):h!==void 0&&(c.limitDaily=100,c.usedDailyBalance=Math.max(0,100-h)),A&&(c.resetTime=new Date(A).toISOString());let g=Pn(l.current_weekly_total_count),m=Pn(l.current_weekly_usage_count),E=Pn(l.current_weekly_remaining_percent),D=Pn(l.weekly_end_time);return g!==void 0&&m!==void 0&&g>0?(c.usedBalance=Math.max(0,g-m),c.remainingBalance=m,c.totalBalance=g):E!==void 0&&(c.totalBalance=100,c.usedBalance=Math.max(0,100-E),c.remainingBalance=E),D&&!c.resetTime&&(c.resetTime=new Date(D).toISOString()),this.hasQuotaData(c)?c:null}catch{return null}}},FG=new wG,kG=new IG,TG=new vG,RG=new BG,QG=new xG,NG=new _G,OG=new SG;function LG(e){let t=nD(e);return t?t==="kimi.com"||t.endsWith(".kimi.com")||t==="moonshot.cn"||t.endsWith(".moonshot.cn")?NG:t==="minimaxi.com"||t.endsWith(".minimaxi.com")||t==="minimax.io"||t.endsWith(".minimax.io")?OG:t==="deepseek.com"||t.endsWith(".deepseek.com")?FG:t==="openrouter.ai"||t.endsWith(".openrouter.ai")?kG:t==="siliconflow.com"||t.endsWith(".siliconflow.com")||t==="siliconflow.cn"||t.endsWith(".siliconflow.cn")?TG:t==="bigmodel.cn"||t.endsWith(".bigmodel.cn")?RG:t==="dashscope.aliyuncs.com"||t.endsWith(".dashscope.aliyuncs.com")?QG:null:null}function PG(e){let t=nD(e);return t?.endsWith(".siliconflow.cn")||t==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function nD(e){try{return new URL(e).hostname.toLowerCase()}catch{return null}}function Pn(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string")return;let t=e.trim().replace(/,/g,"");if(!t)return;let r=Number(t);return Number.isFinite(r)?r:void 0}var MG={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function UG(e){return e===!0||e==="true"||e===1||e==="1"}function $G(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${n}`}function jG(e){try{let t=new URL(e),r=t.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),t.pathname=`${r}/models`,t.toString()}catch{return null}}function HG(e){try{let t=new URL(e).hostname.toLowerCase();return t.includes("moonshot")||t.includes("kimi")}catch{return!1}}async function py(e,t,r){let n=jG(e.baseUrl);if(!n)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let i={method:"GET",headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:a}=await Promise.resolve().then(()=>Sn(Po(),1));i.dispatcher=new a(new URL(r).toString())}catch{}let o=await fetch(n,i);if(o.headers&&eD(e.name,e.baseUrl,o.headers),o.ok)return{success:!0,headers:o.headers};if(o.status===429)return{success:!1,error:`HTTP 429: ${(await o.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:o.headers};if(o.status>=400&&o.status<500)return{success:!0,headers:o.headers};let s=await o.text().catch(()=>"");return{success:!1,error:`HTTP ${o.status}: ${s.slice(0,100)}`,headers:o.headers}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown probe error"}}}async function qG(e,t,r,n){let i=e.wakeupModel||(Array.isArray(e.models)?e.models[0]:void 0);if(!i)return{success:!1,error:"No models configured for provider"};let o=e.baseUrl.includes("anthropic")||i.includes("claude"),s=o?e.baseUrl.includes("/messages")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/v1/messages`:e.baseUrl.includes("/chat/completions")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let a={"Content-Type":"application/json"};o?(a["x-api-key"]=e.apiKey,a["anthropic-version"]="2023-06-01"):a.Authorization=`Bearer ${e.apiKey}`;let u={method:"POST",headers:a,body:JSON.stringify({model:i,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:d}=await Promise.resolve().then(()=>Sn(Po(),1));u.dispatcher=new d(new URL(r).toString())}catch{}n?.info(`Sending scheduled wake-up call to provider ${e.name} using model ${i}...`);let l=await fetch(s,u);if(l.ok)return{success:!0};let c=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${c.slice(0,200)||"Unknown error"}`}}catch(a){return{success:!1,error:a?.message||a?.toString()||"Unknown wake-up error"}}}async function GG(e,t,r,n,i){let o=e.baseUrl.includes("anthropic")||t.includes("claude"),s=o?e.baseUrl.includes("/messages")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/v1/messages`:e.baseUrl.includes("/chat/completions")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let a={"Content-Type":"application/json"};o?(a["x-api-key"]=e.apiKey,a["anthropic-version"]="2023-06-01"):a.Authorization=`Bearer ${e.apiKey}`;let u={method:"POST",headers:a,body:JSON.stringify({model:t,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:d}=await Promise.resolve().then(()=>Sn(Po(),1));u.dispatcher=new d(new URL(n).toString())}catch{}i?.debug?.(`Sending independent ping to rate-limited model ${e.name} (${t})...`);let l=await fetch(s,u);if(l.ok)return{success:!0};let c=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${c.slice(0,200)||"Unknown error"}`}}catch(a){return{success:!1,error:a?.message||a?.toString()||"Unknown ping error"}}}var VG=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,t,r,n,i){this.config={...MG,...t},this.getProviders=e,this.getHttpsProxy=r,this.logger=n,this.getConfig=i}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.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.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(o=>o?.name&&o.enabled!==!1&&!this.config.excludeProviders.includes(o.name)),t=this.getHttpsProxy?.(),r=os();if(e.length===0)return;let n=[];for(let o of e){let s=LG(o.baseUrl),a=Array.isArray(o.models)?o.models:[];s&&n.push({provider:o.name,models:a,type:"quota-adapter",promise:s.queryQuota(o,this.config.probeTimeoutMs,t).then(u=>{if(u){hG(o.name,u),this.logger?.debug?.(`Stored quota probe result for ${o.name}`);let l=u.limitDaily!==void 0&&u.usedDailyBalance!==void 0&&u.usedDailyBalance>=u.limitDaily,c=u.totalBalance!==void 0&&u.usedBalance!==void 0&&u.usedBalance>=u.totalBalance;if(l||c){let d=l?`Quota exhausted: 5h limit reached (${u.usedDailyBalance}/${u.limitDaily})`:`Quota exhausted: 7d balance depleted (${u.usedBalance}/${u.totalBalance})`;for(let f of a){if(r.getState(o.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${o.name} (${f}): already rate-limited with active cooldown`);continue}r.forceOpen(o.name,f,d)}this.logger?.warn?.(`${d} for ${o.name}, marked as unhealthy`)}else for(let d of a){let f=r.getState(o.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(r.recover(o.name,d),this.logger?.info?.(`Quota recovered for ${o.name} (${d}), marked as healthy`))}}})}),HG(o.baseUrl)&&n.push({provider:o.name,models:a,type:"rate-limit-headers",promise:py(o,this.config.probeTimeoutMs,t).then(()=>{})})}if(n.length===0)return;this.logger?.debug?.(`Running quota probe with ${n.length} tasks for ${e.length} providers`);let i=await Promise.allSettled(n.map(o=>o.promise));for(let o=0;o<n.length;o++){let s=i[o];if(s.status==="rejected"){let a=n[o];this.logger?.warn?.(`Quota probe failed for ${a.provider} (${a.type}): ${s.reason}`)}}}async runHealthProbe(){let e=os(),t=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!this.config.excludeProviders.includes(i.name)),r=this.getHttpsProxy?.();if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let n=await Promise.allSettled(t.map(i=>py(i,this.config.probeTimeoutMs,r)));for(let i=0;i<t.length;i++){let o=t[i],s=n[i],a=Array.isArray(o.models)?o.models:[];if(s.status==="fulfilled"){let u=s.value;if(u.success){let l=0;for(let c of a){let d=e.getState(o.name,c);if(d&&d.status==="open"){let f=d.lastError?.includes("Quota exhausted"),h=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(f){this.logger?.debug?.(`Skipping health probe recovery for ${o.name} (${c}) because quota is exhausted`);continue}if(h||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${o.name} (${c})`);continue}}e.recordSuccess(o.name,c),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${o.name}`)}else{for(let l of a)e.recordFailure(o.name,l,u.error);this.logger?.warn?.(`Health probe failed for ${o.name}: ${u.error}`)}}else{for(let u of a)e.recordFailure(o.name,u,s.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${o.name}: ${s.reason}`)}}}async runRateLimitProbe(){let e=os(),t=e.getRateLimitedModels();if(t.length===0)return;let r=this.getProviders(),n=this.getHttpsProxy?.(),i=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let o of t){let[s,...a]=o.split(","),u=a.join(",");if(!s||!u)continue;let l=e.getState(s,u);if(!l||!l.rateLimitUntil)continue;if(Date.now()>=l.rateLimitUntil){e.recover(s,u),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${o}`);continue}let c=r.find(d=>d?.name===s&&d.enabled!==!1);if(!c){this.logger?.warn?.(`Provider ${s} not found or disabled for rate-limit probe`);continue}try{let d=await GG(c,u,i,n,this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${o}, recovering model`),e.recover(s,u);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();l.rateLimitUntil&&l.rateLimitUntil>f?l.rateLimitUntil+=120*1e3:l.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${o} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${o} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${o}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&a.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,r=t.getHours(),n=t.getMinutes(),i=$G(t),o=this.getHttpsProxy?.(),s=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let a of e){let u=a.wakeupTime||s,[l,c]=u.split(":"),d=parseInt(l,10),f=parseInt(c,10);isNaN(d)||isNaN(f)||r===d&&n===f&&this.lastWakeupDate.get(a.name)!==i&&(this.lastWakeupDate.set(a.name,i),this.logger?.info?.(`Scheduled wake-up triggered for provider ${a.name} at ${u}`),qG(a,3e4,o,this.logger).then(h=>{h.success?this.logger?.info?.(`Successfully woke up provider ${a.name}`):this.logger?.error?.(`Failed to wake up provider ${a.name}: ${h.error}`)}).catch(h=>{this.logger?.error?.(`Error in wake-up task for ${a.name}: ${h}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?UG(this.getConfig("WAKEUP_ENABLED")):!1}async probeProviderManually(e){let t=this.getProviders().find(o=>o.name===e);if(!t)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(t.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let r=this.getHttpsProxy?.(),n=await py(t,this.config.probeTimeoutMs,r),i=Array.isArray(t.models)?t.models:[];if(n.success)for(let o of i)os().recordSuccess(t.name,o);else for(let o of i)os().recordFailure(t.name,o,n.error);return n.success}},Wf=null;function JG(e,t,r,n,i){return Wf||(Wf=new VG(e,t,r,n,i)),Wf}function YG(e,t,r,n,i){let o=JG(e,t,r,n,i);return o.start(),o}function zG(){Wf&&Wf.stop()}$c();var WG=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 r=this.plugins.get(e),n=this.pluginInstances.get(e);if(!r||!n)throw new Error(`Plugin ${e} not found`);r.enabled&&await t.register(n.register,r.options)}async enablePlugins(e){for(let[t,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(t,e)}catch(n){let i=n instanceof Error?n.message:String(n);e.log?.error(`Failed to enable plugin ${t}: ${i}`)}}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 r=this.plugins.get(e);r&&(r.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Xy=new WG,KG=Ul(Fj(),1),ZG=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let r=this.buffer.split(`
|
|
1348
|
+
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(e)}}clean_text(e){let t=[];for(let r of e){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},gH=pH,mH=class extends tl{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("\uFF5E")?e=e.split("\uFF5E").map(t=>t.normalize("NFKC")).join("\uFF5E"):e=e.normalize("NFKC"),e}},EH=mH,yH=class extends tl{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>oF(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},CH=yH,DH=class extends tl{normalize(e){let t=Ig(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},bH=DH,wH=class extends tl{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},vg=wH,IH=class extends vg{constructor(){super(...arguments),this.form="NFC"}},vH=IH,BH=class extends vg{constructor(){super(...arguments),this.form="NFD"}},xH=BH,_H=class extends vg{constructor(){super(...arguments),this.form="NFKC"}},SH=_H,FH=class extends vg{constructor(){super(...arguments),this.form="NFKD"}},kH=FH,TH=class extends tl{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},RH=TH,QH=class extends tl{normalize(e){return iF(e)}},NH=QH,OH=class extends tl{normalize(e){return e.toLowerCase()}},LH=OH,PH=class extends tl{normalize(e){return e=this.config.prepend+e,e}},MH=PH;function UH(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new gH(e);case"Precompiled":return new EH(e);case"Sequence":return new CH(e);case"Replace":return new bH(e);case"NFC":return new vH(e);case"NFD":return new xH(e);case"NFKC":return new SH(e);case"NFKD":return new kH(e);case"Strip":return new RH(e);case"StripAccents":return new NH(e);case"Lowercase":return new LH(e);case"Prepend":return new MH(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var oF=UH,$H=class extends EA{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},au=$H,jH=class extends au{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=nF,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},HH=jH,qH=class extends au{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},GH=qH,VH=class extends au{constructor(e){super(),this.replacement=e.replacement??"\u2581",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){let{section_index:r=void 0}=t??{},n=e.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},JH=VH,YH=class extends au{constructor(e){super(),this.config=e,this.pattern=Ig(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):dH(e,this.pattern)}},zH=YH,WH=class extends au{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${tA}]+|[${tA}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},KH=WH,ZH=class extends au{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},XH=ZH,eq=class extends au{constructor(){super(),this.pattern=new RegExp(`[^\\s${tA}]+|[${tA}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},tq=eq,rq=class extends au{constructor(e){super(),this.config=e,this.pattern=Ig(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},nq=rq,iq=class extends au{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>sF(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},oq=iq,sq=class extends au{pre_tokenize_text(e){return hH(e)}},aq=sq;function uq(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new tq;case"Sequence":return new oq(e);case"Whitespace":return new GH;case"WhitespaceSplit":return new aq;case"Metaspace":return new JH(e);case"ByteLevel":return new HH(e);case"Split":return new zH(e);case"Punctuation":return new KH(e);case"Digits":return new XH(e);case"Replace":return new nq(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var sF=uq,lq=class extends EA{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=sH(t,this.tokens_to_ids,this.unk_token_id)),t}convert_tokens_to_ids(e){return e.map(t=>this.tokens_to_ids.get(t)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(t=>this.vocab[Number(t)]??this.unk_token)}},Bg=lq,cq=class extends Bg{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=rD(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){let t=[];for(let r of e){let n=[...r];if(n.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let i=!1,o=0,s=[];for(;o<n.length;){let a=n.length,u=null;for(;o<a;){let l=n.slice(o,a).join("");if(o>0&&(l=this.config.continuing_subword_prefix+l),this.tokens_to_ids.has(l)){u=l;break}--a}if(u===null){i=!0;break}s.push(u),o=a}i?t.push(this.unk_token):t.push(...s)}return t}},qv=cq,Gv=class aF{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new aF(!1,new Map)}},dq=class{constructor(){this.root=Gv.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let r of e){let n=t.children.get(r);n===void 0&&(n=Gv.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(let n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},hq=dq,fy=class uF{constructor(t,r,n,i,o){this.token_id=t,this.node_id=r,this.pos=n,this.length=i,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let t=new uF(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},fq=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new fy(this.bos_token_id??0,0,0,0,0),i=new fy(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(n)}insert(e,t,r,n){let i=this.nodes.length,o=new fy(n,i,e,t,r);this.begin_nodes[e].push(o),this.end_nodes[e+t].push(o),this.nodes.push(o)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let o of this.begin_nodes[t]){o.prev=null;let s=0,a=null;for(let u of this.end_nodes[t]){let l=u.backtrace_score+o.score;(a===null||l>s)&&(a=u.clone(),s=l)}if(a!==null)o.prev=a,o.backtrace_score=s;else return[]}++t}let r=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let i=n.clone();for(;i.prev!==null;)r.push(i.clone()),i=i.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},Aq=fq;function pq(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}var gq=class extends Bg{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=e.vocab[n];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,i)=>[n,i])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=pq(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new hq,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,r=1,n=0;for(;n<t.length;){let i=!1,o=[],s=t.slice(n).join(""),a=this.trie.common_prefix_search(s);for(let u of a){o.push(u);let l=this.tokens_to_ids.get(u),c=this.scores[l],d=lH(u);e.insert(n,d,c,l),!i&&d===r&&(i=!0)}i||e.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(e){let t=new Aq(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let r of e){let n=this.tokenize(r);t.push(...n)}return t}},Vv=gq,mq=class{constructor(e=(r,n)=>r>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},Eq=mq,yq=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},Cq=yq,Dq=class extends Bg{constructor(e){super(e),this.tokens_to_ids=rD(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new Cq(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let i=new Eq((a,u)=>a.score<u.score),o={token:r[0],bias:0,prev:null,next:null},s=o;for(let a=1;a<r.length;++a){let u={bias:a/r.length,token:r[a],prev:s,next:null};s.next=u,this.add_node(i,s),s=u}for(;!i.is_empty();){let a=i.pop();if(a.deleted||!a.next||a.next.deleted)continue;if(a.deleted=!0,a.next.deleted=!0,a.prev){let l={...a.prev};a.prev.deleted=!0,a.prev=l,l.prev?l.prev.next=l:o=l}let u={token:a.token+a.next.token,bias:a.bias,prev:a.prev,next:a.next.next};u.prev?(u.prev.next=u,this.add_node(i,u.prev)):o=u,u.next&&(u.next.prev=u,this.add_node(i,u))}for(let a=o;a!==null;a=a.next)n.push(a.token)}else n=r;if(this.continuing_subword_suffix)for(let i=0;i<n.length-1;++i)n[i]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){let r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){let t=[];for(let r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}let n=this.bpe(r);for(let i of n)if(this.tokens_to_ids.has(i))t.push(i);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(i)).map(s=>`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(s=>this.tokens_to_ids.has(s))?t.push(...o):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},Jv=Dq,bq=class extends Bg{constructor(e,t){super(e);let r=e.vocab;this.tokens_to_ids=rD(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,i]of this.tokens_to_ids)this.vocab[i]=n}encode(e){return e}},wq=bq;function Iq(e,t){switch(e.type){case"WordPiece":return new qv(e);case"Unigram":return new Vv(e,t.eos_token);case"BPE":return new Jv(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Vv(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Jv(e):new qv(e):new wq(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var vq=Iq,Bq=class extends EA{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},yA=Bq,xq=class extends yA{post_process(e,t=null,r=!0){let n=t===null?this.config.single:this.config.pair,i=[],o=[];for(let s of n)"SpecialToken"in s?r&&(i.push(s.SpecialToken.id),o.push(s.SpecialToken.type_id)):"Sequence"in s&&(s.Sequence.id==="A"?(i=Ks(i,e),o=Ks(o,new Array(e.length).fill(s.Sequence.type_id))):s.Sequence.id==="B"&&(i=Ks(i,t),o=Ks(o,new Array(t.length).fill(s.Sequence.type_id))));return{tokens:i,token_type_ids:o}}},_q=xq,Sq=class extends yA{post_process(e,t=null){return{tokens:t?Ks(e,t):e}}},Fq=Sq,kq=class extends yA{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Ks([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){let i=[],o=r?[this.sep[0]]:[];e=Ks(e,i,t,o),n=Ks(n,new Array(t.length+i.length+o.length).fill(1))}return{tokens:e,token_type_ids:n}}},Tq=kq,Rq=class extends yA{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Ks([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){let i=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];e=Ks(e,i,t,o),n=Ks(n,new Array(t.length+i.length+o.length).fill(1))}return{tokens:e,token_type_ids:n}}},Qq=Rq,Nq=class extends yA{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>lF(t))}post_process(e,t=null,r=!0){let n={tokens:e};for(let i of this.processors)n=i.post_process(n.tokens,t,r);return n}},Oq=Nq;function Lq(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new _q(e);case"ByteLevel":return new Fq(e);case"BertProcessing":return new Tq(e);case"RobertaProcessing":return new Qq(e);case"Sequence":return new Oq(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var lF=Lq,Pq=class extends EA{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},uu=Pq,Mq=class extends uu{constructor(e){super(e),this.byte_decoder=nH,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let n of e)this.added_tokens.find(i=>i.content===n)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},Uq=Mq,$q=class extends uu{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){let n=this.config.prefix;n&&t.startsWith(n)?t=t.replace(n,""):t=" "+t}return this.cleanup&&(t=tD(t)),t})}},jq=$q,Hq=class extends uu{constructor(e){super(e),this.replacement=e.replacement??"\u2581"}decode_chain(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}},qq=Hq,Gq=class extends uu{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},Vq=Gq,Jq=class extends uu{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let r=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=tD(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Yq=Jq,zq=class extends uu{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>cF(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},Wq=zq,Kq=class extends uu{decode_chain(e){let t=Ig(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},Zq=Kq,Xq=class extends uu{decode_chain(e){return[e.join("")]}},eG=Xq,tG=class extends uu{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let i=0;i<this.start&&t[i]===this.content;++i)r=i+1;let n=t.length;for(let i=0;i<this.stop;++i){let o=t.length-i-1;if(t[o]===this.content){n=o;continue}else break}return t.slice(r,n)})}},rG=tG,nG=class extends uu{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let n of e){let i=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let o=parseInt(n.slice(3,5),16);isNaN(o)||(i=o)}if(i!==null)r.push(i);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));t.push(o),r=[]}t.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},iG=nG;function oG(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new Uq(e);case"WordPiece":return new jq(e);case"Metaspace":return new qq(e);case"BPEDecoder":return new Vq(e);case"CTC":return new Yq(e);case"Sequence":return new Wq(e);case"Replace":return new Zq(e);case"Fuse":return new eG(e);case"Strip":return new rG(e);case"ByteFallback":return new iG(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var cF=oG,sG=class{constructor(e,t){let r=Hv(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Hv(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=oF(this.tokenizer.normalizer),this.pre_tokenizer=sF(this.tokenizer.pre_tokenizer),this.model=vq(this.tokenizer.model,this.config),this.post_processor=lF(this.tokenizer.post_processor),this.decoder=cF(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(i=>{let o=new tH(i);this.added_tokens.push(o),this.model.tokens_to_ids.set(o.content,o.id),this.model.vocab[o.id]=o.content,o.special&&(this.special_tokens.push(o.content),this.all_special_ids.push(o.id))}),(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new X7(this.added_tokens.map(i=>i.content)),this.added_tokens_map=new Map(this.added_tokens.map(i=>[i.content,i])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:i,token_type_ids:o}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),s=this.model.convert_tokens_to_ids(i),a={ids:s,tokens:i,attention_mask:new Array(s.length).fill(1)};return n&&o&&(a.token_type_ids=o),a}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!uH(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(e);t.skip_special_tokens&&(r=r.filter(i=>!this.special_tokens.includes(i)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(n=n.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=tD(n)),n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;let t=this.added_tokens_splitter.split(e);return t.forEach((r,n)=>{let i=this.added_tokens_map.get(r);i&&(i.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),i.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=cH(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let i=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(i)})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){let n=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(n,i,r):{tokens:Ks(n??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}},aG=sG,uG=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,r={}){this.modelId=e,this.logger=t,this.options=r,this.cacheDir=r.cacheDir||(0,mp.join)((0,c$.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,mp.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,mp.join)(e,"tokenizer.json"),tokenizerConfig:(0,mp.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Ep.existsSync)(e)||(0,Ep.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Ep.existsSync)(e.tokenizerJson)||!(0,Ep.existsSync)(e.tokenizerConfig))return null;let[t,r]=await Promise.all([yp.promises.readFile(e.tokenizerJson,"utf-8"),yp.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(r)}}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 r=new AbortController,n=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[i,o]=await Promise.all([fetch(t.json,{signal:r.signal}),fetch(t.config,{signal:r.signal})]);if(!i.ok)throw new Error(`Failed to fetch tokenizer.json: ${i.statusText}`);let[s,a]=await Promise.all([i.json(),o.ok?o.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([yp.promises.writeFile(e.tokenizerJson,JSON.stringify(s,null,2)),yp.promises.writeFile(e.tokenizerConfig,JSON.stringify(a,null,2))]),{tokenizerJson:s,tokenizerConfig:a}}finally{clearTimeout(n)}}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 aG(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:r,system:n,tools:i}=e;if(Array.isArray(r)){for(let o of r)if(typeof o.content=="string")t.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&s.text?t.push(s.text):s.type==="tool_use"&&s.input?t.push(JSON.stringify(s.input)):s.type==="tool_result"&&t.push(typeof s.content=="string"?s.content:JSON.stringify(s.content))}if(typeof n=="string")t.push(n);else if(Array.isArray(n)){for(let o of n)if(o.type==="text"){if(typeof o.text=="string")t.push(o.text);else if(Array.isArray(o.text))for(let s of o.text)s&&t.push(s)}}if(i)for(let o of i)o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema));return t.join(" ")}},lG=class{type="api";name;config;logger;options;constructor(e,t,r={}){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=r;try{let n=new URL(e.url);this.name=`api-${n.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),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},n=new AbortController,i=setTimeout(()=>n.abort(),this.options.timeout||3e4),o=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(t),signal:n.signal});if(clearTimeout(i),!o.ok)throw new Error(`API tokenizer request failed: ${o.status} ${o.statusText}`);let s=await o.json();return this.extractTokenCount(s)}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"?typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(r=>{t.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?t.push(r.text):Array.isArray(r.text)&&r.text.forEach(n=>{n&&t.push(n)}))}),e.tools&&e.tools.forEach(r=>{r.name&&t.push(r.name),r.description&&t.push(r.description),r.input_schema&&t.push(JSON.stringify(r.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,r=t.split("."),n=e;for(let i of r){if(n==null)throw new Error(`Field path '${t}' not found in response`);n=n[i]}if(typeof n!="number")throw new Error(`Expected number at field path '${t}', got ${typeof n}`);return n}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}`)}}},Yv=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,r={}){this.configService=e,this.logger=t,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new $v("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){let t=this.getCacheKey(e);if(this.tokenizers.has(t))return this.tokenizers.get(t);let r;try{switch(e.type){case"tiktoken":r=new $v(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new uG(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new lG(e,this.logger,{timeout:this.options.timeout});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(t,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${t})`),r}catch(n){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${n.message}`),this.logger?.error(`Error stack: ${n.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t){let r=t?await this.getTokenizer(t):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(n=>n.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){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}},cG=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}},Ql=new cG(100);$c();var Ky=(0,I_.join)(h$.HOME_DIR,"runtime"),Zy=(0,I_.join)(Ky,"quota-store.json"),uh=new Map,zv=!1,dG=null;function hG(e,t){e&&uh.set(e,{...t,provider:e,capturedAt:Date.now()})}function fG(e){let t=uh.get(e);return t?{...t}:void 0}function AG(){return Array.from(uh.values()).map(e=>({...e}))}function pG(){try{if(!(0,Jf.existsSync)(Zy))return;let e=JSON.parse((0,Jf.readFileSync)(Zy,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let r of e)if(r&&r.provider){if(r.capturedAt&&t-r.capturedAt>1440*60*1e3)continue;uh.set(r.provider,r)}}catch{}}function Wv(){try{if(uh.size===0)return;(0,Jf.existsSync)(Ky)||(0,Jf.mkdirSync)(Ky,{recursive:!0}),(0,Jf.writeFileSync)(Zy,JSON.stringify(Array.from(uh.values()),null,2),"utf-8")}catch{}}function gG(){zv||(zv=!0,pG(),dG=setInterval(Wv,6e4),process.on("exit",Wv))}jC();var Wu=(0,d$.get_encoding)("cl100k_base"),dF=(e,t,r)=>{let n=0;return Array.isArray(e)&&e.forEach(i=>{typeof i.content=="string"?n+=Wu.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(o=>{o.type==="text"?n+=Wu.encode(o.text).length:o.type==="tool_use"?n+=Wu.encode(JSON.stringify(o.input)).length:o.type==="tool_result"&&(n+=Wu.encode(typeof o.content=="string"?o.content:JSON.stringify(o.content)).length)})}),typeof t=="string"?n+=Wu.encode(t).length:Array.isArray(t)&&t.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?n+=Wu.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(o=>{n+=Wu.encode(o||"").length}))}),r&&r.forEach(i=>{i.description&&(n+=Wu.encode(i.name+i.description).length),i.input_schema&&(n+=Wu.encode(JSON.stringify(i.input_schema)).length)}),n},hF=async(e,t)=>{if(e.sessionId){let r=await bG(e.sessionId);if(r){let n=(0,Ly.join)(Up.HOME_DIR,r,"config.json"),i=(0,Ly.join)(Up.HOME_DIR,r,`${e.sessionId}.json`);try{let o=JSON.parse(await(0,Oy.readFile)(i,"utf8"));if(o&&o.Router)return o.Router}catch{}try{let o=JSON.parse(await(0,Oy.readFile)(n,"utf8"));if(o&&o.Router)return o.Router}catch{}}}};function qp(e){let t=e||"";return t.includes(",")&&(t=t.split(",").pop()||t),t.includes("/")&&(t=t.split("/").pop()||t),t.includes(":")&&(t=t.split(":")[0]),t.trim().toLowerCase()}function fF(e){let t=qp(e),r=t.includes("[1m]")||t.endsWith("[1m"),n=t.replace(/\[1m\]|\[1m$/g,""),i=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(i)return{family:i[1].toLowerCase(),extended:r};let o=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return o?{family:o[1].toLowerCase(),extended:r}:{family:null,extended:r}}function mG(e,t){if(!t||!e)return null;let r=qp(e);if(t[e])return t[e];if(t[r])return t[r];let{family:n}=fF(e);if(n&&t[n])return t[n];for(let[i,o]of Object.entries(t)){let s=qp(i);if(s&&r.includes(s))return o}return null}function AF(e){return e?(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0):0}function Kv(e){if(!e?.includes(","))return null;let[t,...r]=e.split(","),n=t.trim(),i=r.join(",").trim();return!n||!i?null:{providerName:n,routeModel:i}}function is(e,t,r,n){let i=Kv(e);if(!i)return e;let{providerName:o,routeModel:s}=i,a=t.find(c=>c.name.toLowerCase()===o.toLowerCase());if(a&&a.enabled===!1)return null;if(n&&!r){let c=$C(),d=c.getPromotion(o,s,n,t);if(d){let f=Kv(d);if(f){let h=t.find(g=>g.name.toLowerCase()===f.providerName.toLowerCase()),A=h?.models?.find(g=>String(g).toLowerCase()===f.routeModel.toLowerCase());if(h&&A)return`${h.name},${A}`}c.clear(o,s,n)}}if(!r&&!os().isAvailable(o,s))return null;let u=fG(o);if(u){let c=u.limitDaily!==void 0&&u.usedDailyBalance!==void 0&&u.usedDailyBalance>=u.limitDaily,d=u.totalBalance!==void 0&&u.usedBalance!==void 0&&u.usedBalance>=u.totalBalance;if(c||d)return null}let l=a?.models?.find(c=>String(c).toLowerCase()===s.toLowerCase());return a&&l?`${a.name},${l}`:e}function Ra(e,t,r,n,i){let o=os(),s=[r?.[e],n?.[e]];for(let a of s)if(!(!Array.isArray(a)||a.length===0))for(let u of a){let l=is(u,t);if(l)return l}return null}function EG(e){return e.body.messages?.some(t=>t.role==="user"&&Array.isArray(t.content)&&t.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function yG(e){let t=qp(e);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(r=>r.test(t))}function CG(e,t,r,n,i,o,s){let a=r.longContextThreshold||6e4,u=Math.max(t,AF(i)),l=e.modelFamily;if((o||u>2e5)&&r.extendedContext){let c=is(r.extendedContext,n,!1,"extendedContext");if(c)return e.log.info(`Family: using extended context model (1M+), tokens: ${u}, estimated: ${t}, explicit: ${o}`),{model:c,scenarioType:"extendedContext",isFallback:!1};let d=Ra("extendedContext",n,r.fallback,s,l);if(d)return e.log.info(`Family: using extended context fallback model (1M+), tokens: ${u}, estimated: ${t}, explicit: ${o}`),{model:d,scenarioType:"extendedContext",isFallback:!0};e.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(u>a&&(r.longContext||r.fallback?.longContext?.length||s?.longContext?.length)){let c=r.longContext?is(r.longContext,n,!1,"longContext"):null;if(c)return e.log.info(`Family: using long context model, tokens: ${u}, estimated: ${t}`),{model:c,scenarioType:"longContext",isFallback:!1};let d=Ra("longContext",n,r.fallback,s,l);if(d)return e.log.info(`Family: using long context fallback model, tokens: ${u}, estimated: ${t}`),{model:d,scenarioType:"longContext",isFallback:!0};e.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(e.body.tools)&&e.body.tools.some(c=>c.type?.startsWith("web_search"))&&r.webSearch){let c=is(r.webSearch,n,!1,"webSearch");if(c)return{model:c,scenarioType:"webSearch",isFallback:!1};let d=Ra("webSearch",n,r.fallback,s,l);if(d)return e.log.info("Family: using webSearch fallback model"),{model:d,scenarioType:"webSearch",isFallback:!0};e.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(e.body.thinking&&r.think){let c=is(r.think,n,!1,"think");if(c)return{model:c,scenarioType:"think",isFallback:!1};let d=Ra("think",n,r.fallback,s,l);if(d)return e.log.info("Family: using think fallback model"),{model:d,scenarioType:"think",isFallback:!0};e.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let c=is(r.default,n,!1,"default");if(c)return{model:c,scenarioType:"default",isFallback:!1};let d=Ra("default",n,r.fallback,s,l);if(d)return e.log.info("Family: using default fallback model"),{model:d,scenarioType:"default",isFallback:!0};e.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var DG=async(e,t,r,n)=>{let i=await hF(e,r),o=r.get("providers")||[],s=i||r.get("Router"),a=r.get("fallback");if(e.body.model.includes(",")){let m=is(e.body.model,o,!1,"default");if(m)return{model:m,scenarioType:"default"};e.log.warn(`Explicit model ${e.body.model} unavailable (fail pool), trying fallback`);let E=Ra("default",o,void 0,a);if(E)return e.log.info(`Using fallback for explicit model: ${E}`),{model:E,scenarioType:"default"};e.log.warn(`No fallback available for explicit model ${e.body.model}, continuing through routing logic`)}let{family:u,extended:l}=fF(e.body.model),c=s?.families?.[u||""];if(c&&s?.enableFamilyRouting){e.log.info(`Using model family routing for: ${u}${l?" (1M)":""}`),e.modelFamily=u,e.familyFallback=c.fallback;let m=CG(e,t,c,o,n,l,a);if(m)return{model:m.model,scenarioType:m.scenarioType}}let d=mG(e.body.model,s?.models);if(d){let m=is(d,o,!1,"modelMapping");if(m)return e.log.info(`Using mapped model for ${e.body.model}: ${d}`),{model:m,scenarioType:"modelMapping"};e.log.warn(`Mapped model ${d} unavailable (fail pool), skipping`)}let f=Math.max(t,AF(n)),h=s?.extendedContextThreshold||2e5;if(f>h&&s?.extendedContext){e.log.info(`Using extended context (1M) model due to token count: ${f}, estimated: ${t}, threshold: ${h}`);let m=is(s.extendedContext,o,!1,"extendedContext");if(m)return{model:m,scenarioType:"extendedContext"};e.log.warn(`Extended context model ${s.extendedContext} unavailable (fail pool), trying fallback`);let E=Ra("extendedContext",o,void 0,a);if(E)return{model:E,scenarioType:"extendedContext"}}let A=s?.longContextThreshold||6e4;if(f>A&&s?.longContext){e.log.info(`Using long context model due to token count: ${f}, estimated: ${t}, threshold: ${A}`);let m=is(s.longContext,o,!1,"longContext");if(m)return{model:m,scenarioType:"longContext"};e.log.warn(`Long context model ${s.longContext} unavailable (fail pool), trying fallback`);let E=Ra("longContext",o,void 0,a);if(E)return{model:E,scenarioType:"longContext"}}if(e.body?.system?.length>1&&e.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let m=e.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(m)return e.body.system[1].text=e.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${m[1]}</CCR-SUBAGENT-MODEL>`,""),{model:m[1],scenarioType:"default"}}let g=r.get("Router");if(e.body.model?.includes("claude")&&e.body.model?.includes("haiku")&&g?.background){e.log.info(`Using background model for ${e.body.model}`);let m=is(g.background,o,!1,"background");if(m)return{model:m,scenarioType:"background"};e.log.warn(`Background model ${g.background} unavailable (fail pool), falling through`)}if(Array.isArray(e.body.tools)&&e.body.tools.some(m=>m.type?.startsWith("web_search"))&&s?.webSearch){let m=is(s.webSearch,o,!1,"webSearch");if(m)return{model:m,scenarioType:"webSearch"};e.log.warn(`WebSearch model ${s.webSearch} unavailable (fail pool), trying fallback`);let E=Ra("webSearch",o,void 0,a);if(E)return{model:E,scenarioType:"webSearch"}}if(e.body.thinking&&s?.think){e.log.info(`Using think model for ${e.body.thinking}`);let m=is(s.think,o,!1,"think");if(m)return{model:m,scenarioType:"think"};e.log.warn(`Think model ${s.think} unavailable (fail pool), trying fallback`);let E=Ra("think",o,void 0,a);if(E)return{model:E,scenarioType:"think"}}if(s?.default){let m=is(s.default,o,!1,"default");if(m)return{model:m,scenarioType:"default"};e.log.warn(`Default model ${s.default} unavailable (fail pool), trying fallback`);let E=Ra("default",o,void 0,a);if(E)return{model:E,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Zv=async(e,t,r)=>{let{configService:n,event:i}=r;if(e.originalModel=e.body.model,e.body.metadata?.user_id){let f=e.body.metadata.user_id.split("_session_");f.length>1&&(e.sessionId=f[1])}let o=await hF(e,n)||n.get("Router"),s=n.get("providers")||[],a=Ql.get(e.sessionId),{messages:u,system:l=[],tools:c}=e.body,d=n.get("REWRITE_SYSTEM_PROMPT");if(d&&l.length>1&&l[1]?.text?.includes("<env>")){let f=await(0,Oy.readFile)(d,"utf-8");l[1].text=`${f}<env>${l[1].text.split("<env>").pop()}`}try{let[f,h]=e.body.model.split(","),A=r.tokenizerService?.getTokenizerConfigForModel(f,h),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:u,system:l,tools:c},A)).tokenCount:g=dF(u,l,c),e.tokenCount=g;let m,E=n.get("CUSTOM_ROUTER_PATH");if(E)try{m=await Vr(E)(e,n.getAll(),{event:i})}catch(D){e.log.error(`failed to load custom router: ${D.message}`)}if(m)e.scenarioType="default";else{let D=await DG(e,g,n,a);m=D.model,e.scenarioType=D.scenarioType}if(o?.image&&m!==o.image&&EG(e)&&!yG(m)){let D=is(o.image,s,!1,"image");D?(e.log.info(`Using image model fallback for ${m}`),m=D,e.scenarioType="image"):(e.log.warn(`Image model ${o.image} unavailable (fail pool), keeping ${m}`),e.scenarioType="image")}e.body.model=m}catch(f){e.log.error(`Error in router middleware: ${f.message}`),e.body.model=o?.default,e.scenarioType="default"}},Zu=new Map,Xv=1e3;function Ay(){if(Zu.size<=Xv)return;let e=[...Zu.keys()].slice(0,Zu.size-Xv);for(let t of e)Zu.delete(t)}var bG=async e=>{if(Zu.has(e)){let t=Zu.get(e);return!t||t===""?null:t}try{let t=await(0,WI.opendir)(Up.CLAUDE_PROJECTS_DIR),r=[];for await(let o of t)o.isDirectory()&&r.push(o.name);let n=r.map(async o=>{let s=(0,Ly.join)(Up.CLAUDE_PROJECTS_DIR,o,`${e}.jsonl`);try{return(await(0,WI.stat)(s)).isFile()?o:null}catch{return null}}),i=await Promise.all(n);for(let o of i)if(o)return Zu.set(e,o),Ay(),o;return Zu.set(e,""),Ay(),null}catch(t){return console.error("Error searching for project by session:",t),Zu.set(e,""),Ay(),null}};$c();var Hc=class{async fetchJson(e,t,r,n,i){let o=i||t.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:a}=await Promise.resolve().then(()=>Sn(Po(),1));s.dispatcher=new a(new URL(n).toString())}catch{}try{let a=await fetch(e,s);return a.ok?await a.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}},wG=class extends Hc{async queryQuota(e,t,r){let n=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,r),i=(Array.isArray(n?.balance_infos)?n.balance_infos:[]).find(s=>Pn(s?.total_balance)!==void 0);if(!i)return null;let o=Pn(i.total_balance);return o===void 0?null:{totalBalance:o,currency:typeof i.currency=="string"?i.currency:void 0}}},IG=class extends Hc{async queryQuota(e,t,r){let n=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,r))?.data;if(!n||typeof n!="object")return null;let i={},o=Pn(n.limit),s=Pn(n.limit_remaining),a=Pn(n.usage),u=Pn(n.usage_daily);return o!==void 0&&(i.totalBalance=o),s!==void 0&&(i.remainingBalance=s),a!==void 0&&(i.usedBalance=a),u!==void 0&&(i.usedDailyBalance=u),this.hasQuotaData(i)?i:null}},vG=class extends Hc{async queryQuota(e,t,r){let n=PG(e.baseUrl),i=(await this.fetchJson(n,e,t,r))?.data;if(!i||typeof i!="object")return null;let o={},s=Pn(i.totalBalance),a=Pn(i.balance);return s!==void 0&&(o.totalBalance=s),a!==void 0&&(o.remainingBalance=a),s!==void 0&&a!==void 0&&(o.usedBalance=Math.max(0,s-a)),this.hasQuotaData(o)?o:null}},BG=class extends Hc{async queryQuota(e,t,r){if(!e.apiKey)return null;let n={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:i}=await Promise.resolve().then(()=>Sn(Po(),1));n.dispatcher=new i(new URL(r).toString())}catch{}try{let i=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",n);if(!i.ok)return null;let o=await i.json(),s=Array.isArray(o?.data?.limits)?o.data.limits:[],a=null,u=null,l=null;for(let d of s)d.type==="TOKENS_LIMIT"?d.unit===3?a=d:d.unit===6?u=d:a||(a=d):d.type==="TIME_LIMIT"&&(l=d);let c={};if(a){let d=Pn(a.currentValue),f=Pn(a.usage),h=Pn(a.remaining),A=Pn(a.percentage);d!==void 0?c.usedDailyBalance=d:A!==void 0&&(c.usedDailyBalance=A,c.limitDaily=100),f!==void 0?c.limitDaily=f:d!==void 0&&h!==void 0&&(c.limitDaily=d+h),a.nextResetTime&&(c.resetTime=new Date(a.nextResetTime).toISOString())}if(u){let d=Pn(u.currentValue),f=Pn(u.usage),h=Pn(u.remaining),A=Pn(u.percentage);d!==void 0?c.usedBalance=d:A!==void 0&&(c.usedBalance=A,c.totalBalance=100),f!==void 0?c.totalBalance=f:d!==void 0&&h!==void 0&&(c.totalBalance=d+h),u.nextResetTime&&!c.resetTime&&(c.resetTime=new Date(u.nextResetTime).toISOString())}if(l){if(c.usedDailyBalance===void 0){let d=Pn(l.currentValue);d!==void 0&&(c.usedDailyBalance=d)}if(c.limitDaily===void 0){let d=Pn(l.usage),f=Pn(l.currentValue),h=Pn(l.remaining);d!==void 0?c.limitDaily=d:f!==void 0&&h!==void 0&&(c.limitDaily=f+h)}l.nextResetTime&&!c.resetTime&&(c.resetTime=new Date(l.nextResetTime).toISOString())}return this.hasQuotaData(c)?c:null}catch{return null}}},xG=class extends Hc{async queryQuota(e,t,r){if(!e.quotaToken)return null;let n={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)};if(r)try{let{ProxyAgent:s}=await Promise.resolve().then(()=>Sn(Po(),1));n.dispatcher=new s(new URL(r).toString())}catch{}let i=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"}}}),o=new URLSearchParams({params:i,region:"cn-beijing"}).toString();try{let s=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...n,body:o});if(!s.ok)return null;let a=(await s.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(a)||a.length===0)return null;let u=a[0]?.codingPlanQuotaInfo;if(!u)return null;let l={},c=Pn(u.per5HourUsedQuota),d=Pn(u.per5HourTotalQuota);c!==void 0&&(l.usedDailyBalance=c),d!==void 0&&(l.limitDaily=d);let f=Pn(u.perWeekUsedQuota),h=Pn(u.perWeekTotalQuota);return f!==void 0&&(l.usedBalance=f),h!==void 0&&(l.totalBalance=h),this.hasQuotaData(l)?l:null}catch{return null}}},_G=class extends Hc{async queryQuota(e,t,r){let n=e.quotaToken||e.apiKey;if(!n)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${n.trim()}`},signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:o}=await Promise.resolve().then(()=>Sn(Po(),1));i.dispatcher=new o(new URL(r).toString())}catch{}try{let o=await fetch("https://api.kimi.com/coding/v1/usages",i);if(!o.ok)return null;let s=await o.json(),a={},u=Array.isArray(s?.limits)?s.limits:[];if(u.length>0&&u[0]?.detail){let c=u[0].detail,d=Pn(c.limit),f=Pn(c.remaining),h=c.resetTime;d!==void 0&&f!==void 0&&(a.usedDailyBalance=Math.max(0,d-f),a.limitDaily=d),h&&(a.resetTime=new Date(h).toISOString())}let l=s?.usage;if(l){let c=Pn(l.limit),d=Pn(l.remaining),f=Pn(l.used),h=l.resetTime;c!==void 0&&(a.totalBalance=c,f!==void 0?a.usedBalance=f:d!==void 0&&(a.usedBalance=Math.max(0,c-d),a.remainingBalance=d)),h&&(a.resetTime7d=new Date(h).toISOString(),a.resetTime||(a.resetTime=a.resetTime7d))}return this.hasQuotaData(a)?a:null}catch{return null}}},SG=class extends Hc{async queryQuota(e,t,r){let n=e.quotaToken||e.apiKey;if(!n)return null;let i=nD(e.baseUrl)||"api.minimaxi.com",o=i.endsWith(".minimax.io")||i==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let s=[`https://${o}/v1/token_plan/remains`,`https://${o}/v1/api/openplatform/coding_plan/remains`],a=null;for(let y of s)if(a=await this.fetchJson(y,e,t,r,n.trim()),a)break;if(!a)return null;if(a?.base_resp){let y=a.base_resp.status_code;if(y!==void 0&&y!==0)return null}let u=Array.isArray(a?.model_remains)?a.model_remains:[];if(u.length===0)return null;let l=u[0],c={},d=Pn(l.current_interval_total_count),f=Pn(l.current_interval_usage_count),h=Pn(l.current_interval_remaining_percent),A=Pn(l.end_time);d!==void 0&&f!==void 0&&d>0?(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d):h!==void 0&&(c.limitDaily=100,c.usedDailyBalance=Math.max(0,100-h)),A&&(c.resetTime=new Date(A).toISOString());let g=Pn(l.current_weekly_total_count),m=Pn(l.current_weekly_usage_count),E=Pn(l.current_weekly_remaining_percent),D=Pn(l.weekly_end_time);return g!==void 0&&m!==void 0&&g>0?(c.usedBalance=Math.max(0,g-m),c.remainingBalance=m,c.totalBalance=g):E!==void 0&&(c.totalBalance=100,c.usedBalance=Math.max(0,100-E),c.remainingBalance=E),D&&!c.resetTime&&(c.resetTime=new Date(D).toISOString()),this.hasQuotaData(c)?c:null}catch{return null}}},FG=new wG,kG=new IG,TG=new vG,RG=new BG,QG=new xG,NG=new _G,OG=new SG;function LG(e){let t=nD(e);return t?t==="kimi.com"||t.endsWith(".kimi.com")||t==="moonshot.cn"||t.endsWith(".moonshot.cn")?NG:t==="minimaxi.com"||t.endsWith(".minimaxi.com")||t==="minimax.io"||t.endsWith(".minimax.io")?OG:t==="deepseek.com"||t.endsWith(".deepseek.com")?FG:t==="openrouter.ai"||t.endsWith(".openrouter.ai")?kG:t==="siliconflow.com"||t.endsWith(".siliconflow.com")||t==="siliconflow.cn"||t.endsWith(".siliconflow.cn")?TG:t==="bigmodel.cn"||t.endsWith(".bigmodel.cn")?RG:t==="dashscope.aliyuncs.com"||t.endsWith(".dashscope.aliyuncs.com")?QG:null:null}function PG(e){let t=nD(e);return t?.endsWith(".siliconflow.cn")||t==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function nD(e){try{return new URL(e).hostname.toLowerCase()}catch{return null}}function Pn(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string")return;let t=e.trim().replace(/,/g,"");if(!t)return;let r=Number(t);return Number.isFinite(r)?r:void 0}var MG={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function UG(e){return e===!0||e==="true"||e===1||e==="1"}function $G(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${n}`}function jG(e){try{let t=new URL(e),r=t.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),t.pathname=`${r}/models`,t.toString()}catch{return null}}function HG(e){try{let t=new URL(e).hostname.toLowerCase();return t.includes("moonshot")||t.includes("kimi")}catch{return!1}}async function py(e,t,r){let n=jG(e.baseUrl);if(!n)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let i={method:"GET",headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:a}=await Promise.resolve().then(()=>Sn(Po(),1));i.dispatcher=new a(new URL(r).toString())}catch{}let o=await fetch(n,i);if(o.headers&&eD(e.name,e.baseUrl,o.headers),o.ok)return{success:!0,headers:o.headers};if(o.status===429)return{success:!1,error:`HTTP 429: ${(await o.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:o.headers};if(o.status>=400&&o.status<500)return{success:!0,headers:o.headers};let s=await o.text().catch(()=>"");return{success:!1,error:`HTTP ${o.status}: ${s.slice(0,100)}`,headers:o.headers}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown probe error"}}}async function qG(e,t,r,n){let i=e.wakeupModel||(Array.isArray(e.models)?e.models[0]:void 0);if(!i)return{success:!1,error:"No models configured for provider"};let o=e.baseUrl.includes("anthropic")||i.includes("claude"),s=o?e.baseUrl.includes("/messages")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/v1/messages`:e.baseUrl.includes("/chat/completions")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let a={"Content-Type":"application/json"};o?(a["x-api-key"]=e.apiKey,a["anthropic-version"]="2023-06-01"):a.Authorization=`Bearer ${e.apiKey}`;let u={method:"POST",headers:a,body:JSON.stringify({model:i,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(t)};if(r)try{let{ProxyAgent:d}=await Promise.resolve().then(()=>Sn(Po(),1));u.dispatcher=new d(new URL(r).toString())}catch{}n?.info(`Sending scheduled wake-up call to provider ${e.name} using model ${i}...`);let l=await fetch(s,u);if(l.ok)return{success:!0};let c=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${c.slice(0,200)||"Unknown error"}`}}catch(a){return{success:!1,error:a?.message||a?.toString()||"Unknown wake-up error"}}}async function GG(e,t,r,n,i){let o=e.baseUrl.includes("anthropic")||t.includes("claude"),s=o?e.baseUrl.includes("/messages")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/v1/messages`:e.baseUrl.includes("/chat/completions")?e.baseUrl:`${e.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let a={"Content-Type":"application/json"};o?(a["x-api-key"]=e.apiKey,a["anthropic-version"]="2023-06-01"):a.Authorization=`Bearer ${e.apiKey}`;let u={method:"POST",headers:a,body:JSON.stringify({model:t,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:d}=await Promise.resolve().then(()=>Sn(Po(),1));u.dispatcher=new d(new URL(n).toString())}catch{}i?.debug?.(`Sending independent ping to rate-limited model ${e.name} (${t})...`);let l=await fetch(s,u);if(l.ok)return{success:!0};let c=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${c.slice(0,200)||"Unknown error"}`}}catch(a){return{success:!1,error:a?.message||a?.toString()||"Unknown ping error"}}}var VG=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,t,r,n,i){this.config={...MG,...t},this.getProviders=e,this.getHttpsProxy=r,this.logger=n,this.getConfig=i}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.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.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(o=>o?.name&&o.enabled!==!1&&!this.config.excludeProviders.includes(o.name)),t=this.getHttpsProxy?.(),r=os();if(e.length===0)return;let n=[];for(let o of e){let s=LG(o.baseUrl),a=Array.isArray(o.models)?o.models:[];s&&n.push({provider:o.name,models:a,type:"quota-adapter",promise:s.queryQuota(o,this.config.probeTimeoutMs,t).then(u=>{if(u){hG(o.name,u),this.logger?.debug?.(`Stored quota probe result for ${o.name}`);let l=u.limitDaily!==void 0&&u.usedDailyBalance!==void 0&&u.usedDailyBalance>=u.limitDaily,c=u.totalBalance!==void 0&&u.usedBalance!==void 0&&u.usedBalance>=u.totalBalance;if(l||c){let d=l?`Quota exhausted: 5h limit reached (${u.usedDailyBalance}/${u.limitDaily})`:`Quota exhausted: 7d balance depleted (${u.usedBalance}/${u.totalBalance})`;for(let f of a){if(r.getState(o.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${o.name} (${f}): already rate-limited with active cooldown`);continue}r.forceOpen(o.name,f,d)}this.logger?.warn?.(`${d} for ${o.name}, marked as unhealthy`)}else for(let d of a){let f=r.getState(o.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(r.recover(o.name,d),this.logger?.info?.(`Quota recovered for ${o.name} (${d}), marked as healthy`))}}})}),HG(o.baseUrl)&&n.push({provider:o.name,models:a,type:"rate-limit-headers",promise:py(o,this.config.probeTimeoutMs,t).then(()=>{})})}if(n.length===0)return;this.logger?.debug?.(`Running quota probe with ${n.length} tasks for ${e.length} providers`);let i=await Promise.allSettled(n.map(o=>o.promise));for(let o=0;o<n.length;o++){let s=i[o];if(s.status==="rejected"){let a=n[o];this.logger?.warn?.(`Quota probe failed for ${a.provider} (${a.type}): ${s.reason}`)}}}async runHealthProbe(){let e=os(),t=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!this.config.excludeProviders.includes(i.name)),r=this.getHttpsProxy?.();if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let n=await Promise.allSettled(t.map(i=>py(i,this.config.probeTimeoutMs,r)));for(let i=0;i<t.length;i++){let o=t[i],s=n[i],a=Array.isArray(o.models)?o.models:[];if(s.status==="fulfilled"){let u=s.value;if(u.success){let l=0;for(let c of a){let d=e.getState(o.name,c);if(d&&d.status==="open"){let f=d.lastError?.includes("Quota exhausted"),h=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(f){this.logger?.debug?.(`Skipping health probe recovery for ${o.name} (${c}) because quota is exhausted`);continue}if(h||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${o.name} (${c})`);continue}}e.recordSuccess(o.name,c),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${o.name}`)}else{for(let l of a)e.recordFailure(o.name,l,u.error);this.logger?.warn?.(`Health probe failed for ${o.name}: ${u.error}`)}}else{for(let u of a)e.recordFailure(o.name,u,s.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${o.name}: ${s.reason}`)}}}async runRateLimitProbe(){let e=os(),t=e.getRateLimitedModels();if(t.length===0)return;let r=this.getProviders(),n=this.getHttpsProxy?.(),i=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let o of t){let[s,...a]=o.split(","),u=a.join(",");if(!s||!u)continue;let l=e.getState(s,u);if(!l||!l.rateLimitUntil)continue;if(Date.now()>=l.rateLimitUntil){e.recover(s,u),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${o}`);continue}let c=r.find(d=>d?.name===s&&d.enabled!==!1);if(!c){this.logger?.warn?.(`Provider ${s} not found or disabled for rate-limit probe`);continue}try{let d=await GG(c,u,i,n,this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${o}, recovering model`),e.recover(s,u);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();l.rateLimitUntil&&l.rateLimitUntil>f?l.rateLimitUntil+=120*1e3:l.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${o} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${o} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${o}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&a.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,r=t.getHours(),n=t.getMinutes(),i=$G(t),o=this.getHttpsProxy?.(),s=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let a of e){let u=a.wakeupTime||s,[l,c]=u.split(":"),d=parseInt(l,10),f=parseInt(c,10);if(isNaN(d)||isNaN(f))continue;let h=r>d||r===d&&n>=f,A=(d*60+f)*6e4-(r*60+n)*6e4,g=A>0&&A<=300*1e3;(h||g)&&!this.hasWakeupFiredToday(a.name,i)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${a.name} at ${u}`),qG(a,3e4,o,this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${a.name}`):this.logger?.error?.(`Failed to wake up provider ${a.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${a.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?UG(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 t=this.getProviders().find(o=>o.name===e);if(!t)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(t.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let r=this.getHttpsProxy?.(),n=await py(t,this.config.probeTimeoutMs,r),i=Array.isArray(t.models)?t.models:[];if(n.success)for(let o of i)os().recordSuccess(t.name,o);else for(let o of i)os().recordFailure(t.name,o,n.error);return n.success}},Wf=null;function JG(e,t,r,n,i){return Wf||(Wf=new VG(e,t,r,n,i)),Wf}function YG(e,t,r,n,i){let o=JG(e,t,r,n,i);return o.start(),o}function zG(){Wf&&Wf.stop()}$c();var WG=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 r=this.plugins.get(e),n=this.pluginInstances.get(e);if(!r||!n)throw new Error(`Plugin ${e} not found`);r.enabled&&await t.register(n.register,r.options)}async enablePlugins(e){for(let[t,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(t,e)}catch(n){let i=n instanceof Error?n.message:String(n);e.log?.error(`Failed to enable plugin ${t}: ${i}`)}}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 r=this.plugins.get(e);r&&(r.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Xy=new WG,KG=Ul(Fj(),1),ZG=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let r=this.buffer.split(`
|
|
1349
1349
|
`);this.buffer=r.pop()||"";for(let n of r){let i=this.processLine(n);i&&t.enqueue(i)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},t?(t.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,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}},RW=class extends TransformStream{constructor(){super({transform:(e,t)=>{let r="";e.event&&(r+=`event: ${e.event}
|
|
1350
1350
|
`),e.id&&(r+=`id: ${e.id}
|
|
1351
1351
|
`),e.retry&&(r+=`retry: ${e.retry}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wengine-ai/claude-code-router-next",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.35",
|
|
4
4
|
"description": "CLI for Claude Code Router",
|
|
5
5
|
"bin": {
|
|
6
6
|
"ccr": "dist/cli.js"
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"author": "musistudio",
|
|
15
15
|
"license": "MIT",
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@wengine-ai/llms": "^2.1.
|
|
17
|
+
"@wengine-ai/llms": "^2.1.35",
|
|
18
18
|
"lru-cache": "^11.2.2"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|