@wengine-ai/claude-code-router 2.0.45 → 2.0.47
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 +3 -3
- package/dist/index.html +18 -18
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -579,7 +579,7 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Ie
|
|
|
579
579
|
${this.toMarkdown(N,S+1)}`:`${T}- ${N}`).join(`
|
|
580
580
|
`):typeof y=="object"&&y!==null?Object.entries(y).map(([N,V])=>typeof V=="object"&&V!==null?`${T}${N}:
|
|
581
581
|
${this.toMarkdown(V,S+1)}`:`${T}${N}: ${V}`).join(`
|
|
582
|
-
`):`${T}${y}`}async output(y,S={}){try{let T=this.formatData(y,S);switch(this.config.level||"log"){case"info":console.info(T);break;case"warn":console.warn(T);break;case"error":console.error(T);break;case"debug":console.debug(T);break;case"log":default:console.log(T);break}return!0}catch(T){return console.error("[ConsoleOutputHandler] Output failed:",T),!1}}}}),RA,QA=u(()=>{"use strict";RA=class{type="webhook";config;defaultTimeout=3e4;constructor(y){if(!y.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...y}}buildHeaders(){let y={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(y.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let S=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");y.Authorization=`Basic ${S}`}break;case"custom":this.config.auth.custom&&(y[this.config.auth.custom.header]=this.config.auth.custom.value);break}return y}buildBody(y,S){let{format:T="json",timestamp:N=!0,prefix:V,metadata:H}=S||{},Y={data:y};return N&&(Y.timestamp=new Date().toISOString()),V&&(Y.prefix=V),H&&Object.keys(H).length>0&&(Y.metadata=H),Y}async sendRequest(y,S,T,N,V){let H=new AbortController,Y=setTimeout(()=>H.abort(),V);try{let K=await fetch(y,{method:S,headers:T,body:JSON.stringify(N),signal:H.signal});if(clearTimeout(Y),!K.ok)throw new Error(`HTTP ${K.status}: ${K.statusText}`);return K}catch(K){throw clearTimeout(Y),K}}delay(y){return new Promise(S=>setTimeout(S,y))}async sendWithRetry(y,S,T,N,V,H){let Y=null;for(let K=1;K<=H.maxAttempts;K++)try{return await this.sendRequest(y,S,T,N,V)}catch(ae){if(Y=ae,K===H.maxAttempts)break;let ee=H.backoffMs*Math.pow(2,K-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${K}/${H.maxAttempts}), retrying in ${ee}ms...`,ae.message),await this.delay(ee)}throw Y}async output(y,S={}){let T=S.timeout||this.defaultTimeout;try{let N=this.buildHeaders(),V=this.buildBody(y,S),H=await this.sendWithRetry(this.config.url,this.config.method,N,V,T,this.config.retry);return!0}catch(N){let V=N instanceof Error?N.message:String(N);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${V}`),!1;throw new Error(`Webhook output failed: ${V}`)}}}}),Yu,Os,Ju,tu,Ih=u(()=>{"use strict";Yu=require("fs"),Os=require("path"),Ju=require("os"),tu=class{type="temp-file";config;baseDir;constructor(y={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...y};let S=(0,Ju.tmpdir)();this.baseDir=(0,Os.join)(S,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Yu.existsSync)(this.baseDir)||(0,Yu.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(y){try{let S=y.match(/_session_([a-f0-9-]+)/i);return S?S[1]:null}catch{return null}}getFilePath(y){let S=this.config.prefix||"session",T=this.config.extension?`.${this.config.extension}`:"",N;if(this.config.includeTimestamp){let V=Date.now();N=`${S}-${y}-${V}${T}`}else N=`${S}-${y}${T}`;return(0,Os.join)(this.baseDir,N)}async output(y,S={}){try{let T=S.metadata?.sessionId;if(!T)return!1;let N={...y,timestamp:Date.now(),sessionId:T},V=this.getFilePath(T);return(0,Yu.writeFileSync)(V,JSON.stringify(N,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}}),zu,Ls,ru=u(()=>{"use strict";TA(),QA(),Ih(),zu=class{handlers=new Map;defaultOptions={};registerHandler(y,S){this.handlers.set(y,S)}registerHandlers(y){for(let S of y)if(S.enabled!==!1)try{let T=this.createHandler(S),N=S.type+"_"+Date.now();this.registerHandler(N,T)}catch(T){console.error(`[OutputManager] Failed to register ${S.type} handler:`,T)}}createHandler(y){switch(y.type){case"console":return new kA(y.config);case"webhook":return new RA(y.config);case"temp-file":return new tu(y.config);default:throw new Error(`Unknown output handler type: ${y.type}`)}}unregisterHandler(y){return this.handlers.delete(y)}getHandler(y){return this.handlers.get(y)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(y){this.defaultOptions={...this.defaultOptions,...y}}getDefaultOptions(){return{...this.defaultOptions}}async output(y,S){let T={...this.defaultOptions,...S},N={success:[],failed:[]},V=Array.from(this.handlers.entries()).map(async([H,Y])=>{try{await Y.output(y,T)?N.success.push(H):N.failed.push(H)}catch(K){console.error(`[OutputManager] Handler ${H} failed:`,K),N.failed.push(H)}});return await Promise.all(V),N}async outputTo(y,S,T){let N={...this.defaultOptions,...T},V={success:[],failed:[]},H=y.map(async Y=>{let K=this.handlers.get(Y);if(!K){console.warn(`[OutputManager] Handler ${Y} not found`),V.failed.push(Y);return}try{await K.output(S,N)?V.success.push(Y):V.failed.push(Y)}catch(ae){console.error(`[OutputManager] Handler ${Y} failed:`,ae),V.failed.push(Y)}});return await Promise.all(H),V}async outputToType(y,S,T){let N=Array.from(this.handlers.entries()).filter(([V,H])=>H.type===y).map(([V])=>V);return this.outputTo(N,S,T)}},Ls=new zu}),Bs={};c(Bs,{ConfigService:()=>_h,ProviderHealthStore:()=>NA,ProviderService:()=>Wu,SSEParserTransform:()=>_C,SSESerializerTransform:()=>yR,TokenizerService:()=>Qg,TransformerService:()=>Fg,calculateTokenCount:()=>wC,default:()=>IR,getHealthStore:()=>Jl,pluginManager:()=>mR,rewriteStream:()=>DR,router:()=>Lg,searchProjectBySession:()=>vC,sessionUsageCache:()=>CC,tokenSpeedPlugin:()=>bR}),t.exports=h(Bs);var xh=A(CB(),1),gg=A(bB(),1),qo=require("fs"),vh=require("path"),mg=wB(),Yl=A(C(),1),_h=class{config={};options;constructor(y={jsonPath:"./config.json"}){this.options={envPath:y.envPath||".env",jsonPath:y.jsonPath,useEnvFile:!1,useJsonFile:y.useJsonFile!==!1,useEnvironmentVariables:y.useEnvironmentVariables!==!1,...y},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 y=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,vh.join)(process.cwd(),this.options.jsonPath);if((0,qo.existsSync)(y))try{let S=(0,qo.readFileSync)(y,"utf-8"),T=Yl.default.parse(S);this.config={...this.config,...T},console.log(`Loaded JSON config from: ${y}`)}catch(S){console.warn(`Failed to load JSON config from ${y}:`,S)}else console.warn(`JSON config file not found: ${y}`)}loadEnvConfig(){let y=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,vh.join)(process.cwd(),this.options.envPath);if((0,qo.existsSync)(y))try{let S=(0,mg.config)({path:y});S.parsed&&(this.config={...this.config,...this.parseEnvConfig(S.parsed)})}catch(S){console.warn(`Failed to load .env config from ${y}:`,S)}}loadEnvironmentVariables(){let y=this.parseEnvConfig(process.env);this.config={...this.config,...y}}parseEnvConfig(y){let S={};return Object.assign(S,y),S}isAbsolutePath(y){return y.startsWith("/")||y.includes(":")}get(y,S){let T=this.config[y];return T!==void 0?T:S}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(y){return this.config[y]!==void 0}set(y,S){this.config[y]=S}reload(){this.config={},this.loadConfig()}getConfigSummary(){let y=[];return this.options.initialConfig&&y.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&y.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&y.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&y.push("Environment Variables"),`Config sources: ${y.join(", ")}`}};function Is(y,S=500,T="internal_error",N="api_error"){let V=new Error(y);return V.statusCode=S,V.code=T,V.type=N,V}async function Eg(y,S,T){S.log.error(y);let N=y.statusCode||500,V={error:{message:y.message+y.stack||"Internal Server Error",type:y.type||"api_error",code:y.code||"internal_error"}};return T.code(N).send(V)}var yg=zB();function Dg(y,S,T,N,V){let H=new Headers({"Content-Type":"application/json"});T.headers&&Object.entries(T.headers).forEach(([ee,ue])=>{ue&&H.set(ee,ue)});let Y,K=AbortSignal.timeout(T.TIMEOUT??60*1e3*60);if(T.signal){let ee=new AbortController,ue=()=>ee.abort();T.signal.addEventListener("abort",ue),K.addEventListener("abort",ue),Y=ee.signal}else Y=K;let ae={method:"POST",headers:H,body:JSON.stringify(S),signal:Y};return T.httpsProxy&&(ae.dispatcher=new yg.ProxyAgent(new URL(T.httpsProxy).toString())),V?.debug({reqId:N.req.id,request:ae,headers:Object.fromEntries(H.entries()),requestUrl:typeof y=="string"?y:y.toString(),useProxy:T.httpsProxy},"final request"),fetch(typeof y=="string"?y:y.toString(),ae)}var Cg="2.0.41",bg={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},NA=class{states=new Map;config;probeTimer;constructor(y){this.config={...bg,...y}}getKey(y,S){return`${y},${S}`}recordSuccess(y,S){if(!this.config.enabled)return;let T=this.getKey(y,S),N=this.states.get(T);N&&(N.successCount++,N.status==="half-open"?N.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(T):N.status==="open"&&(N.status="half-open",N.successCount=1,N.failureCount=0))}isRateLimitError(y){if(!y)return!1;let S=y.toLowerCase();return S.includes("429")||S.includes("rate_limit")||S.includes("ratelimit")||S.includes("rate limit")||S.includes("overloaded")||S.includes("quota")}recordFailure(y,S,T){if(!this.config.enabled)return;let N=this.getKey(y,S),V=this.states.get(N);V||(V={provider:y,model:S,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(N,V)),V.failureCount++,V.lastFailureTime=Date.now(),V.lastError=T;let H=this.isRateLimitError(T)?this.config.rateLimitThreshold:this.config.failureThreshold;V.status==="half-open"?(V.status="open",V.successCount=0,V.lastProbeTime=0):V.status==="closed"&&V.failureCount>=H&&(V.status="open",V.lastProbeTime=0)}getState(y,S){return this.states.get(this.getKey(y,S))}isAvailable(y,S){if(!this.config.enabled)return!0;let T=this.getState(y,S);return T?T.status!=="open":!0}getPriority(y,S){if(!this.config.enabled)return 0;let T=this.getState(y,S);if(!T)return 0;switch(T.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let y=[];for(let[S,T]of this.states)T.status==="open"&&y.push(S);return y}getHalfOpenModels(){let y=[];for(let[S,T]of this.states)T.status==="half-open"&&y.push(S);return y}needsProbe(y){return Date.now()-y.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(y,S){let T=this.getKey(y,S),N=this.states.get(T);N&&N.status==="open"&&(N.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Sh=null;function Jl(y){return Sh||(Sh=new NA(y)),Sh}async function wg(y,S,T,N){let V=y.body,H=y.provider,Y=T.providerService.getProvider(H);if(!Y)throw Is(`Provider '${H}' not found`,404,"provider_not_found");try{let{requestBody:K,config:ae,bypass:ee}=await OA(V,Y,N,y.headers,{req:y}),ue=await PA(K,ae,Y,T,ee,N,{req:y}),ge=await MA(K,ue,Y,N,ee,{req:y});return vi(ge,S,V)}catch(K){let ae=await Bg(y,S,T,N,K);if(ae)return ae;throw K}}async function Bg(y,S,T,N,V){let H=y.scenarioType||"default",Y=y.familyFallback,K=T.configService.get("fallback"),ae=Jl(),ee=[];if(Y?.[H]?ee=Y[H]:K?.[H]&&(ee=K[H]),!Array.isArray(ee)||ee.length===0)return null;let ue=y.provider||"",ge=y.body.model||"";ae.recordFailure(ue,ge,V?.message),y.log.warn(`Request failed for ${y.scenarioType}, trying ${ee.length} fallback models`);let Ee=ee.sort((se,ce)=>{let[ye,De]=se.split(","),[we,ve]=ce.split(",");return ae.getPriority(ye,De)-ae.getPriority(we,ve)});for(let se of Ee)try{let[ce,...ye]=se.split(","),De=ye.join(",");if(!ae.isAvailable(ce,De)){y.log.warn(`Fallback model ${se} unavailable (fail pool), skipping`);continue}y.log.info(`Trying fallback model: ${se}`);let we={...y.body};we.model=De;let ve={...y,provider:ce,body:we},Ie=T.providerService.getProvider(ce);if(!Ie){y.log.warn(`Fallback provider '${ce}' not found, skipping`);continue}let{requestBody:pe,config:Te,bypass:Pe}=await OA(we,Ie,N,y.headers,{req:ve}),Xe=await PA(pe,Te,Ie,T,Pe,N,{req:ve}),At=await MA(pe,Xe,Ie,N,Pe,{req:ve});return y.log.info(`Fallback model ${se} succeeded`),ae.recordSuccess(ce,De),vi(At,S,we)}catch(ce){let[ye,...De]=se.split(","),we=De.join(",");ae.recordFailure(ye,we,ce.message),y.log.warn(`Fallback model ${se} failed: ${ce.message}`);continue}return y.log.error(`All fallback models failed for ${H}`),null}async function OA(y,S,T,N,V){let H=JSON.parse(JSON.stringify(y)),Y={},K=!1;if(K=LA(S,T,y),K&&(N instanceof Headers?N.delete("content-length"):delete N["content-length"],Y.headers=N),!K&&typeof T.transformRequestOut=="function"){let ae=await T.transformRequestOut(H);ae.body?(H=ae.body,Y=ae.config||{}):H=ae}if(!K&&S.transformer?.use?.length)for(let ae of S.transformer.use){if(!ae||typeof ae.transformRequestIn!="function")continue;let ee=await ae.transformRequestIn(H,S,V);ee.body?(H=ee.body,Y={...Y,...ee.config}):H=ee}if(!K&&S.transformer?.[y.model]?.use?.length)for(let ae of S.transformer[y.model].use)!ae||typeof ae.transformRequestIn!="function"||(H=await ae.transformRequestIn(H,S,V));return{requestBody:H,config:Y,bypass:K}}function LA(y,S,T){return y.transformer?.use?.length===1&&y.transformer.use[0].name===S.name&&(!y.transformer?.[T.model]?.use.length||y.transformer?.[T.model]?.use.length===1&&y.transformer?.[T.model]?.use[0].name===S.name)}async function PA(y,S,T,N,V,H,Y){let K=S.url||new URL(T.baseUrl);if(!S.TIMEOUT){let ue=N.configService.get("API_TIMEOUT_MS");ue&&(S.TIMEOUT=typeof ue=="string"?parseInt(ue,10):ue)}if(V&&typeof H.auth=="function"){let ue=await H.auth(y,T);if(ue.body){y=ue.body;let ge=S.headers||{};ue.config?.headers&&(ge={...ge,...ue.config.headers},delete ge.host,delete ue.config.headers),S={...S,...ue.config,headers:ge}}else y=ue}let ae={Authorization:`Bearer ${T.apiKey}`,...S?.headers||{}};for(let ue in ae)(ae[ue]==="undefined"||["authorization","Authorization"].includes(ue)&&ae[ue]?.includes("undefined"))&&delete ae[ue];let ee=await Dg(K,y,{httpsProxy:N.configService.getHttpsProxy(),...S,headers:JSON.parse(JSON.stringify(ae))},Y,N.log);if(!ee.ok){let ue=await ee.text();throw N.log.error(`[provider_response_error] Error from provider(${T.name},${y.model}: ${ee.status}): ${ue}`),Is(`Error from provider(${T.name},${y.model}: ${ee.status}): ${ue}`,ee.status,"provider_response_error")}return ee}async function MA(y,S,T,N,V,H){let Y=S;if(!V&&T.transformer?.use?.length)for(let K of Array.from(T.transformer.use).reverse())!K||typeof K.transformResponseOut!="function"||(Y=await K.transformResponseOut(Y,H));if(!V&&T.transformer?.[y.model]?.use?.length)for(let K of Array.from(T.transformer[y.model].use).reverse())!K||typeof K.transformResponseOut!="function"||(Y=await K.transformResponseOut(Y,H));return!V&&N.transformResponseIn&&(Y=await N.transformResponseIn(Y,H)),Y}function vi(y,S,T){return y.ok||S.code(y.status),T.stream===!0?(S.header("Content-Type","text/event-stream"),S.header("Cache-Control","no-cache"),S.header("Connection","keep-alive"),S.send(y.body)):y.json()}var nu=async y=>{y.get("/",async()=>({message:"LLMs API",version:Cg})),y.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),y.get("/providers/health",async()=>({states:Jl().getAllStates().map(T=>({provider:T.provider,model:T.model,status:T.status,failureCount:T.failureCount,successCount:T.successCount,lastFailureTime:T.lastFailureTime,lastError:T.lastError})),timestamp:new Date().toISOString()}));let S=y.transformerService.getTransformersWithEndpoint();for(let{transformer:T}of S)T.endPoint&&y.post(T.endPoint,async(N,V)=>wg(N,V,y,T));y.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(T,N)=>{let{name:V,baseUrl:H,apiKey:Y,models:K}=T.body;if(!V?.trim())throw Is("Provider name is required",400,"invalid_request");if(!H||!UA(H))throw Is("Valid base URL is required",400,"invalid_request");if(!Y?.trim())throw Is("API key is required",400,"invalid_request");if(!K||!Array.isArray(K)||K.length===0)throw Is("At least one model is required",400,"invalid_request");if(y.providerService.getProvider(T.body.name))throw Is(`Provider with name '${T.body.name}' already exists`,400,"provider_exists");return y.providerService.registerProvider(T.body)}),y.get("/providers",async()=>y.providerService.getProviders()),y.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async T=>{let N=y.providerService.getProvider(T.params.id);if(!N)throw Is("Provider not found",404,"provider_not_found");return N}),y.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(T,N)=>{let V=y.providerService.updateProvider(T.params.id,T.body);if(!V)throw Is("Provider not found",404,"provider_not_found");return V}),y.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async T=>{if(!y.providerService.deleteProvider(T.params.id))throw Is("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),y.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(T,N)=>{if(!y.providerService.toggleProvider(T.params.id,T.body.enabled))throw Is("Provider not found",404,"provider_not_found");return{message:`Provider ${T.body.enabled?"enabled":"disabled"} successfully`}})};function UA(y){try{return new URL(y),!0}catch{return!1}}var Wu=class{constructor(y,S,T){this.configService=y,this.transformerService=S,this.logger=T,this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let y=this.configService.get("providers");if(y&&Array.isArray(y)){this.initializeFromProvidersArray(y);return}}initializeFromProvidersArray(y){y.forEach(S=>{try{if(!S.name||!S.api_base_url||!S.api_key)return;let T={};S.transformer&&Object.keys(S.transformer).forEach(N=>{N==="use"?Array.isArray(S.transformer.use)&&(T.use=S.transformer.use.map(V=>{if(Array.isArray(V)&&typeof V[0]=="string"){let H=this.transformerService.getTransformer(V[0]);if(H)return new H(V[1])}if(typeof V=="string"){let H=this.transformerService.getTransformer(V);return typeof H=="function"?new H:H}}).filter(V=>typeof V<"u")):Array.isArray(S.transformer[N]?.use)&&(T[N]={use:S.transformer[N].use.map(V=>{if(Array.isArray(V)&&typeof V[0]=="string"){let H=this.transformerService.getTransformer(V[0]);if(H)return new H(V[1])}if(typeof V=="string"){let H=this.transformerService.getTransformer(V);return typeof H=="function"?new H:H}}).filter(V=>typeof V<"u")})}),this.registerProvider({name:S.name,baseUrl:S.api_base_url,apiKey:S.api_key,models:S.models||[],transformer:S.transformer?T:void 0}),this.logger.info(`${S.name} provider registered`)}catch(T){this.logger.error(`${S.name} provider registered error: ${T}`)}})}registerProvider(y){let S={...y};return this.providers.set(S.name,S),y.models.forEach(T=>{let N=`${S.name},${T}`,V={provider:S.name,model:T,fullModel:N};this.modelRoutes.set(N,V),this.modelRoutes.has(T)||this.modelRoutes.set(T,V)}),S}getProviders(){return Array.from(this.providers.values())}getProvider(y){return this.providers.get(y)}updateProvider(y,S){let T=this.providers.get(y);if(!T)return null;let N={...T,...S,updatedAt:new Date};return this.providers.set(y,N),S.models&&(T.models.forEach(V=>{let H=`${T.name},${V}`;this.modelRoutes.delete(H),this.modelRoutes.delete(V)}),S.models.forEach(V=>{let H=`${T.name},${V}`,Y={provider:T.name,model:V,fullModel:H};this.modelRoutes.set(H,Y),this.modelRoutes.has(V)||this.modelRoutes.set(V,Y)})),N}deleteProvider(y){let S=this.providers.get(y);return S?(S.models.forEach(T=>{let N=`${S.name},${T}`;this.modelRoutes.delete(N),this.modelRoutes.delete(T)}),this.providers.delete(y),!0):!1}toggleProvider(y,S){return!!this.providers.get(y)}resolveModelRoute(y){let S=this.modelRoutes.get(y);if(!S)return null;let T=this.providers.get(S.provider);return T?{provider:T,originalModel:y,targetModel:S.model}:null}getAvailableModelNames(){let y=[];return this.providers.forEach(S=>{S.models.forEach(T=>{y.push(T),y.push(`${S.name},${T}`)})}),y}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(y){return y?Array.isArray(y)?y.reduce((S,T)=>{if(Array.isArray(T)){let[N,V={}]=T;S[N]=V}else S[T]={};return S},{}):y:{}}async getAvailableModels(){let y=[];return this.providers.forEach(S=>{S.models.forEach(T=>{y.push({id:T,object:"model",owned_by:S.name,provider:S.name}),y.push({id:`${S.name},${T}`,object:"model",owned_by:S.name,provider:S.name})})}),{object:"list",data:y}}},Wn=[];for(let y=0;y<256;++y)Wn.push((y+256).toString(16).slice(1));function Go(y,S=0){return(Wn[y[S+0]]+Wn[y[S+1]]+Wn[y[S+2]]+Wn[y[S+3]]+"-"+Wn[y[S+4]]+Wn[y[S+5]]+"-"+Wn[y[S+6]]+Wn[y[S+7]]+"-"+Wn[y[S+8]]+Wn[y[S+9]]+"-"+Wn[y[S+10]]+Wn[y[S+11]]+Wn[y[S+12]]+Wn[y[S+13]]+Wn[y[S+14]]+Wn[y[S+15]]).toLowerCase()}var Ps=require("crypto"),Vo=new Uint8Array(256),Ku=Vo.length;function Da(){return Ku>Vo.length-16&&((0,Ps.randomFillSync)(Vo),Ku=0),Vo.slice(Ku,Ku+=16)}var jA=require("crypto"),Fh={randomUUID:jA.randomUUID};function zl(y,S,T){if(Fh.randomUUID&&!S&&!y)return Fh.randomUUID();y=y||{};let N=y.random??y.rng?.()??Da();if(N.length<16)throw new Error("Random bytes length must be >= 16");if(N[6]=N[6]&15|64,N[8]=N[8]&63|128,S){if(T=T||0,T<0||T+16>S.length)throw new RangeError(`UUID byte range ${T}:${T+15} is out of buffer bounds`);for(let V=0;V<16;++V)S[T+V]=N[V];return S}return Go(N)}var iu=zl,$A=y=>y<=0?"none":y<=1024?"low":y<=8192?"medium":"high",HA=(y,S)=>(y.includes("base64")&&(y=y.split("base64").pop(),y.startsWith(",")&&(y=y.slice(1))),`data:${S};base64,${y}`),Wl=class{constructor(y){this.options=y,this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(y,S){let T={};return this.useBearer?(T.authorization=`Bearer ${S.apiKey}`,T["x-api-key"]=void 0):(T["x-api-key"]=S.apiKey,T.authorization=void 0),{body:y,config:{headers:T}}}async transformRequestOut(y){let S=[];if(y.system){if(typeof y.system=="string")S.push({role:"system",content:y.system});else if(Array.isArray(y.system)&&y.system.length){let N=y.system.filter(V=>V.type==="text"&&V.text).map(V=>({type:"text",text:V.text,cache_control:V.cache_control}));S.push({role:"system",content:N})}}JSON.parse(JSON.stringify(y.messages||[]))?.forEach(N=>{if(N.role==="user"||N.role==="assistant"){if(typeof N.content=="string"){S.push({role:N.role,content:N.content});return}if(Array.isArray(N.content)){if(N.role==="user"){let V=N.content.filter(Y=>Y.type==="tool_result"&&Y.tool_use_id);V.length&&V.forEach(Y=>{let K={role:"tool",content:typeof Y.content=="string"?Y.content:JSON.stringify(Y.content),tool_call_id:Y.tool_use_id,cache_control:Y.cache_control};S.push(K)});let H=N.content.filter(Y=>Y.type==="text"&&Y.text||Y.type==="image"&&Y.source);H.length&&S.push({role:"user",content:H.map(Y=>Y?.type==="image"?{type:"image_url",image_url:{url:Y.source?.type==="base64"?HA(Y.source.data,Y.source.media_type):Y.source.url},media_type:Y.source.media_type}:Y)})}else if(N.role==="assistant"){let V={role:"assistant",content:""},H=N.content.filter(ae=>ae.type==="text"&&ae.text);H.length&&(V.content=H.map(ae=>ae.text).join(`
|
|
582
|
+
`):`${T}${y}`}async output(y,S={}){try{let T=this.formatData(y,S);switch(this.config.level||"log"){case"info":console.info(T);break;case"warn":console.warn(T);break;case"error":console.error(T);break;case"debug":console.debug(T);break;case"log":default:console.log(T);break}return!0}catch(T){return console.error("[ConsoleOutputHandler] Output failed:",T),!1}}}}),RA,QA=u(()=>{"use strict";RA=class{type="webhook";config;defaultTimeout=3e4;constructor(y){if(!y.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...y}}buildHeaders(){let y={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(y.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let S=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");y.Authorization=`Basic ${S}`}break;case"custom":this.config.auth.custom&&(y[this.config.auth.custom.header]=this.config.auth.custom.value);break}return y}buildBody(y,S){let{format:T="json",timestamp:N=!0,prefix:V,metadata:H}=S||{},Y={data:y};return N&&(Y.timestamp=new Date().toISOString()),V&&(Y.prefix=V),H&&Object.keys(H).length>0&&(Y.metadata=H),Y}async sendRequest(y,S,T,N,V){let H=new AbortController,Y=setTimeout(()=>H.abort(),V);try{let K=await fetch(y,{method:S,headers:T,body:JSON.stringify(N),signal:H.signal});if(clearTimeout(Y),!K.ok)throw new Error(`HTTP ${K.status}: ${K.statusText}`);return K}catch(K){throw clearTimeout(Y),K}}delay(y){return new Promise(S=>setTimeout(S,y))}async sendWithRetry(y,S,T,N,V,H){let Y=null;for(let K=1;K<=H.maxAttempts;K++)try{return await this.sendRequest(y,S,T,N,V)}catch(ae){if(Y=ae,K===H.maxAttempts)break;let ee=H.backoffMs*Math.pow(2,K-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${K}/${H.maxAttempts}), retrying in ${ee}ms...`,ae.message),await this.delay(ee)}throw Y}async output(y,S={}){let T=S.timeout||this.defaultTimeout;try{let N=this.buildHeaders(),V=this.buildBody(y,S),H=await this.sendWithRetry(this.config.url,this.config.method,N,V,T,this.config.retry);return!0}catch(N){let V=N instanceof Error?N.message:String(N);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${V}`),!1;throw new Error(`Webhook output failed: ${V}`)}}}}),Yu,Os,Ju,tu,Ih=u(()=>{"use strict";Yu=require("fs"),Os=require("path"),Ju=require("os"),tu=class{type="temp-file";config;baseDir;constructor(y={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...y};let S=(0,Ju.tmpdir)();this.baseDir=(0,Os.join)(S,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Yu.existsSync)(this.baseDir)||(0,Yu.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(y){try{let S=y.match(/_session_([a-f0-9-]+)/i);return S?S[1]:null}catch{return null}}getFilePath(y){let S=this.config.prefix||"session",T=this.config.extension?`.${this.config.extension}`:"",N;if(this.config.includeTimestamp){let V=Date.now();N=`${S}-${y}-${V}${T}`}else N=`${S}-${y}${T}`;return(0,Os.join)(this.baseDir,N)}async output(y,S={}){try{let T=S.metadata?.sessionId;if(!T)return!1;let N={...y,timestamp:Date.now(),sessionId:T},V=this.getFilePath(T);return(0,Yu.writeFileSync)(V,JSON.stringify(N,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}}),zu,Ls,ru=u(()=>{"use strict";TA(),QA(),Ih(),zu=class{handlers=new Map;defaultOptions={};registerHandler(y,S){this.handlers.set(y,S)}registerHandlers(y){for(let S of y)if(S.enabled!==!1)try{let T=this.createHandler(S),N=S.type+"_"+Date.now();this.registerHandler(N,T)}catch(T){console.error(`[OutputManager] Failed to register ${S.type} handler:`,T)}}createHandler(y){switch(y.type){case"console":return new kA(y.config);case"webhook":return new RA(y.config);case"temp-file":return new tu(y.config);default:throw new Error(`Unknown output handler type: ${y.type}`)}}unregisterHandler(y){return this.handlers.delete(y)}getHandler(y){return this.handlers.get(y)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(y){this.defaultOptions={...this.defaultOptions,...y}}getDefaultOptions(){return{...this.defaultOptions}}async output(y,S){let T={...this.defaultOptions,...S},N={success:[],failed:[]},V=Array.from(this.handlers.entries()).map(async([H,Y])=>{try{await Y.output(y,T)?N.success.push(H):N.failed.push(H)}catch(K){console.error(`[OutputManager] Handler ${H} failed:`,K),N.failed.push(H)}});return await Promise.all(V),N}async outputTo(y,S,T){let N={...this.defaultOptions,...T},V={success:[],failed:[]},H=y.map(async Y=>{let K=this.handlers.get(Y);if(!K){console.warn(`[OutputManager] Handler ${Y} not found`),V.failed.push(Y);return}try{await K.output(S,N)?V.success.push(Y):V.failed.push(Y)}catch(ae){console.error(`[OutputManager] Handler ${Y} failed:`,ae),V.failed.push(Y)}});return await Promise.all(H),V}async outputToType(y,S,T){let N=Array.from(this.handlers.entries()).filter(([V,H])=>H.type===y).map(([V])=>V);return this.outputTo(N,S,T)}},Ls=new zu}),Bs={};c(Bs,{ConfigService:()=>_h,ProviderHealthStore:()=>NA,ProviderService:()=>Wu,SSEParserTransform:()=>_C,SSESerializerTransform:()=>yR,TokenizerService:()=>Qg,TransformerService:()=>Fg,calculateTokenCount:()=>wC,default:()=>IR,getHealthStore:()=>Jl,pluginManager:()=>mR,rewriteStream:()=>DR,router:()=>Lg,searchProjectBySession:()=>vC,sessionUsageCache:()=>CC,tokenSpeedPlugin:()=>bR}),t.exports=h(Bs);var xh=A(CB(),1),gg=A(bB(),1),qo=require("fs"),vh=require("path"),mg=wB(),Yl=A(C(),1),_h=class{config={};options;constructor(y={jsonPath:"./config.json"}){this.options={envPath:y.envPath||".env",jsonPath:y.jsonPath,useEnvFile:!1,useJsonFile:y.useJsonFile!==!1,useEnvironmentVariables:y.useEnvironmentVariables!==!1,...y},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 y=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,vh.join)(process.cwd(),this.options.jsonPath);if((0,qo.existsSync)(y))try{let S=(0,qo.readFileSync)(y,"utf-8"),T=Yl.default.parse(S);this.config={...this.config,...T},console.log(`Loaded JSON config from: ${y}`)}catch(S){console.warn(`Failed to load JSON config from ${y}:`,S)}else console.warn(`JSON config file not found: ${y}`)}loadEnvConfig(){let y=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,vh.join)(process.cwd(),this.options.envPath);if((0,qo.existsSync)(y))try{let S=(0,mg.config)({path:y});S.parsed&&(this.config={...this.config,...this.parseEnvConfig(S.parsed)})}catch(S){console.warn(`Failed to load .env config from ${y}:`,S)}}loadEnvironmentVariables(){let y=this.parseEnvConfig(process.env);this.config={...this.config,...y}}parseEnvConfig(y){let S={};return Object.assign(S,y),S}isAbsolutePath(y){return y.startsWith("/")||y.includes(":")}get(y,S){let T=this.config[y];return T!==void 0?T:S}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(y){return this.config[y]!==void 0}set(y,S){this.config[y]=S}reload(){this.config={},this.loadConfig()}getConfigSummary(){let y=[];return this.options.initialConfig&&y.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&y.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&y.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&y.push("Environment Variables"),`Config sources: ${y.join(", ")}`}};function Is(y,S=500,T="internal_error",N="api_error"){let V=new Error(y);return V.statusCode=S,V.code=T,V.type=N,V}async function Eg(y,S,T){S.log.error(y);let N=y.statusCode||500,V={error:{message:y.message+y.stack||"Internal Server Error",type:y.type||"api_error",code:y.code||"internal_error"}};return T.code(N).send(V)}var yg=zB();function Dg(y,S,T,N,V){let H=new Headers({"Content-Type":"application/json"});T.headers&&Object.entries(T.headers).forEach(([ee,ue])=>{ue&&H.set(ee,ue)});let Y,K=AbortSignal.timeout(T.TIMEOUT??60*1e3*60);if(T.signal){let ee=new AbortController,ue=()=>ee.abort();T.signal.addEventListener("abort",ue),K.addEventListener("abort",ue),Y=ee.signal}else Y=K;let ae={method:"POST",headers:H,body:JSON.stringify(S),signal:Y};return T.httpsProxy&&(ae.dispatcher=new yg.ProxyAgent(new URL(T.httpsProxy).toString())),V?.debug({reqId:N.req.id,request:ae,headers:Object.fromEntries(H.entries()),requestUrl:typeof y=="string"?y:y.toString(),useProxy:T.httpsProxy},"final request"),fetch(typeof y=="string"?y:y.toString(),ae)}var Cg="2.0.42",bg={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},NA=class{states=new Map;config;probeTimer;constructor(y){this.config={...bg,...y}}getKey(y,S){return`${y},${S}`}recordSuccess(y,S){if(!this.config.enabled)return;let T=this.getKey(y,S),N=this.states.get(T);N&&(N.successCount++,N.status==="half-open"?N.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(T):N.status==="open"&&(N.status="half-open",N.successCount=1,N.failureCount=0))}isRateLimitError(y){if(!y)return!1;let S=y.toLowerCase();return S.includes("429")||S.includes("rate_limit")||S.includes("ratelimit")||S.includes("rate limit")||S.includes("overloaded")||S.includes("quota")}recordFailure(y,S,T){if(!this.config.enabled)return;let N=this.getKey(y,S),V=this.states.get(N);V||(V={provider:y,model:S,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(N,V)),V.failureCount++,V.lastFailureTime=Date.now(),V.lastError=T;let H=this.isRateLimitError(T)?this.config.rateLimitThreshold:this.config.failureThreshold;V.status==="half-open"?(V.status="open",V.successCount=0,V.lastProbeTime=0):V.status==="closed"&&V.failureCount>=H&&(V.status="open",V.lastProbeTime=0)}getState(y,S){return this.states.get(this.getKey(y,S))}isAvailable(y,S){if(!this.config.enabled)return!0;let T=this.getState(y,S);return T?T.status!=="open":!0}getPriority(y,S){if(!this.config.enabled)return 0;let T=this.getState(y,S);if(!T)return 0;switch(T.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let y=[];for(let[S,T]of this.states)T.status==="open"&&y.push(S);return y}getHalfOpenModels(){let y=[];for(let[S,T]of this.states)T.status==="half-open"&&y.push(S);return y}needsProbe(y){return Date.now()-y.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(y,S){let T=this.getKey(y,S),N=this.states.get(T);N&&N.status==="open"&&(N.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Sh=null;function Jl(y){return Sh||(Sh=new NA(y)),Sh}async function wg(y,S,T,N){let V=y.body,H=y.provider,Y=T.providerService.getProvider(H);if(!Y)throw Is(`Provider '${H}' not found`,404,"provider_not_found");try{let{requestBody:K,config:ae,bypass:ee}=await OA(V,Y,N,y.headers,{req:y}),ue=await PA(K,ae,Y,T,ee,N,{req:y}),ge=await MA(K,ue,Y,N,ee,{req:y});return vi(ge,S,V)}catch(K){let ae=await Bg(y,S,T,N,K);if(ae)return ae;throw K}}async function Bg(y,S,T,N,V){let H=y.scenarioType||"default",Y=y.familyFallback,K=T.configService.get("fallback"),ae=Jl(),ee=[];if(Y?.[H]?ee=Y[H]:K?.[H]&&(ee=K[H]),!Array.isArray(ee)||ee.length===0)return null;let ue=y.provider||"",ge=y.body.model||"";ae.recordFailure(ue,ge,V?.message),y.log.warn(`Request failed for ${y.scenarioType}, trying ${ee.length} fallback models`);let Ee=ee.sort((se,ce)=>{let[ye,De]=se.split(","),[we,ve]=ce.split(",");return ae.getPriority(ye,De)-ae.getPriority(we,ve)});for(let se of Ee)try{let[ce,...ye]=se.split(","),De=ye.join(",");if(!ae.isAvailable(ce,De)){y.log.warn(`Fallback model ${se} unavailable (fail pool), skipping`);continue}y.log.info(`Trying fallback model: ${se}`);let we={...y.body};we.model=De;let ve={...y,provider:ce,body:we},Ie=T.providerService.getProvider(ce);if(!Ie){y.log.warn(`Fallback provider '${ce}' not found, skipping`);continue}let{requestBody:pe,config:Te,bypass:Pe}=await OA(we,Ie,N,y.headers,{req:ve}),Xe=await PA(pe,Te,Ie,T,Pe,N,{req:ve}),At=await MA(pe,Xe,Ie,N,Pe,{req:ve});return y.log.info(`Fallback model ${se} succeeded`),ae.recordSuccess(ce,De),vi(At,S,we)}catch(ce){let[ye,...De]=se.split(","),we=De.join(",");ae.recordFailure(ye,we,ce.message),y.log.warn(`Fallback model ${se} failed: ${ce.message}`);continue}return y.log.error(`All fallback models failed for ${H}`),null}async function OA(y,S,T,N,V){let H=JSON.parse(JSON.stringify(y)),Y={},K=!1;if(K=LA(S,T,y),K&&(N instanceof Headers?N.delete("content-length"):delete N["content-length"],Y.headers=N),!K&&typeof T.transformRequestOut=="function"){let ae=await T.transformRequestOut(H);ae.body?(H=ae.body,Y=ae.config||{}):H=ae}if(!K&&S.transformer?.use?.length)for(let ae of S.transformer.use){if(!ae||typeof ae.transformRequestIn!="function")continue;let ee=await ae.transformRequestIn(H,S,V);ee.body?(H=ee.body,Y={...Y,...ee.config}):H=ee}if(!K&&S.transformer?.[y.model]?.use?.length)for(let ae of S.transformer[y.model].use)!ae||typeof ae.transformRequestIn!="function"||(H=await ae.transformRequestIn(H,S,V));return{requestBody:H,config:Y,bypass:K}}function LA(y,S,T){return y.transformer?.use?.length===1&&y.transformer.use[0].name===S.name&&(!y.transformer?.[T.model]?.use.length||y.transformer?.[T.model]?.use.length===1&&y.transformer?.[T.model]?.use[0].name===S.name)}async function PA(y,S,T,N,V,H,Y){let K=S.url||new URL(T.baseUrl);if(!S.TIMEOUT){let ue=N.configService.get("API_TIMEOUT_MS");ue&&(S.TIMEOUT=typeof ue=="string"?parseInt(ue,10):ue)}if(V&&typeof H.auth=="function"){let ue=await H.auth(y,T);if(ue.body){y=ue.body;let ge=S.headers||{};ue.config?.headers&&(ge={...ge,...ue.config.headers},delete ge.host,delete ue.config.headers),S={...S,...ue.config,headers:ge}}else y=ue}let ae={Authorization:`Bearer ${T.apiKey}`,...S?.headers||{}};for(let ue in ae)(ae[ue]==="undefined"||["authorization","Authorization"].includes(ue)&&ae[ue]?.includes("undefined"))&&delete ae[ue];let ee=await Dg(K,y,{httpsProxy:N.configService.getHttpsProxy(),...S,headers:JSON.parse(JSON.stringify(ae))},Y,N.log);if(!ee.ok){let ue=await ee.text();throw N.log.error(`[provider_response_error] Error from provider(${T.name},${y.model}: ${ee.status}): ${ue}`),Is(`Error from provider(${T.name},${y.model}: ${ee.status}): ${ue}`,ee.status,"provider_response_error")}return ee}async function MA(y,S,T,N,V,H){let Y=S;if(!V&&T.transformer?.use?.length)for(let K of Array.from(T.transformer.use).reverse())!K||typeof K.transformResponseOut!="function"||(Y=await K.transformResponseOut(Y,H));if(!V&&T.transformer?.[y.model]?.use?.length)for(let K of Array.from(T.transformer[y.model].use).reverse())!K||typeof K.transformResponseOut!="function"||(Y=await K.transformResponseOut(Y,H));return!V&&N.transformResponseIn&&(Y=await N.transformResponseIn(Y,H)),Y}function vi(y,S,T){return y.ok||S.code(y.status),T.stream===!0?(S.header("Content-Type","text/event-stream"),S.header("Cache-Control","no-cache"),S.header("Connection","keep-alive"),S.send(y.body)):y.json()}var nu=async y=>{y.get("/",async()=>({message:"LLMs API",version:Cg})),y.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),y.get("/providers/health",async()=>({states:Jl().getAllStates().map(T=>({provider:T.provider,model:T.model,status:T.status,failureCount:T.failureCount,successCount:T.successCount,lastFailureTime:T.lastFailureTime,lastError:T.lastError})),timestamp:new Date().toISOString()}));let S=y.transformerService.getTransformersWithEndpoint();for(let{transformer:T}of S)T.endPoint&&y.post(T.endPoint,async(N,V)=>wg(N,V,y,T));y.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(T,N)=>{let{name:V,baseUrl:H,apiKey:Y,models:K}=T.body;if(!V?.trim())throw Is("Provider name is required",400,"invalid_request");if(!H||!UA(H))throw Is("Valid base URL is required",400,"invalid_request");if(!Y?.trim())throw Is("API key is required",400,"invalid_request");if(!K||!Array.isArray(K)||K.length===0)throw Is("At least one model is required",400,"invalid_request");if(y.providerService.getProvider(T.body.name))throw Is(`Provider with name '${T.body.name}' already exists`,400,"provider_exists");return y.providerService.registerProvider(T.body)}),y.get("/providers",async()=>y.providerService.getProviders()),y.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async T=>{let N=y.providerService.getProvider(T.params.id);if(!N)throw Is("Provider not found",404,"provider_not_found");return N}),y.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(T,N)=>{let V=y.providerService.updateProvider(T.params.id,T.body);if(!V)throw Is("Provider not found",404,"provider_not_found");return V}),y.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async T=>{if(!y.providerService.deleteProvider(T.params.id))throw Is("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),y.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(T,N)=>{if(!y.providerService.toggleProvider(T.params.id,T.body.enabled))throw Is("Provider not found",404,"provider_not_found");return{message:`Provider ${T.body.enabled?"enabled":"disabled"} successfully`}})};function UA(y){try{return new URL(y),!0}catch{return!1}}var Wu=class{constructor(y,S,T){this.configService=y,this.transformerService=S,this.logger=T,this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let y=this.configService.get("providers");if(y&&Array.isArray(y)){this.initializeFromProvidersArray(y);return}}initializeFromProvidersArray(y){y.forEach(S=>{try{if(!S.name||!S.api_base_url||!S.api_key)return;let T={};S.transformer&&Object.keys(S.transformer).forEach(N=>{N==="use"?Array.isArray(S.transformer.use)&&(T.use=S.transformer.use.map(V=>{if(Array.isArray(V)&&typeof V[0]=="string"){let H=this.transformerService.getTransformer(V[0]);if(H)return new H(V[1])}if(typeof V=="string"){let H=this.transformerService.getTransformer(V);return typeof H=="function"?new H:H}}).filter(V=>typeof V<"u")):Array.isArray(S.transformer[N]?.use)&&(T[N]={use:S.transformer[N].use.map(V=>{if(Array.isArray(V)&&typeof V[0]=="string"){let H=this.transformerService.getTransformer(V[0]);if(H)return new H(V[1])}if(typeof V=="string"){let H=this.transformerService.getTransformer(V);return typeof H=="function"?new H:H}}).filter(V=>typeof V<"u")})}),this.registerProvider({name:S.name,baseUrl:S.api_base_url,apiKey:S.api_key,models:S.models||[],transformer:S.transformer?T:void 0}),this.logger.info(`${S.name} provider registered`)}catch(T){this.logger.error(`${S.name} provider registered error: ${T}`)}})}registerProvider(y){let S={...y};return this.providers.set(S.name,S),y.models.forEach(T=>{let N=`${S.name},${T}`,V={provider:S.name,model:T,fullModel:N};this.modelRoutes.set(N,V),this.modelRoutes.has(T)||this.modelRoutes.set(T,V)}),S}getProviders(){return Array.from(this.providers.values())}getProvider(y){return this.providers.get(y)}updateProvider(y,S){let T=this.providers.get(y);if(!T)return null;let N={...T,...S,updatedAt:new Date};return this.providers.set(y,N),S.models&&(T.models.forEach(V=>{let H=`${T.name},${V}`;this.modelRoutes.delete(H),this.modelRoutes.delete(V)}),S.models.forEach(V=>{let H=`${T.name},${V}`,Y={provider:T.name,model:V,fullModel:H};this.modelRoutes.set(H,Y),this.modelRoutes.has(V)||this.modelRoutes.set(V,Y)})),N}deleteProvider(y){let S=this.providers.get(y);return S?(S.models.forEach(T=>{let N=`${S.name},${T}`;this.modelRoutes.delete(N),this.modelRoutes.delete(T)}),this.providers.delete(y),!0):!1}toggleProvider(y,S){return!!this.providers.get(y)}resolveModelRoute(y){let S=this.modelRoutes.get(y);if(!S)return null;let T=this.providers.get(S.provider);return T?{provider:T,originalModel:y,targetModel:S.model}:null}getAvailableModelNames(){let y=[];return this.providers.forEach(S=>{S.models.forEach(T=>{y.push(T),y.push(`${S.name},${T}`)})}),y}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(y){return y?Array.isArray(y)?y.reduce((S,T)=>{if(Array.isArray(T)){let[N,V={}]=T;S[N]=V}else S[T]={};return S},{}):y:{}}async getAvailableModels(){let y=[];return this.providers.forEach(S=>{S.models.forEach(T=>{y.push({id:T,object:"model",owned_by:S.name,provider:S.name}),y.push({id:`${S.name},${T}`,object:"model",owned_by:S.name,provider:S.name})})}),{object:"list",data:y}}},Wn=[];for(let y=0;y<256;++y)Wn.push((y+256).toString(16).slice(1));function Go(y,S=0){return(Wn[y[S+0]]+Wn[y[S+1]]+Wn[y[S+2]]+Wn[y[S+3]]+"-"+Wn[y[S+4]]+Wn[y[S+5]]+"-"+Wn[y[S+6]]+Wn[y[S+7]]+"-"+Wn[y[S+8]]+Wn[y[S+9]]+"-"+Wn[y[S+10]]+Wn[y[S+11]]+Wn[y[S+12]]+Wn[y[S+13]]+Wn[y[S+14]]+Wn[y[S+15]]).toLowerCase()}var Ps=require("crypto"),Vo=new Uint8Array(256),Ku=Vo.length;function Da(){return Ku>Vo.length-16&&((0,Ps.randomFillSync)(Vo),Ku=0),Vo.slice(Ku,Ku+=16)}var jA=require("crypto"),Fh={randomUUID:jA.randomUUID};function zl(y,S,T){if(Fh.randomUUID&&!S&&!y)return Fh.randomUUID();y=y||{};let N=y.random??y.rng?.()??Da();if(N.length<16)throw new Error("Random bytes length must be >= 16");if(N[6]=N[6]&15|64,N[8]=N[8]&63|128,S){if(T=T||0,T<0||T+16>S.length)throw new RangeError(`UUID byte range ${T}:${T+15} is out of buffer bounds`);for(let V=0;V<16;++V)S[T+V]=N[V];return S}return Go(N)}var iu=zl,$A=y=>y<=0?"none":y<=1024?"low":y<=8192?"medium":"high",HA=(y,S)=>(y.includes("base64")&&(y=y.split("base64").pop(),y.startsWith(",")&&(y=y.slice(1))),`data:${S};base64,${y}`),Wl=class{constructor(y){this.options=y,this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(y,S){let T={};return this.useBearer?(T.authorization=`Bearer ${S.apiKey}`,T["x-api-key"]=void 0):(T["x-api-key"]=S.apiKey,T.authorization=void 0),{body:y,config:{headers:T}}}async transformRequestOut(y){let S=[];if(y.system){if(typeof y.system=="string")S.push({role:"system",content:y.system});else if(Array.isArray(y.system)&&y.system.length){let N=y.system.filter(V=>V.type==="text"&&V.text).map(V=>({type:"text",text:V.text,cache_control:V.cache_control}));S.push({role:"system",content:N})}}JSON.parse(JSON.stringify(y.messages||[]))?.forEach(N=>{if(N.role==="user"||N.role==="assistant"){if(typeof N.content=="string"){S.push({role:N.role,content:N.content});return}if(Array.isArray(N.content)){if(N.role==="user"){let V=N.content.filter(Y=>Y.type==="tool_result"&&Y.tool_use_id);V.length&&V.forEach(Y=>{let K={role:"tool",content:typeof Y.content=="string"?Y.content:JSON.stringify(Y.content),tool_call_id:Y.tool_use_id,cache_control:Y.cache_control};S.push(K)});let H=N.content.filter(Y=>Y.type==="text"&&Y.text||Y.type==="image"&&Y.source);H.length&&S.push({role:"user",content:H.map(Y=>Y?.type==="image"?{type:"image_url",image_url:{url:Y.source?.type==="base64"?HA(Y.source.data,Y.source.media_type):Y.source.url},media_type:Y.source.media_type}:Y)})}else if(N.role==="assistant"){let V={role:"assistant",content:""},H=N.content.filter(ae=>ae.type==="text"&&ae.text);H.length&&(V.content=H.map(ae=>ae.text).join(`
|
|
583
583
|
`));let Y=N.content.filter(ae=>ae.type==="tool_use"&&ae.id);Y.length&&(V.tool_calls=Y.map(ae=>({id:ae.id,type:"function",function:{name:ae.name,arguments:JSON.stringify(ae.input||{})}})));let K=N.content.find(ae=>ae.type==="thinking"&&ae.signature);K&&(V.thinking={content:K.thinking,signature:K.signature}),S.push(V)}return}}});let T={messages:S,model:y.model,max_tokens:y.max_tokens,temperature:y.temperature,stream:y.stream,tools:y.tools?.length?this.convertAnthropicToolsToUnified(y.tools):void 0,tool_choice:y.tool_choice};return y.thinking&&(T.reasoning={effort:$A(y.thinking.budget_tokens),enabled:y.thinking.type==="enabled"}),y.tool_choice&&(y.tool_choice.type==="tool"?T.tool_choice={type:"function",function:{name:y.tool_choice.name}}:T.tool_choice=y.tool_choice.type),T}async transformResponseIn(y,S){if(y.headers.get("Content-Type")?.includes("text/event-stream")){if(!y.body)throw new Error("Stream response body is null");let T=await this.convertOpenAIStreamToAnthropic(y.body,S);return new Response(T,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let T=await y.json(),N=this.convertOpenAIResponseToAnthropic(T,S);return new Response(JSON.stringify(N),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(y){return y.map(S=>({type:"function",function:{name:S.name,description:S.description||"",parameters:S.input_schema}}))}async convertOpenAIStreamToAnthropic(y,S){return new ReadableStream({start:async T=>{let N=new TextEncoder,V=`msg_${Date.now()}`,H=null,Y="unknown",K=!1,ae=!1,ee=!1,ue=new Map,ge=new Map,Ee=0,se=0,ce=0,ye=!1,De=!1,we=0,ve=-1,Ie=()=>{let Xe=we;return we++,Xe},pe=Xe=>{if(!ye)try{T.enqueue(Xe);let At=new TextDecoder().decode(Xe);this.logger.debug({reqId:S.req.id,data:At,type:"send data"})}catch(At){if(At instanceof TypeError&&At.message.includes("Controller is already closed"))ye=!0;else throw this.logger.debug({reqId:S.req.id,error:At instanceof Error?At.message:String(At),type:"send data error"}),At}},Te=()=>{if(!ye)try{if(ve>=0){let At={type:"content_block_stop",index:ve};pe(N.encode(`event: content_block_stop
|
|
584
584
|
data: ${JSON.stringify(At)}
|
|
585
585
|
|
|
@@ -925,7 +925,7 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var E=
|
|
|
925
925
|
${this.toMarkdown(n,t+1)}`:`${r}- ${n}`).join(`
|
|
926
926
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([n,s])=>typeof s=="object"&&s!==null?`${r}${n}:
|
|
927
927
|
${this.toMarkdown(s,t+1)}`:`${r}${n}: ${s}`).join(`
|
|
928
|
-
`):`${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}}}}),Hx,qx=Ai(()=>{"use strict";Hx=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:s,metadata:o}=t||{},i={data:e};return n&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),o&&Object.keys(o).length>0&&(i.metadata=o),i}async sendRequest(e,t,r,n,s){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let a=await fetch(e,{method:t,headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(i),!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);return a}catch(a){throw clearTimeout(i),a}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,r,n,s,o){let i=null;for(let a=1;a<=o.maxAttempts;a++)try{return await this.sendRequest(e,t,r,n,s)}catch(u){if(i=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 i}async output(e,t={}){let r=t.timeout||this.defaultTimeout;try{let n=this.buildHeaders(),s=this.buildBody(e,t),o=await this.sendWithRetry(this.config.url,this.config.method,n,s,r,this.config.retry);return!0}catch(n){let s=n instanceof Error?n.message:String(n);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}}),Gx,Vx=Ai(()=>{"use strict";Gx=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let t=(0,r4.tmpdir)();this.baseDir=(0,yb.join)(t,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Sm.existsSync)(this.baseDir)||(0,Sm.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 s=Date.now();n=`${t}-${e}-${s}${r}`}else n=`${t}-${e}${r}`;return(0,yb.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},s=this.getFilePath(r);return(0,Sm.writeFileSync)(s,JSON.stringify(n,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}}),jb,Ad,vM=Ai(()=>{"use strict";$x(),qx(),Vx(),jb=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 jx(e.config);case"webhook":return new Hx(e.config);case"temp-file":return new Gx(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:[]},s=Array.from(this.handlers.entries()).map(async([o,i])=>{try{await i.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(s),n}async outputTo(e,t,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},o=e.map(async i=>{let a=this.handlers.get(i);if(!a){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await a.output(t,n)?s.success.push(i):s.failed.push(i)}catch(u){console.error(`[OutputManager] Handler ${i} failed:`,u),s.failed.push(i)}});return await Promise.all(o),s}async outputToType(e,t,r){let n=Array.from(this.handlers.entries()).filter(([s,o])=>o.type===e).map(([s])=>s);return this.outputTo(n,t,r)}},Ad=new jb}),_M=Fu(kI(),1),$b=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,Db.join)(process.cwd(),this.options.jsonPath);if((0,Fm.existsSync)(e))try{let t=(0,Fm.readFileSync)(e,"utf-8"),r=_M.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,Db.join)(process.cwd(),this.options.envPath);if((0,Fm.existsSync)(e))try{let t=(0,s4.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 no(e,t=500,r="internal_error",n="api_error"){let s=new Error(e);return s.statusCode=t,s.code=r,s.type=n,s}async function SM(e,t,r){t.log.error(e);let n=e.statusCode||500,s={error:{message:e.message+e.stack||"Internal Server Error",type:e.type||"api_error",code:e.code||"internal_error"}};return r.code(n).send(s)}function FM(e,t,r,n,s){let o=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([l,c])=>{c&&o.set(l,c)});let i,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),i=l.signal}else i=a;let u={method:"POST",headers:o,body:JSON.stringify(t),signal:i};return r.httpsProxy&&(u.dispatcher=new o4.ProxyAgent(new URL(r.httpsProxy).toString())),s?.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 kM="2.0.41",TM={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},RM=class{states=new Map;config;probeTimer;constructor(e){this.config={...TM,...e}}getKey(e,t){return`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let r=this.getKey(e,t),n=this.states.get(r);n&&(n.successCount++,n.status==="half-open"?n.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(r):n.status==="open"&&(n.status="half-open",n.successCount=1,n.failureCount=0))}isRateLimitError(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("429")||t.includes("rate_limit")||t.includes("ratelimit")||t.includes("rate limit")||t.includes("overloaded")||t.includes("quota")}recordFailure(e,t,r){if(!this.config.enabled)return;let n=this.getKey(e,t),s=this.states.get(n);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(n,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r;let o=this.isRateLimitError(r)?this.config.rateLimitThreshold:this.config.failureThreshold;s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=o&&(s.status="open",s.lastProbeTime=0)}getState(e,t){return this.states.get(this.getKey(e,t))}isAvailable(e,t){if(!this.config.enabled)return!0;let r=this.getState(e,t);return r?r.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,r]of this.states)r.status==="open"&&e.push(t);return e}getHalfOpenModels(){let e=[];for(let[t,r]of this.states)r.status==="half-open"&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let r=this.getKey(e,t),n=this.states.get(r);n&&n.status==="open"&&(n.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Mm=null;function fy(e){return Mm||(Mm=new RM(e)),Mm}async function QM(e,t,r,n){let s=e.body,o=e.provider,i=r.providerService.getProvider(o);if(!i)throw no(`Provider '${o}' not found`,404,"provider_not_found");try{let{requestBody:a,config:u,bypass:l}=await Yx(s,i,n,e.headers,{req:e}),c=await Jx(a,u,i,r,l,n,{req:e}),d=await zx(a,c,i,n,l,{req:e});return Wx(d,t,s)}catch(a){let u=await NM(e,t,r,n,a);if(u)return u;throw a}}async function NM(e,t,r,n,s){let o=e.scenarioType||"default",i=e.familyFallback,a=r.configService.get("fallback"),u=fy(),l=[];if(i?.[o]?l=i[o]:a?.[o]&&(l=a[o]),!Array.isArray(l)||l.length===0)return null;let c=e.provider||"",d=e.body.model||"";u.recordFailure(c,d,s?.message),e.log.warn(`Request failed for ${e.scenarioType}, trying ${l.length} fallback models`);let A=l.sort((h,f)=>{let[p,g]=h.split(","),[m,C]=f.split(",");return u.getPriority(p,g)-u.getPriority(m,C)});for(let h of A)try{let[f,...p]=h.split(","),g=p.join(",");if(!u.isAvailable(f,g)){e.log.warn(`Fallback model ${h} unavailable (fail pool), skipping`);continue}e.log.info(`Trying fallback model: ${h}`);let m={...e.body};m.model=g;let C={...e,provider:f,body:m},E=r.providerService.getProvider(f);if(!E){e.log.warn(`Fallback provider '${f}' not found, skipping`);continue}let{requestBody:D,config:w,bypass:x}=await Yx(m,E,n,e.headers,{req:C}),b=await Jx(D,w,E,r,x,n,{req:C}),I=await zx(D,b,E,n,x,{req:C});return e.log.info(`Fallback model ${h} succeeded`),u.recordSuccess(f,g),Wx(I,t,m)}catch(f){let[p,...g]=h.split(","),m=g.join(",");u.recordFailure(p,m,f.message),e.log.warn(`Fallback model ${h} failed: ${f.message}`);continue}return e.log.error(`All fallback models failed for ${o}`),null}async function Yx(e,t,r,n,s){let o=JSON.parse(JSON.stringify(e)),i={},a=!1;if(a=OM(t,r,e),a&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],i.headers=n),!a&&typeof r.transformRequestOut=="function"){let u=await r.transformRequestOut(o);u.body?(o=u.body,i=u.config||{}):o=u}if(!a&&t.transformer?.use?.length)for(let u of t.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let l=await u.transformRequestIn(o,t,s);l.body?(o=l.body,i={...i,...l.config}):o=l}if(!a&&t.transformer?.[e.model]?.use?.length)for(let u of t.transformer[e.model].use)!u||typeof u.transformRequestIn!="function"||(o=await u.transformRequestIn(o,t,s));return{requestBody:o,config:i,bypass:a}}function OM(e,t,r){return e.transformer?.use?.length===1&&e.transformer.use[0].name===t.name&&(!e.transformer?.[r.model]?.use.length||e.transformer?.[r.model]?.use.length===1&&e.transformer?.[r.model]?.use[0].name===t.name)}async function Jx(e,t,r,n,s,o,i){let a=t.url||new URL(r.baseUrl);if(!t.TIMEOUT){let c=n.configService.get("API_TIMEOUT_MS");c&&(t.TIMEOUT=typeof c=="string"?parseInt(c,10):c)}if(s&&typeof o.auth=="function"){let c=await o.auth(e,r);if(c.body){e=c.body;let d=t.headers||{};c.config?.headers&&(d={...d,...c.config.headers},delete d.host,delete c.config.headers),t={...t,...c.config,headers:d}}else e=c}let u={Authorization:`Bearer ${r.apiKey}`,...t?.headers||{}};for(let c in u)(u[c]==="undefined"||["authorization","Authorization"].includes(c)&&u[c]?.includes("undefined"))&&delete u[c];let l=await FM(a,e,{httpsProxy:n.configService.getHttpsProxy(),...t,headers:JSON.parse(JSON.stringify(u))},i,n.log);if(!l.ok){let c=await l.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${e.model}: ${l.status}): ${c}`),no(`Error from provider(${r.name},${e.model}: ${l.status}): ${c}`,l.status,"provider_response_error")}return l}async function zx(e,t,r,n,s,o){let i=t;if(!s&&r.transformer?.use?.length)for(let a of Array.from(r.transformer.use).reverse())!a||typeof a.transformResponseOut!="function"||(i=await a.transformResponseOut(i,o));if(!s&&r.transformer?.[e.model]?.use?.length)for(let a of Array.from(r.transformer[e.model].use).reverse())!a||typeof a.transformResponseOut!="function"||(i=await a.transformResponseOut(i,o));return!s&&n.transformResponseIn&&(i=await n.transformResponseIn(i,o)),i}function Wx(e,t,r){return e.ok||t.code(e.status),r.stream===!0?(t.header("Content-Type","text/event-stream"),t.header("Cache-Control","no-cache"),t.header("Connection","keep-alive"),t.send(e.body)):e.json()}var Hb=async e=>{e.get("/",async()=>({message:"LLMs API",version:kM})),e.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),e.get("/providers/health",async()=>({states:fy().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError})),timestamp:new Date().toISOString()}));let t=e.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of t)r.endPoint&&e.post(r.endPoint,async(n,s)=>QM(n,s,e,r));e.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(r,n)=>{let{name:s,baseUrl:o,apiKey:i,models:a}=r.body;if(!s?.trim())throw no("Provider name is required",400,"invalid_request");if(!o||!LM(o))throw no("Valid base URL is required",400,"invalid_request");if(!i?.trim())throw no("API key is required",400,"invalid_request");if(!a||!Array.isArray(a)||a.length===0)throw no("At least one model is required",400,"invalid_request");if(e.providerService.getProvider(r.body.name))throw no(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return e.providerService.registerProvider(r.body)}),e.get("/providers",async()=>e.providerService.getProviders()),e.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=e.providerService.getProvider(r.params.id);if(!n)throw no("Provider not found",404,"provider_not_found");return n}),e.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(r,n)=>{let s=e.providerService.updateProvider(r.params.id,r.body);if(!s)throw no("Provider not found",404,"provider_not_found");return s}),e.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!e.providerService.deleteProvider(r.params.id))throw no("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),e.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(r,n)=>{if(!e.providerService.toggleProvider(r.params.id,r.body.enabled))throw no("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function LM(e){try{return new URL(e),!0}catch{return!1}}var qb=class{constructor(e,t,r){this.configService=e,this.transformerService=t,this.logger=r,this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let r={};t.transformer&&Object.keys(t.transformer).forEach(n=>{n==="use"?Array.isArray(t.transformer.use)&&(r.use=t.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let o=this.transformerService.getTransformer(s[0]);if(o)return new o(s[1])}if(typeof s=="string"){let o=this.transformerService.getTransformer(s);return typeof o=="function"?new o:o}}).filter(s=>typeof s<"u")):Array.isArray(t.transformer[n]?.use)&&(r[n]={use:t.transformer[n].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let o=this.transformerService.getTransformer(s[0]);if(o)return new o(s[1])}if(typeof s=="string"){let o=this.transformerService.getTransformer(s);return typeof o=="function"?new o:o}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],transformer:t.transformer?r:void 0}),this.logger.info(`${t.name} provider registered`)}catch(r){this.logger.error(`${t.name} provider registered error: ${r}`)}})}registerProvider(e){let t={...e};return this.providers.set(t.name,t),e.models.forEach(r=>{let n=`${t.name},${r}`,s={provider:t.name,model:r,fullModel:n};this.modelRoutes.set(n,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let r=this.providers.get(e);if(!r)return null;let n={...r,...t,updatedAt:new Date};return this.providers.set(e,n),t.models&&(r.models.forEach(s=>{let o=`${r.name},${s}`;this.modelRoutes.delete(o),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let o=`${r.name},${s}`,i={provider:r.name,model:s,fullModel:o};this.modelRoutes.set(o,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),n}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(r=>{let n=`${t.name},${r}`;this.modelRoutes.delete(n),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){return!!this.providers.get(e)}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let r=this.providers.get(t.provider);return r?{provider:r,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.models.forEach(r=>{e.push(r),e.push(`${t.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,r)=>{if(Array.isArray(r)){let[n,s={}]=r;t[n]=s}else t[r]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.models.forEach(r=>{e.push({id:r,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${r}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}},Gi=[];for(let e=0;e<256;++e)Gi.push((e+256).toString(16).slice(1));function PM(e,t=0){return(Gi[e[t+0]]+Gi[e[t+1]]+Gi[e[t+2]]+Gi[e[t+3]]+"-"+Gi[e[t+4]]+Gi[e[t+5]]+"-"+Gi[e[t+6]]+Gi[e[t+7]]+"-"+Gi[e[t+8]]+Gi[e[t+9]]+"-"+Gi[e[t+10]]+Gi[e[t+11]]+Gi[e[t+12]]+Gi[e[t+13]]+Gi[e[t+14]]+Gi[e[t+15]]).toLowerCase()}var A0=new Uint8Array(256),e0=A0.length;function MM(){return e0>A0.length-16&&((0,a4.randomFillSync)(A0),e0=0),A0.slice(e0,e0+=16)}var Gb={randomUUID:u4.randomUUID};function UM(e,t,r){if(Gb.randomUUID&&!t&&!e)return Gb.randomUUID();e=e||{};let n=e.random??e.rng?.()??MM();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)t[r+s]=n[s];return t}return PM(n)}var Ed=UM,jM=e=>e<=0?"none":e<=1024?"low":e<=8192?"medium":"high",$M=(e,t)=>(e.includes("base64")&&(e=e.split("base64").pop(),e.startsWith(",")&&(e=e.slice(1))),`data:${t};base64,${e}`),HM=class{constructor(e){this.options=e,this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let r={};return this.useBearer?(r.authorization=`Bearer ${t.apiKey}`,r["x-api-key"]=void 0):(r["x-api-key"]=t.apiKey,r.authorization=void 0),{body:e,config:{headers:r}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let n=e.system.filter(s=>s.type==="text"&&s.text).map(s=>({type:"text",text:s.text,cache_control:s.cache_control}));t.push({role:"system",content:n})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(n=>{if(n.role==="user"||n.role==="assistant"){if(typeof n.content=="string"){t.push({role:n.role,content:n.content});return}if(Array.isArray(n.content)){if(n.role==="user"){let s=n.content.filter(i=>i.type==="tool_result"&&i.tool_use_id);s.length&&s.forEach(i=>{let a={role:"tool",content:typeof i.content=="string"?i.content:JSON.stringify(i.content),tool_call_id:i.tool_use_id,cache_control:i.cache_control};t.push(a)});let o=n.content.filter(i=>i.type==="text"&&i.text||i.type==="image"&&i.source);o.length&&t.push({role:"user",content:o.map(i=>i?.type==="image"?{type:"image_url",image_url:{url:i.source?.type==="base64"?$M(i.source.data,i.source.media_type):i.source.url},media_type:i.source.media_type}:i)})}else if(n.role==="assistant"){let s={role:"assistant",content:""},o=n.content.filter(u=>u.type==="text"&&u.text);o.length&&(s.content=o.map(u=>u.text).join(`
|
|
928
|
+
`):`${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}}}}),Hx,qx=Ai(()=>{"use strict";Hx=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:s,metadata:o}=t||{},i={data:e};return n&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),o&&Object.keys(o).length>0&&(i.metadata=o),i}async sendRequest(e,t,r,n,s){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let a=await fetch(e,{method:t,headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(i),!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);return a}catch(a){throw clearTimeout(i),a}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,r,n,s,o){let i=null;for(let a=1;a<=o.maxAttempts;a++)try{return await this.sendRequest(e,t,r,n,s)}catch(u){if(i=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 i}async output(e,t={}){let r=t.timeout||this.defaultTimeout;try{let n=this.buildHeaders(),s=this.buildBody(e,t),o=await this.sendWithRetry(this.config.url,this.config.method,n,s,r,this.config.retry);return!0}catch(n){let s=n instanceof Error?n.message:String(n);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}}),Gx,Vx=Ai(()=>{"use strict";Gx=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let t=(0,r4.tmpdir)();this.baseDir=(0,yb.join)(t,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Sm.existsSync)(this.baseDir)||(0,Sm.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 s=Date.now();n=`${t}-${e}-${s}${r}`}else n=`${t}-${e}${r}`;return(0,yb.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},s=this.getFilePath(r);return(0,Sm.writeFileSync)(s,JSON.stringify(n,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}}),jb,Ad,vM=Ai(()=>{"use strict";$x(),qx(),Vx(),jb=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 jx(e.config);case"webhook":return new Hx(e.config);case"temp-file":return new Gx(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:[]},s=Array.from(this.handlers.entries()).map(async([o,i])=>{try{await i.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(s),n}async outputTo(e,t,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},o=e.map(async i=>{let a=this.handlers.get(i);if(!a){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await a.output(t,n)?s.success.push(i):s.failed.push(i)}catch(u){console.error(`[OutputManager] Handler ${i} failed:`,u),s.failed.push(i)}});return await Promise.all(o),s}async outputToType(e,t,r){let n=Array.from(this.handlers.entries()).filter(([s,o])=>o.type===e).map(([s])=>s);return this.outputTo(n,t,r)}},Ad=new jb}),_M=Fu(kI(),1),$b=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,Db.join)(process.cwd(),this.options.jsonPath);if((0,Fm.existsSync)(e))try{let t=(0,Fm.readFileSync)(e,"utf-8"),r=_M.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,Db.join)(process.cwd(),this.options.envPath);if((0,Fm.existsSync)(e))try{let t=(0,s4.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 no(e,t=500,r="internal_error",n="api_error"){let s=new Error(e);return s.statusCode=t,s.code=r,s.type=n,s}async function SM(e,t,r){t.log.error(e);let n=e.statusCode||500,s={error:{message:e.message+e.stack||"Internal Server Error",type:e.type||"api_error",code:e.code||"internal_error"}};return r.code(n).send(s)}function FM(e,t,r,n,s){let o=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([l,c])=>{c&&o.set(l,c)});let i,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),i=l.signal}else i=a;let u={method:"POST",headers:o,body:JSON.stringify(t),signal:i};return r.httpsProxy&&(u.dispatcher=new o4.ProxyAgent(new URL(r.httpsProxy).toString())),s?.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 kM="2.0.42",TM={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},RM=class{states=new Map;config;probeTimer;constructor(e){this.config={...TM,...e}}getKey(e,t){return`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let r=this.getKey(e,t),n=this.states.get(r);n&&(n.successCount++,n.status==="half-open"?n.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(r):n.status==="open"&&(n.status="half-open",n.successCount=1,n.failureCount=0))}isRateLimitError(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("429")||t.includes("rate_limit")||t.includes("ratelimit")||t.includes("rate limit")||t.includes("overloaded")||t.includes("quota")}recordFailure(e,t,r){if(!this.config.enabled)return;let n=this.getKey(e,t),s=this.states.get(n);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(n,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r;let o=this.isRateLimitError(r)?this.config.rateLimitThreshold:this.config.failureThreshold;s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=o&&(s.status="open",s.lastProbeTime=0)}getState(e,t){return this.states.get(this.getKey(e,t))}isAvailable(e,t){if(!this.config.enabled)return!0;let r=this.getState(e,t);return r?r.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,r]of this.states)r.status==="open"&&e.push(t);return e}getHalfOpenModels(){let e=[];for(let[t,r]of this.states)r.status==="half-open"&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let r=this.getKey(e,t),n=this.states.get(r);n&&n.status==="open"&&(n.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Mm=null;function fy(e){return Mm||(Mm=new RM(e)),Mm}async function QM(e,t,r,n){let s=e.body,o=e.provider,i=r.providerService.getProvider(o);if(!i)throw no(`Provider '${o}' not found`,404,"provider_not_found");try{let{requestBody:a,config:u,bypass:l}=await Yx(s,i,n,e.headers,{req:e}),c=await Jx(a,u,i,r,l,n,{req:e}),d=await zx(a,c,i,n,l,{req:e});return Wx(d,t,s)}catch(a){let u=await NM(e,t,r,n,a);if(u)return u;throw a}}async function NM(e,t,r,n,s){let o=e.scenarioType||"default",i=e.familyFallback,a=r.configService.get("fallback"),u=fy(),l=[];if(i?.[o]?l=i[o]:a?.[o]&&(l=a[o]),!Array.isArray(l)||l.length===0)return null;let c=e.provider||"",d=e.body.model||"";u.recordFailure(c,d,s?.message),e.log.warn(`Request failed for ${e.scenarioType}, trying ${l.length} fallback models`);let A=l.sort((h,f)=>{let[p,g]=h.split(","),[m,C]=f.split(",");return u.getPriority(p,g)-u.getPriority(m,C)});for(let h of A)try{let[f,...p]=h.split(","),g=p.join(",");if(!u.isAvailable(f,g)){e.log.warn(`Fallback model ${h} unavailable (fail pool), skipping`);continue}e.log.info(`Trying fallback model: ${h}`);let m={...e.body};m.model=g;let C={...e,provider:f,body:m},E=r.providerService.getProvider(f);if(!E){e.log.warn(`Fallback provider '${f}' not found, skipping`);continue}let{requestBody:D,config:w,bypass:x}=await Yx(m,E,n,e.headers,{req:C}),b=await Jx(D,w,E,r,x,n,{req:C}),I=await zx(D,b,E,n,x,{req:C});return e.log.info(`Fallback model ${h} succeeded`),u.recordSuccess(f,g),Wx(I,t,m)}catch(f){let[p,...g]=h.split(","),m=g.join(",");u.recordFailure(p,m,f.message),e.log.warn(`Fallback model ${h} failed: ${f.message}`);continue}return e.log.error(`All fallback models failed for ${o}`),null}async function Yx(e,t,r,n,s){let o=JSON.parse(JSON.stringify(e)),i={},a=!1;if(a=OM(t,r,e),a&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],i.headers=n),!a&&typeof r.transformRequestOut=="function"){let u=await r.transformRequestOut(o);u.body?(o=u.body,i=u.config||{}):o=u}if(!a&&t.transformer?.use?.length)for(let u of t.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let l=await u.transformRequestIn(o,t,s);l.body?(o=l.body,i={...i,...l.config}):o=l}if(!a&&t.transformer?.[e.model]?.use?.length)for(let u of t.transformer[e.model].use)!u||typeof u.transformRequestIn!="function"||(o=await u.transformRequestIn(o,t,s));return{requestBody:o,config:i,bypass:a}}function OM(e,t,r){return e.transformer?.use?.length===1&&e.transformer.use[0].name===t.name&&(!e.transformer?.[r.model]?.use.length||e.transformer?.[r.model]?.use.length===1&&e.transformer?.[r.model]?.use[0].name===t.name)}async function Jx(e,t,r,n,s,o,i){let a=t.url||new URL(r.baseUrl);if(!t.TIMEOUT){let c=n.configService.get("API_TIMEOUT_MS");c&&(t.TIMEOUT=typeof c=="string"?parseInt(c,10):c)}if(s&&typeof o.auth=="function"){let c=await o.auth(e,r);if(c.body){e=c.body;let d=t.headers||{};c.config?.headers&&(d={...d,...c.config.headers},delete d.host,delete c.config.headers),t={...t,...c.config,headers:d}}else e=c}let u={Authorization:`Bearer ${r.apiKey}`,...t?.headers||{}};for(let c in u)(u[c]==="undefined"||["authorization","Authorization"].includes(c)&&u[c]?.includes("undefined"))&&delete u[c];let l=await FM(a,e,{httpsProxy:n.configService.getHttpsProxy(),...t,headers:JSON.parse(JSON.stringify(u))},i,n.log);if(!l.ok){let c=await l.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${e.model}: ${l.status}): ${c}`),no(`Error from provider(${r.name},${e.model}: ${l.status}): ${c}`,l.status,"provider_response_error")}return l}async function zx(e,t,r,n,s,o){let i=t;if(!s&&r.transformer?.use?.length)for(let a of Array.from(r.transformer.use).reverse())!a||typeof a.transformResponseOut!="function"||(i=await a.transformResponseOut(i,o));if(!s&&r.transformer?.[e.model]?.use?.length)for(let a of Array.from(r.transformer[e.model].use).reverse())!a||typeof a.transformResponseOut!="function"||(i=await a.transformResponseOut(i,o));return!s&&n.transformResponseIn&&(i=await n.transformResponseIn(i,o)),i}function Wx(e,t,r){return e.ok||t.code(e.status),r.stream===!0?(t.header("Content-Type","text/event-stream"),t.header("Cache-Control","no-cache"),t.header("Connection","keep-alive"),t.send(e.body)):e.json()}var Hb=async e=>{e.get("/",async()=>({message:"LLMs API",version:kM})),e.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),e.get("/providers/health",async()=>({states:fy().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError})),timestamp:new Date().toISOString()}));let t=e.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of t)r.endPoint&&e.post(r.endPoint,async(n,s)=>QM(n,s,e,r));e.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(r,n)=>{let{name:s,baseUrl:o,apiKey:i,models:a}=r.body;if(!s?.trim())throw no("Provider name is required",400,"invalid_request");if(!o||!LM(o))throw no("Valid base URL is required",400,"invalid_request");if(!i?.trim())throw no("API key is required",400,"invalid_request");if(!a||!Array.isArray(a)||a.length===0)throw no("At least one model is required",400,"invalid_request");if(e.providerService.getProvider(r.body.name))throw no(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return e.providerService.registerProvider(r.body)}),e.get("/providers",async()=>e.providerService.getProviders()),e.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=e.providerService.getProvider(r.params.id);if(!n)throw no("Provider not found",404,"provider_not_found");return n}),e.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(r,n)=>{let s=e.providerService.updateProvider(r.params.id,r.body);if(!s)throw no("Provider not found",404,"provider_not_found");return s}),e.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!e.providerService.deleteProvider(r.params.id))throw no("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),e.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(r,n)=>{if(!e.providerService.toggleProvider(r.params.id,r.body.enabled))throw no("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function LM(e){try{return new URL(e),!0}catch{return!1}}var qb=class{constructor(e,t,r){this.configService=e,this.transformerService=t,this.logger=r,this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let r={};t.transformer&&Object.keys(t.transformer).forEach(n=>{n==="use"?Array.isArray(t.transformer.use)&&(r.use=t.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let o=this.transformerService.getTransformer(s[0]);if(o)return new o(s[1])}if(typeof s=="string"){let o=this.transformerService.getTransformer(s);return typeof o=="function"?new o:o}}).filter(s=>typeof s<"u")):Array.isArray(t.transformer[n]?.use)&&(r[n]={use:t.transformer[n].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let o=this.transformerService.getTransformer(s[0]);if(o)return new o(s[1])}if(typeof s=="string"){let o=this.transformerService.getTransformer(s);return typeof o=="function"?new o:o}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],transformer:t.transformer?r:void 0}),this.logger.info(`${t.name} provider registered`)}catch(r){this.logger.error(`${t.name} provider registered error: ${r}`)}})}registerProvider(e){let t={...e};return this.providers.set(t.name,t),e.models.forEach(r=>{let n=`${t.name},${r}`,s={provider:t.name,model:r,fullModel:n};this.modelRoutes.set(n,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let r=this.providers.get(e);if(!r)return null;let n={...r,...t,updatedAt:new Date};return this.providers.set(e,n),t.models&&(r.models.forEach(s=>{let o=`${r.name},${s}`;this.modelRoutes.delete(o),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let o=`${r.name},${s}`,i={provider:r.name,model:s,fullModel:o};this.modelRoutes.set(o,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),n}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(r=>{let n=`${t.name},${r}`;this.modelRoutes.delete(n),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){return!!this.providers.get(e)}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let r=this.providers.get(t.provider);return r?{provider:r,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.models.forEach(r=>{e.push(r),e.push(`${t.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,r)=>{if(Array.isArray(r)){let[n,s={}]=r;t[n]=s}else t[r]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.models.forEach(r=>{e.push({id:r,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${r}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}},Gi=[];for(let e=0;e<256;++e)Gi.push((e+256).toString(16).slice(1));function PM(e,t=0){return(Gi[e[t+0]]+Gi[e[t+1]]+Gi[e[t+2]]+Gi[e[t+3]]+"-"+Gi[e[t+4]]+Gi[e[t+5]]+"-"+Gi[e[t+6]]+Gi[e[t+7]]+"-"+Gi[e[t+8]]+Gi[e[t+9]]+"-"+Gi[e[t+10]]+Gi[e[t+11]]+Gi[e[t+12]]+Gi[e[t+13]]+Gi[e[t+14]]+Gi[e[t+15]]).toLowerCase()}var A0=new Uint8Array(256),e0=A0.length;function MM(){return e0>A0.length-16&&((0,a4.randomFillSync)(A0),e0=0),A0.slice(e0,e0+=16)}var Gb={randomUUID:u4.randomUUID};function UM(e,t,r){if(Gb.randomUUID&&!t&&!e)return Gb.randomUUID();e=e||{};let n=e.random??e.rng?.()??MM();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)t[r+s]=n[s];return t}return PM(n)}var Ed=UM,jM=e=>e<=0?"none":e<=1024?"low":e<=8192?"medium":"high",$M=(e,t)=>(e.includes("base64")&&(e=e.split("base64").pop(),e.startsWith(",")&&(e=e.slice(1))),`data:${t};base64,${e}`),HM=class{constructor(e){this.options=e,this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let r={};return this.useBearer?(r.authorization=`Bearer ${t.apiKey}`,r["x-api-key"]=void 0):(r["x-api-key"]=t.apiKey,r.authorization=void 0),{body:e,config:{headers:r}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let n=e.system.filter(s=>s.type==="text"&&s.text).map(s=>({type:"text",text:s.text,cache_control:s.cache_control}));t.push({role:"system",content:n})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(n=>{if(n.role==="user"||n.role==="assistant"){if(typeof n.content=="string"){t.push({role:n.role,content:n.content});return}if(Array.isArray(n.content)){if(n.role==="user"){let s=n.content.filter(i=>i.type==="tool_result"&&i.tool_use_id);s.length&&s.forEach(i=>{let a={role:"tool",content:typeof i.content=="string"?i.content:JSON.stringify(i.content),tool_call_id:i.tool_use_id,cache_control:i.cache_control};t.push(a)});let o=n.content.filter(i=>i.type==="text"&&i.text||i.type==="image"&&i.source);o.length&&t.push({role:"user",content:o.map(i=>i?.type==="image"?{type:"image_url",image_url:{url:i.source?.type==="base64"?$M(i.source.data,i.source.media_type):i.source.url},media_type:i.source.media_type}:i)})}else if(n.role==="assistant"){let s={role:"assistant",content:""},o=n.content.filter(u=>u.type==="text"&&u.text);o.length&&(s.content=o.map(u=>u.text).join(`
|
|
929
929
|
`));let i=n.content.filter(u=>u.type==="tool_use"&&u.id);i.length&&(s.tool_calls=i.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input||{})}})));let a=n.content.find(u=>u.type==="thinking"&&u.signature);a&&(s.thinking={content:a.thinking,signature:a.signature}),t.push(s)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(r.reasoning={effort:jM(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let r=await this.convertOpenAIStreamToAnthropic(e.body,t);return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let r=await e.json(),n=this.convertOpenAIResponseToAnthropic(r,t);return new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let n=new TextEncoder,s=`msg_${Date.now()}`,o=null,i="unknown",a=!1,u=!1,l=!1,c=new Map,d=new Map,A=0,h=0,f=0,p=!1,g=!1,m=0,C=-1,E=()=>{let b=m;return m++,b},D=b=>{if(!p)try{r.enqueue(b);let I=new TextDecoder().decode(b);this.logger.debug({reqId:t.req.id,data:I,type:"send data"})}catch(I){if(I instanceof TypeError&&I.message.includes("Controller is already closed"))p=!0;else throw this.logger.debug({reqId:t.req.id,error:I instanceof Error?I.message:String(I),type:"send data error"}),I}},w=()=>{if(!p)try{if(C>=0){let I={type:"content_block_stop",index:C};D(n.encode(`event: content_block_stop
|
|
930
930
|
data: ${JSON.stringify(I)}
|
|
931
931
|
|
|
@@ -1228,7 +1228,7 @@ If multiple images exist, select the **most relevant imageId** based on the user
|
|
|
1228
1228
|
|
|
1229
1229
|
Do not attempt to describe or analyze the image directly yourself.
|
|
1230
1230
|
Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
|
|
1231
|
-
Your response should consistently follow this rule whenever image-related analysis is requested.`});let r=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(o=>o.type==="image"||Array.isArray(o.content)&&o.content.some(i=>i.type==="image"))),n=1;r.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(o=>{o.type==="image"?(n0.storeImage(`${e.id}_Image#${n}`,o.source),o.type="text",delete o.source,o.text=`[Image #${n}]This is an image, if you need to view or analyze it, you need to extract the imageId`,n++):o.type==="text"&&o.text.includes("[Image #")?o.text=o.text.replace(/\[Image #\d+\]/g,""):o.type==="tool_result"&&Array.isArray(o.content)&&o.content.some(i=>i.type==="image")&&(n0.storeImage(`${e.id}_Image#${n}`,o.content[0].source),o.content=`[Image #${n}]This is an image, if you need to view or analyze it, you need to extract the imageId`,n++)})})}},Mj=new Pj,Uj=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},mv=new Uj;mv.registerAgent(Mj);var zm=mv,jj=require("node:events"),Dw=require("node:perf_hooks"),$j=VP(),Hj=$j.getHealthStore,Cw=new jj.EventEmitter;function bw(e){if(e.usageSessionId)return e.usageSessionId;try{let n=e.body?.metadata?.user_id;if(n&&typeof n=="string")try{let s=JSON.parse(n);if(s.session_id)return e.usageSessionId=s.session_id,e.usageSessionId}catch{let s=n.match(/_session_([a-f0-9-]+)/i);if(s)return e.usageSessionId=s[1],e.usageSessionId}}catch{}let t=e.headers?.["x-request-id"],r=Array.isArray(t)?t[0]:t;return e.usageSessionId=e.sessionId||(typeof r=="string"?r:void 0)||e.id||`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,e.usageSessionId}function Wm(e){return e.body?.model?Array.isArray(e.body.model)?e.body.model.join(","):e.body.model:Array.isArray(e.model)?e.model.join(","):e.model||""}async function qj(){let e=(0,xI.homedir)(),t=(0,vI.join)(e,".claude.json");if(!(0,YP.existsSync)(t)){let r={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await(0,JP.writeFile)(t,JSON.stringify(r,null,2))}}async function Gj(e,t){let r=t.plugins||t.Plugins||[];for(let n of r){let{name:s,enabled:o=!1,options:i={}}=n;switch(s){case"token-speed":EE.registerPlugin(dv,{enabled:o,outputHandlers:[{type:"temp-file",enabled:!0}],...i});break;default:console.warn(`Unknown plugin: ${s}`);break}}await EE.enablePlugins(e)}async function Ev(e={}){await qj(),await ty();let t=await _I(),r=t.Providers||t.providers||[],n=r&&r.length>0,s=t.HOST||"127.0.0.1";n?(s=t.HOST,t.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let o=t.PORT||3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):o,a=A=>(A>9?"":"0")+A,u=(A,h)=>{let f;A?typeof A=="number"?f=new Date(A):f=A:f=new Date;let p=f.getFullYear()+""+a(f.getMonth()+1),g=a(f.getDate()),m=a(f.getHours()),C=a(f.getMinutes());return`./logs/ccr-${p}${g}${m}${C}${a(f.getSeconds())}${h?`_${h}`:""}.log`},l;e.logger!==void 0?l=e.logger:t.LOG!==!1?(t.LOG===void 0&&(t.LOG=!0),l={level:t.LOG_LEVEL||"debug",stream:Fj(u,{path:Gm.HOME_DIR,maxFiles:3,interval:"1d",compress:!1,maxSize:"50M"})}):l=!1;let c=await(0,Gm.listPresets)(),d=await gj({jsonPath:Gm.CONFIG_FILE,initialConfig:{providers:t.Providers||t.providers,HOST:s,PORT:i,LOG_FILE:(0,vI.join)((0,xI.homedir)(),".claude-code-router","claude-code-router.log")},logger:l});return await Promise.allSettled(c.map(async A=>await d.registerNamespace(`/preset/${A.name}`,A.config))),await Gj(d,t),d.addHook("onRequest",async A=>{new URL(`http://127.0.0.1${A.url}`).pathname.endsWith("/v1/messages")&&!A.requestStartTime&&(A.requestStartTime=Dw.performance.now())}),d.addHook("preHandler",async(A,h)=>new Promise((f,p)=>{let g=m=>{m?p(m):f()};mj(t)(A,h,g).catch(p)})),d.addHook("preHandler",async(A,h)=>{let f=new URL(`http://127.0.0.1${A.url}`);A.pathname=f.pathname,A.pathname.endsWith("/v1/messages")&&A.pathname!=="/v1/messages"&&(A.preset=A.pathname.replace("/v1/messages","").replace("/",""))}),d.addHook("preHandler",async(A,h)=>{if(A.pathname.endsWith("/v1/messages")){let f=[];for(let p of zm.getAllAgents())p.shouldHandle(A,t)&&(f.push(p.name),p.reqHandler(A,t),p.tools.size&&(A.body?.tools?.length||(A.body.tools=[]),A.body.tools.unshift(...Array.from(p.tools.values()).map(g=>({name:g.name,description:g.description,input_schema:g.input_schema})))));f.length&&(A.agents=f)}}),d.addHook("onError",async(A,h,f)=>{A.errorMessage=f?.message||f?.toString?.()||"Unknown error",Cw.emit("onError",A,h,f)}),d.addHook("onSend",(A,h,f,p)=>{if(A.pathname?.endsWith("/v1/messages")){let g=bw(A);if(f instanceof ReadableStream){if(A.agents){let E=new AbortController,D=f.pipeThrough(new Jm),w,x=-1,b="",I="",B="",_=[],v=[];return p(null,Tj(D,async(F,R)=>{try{if(F.event==="content_block_start"&&F?.data?.content_block?.name){let O=A.agents.find(k=>zm.getAgent(k)?.tools.get(F.data.content_block.name));if(O){w=zm.getAgent(O),x=F.data.index,b=F.data.content_block.name,B=F.data.content_block.id;return}}if(x>-1&&F.data.index===x&&F.data?.delta?.type==="input_json_delta"){I+=F.data?.delta?.partial_json;return}if(x>-1&&F.data.index===x&&F.data.type==="content_block_stop"){try{let O=Rj.default.parse(I);v.push({type:"tool_use",id:B,name:b,input:O});let k=await w?.tools.get(b)?.handler(O,{req:A,config:t});_.push({tool_use_id:B,type:"tool_result",content:k}),w=void 0,x=-1,b="",I="",B=""}catch(O){console.log(O)}return}if(F.event==="message_delta"&&_.length){A.body.messages.push({role:"assistant",content:v}),A.body.messages.push({role:"user",content:_});let O=await fetch(`http://127.0.0.1:${t.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.APIKEY,"content-type":"application/json"},body:JSON.stringify(A.body)});if(!O.ok)return;let k=O.body.pipeThrough(new Jm).getReader();for(;;)try{let{value:Q,done:M}=await k.read();if(M)break;let G=Q;if(["message_start","message_stop"].includes(G.event))continue;if(!R.desiredSize)break;R.enqueue(G)}catch(Q){if(Q.name==="AbortError"||Q.code==="ERR_STREAM_PREMATURE_CLOSE"){E.abort();break}throw Q}return}return F}catch(O){if(console.error("Unexpected error in stream processing:",O),O.code==="ERR_STREAM_PREMATURE_CLOSE"){E.abort();return}throw O}}).pipeThrough(new kj))}let[m,C]=f.tee();return(async E=>{let D=E.pipeThrough(new TextDecoderStream).pipeThrough(new Jm).getReader();try{for(;;){let{done:w,value:x}=await D.read();if(w)break;let b=x.event,I=x.data;if(I?.usage){let B={...hd.get(g)||{},...I.usage};(I.usage.cache_read_input_tokens||I.usage.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:I.usage.cache_read_input_tokens,cache_creation:I.usage.cache_creation_input_tokens}),hd.put(g,B)}}}catch(w){w.name==="AbortError"||w.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",w)}finally{D.releaseLock()}})(C),p(null,m)}if(hd.put(g,f.usage),typeof f=="object")return f.error?p(f.error,null):p(f,null)}if(typeof f=="object"&&f.error)return p(f.error,null);p(null,f)}),d.addHook("onSend",async(A,h,f)=>{if(Cw.emit("onSend",A,h,f),h.statusCode>=400&&A.pathname?.endsWith("/v1/messages"))try{typeof f=="string"?A.errorResponseBody=f:f&&typeof f=="object"&&(A.errorResponseBody=JSON.stringify(f))}catch{}return f}),d.addHook("onResponse",async(A,h)=>{if(A.pathname?.endsWith("/v1/messages"))try{let f=bw(A),p=hd.get(f),g=fj(f),m=Hj(),C,E;if(h.statusCode>=400){C=A.errorMessage||h.errorMessage||A.error?.message||A.error?.toString?.()||void 0,E=A.errorResponseBody;let D=Wm(A);m.recordFailure(A.provider||"",D,C)}else{let D=Wm(A);m.recordSuccess(A.provider||"",D)}hj({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:f,provider:A.provider||"",originalModel:A.originalModel||A.body?.model||"",model:Wm(A),modelFamily:A.modelFamily||"",scenarioType:A.scenarioType||"default",stream:A.body?.stream??!1,inputTokens:p?.input_tokens||A.tokenCount||0,outputTokens:p?.output_tokens||0,cacheReadInputTokens:p?.cache_read_input_tokens||0,cacheCreationInputTokens:p?.cache_creation_input_tokens||0,ttft:g.ttft,tokensPerSecond:g.tokensPerSecond,durationMs:A.requestStartTime?Math.round(Dw.performance.now()-A.requestStartTime):0,status:h.statusCode<400?"success":"error",errorMessage:C,responseBody:E})}catch(f){console.error("Usage tracking error:",f)}}),process.on("uncaughtException",A=>{d.app.log.error("Uncaught exception:",A)}),process.on("unhandledRejection",(A,h)=>{d.app.log.error("Unhandled rejection at:",h,"reason:",A)}),d}async function Vj(){let e=await Ev();e.app.post("/api/restart",async()=>(setTimeout(async()=>{process.exit(0)},100),{success:!0,message:"Service restart initiated"})),await e.start()}require.main===Ey&&Vj().catch(e=>{console.error("Failed to start server:",e),process.exit(1)});});async function wv(e){try{let{stdout:t}=await bv("npm view @wengine-ai/claude-code-router version"),r=t.trim();return{hasUpdate:Yj(r,e)>0,latestVersion:r,changelog:""}}catch(t){return console.error("Error checking for updates:",t),{hasUpdate:!1,latestVersion:e,changelog:""}}}async function Bv(){try{let{stdout:e,stderr:t}=await bv("npm update -g @wengine-ai/claude-code-router");return t&&console.error("Update stderr:",t),console.log("Update stdout:",e),{success:!0,message:"Update completed successfully. Please restart the application to apply changes."}}catch(e){return console.error("Error performing update:",e),{success:!1,message:`Failed to perform update: ${e instanceof Error?e.message:"Unknown error"}`}}}function Yj(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let s=0;s<Math.max(r.length,n.length);s++){let o=s<r.length?r[s]:0,i=s<n.length?n[s]:0;if(o>i)return 1;if(o<i)return-1}return 0}var Dv,Cv,bv,Iv=Uf(()=>{"use strict";Dv=require("child_process"),Cv=require("util"),bv=(0,Cv.promisify)(Dv.exec)});var tp,yy=Uf(()=>{tp="2.0.45"});var Cy=Fr(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var xv=require("child_process"),zj=1024*1024,vv={exec(e,t){let r={maxBuffer:2*zj,windowsHide:!0};(0,xv.exec)(e,r,t)},spawn(e,t,r){return(0,xv.spawn)(e,t,r)},stripLine(e,t){let r=0;for(;t-- >0;){let n=e.indexOf(`
|
|
1231
|
+
Your response should consistently follow this rule whenever image-related analysis is requested.`});let r=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(o=>o.type==="image"||Array.isArray(o.content)&&o.content.some(i=>i.type==="image"))),n=1;r.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(o=>{o.type==="image"?(n0.storeImage(`${e.id}_Image#${n}`,o.source),o.type="text",delete o.source,o.text=`[Image #${n}]This is an image, if you need to view or analyze it, you need to extract the imageId`,n++):o.type==="text"&&o.text.includes("[Image #")?o.text=o.text.replace(/\[Image #\d+\]/g,""):o.type==="tool_result"&&Array.isArray(o.content)&&o.content.some(i=>i.type==="image")&&(n0.storeImage(`${e.id}_Image#${n}`,o.content[0].source),o.content=`[Image #${n}]This is an image, if you need to view or analyze it, you need to extract the imageId`,n++)})})}},Mj=new Pj,Uj=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},mv=new Uj;mv.registerAgent(Mj);var zm=mv,jj=require("node:events"),Dw=require("node:perf_hooks"),$j=VP(),Hj=$j.getHealthStore,Cw=new jj.EventEmitter;function bw(e){if(e.usageSessionId)return e.usageSessionId;try{let n=e.body?.metadata?.user_id;if(n&&typeof n=="string")try{let s=JSON.parse(n);if(s.session_id)return e.usageSessionId=s.session_id,e.usageSessionId}catch{let s=n.match(/_session_([a-f0-9-]+)/i);if(s)return e.usageSessionId=s[1],e.usageSessionId}}catch{}let t=e.headers?.["x-request-id"],r=Array.isArray(t)?t[0]:t;return e.usageSessionId=e.sessionId||(typeof r=="string"?r:void 0)||e.id||`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,e.usageSessionId}function Wm(e){return e.body?.model?Array.isArray(e.body.model)?e.body.model.join(","):e.body.model:Array.isArray(e.model)?e.model.join(","):e.model||""}async function qj(){let e=(0,xI.homedir)(),t=(0,vI.join)(e,".claude.json");if(!(0,YP.existsSync)(t)){let r={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await(0,JP.writeFile)(t,JSON.stringify(r,null,2))}}async function Gj(e,t){let r=t.plugins||t.Plugins||[];for(let n of r){let{name:s,enabled:o=!1,options:i={}}=n;switch(s){case"token-speed":EE.registerPlugin(dv,{enabled:o,outputHandlers:[{type:"temp-file",enabled:!0}],...i});break;default:console.warn(`Unknown plugin: ${s}`);break}}await EE.enablePlugins(e)}async function Ev(e={}){await qj(),await ty();let t=await _I(),r=t.Providers||t.providers||[],n=r&&r.length>0,s=t.HOST||"127.0.0.1";n?(s=t.HOST,t.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let o=t.PORT||3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):o,a=A=>(A>9?"":"0")+A,u=(A,h)=>{let f;A?typeof A=="number"?f=new Date(A):f=A:f=new Date;let p=f.getFullYear()+""+a(f.getMonth()+1),g=a(f.getDate()),m=a(f.getHours()),C=a(f.getMinutes());return`./logs/ccr-${p}${g}${m}${C}${a(f.getSeconds())}${h?`_${h}`:""}.log`},l;e.logger!==void 0?l=e.logger:t.LOG!==!1?(t.LOG===void 0&&(t.LOG=!0),l={level:t.LOG_LEVEL||"debug",stream:Fj(u,{path:Gm.HOME_DIR,maxFiles:3,interval:"1d",compress:!1,maxSize:"50M"})}):l=!1;let c=await(0,Gm.listPresets)(),d=await gj({jsonPath:Gm.CONFIG_FILE,initialConfig:{providers:t.Providers||t.providers,HOST:s,PORT:i,LOG_FILE:(0,vI.join)((0,xI.homedir)(),".claude-code-router","claude-code-router.log")},logger:l});return await Promise.allSettled(c.map(async A=>await d.registerNamespace(`/preset/${A.name}`,A.config))),await Gj(d,t),d.addHook("onRequest",async A=>{new URL(`http://127.0.0.1${A.url}`).pathname.endsWith("/v1/messages")&&!A.requestStartTime&&(A.requestStartTime=Dw.performance.now())}),d.addHook("preHandler",async(A,h)=>new Promise((f,p)=>{let g=m=>{m?p(m):f()};mj(t)(A,h,g).catch(p)})),d.addHook("preHandler",async(A,h)=>{let f=new URL(`http://127.0.0.1${A.url}`);A.pathname=f.pathname,A.pathname.endsWith("/v1/messages")&&A.pathname!=="/v1/messages"&&(A.preset=A.pathname.replace("/v1/messages","").replace("/",""))}),d.addHook("preHandler",async(A,h)=>{if(A.pathname.endsWith("/v1/messages")){let f=[];for(let p of zm.getAllAgents())p.shouldHandle(A,t)&&(f.push(p.name),p.reqHandler(A,t),p.tools.size&&(A.body?.tools?.length||(A.body.tools=[]),A.body.tools.unshift(...Array.from(p.tools.values()).map(g=>({name:g.name,description:g.description,input_schema:g.input_schema})))));f.length&&(A.agents=f)}}),d.addHook("onError",async(A,h,f)=>{A.errorMessage=f?.message||f?.toString?.()||"Unknown error",Cw.emit("onError",A,h,f)}),d.addHook("onSend",(A,h,f,p)=>{if(A.pathname?.endsWith("/v1/messages")){let g=bw(A);if(f instanceof ReadableStream){if(A.agents){let E=new AbortController,D=f.pipeThrough(new Jm),w,x=-1,b="",I="",B="",_=[],v=[];return p(null,Tj(D,async(F,R)=>{try{if(F.event==="content_block_start"&&F?.data?.content_block?.name){let O=A.agents.find(k=>zm.getAgent(k)?.tools.get(F.data.content_block.name));if(O){w=zm.getAgent(O),x=F.data.index,b=F.data.content_block.name,B=F.data.content_block.id;return}}if(x>-1&&F.data.index===x&&F.data?.delta?.type==="input_json_delta"){I+=F.data?.delta?.partial_json;return}if(x>-1&&F.data.index===x&&F.data.type==="content_block_stop"){try{let O=Rj.default.parse(I);v.push({type:"tool_use",id:B,name:b,input:O});let k=await w?.tools.get(b)?.handler(O,{req:A,config:t});_.push({tool_use_id:B,type:"tool_result",content:k}),w=void 0,x=-1,b="",I="",B=""}catch(O){console.log(O)}return}if(F.event==="message_delta"&&_.length){A.body.messages.push({role:"assistant",content:v}),A.body.messages.push({role:"user",content:_});let O=await fetch(`http://127.0.0.1:${t.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.APIKEY,"content-type":"application/json"},body:JSON.stringify(A.body)});if(!O.ok)return;let k=O.body.pipeThrough(new Jm).getReader();for(;;)try{let{value:Q,done:M}=await k.read();if(M)break;let G=Q;if(["message_start","message_stop"].includes(G.event))continue;if(!R.desiredSize)break;R.enqueue(G)}catch(Q){if(Q.name==="AbortError"||Q.code==="ERR_STREAM_PREMATURE_CLOSE"){E.abort();break}throw Q}return}return F}catch(O){if(console.error("Unexpected error in stream processing:",O),O.code==="ERR_STREAM_PREMATURE_CLOSE"){E.abort();return}throw O}}).pipeThrough(new kj))}let[m,C]=f.tee();return(async E=>{let D=E.pipeThrough(new TextDecoderStream).pipeThrough(new Jm).getReader();try{for(;;){let{done:w,value:x}=await D.read();if(w)break;let b=x.event,I=x.data;if(I?.usage){let B={...hd.get(g)||{},...I.usage};(I.usage.cache_read_input_tokens||I.usage.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:I.usage.cache_read_input_tokens,cache_creation:I.usage.cache_creation_input_tokens}),hd.put(g,B)}}}catch(w){w.name==="AbortError"||w.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",w)}finally{D.releaseLock()}})(C),p(null,m)}if(hd.put(g,f.usage),typeof f=="object")return f.error?p(f.error,null):p(f,null)}if(typeof f=="object"&&f.error)return p(f.error,null);p(null,f)}),d.addHook("onSend",async(A,h,f)=>{if(Cw.emit("onSend",A,h,f),h.statusCode>=400&&A.pathname?.endsWith("/v1/messages"))try{typeof f=="string"?A.errorResponseBody=f:f&&typeof f=="object"&&(A.errorResponseBody=JSON.stringify(f))}catch{}return f}),d.addHook("onResponse",async(A,h)=>{if(A.pathname?.endsWith("/v1/messages"))try{let f=bw(A),p=hd.get(f),g=fj(f),m=Hj(),C,E;if(h.statusCode>=400){C=A.errorMessage||h.errorMessage||A.error?.message||A.error?.toString?.()||void 0,E=A.errorResponseBody;let D=Wm(A);m.recordFailure(A.provider||"",D,C)}else{let D=Wm(A);m.recordSuccess(A.provider||"",D)}hj({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:f,provider:A.provider||"",originalModel:A.originalModel||A.body?.model||"",model:Wm(A),modelFamily:A.modelFamily||"",scenarioType:A.scenarioType||"default",stream:A.body?.stream??!1,inputTokens:p?.input_tokens||A.tokenCount||0,outputTokens:p?.output_tokens||0,cacheReadInputTokens:p?.cache_read_input_tokens||0,cacheCreationInputTokens:p?.cache_creation_input_tokens||0,ttft:g.ttft,tokensPerSecond:g.tokensPerSecond,durationMs:A.requestStartTime?Math.round(Dw.performance.now()-A.requestStartTime):0,status:h.statusCode<400?"success":"error",errorMessage:C,responseBody:E})}catch(f){console.error("Usage tracking error:",f)}}),process.on("uncaughtException",A=>{d.app.log.error("Uncaught exception:",A)}),process.on("unhandledRejection",(A,h)=>{d.app.log.error("Unhandled rejection at:",h,"reason:",A)}),d}async function Vj(){let e=await Ev();e.app.post("/api/restart",async()=>(setTimeout(async()=>{process.exit(0)},100),{success:!0,message:"Service restart initiated"})),await e.start()}require.main===Ey&&Vj().catch(e=>{console.error("Failed to start server:",e),process.exit(1)});});async function wv(e){try{let{stdout:t}=await bv("npm view @wengine-ai/claude-code-router version"),r=t.trim();return{hasUpdate:Yj(r,e)>0,latestVersion:r,changelog:""}}catch(t){return console.error("Error checking for updates:",t),{hasUpdate:!1,latestVersion:e,changelog:""}}}async function Bv(){try{let{stdout:e,stderr:t}=await bv("npm update -g @wengine-ai/claude-code-router");return t&&console.error("Update stderr:",t),console.log("Update stdout:",e),{success:!0,message:"Update completed successfully. Please restart the application to apply changes."}}catch(e){return console.error("Error performing update:",e),{success:!1,message:`Failed to perform update: ${e instanceof Error?e.message:"Unknown error"}`}}}function Yj(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let s=0;s<Math.max(r.length,n.length);s++){let o=s<r.length?r[s]:0,i=s<n.length?n[s]:0;if(o>i)return 1;if(o<i)return-1}return 0}var Dv,Cv,bv,Iv=Uf(()=>{"use strict";Dv=require("child_process"),Cv=require("util"),bv=(0,Cv.promisify)(Dv.exec)});var tp,yy=Uf(()=>{tp="2.0.47"});var Cy=Fr(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var xv=require("child_process"),zj=1024*1024,vv={exec(e,t){let r={maxBuffer:2*zj,windowsHide:!0};(0,xv.exec)(e,r,t)},spawn(e,t,r){return(0,xv.spawn)(e,t,r)},stripLine(e,t){let r=0;for(;t-- >0;){let n=e.indexOf(`
|
|
1232
1232
|
`,r);n>=0&&(r=n+1)}return r>0?e.substring(r):e},split(e,t){let r=e.trim().split(/\s+/);return r.length>t&&(r[t-1]=r.slice(t-1).join(" ")),r},extractColumns(e,t,r){let n=e.split(/(\r\n|\n|\r)/),s=[];return r||(r=Math.max.apply(null,t)+1),n.forEach(o=>{let i=vv.split(o,r),a=[];t.forEach(u=>{a.push(i[u]||"")}),s.push(a)}),s},parseTable(e){let t=e.split(/(\r\n\r\n|\r\n\n|\n\r\n|\n\n)/).filter(r=>r&&r.trim().length>0).map(r=>r.split(/(\r\n|\n|\r)/).filter(n=>n.trim().length>0));return t.forEach(r=>{for(let n=0;r[n];){let s=r[n];s.startsWith(" ")?(r[n-1]+=s.trimLeft(),r.splice(n,1)):n+=1}}),t.map(r=>{let n={};return r.forEach(s=>{let o=s.indexOf(":"),i=s.slice(0,o).trim();n[i]=s.slice(o+1).trim()}),n})}};Dy.default=vv});var Sv=Fr((_v,rp)=>{(function(e,t){"use strict";typeof define=="function"&&define.amd?define(t):typeof rp=="object"&&rp.exports?rp.exports=t():e.log=t()})(_v,function(){"use strict";var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},o=null;function i(f,p){var g=f[p];if(typeof g.bind=="function")return g.bind(f);try{return Function.prototype.bind.call(g,f)}catch{return function(){return Function.prototype.apply.apply(g,[f,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function u(f){return f==="debug"&&(f="log"),typeof console===t?!1:f==="trace"&&r?a:console[f]!==void 0?i(console,f):console.log!==void 0?i(console,"log"):e}function l(){for(var f=this.getLevel(),p=0;p<n.length;p++){var g=n[p];this[g]=p<f?e:this.methodFactory(g,f,this.name)}if(this.log=this.debug,typeof console===t&&f<this.levels.SILENT)return"No console available for logging"}function c(f){return function(){typeof console!==t&&(l.call(this),this[f].apply(this,arguments))}}function d(f,p,g){return u(f)||c.apply(this,arguments)}function A(f,p){var g=this,m,C,E,D="loglevel";typeof f=="string"?D+=":"+f:typeof f=="symbol"&&(D=void 0);function w(_){var v=(n[_]||"silent").toUpperCase();if(!(typeof window===t||!D)){try{window.localStorage[D]=v;return}catch{}try{window.document.cookie=encodeURIComponent(D)+"="+v+";"}catch{}}}function x(){var _;if(!(typeof window===t||!D)){try{_=window.localStorage[D]}catch{}if(typeof _===t)try{var v=window.document.cookie,F=encodeURIComponent(D),R=v.indexOf(F+"=");R!==-1&&(_=/^([^;]+)/.exec(v.slice(R+F.length+1))[1])}catch{}return g.levels[_]===void 0&&(_=void 0),_}}function b(){if(!(typeof window===t||!D)){try{window.localStorage.removeItem(D)}catch{}try{window.document.cookie=encodeURIComponent(D)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function I(_){var v=_;if(typeof v=="string"&&g.levels[v.toUpperCase()]!==void 0&&(v=g.levels[v.toUpperCase()]),typeof v=="number"&&v>=0&&v<=g.levels.SILENT)return v;throw new TypeError("log.setLevel() called with invalid level: "+_)}g.name=f,g.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},g.methodFactory=p||d,g.getLevel=function(){return E??C??m},g.setLevel=function(_,v){return E=I(_),v!==!1&&w(E),l.call(g)},g.setDefaultLevel=function(_){C=I(_),x()||g.setLevel(_,!1)},g.resetLevel=function(){E=null,b(),l.call(g)},g.enableAll=function(_){g.setLevel(g.levels.TRACE,_)},g.disableAll=function(_){g.setLevel(g.levels.SILENT,_)},g.rebuild=function(){if(o!==g&&(m=I(o.getLevel())),l.call(g),o===g)for(var _ in s)s[_].rebuild()},m=I(o?o.getLevel():"WARN");var B=x();B!=null&&(E=I(B)),l.call(g)}o=new A,o.getLogger=function(p){if(typeof p!="symbol"&&typeof p!="string"||p==="")throw new TypeError("You must supply a name when creating a logger.");var g=s[p];return g||(g=s[p]=new A(p,o.methodFactory)),g};var h=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=h),o},o.getLoggers=function(){return s},o.default=o,o})});var by=Fr(Md=>{"use strict";var Wj=Md&&Md.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Md,"__esModule",{value:!0});var Kj=Wj(Sv());Md.default=Kj.default});var Tv=Fr(Qo=>{"use strict";var Zj=Qo&&Qo.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Xj=Qo&&Qo.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Fv=Qo&&Qo.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),s=0;s<n.length;s++)n[s]!=="default"&&Zj(r,t,n[s]);return Xj(r,t),r}})(),kv=Qo&&Qo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qo,"__esModule",{value:!0});var e7=Fv(require("os")),np=Fv(require("fs")),Gs=kv(Cy()),t7=kv(by()),r7=e=>new Promise((t,r)=>{np.existsSync(e)?t():np.mkdir(e,n=>{n?r(n):t()})}),Lc={darwin(e){return new Promise((t,r)=>{Gs.default.exec("netstat -anv -p TCP && netstat -anv -p UDP",function(n,s,o){if(n)r(n);else{let i=o.toString().trim();if(i){r(new Error(i));return}let a=Gs.default.stripLine(s.toString(),1),u=a.slice(0,a.indexOf(`
|
|
1233
1233
|
`)),l=Gs.default.stripLine(a,1),c=u.indexOf("rxbytes")>=0?10:8,d=Gs.default.extractColumns(l,[0,3,c],10).filter(A=>!!String(A[0]).match(/^(udp|tcp)/)).find(A=>{let h=String(A[1]).match(/\.(\d+)$/);return!!(h&&h[1]===String(e))});d&&d[2].length?t(parseInt(d[2],10)):r(new Error(`pid of port (${e}) not found`))}})})},linux(e){return new Promise((t,r)=>{Gs.default.exec("netstat -tunlp",function(s,o,i){if(s)r(s);else{let a=i.toString().trim();a&&t7.default.warn(a);let u=Gs.default.stripLine(o.toString(),2),l=Gs.default.extractColumns(u,[3,6],7).find(c=>{let d=String(c[0]).match(/:(\d+)$/);return!!(d&&d[1]===String(e))});if(l&&l[1]){let c=l[1].split("/",1)[0];c.length?t(parseInt(c,10)):r(new Error(`pid of port (${e}) not found`))}else r(new Error(`pid of port (${e}) not found`))}})})},win32(e){return new Promise((t,r)=>{Gs.default.exec("netstat -ano",function(n,s,o){if(n)r(n);else{let i=o.toString().trim();if(i){r(new Error(i));return}let a=Gs.default.stripLine(s.toString(),4),u=Gs.default.extractColumns(a,[1,4],5).find(l=>{let c=String(l[0]).match(/:(\d+)$/);return!!(c&&c[1]===String(e))});u&&u[1].length&&parseInt(u[1],10)>0?t(parseInt(u[1],10)):r(new Error(`pid of port (${e}) not found`))}})})},android(e){return new Promise((t,r)=>{let n=e7.tmpdir()+"/.find-process",s=n+"/"+process.pid,o='netstat -tunp >> "'+s+'"';r7(n).then(()=>{Gs.default.exec(o,()=>{np.readFile(s,"utf8",(i,a)=>{if(np.unlink(s,()=>{}),i)r(i);else{a=Gs.default.stripLine(a,2);let u=Gs.default.extractColumns(a,[3,6],7).find(l=>{let c=String(l[0]).match(/:(\d+)$/);return!!(c&&c[1]===String(e))});if(u&&u[1]){let l=u[1].split("/",1)[0];l.length?t(parseInt(l,10)):r(new Error(`pid of port (${e}) not found`))}else r(new Error(`pid of port (${e}) not found`))}})})})})}};Lc.freebsd=Lc.darwin;Lc.sunos=Lc.darwin;function n7(e){let t=process.platform;return new Promise((r,n)=>{if(!(t in Lc))return n(new Error(`platform ${t} is unsupported`));let s=Lc[t];s(e).then(r,n)})}Qo.default=n7});var Nv=Fr(No=>{"use strict";var i7=No&&No.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),s7=No&&No.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),o7=No&&No.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),s=0;s<n.length;s++)n[s]!=="default"&&i7(r,t,n[s]);return s7(r,t),r}})(),a7=No&&No.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(No,"__esModule",{value:!0});var ip=o7(require("path")),ku=a7(Cy());function wy(e,t){return t?e&&e.match?e.match(t)!==null:!1:!0}function Rv(e){let t=e.split(ip.sep),r=t[t.length-1];r&&(t[t.length-1]=r.split(" ")[0]);let n=[];for(let s of t){let o=s.indexOf(" -");if(o>=0){n.push(s.substring(0,o).trim());break}else if(s.endsWith(" ")){n.push(s.trim());break}n.push(s)}return n.join(ip.sep)}function Qv(e){if(process.platform==="darwin"){let t=e.indexOf(".app/");if(t>=0)return ip.basename(e.substring(0,t))}return ip.basename(e)}var bl={darwin(e){return new Promise((t,r)=>{let n;"pid"in e&&e.pid!==void 0?n=`ps -p ${e.pid} -ww -o pid,ppid,uid,gid,args`:n="ps ax -ww -o pid,ppid,uid,gid,args",ku.default.exec(n,function(s,o,i){if(s)"pid"in e&&e.pid!==void 0?t([]):r(s);else{let a=i.toString().trim();if(a){r(new Error(a));return}let u=ku.default.stripLine(o.toString(),1),c=ku.default.extractColumns(u,[0,1,2,3,4],5).filter(d=>d[0]&&e.pid!==void 0?d[0]===String(e.pid):d[4]&&e.name?wy(d[4],e.name):!!d[0]).map(d=>{let A=String(d[4]),h=Rv(A);return{pid:parseInt(d[0],10),ppid:parseInt(d[1],10),uid:parseInt(d[2],10),gid:parseInt(d[3],10),name:Qv(h),bin:h,cmd:d[4]}});e.config.strict&&e.name&&(c=c.filter(d=>d.name===e.name)),t(c)}})})},win32(e){return new Promise((t,r)=>{let n="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance -className win32_process | select Name,ProcessId,ParentProcessId,CommandLine,ExecutablePath",s=[],o=ku.default.spawn("powershell.exe",["/c",n],{detached:!1,windowsHide:!0});o.stdout.on("data",i=>{s.push(i.toString())}),o.on("error",i=>{r(new Error("Command '"+n+"' failed with reason: "+i.toString()))}),o.on("close",i=>{if(i!==0)return r(new Error("Command '"+n+"' terminated with code: "+i));let a=ku.default.parseTable(s.join("")).filter(u=>{if(e.pid!==void 0)return u.ProcessId===String(e.pid);if(e.name){let l=u.Name||"";return e.config.strict?l===e.name||l.endsWith(".exe")&&l.slice(0,-4)===e.name:wy(u.CommandLine||l,e.name)}else return!0}).map(u=>({pid:parseInt(u.ProcessId,10),ppid:parseInt(u.ParentProcessId,10),bin:u.ExecutablePath,name:u.Name||"",cmd:u.CommandLine}));t(a)})})},android(e){return new Promise((t,r)=>{ku.default.exec("ps",function(s,o,i){if(s)e.pid!==void 0?t([]):r(s);else{let a=i.toString().trim();if(a){r(new Error(a));return}let u=ku.default.stripLine(o.toString(),1),c=ku.default.extractColumns(u,[0,3],4).filter(d=>d[0]&&e.pid!==void 0?d[0]===String(e.pid):d[1]&&e.name?wy(d[1],e.name):!!d[0]).map(d=>{let A=String(d[1]),h=Rv(A);return{pid:parseInt(d[0],10),ppid:0,name:Qv(h),bin:h,cmd:d[1]}});e.config.strict&&e.name&&(c=c.filter(d=>d.name===e.name)),t(c)}})})}};bl.linux=bl.darwin;bl.sunos=bl.darwin;bl.freebsd=bl.darwin;function u7(e){let t=process.platform,r=bl[t];return r?r(e):Promise.reject(new Error(`Platform "${t}" is not supported`))}No.default=u7});var Lv=Fr(Ud=>{"use strict";var Iy=Ud&&Ud.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ud,"__esModule",{value:!0});var l7=Iy(Tv()),Ov=Iy(Nv()),c7=Iy(by()),By={port(e,t){return(0,l7.default)(e).then(r=>By.pid(r,t),()=>[])},pid(e,t){return(0,Ov.default)({pid:e,config:t})},name(e,t){return(0,Ov.default)({name:e,config:t,skipSelf:!0})}};function h7(e,t,r){let n=Object.assign({logLevel:"warn",strict:typeof r=="boolean"?r:!1},typeof r=="object"?r:{});return n.logLevel&&c7.default.setLevel(n.logLevel),new Promise((s,o)=>{if(!(e in By))o(new Error(`do not support find by "${e}"`));else{let i=/^\d+$/.test(String(t));e==="pid"&&!i?o(new Error("pid must be a number")):e==="port"&&!i?o(new Error("port must be a number")):By[e](t,n).then(s,o)}})}Ud.default=h7});var Mv=Fr(Pv=>{"use strict";Object.defineProperty(Pv,"__esModule",{value:!0})});var Uv=Fr(Oo=>{"use strict";var d7=Oo&&Oo.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),A7=Oo&&Oo.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&d7(t,e,r)},f7=Oo&&Oo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Oo,"__esModule",{value:!0});Oo.default=void 0;var p7=Lv();Object.defineProperty(Oo,"default",{enumerable:!0,get:function(){return f7(p7).default}});A7(Mv(),Oo)});function $v(){let e=0;(0,cs.existsSync)(Vi.REFERENCE_COUNT_FILE)&&(e=parseInt((0,cs.readFileSync)(Vi.REFERENCE_COUNT_FILE,"utf-8"))||0),e++,(0,cs.writeFileSync)(Vi.REFERENCE_COUNT_FILE,e.toString())}function xy(){let e=0;(0,cs.existsSync)(Vi.REFERENCE_COUNT_FILE)&&(e=parseInt((0,cs.readFileSync)(Vi.REFERENCE_COUNT_FILE,"utf-8"))||0),e=Math.max(0,e-1),(0,cs.writeFileSync)(Vi.REFERENCE_COUNT_FILE,e.toString())}function Hv(){return(0,cs.existsSync)(Vi.REFERENCE_COUNT_FILE)&&parseInt((0,cs.readFileSync)(Vi.REFERENCE_COUNT_FILE,"utf-8"))||0}function wl(){if(!(0,cs.existsSync)(Vi.PID_FILE))return!1;let e;try{let t=(0,cs.readFileSync)(Vi.PID_FILE,"utf-8");if(e=parseInt(t,10),isNaN(e))return Ha(),!1}catch{return!1}try{if(process.platform==="win32"){let t=`tasklist /FI "PID eq ${e}"`;return(0,jv.execSync)(t,{stdio:"pipe"}).toString().includes(e.toString())?!0:(Ha(),!1)}else return process.kill(e,0),!0}catch{return Ha(),!1}}function Ha(){if((0,cs.existsSync)(Vi.PID_FILE))try{require("fs").unlinkSync(Vi.PID_FILE)}catch{}}function qv(){if(!(0,cs.existsSync)(Vi.PID_FILE))return null;try{let e=parseInt((0,cs.readFileSync)(Vi.PID_FILE,"utf-8"));return isNaN(e)?null:e}catch{return null}}async function sp(){let e=qv(),t=await wl(),n=(await ys()).PORT||3456;return{running:t,pid:e,port:n,endpoint:`http://127.0.0.1:${n}`,pidFile:Vi.PID_FILE,referenceCount:Hv()}}async function Gv(){if(Hv()===0){let t=qv();if(t&&await wl())try{process.kill(t,"SIGTERM")}catch{}}}var cs,Vi,g7,jv,jd=Uf(()=>{"use strict";cs=require("fs"),Vi=en(to());Tu();g7=en(Uv()),jv=require("child_process")});var Xv={};S1(Xv,{backupConfigFile:()=>Kv,getSettingsPath:()=>ky,initConfig:()=>m7,initDir:()=>Wv,readConfigFile:()=>ys,restartService:()=>Fy,run:()=>Sy,writeConfigFile:()=>Zv});var Ts,Vv,Ru,Yv,Jv,si,zv,Pc,_y,vy,$d,Wv,ys,Kv,Zv,m7,Sy,Fy,ky,Tu=Uf(()=>{"use strict";Ts=en(require("node:fs/promises")),Vv=en(Gf()),Ru=en(require("node:path")),Yv=require("node:crypto"),Jv=en(require("node:os")),si=en(to()),zv=en(yv()),Pc=require("fs");Iv();yy();_y=require("child_process");jd();vy=e=>{if(typeof e=="string")return e.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(t,r,n)=>{let s=r||n;return process.env[s]||t});if(Array.isArray(e))return e.map(vy);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=vy(n);return t}return e},$d=async e=>{try{await Ts.default.access(e)}catch{await Ts.default.mkdir(e,{recursive:!0})}},Wv=async()=>{await $d(si.HOME_DIR),await $d(si.PLUGINS_DIR),await $d(si.PRESETS_DIR),await $d(Ru.default.join(si.HOME_DIR,"logs"))},ys=async()=>{try{let e=await Ts.default.readFile(si.CONFIG_FILE,"utf-8");try{let t=Vv.default.parse(e);return vy(t)}catch(t){console.error(`Failed to parse config file at ${si.CONFIG_FILE}`),console.error("Error details:",t.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(e){if(e.code==="ENOENT")try{await Wv();let t=await Kv();t&&console.log(`Backed up existing configuration file to ${t}`);let r={PORT:3456,Providers:[],Router:{}};return await Zv(r),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),r}catch(t){console.error("Failed to create default configuration:",t.message),process.exit(1)}else console.error(`Failed to read config file at ${si.CONFIG_FILE}`),console.error("Error details:",e.message),process.exit(1)}},Kv=async()=>{try{if(await Ts.default.access(si.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let e=new Date().toISOString().replace(/[:.]/g,"-"),t=`${si.CONFIG_FILE}.${e}.bak`;await Ts.default.copyFile(si.CONFIG_FILE,t);try{let r=Ru.default.dirname(si.CONFIG_FILE),n=Ru.default.basename(si.CONFIG_FILE),o=(await Ts.default.readdir(r)).filter(i=>i.startsWith(n)&&i.endsWith(".bak")).sort().reverse();if(o.length>3)for(let i=3;i<o.length;i++){let a=Ru.default.join(r,o[i]);await Ts.default.unlink(a)}}catch(r){console.warn("Failed to clean up old backups:",r)}return t}}catch(e){console.error("Failed to backup config file:",e)}return null},Zv=async e=>{await $d(si.HOME_DIR);let t=`${JSON.stringify(e,null,2)}`;await Ts.default.writeFile(si.CONFIG_FILE,t)},m7=async()=>{let e=await ys();return Object.assign(process.env,e),e},Sy=async(e=[])=>{if(wl()){console.log("claude-code-router server is running");return}let r=await(0,zv.getServer)(),n=r.app;(0,Pc.writeFileSync)(si.PID_FILE,process.pid.toString()),n.post("/api/update/perform",async()=>await Bv()),n.get("/api/update/check",async()=>await wv(tp)),n.post("/api/restart",async()=>(setTimeout(async()=>{(0,_y.spawn)("ccr",["restart"],{detached:!0,stdio:"ignore"}).unref()},100),{success:!0,message:"Service restart initiated"})),await r.start()},Fy=async()=>{try{let r=parseInt((0,Pc.readFileSync)(si.PID_FILE,"utf-8"));if(process.kill(r),Ha(),(0,Pc.existsSync)(si.REFERENCE_COUNT_FILE))try{await Ts.default.unlink(si.REFERENCE_COUNT_FILE)}catch{}console.log("claude code router service has been stopped.")}catch{console.log("Service was not running or failed to stop."),Ha()}console.log("Starting claude code router service...");let e=Ru.default.join(__dirname,"cli.js"),t=(0,_y.spawn)("node",[e,"start"],{detached:!0,stdio:"ignore"});t.on("error",r=>{throw console.error("Failed to start service:",r),r}),t.unref(),console.log("\u2705 Service started successfully in the background.")},ky=async e=>{let t=(0,Yv.createHash)("sha256").update(e,"utf-8").digest("hex"),r=Ru.default.join(Jv.default.tmpdir(),"claude-code-router"),n=`ccr-settings-${t}.json`,s=Ru.default.join(r,n);try{await Ts.default.access(r)}catch{await Ts.default.mkdir(r,{recursive:!0})}try{return await Ts.default.access(s),s}catch{return await Ts.default.writeFile(s,e,"utf-8"),s}}});var qd=Fr((pX,o_)=>{var D7=require("node:tty"),C7=D7?.WriteStream?.prototype?.hasColors?.()??!1,Dn=(e,t)=>{if(!C7)return s=>s;let r=`\x1B[${e}m`,n=`\x1B[${t}m`;return s=>{let o=s+"",i=o.indexOf(n);if(i===-1)return r+o+n;let a=r,u=0,c=(t===22?n:"")+r;for(;i!==-1;)a+=o.slice(u,i)+c,u=i+n.length,i=o.indexOf(n,u);return a+=o.slice(u)+n,a}},mn={};mn.reset=Dn(0,0);mn.bold=Dn(1,22);mn.dim=Dn(2,22);mn.italic=Dn(3,23);mn.underline=Dn(4,24);mn.overline=Dn(53,55);mn.inverse=Dn(7,27);mn.hidden=Dn(8,28);mn.strikethrough=Dn(9,29);mn.black=Dn(30,39);mn.red=Dn(31,39);mn.green=Dn(32,39);mn.yellow=Dn(33,39);mn.blue=Dn(34,39);mn.magenta=Dn(35,39);mn.cyan=Dn(36,39);mn.white=Dn(37,39);mn.gray=Dn(90,39);mn.bgBlack=Dn(40,49);mn.bgRed=Dn(41,49);mn.bgGreen=Dn(42,49);mn.bgYellow=Dn(43,49);mn.bgBlue=Dn(44,49);mn.bgMagenta=Dn(45,49);mn.bgCyan=Dn(46,49);mn.bgWhite=Dn(47,49);mn.bgGray=Dn(100,49);mn.redBright=Dn(91,39);mn.greenBright=Dn(92,39);mn.yellowBright=Dn(93,39);mn.blueBright=Dn(94,39);mn.magentaBright=Dn(95,39);mn.cyanBright=Dn(96,39);mn.whiteBright=Dn(97,39);mn.bgRedBright=Dn(101,49);mn.bgGreenBright=Dn(102,49);mn.bgYellowBright=Dn(103,49);mn.bgBlueBright=Dn(104,49);mn.bgMagentaBright=Dn(105,49);mn.bgCyanBright=Dn(106,49);mn.bgWhiteBright=Dn(107,49);o_.exports=mn});var A_=Fr((QX,d_)=>{"use strict";d_.exports=S7;function _7(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};return e?(Object.keys(t).forEach(function(r){e[r]||(e[r]=t[r])}),e):t}function S7(e){let t=_7(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var p_=Fr((NX,f_)=>{"use strict";f_.exports=({onlyFirst:e=!1}={})=>{let t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}});var fp=Fr((OX,g_)=>{"use strict";var F7=p_();g_.exports=e=>typeof e=="string"?e.replace(F7(),""):e});var E_=Fr((LX,Oy)=>{"use strict";var m_=e=>Number.isNaN(e)?!1:e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141);Oy.exports=m_;Oy.exports.default=m_});var D_=Fr((PX,y_)=>{"use strict";y_.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var b_=Fr((MX,Ly)=>{"use strict";var k7=fp(),T7=E_(),R7=D_(),C_=e=>{if(typeof e!="string"||e.length===0||(e=k7(e),e.length===0))return 0;e=e.replace(R7()," ");let t=0;for(let r=0;r<e.length;r++){let n=e.codePointAt(r);n<=31||n>=127&&n<=159||n>=768&&n<=879||(n>65535&&r++,t+=T7(n)?2:1)}return t};Ly.exports=C_;Ly.exports.default=C_});var B_=Fr((UX,w_)=>{"use strict";w_.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Py=Fr((jX,x_)=>{var Gd=B_(),I_={};for(let e of Object.keys(Gd))I_[Gd[e]]=e;var Gr={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};x_.exports=Gr;for(let e of Object.keys(Gr)){if(!("channels"in Gr[e]))throw new Error("missing channels property: "+e);if(!("labels"in Gr[e]))throw new Error("missing channel labels property: "+e);if(Gr[e].labels.length!==Gr[e].channels)throw new Error("channel and label counts mismatch: "+e);let{channels:t,labels:r}=Gr[e];delete Gr[e].channels,delete Gr[e].labels,Object.defineProperty(Gr[e],"channels",{value:t}),Object.defineProperty(Gr[e],"labels",{value:r})}Gr.rgb.hsl=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255,s=Math.min(t,r,n),o=Math.max(t,r,n),i=o-s,a,u;o===s?a=0:t===o?a=(r-n)/i:r===o?a=2+(n-t)/i:n===o&&(a=4+(t-r)/i),a=Math.min(a*60,360),a<0&&(a+=360);let l=(s+o)/2;return o===s?u=0:l<=.5?u=i/(o+s):u=i/(2-o-s),[a,u*100,l*100]};Gr.rgb.hsv=function(e){let t,r,n,s,o,i=e[0]/255,a=e[1]/255,u=e[2]/255,l=Math.max(i,a,u),c=l-Math.min(i,a,u),d=function(A){return(l-A)/6/c+1/2};return c===0?(s=0,o=0):(o=c/l,t=d(i),r=d(a),n=d(u),i===l?s=n-r:a===l?s=1/3+t-n:u===l&&(s=2/3+r-t),s<0?s+=1:s>1&&(s-=1)),[s*360,o*100,l*100]};Gr.rgb.hwb=function(e){let t=e[0],r=e[1],n=e[2],s=Gr.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(r,n));return n=1-1/255*Math.max(t,Math.max(r,n)),[s,o*100,n*100]};Gr.rgb.cmyk=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255,s=Math.min(1-t,1-r,1-n),o=(1-t-s)/(1-s)||0,i=(1-r-s)/(1-s)||0,a=(1-n-s)/(1-s)||0;return[o*100,i*100,a*100,s*100]};function Q7(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}Gr.rgb.keyword=function(e){let t=I_[e];if(t)return t;let r=1/0,n;for(let s of Object.keys(Gd)){let o=Gd[s],i=Q7(e,o);i<r&&(r=i,n=s)}return n};Gr.keyword.rgb=function(e){return Gd[e]};Gr.rgb.xyz=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let s=t*.4124+r*.3576+n*.1805,o=t*.2126+r*.7152+n*.0722,i=t*.0193+r*.1192+n*.9505;return[s*100,o*100,i*100]};Gr.rgb.lab=function(e){let t=Gr.rgb.xyz(e),r=t[0],n=t[1],s=t[2];r/=95.047,n/=100,s/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,s=s>.008856?s**(1/3):7.787*s+16/116;let o=116*n-16,i=500*(r-n),a=200*(n-s);return[o,i,a]};Gr.hsl.rgb=function(e){let t=e[0]/360,r=e[1]/100,n=e[2]/100,s,o,i;if(r===0)return i=n*255,[i,i,i];n<.5?s=n*(1+r):s=n+r-n*r;let a=2*n-s,u=[0,0,0];for(let l=0;l<3;l++)o=t+1/3*-(l-1),o<0&&o++,o>1&&o--,6*o<1?i=a+(s-a)*6*o:2*o<1?i=s:3*o<2?i=a+(s-a)*(2/3-o)*6:i=a,u[l]=i*255;return u};Gr.hsl.hsv=function(e){let t=e[0],r=e[1]/100,n=e[2]/100,s=r,o=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,s*=o<=1?o:2-o;let i=(n+r)/2,a=n===0?2*s/(o+s):2*r/(n+r);return[t,a*100,i*100]};Gr.hsv.rgb=function(e){let t=e[0]/60,r=e[1]/100,n=e[2]/100,s=Math.floor(t)%6,o=t-Math.floor(t),i=255*n*(1-r),a=255*n*(1-r*o),u=255*n*(1-r*(1-o));switch(n*=255,s){case 0:return[n,u,i];case 1:return[a,n,i];case 2:return[i,n,u];case 3:return[i,a,n];case 4:return[u,i,n];case 5:return[n,i,a]}};Gr.hsv.hsl=function(e){let t=e[0],r=e[1]/100,n=e[2]/100,s=Math.max(n,.01),o,i;i=(2-r)*n;let a=(2-r)*s;return o=r*s,o/=a<=1?a:2-a,o=o||0,i/=2,[t,o*100,i*100]};Gr.hwb.rgb=function(e){let t=e[0]/360,r=e[1]/100,n=e[2]/100,s=r+n,o;s>1&&(r/=s,n/=s);let i=Math.floor(6*t),a=1-n;o=6*t-i,(i&1)!==0&&(o=1-o);let u=r+o*(a-r),l,c,d;switch(i){default:case 6:case 0:l=a,c=u,d=r;break;case 1:l=u,c=a,d=r;break;case 2:l=r,c=a,d=u;break;case 3:l=r,c=u,d=a;break;case 4:l=u,c=r,d=a;break;case 5:l=a,c=r,d=u;break}return[l*255,c*255,d*255]};Gr.cmyk.rgb=function(e){let t=e[0]/100,r=e[1]/100,n=e[2]/100,s=e[3]/100,o=1-Math.min(1,t*(1-s)+s),i=1-Math.min(1,r*(1-s)+s),a=1-Math.min(1,n*(1-s)+s);return[o*255,i*255,a*255]};Gr.xyz.rgb=function(e){let t=e[0]/100,r=e[1]/100,n=e[2]/100,s,o,i;return s=t*3.2406+r*-1.5372+n*-.4986,o=t*-.9689+r*1.8758+n*.0415,i=t*.0557+r*-.204+n*1.057,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,s=Math.min(Math.max(0,s),1),o=Math.min(Math.max(0,o),1),i=Math.min(Math.max(0,i),1),[s*255,o*255,i*255]};Gr.xyz.lab=function(e){let t=e[0],r=e[1],n=e[2];t/=95.047,r/=100,n/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let s=116*r-16,o=500*(t-r),i=200*(r-n);return[s,o,i]};Gr.lab.xyz=function(e){let t=e[0],r=e[1],n=e[2],s,o,i;o=(t+16)/116,s=r/500+o,i=o-n/200;let a=o**3,u=s**3,l=i**3;return o=a>.008856?a:(o-16/116)/7.787,s=u>.008856?u:(s-16/116)/7.787,i=l>.008856?l:(i-16/116)/7.787,s*=95.047,o*=100,i*=108.883,[s,o,i]};Gr.lab.lch=function(e){let t=e[0],r=e[1],n=e[2],s;s=Math.atan2(n,r)*360/2/Math.PI,s<0&&(s+=360);let i=Math.sqrt(r*r+n*n);return[t,i,s]};Gr.lch.lab=function(e){let t=e[0],r=e[1],s=e[2]/360*2*Math.PI,o=r*Math.cos(s),i=r*Math.sin(s);return[t,o,i]};Gr.rgb.ansi16=function(e,t=null){let[r,n,s]=e,o=t===null?Gr.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let i=30+(Math.round(s/255)<<2|Math.round(n/255)<<1|Math.round(r/255));return o===2&&(i+=60),i};Gr.hsv.ansi16=function(e){return Gr.rgb.ansi16(Gr.hsv.rgb(e),e[2])};Gr.rgb.ansi256=function(e){let t=e[0],r=e[1],n=e[2];return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)};Gr.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let r=(~~(e>50)+1)*.5,n=(t&1)*r*255,s=(t>>1&1)*r*255,o=(t>>2&1)*r*255;return[n,s,o]};Gr.ansi256.rgb=function(e){if(e>=232){let o=(e-232)*10+8;return[o,o,o]}e-=16;let t,r=Math.floor(e/36)/5*255,n=Math.floor((t=e%36)/6)/5*255,s=t%6/5*255;return[r,n,s]};Gr.rgb.hex=function(e){let r=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};Gr.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let r=t[0];t[0].length===3&&(r=r.split("").map(a=>a+a).join(""));let n=parseInt(r,16),s=n>>16&255,o=n>>8&255,i=n&255;return[s,o,i]};Gr.rgb.hcg=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255,s=Math.max(Math.max(t,r),n),o=Math.min(Math.min(t,r),n),i=s-o,a,u;return i<1?a=o/(1-i):a=0,i<=0?u=0:s===t?u=(r-n)/i%6:s===r?u=2+(n-t)/i:u=4+(t-r)/i,u/=6,u%=1,[u*360,i*100,a*100]};Gr.hsl.hcg=function(e){let t=e[1]/100,r=e[2]/100,n=r<.5?2*t*r:2*t*(1-r),s=0;return n<1&&(s=(r-.5*n)/(1-n)),[e[0],n*100,s*100]};Gr.hsv.hcg=function(e){let t=e[1]/100,r=e[2]/100,n=t*r,s=0;return n<1&&(s=(r-n)/(1-n)),[e[0],n*100,s*100]};Gr.hcg.rgb=function(e){let t=e[0]/360,r=e[1]/100,n=e[2]/100;if(r===0)return[n*255,n*255,n*255];let s=[0,0,0],o=t%1*6,i=o%1,a=1-i,u=0;switch(Math.floor(o)){case 0:s[0]=1,s[1]=i,s[2]=0;break;case 1:s[0]=a,s[1]=1,s[2]=0;break;case 2:s[0]=0,s[1]=1,s[2]=i;break;case 3:s[0]=0,s[1]=a,s[2]=1;break;case 4:s[0]=i,s[1]=0,s[2]=1;break;default:s[0]=1,s[1]=0,s[2]=a}return u=(1-r)*n,[(r*s[0]+u)*255,(r*s[1]+u)*255,(r*s[2]+u)*255]};Gr.hcg.hsv=function(e){let t=e[1]/100,r=e[2]/100,n=t+r*(1-t),s=0;return n>0&&(s=t/n),[e[0],s*100,n*100]};Gr.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,s=0;return n>0&&n<.5?s=t/(2*n):n>=.5&&n<1&&(s=t/(2*(1-n))),[e[0],s*100,n*100]};Gr.hcg.hwb=function(e){let t=e[1]/100,r=e[2]/100,n=t+r*(1-t);return[e[0],(n-t)*100,(1-n)*100]};Gr.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,s=n-t,o=0;return s<1&&(o=(n-s)/(1-s)),[e[0],s*100,o*100]};Gr.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]};Gr.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]};Gr.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]};Gr.gray.hsl=function(e){return[0,0,e[0]]};Gr.gray.hsv=Gr.gray.hsl;Gr.gray.hwb=function(e){return[0,100,e[0]]};Gr.gray.cmyk=function(e){return[0,0,0,e[0]]};Gr.gray.lab=function(e){return[e[0],0,0]};Gr.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(n.length)+n};Gr.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}});var __=Fr(($X,v_)=>{var pp=Py();function N7(){let e={},t=Object.keys(pp);for(let r=t.length,n=0;n<r;n++)e[t[n]]={distance:-1,parent:null};return e}function O7(e){let t=N7(),r=[e];for(t[e].distance=0;r.length;){let n=r.pop(),s=Object.keys(pp[n]);for(let o=s.length,i=0;i<o;i++){let a=s[i],u=t[a];u.distance===-1&&(u.distance=t[n].distance+1,u.parent=n,r.unshift(a))}}return t}function L7(e,t){return function(r){return t(e(r))}}function P7(e,t){let r=[t[e].parent,e],n=pp[t[e].parent][e],s=t[e].parent;for(;t[s].parent;)r.unshift(t[s].parent),n=L7(pp[t[s].parent][s],n),s=t[s].parent;return n.conversion=r,n}v_.exports=function(e){let t=O7(e),r={},n=Object.keys(t);for(let s=n.length,o=0;o<s;o++){let i=n[o];t[i].parent!==null&&(r[i]=P7(i,t))}return r}});var F_=Fr((HX,S_)=>{var My=Py(),M7=__(),jc={},U7=Object.keys(My);function j7(e){let t=function(...r){let n=r[0];return n==null?n:(n.length>1&&(r=n),e(r))};return"conversion"in e&&(t.conversion=e.conversion),t}function $7(e){let t=function(...r){let n=r[0];if(n==null)return n;n.length>1&&(r=n);let s=e(r);if(typeof s=="object")for(let o=s.length,i=0;i<o;i++)s[i]=Math.round(s[i]);return s};return"conversion"in e&&(t.conversion=e.conversion),t}U7.forEach(e=>{jc[e]={},Object.defineProperty(jc[e],"channels",{value:My[e].channels}),Object.defineProperty(jc[e],"labels",{value:My[e].labels});let t=M7(e);Object.keys(t).forEach(n=>{let s=t[n];jc[e][n]=$7(s),jc[e][n].raw=j7(s)})});S_.exports=jc});var O_=Fr((qX,N_)=>{"use strict";var k_=(e,t)=>(...r)=>`\x1B[${e(...r)+t}m`,T_=(e,t)=>(...r)=>{let n=e(...r);return`\x1B[${38+t};5;${n}m`},R_=(e,t)=>(...r)=>{let n=e(...r);return`\x1B[${38+t};2;${n[0]};${n[1]};${n[2]}m`},gp=e=>e,Q_=(e,t,r)=>[e,t,r],$c=(e,t,r)=>{Object.defineProperty(e,t,{get:()=>{let n=r();return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},Uy,Hc=(e,t,r,n)=>{Uy===void 0&&(Uy=F_());let s=n?10:0,o={};for(let[i,a]of Object.entries(Uy)){let u=i==="ansi16"?"ansi":i;i===t?o[u]=e(r,s):typeof a=="object"&&(o[u]=e(a[t],s))}return o};function H7(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[r,n]of Object.entries(t)){for(let[s,o]of Object.entries(n))t[s]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[s]=t[s],e.set(o[0],o[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1B[39m",t.bgColor.close="\x1B[49m",$c(t.color,"ansi",()=>Hc(k_,"ansi16",gp,!1)),$c(t.color,"ansi256",()=>Hc(T_,"ansi256",gp,!1)),$c(t.color,"ansi16m",()=>Hc(R_,"rgb",Q_,!1)),$c(t.bgColor,"ansi",()=>Hc(k_,"ansi16",gp,!0)),$c(t.bgColor,"ansi256",()=>Hc(T_,"ansi256",gp,!0)),$c(t.bgColor,"ansi16m",()=>Hc(R_,"rgb",Q_,!0)),t}Object.defineProperty(N_,"exports",{enumerable:!0,get:H7})});var M_=Fr((GX,P_)=>{"use strict";var Vd=b_(),q7=fp(),G7=O_(),$y=new Set(["\x1B","\x9B"]),V7=39,L_=e=>`${$y.values().next().value}[${e}m`,Y7=e=>e.split(" ").map(t=>Vd(t)),jy=(e,t,r)=>{let n=[...t],s=!1,o=Vd(q7(e[e.length-1]));for(let[i,a]of n.entries()){let u=Vd(a);if(o+u<=r?e[e.length-1]+=a:(e.push(a),o=0),$y.has(a))s=!0;else if(s&&a==="m"){s=!1;continue}s||(o+=u,o===r&&i<n.length-1&&(e.push(""),o=0))}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},J7=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(Vd(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},z7=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",s="",o,i=Y7(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimLeft());let c=Vd(a[a.length-1]);if(u!==0&&(c>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c>0||r.trim===!1)&&(a[a.length-1]+=" ",c++)),r.hard&&i[u]>t){let d=t-c,A=1+Math.floor((i[u]-d-1)/t);Math.floor((i[u]-1)/t)<A&&a.push(""),jy(a,l,t);continue}if(c+i[u]>t&&c>0&&i[u]>0){if(r.wordWrap===!1&&c<t){jy(a,l,t);continue}a.push("")}if(c+i[u]>t&&r.wordWrap===!1){jy(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(J7)),n=a.join(`
|
|
1234
1234
|
`);for(let[u,l]of[...n].entries()){if(s+=l,$y.has(l)){let d=parseFloat(/\d[^m]*/.exec(n.slice(u,u+4)));o=d===V7?null:d}let c=G7.codes.get(Number(o));o&&c&&(n[u+1]===`
|