@wengine-ai/claude-code-router 2.0.50 → 2.0.51

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 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.45",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.46",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.45",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.46",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.50"});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.51"});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]===`
package/dist/index.html CHANGED
@@ -59,7 +59,7 @@ Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}
59
59
 
60
60
  If you want to hide the \`${a.titleName}\`, you can wrap it with our VisuallyHidden component.
61
61
 
62
- For more information, see https://radix-ui.com/primitives/docs/components/${a.docsSlug}`;return v.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},wM="DialogDescriptionWarning",SM=({contentRef:t,descriptionId:a})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Y1(wM).contentName}}.`;return v.useEffect(()=>{const o=t.current?.getAttribute("aria-describedby");a&&o&&(document.getElementById(a)||console.warn(s))},[s,t,a]),null},X1=L1,Q1=U1,Qm=H1,Zm=B1,Z1=$1,J1=q1,_M=G1;const xa=X1,jM=Q1,W1=v.forwardRef(({className:t,...a},r)=>c.jsx(Qm,{ref:r,className:Xe("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a}));W1.displayName=Qm.displayName;const la=v.forwardRef(({className:t,children:a,...r},s)=>c.jsxs(jM,{children:[c.jsx(W1,{}),c.jsxs(Zm,{ref:s,className:Xe("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg animate-scale-in",t),...r,children:[a,c.jsxs(_M,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground transition-all-ease hover:scale-110",children:[c.jsx(Wa,{className:"h-4 w-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));la.displayName=Zm.displayName;const sa=({className:t,...a})=>c.jsx("div",{className:Xe("flex flex-col space-y-1.5 text-center sm:text-left",t),...a});sa.displayName="DialogHeader";const qr=({className:t,...a})=>c.jsx("div",{className:Xe("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});qr.displayName="DialogFooter";const oa=v.forwardRef(({className:t,...a},r)=>c.jsx(Z1,{ref:r,className:Xe("text-lg font-semibold leading-none tracking-tight",t),...a}));oa.displayName=Z1.displayName;const Nl=v.forwardRef(({className:t,...a},r)=>c.jsx(J1,{ref:r,className:Xe("text-sm text-muted-foreground",t),...a}));Nl.displayName=J1.displayName;function NM(){const{t}=un(),{config:a,setConfig:r}=Yr(),[s,o]=v.useState(null),[u,d]=v.useState(null),[f,p]=v.useState(null);if(!a)return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"flex flex-row items-center justify-between border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("transformers.title")})}),c.jsx(Xn,{className:"flex-grow flex items-center justify-center p-4",children:c.jsx("div",{className:"text-gray-500",children:"Loading transformers configuration..."})})]});const m=Array.isArray(a.transformers)?a.transformers:[],x=()=>{p({name:"",path:"",options:{}}),o(m.length)},y=E=>{const O=[...m];O.splice(E,1),r({...a,transformers:O}),d(null)},w=(E,O,R,N)=>{if(E<m.length){const A=[...m];N!==void 0?A[E].options[N]=R:A[E][O]=R,r({...a,transformers:A})}else if(f){const A={...f};N!==void 0?A.options[N]=R:A[O]=R,p(A)}},S=s!==null?s<m.length?m[s]:f:null,j=()=>{if(f&&s===m.length){const E=[...m,f];r({...a,transformers:E})}o(null),p(null)},_=()=>{o(null),p(null)};return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsxs(ia,{className:"flex flex-row items-center justify-between border-b p-4",children:[c.jsxs(ca,{className:"text-lg",children:[t("transformers.title")," ",c.jsxs("span",{className:"text-sm font-normal text-gray-500",children:["(",m.length,")"]})]}),c.jsx(ve,{onClick:x,children:t("transformers.add")})]}),c.jsx(Xn,{className:"flex-grow overflow-y-auto p-4",children:c.jsx(YO,{transformers:m,onEdit:o,onRemove:d})}),c.jsx(xa,{open:s!==null,onOpenChange:_,children:c.jsxs(la,{children:[c.jsx(sa,{children:c.jsx(oa,{children:t("transformers.edit")})}),S&&s!==null&&c.jsxs("div",{className:"space-y-4 py-4 px-6 max-h-96 overflow-y-auto",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"transformer-path",children:t("transformers.path")}),c.jsx(lt,{id:"transformer-path",value:S.path||"",onChange:E=>w(s,"path",E.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Te,{children:t("transformers.parameters")}),c.jsx(ve,{variant:"outline",size:"sm",onClick:()=>{const E=S.options||{},O=`param${Object.keys(E).length+1}`;if(s!==null){const R={...E,[O]:""};if(s<m.length){const N=[...m];N[s].options=R,r({...a,transformers:N})}else f&&p({...f,options:R})}},children:c.jsx(du,{className:"h-4 w-4"})})]}),Object.entries(S.options||{}).map(([E,O])=>c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(lt,{value:E,onChange:R=>{const A={...S.options||{}};if(delete A[E],A[R.target.value]=O,s!==null)if(s<m.length){const L=[...m];L[s].options=A,r({...a,transformers:L})}else f&&p({...f,options:A})},className:"flex-1"}),c.jsx(lt,{value:O,onChange:R=>{s!==null&&w(s,"parameters",R.target.value,E)},className:"flex-1"}),c.jsx(ve,{variant:"outline",size:"icon",onClick:()=>{if(s!==null){const N={...S.options||{}};if(delete N[E],s<m.length){const A=[...m];A[s].options=N,r({...a,transformers:A})}else f&&p({...f,options:N})}},children:c.jsx(kn,{className:"h-4 w-4"})})]},E))]})]}),c.jsxs(qr,{children:[c.jsx(ve,{variant:"outline",onClick:_,children:t("app.cancel")}),c.jsx(ve,{onClick:j,children:t("app.save")})]})]})}),c.jsx(xa,{open:u!==null,onOpenChange:()=>d(null),children:c.jsxs(la,{children:[c.jsxs(sa,{children:[c.jsx(oa,{children:t("transformers.delete")}),c.jsx(Nl,{children:t("transformers.delete_transformer_confirm")})]}),c.jsxs(qr,{children:[c.jsx(ve,{variant:"outline",onClick:()=>d(null),children:t("app.cancel")}),c.jsx(ve,{variant:"destructive",onClick:()=>u!==null&&y(u),children:t("app.delete")})]})]})})]})}const CM=$m("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Ur({className:t,variant:a,...r}){return c.jsx("div",{className:Xe(CM({variant:a}),t),...r})}function EM(t,a){if(!a||a.length===0)return{status:"closed",hasFailure:!1};const r=a.filter(u=>u.provider===t);if(r.length===0)return{status:"closed",hasFailure:!1};const s=r.filter(u=>u.status==="open"),o=r.filter(u=>u.status==="half-open");return s.length>0?{status:"open",hasFailure:!0,lastError:s[0].lastError}:o.length>0?{status:"half-open",hasFailure:!0,lastError:o[0].lastError}:{status:"closed",hasFailure:!1}}function RM({status:t}){const a={closed:"bg-green-500",open:"bg-red-500","half-open":"bg-yellow-500",unknown:"bg-gray-400"},r={closed:"Healthy",open:"Failed","half-open":"Recovering",unknown:"Unknown"};return c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${a[t]} animate-pulse`,title:r[t]}),c.jsx("span",{className:"text-xs text-gray-500",children:r[t]})]})}function L0(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function z0({label:t,used:a,limit:r,resetTime:s,t:o}){if(a===0&&!r)return null;const u=r?Math.min(100,a/r*100):void 0,d=L0(a);r&&L0(r);let f="bg-emerald-400",p="text-emerald-600";return u!==void 0&&(u>=90?(f="bg-red-500",p="text-red-600"):u>=70?(f="bg-amber-400",p="text-amber-600"):u>=40&&(f="bg-blue-400",p="text-blue-600")),c.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[c.jsx("span",{className:"w-12 shrink-0",children:t}),c.jsx("div",{className:"flex-1 h-2.5 bg-gray-200 rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${f} transition-all duration-300`,style:{width:u!==void 0?`${Math.max(2,u)}%`:"0%"}})}),c.jsx("span",{className:`w-14 shrink-0 text-right tabular-nums font-medium ${p}`,children:u!==void 0?`${u.toFixed(1)}%`:d}),s&&c.jsx("span",{className:"w-24 shrink-0 text-right text-gray-400",children:o("providers.quota_reset",{time:new Date(s).toLocaleTimeString()})})]})}function TM({providers:t,healthStates:a,quotaUsages:r,onEdit:s,onRemove:o}){const{t:u}=un();return!t||!Array.isArray(t)?c.jsx("div",{className:"space-y-3",children:c.jsx("div",{className:"flex items-center justify-center rounded-md border bg-white p-8 text-gray-500",children:"No providers configured"})}):c.jsx("div",{className:"space-y-3",children:t.map((d,f)=>{if(!d)return c.jsxs("div",{className:"flex items-start justify-between rounded-md border bg-white p-4 transition-all hover:shadow-md animate-slide-in hover:scale-[1.01]",children:[c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("p",{className:"text-md font-semibold text-gray-800",children:"Invalid Provider"}),c.jsx("p",{className:"text-sm text-gray-500",children:"Provider data is missing"})]}),c.jsxs("div",{className:"ml-4 flex flex-shrink-0 items-center gap-2",children:[c.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>s(f),className:"transition-all-ease hover:scale-110",disabled:!0,children:c.jsx(uu,{className:"h-4 w-4"})}),c.jsx(ve,{variant:"destructive",size:"icon",onClick:()=>o(f),className:"transition-all duration-200 hover:scale-110",children:c.jsx(kn,{className:"h-4 w-4 text-current transition-colors duration-200"})})]})]},f);const p=d.name||"Unnamed Provider",m=d.api_base_url||"No API URL",x=Array.isArray(d.models)?d.models:[],y=EM(p,a),w=r?.find(j=>j.provider===p),S=w&&(w.used5h>0||w.limit5h||w.used7d>0||w.limit7d);return c.jsxs("div",{className:"flex items-start justify-between rounded-md border bg-white p-4 transition-all hover:shadow-md animate-slide-in hover:scale-[1.01]",children:[c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("p",{className:"text-md font-semibold text-gray-800",children:p})}),c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("p",{className:"text-sm text-gray-500",children:m})}),y.lastError&&c.jsxs("p",{className:"text-xs text-red-500 truncate max-w-md",title:y.lastError,children:["Error: ",y.lastError]}),S&&c.jsxs("div",{className:"space-y-1 pt-1",children:[c.jsx(z0,{label:u("providers.quota_5h"),used:w.used5h,limit:w.limit5h,resetTime:w.reset5h,t:u}),c.jsx(z0,{label:u("providers.quota_7d"),used:w.used7d,limit:w.limit7d,resetTime:w.reset7d,t:u})]}),c.jsx("div",{className:"flex flex-wrap gap-2 pt-2",children:x.map((j,_)=>c.jsx(Ur,{variant:"outline",className:"font-normal transition-all-ease hover:scale-105",children:j||"Unnamed Model"},_))})]}),c.jsxs("div",{className:"ml-4 flex flex-shrink-0 items-center gap-2",children:[c.jsx(RM,{status:y.status}),c.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>s(f),className:"transition-all-ease hover:scale-110",children:c.jsx(uu,{className:"h-4 w-4"})}),c.jsx(ve,{variant:"destructive",size:"icon",onClick:()=>o(f),className:"transition-all duration-200 hover:scale-110",children:c.jsx(kn,{className:"h-4 w-4 text-current transition-colors duration-200"})})]})]},f)})})}var P0=1,OM=.9,AM=.8,MM=.17,Ph=.1,Uh=.999,kM=.9999,DM=.99,LM=/[\\\/_+.#"@\[\(\{&]/,zM=/[\\\/_+.#"@\[\(\{&]/g,PM=/[\s-]/,ew=/[\s-]/g;function im(t,a,r,s,o,u,d){if(u===a.length)return o===t.length?P0:DM;var f=`${o},${u}`;if(d[f]!==void 0)return d[f];for(var p=s.charAt(u),m=r.indexOf(p,o),x=0,y,w,S,j;m>=0;)y=im(t,a,r,s,m+1,u+1,d),y>x&&(m===o?y*=P0:LM.test(t.charAt(m-1))?(y*=AM,S=t.slice(o,m-1).match(zM),S&&o>0&&(y*=Math.pow(Uh,S.length))):PM.test(t.charAt(m-1))?(y*=OM,j=t.slice(o,m-1).match(ew),j&&o>0&&(y*=Math.pow(Uh,j.length))):(y*=MM,o>0&&(y*=Math.pow(Uh,m-o))),t.charAt(m)!==a.charAt(u)&&(y*=kM)),(y<Ph&&r.charAt(m-1)===s.charAt(u+1)||s.charAt(u+1)===s.charAt(u)&&r.charAt(m-1)!==s.charAt(u))&&(w=im(t,a,r,s,m+1,u+2,d),w*Ph>y&&(y=w*Ph)),y>x&&(x=y),m=r.indexOf(p,m+1);return d[f]=x,x}function U0(t){return t.toLowerCase().replace(ew," ")}function UM(t,a,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,im(t,a,U0(t),U0(a),0,0,{})}var Fo='[cmdk-group=""]',Hh='[cmdk-group-items=""]',HM='[cmdk-group-heading=""]',tw='[cmdk-item=""]',H0=`${tw}:not([aria-disabled="true"])`,cm="cmdk-item-select",bs="data-value",BM=(t,a,r)=>UM(t,a,r),nw=v.createContext(void 0),hi=()=>v.useContext(nw),aw=v.createContext(void 0),Jm=()=>v.useContext(aw),rw=v.createContext(void 0),lw=v.forwardRef((t,a)=>{let r=ws(()=>{var U,X;return{search:"",value:(X=(U=t.value)!=null?U:t.defaultValue)!=null?X:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),s=ws(()=>new Set),o=ws(()=>new Map),u=ws(()=>new Map),d=ws(()=>new Set),f=sw(t),{label:p,children:m,value:x,onValueChange:y,filter:w,shouldFilter:S,loop:j,disablePointerSelection:_=!1,vimBindings:E=!0,...O}=t,R=on(),N=on(),A=on(),L=v.useRef(null),z=ZM();El(()=>{if(x!==void 0){let U=x.trim();r.current.value=U,C.emit()}},[x]),El(()=>{z(6,re)},[]);let C=v.useMemo(()=>({subscribe:U=>(d.current.add(U),()=>d.current.delete(U)),snapshot:()=>r.current,setState:(U,X,ne)=>{var oe,ye,se,Re;if(!Object.is(r.current[U],X)){if(r.current[U]=X,U==="search")te(),D(),z(1,G);else if(U==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let J=document.getElementById(A);J?J.focus():(oe=document.getElementById(R))==null||oe.focus()}if(z(7,()=>{var J;r.current.selectedItemId=(J=le())==null?void 0:J.id,C.emit()}),ne||z(5,re),((ye=f.current)==null?void 0:ye.value)!==void 0){let J=X??"";(Re=(se=f.current).onValueChange)==null||Re.call(se,J);return}}C.emit()}},emit:()=>{d.current.forEach(U=>U())}}),[]),B=v.useMemo(()=>({value:(U,X,ne)=>{var oe;X!==((oe=u.current.get(U))==null?void 0:oe.value)&&(u.current.set(U,{value:X,keywords:ne}),r.current.filtered.items.set(U,q(X,ne)),z(2,()=>{D(),C.emit()}))},item:(U,X)=>(s.current.add(U),X&&(o.current.has(X)?o.current.get(X).add(U):o.current.set(X,new Set([U]))),z(3,()=>{te(),D(),r.current.value||G(),C.emit()}),()=>{u.current.delete(U),s.current.delete(U),r.current.filtered.items.delete(U);let ne=le();z(4,()=>{te(),ne?.getAttribute("id")===U&&G(),C.emit()})}),group:U=>(o.current.has(U)||o.current.set(U,new Set),()=>{u.current.delete(U),o.current.delete(U)}),filter:()=>f.current.shouldFilter,label:p||t["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:R,inputId:A,labelId:N,listInnerRef:L}),[]);function q(U,X){var ne,oe;let ye=(oe=(ne=f.current)==null?void 0:ne.filter)!=null?oe:BM;return U?ye(U,r.current.search,X):0}function D(){if(!r.current.search||f.current.shouldFilter===!1)return;let U=r.current.filtered.items,X=[];r.current.filtered.groups.forEach(oe=>{let ye=o.current.get(oe),se=0;ye.forEach(Re=>{let J=U.get(Re);se=Math.max(J,se)}),X.push([oe,se])});let ne=L.current;V().sort((oe,ye)=>{var se,Re;let J=oe.getAttribute("id"),we=ye.getAttribute("id");return((se=U.get(we))!=null?se:0)-((Re=U.get(J))!=null?Re:0)}).forEach(oe=>{let ye=oe.closest(Hh);ye?ye.appendChild(oe.parentElement===ye?oe:oe.closest(`${Hh} > *`)):ne.appendChild(oe.parentElement===ne?oe:oe.closest(`${Hh} > *`))}),X.sort((oe,ye)=>ye[1]-oe[1]).forEach(oe=>{var ye;let se=(ye=L.current)==null?void 0:ye.querySelector(`${Fo}[${bs}="${encodeURIComponent(oe[0])}"]`);se?.parentElement.appendChild(se)})}function G(){let U=V().find(ne=>ne.getAttribute("aria-disabled")!=="true"),X=U?.getAttribute(bs);C.setState("value",X||void 0)}function te(){var U,X,ne,oe;if(!r.current.search||f.current.shouldFilter===!1){r.current.filtered.count=s.current.size;return}r.current.filtered.groups=new Set;let ye=0;for(let se of s.current){let Re=(X=(U=u.current.get(se))==null?void 0:U.value)!=null?X:"",J=(oe=(ne=u.current.get(se))==null?void 0:ne.keywords)!=null?oe:[],we=q(Re,J);r.current.filtered.items.set(se,we),we>0&&ye++}for(let[se,Re]of o.current)for(let J of Re)if(r.current.filtered.items.get(J)>0){r.current.filtered.groups.add(se);break}r.current.filtered.count=ye}function re(){var U,X,ne;let oe=le();oe&&(((U=oe.parentElement)==null?void 0:U.firstChild)===oe&&((ne=(X=oe.closest(Fo))==null?void 0:X.querySelector(HM))==null||ne.scrollIntoView({block:"nearest"})),oe.scrollIntoView({block:"nearest"}))}function le(){var U;return(U=L.current)==null?void 0:U.querySelector(`${tw}[aria-selected="true"]`)}function V(){var U;return Array.from(((U=L.current)==null?void 0:U.querySelectorAll(H0))||[])}function M(U){let X=V()[U];X&&C.setState("value",X.getAttribute(bs))}function P(U){var X;let ne=le(),oe=V(),ye=oe.findIndex(Re=>Re===ne),se=oe[ye+U];(X=f.current)!=null&&X.loop&&(se=ye+U<0?oe[oe.length-1]:ye+U===oe.length?oe[0]:oe[ye+U]),se&&C.setState("value",se.getAttribute(bs))}function H(U){let X=le(),ne=X?.closest(Fo),oe;for(;ne&&!oe;)ne=U>0?XM(ne,Fo):QM(ne,Fo),oe=ne?.querySelector(H0);oe?C.setState("value",oe.getAttribute(bs)):P(U)}let fe=()=>M(V().length-1),pe=U=>{U.preventDefault(),U.metaKey?fe():U.altKey?H(1):P(1)},k=U=>{U.preventDefault(),U.metaKey?M(0):U.altKey?H(-1):P(-1)};return v.createElement(lr.div,{ref:a,tabIndex:-1,...O,"cmdk-root":"",onKeyDown:U=>{var X;(X=O.onKeyDown)==null||X.call(O,U);let ne=U.nativeEvent.isComposing||U.keyCode===229;if(!(U.defaultPrevented||ne))switch(U.key){case"n":case"j":{E&&U.ctrlKey&&pe(U);break}case"ArrowDown":{pe(U);break}case"p":case"k":{E&&U.ctrlKey&&k(U);break}case"ArrowUp":{k(U);break}case"Home":{U.preventDefault(),M(0);break}case"End":{U.preventDefault(),fe();break}case"Enter":{U.preventDefault();let oe=le();if(oe){let ye=new Event(cm);oe.dispatchEvent(ye)}}}}},v.createElement("label",{"cmdk-label":"",htmlFor:B.inputId,id:B.labelId,style:WM},p),zu(t,U=>v.createElement(aw.Provider,{value:C},v.createElement(nw.Provider,{value:B},U))))}),FM=v.forwardRef((t,a)=>{var r,s;let o=on(),u=v.useRef(null),d=v.useContext(rw),f=hi(),p=sw(t),m=(s=(r=p.current)==null?void 0:r.forceMount)!=null?s:d?.forceMount;El(()=>{if(!m)return f.item(o,d?.id)},[m]);let x=ow(o,u,[t.value,t.children,u],t.keywords),y=Jm(),w=Vr(z=>z.value&&z.value===x.current),S=Vr(z=>m||f.filter()===!1?!0:z.search?z.filtered.items.get(o)>0:!0);v.useEffect(()=>{let z=u.current;if(!(!z||t.disabled))return z.addEventListener(cm,j),()=>z.removeEventListener(cm,j)},[S,t.onSelect,t.disabled]);function j(){var z,C;_(),(C=(z=p.current).onSelect)==null||C.call(z,x.current)}function _(){y.setState("value",x.current,!0)}if(!S)return null;let{disabled:E,value:O,onSelect:R,forceMount:N,keywords:A,...L}=t;return v.createElement(lr.div,{ref:$r(u,a),...L,id:o,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:_,onClick:E?void 0:j},t.children)}),$M=v.forwardRef((t,a)=>{let{heading:r,children:s,forceMount:o,...u}=t,d=on(),f=v.useRef(null),p=v.useRef(null),m=on(),x=hi(),y=Vr(S=>o||x.filter()===!1?!0:S.search?S.filtered.groups.has(d):!0);El(()=>x.group(d),[]),ow(d,f,[t.value,t.heading,p]);let w=v.useMemo(()=>({id:d,forceMount:o}),[o]);return v.createElement(lr.div,{ref:$r(f,a),...u,"cmdk-group":"",role:"presentation",hidden:y?void 0:!0},r&&v.createElement("div",{ref:p,"cmdk-group-heading":"","aria-hidden":!0,id:m},r),zu(t,S=>v.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?m:void 0},v.createElement(rw.Provider,{value:w},S))))}),IM=v.forwardRef((t,a)=>{let{alwaysRender:r,...s}=t,o=v.useRef(null),u=Vr(d=>!d.search);return!r&&!u?null:v.createElement(lr.div,{ref:$r(o,a),...s,"cmdk-separator":"",role:"separator"})}),qM=v.forwardRef((t,a)=>{let{onValueChange:r,...s}=t,o=t.value!=null,u=Jm(),d=Vr(m=>m.search),f=Vr(m=>m.selectedItemId),p=hi();return v.useEffect(()=>{t.value!=null&&u.setState("search",t.value)},[t.value]),v.createElement(lr.input,{ref:a,...s,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":p.listId,"aria-labelledby":p.labelId,"aria-activedescendant":f,id:p.inputId,type:"text",value:o?t.value:d,onChange:m=>{o||u.setState("search",m.target.value),r?.(m.target.value)}})}),VM=v.forwardRef((t,a)=>{let{children:r,label:s="Suggestions",...o}=t,u=v.useRef(null),d=v.useRef(null),f=Vr(m=>m.selectedItemId),p=hi();return v.useEffect(()=>{if(d.current&&u.current){let m=d.current,x=u.current,y,w=new ResizeObserver(()=>{y=requestAnimationFrame(()=>{let S=m.offsetHeight;x.style.setProperty("--cmdk-list-height",S.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(y),w.unobserve(m)}}},[]),v.createElement(lr.div,{ref:$r(u,a),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":s,id:p.listId},zu(t,m=>v.createElement("div",{ref:$r(d,p.listInnerRef),"cmdk-list-sizer":""},m)))}),GM=v.forwardRef((t,a)=>{let{open:r,onOpenChange:s,overlayClassName:o,contentClassName:u,container:d,...f}=t;return v.createElement(X1,{open:r,onOpenChange:s},v.createElement(Q1,{container:d},v.createElement(Qm,{"cmdk-overlay":"",className:o}),v.createElement(Zm,{"aria-label":t.label,"cmdk-dialog":"",className:u},v.createElement(lw,{ref:a,...f}))))}),KM=v.forwardRef((t,a)=>Vr(r=>r.filtered.count===0)?v.createElement(lr.div,{ref:a,...t,"cmdk-empty":"",role:"presentation"}):null),YM=v.forwardRef((t,a)=>{let{progress:r,children:s,label:o="Loading...",...u}=t;return v.createElement(lr.div,{ref:a,...u,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},zu(t,d=>v.createElement("div",{"aria-hidden":!0},d)))}),Us=Object.assign(lw,{List:VM,Item:FM,Input:qM,Group:$M,Separator:IM,Dialog:GM,Empty:KM,Loading:YM});function XM(t,a){let r=t.nextElementSibling;for(;r;){if(r.matches(a))return r;r=r.nextElementSibling}}function QM(t,a){let r=t.previousElementSibling;for(;r;){if(r.matches(a))return r;r=r.previousElementSibling}}function sw(t){let a=v.useRef(t);return El(()=>{a.current=t}),a}var El=typeof window>"u"?v.useEffect:v.useLayoutEffect;function ws(t){let a=v.useRef();return a.current===void 0&&(a.current=t()),a}function Vr(t){let a=Jm(),r=()=>t(a.snapshot());return v.useSyncExternalStore(a.subscribe,r,r)}function ow(t,a,r,s=[]){let o=v.useRef(),u=hi();return El(()=>{var d;let f=(()=>{var m;for(let x of r){if(typeof x=="string")return x.trim();if(typeof x=="object"&&"current"in x)return x.current?(m=x.current.textContent)==null?void 0:m.trim():o.current}})(),p=s.map(m=>m.trim());u.value(t,f,p),(d=a.current)==null||d.setAttribute(bs,f),o.current=f}),o}var ZM=()=>{let[t,a]=v.useState(),r=ws(()=>new Map);return El(()=>{r.current.forEach(s=>s()),r.current=new Map},[t]),(s,o)=>{r.current.set(s,o),a({})}};function JM(t){let a=t.type;return typeof a=="function"?a(t.props):"render"in a?a.render(t.props):t}function zu({asChild:t,children:a},r){return t&&v.isValidElement(a)?v.cloneElement(JM(a),{ref:a.ref},r(a.props.children)):r(a)}var WM={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Wm({className:t,...a}){return c.jsx(Us,{"data-slot":"command",className:Xe("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...a})}function ep({className:t,...a}){return c.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[c.jsx(qm,{className:"size-4 shrink-0 opacity-50"}),c.jsx(Us.Input,{"data-slot":"command-input",className:Xe("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...a})]})}function tp({className:t,...a}){return c.jsx(Us.List,{"data-slot":"command-list",className:Xe("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...a})}function np({...t}){return c.jsx(Us.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function ap({className:t,...a}){return c.jsx(Us.Group,{"data-slot":"command-group",className:Xe("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...a})}function rp({className:t,...a}){return c.jsx(Us.Item,{"data-slot":"command-item",className:Xe("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...a})}const ek=["top","right","bottom","left"],Gr=Math.min,An=Math.max,hu=Math.round,Vc=Math.floor,Sa=t=>({x:t,y:t}),tk={left:"right",right:"left",bottom:"top",top:"bottom"},nk={start:"end",end:"start"};function um(t,a,r){return An(t,Gr(a,r))}function tr(t,a){return typeof t=="function"?t(a):t}function nr(t){return t.split("-")[0]}function Hs(t){return t.split("-")[1]}function lp(t){return t==="x"?"y":"x"}function sp(t){return t==="y"?"height":"width"}const ak=new Set(["top","bottom"]);function ba(t){return ak.has(nr(t))?"y":"x"}function op(t){return lp(ba(t))}function rk(t,a,r){r===void 0&&(r=!1);const s=Hs(t),o=op(t),u=sp(o);let d=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return a.reference[u]>a.floating[u]&&(d=mu(d)),[d,mu(d)]}function lk(t){const a=mu(t);return[dm(t),a,dm(a)]}function dm(t){return t.replace(/start|end/g,a=>nk[a])}const B0=["left","right"],F0=["right","left"],sk=["top","bottom"],ok=["bottom","top"];function ik(t,a,r){switch(t){case"top":case"bottom":return r?a?F0:B0:a?B0:F0;case"left":case"right":return a?sk:ok;default:return[]}}function ck(t,a,r,s){const o=Hs(t);let u=ik(nr(t),r==="start",s);return o&&(u=u.map(d=>d+"-"+o),a&&(u=u.concat(u.map(dm)))),u}function mu(t){return t.replace(/left|right|bottom|top/g,a=>tk[a])}function uk(t){return{top:0,right:0,bottom:0,left:0,...t}}function iw(t){return typeof t!="number"?uk(t):{top:t,right:t,bottom:t,left:t}}function pu(t){const{x:a,y:r,width:s,height:o}=t;return{width:s,height:o,top:r,left:a,right:a+s,bottom:r+o,x:a,y:r}}function $0(t,a,r){let{reference:s,floating:o}=t;const u=ba(a),d=op(a),f=sp(d),p=nr(a),m=u==="y",x=s.x+s.width/2-o.width/2,y=s.y+s.height/2-o.height/2,w=s[f]/2-o[f]/2;let S;switch(p){case"top":S={x,y:s.y-o.height};break;case"bottom":S={x,y:s.y+s.height};break;case"right":S={x:s.x+s.width,y};break;case"left":S={x:s.x-o.width,y};break;default:S={x:s.x,y:s.y}}switch(Hs(a)){case"start":S[d]-=w*(r&&m?-1:1);break;case"end":S[d]+=w*(r&&m?-1:1);break}return S}const dk=async(t,a,r)=>{const{placement:s="bottom",strategy:o="absolute",middleware:u=[],platform:d}=r,f=u.filter(Boolean),p=await(d.isRTL==null?void 0:d.isRTL(a));let m=await d.getElementRects({reference:t,floating:a,strategy:o}),{x,y}=$0(m,s,p),w=s,S={},j=0;for(let _=0;_<f.length;_++){const{name:E,fn:O}=f[_],{x:R,y:N,data:A,reset:L}=await O({x,y,initialPlacement:s,placement:w,strategy:o,middlewareData:S,rects:m,platform:d,elements:{reference:t,floating:a}});x=R??x,y=N??y,S={...S,[E]:{...S[E],...A}},L&&j<=50&&(j++,typeof L=="object"&&(L.placement&&(w=L.placement),L.rects&&(m=L.rects===!0?await d.getElementRects({reference:t,floating:a,strategy:o}):L.rects),{x,y}=$0(m,w,p)),_=-1)}return{x,y,placement:w,strategy:o,middlewareData:S}};async function ri(t,a){var r;a===void 0&&(a={});const{x:s,y:o,platform:u,rects:d,elements:f,strategy:p}=t,{boundary:m="clippingAncestors",rootBoundary:x="viewport",elementContext:y="floating",altBoundary:w=!1,padding:S=0}=tr(a,t),j=iw(S),E=f[w?y==="floating"?"reference":"floating":y],O=pu(await u.getClippingRect({element:(r=await(u.isElement==null?void 0:u.isElement(E)))==null||r?E:E.contextElement||await(u.getDocumentElement==null?void 0:u.getDocumentElement(f.floating)),boundary:m,rootBoundary:x,strategy:p})),R=y==="floating"?{x:s,y:o,width:d.floating.width,height:d.floating.height}:d.reference,N=await(u.getOffsetParent==null?void 0:u.getOffsetParent(f.floating)),A=await(u.isElement==null?void 0:u.isElement(N))?await(u.getScale==null?void 0:u.getScale(N))||{x:1,y:1}:{x:1,y:1},L=pu(u.convertOffsetParentRelativeRectToViewportRelativeRect?await u.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:R,offsetParent:N,strategy:p}):R);return{top:(O.top-L.top+j.top)/A.y,bottom:(L.bottom-O.bottom+j.bottom)/A.y,left:(O.left-L.left+j.left)/A.x,right:(L.right-O.right+j.right)/A.x}}const fk=t=>({name:"arrow",options:t,async fn(a){const{x:r,y:s,placement:o,rects:u,platform:d,elements:f,middlewareData:p}=a,{element:m,padding:x=0}=tr(t,a)||{};if(m==null)return{};const y=iw(x),w={x:r,y:s},S=op(o),j=sp(S),_=await d.getDimensions(m),E=S==="y",O=E?"top":"left",R=E?"bottom":"right",N=E?"clientHeight":"clientWidth",A=u.reference[j]+u.reference[S]-w[S]-u.floating[j],L=w[S]-u.reference[S],z=await(d.getOffsetParent==null?void 0:d.getOffsetParent(m));let C=z?z[N]:0;(!C||!await(d.isElement==null?void 0:d.isElement(z)))&&(C=f.floating[N]||u.floating[j]);const B=A/2-L/2,q=C/2-_[j]/2-1,D=Gr(y[O],q),G=Gr(y[R],q),te=D,re=C-_[j]-G,le=C/2-_[j]/2+B,V=um(te,le,re),M=!p.arrow&&Hs(o)!=null&&le!==V&&u.reference[j]/2-(le<te?D:G)-_[j]/2<0,P=M?le<te?le-te:le-re:0;return{[S]:w[S]+P,data:{[S]:V,centerOffset:le-V-P,...M&&{alignmentOffset:P}},reset:M}}}),hk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(a){var r,s;const{placement:o,middlewareData:u,rects:d,initialPlacement:f,platform:p,elements:m}=a,{mainAxis:x=!0,crossAxis:y=!0,fallbackPlacements:w,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:j="none",flipAlignment:_=!0,...E}=tr(t,a);if((r=u.arrow)!=null&&r.alignmentOffset)return{};const O=nr(o),R=ba(f),N=nr(f)===f,A=await(p.isRTL==null?void 0:p.isRTL(m.floating)),L=w||(N||!_?[mu(f)]:lk(f)),z=j!=="none";!w&&z&&L.push(...ck(f,_,j,A));const C=[f,...L],B=await ri(a,E),q=[];let D=((s=u.flip)==null?void 0:s.overflows)||[];if(x&&q.push(B[O]),y){const le=rk(o,d,A);q.push(B[le[0]],B[le[1]])}if(D=[...D,{placement:o,overflows:q}],!q.every(le=>le<=0)){var G,te;const le=(((G=u.flip)==null?void 0:G.index)||0)+1,V=C[le];if(V&&(!(y==="alignment"?R!==ba(V):!1)||D.every(H=>ba(H.placement)===R?H.overflows[0]>0:!0)))return{data:{index:le,overflows:D},reset:{placement:V}};let M=(te=D.filter(P=>P.overflows[0]<=0).sort((P,H)=>P.overflows[1]-H.overflows[1])[0])==null?void 0:te.placement;if(!M)switch(S){case"bestFit":{var re;const P=(re=D.filter(H=>{if(z){const fe=ba(H.placement);return fe===R||fe==="y"}return!0}).map(H=>[H.placement,H.overflows.filter(fe=>fe>0).reduce((fe,pe)=>fe+pe,0)]).sort((H,fe)=>H[1]-fe[1])[0])==null?void 0:re[0];P&&(M=P);break}case"initialPlacement":M=f;break}if(o!==M)return{reset:{placement:M}}}return{}}}};function I0(t,a){return{top:t.top-a.height,right:t.right-a.width,bottom:t.bottom-a.height,left:t.left-a.width}}function q0(t){return ek.some(a=>t[a]>=0)}const mk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(a){const{rects:r}=a,{strategy:s="referenceHidden",...o}=tr(t,a);switch(s){case"referenceHidden":{const u=await ri(a,{...o,elementContext:"reference"}),d=I0(u,r.reference);return{data:{referenceHiddenOffsets:d,referenceHidden:q0(d)}}}case"escaped":{const u=await ri(a,{...o,altBoundary:!0}),d=I0(u,r.floating);return{data:{escapedOffsets:d,escaped:q0(d)}}}default:return{}}}}},cw=new Set(["left","top"]);async function pk(t,a){const{placement:r,platform:s,elements:o}=t,u=await(s.isRTL==null?void 0:s.isRTL(o.floating)),d=nr(r),f=Hs(r),p=ba(r)==="y",m=cw.has(d)?-1:1,x=u&&p?-1:1,y=tr(a,t);let{mainAxis:w,crossAxis:S,alignmentAxis:j}=typeof y=="number"?{mainAxis:y,crossAxis:0,alignmentAxis:null}:{mainAxis:y.mainAxis||0,crossAxis:y.crossAxis||0,alignmentAxis:y.alignmentAxis};return f&&typeof j=="number"&&(S=f==="end"?j*-1:j),p?{x:S*x,y:w*m}:{x:w*m,y:S*x}}const gk=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(a){var r,s;const{x:o,y:u,placement:d,middlewareData:f}=a,p=await pk(a,t);return d===((r=f.offset)==null?void 0:r.placement)&&(s=f.arrow)!=null&&s.alignmentOffset?{}:{x:o+p.x,y:u+p.y,data:{...p,placement:d}}}}},vk=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(a){const{x:r,y:s,placement:o}=a,{mainAxis:u=!0,crossAxis:d=!1,limiter:f={fn:E=>{let{x:O,y:R}=E;return{x:O,y:R}}},...p}=tr(t,a),m={x:r,y:s},x=await ri(a,p),y=ba(nr(o)),w=lp(y);let S=m[w],j=m[y];if(u){const E=w==="y"?"top":"left",O=w==="y"?"bottom":"right",R=S+x[E],N=S-x[O];S=um(R,S,N)}if(d){const E=y==="y"?"top":"left",O=y==="y"?"bottom":"right",R=j+x[E],N=j-x[O];j=um(R,j,N)}const _=f.fn({...a,[w]:S,[y]:j});return{..._,data:{x:_.x-r,y:_.y-s,enabled:{[w]:u,[y]:d}}}}}},yk=function(t){return t===void 0&&(t={}),{options:t,fn(a){const{x:r,y:s,placement:o,rects:u,middlewareData:d}=a,{offset:f=0,mainAxis:p=!0,crossAxis:m=!0}=tr(t,a),x={x:r,y:s},y=ba(o),w=lp(y);let S=x[w],j=x[y];const _=tr(f,a),E=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(p){const N=w==="y"?"height":"width",A=u.reference[w]-u.floating[N]+E.mainAxis,L=u.reference[w]+u.reference[N]-E.mainAxis;S<A?S=A:S>L&&(S=L)}if(m){var O,R;const N=w==="y"?"width":"height",A=cw.has(nr(o)),L=u.reference[y]-u.floating[N]+(A&&((O=d.offset)==null?void 0:O[y])||0)+(A?0:E.crossAxis),z=u.reference[y]+u.reference[N]+(A?0:((R=d.offset)==null?void 0:R[y])||0)-(A?E.crossAxis:0);j<L?j=L:j>z&&(j=z)}return{[w]:S,[y]:j}}}},xk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(a){var r,s;const{placement:o,rects:u,platform:d,elements:f}=a,{apply:p=()=>{},...m}=tr(t,a),x=await ri(a,m),y=nr(o),w=Hs(o),S=ba(o)==="y",{width:j,height:_}=u.floating;let E,O;y==="top"||y==="bottom"?(E=y,O=w===(await(d.isRTL==null?void 0:d.isRTL(f.floating))?"start":"end")?"left":"right"):(O=y,E=w==="end"?"top":"bottom");const R=_-x.top-x.bottom,N=j-x.left-x.right,A=Gr(_-x[E],R),L=Gr(j-x[O],N),z=!a.middlewareData.shift;let C=A,B=L;if((r=a.middlewareData.shift)!=null&&r.enabled.x&&(B=N),(s=a.middlewareData.shift)!=null&&s.enabled.y&&(C=R),z&&!w){const D=An(x.left,0),G=An(x.right,0),te=An(x.top,0),re=An(x.bottom,0);S?B=j-2*(D!==0||G!==0?D+G:An(x.left,x.right)):C=_-2*(te!==0||re!==0?te+re:An(x.top,x.bottom))}await p({...a,availableWidth:B,availableHeight:C});const q=await d.getDimensions(f.floating);return j!==q.width||_!==q.height?{reset:{rects:!0}}:{}}}};function Pu(){return typeof window<"u"}function Bs(t){return uw(t)?(t.nodeName||"").toLowerCase():"#document"}function Mn(t){var a;return(t==null||(a=t.ownerDocument)==null?void 0:a.defaultView)||window}function Ra(t){var a;return(a=(uw(t)?t.ownerDocument:t.document)||window.document)==null?void 0:a.documentElement}function uw(t){return Pu()?t instanceof Node||t instanceof Mn(t).Node:!1}function ua(t){return Pu()?t instanceof Element||t instanceof Mn(t).Element:!1}function ja(t){return Pu()?t instanceof HTMLElement||t instanceof Mn(t).HTMLElement:!1}function V0(t){return!Pu()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Mn(t).ShadowRoot}const bk=new Set(["inline","contents"]);function mi(t){const{overflow:a,overflowX:r,overflowY:s,display:o}=da(t);return/auto|scroll|overlay|hidden|clip/.test(a+s+r)&&!bk.has(o)}const wk=new Set(["table","td","th"]);function Sk(t){return wk.has(Bs(t))}const _k=[":popover-open",":modal"];function Uu(t){return _k.some(a=>{try{return t.matches(a)}catch{return!1}})}const jk=["transform","translate","scale","rotate","perspective"],Nk=["transform","translate","scale","rotate","perspective","filter"],Ck=["paint","layout","strict","content"];function ip(t){const a=cp(),r=ua(t)?da(t):t;return jk.some(s=>r[s]?r[s]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!a&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!a&&(r.filter?r.filter!=="none":!1)||Nk.some(s=>(r.willChange||"").includes(s))||Ck.some(s=>(r.contain||"").includes(s))}function Ek(t){let a=Kr(t);for(;ja(a)&&!Rs(a);){if(ip(a))return a;if(Uu(a))return null;a=Kr(a)}return null}function cp(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Rk=new Set(["html","body","#document"]);function Rs(t){return Rk.has(Bs(t))}function da(t){return Mn(t).getComputedStyle(t)}function Hu(t){return ua(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Kr(t){if(Bs(t)==="html")return t;const a=t.assignedSlot||t.parentNode||V0(t)&&t.host||Ra(t);return V0(a)?a.host:a}function dw(t){const a=Kr(t);return Rs(a)?t.ownerDocument?t.ownerDocument.body:t.body:ja(a)&&mi(a)?a:dw(a)}function li(t,a,r){var s;a===void 0&&(a=[]),r===void 0&&(r=!0);const o=dw(t),u=o===((s=t.ownerDocument)==null?void 0:s.body),d=Mn(o);if(u){const f=fm(d);return a.concat(d,d.visualViewport||[],mi(o)?o:[],f&&r?li(f):[])}return a.concat(o,li(o,[],r))}function fm(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function fw(t){const a=da(t);let r=parseFloat(a.width)||0,s=parseFloat(a.height)||0;const o=ja(t),u=o?t.offsetWidth:r,d=o?t.offsetHeight:s,f=hu(r)!==u||hu(s)!==d;return f&&(r=u,s=d),{width:r,height:s,$:f}}function up(t){return ua(t)?t:t.contextElement}function Cs(t){const a=up(t);if(!ja(a))return Sa(1);const r=a.getBoundingClientRect(),{width:s,height:o,$:u}=fw(a);let d=(u?hu(r.width):r.width)/s,f=(u?hu(r.height):r.height)/o;return(!d||!Number.isFinite(d))&&(d=1),(!f||!Number.isFinite(f))&&(f=1),{x:d,y:f}}const Tk=Sa(0);function hw(t){const a=Mn(t);return!cp()||!a.visualViewport?Tk:{x:a.visualViewport.offsetLeft,y:a.visualViewport.offsetTop}}function Ok(t,a,r){return a===void 0&&(a=!1),!r||a&&r!==Mn(t)?!1:a}function Rl(t,a,r,s){a===void 0&&(a=!1),r===void 0&&(r=!1);const o=t.getBoundingClientRect(),u=up(t);let d=Sa(1);a&&(s?ua(s)&&(d=Cs(s)):d=Cs(t));const f=Ok(u,r,s)?hw(u):Sa(0);let p=(o.left+f.x)/d.x,m=(o.top+f.y)/d.y,x=o.width/d.x,y=o.height/d.y;if(u){const w=Mn(u),S=s&&ua(s)?Mn(s):s;let j=w,_=fm(j);for(;_&&s&&S!==j;){const E=Cs(_),O=_.getBoundingClientRect(),R=da(_),N=O.left+(_.clientLeft+parseFloat(R.paddingLeft))*E.x,A=O.top+(_.clientTop+parseFloat(R.paddingTop))*E.y;p*=E.x,m*=E.y,x*=E.x,y*=E.y,p+=N,m+=A,j=Mn(_),_=fm(j)}}return pu({width:x,height:y,x:p,y:m})}function Bu(t,a){const r=Hu(t).scrollLeft;return a?a.left+r:Rl(Ra(t)).left+r}function mw(t,a){const r=t.getBoundingClientRect(),s=r.left+a.scrollLeft-Bu(t,r),o=r.top+a.scrollTop;return{x:s,y:o}}function Ak(t){let{elements:a,rect:r,offsetParent:s,strategy:o}=t;const u=o==="fixed",d=Ra(s),f=a?Uu(a.floating):!1;if(s===d||f&&u)return r;let p={scrollLeft:0,scrollTop:0},m=Sa(1);const x=Sa(0),y=ja(s);if((y||!y&&!u)&&((Bs(s)!=="body"||mi(d))&&(p=Hu(s)),ja(s))){const S=Rl(s);m=Cs(s),x.x=S.x+s.clientLeft,x.y=S.y+s.clientTop}const w=d&&!y&&!u?mw(d,p):Sa(0);return{width:r.width*m.x,height:r.height*m.y,x:r.x*m.x-p.scrollLeft*m.x+x.x+w.x,y:r.y*m.y-p.scrollTop*m.y+x.y+w.y}}function Mk(t){return Array.from(t.getClientRects())}function kk(t){const a=Ra(t),r=Hu(t),s=t.ownerDocument.body,o=An(a.scrollWidth,a.clientWidth,s.scrollWidth,s.clientWidth),u=An(a.scrollHeight,a.clientHeight,s.scrollHeight,s.clientHeight);let d=-r.scrollLeft+Bu(t);const f=-r.scrollTop;return da(s).direction==="rtl"&&(d+=An(a.clientWidth,s.clientWidth)-o),{width:o,height:u,x:d,y:f}}const G0=25;function Dk(t,a){const r=Mn(t),s=Ra(t),o=r.visualViewport;let u=s.clientWidth,d=s.clientHeight,f=0,p=0;if(o){u=o.width,d=o.height;const x=cp();(!x||x&&a==="fixed")&&(f=o.offsetLeft,p=o.offsetTop)}const m=Bu(s);if(m<=0){const x=s.ownerDocument,y=x.body,w=getComputedStyle(y),S=x.compatMode==="CSS1Compat"&&parseFloat(w.marginLeft)+parseFloat(w.marginRight)||0,j=Math.abs(s.clientWidth-y.clientWidth-S);j<=G0&&(u-=j)}else m<=G0&&(u+=m);return{width:u,height:d,x:f,y:p}}const Lk=new Set(["absolute","fixed"]);function zk(t,a){const r=Rl(t,!0,a==="fixed"),s=r.top+t.clientTop,o=r.left+t.clientLeft,u=ja(t)?Cs(t):Sa(1),d=t.clientWidth*u.x,f=t.clientHeight*u.y,p=o*u.x,m=s*u.y;return{width:d,height:f,x:p,y:m}}function K0(t,a,r){let s;if(a==="viewport")s=Dk(t,r);else if(a==="document")s=kk(Ra(t));else if(ua(a))s=zk(a,r);else{const o=hw(t);s={x:a.x-o.x,y:a.y-o.y,width:a.width,height:a.height}}return pu(s)}function pw(t,a){const r=Kr(t);return r===a||!ua(r)||Rs(r)?!1:da(r).position==="fixed"||pw(r,a)}function Pk(t,a){const r=a.get(t);if(r)return r;let s=li(t,[],!1).filter(f=>ua(f)&&Bs(f)!=="body"),o=null;const u=da(t).position==="fixed";let d=u?Kr(t):t;for(;ua(d)&&!Rs(d);){const f=da(d),p=ip(d);!p&&f.position==="fixed"&&(o=null),(u?!p&&!o:!p&&f.position==="static"&&!!o&&Lk.has(o.position)||mi(d)&&!p&&pw(t,d))?s=s.filter(x=>x!==d):o=f,d=Kr(d)}return a.set(t,s),s}function Uk(t){let{element:a,boundary:r,rootBoundary:s,strategy:o}=t;const d=[...r==="clippingAncestors"?Uu(a)?[]:Pk(a,this._c):[].concat(r),s],f=d[0],p=d.reduce((m,x)=>{const y=K0(a,x,o);return m.top=An(y.top,m.top),m.right=Gr(y.right,m.right),m.bottom=Gr(y.bottom,m.bottom),m.left=An(y.left,m.left),m},K0(a,f,o));return{width:p.right-p.left,height:p.bottom-p.top,x:p.left,y:p.top}}function Hk(t){const{width:a,height:r}=fw(t);return{width:a,height:r}}function Bk(t,a,r){const s=ja(a),o=Ra(a),u=r==="fixed",d=Rl(t,!0,u,a);let f={scrollLeft:0,scrollTop:0};const p=Sa(0);function m(){p.x=Bu(o)}if(s||!s&&!u)if((Bs(a)!=="body"||mi(o))&&(f=Hu(a)),s){const S=Rl(a,!0,u,a);p.x=S.x+a.clientLeft,p.y=S.y+a.clientTop}else o&&m();u&&!s&&o&&m();const x=o&&!s&&!u?mw(o,f):Sa(0),y=d.left+f.scrollLeft-p.x-x.x,w=d.top+f.scrollTop-p.y-x.y;return{x:y,y:w,width:d.width,height:d.height}}function Bh(t){return da(t).position==="static"}function Y0(t,a){if(!ja(t)||da(t).position==="fixed")return null;if(a)return a(t);let r=t.offsetParent;return Ra(t)===r&&(r=r.ownerDocument.body),r}function gw(t,a){const r=Mn(t);if(Uu(t))return r;if(!ja(t)){let o=Kr(t);for(;o&&!Rs(o);){if(ua(o)&&!Bh(o))return o;o=Kr(o)}return r}let s=Y0(t,a);for(;s&&Sk(s)&&Bh(s);)s=Y0(s,a);return s&&Rs(s)&&Bh(s)&&!ip(s)?r:s||Ek(t)||r}const Fk=async function(t){const a=this.getOffsetParent||gw,r=this.getDimensions,s=await r(t.floating);return{reference:Bk(t.reference,await a(t.floating),t.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function $k(t){return da(t).direction==="rtl"}const Ik={convertOffsetParentRelativeRectToViewportRelativeRect:Ak,getDocumentElement:Ra,getClippingRect:Uk,getOffsetParent:gw,getElementRects:Fk,getClientRects:Mk,getDimensions:Hk,getScale:Cs,isElement:ua,isRTL:$k};function vw(t,a){return t.x===a.x&&t.y===a.y&&t.width===a.width&&t.height===a.height}function qk(t,a){let r=null,s;const o=Ra(t);function u(){var f;clearTimeout(s),(f=r)==null||f.disconnect(),r=null}function d(f,p){f===void 0&&(f=!1),p===void 0&&(p=1),u();const m=t.getBoundingClientRect(),{left:x,top:y,width:w,height:S}=m;if(f||a(),!w||!S)return;const j=Vc(y),_=Vc(o.clientWidth-(x+w)),E=Vc(o.clientHeight-(y+S)),O=Vc(x),N={rootMargin:-j+"px "+-_+"px "+-E+"px "+-O+"px",threshold:An(0,Gr(1,p))||1};let A=!0;function L(z){const C=z[0].intersectionRatio;if(C!==p){if(!A)return d();C?d(!1,C):s=setTimeout(()=>{d(!1,1e-7)},1e3)}C===1&&!vw(m,t.getBoundingClientRect())&&d(),A=!1}try{r=new IntersectionObserver(L,{...N,root:o.ownerDocument})}catch{r=new IntersectionObserver(L,N)}r.observe(t)}return d(!0),u}function Vk(t,a,r,s){s===void 0&&(s={});const{ancestorScroll:o=!0,ancestorResize:u=!0,elementResize:d=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:p=!1}=s,m=up(t),x=o||u?[...m?li(m):[],...li(a)]:[];x.forEach(O=>{o&&O.addEventListener("scroll",r,{passive:!0}),u&&O.addEventListener("resize",r)});const y=m&&f?qk(m,r):null;let w=-1,S=null;d&&(S=new ResizeObserver(O=>{let[R]=O;R&&R.target===m&&S&&(S.unobserve(a),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var N;(N=S)==null||N.observe(a)})),r()}),m&&!p&&S.observe(m),S.observe(a));let j,_=p?Rl(t):null;p&&E();function E(){const O=Rl(t);_&&!vw(_,O)&&r(),_=O,j=requestAnimationFrame(E)}return r(),()=>{var O;x.forEach(R=>{o&&R.removeEventListener("scroll",r),u&&R.removeEventListener("resize",r)}),y?.(),(O=S)==null||O.disconnect(),S=null,p&&cancelAnimationFrame(j)}}const Gk=gk,Kk=vk,Yk=hk,Xk=xk,Qk=mk,X0=fk,Zk=yk,Jk=(t,a,r)=>{const s=new Map,o={platform:Ik,...r},u={...o.platform,_c:s};return dk(t,a,{...o,platform:u})};var Wk=typeof document<"u",eD=function(){},eu=Wk?v.useLayoutEffect:eD;function gu(t,a){if(t===a)return!0;if(typeof t!=typeof a)return!1;if(typeof t=="function"&&t.toString()===a.toString())return!0;let r,s,o;if(t&&a&&typeof t=="object"){if(Array.isArray(t)){if(r=t.length,r!==a.length)return!1;for(s=r;s--!==0;)if(!gu(t[s],a[s]))return!1;return!0}if(o=Object.keys(t),r=o.length,r!==Object.keys(a).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(a,o[s]))return!1;for(s=r;s--!==0;){const u=o[s];if(!(u==="_owner"&&t.$$typeof)&&!gu(t[u],a[u]))return!1}return!0}return t!==t&&a!==a}function yw(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function Q0(t,a){const r=yw(t);return Math.round(a*r)/r}function Fh(t){const a=v.useRef(t);return eu(()=>{a.current=t}),a}function tD(t){t===void 0&&(t={});const{placement:a="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:u,floating:d}={},transform:f=!0,whileElementsMounted:p,open:m}=t,[x,y]=v.useState({x:0,y:0,strategy:r,placement:a,middlewareData:{},isPositioned:!1}),[w,S]=v.useState(s);gu(w,s)||S(s);const[j,_]=v.useState(null),[E,O]=v.useState(null),R=v.useCallback(H=>{H!==z.current&&(z.current=H,_(H))},[]),N=v.useCallback(H=>{H!==C.current&&(C.current=H,O(H))},[]),A=u||j,L=d||E,z=v.useRef(null),C=v.useRef(null),B=v.useRef(x),q=p!=null,D=Fh(p),G=Fh(o),te=Fh(m),re=v.useCallback(()=>{if(!z.current||!C.current)return;const H={placement:a,strategy:r,middleware:w};G.current&&(H.platform=G.current),Jk(z.current,C.current,H).then(fe=>{const pe={...fe,isPositioned:te.current!==!1};le.current&&!gu(B.current,pe)&&(B.current=pe,Ms.flushSync(()=>{y(pe)}))})},[w,a,r,G,te]);eu(()=>{m===!1&&B.current.isPositioned&&(B.current.isPositioned=!1,y(H=>({...H,isPositioned:!1})))},[m]);const le=v.useRef(!1);eu(()=>(le.current=!0,()=>{le.current=!1}),[]),eu(()=>{if(A&&(z.current=A),L&&(C.current=L),A&&L){if(D.current)return D.current(A,L,re);re()}},[A,L,re,D,q]);const V=v.useMemo(()=>({reference:z,floating:C,setReference:R,setFloating:N}),[R,N]),M=v.useMemo(()=>({reference:A,floating:L}),[A,L]),P=v.useMemo(()=>{const H={position:r,left:0,top:0};if(!M.floating)return H;const fe=Q0(M.floating,x.x),pe=Q0(M.floating,x.y);return f?{...H,transform:"translate("+fe+"px, "+pe+"px)",...yw(M.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:fe,top:pe}},[r,f,M.floating,x.x,x.y]);return v.useMemo(()=>({...x,update:re,refs:V,elements:M,floatingStyles:P}),[x,re,V,M,P])}const nD=t=>{function a(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:t,fn(r){const{element:s,padding:o}=typeof t=="function"?t(r):t;return s&&a(s)?s.current!=null?X0({element:s.current,padding:o}).fn(r):{}:s?X0({element:s,padding:o}).fn(r):{}}}},aD=(t,a)=>({...Gk(t),options:[t,a]}),rD=(t,a)=>({...Kk(t),options:[t,a]}),lD=(t,a)=>({...Zk(t),options:[t,a]}),sD=(t,a)=>({...Yk(t),options:[t,a]}),oD=(t,a)=>({...Xk(t),options:[t,a]}),iD=(t,a)=>({...Qk(t),options:[t,a]}),cD=(t,a)=>({...nD(t),options:[t,a]});var uD="Arrow",xw=v.forwardRef((t,a)=>{const{children:r,width:s=10,height:o=5,...u}=t;return c.jsx(We.svg,{...u,ref:a,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:c.jsx("polygon",{points:"0,0 30,0 15,10"})})});xw.displayName=uD;var dD=xw;function dp(t){const[a,r]=v.useState(void 0);return cn(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const s=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const u=o[0];let d,f;if("borderBoxSize"in u){const p=u.borderBoxSize,m=Array.isArray(p)?p[0]:p;d=m.inlineSize,f=m.blockSize}else d=t.offsetWidth,f=t.offsetHeight;r({width:d,height:f})});return s.observe(t,{box:"border-box"}),()=>s.unobserve(t)}else r(void 0)},[t]),a}var fp="Popper",[bw,Fs]=Ea(fp),[fD,ww]=bw(fp),Sw=t=>{const{__scopePopper:a,children:r}=t,[s,o]=v.useState(null);return c.jsx(fD,{scope:a,anchor:s,onAnchorChange:o,children:r})};Sw.displayName=fp;var _w="PopperAnchor",jw=v.forwardRef((t,a)=>{const{__scopePopper:r,virtualRef:s,...o}=t,u=ww(_w,r),d=v.useRef(null),f=bt(a,d),p=v.useRef(null);return v.useEffect(()=>{const m=p.current;p.current=s?.current||d.current,m!==p.current&&u.onAnchorChange(p.current)}),s?null:c.jsx(We.div,{...o,ref:f})});jw.displayName=_w;var hp="PopperContent",[hD,mD]=bw(hp),Nw=v.forwardRef((t,a)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:u="center",alignOffset:d=0,arrowPadding:f=0,avoidCollisions:p=!0,collisionBoundary:m=[],collisionPadding:x=0,sticky:y="partial",hideWhenDetached:w=!1,updatePositionStrategy:S="optimized",onPlaced:j,..._}=t,E=ww(hp,r),[O,R]=v.useState(null),N=bt(a,se=>R(se)),[A,L]=v.useState(null),z=dp(A),C=z?.width??0,B=z?.height??0,q=s+(u!=="center"?"-"+u:""),D=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},G=Array.isArray(m)?m:[m],te=G.length>0,re={padding:D,boundary:G.filter(gD),altBoundary:te},{refs:le,floatingStyles:V,placement:M,isPositioned:P,middlewareData:H}=tD({strategy:"fixed",placement:q,whileElementsMounted:(...se)=>Vk(...se,{animationFrame:S==="always"}),elements:{reference:E.anchor},middleware:[aD({mainAxis:o+B,alignmentAxis:d}),p&&rD({mainAxis:!0,crossAxis:!1,limiter:y==="partial"?lD():void 0,...re}),p&&sD({...re}),oD({...re,apply:({elements:se,rects:Re,availableWidth:J,availableHeight:we})=>{const{width:Ce,height:Ee}=Re.reference,Pe=se.floating.style;Pe.setProperty("--radix-popper-available-width",`${J}px`),Pe.setProperty("--radix-popper-available-height",`${we}px`),Pe.setProperty("--radix-popper-anchor-width",`${Ce}px`),Pe.setProperty("--radix-popper-anchor-height",`${Ee}px`)}}),A&&cD({element:A,padding:f}),vD({arrowWidth:C,arrowHeight:B}),w&&iD({strategy:"referenceHidden",...re})]}),[fe,pe]=Rw(M),k=Ir(j);cn(()=>{P&&k?.()},[P,k]);const U=H.arrow?.x,X=H.arrow?.y,ne=H.arrow?.centerOffset!==0,[oe,ye]=v.useState();return cn(()=>{O&&ye(window.getComputedStyle(O).zIndex)},[O]),c.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...V,transform:P?V.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:oe,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:c.jsx(hD,{scope:r,placedSide:fe,onArrowChange:L,arrowX:U,arrowY:X,shouldHideArrow:ne,children:c.jsx(We.div,{"data-side":fe,"data-align":pe,..._,ref:N,style:{..._.style,animation:P?void 0:"none"}})})})});Nw.displayName=hp;var Cw="PopperArrow",pD={top:"bottom",right:"left",bottom:"top",left:"right"},Ew=v.forwardRef(function(a,r){const{__scopePopper:s,...o}=a,u=mD(Cw,s),d=pD[u.placedSide];return c.jsx("span",{ref:u.onArrowChange,style:{position:"absolute",left:u.arrowX,top:u.arrowY,[d]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[u.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[u.placedSide],visibility:u.shouldHideArrow?"hidden":void 0},children:c.jsx(dD,{...o,ref:r,style:{...o.style,display:"block"}})})});Ew.displayName=Cw;function gD(t){return t!==null}var vD=t=>({name:"transformOrigin",options:t,fn(a){const{placement:r,rects:s,middlewareData:o}=a,d=o.arrow?.centerOffset!==0,f=d?0:t.arrowWidth,p=d?0:t.arrowHeight,[m,x]=Rw(r),y={start:"0%",center:"50%",end:"100%"}[x],w=(o.arrow?.x??0)+f/2,S=(o.arrow?.y??0)+p/2;let j="",_="";return m==="bottom"?(j=d?y:`${w}px`,_=`${-p}px`):m==="top"?(j=d?y:`${w}px`,_=`${s.floating.height+p}px`):m==="right"?(j=`${-p}px`,_=d?y:`${S}px`):m==="left"&&(j=`${s.floating.width+p}px`,_=d?y:`${S}px`),{data:{x:j,y:_}}}});function Rw(t){const[a,r="center"]=t.split("-");return[a,r]}var mp=Sw,Fu=jw,pp=Nw,gp=Ew,$u="Popover",[Tw]=Ea($u,[Fs]),pi=Fs(),[yD,Xr]=Tw($u),Ow=t=>{const{__scopePopover:a,children:r,open:s,defaultOpen:o,onOpenChange:u,modal:d=!1}=t,f=pi(a),p=v.useRef(null),[m,x]=v.useState(!1),[y,w]=er({prop:s,defaultProp:o??!1,onChange:u,caller:$u});return c.jsx(mp,{...f,children:c.jsx(yD,{scope:a,contentId:on(),triggerRef:p,open:y,onOpenChange:w,onOpenToggle:v.useCallback(()=>w(S=>!S),[w]),hasCustomAnchor:m,onCustomAnchorAdd:v.useCallback(()=>x(!0),[]),onCustomAnchorRemove:v.useCallback(()=>x(!1),[]),modal:d,children:r})})};Ow.displayName=$u;var Aw="PopoverAnchor",xD=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=Xr(Aw,r),u=pi(r),{onCustomAnchorAdd:d,onCustomAnchorRemove:f}=o;return v.useEffect(()=>(d(),()=>f()),[d,f]),c.jsx(Fu,{...u,...s,ref:a})});xD.displayName=Aw;var Mw="PopoverTrigger",kw=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=Xr(Mw,r),u=pi(r),d=bt(a,o.triggerRef),f=c.jsx(We.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Uw(o.open),...s,ref:d,onClick:Ve(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?f:c.jsx(Fu,{asChild:!0,...u,children:f})});kw.displayName=Mw;var vp="PopoverPortal",[bD,wD]=Tw(vp,{forceMount:void 0}),Dw=t=>{const{__scopePopover:a,forceMount:r,children:s,container:o}=t,u=Xr(vp,a);return c.jsx(bD,{scope:a,forceMount:r,children:c.jsx(sr,{present:r||u.open,children:c.jsx(Mu,{asChild:!0,container:o,children:s})})})};Dw.displayName=vp;var Ts="PopoverContent",Lw=v.forwardRef((t,a)=>{const r=wD(Ts,t.__scopePopover),{forceMount:s=r.forceMount,...o}=t,u=Xr(Ts,t.__scopePopover);return c.jsx(sr,{present:s||u.open,children:u.modal?c.jsx(_D,{...o,ref:a}):c.jsx(jD,{...o,ref:a})})});Lw.displayName=Ts;var SD=Es("PopoverContent.RemoveScroll"),_D=v.forwardRef((t,a)=>{const r=Xr(Ts,t.__scopePopover),s=v.useRef(null),o=bt(a,s),u=v.useRef(!1);return v.useEffect(()=>{const d=s.current;if(d)return Gm(d)},[]),c.jsx(Du,{as:SD,allowPinchZoom:!0,children:c.jsx(zw,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ve(t.onCloseAutoFocus,d=>{d.preventDefault(),u.current||r.triggerRef.current?.focus()}),onPointerDownOutside:Ve(t.onPointerDownOutside,d=>{const f=d.detail.originalEvent,p=f.button===0&&f.ctrlKey===!0,m=f.button===2||p;u.current=m},{checkForDefaultPrevented:!1}),onFocusOutside:Ve(t.onFocusOutside,d=>d.preventDefault(),{checkForDefaultPrevented:!1})})})}),jD=v.forwardRef((t,a)=>{const r=Xr(Ts,t.__scopePopover),s=v.useRef(!1),o=v.useRef(!1);return c.jsx(zw,{...t,ref:a,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:u=>{t.onCloseAutoFocus?.(u),u.defaultPrevented||(s.current||r.triggerRef.current?.focus(),u.preventDefault()),s.current=!1,o.current=!1},onInteractOutside:u=>{t.onInteractOutside?.(u),u.defaultPrevented||(s.current=!0,u.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const d=u.target;r.triggerRef.current?.contains(d)&&u.preventDefault(),u.detail.originalEvent.type==="focusin"&&o.current&&u.preventDefault()}})}),zw=v.forwardRef((t,a)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:u,disableOutsidePointerEvents:d,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:x,...y}=t,w=Xr(Ts,r),S=pi(r);return Vm(),c.jsx(Au,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:u,children:c.jsx(fi,{asChild:!0,disableOutsidePointerEvents:d,onInteractOutside:x,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onDismiss:()=>w.onOpenChange(!1),children:c.jsx(pp,{"data-state":Uw(w.open),role:"dialog",id:w.contentId,...S,...y,ref:a,style:{...y.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Pw="PopoverClose",ND=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=Xr(Pw,r);return c.jsx(We.button,{type:"button",...s,ref:a,onClick:Ve(t.onClick,()=>o.onOpenChange(!1))})});ND.displayName=Pw;var CD="PopoverArrow",ED=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=pi(r);return c.jsx(gp,{...o,...s,ref:a})});ED.displayName=CD;function Uw(t){return t?"open":"closed"}var RD=Ow,TD=kw,OD=Dw,AD=Lw;function Iu({...t}){return c.jsx(RD,{"data-slot":"popover",...t})}function qu({...t}){return c.jsx(TD,{"data-slot":"popover-trigger",...t})}function Vu({className:t,align:a="center",sideOffset:r=4,...s}){return c.jsx(OD,{children:c.jsx(AD,{"data-slot":"popover-content",align:a,sideOffset:r,className:Xe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden animate-fade-in",t),...s})})}function Rt({options:t,value:a,onChange:r,placeholder:s="Select an option...",searchPlaceholder:o="Search...",emptyPlaceholder:u="No options found."}){const[d,f]=v.useState(!1),p=t.find(m=>m.value===a);return c.jsxs(Iu,{open:d,onOpenChange:f,children:[c.jsx(qu,{asChild:!0,children:c.jsxs(ve,{variant:"outline",role:"combobox","aria-expanded":d,className:"w-full justify-between transition-all-ease hover:scale-[1.02] active:scale-[0.98]",children:[p?p.label:s,c.jsx(Im,{className:"ml-2 h-4 w-4 shrink-0 opacity-50 transition-transform duration-200 group-data-[state=open]:rotate-180"})]})}),c.jsx(Vu,{className:"w-[--radix-popover-trigger-width] p-0 animate-fade-in",children:c.jsxs(Wm,{children:[c.jsx(ep,{placeholder:o}),c.jsxs(tp,{children:[c.jsx(np,{children:u}),c.jsx(ap,{children:t.map(m=>c.jsxs(rp,{value:m.value,onSelect:x=>{r(x===a?"":x),f(!1)},className:"transition-all-ease hover:bg-accent hover:text-accent-foreground",children:[c.jsx(zs,{className:Xe("mr-2 h-4 w-4 transition-opacity",a===m.value?"opacity-100":"opacity-0")}),m.label]},m.value))})]})]})})]})}const MD=v.forwardRef(({options:t,value:a,onChange:r,onEnter:s,searchPlaceholder:o="Search...",emptyPlaceholder:u="No options found.",inputPlaceholder:d="Type or select..."},f)=>{const[p,m]=v.useState(!1),[x,y]=v.useState(a||""),w=v.useRef(null);v.useImperativeHandle(f,()=>w.current),v.useEffect(()=>{y(a||"")},[a]);const S=O=>{const R=O.target.value;y(R),r(R)},j=O=>{O.key==="Enter"&&x.trim()&&s&&(s(x.trim()),y(""))},_=O=>{y(O),r(O),s&&(s(O),y("")),m(!1)},E=()=>x;return v.useImperativeHandle(f,()=>({...w.current,value:x,getCurrentValue:E,clearInput:()=>{y(""),r("")}})),c.jsxs("div",{className:"relative",children:[c.jsx(lt,{ref:w,value:x,onChange:S,onKeyDown:j,placeholder:d,className:"pr-10"}),c.jsxs(Iu,{open:p,onOpenChange:m,children:[c.jsx(qu,{asChild:!0,children:c.jsx(ve,{variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",children:c.jsx(Im,{className:"h-4 w-4 opacity-50"})})}),c.jsx(Vu,{className:"w-[--radix-popover-trigger-width] p-0 animate-fade-in",children:c.jsxs(Wm,{children:[c.jsx(ep,{placeholder:o}),c.jsxs(tp,{children:[c.jsx(np,{children:u}),c.jsx(ap,{children:t.map(O=>c.jsxs(rp,{value:O.value,onSelect:()=>_(O.value),className:"transition-all-ease hover:bg-accent hover:text-accent-foreground",children:[c.jsx(zs,{className:Xe("mr-2 h-4 w-4 transition-opacity",a===O.value?"opacity-100":"opacity-0")}),O.label]},O.value))})]})]})})]})]})});function kD(){const{t}=un(),{config:a,setConfig:r}=Yr(),[s,o]=v.useState(null),[u,d]=v.useState(null),[f,p]=v.useState({}),[m,x]=v.useState({}),[y,w]=v.useState({}),[S,j]=v.useState([]),[_,E]=v.useState(null),[O,R]=v.useState(!1),[N,A]=v.useState([]),[L,z]=v.useState({}),[C,B]=v.useState(null),[q,D]=v.useState(null),[G,te]=v.useState(""),[re,le]=v.useState([]),[V,M]=v.useState([]),P=v.useRef(null);if(v.useEffect(()=>{(async()=>{try{const ce=await fetch("https://pub-0dc3e1677e894f07bbea11b17a29e032.r2.dev/providers.json");if(ce.ok){const me=await ce.json();A(me||[])}else console.error("Failed to fetch provider templates")}catch(ce){console.error("Failed to fetch provider templates:",ce)}})()},[]),v.useEffect(()=>{(async()=>{try{const ce=await nt.get("/transformers");j(ce.transformers)}catch(ce){console.error("Failed to fetch transformers:",ce)}})()},[]),v.useEffect(()=>{const ue=async()=>{try{const me=await nt.getProviderHealth();le(me.states||[])}catch(me){console.error("Failed to fetch provider health:",me)}};ue();const ce=setInterval(ue,3e4);return()=>clearInterval(ce)},[]),v.useEffect(()=>{const ue=async()=>{try{const me=await nt.getProviderQuota();M(me.quotas||[])}catch(me){console.error("Failed to fetch provider quota:",me)}};ue();const ce=setInterval(ue,3e4);return()=>clearInterval(ce)},[]),!a)return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"flex flex-row items-center justify-between border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("providers.title")})}),c.jsx(Xn,{className:"flex-grow flex items-center justify-center p-4",children:c.jsx("div",{className:"text-gray-500",children:"Loading providers configuration..."})})]});const H=Array.isArray(a.Providers)?a.Providers:[],fe=()=>{const ue={name:"",api_base_url:"",api_key:"",models:[]};o(a.Providers.length),E(ue),R(!0),z(ce=>({...ce,[a.Providers.length]:!1})),B(null),D(null)},pe=ue=>{const ce=H.indexOf(Qe[ue]),me=a.Providers[ce];o(ce),E(JSON.parse(JSON.stringify(me))),R(!1),z(xe=>({...xe,[ce]:!1})),B(null),D(null)},k=()=>{if(!_)return;if(!_.name||_.name.trim()===""){D(t("providers.name_required"));return}const ue=_.name.trim();if(a.Providers.some((me,xe)=>!O&&xe===s?!1:me.name.toLowerCase()===ue.toLowerCase())){D(t("providers.name_duplicate"));return}if(!_.api_key||_.api_key.trim()===""){B(t("providers.api_key_required"));return}if(B(null),D(null),s!==null&&_){const me=[...a.Providers];O?me.push(_):me[s]=_,r({...a,Providers:me})}s!==null&&z(me=>{const xe={...me};return delete xe[s],xe}),o(null),E(null),R(!1)},U=()=>{s!==null&&(p(ue=>{const ce={...ue};return delete ce[s],ce}),z(ue=>{const ce={...ue};return delete ce[s],ce})),o(null),E(null),R(!1),B(null),D(null)},X=ue=>{d(ue)},ne=ue=>{const ce=H.indexOf(Qe[ue]),me=[...a.Providers];me.splice(ce,1),r({...a,Providers:me}),d(null)},oe=(ue,ce,me)=>{if(_){const xe={..._,[ce]:me};E(xe)}},ye=(ue,ce)=>{if(!ce||!_)return;const me={..._};me.transformer||(me.transformer={use:[]}),me.transformer.use=[...me.transformer.use,ce],E(me)},se=(ue,ce)=>{if(!_)return;const me={..._};if(me.transformer){const xe=[...me.transformer.use];xe.splice(ce,1),me.transformer.use=xe,xe.length===0&&Object.keys(me.transformer).length===1&&delete me.transformer}E(me)},Re=(ue,ce,me)=>{if(!me||!_)return;const xe={..._};xe.transformer||(xe.transformer={use:[]}),xe.transformer[ce]||(xe.transformer[ce]={use:[]}),xe.transformer[ce].use=[...xe.transformer[ce].use,me],E(xe)},J=(ue,ce,me)=>{if(!_)return;const xe={..._};if(xe.transformer&&xe.transformer[ce]){const Be=[...xe.transformer[ce].use];Be.splice(me,1),xe.transformer[ce].use=Be,Be.length===0&&Object.keys(xe.transformer[ce]).length===1&&delete xe.transformer[ce]}E(xe)},we=(ue,ce,me,xe)=>{if(!_)return;const Be={..._};if(Be.transformer||(Be.transformer={use:[]}),Be.transformer.use&&Be.transformer.use.length>ce){const Oe=Be.transformer.use[ce];if(Array.isArray(Oe)){const Ge=[...Oe];if(Ge.length>1&&typeof Ge[1]=="object"&&Ge[1]!==null){const bn={...Ge[1],[me]:xe};Ge[1]=bn}else if(Ge.length>1){const wt={[me]:xe};Ge.splice(1,Ge.length-1,wt)}else{const wt={[me]:xe};Ge.push(wt)}Be.transformer.use[ce]=Ge}else{const Ge={[me]:xe};Be.transformer.use[ce]=[Oe,Ge]}}E(Be)},Ce=(ue,ce,me)=>{if(!_)return;const xe={..._};if(!xe.transformer?.use||xe.transformer.use.length<=ce)return;const Be=xe.transformer.use[ce];if(Array.isArray(Be)&&Be.length>1){const Oe=[...Be];if(typeof Oe[1]=="object"&&Oe[1]!==null){const Ge={...Oe[1]};delete Ge[me],Object.keys(Ge).length===0?Oe.splice(1,1):Oe[1]=Ge,xe.transformer.use[ce]=Oe,E(xe)}}},Ee=(ue,ce,me,xe,Be)=>{if(!_)return;const Oe={..._};if(Oe.transformer||(Oe.transformer={use:[]}),Oe.transformer[ce]||(Oe.transformer[ce]={use:[]}),Oe.transformer[ce].use&&Oe.transformer[ce].use.length>me){const Ge=Oe.transformer[ce].use[me];if(Array.isArray(Ge)){const wt=[...Ge];if(wt.length>1&&typeof wt[1]=="object"&&wt[1]!==null){const an={...wt[1],[xe]:Be};wt[1]=an}else if(wt.length>1){const bn={[xe]:Be};wt.splice(1,wt.length-1,bn)}else{const bn={[xe]:Be};wt.push(bn)}Oe.transformer[ce].use[me]=wt}else{const wt={[xe]:Be};Oe.transformer[ce].use[me]=[Ge,wt]}}E(Oe)},Pe=(ue,ce,me,xe)=>{if(!_)return;const Be={..._};if(!Be.transformer?.[ce]?.use||Be.transformer[ce].use.length<=me)return;const Oe=Be.transformer[ce].use[me];if(Array.isArray(Oe)&&Oe.length>1){const Ge=[...Oe];if(typeof Ge[1]=="object"&&Ge[1]!==null){const wt={...Ge[1]};delete wt[xe],Object.keys(wt).length===0?Ge.splice(1,1):Ge[1]=wt,Be.transformer[ce].use[me]=Ge,E(Be)}}},gt=(ue,ce)=>{if(!ce.trim()||!_)return;const me={..._},xe=Array.isArray(me.models)?[...me.models]:[];xe.includes(ce.trim())||(xe.push(ce.trim()),me.models=xe,E(me))},Se=ue=>{if(ue)try{const ce=JSON.parse(ue);if(ce){const me=_?.name,xe=JSON.parse(JSON.stringify(ce));!O&&me&&(xe.name=me),E(xe)}}catch(ce){console.error("Failed to parse template",ce)}},qe=(ue,ce)=>{if(!_)return;const me={..._},xe=Array.isArray(me.models)?[...me.models]:[];ce>=0&&ce<xe.length&&(xe.splice(ce,1),me.models=xe,E(me))},Ue=_||(s!==null?H[s]:null),Qe=H.filter(ue=>{if(!G)return!0;const ce=G.toLowerCase();return ue.name&&ue.name.toLowerCase().includes(ce)||ue.api_base_url&&ue.api_base_url.toLowerCase().includes(ce)?!0:ue.models&&Array.isArray(ue.models)?ue.models.some(me=>me&&me.toLowerCase().includes(ce)):!1});return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsxs(ia,{className:"flex flex-col border-b p-4 gap-3",children:[c.jsxs("div",{className:"flex flex-row items-center justify-between",children:[c.jsxs(ca,{className:"text-lg",children:[t("providers.title")," ",c.jsxs("span",{className:"text-sm font-normal text-gray-500",children:["(",Qe.length,"/",H.length,")"]})]}),c.jsx(ve,{onClick:fe,children:t("providers.add")})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx(qm,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500"}),c.jsx(lt,{placeholder:t("providers.search"),value:G,onChange:ue=>te(ue.target.value),className:"pl-8"})]}),G&&c.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>te(""),children:c.jsx(b1,{className:"h-4 w-4"})})]})]}),c.jsx(Xn,{className:"flex-grow overflow-y-auto p-4",children:c.jsx(TM,{providers:Qe,healthStates:re,quotaUsages:V,onEdit:pe,onRemove:X})}),c.jsx(xa,{open:s!==null,onOpenChange:ue=>{ue||U()},children:c.jsxs(la,{className:"max-h-[80vh] flex flex-col sm:max-w-2xl",children:[c.jsx(sa,{children:c.jsx(oa,{children:t("providers.edit")})}),Ue&&s!==null&&c.jsxs("div",{className:"space-y-4 p-4 overflow-y-auto flex-grow",children:[N.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("providers.import_from_template")}),c.jsx(Rt,{options:N.map(ue=>({label:ue.name,value:JSON.stringify(ue)})),value:"",onChange:Se,placeholder:t("providers.select_template"),emptyPlaceholder:t("providers.no_templates_found")})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"name",children:t("providers.name")}),c.jsx(lt,{id:"name",value:Ue.name||"",onChange:ue=>{oe(s,"name",ue.target.value),q&&D(null)},className:q?"border-red-500":""}),q&&c.jsx("p",{className:"text-sm text-red-500",children:q})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"api_base_url",children:t("providers.api_base_url")}),c.jsx(lt,{id:"api_base_url",value:Ue.api_base_url||"",onChange:ue=>oe(s,"api_base_url",ue.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"api_key",children:t("providers.api_key")}),c.jsxs("div",{className:"relative",children:[c.jsx(lt,{id:"api_key",type:L[s||0]?"text":"password",value:Ue.api_key||"",onChange:ue=>oe(s,"api_key",ue.target.value),className:C?"border-red-500":""}),c.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 transform -translate-y-1/2 h-8 w-8",onClick:()=>{const ue=s||0;z(ce=>({...ce,[ue]:!ce[ue]}))},children:L[s||0]?c.jsx(cO,{className:"h-4 w-4"}):c.jsx(dO,{className:"h-4 w-4"})})]}),C&&c.jsx("p",{className:"text-sm text-red-500",children:C})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"models",children:t("providers.models")}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx("div",{className:"flex-1",children:f[s]?c.jsx(MD,{ref:P,options:(Ue.models||[]).map(ue=>({label:ue,value:ue})),value:"",onChange:()=>{},onEnter:ue=>{s!==null&&gt(s,ue)},inputPlaceholder:t("providers.models_placeholder")}):c.jsx(lt,{id:"models",placeholder:t("providers.models_placeholder"),onKeyDown:ue=>{ue.key==="Enter"&&ue.currentTarget.value.trim()&&s!==null&&(gt(s,ue.currentTarget.value),ue.currentTarget.value="")}})}),c.jsx(ve,{onClick:()=>{if(f[s]&&P.current){const ue=P.current,ce=ue.getCurrentValue();ce&&ce.trim()&&s!==null&&(gt(s,ce.trim()),ue.clearInput())}else{const ue=document.getElementById("models");ue&&ue.value.trim()&&s!==null&&(gt(s,ue.value),ue.value="")}},children:t("providers.add_model")})]}),c.jsx("div",{className:"flex flex-wrap gap-2 pt-2",children:(Ue.models||[]).map((ue,ce)=>c.jsxs(Ur,{variant:"outline",className:"font-normal flex items-center gap-1",children:[ue,c.jsx("button",{type:"button",className:"ml-1 rounded-full hover:bg-gray-200",onClick:()=>s!==null&&qe(s,ce),children:c.jsx(Wa,{className:"h-3 w-3"})})]},ce))})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("providers.provider_transformer")}),c.jsx("div",{className:"flex gap-2",children:c.jsx(Rt,{options:S.map(ue=>({label:ue.name,value:ue.name})),value:"",onChange:ue=>{s!==null&&ye(s,ue)},placeholder:t("providers.select_transformer"),emptyPlaceholder:t("providers.no_transformers")})}),Ue.transformer?.use&&Ue.transformer.use.length>0&&c.jsxs("div",{className:"space-y-2 mt-2",children:[c.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("providers.selected_transformers")}),Ue.transformer.use.map((ue,ce)=>c.jsxs("div",{className:"border rounded-md p-3",children:[c.jsxs("div",{className:"flex gap-2 items-center mb-2",children:[c.jsx("div",{className:"flex-1 bg-gray-50 rounded p-2 text-sm",children:typeof ue=="string"?ue:Array.isArray(ue)?String(ue[0]):String(ue)}),c.jsx(ve,{variant:"outline",size:"icon",onClick:()=>{s!==null&&se(s,ce)},children:c.jsx(kn,{className:"h-4 w-4"})})]}),c.jsxs("div",{className:"mt-2 pl-4 border-l-2 border-gray-200",children:[c.jsx(Te,{className:"text-sm",children:t("providers.transformer_parameters")}),c.jsxs("div",{className:"space-y-2 mt-1",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx(lt,{placeholder:t("providers.parameter_name"),value:m[`provider-${s}-transformer-${ce}`]?.name||"",onChange:me=>{const xe=`provider-${s}-transformer-${ce}`;x(Be=>({...Be,[xe]:{...Be[xe]||{name:"",value:""},name:me.target.value}}))}}),c.jsx(lt,{placeholder:t("providers.parameter_value"),value:m[`provider-${s}-transformer-${ce}`]?.value||"",onChange:me=>{const xe=`provider-${s}-transformer-${ce}`;x(Be=>({...Be,[xe]:{...Be[xe]||{name:"",value:""},value:me.target.value}}))}}),c.jsx(ve,{size:"sm",onClick:()=>{if(s!==null){const me=`provider-${s}-transformer-${ce}`,xe=m[me];xe&&xe.name&&xe.value&&(we(s,ce,xe.name,xe.value),x(Be=>({...Be,[me]:{name:"",value:""}})))}},children:c.jsx(du,{className:"h-4 w-4"})})]}),(()=>{if(!Ue.transformer?.use||Ue.transformer.use.length<=ce)return null;const me=Ue.transformer.use[ce];let xe={};return Array.isArray(me)&&me.length>1&&typeof me[1]=="object"&&me[1]!==null&&(xe=me[1]),Object.keys(xe).length>0?c.jsx("div",{className:"space-y-1",children:Object.entries(xe).map(([Be,Oe])=>c.jsxs("div",{className:"flex items-center justify-between bg-gray-50 rounded p-2",children:[c.jsxs("div",{className:"text-sm",children:[c.jsxs("span",{className:"font-medium",children:[Be,":"]})," ",String(Oe)]}),c.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>{s!==null&&Ce(s,ce,Be)},children:c.jsx(Wa,{className:"h-3 w-3"})})]},Be))}):null})()]})]})]},ce))]})]}),Ue.models&&Ue.models.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("providers.model_transformers")}),c.jsx("div",{className:"space-y-3",children:(Ue.models||[]).map((ue,ce)=>c.jsxs("div",{className:"border rounded-md p-3",children:[c.jsx("div",{className:"font-medium text-sm mb-2",children:ue}),c.jsx("div",{className:"flex gap-2",children:c.jsx("div",{className:"flex-1 flex gap-2",children:c.jsx(Rt,{options:S.map(me=>({label:me.name,value:me.name})),value:"",onChange:me=>{s!==null&&Re(s,ue,me)},placeholder:t("providers.select_transformer"),emptyPlaceholder:t("providers.no_transformers")})})}),Ue.transformer?.[ue]?.use&&Ue.transformer[ue].use.length>0&&c.jsxs("div",{className:"space-y-2 mt-2",children:[c.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("providers.selected_transformers")}),Ue.transformer[ue].use.map((me,xe)=>c.jsxs("div",{className:"border rounded-md p-3",children:[c.jsxs("div",{className:"flex gap-2 items-center mb-2",children:[c.jsx("div",{className:"flex-1 bg-gray-50 rounded p-2 text-sm",children:typeof me=="string"?me:Array.isArray(me)?String(me[0]):String(me)}),c.jsx(ve,{variant:"outline",size:"icon",onClick:()=>{s!==null&&J(s,ue,xe)},children:c.jsx(kn,{className:"h-4 w-4"})})]}),c.jsxs("div",{className:"mt-2 pl-4 border-l-2 border-gray-200",children:[c.jsx(Te,{className:"text-sm",children:t("providers.transformer_parameters")}),c.jsxs("div",{className:"space-y-2 mt-1",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx(lt,{placeholder:t("providers.parameter_name"),value:y[`model-${s}-${ue}-transformer-${xe}`]?.name||"",onChange:Be=>{const Oe=`model-${s}-${ue}-transformer-${xe}`;w(Ge=>({...Ge,[Oe]:{...Ge[Oe]||{name:"",value:""},name:Be.target.value}}))}}),c.jsx(lt,{placeholder:t("providers.parameter_value"),value:y[`model-${s}-${ue}-transformer-${xe}`]?.value||"",onChange:Be=>{const Oe=`model-${s}-${ue}-transformer-${xe}`;w(Ge=>({...Ge,[Oe]:{...Ge[Oe]||{name:"",value:""},value:Be.target.value}}))}}),c.jsx(ve,{size:"sm",onClick:()=>{if(s!==null){const Be=`model-${s}-${ue}-transformer-${xe}`,Oe=y[Be];Oe&&Oe.name&&Oe.value&&(Ee(s,ue,xe,Oe.name,Oe.value),w(Ge=>({...Ge,[Be]:{name:"",value:""}})))}},children:c.jsx(du,{className:"h-4 w-4"})})]}),(()=>{if(!Ue.transformer?.[ue]?.use||Ue.transformer[ue].use.length<=xe)return null;const Be=Ue.transformer[ue].use[xe];let Oe={};return Array.isArray(Be)&&Be.length>1&&typeof Be[1]=="object"&&Be[1]!==null&&(Oe=Be[1]),Object.keys(Oe).length>0?c.jsx("div",{className:"space-y-1",children:Object.entries(Oe).map(([Ge,wt])=>c.jsxs("div",{className:"flex items-center justify-between bg-gray-50 rounded p-2",children:[c.jsxs("div",{className:"text-sm",children:[c.jsxs("span",{className:"font-medium",children:[Ge,":"]})," ",String(wt)]}),c.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>{s!==null&&Pe(s,ue,xe,Ge)},children:c.jsx(Wa,{className:"h-3 w-3"})})]},Ge))}):null})()]})]})]},xe))]})]},ce))})]})]}),c.jsx("div",{className:"space-y-3 mt-auto",children:c.jsx("div",{className:"flex justify-end gap-2",children:c.jsx(ve,{onClick:k,children:t("app.save")})})})]})}),c.jsx(xa,{open:u!==null,onOpenChange:()=>d(null),children:c.jsxs(la,{children:[c.jsxs(sa,{children:[c.jsx(oa,{children:t("providers.delete")}),c.jsx(Nl,{children:t("providers.delete_provider_confirm")})]}),c.jsxs(qr,{children:[c.jsx(ve,{variant:"outline",onClick:()=>d(null),children:t("providers.cancel")}),c.jsx(ve,{variant:"destructive",onClick:()=>u!==null&&ne(u),children:t("providers.delete")})]})]})})]})}function DD(){const{t}=un(),{config:a,setConfig:r}=Yr();if(!a)return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("router.title")})}),c.jsx(Xn,{className:"flex-grow flex items-center justify-center p-4",children:c.jsx("div",{className:"text-gray-500",children:"Loading router configuration..."})})]});const s=a.Router||{default:"",background:"",think:"",longContext:"",longContextThreshold:6e4,webSearch:"",image:""},o=(p,m)=>{const y={...a.Router||{},[p]:m};r({...a,Router:y})},u=p=>{r({...a,forceUseImageAgent:p})},f=(Array.isArray(a.Providers)?a.Providers:[]).flatMap(p=>{if(!p)return[];const m=Array.isArray(p.models)?p.models:[],x=p.name||"Unknown Provider";return m.map(y=>({value:`${x},${y||"Unknown Model"}`,label:`${x}, ${y||"Unknown Model"}`}))});return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("router.title")})}),c.jsxs(Xn,{className:"flex-grow space-y-5 overflow-y-auto p-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.default")}),c.jsx(Rt,{options:f,value:s.default||"",onChange:p=>o("default",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.background")}),c.jsx(Rt,{options:f,value:s.background||"",onChange:p=>o("background",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.think")}),c.jsx(Rt,{options:f,value:s.think||"",onChange:p=>o("think",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsx("div",{className:"space-y-2",children:c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsxs("div",{className:"flex-1",children:[c.jsx(Te,{children:t("router.longContext")}),c.jsx(Rt,{options:f,value:s.longContext||"",onChange:p=>o("longContext",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"w-48",children:[c.jsx(Te,{children:t("router.longContextThreshold")}),c.jsx(lt,{type:"number",value:s.longContextThreshold||6e4,onChange:p=>o("longContextThreshold",parseInt(p.target.value)||6e4),placeholder:"60000"})]})]})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.webSearch")}),c.jsx(Rt,{options:f,value:s.webSearch||"",onChange:p=>o("webSearch",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsx("div",{className:"space-y-2",children:c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsxs("div",{className:"flex-1",children:[c.jsxs(Te,{children:[t("router.image")," (beta)"]}),c.jsx(Rt,{options:f,value:s.image||"",onChange:p=>o("image",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"w-48",children:[c.jsx(Te,{htmlFor:"forceUseImageAgent",children:t("router.forceUseImageAgent")}),c.jsxs("select",{id:"forceUseImageAgent",value:a.forceUseImageAgent?"true":"false",onChange:p=>u(p.target.value==="true"),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[c.jsx("option",{value:"false",children:t("common.no")}),c.jsx("option",{value:"true",children:t("common.yes")})]})]})]})})]})]})}function Z0(t,a){(a==null||a>t.length)&&(a=t.length);for(var r=0,s=Array(a);r<a;r++)s[r]=t[r];return s}function LD(t){if(Array.isArray(t))return t}function zD(t,a,r){return(a=ID(a))in t?Object.defineProperty(t,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[a]=r,t}function PD(t,a){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var s,o,u,d,f=[],p=!0,m=!1;try{if(u=(r=r.call(t)).next,a!==0)for(;!(p=(s=u.call(r)).done)&&(f.push(s.value),f.length!==a);p=!0);}catch(x){m=!0,o=x}finally{try{if(!p&&r.return!=null&&(d=r.return(),Object(d)!==d))return}finally{if(m)throw o}}return f}}function UD(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
62
+ For more information, see https://radix-ui.com/primitives/docs/components/${a.docsSlug}`;return v.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},wM="DialogDescriptionWarning",SM=({contentRef:t,descriptionId:a})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Y1(wM).contentName}}.`;return v.useEffect(()=>{const o=t.current?.getAttribute("aria-describedby");a&&o&&(document.getElementById(a)||console.warn(s))},[s,t,a]),null},X1=L1,Q1=U1,Qm=H1,Zm=B1,Z1=$1,J1=q1,_M=G1;const xa=X1,jM=Q1,W1=v.forwardRef(({className:t,...a},r)=>c.jsx(Qm,{ref:r,className:Xe("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a}));W1.displayName=Qm.displayName;const la=v.forwardRef(({className:t,children:a,...r},s)=>c.jsxs(jM,{children:[c.jsx(W1,{}),c.jsxs(Zm,{ref:s,className:Xe("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg animate-scale-in",t),...r,children:[a,c.jsxs(_M,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground transition-all-ease hover:scale-110",children:[c.jsx(Wa,{className:"h-4 w-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));la.displayName=Zm.displayName;const sa=({className:t,...a})=>c.jsx("div",{className:Xe("flex flex-col space-y-1.5 text-center sm:text-left",t),...a});sa.displayName="DialogHeader";const qr=({className:t,...a})=>c.jsx("div",{className:Xe("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});qr.displayName="DialogFooter";const oa=v.forwardRef(({className:t,...a},r)=>c.jsx(Z1,{ref:r,className:Xe("text-lg font-semibold leading-none tracking-tight",t),...a}));oa.displayName=Z1.displayName;const Nl=v.forwardRef(({className:t,...a},r)=>c.jsx(J1,{ref:r,className:Xe("text-sm text-muted-foreground",t),...a}));Nl.displayName=J1.displayName;function NM(){const{t}=un(),{config:a,setConfig:r}=Yr(),[s,o]=v.useState(null),[u,d]=v.useState(null),[f,p]=v.useState(null);if(!a)return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"flex flex-row items-center justify-between border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("transformers.title")})}),c.jsx(Xn,{className:"flex-grow flex items-center justify-center p-4",children:c.jsx("div",{className:"text-gray-500",children:"Loading transformers configuration..."})})]});const m=Array.isArray(a.transformers)?a.transformers:[],x=()=>{p({name:"",path:"",options:{}}),o(m.length)},y=E=>{const O=[...m];O.splice(E,1),r({...a,transformers:O}),d(null)},w=(E,O,R,N)=>{if(E<m.length){const A=[...m];N!==void 0?A[E].options[N]=R:A[E][O]=R,r({...a,transformers:A})}else if(f){const A={...f};N!==void 0?A.options[N]=R:A[O]=R,p(A)}},S=s!==null?s<m.length?m[s]:f:null,j=()=>{if(f&&s===m.length){const E=[...m,f];r({...a,transformers:E})}o(null),p(null)},_=()=>{o(null),p(null)};return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsxs(ia,{className:"flex flex-row items-center justify-between border-b p-4",children:[c.jsxs(ca,{className:"text-lg",children:[t("transformers.title")," ",c.jsxs("span",{className:"text-sm font-normal text-gray-500",children:["(",m.length,")"]})]}),c.jsx(ve,{onClick:x,children:t("transformers.add")})]}),c.jsx(Xn,{className:"flex-grow overflow-y-auto p-4",children:c.jsx(YO,{transformers:m,onEdit:o,onRemove:d})}),c.jsx(xa,{open:s!==null,onOpenChange:_,children:c.jsxs(la,{children:[c.jsx(sa,{children:c.jsx(oa,{children:t("transformers.edit")})}),S&&s!==null&&c.jsxs("div",{className:"space-y-4 py-4 px-6 max-h-96 overflow-y-auto",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"transformer-path",children:t("transformers.path")}),c.jsx(lt,{id:"transformer-path",value:S.path||"",onChange:E=>w(s,"path",E.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Te,{children:t("transformers.parameters")}),c.jsx(ve,{variant:"outline",size:"sm",onClick:()=>{const E=S.options||{},O=`param${Object.keys(E).length+1}`;if(s!==null){const R={...E,[O]:""};if(s<m.length){const N=[...m];N[s].options=R,r({...a,transformers:N})}else f&&p({...f,options:R})}},children:c.jsx(du,{className:"h-4 w-4"})})]}),Object.entries(S.options||{}).map(([E,O])=>c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(lt,{value:E,onChange:R=>{const A={...S.options||{}};if(delete A[E],A[R.target.value]=O,s!==null)if(s<m.length){const L=[...m];L[s].options=A,r({...a,transformers:L})}else f&&p({...f,options:A})},className:"flex-1"}),c.jsx(lt,{value:O,onChange:R=>{s!==null&&w(s,"parameters",R.target.value,E)},className:"flex-1"}),c.jsx(ve,{variant:"outline",size:"icon",onClick:()=>{if(s!==null){const N={...S.options||{}};if(delete N[E],s<m.length){const A=[...m];A[s].options=N,r({...a,transformers:A})}else f&&p({...f,options:N})}},children:c.jsx(kn,{className:"h-4 w-4"})})]},E))]})]}),c.jsxs(qr,{children:[c.jsx(ve,{variant:"outline",onClick:_,children:t("app.cancel")}),c.jsx(ve,{onClick:j,children:t("app.save")})]})]})}),c.jsx(xa,{open:u!==null,onOpenChange:()=>d(null),children:c.jsxs(la,{children:[c.jsxs(sa,{children:[c.jsx(oa,{children:t("transformers.delete")}),c.jsx(Nl,{children:t("transformers.delete_transformer_confirm")})]}),c.jsxs(qr,{children:[c.jsx(ve,{variant:"outline",onClick:()=>d(null),children:t("app.cancel")}),c.jsx(ve,{variant:"destructive",onClick:()=>u!==null&&y(u),children:t("app.delete")})]})]})})]})}const CM=$m("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Ur({className:t,variant:a,...r}){return c.jsx("div",{className:Xe(CM({variant:a}),t),...r})}function EM(t,a){if(!a||a.length===0)return{status:"closed",hasFailure:!1};const r=a.filter(u=>u.provider===t);if(r.length===0)return{status:"closed",hasFailure:!1};const s=r.filter(u=>u.status==="open"),o=r.filter(u=>u.status==="half-open");return s.length>0?{status:"open",hasFailure:!0,lastError:s[0].lastError}:o.length>0?{status:"half-open",hasFailure:!0,lastError:o[0].lastError}:{status:"closed",hasFailure:!1}}function RM({status:t}){const a={closed:"bg-green-500",open:"bg-red-500","half-open":"bg-yellow-500",unknown:"bg-gray-400"},r={closed:"Healthy",open:"Failed","half-open":"Recovering",unknown:"Unknown"};return c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("div",{className:`w-3 h-3 rounded-full ${a[t]} animate-pulse`,title:r[t]}),c.jsx("span",{className:"text-xs text-gray-500",children:r[t]})]})}function L0(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function z0({label:t,used:a,limit:r,resetTime:s,t:o}){if(a===0&&!r)return null;const u=r?Math.min(100,a/r*100):void 0,d=L0(a);r&&L0(r);let f="bg-emerald-400",p="text-emerald-600";return u!==void 0&&(u>=90?(f="bg-red-500",p="text-red-600"):u>=70?(f="bg-amber-400",p="text-amber-600"):u>=40&&(f="bg-blue-400",p="text-blue-600")),c.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[c.jsx("span",{className:"w-12 shrink-0",children:t}),c.jsx("div",{className:"flex-1 h-2.5 bg-gray-200 rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${f} transition-all duration-300`,style:{width:u!==void 0?`${Math.max(2,u)}%`:"0%"}})}),c.jsx("span",{className:`w-14 shrink-0 text-right tabular-nums font-medium ${p}`,children:u!==void 0?`${u.toFixed(1)}%`:d}),s&&c.jsx("span",{className:"w-24 shrink-0 text-right text-gray-400",children:o("providers.quota_reset",{time:new Date(s).toLocaleTimeString()})})]})}function TM({providers:t,healthStates:a,quotaUsages:r,onEdit:s,onRemove:o}){const{t:u}=un();return!t||!Array.isArray(t)?c.jsx("div",{className:"space-y-3",children:c.jsx("div",{className:"flex items-center justify-center rounded-md border bg-white p-8 text-gray-500",children:"No providers configured"})}):c.jsx("div",{className:"space-y-3",children:t.map((d,f)=>{if(!d)return c.jsxs("div",{className:"flex items-start justify-between rounded-md border bg-white p-4 transition-all hover:shadow-md animate-slide-in hover:scale-[1.01]",children:[c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("p",{className:"text-md font-semibold text-gray-800",children:"Invalid Provider"}),c.jsx("p",{className:"text-sm text-gray-500",children:"Provider data is missing"})]}),c.jsxs("div",{className:"ml-4 flex flex-shrink-0 items-center gap-2",children:[c.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>s(f),className:"transition-all-ease hover:scale-110",disabled:!0,children:c.jsx(uu,{className:"h-4 w-4"})}),c.jsx(ve,{variant:"destructive",size:"icon",onClick:()=>o(f),className:"transition-all duration-200 hover:scale-110",children:c.jsx(kn,{className:"h-4 w-4 text-current transition-colors duration-200"})})]})]},f);const p=d.name||"Unnamed Provider",m=d.api_base_url||"No API URL",x=Array.isArray(d.models)?d.models:[],y=EM(p,a),w=r?.find(j=>j.provider===p),S=w&&(w.limit5h||w.limit7d);return c.jsxs("div",{className:"flex items-start justify-between rounded-md border bg-white p-4 transition-all hover:shadow-md animate-slide-in hover:scale-[1.01]",children:[c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("p",{className:"text-md font-semibold text-gray-800",children:p})}),c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("p",{className:"text-sm text-gray-500",children:m})}),y.lastError&&c.jsxs("p",{className:"text-xs text-red-500 truncate max-w-md",title:y.lastError,children:["Error: ",y.lastError]}),S&&c.jsxs("div",{className:"space-y-1 pt-1",children:[c.jsx(z0,{label:u("providers.quota_5h"),used:w.used5h,limit:w.limit5h,resetTime:w.reset5h,t:u}),c.jsx(z0,{label:u("providers.quota_7d"),used:w.used7d,limit:w.limit7d,resetTime:w.reset7d,t:u})]}),c.jsx("div",{className:"flex flex-wrap gap-2 pt-2",children:x.map((j,_)=>c.jsx(Ur,{variant:"outline",className:"font-normal transition-all-ease hover:scale-105",children:j||"Unnamed Model"},_))})]}),c.jsxs("div",{className:"ml-4 flex flex-shrink-0 items-center gap-2",children:[c.jsx(RM,{status:y.status}),c.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>s(f),className:"transition-all-ease hover:scale-110",children:c.jsx(uu,{className:"h-4 w-4"})}),c.jsx(ve,{variant:"destructive",size:"icon",onClick:()=>o(f),className:"transition-all duration-200 hover:scale-110",children:c.jsx(kn,{className:"h-4 w-4 text-current transition-colors duration-200"})})]})]},f)})})}var P0=1,OM=.9,AM=.8,MM=.17,Ph=.1,Uh=.999,kM=.9999,DM=.99,LM=/[\\\/_+.#"@\[\(\{&]/,zM=/[\\\/_+.#"@\[\(\{&]/g,PM=/[\s-]/,ew=/[\s-]/g;function im(t,a,r,s,o,u,d){if(u===a.length)return o===t.length?P0:DM;var f=`${o},${u}`;if(d[f]!==void 0)return d[f];for(var p=s.charAt(u),m=r.indexOf(p,o),x=0,y,w,S,j;m>=0;)y=im(t,a,r,s,m+1,u+1,d),y>x&&(m===o?y*=P0:LM.test(t.charAt(m-1))?(y*=AM,S=t.slice(o,m-1).match(zM),S&&o>0&&(y*=Math.pow(Uh,S.length))):PM.test(t.charAt(m-1))?(y*=OM,j=t.slice(o,m-1).match(ew),j&&o>0&&(y*=Math.pow(Uh,j.length))):(y*=MM,o>0&&(y*=Math.pow(Uh,m-o))),t.charAt(m)!==a.charAt(u)&&(y*=kM)),(y<Ph&&r.charAt(m-1)===s.charAt(u+1)||s.charAt(u+1)===s.charAt(u)&&r.charAt(m-1)!==s.charAt(u))&&(w=im(t,a,r,s,m+1,u+2,d),w*Ph>y&&(y=w*Ph)),y>x&&(x=y),m=r.indexOf(p,m+1);return d[f]=x,x}function U0(t){return t.toLowerCase().replace(ew," ")}function UM(t,a,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,im(t,a,U0(t),U0(a),0,0,{})}var Fo='[cmdk-group=""]',Hh='[cmdk-group-items=""]',HM='[cmdk-group-heading=""]',tw='[cmdk-item=""]',H0=`${tw}:not([aria-disabled="true"])`,cm="cmdk-item-select",bs="data-value",BM=(t,a,r)=>UM(t,a,r),nw=v.createContext(void 0),hi=()=>v.useContext(nw),aw=v.createContext(void 0),Jm=()=>v.useContext(aw),rw=v.createContext(void 0),lw=v.forwardRef((t,a)=>{let r=ws(()=>{var U,X;return{search:"",value:(X=(U=t.value)!=null?U:t.defaultValue)!=null?X:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),s=ws(()=>new Set),o=ws(()=>new Map),u=ws(()=>new Map),d=ws(()=>new Set),f=sw(t),{label:p,children:m,value:x,onValueChange:y,filter:w,shouldFilter:S,loop:j,disablePointerSelection:_=!1,vimBindings:E=!0,...O}=t,R=on(),N=on(),A=on(),L=v.useRef(null),z=ZM();El(()=>{if(x!==void 0){let U=x.trim();r.current.value=U,C.emit()}},[x]),El(()=>{z(6,re)},[]);let C=v.useMemo(()=>({subscribe:U=>(d.current.add(U),()=>d.current.delete(U)),snapshot:()=>r.current,setState:(U,X,ne)=>{var oe,ye,se,Re;if(!Object.is(r.current[U],X)){if(r.current[U]=X,U==="search")te(),D(),z(1,G);else if(U==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let J=document.getElementById(A);J?J.focus():(oe=document.getElementById(R))==null||oe.focus()}if(z(7,()=>{var J;r.current.selectedItemId=(J=le())==null?void 0:J.id,C.emit()}),ne||z(5,re),((ye=f.current)==null?void 0:ye.value)!==void 0){let J=X??"";(Re=(se=f.current).onValueChange)==null||Re.call(se,J);return}}C.emit()}},emit:()=>{d.current.forEach(U=>U())}}),[]),B=v.useMemo(()=>({value:(U,X,ne)=>{var oe;X!==((oe=u.current.get(U))==null?void 0:oe.value)&&(u.current.set(U,{value:X,keywords:ne}),r.current.filtered.items.set(U,q(X,ne)),z(2,()=>{D(),C.emit()}))},item:(U,X)=>(s.current.add(U),X&&(o.current.has(X)?o.current.get(X).add(U):o.current.set(X,new Set([U]))),z(3,()=>{te(),D(),r.current.value||G(),C.emit()}),()=>{u.current.delete(U),s.current.delete(U),r.current.filtered.items.delete(U);let ne=le();z(4,()=>{te(),ne?.getAttribute("id")===U&&G(),C.emit()})}),group:U=>(o.current.has(U)||o.current.set(U,new Set),()=>{u.current.delete(U),o.current.delete(U)}),filter:()=>f.current.shouldFilter,label:p||t["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:R,inputId:A,labelId:N,listInnerRef:L}),[]);function q(U,X){var ne,oe;let ye=(oe=(ne=f.current)==null?void 0:ne.filter)!=null?oe:BM;return U?ye(U,r.current.search,X):0}function D(){if(!r.current.search||f.current.shouldFilter===!1)return;let U=r.current.filtered.items,X=[];r.current.filtered.groups.forEach(oe=>{let ye=o.current.get(oe),se=0;ye.forEach(Re=>{let J=U.get(Re);se=Math.max(J,se)}),X.push([oe,se])});let ne=L.current;V().sort((oe,ye)=>{var se,Re;let J=oe.getAttribute("id"),we=ye.getAttribute("id");return((se=U.get(we))!=null?se:0)-((Re=U.get(J))!=null?Re:0)}).forEach(oe=>{let ye=oe.closest(Hh);ye?ye.appendChild(oe.parentElement===ye?oe:oe.closest(`${Hh} > *`)):ne.appendChild(oe.parentElement===ne?oe:oe.closest(`${Hh} > *`))}),X.sort((oe,ye)=>ye[1]-oe[1]).forEach(oe=>{var ye;let se=(ye=L.current)==null?void 0:ye.querySelector(`${Fo}[${bs}="${encodeURIComponent(oe[0])}"]`);se?.parentElement.appendChild(se)})}function G(){let U=V().find(ne=>ne.getAttribute("aria-disabled")!=="true"),X=U?.getAttribute(bs);C.setState("value",X||void 0)}function te(){var U,X,ne,oe;if(!r.current.search||f.current.shouldFilter===!1){r.current.filtered.count=s.current.size;return}r.current.filtered.groups=new Set;let ye=0;for(let se of s.current){let Re=(X=(U=u.current.get(se))==null?void 0:U.value)!=null?X:"",J=(oe=(ne=u.current.get(se))==null?void 0:ne.keywords)!=null?oe:[],we=q(Re,J);r.current.filtered.items.set(se,we),we>0&&ye++}for(let[se,Re]of o.current)for(let J of Re)if(r.current.filtered.items.get(J)>0){r.current.filtered.groups.add(se);break}r.current.filtered.count=ye}function re(){var U,X,ne;let oe=le();oe&&(((U=oe.parentElement)==null?void 0:U.firstChild)===oe&&((ne=(X=oe.closest(Fo))==null?void 0:X.querySelector(HM))==null||ne.scrollIntoView({block:"nearest"})),oe.scrollIntoView({block:"nearest"}))}function le(){var U;return(U=L.current)==null?void 0:U.querySelector(`${tw}[aria-selected="true"]`)}function V(){var U;return Array.from(((U=L.current)==null?void 0:U.querySelectorAll(H0))||[])}function M(U){let X=V()[U];X&&C.setState("value",X.getAttribute(bs))}function P(U){var X;let ne=le(),oe=V(),ye=oe.findIndex(Re=>Re===ne),se=oe[ye+U];(X=f.current)!=null&&X.loop&&(se=ye+U<0?oe[oe.length-1]:ye+U===oe.length?oe[0]:oe[ye+U]),se&&C.setState("value",se.getAttribute(bs))}function H(U){let X=le(),ne=X?.closest(Fo),oe;for(;ne&&!oe;)ne=U>0?XM(ne,Fo):QM(ne,Fo),oe=ne?.querySelector(H0);oe?C.setState("value",oe.getAttribute(bs)):P(U)}let fe=()=>M(V().length-1),pe=U=>{U.preventDefault(),U.metaKey?fe():U.altKey?H(1):P(1)},k=U=>{U.preventDefault(),U.metaKey?M(0):U.altKey?H(-1):P(-1)};return v.createElement(lr.div,{ref:a,tabIndex:-1,...O,"cmdk-root":"",onKeyDown:U=>{var X;(X=O.onKeyDown)==null||X.call(O,U);let ne=U.nativeEvent.isComposing||U.keyCode===229;if(!(U.defaultPrevented||ne))switch(U.key){case"n":case"j":{E&&U.ctrlKey&&pe(U);break}case"ArrowDown":{pe(U);break}case"p":case"k":{E&&U.ctrlKey&&k(U);break}case"ArrowUp":{k(U);break}case"Home":{U.preventDefault(),M(0);break}case"End":{U.preventDefault(),fe();break}case"Enter":{U.preventDefault();let oe=le();if(oe){let ye=new Event(cm);oe.dispatchEvent(ye)}}}}},v.createElement("label",{"cmdk-label":"",htmlFor:B.inputId,id:B.labelId,style:WM},p),zu(t,U=>v.createElement(aw.Provider,{value:C},v.createElement(nw.Provider,{value:B},U))))}),FM=v.forwardRef((t,a)=>{var r,s;let o=on(),u=v.useRef(null),d=v.useContext(rw),f=hi(),p=sw(t),m=(s=(r=p.current)==null?void 0:r.forceMount)!=null?s:d?.forceMount;El(()=>{if(!m)return f.item(o,d?.id)},[m]);let x=ow(o,u,[t.value,t.children,u],t.keywords),y=Jm(),w=Vr(z=>z.value&&z.value===x.current),S=Vr(z=>m||f.filter()===!1?!0:z.search?z.filtered.items.get(o)>0:!0);v.useEffect(()=>{let z=u.current;if(!(!z||t.disabled))return z.addEventListener(cm,j),()=>z.removeEventListener(cm,j)},[S,t.onSelect,t.disabled]);function j(){var z,C;_(),(C=(z=p.current).onSelect)==null||C.call(z,x.current)}function _(){y.setState("value",x.current,!0)}if(!S)return null;let{disabled:E,value:O,onSelect:R,forceMount:N,keywords:A,...L}=t;return v.createElement(lr.div,{ref:$r(u,a),...L,id:o,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:_,onClick:E?void 0:j},t.children)}),$M=v.forwardRef((t,a)=>{let{heading:r,children:s,forceMount:o,...u}=t,d=on(),f=v.useRef(null),p=v.useRef(null),m=on(),x=hi(),y=Vr(S=>o||x.filter()===!1?!0:S.search?S.filtered.groups.has(d):!0);El(()=>x.group(d),[]),ow(d,f,[t.value,t.heading,p]);let w=v.useMemo(()=>({id:d,forceMount:o}),[o]);return v.createElement(lr.div,{ref:$r(f,a),...u,"cmdk-group":"",role:"presentation",hidden:y?void 0:!0},r&&v.createElement("div",{ref:p,"cmdk-group-heading":"","aria-hidden":!0,id:m},r),zu(t,S=>v.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?m:void 0},v.createElement(rw.Provider,{value:w},S))))}),IM=v.forwardRef((t,a)=>{let{alwaysRender:r,...s}=t,o=v.useRef(null),u=Vr(d=>!d.search);return!r&&!u?null:v.createElement(lr.div,{ref:$r(o,a),...s,"cmdk-separator":"",role:"separator"})}),qM=v.forwardRef((t,a)=>{let{onValueChange:r,...s}=t,o=t.value!=null,u=Jm(),d=Vr(m=>m.search),f=Vr(m=>m.selectedItemId),p=hi();return v.useEffect(()=>{t.value!=null&&u.setState("search",t.value)},[t.value]),v.createElement(lr.input,{ref:a,...s,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":p.listId,"aria-labelledby":p.labelId,"aria-activedescendant":f,id:p.inputId,type:"text",value:o?t.value:d,onChange:m=>{o||u.setState("search",m.target.value),r?.(m.target.value)}})}),VM=v.forwardRef((t,a)=>{let{children:r,label:s="Suggestions",...o}=t,u=v.useRef(null),d=v.useRef(null),f=Vr(m=>m.selectedItemId),p=hi();return v.useEffect(()=>{if(d.current&&u.current){let m=d.current,x=u.current,y,w=new ResizeObserver(()=>{y=requestAnimationFrame(()=>{let S=m.offsetHeight;x.style.setProperty("--cmdk-list-height",S.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(y),w.unobserve(m)}}},[]),v.createElement(lr.div,{ref:$r(u,a),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":s,id:p.listId},zu(t,m=>v.createElement("div",{ref:$r(d,p.listInnerRef),"cmdk-list-sizer":""},m)))}),GM=v.forwardRef((t,a)=>{let{open:r,onOpenChange:s,overlayClassName:o,contentClassName:u,container:d,...f}=t;return v.createElement(X1,{open:r,onOpenChange:s},v.createElement(Q1,{container:d},v.createElement(Qm,{"cmdk-overlay":"",className:o}),v.createElement(Zm,{"aria-label":t.label,"cmdk-dialog":"",className:u},v.createElement(lw,{ref:a,...f}))))}),KM=v.forwardRef((t,a)=>Vr(r=>r.filtered.count===0)?v.createElement(lr.div,{ref:a,...t,"cmdk-empty":"",role:"presentation"}):null),YM=v.forwardRef((t,a)=>{let{progress:r,children:s,label:o="Loading...",...u}=t;return v.createElement(lr.div,{ref:a,...u,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},zu(t,d=>v.createElement("div",{"aria-hidden":!0},d)))}),Us=Object.assign(lw,{List:VM,Item:FM,Input:qM,Group:$M,Separator:IM,Dialog:GM,Empty:KM,Loading:YM});function XM(t,a){let r=t.nextElementSibling;for(;r;){if(r.matches(a))return r;r=r.nextElementSibling}}function QM(t,a){let r=t.previousElementSibling;for(;r;){if(r.matches(a))return r;r=r.previousElementSibling}}function sw(t){let a=v.useRef(t);return El(()=>{a.current=t}),a}var El=typeof window>"u"?v.useEffect:v.useLayoutEffect;function ws(t){let a=v.useRef();return a.current===void 0&&(a.current=t()),a}function Vr(t){let a=Jm(),r=()=>t(a.snapshot());return v.useSyncExternalStore(a.subscribe,r,r)}function ow(t,a,r,s=[]){let o=v.useRef(),u=hi();return El(()=>{var d;let f=(()=>{var m;for(let x of r){if(typeof x=="string")return x.trim();if(typeof x=="object"&&"current"in x)return x.current?(m=x.current.textContent)==null?void 0:m.trim():o.current}})(),p=s.map(m=>m.trim());u.value(t,f,p),(d=a.current)==null||d.setAttribute(bs,f),o.current=f}),o}var ZM=()=>{let[t,a]=v.useState(),r=ws(()=>new Map);return El(()=>{r.current.forEach(s=>s()),r.current=new Map},[t]),(s,o)=>{r.current.set(s,o),a({})}};function JM(t){let a=t.type;return typeof a=="function"?a(t.props):"render"in a?a.render(t.props):t}function zu({asChild:t,children:a},r){return t&&v.isValidElement(a)?v.cloneElement(JM(a),{ref:a.ref},r(a.props.children)):r(a)}var WM={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Wm({className:t,...a}){return c.jsx(Us,{"data-slot":"command",className:Xe("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...a})}function ep({className:t,...a}){return c.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[c.jsx(qm,{className:"size-4 shrink-0 opacity-50"}),c.jsx(Us.Input,{"data-slot":"command-input",className:Xe("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...a})]})}function tp({className:t,...a}){return c.jsx(Us.List,{"data-slot":"command-list",className:Xe("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...a})}function np({...t}){return c.jsx(Us.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function ap({className:t,...a}){return c.jsx(Us.Group,{"data-slot":"command-group",className:Xe("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...a})}function rp({className:t,...a}){return c.jsx(Us.Item,{"data-slot":"command-item",className:Xe("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...a})}const ek=["top","right","bottom","left"],Gr=Math.min,An=Math.max,hu=Math.round,Vc=Math.floor,Sa=t=>({x:t,y:t}),tk={left:"right",right:"left",bottom:"top",top:"bottom"},nk={start:"end",end:"start"};function um(t,a,r){return An(t,Gr(a,r))}function tr(t,a){return typeof t=="function"?t(a):t}function nr(t){return t.split("-")[0]}function Hs(t){return t.split("-")[1]}function lp(t){return t==="x"?"y":"x"}function sp(t){return t==="y"?"height":"width"}const ak=new Set(["top","bottom"]);function ba(t){return ak.has(nr(t))?"y":"x"}function op(t){return lp(ba(t))}function rk(t,a,r){r===void 0&&(r=!1);const s=Hs(t),o=op(t),u=sp(o);let d=o==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return a.reference[u]>a.floating[u]&&(d=mu(d)),[d,mu(d)]}function lk(t){const a=mu(t);return[dm(t),a,dm(a)]}function dm(t){return t.replace(/start|end/g,a=>nk[a])}const B0=["left","right"],F0=["right","left"],sk=["top","bottom"],ok=["bottom","top"];function ik(t,a,r){switch(t){case"top":case"bottom":return r?a?F0:B0:a?B0:F0;case"left":case"right":return a?sk:ok;default:return[]}}function ck(t,a,r,s){const o=Hs(t);let u=ik(nr(t),r==="start",s);return o&&(u=u.map(d=>d+"-"+o),a&&(u=u.concat(u.map(dm)))),u}function mu(t){return t.replace(/left|right|bottom|top/g,a=>tk[a])}function uk(t){return{top:0,right:0,bottom:0,left:0,...t}}function iw(t){return typeof t!="number"?uk(t):{top:t,right:t,bottom:t,left:t}}function pu(t){const{x:a,y:r,width:s,height:o}=t;return{width:s,height:o,top:r,left:a,right:a+s,bottom:r+o,x:a,y:r}}function $0(t,a,r){let{reference:s,floating:o}=t;const u=ba(a),d=op(a),f=sp(d),p=nr(a),m=u==="y",x=s.x+s.width/2-o.width/2,y=s.y+s.height/2-o.height/2,w=s[f]/2-o[f]/2;let S;switch(p){case"top":S={x,y:s.y-o.height};break;case"bottom":S={x,y:s.y+s.height};break;case"right":S={x:s.x+s.width,y};break;case"left":S={x:s.x-o.width,y};break;default:S={x:s.x,y:s.y}}switch(Hs(a)){case"start":S[d]-=w*(r&&m?-1:1);break;case"end":S[d]+=w*(r&&m?-1:1);break}return S}const dk=async(t,a,r)=>{const{placement:s="bottom",strategy:o="absolute",middleware:u=[],platform:d}=r,f=u.filter(Boolean),p=await(d.isRTL==null?void 0:d.isRTL(a));let m=await d.getElementRects({reference:t,floating:a,strategy:o}),{x,y}=$0(m,s,p),w=s,S={},j=0;for(let _=0;_<f.length;_++){const{name:E,fn:O}=f[_],{x:R,y:N,data:A,reset:L}=await O({x,y,initialPlacement:s,placement:w,strategy:o,middlewareData:S,rects:m,platform:d,elements:{reference:t,floating:a}});x=R??x,y=N??y,S={...S,[E]:{...S[E],...A}},L&&j<=50&&(j++,typeof L=="object"&&(L.placement&&(w=L.placement),L.rects&&(m=L.rects===!0?await d.getElementRects({reference:t,floating:a,strategy:o}):L.rects),{x,y}=$0(m,w,p)),_=-1)}return{x,y,placement:w,strategy:o,middlewareData:S}};async function ri(t,a){var r;a===void 0&&(a={});const{x:s,y:o,platform:u,rects:d,elements:f,strategy:p}=t,{boundary:m="clippingAncestors",rootBoundary:x="viewport",elementContext:y="floating",altBoundary:w=!1,padding:S=0}=tr(a,t),j=iw(S),E=f[w?y==="floating"?"reference":"floating":y],O=pu(await u.getClippingRect({element:(r=await(u.isElement==null?void 0:u.isElement(E)))==null||r?E:E.contextElement||await(u.getDocumentElement==null?void 0:u.getDocumentElement(f.floating)),boundary:m,rootBoundary:x,strategy:p})),R=y==="floating"?{x:s,y:o,width:d.floating.width,height:d.floating.height}:d.reference,N=await(u.getOffsetParent==null?void 0:u.getOffsetParent(f.floating)),A=await(u.isElement==null?void 0:u.isElement(N))?await(u.getScale==null?void 0:u.getScale(N))||{x:1,y:1}:{x:1,y:1},L=pu(u.convertOffsetParentRelativeRectToViewportRelativeRect?await u.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:R,offsetParent:N,strategy:p}):R);return{top:(O.top-L.top+j.top)/A.y,bottom:(L.bottom-O.bottom+j.bottom)/A.y,left:(O.left-L.left+j.left)/A.x,right:(L.right-O.right+j.right)/A.x}}const fk=t=>({name:"arrow",options:t,async fn(a){const{x:r,y:s,placement:o,rects:u,platform:d,elements:f,middlewareData:p}=a,{element:m,padding:x=0}=tr(t,a)||{};if(m==null)return{};const y=iw(x),w={x:r,y:s},S=op(o),j=sp(S),_=await d.getDimensions(m),E=S==="y",O=E?"top":"left",R=E?"bottom":"right",N=E?"clientHeight":"clientWidth",A=u.reference[j]+u.reference[S]-w[S]-u.floating[j],L=w[S]-u.reference[S],z=await(d.getOffsetParent==null?void 0:d.getOffsetParent(m));let C=z?z[N]:0;(!C||!await(d.isElement==null?void 0:d.isElement(z)))&&(C=f.floating[N]||u.floating[j]);const B=A/2-L/2,q=C/2-_[j]/2-1,D=Gr(y[O],q),G=Gr(y[R],q),te=D,re=C-_[j]-G,le=C/2-_[j]/2+B,V=um(te,le,re),M=!p.arrow&&Hs(o)!=null&&le!==V&&u.reference[j]/2-(le<te?D:G)-_[j]/2<0,P=M?le<te?le-te:le-re:0;return{[S]:w[S]+P,data:{[S]:V,centerOffset:le-V-P,...M&&{alignmentOffset:P}},reset:M}}}),hk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(a){var r,s;const{placement:o,middlewareData:u,rects:d,initialPlacement:f,platform:p,elements:m}=a,{mainAxis:x=!0,crossAxis:y=!0,fallbackPlacements:w,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:j="none",flipAlignment:_=!0,...E}=tr(t,a);if((r=u.arrow)!=null&&r.alignmentOffset)return{};const O=nr(o),R=ba(f),N=nr(f)===f,A=await(p.isRTL==null?void 0:p.isRTL(m.floating)),L=w||(N||!_?[mu(f)]:lk(f)),z=j!=="none";!w&&z&&L.push(...ck(f,_,j,A));const C=[f,...L],B=await ri(a,E),q=[];let D=((s=u.flip)==null?void 0:s.overflows)||[];if(x&&q.push(B[O]),y){const le=rk(o,d,A);q.push(B[le[0]],B[le[1]])}if(D=[...D,{placement:o,overflows:q}],!q.every(le=>le<=0)){var G,te;const le=(((G=u.flip)==null?void 0:G.index)||0)+1,V=C[le];if(V&&(!(y==="alignment"?R!==ba(V):!1)||D.every(H=>ba(H.placement)===R?H.overflows[0]>0:!0)))return{data:{index:le,overflows:D},reset:{placement:V}};let M=(te=D.filter(P=>P.overflows[0]<=0).sort((P,H)=>P.overflows[1]-H.overflows[1])[0])==null?void 0:te.placement;if(!M)switch(S){case"bestFit":{var re;const P=(re=D.filter(H=>{if(z){const fe=ba(H.placement);return fe===R||fe==="y"}return!0}).map(H=>[H.placement,H.overflows.filter(fe=>fe>0).reduce((fe,pe)=>fe+pe,0)]).sort((H,fe)=>H[1]-fe[1])[0])==null?void 0:re[0];P&&(M=P);break}case"initialPlacement":M=f;break}if(o!==M)return{reset:{placement:M}}}return{}}}};function I0(t,a){return{top:t.top-a.height,right:t.right-a.width,bottom:t.bottom-a.height,left:t.left-a.width}}function q0(t){return ek.some(a=>t[a]>=0)}const mk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(a){const{rects:r}=a,{strategy:s="referenceHidden",...o}=tr(t,a);switch(s){case"referenceHidden":{const u=await ri(a,{...o,elementContext:"reference"}),d=I0(u,r.reference);return{data:{referenceHiddenOffsets:d,referenceHidden:q0(d)}}}case"escaped":{const u=await ri(a,{...o,altBoundary:!0}),d=I0(u,r.floating);return{data:{escapedOffsets:d,escaped:q0(d)}}}default:return{}}}}},cw=new Set(["left","top"]);async function pk(t,a){const{placement:r,platform:s,elements:o}=t,u=await(s.isRTL==null?void 0:s.isRTL(o.floating)),d=nr(r),f=Hs(r),p=ba(r)==="y",m=cw.has(d)?-1:1,x=u&&p?-1:1,y=tr(a,t);let{mainAxis:w,crossAxis:S,alignmentAxis:j}=typeof y=="number"?{mainAxis:y,crossAxis:0,alignmentAxis:null}:{mainAxis:y.mainAxis||0,crossAxis:y.crossAxis||0,alignmentAxis:y.alignmentAxis};return f&&typeof j=="number"&&(S=f==="end"?j*-1:j),p?{x:S*x,y:w*m}:{x:w*m,y:S*x}}const gk=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(a){var r,s;const{x:o,y:u,placement:d,middlewareData:f}=a,p=await pk(a,t);return d===((r=f.offset)==null?void 0:r.placement)&&(s=f.arrow)!=null&&s.alignmentOffset?{}:{x:o+p.x,y:u+p.y,data:{...p,placement:d}}}}},vk=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(a){const{x:r,y:s,placement:o}=a,{mainAxis:u=!0,crossAxis:d=!1,limiter:f={fn:E=>{let{x:O,y:R}=E;return{x:O,y:R}}},...p}=tr(t,a),m={x:r,y:s},x=await ri(a,p),y=ba(nr(o)),w=lp(y);let S=m[w],j=m[y];if(u){const E=w==="y"?"top":"left",O=w==="y"?"bottom":"right",R=S+x[E],N=S-x[O];S=um(R,S,N)}if(d){const E=y==="y"?"top":"left",O=y==="y"?"bottom":"right",R=j+x[E],N=j-x[O];j=um(R,j,N)}const _=f.fn({...a,[w]:S,[y]:j});return{..._,data:{x:_.x-r,y:_.y-s,enabled:{[w]:u,[y]:d}}}}}},yk=function(t){return t===void 0&&(t={}),{options:t,fn(a){const{x:r,y:s,placement:o,rects:u,middlewareData:d}=a,{offset:f=0,mainAxis:p=!0,crossAxis:m=!0}=tr(t,a),x={x:r,y:s},y=ba(o),w=lp(y);let S=x[w],j=x[y];const _=tr(f,a),E=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(p){const N=w==="y"?"height":"width",A=u.reference[w]-u.floating[N]+E.mainAxis,L=u.reference[w]+u.reference[N]-E.mainAxis;S<A?S=A:S>L&&(S=L)}if(m){var O,R;const N=w==="y"?"width":"height",A=cw.has(nr(o)),L=u.reference[y]-u.floating[N]+(A&&((O=d.offset)==null?void 0:O[y])||0)+(A?0:E.crossAxis),z=u.reference[y]+u.reference[N]+(A?0:((R=d.offset)==null?void 0:R[y])||0)-(A?E.crossAxis:0);j<L?j=L:j>z&&(j=z)}return{[w]:S,[y]:j}}}},xk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(a){var r,s;const{placement:o,rects:u,platform:d,elements:f}=a,{apply:p=()=>{},...m}=tr(t,a),x=await ri(a,m),y=nr(o),w=Hs(o),S=ba(o)==="y",{width:j,height:_}=u.floating;let E,O;y==="top"||y==="bottom"?(E=y,O=w===(await(d.isRTL==null?void 0:d.isRTL(f.floating))?"start":"end")?"left":"right"):(O=y,E=w==="end"?"top":"bottom");const R=_-x.top-x.bottom,N=j-x.left-x.right,A=Gr(_-x[E],R),L=Gr(j-x[O],N),z=!a.middlewareData.shift;let C=A,B=L;if((r=a.middlewareData.shift)!=null&&r.enabled.x&&(B=N),(s=a.middlewareData.shift)!=null&&s.enabled.y&&(C=R),z&&!w){const D=An(x.left,0),G=An(x.right,0),te=An(x.top,0),re=An(x.bottom,0);S?B=j-2*(D!==0||G!==0?D+G:An(x.left,x.right)):C=_-2*(te!==0||re!==0?te+re:An(x.top,x.bottom))}await p({...a,availableWidth:B,availableHeight:C});const q=await d.getDimensions(f.floating);return j!==q.width||_!==q.height?{reset:{rects:!0}}:{}}}};function Pu(){return typeof window<"u"}function Bs(t){return uw(t)?(t.nodeName||"").toLowerCase():"#document"}function Mn(t){var a;return(t==null||(a=t.ownerDocument)==null?void 0:a.defaultView)||window}function Ra(t){var a;return(a=(uw(t)?t.ownerDocument:t.document)||window.document)==null?void 0:a.documentElement}function uw(t){return Pu()?t instanceof Node||t instanceof Mn(t).Node:!1}function ua(t){return Pu()?t instanceof Element||t instanceof Mn(t).Element:!1}function ja(t){return Pu()?t instanceof HTMLElement||t instanceof Mn(t).HTMLElement:!1}function V0(t){return!Pu()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Mn(t).ShadowRoot}const bk=new Set(["inline","contents"]);function mi(t){const{overflow:a,overflowX:r,overflowY:s,display:o}=da(t);return/auto|scroll|overlay|hidden|clip/.test(a+s+r)&&!bk.has(o)}const wk=new Set(["table","td","th"]);function Sk(t){return wk.has(Bs(t))}const _k=[":popover-open",":modal"];function Uu(t){return _k.some(a=>{try{return t.matches(a)}catch{return!1}})}const jk=["transform","translate","scale","rotate","perspective"],Nk=["transform","translate","scale","rotate","perspective","filter"],Ck=["paint","layout","strict","content"];function ip(t){const a=cp(),r=ua(t)?da(t):t;return jk.some(s=>r[s]?r[s]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!a&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!a&&(r.filter?r.filter!=="none":!1)||Nk.some(s=>(r.willChange||"").includes(s))||Ck.some(s=>(r.contain||"").includes(s))}function Ek(t){let a=Kr(t);for(;ja(a)&&!Rs(a);){if(ip(a))return a;if(Uu(a))return null;a=Kr(a)}return null}function cp(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Rk=new Set(["html","body","#document"]);function Rs(t){return Rk.has(Bs(t))}function da(t){return Mn(t).getComputedStyle(t)}function Hu(t){return ua(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Kr(t){if(Bs(t)==="html")return t;const a=t.assignedSlot||t.parentNode||V0(t)&&t.host||Ra(t);return V0(a)?a.host:a}function dw(t){const a=Kr(t);return Rs(a)?t.ownerDocument?t.ownerDocument.body:t.body:ja(a)&&mi(a)?a:dw(a)}function li(t,a,r){var s;a===void 0&&(a=[]),r===void 0&&(r=!0);const o=dw(t),u=o===((s=t.ownerDocument)==null?void 0:s.body),d=Mn(o);if(u){const f=fm(d);return a.concat(d,d.visualViewport||[],mi(o)?o:[],f&&r?li(f):[])}return a.concat(o,li(o,[],r))}function fm(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function fw(t){const a=da(t);let r=parseFloat(a.width)||0,s=parseFloat(a.height)||0;const o=ja(t),u=o?t.offsetWidth:r,d=o?t.offsetHeight:s,f=hu(r)!==u||hu(s)!==d;return f&&(r=u,s=d),{width:r,height:s,$:f}}function up(t){return ua(t)?t:t.contextElement}function Cs(t){const a=up(t);if(!ja(a))return Sa(1);const r=a.getBoundingClientRect(),{width:s,height:o,$:u}=fw(a);let d=(u?hu(r.width):r.width)/s,f=(u?hu(r.height):r.height)/o;return(!d||!Number.isFinite(d))&&(d=1),(!f||!Number.isFinite(f))&&(f=1),{x:d,y:f}}const Tk=Sa(0);function hw(t){const a=Mn(t);return!cp()||!a.visualViewport?Tk:{x:a.visualViewport.offsetLeft,y:a.visualViewport.offsetTop}}function Ok(t,a,r){return a===void 0&&(a=!1),!r||a&&r!==Mn(t)?!1:a}function Rl(t,a,r,s){a===void 0&&(a=!1),r===void 0&&(r=!1);const o=t.getBoundingClientRect(),u=up(t);let d=Sa(1);a&&(s?ua(s)&&(d=Cs(s)):d=Cs(t));const f=Ok(u,r,s)?hw(u):Sa(0);let p=(o.left+f.x)/d.x,m=(o.top+f.y)/d.y,x=o.width/d.x,y=o.height/d.y;if(u){const w=Mn(u),S=s&&ua(s)?Mn(s):s;let j=w,_=fm(j);for(;_&&s&&S!==j;){const E=Cs(_),O=_.getBoundingClientRect(),R=da(_),N=O.left+(_.clientLeft+parseFloat(R.paddingLeft))*E.x,A=O.top+(_.clientTop+parseFloat(R.paddingTop))*E.y;p*=E.x,m*=E.y,x*=E.x,y*=E.y,p+=N,m+=A,j=Mn(_),_=fm(j)}}return pu({width:x,height:y,x:p,y:m})}function Bu(t,a){const r=Hu(t).scrollLeft;return a?a.left+r:Rl(Ra(t)).left+r}function mw(t,a){const r=t.getBoundingClientRect(),s=r.left+a.scrollLeft-Bu(t,r),o=r.top+a.scrollTop;return{x:s,y:o}}function Ak(t){let{elements:a,rect:r,offsetParent:s,strategy:o}=t;const u=o==="fixed",d=Ra(s),f=a?Uu(a.floating):!1;if(s===d||f&&u)return r;let p={scrollLeft:0,scrollTop:0},m=Sa(1);const x=Sa(0),y=ja(s);if((y||!y&&!u)&&((Bs(s)!=="body"||mi(d))&&(p=Hu(s)),ja(s))){const S=Rl(s);m=Cs(s),x.x=S.x+s.clientLeft,x.y=S.y+s.clientTop}const w=d&&!y&&!u?mw(d,p):Sa(0);return{width:r.width*m.x,height:r.height*m.y,x:r.x*m.x-p.scrollLeft*m.x+x.x+w.x,y:r.y*m.y-p.scrollTop*m.y+x.y+w.y}}function Mk(t){return Array.from(t.getClientRects())}function kk(t){const a=Ra(t),r=Hu(t),s=t.ownerDocument.body,o=An(a.scrollWidth,a.clientWidth,s.scrollWidth,s.clientWidth),u=An(a.scrollHeight,a.clientHeight,s.scrollHeight,s.clientHeight);let d=-r.scrollLeft+Bu(t);const f=-r.scrollTop;return da(s).direction==="rtl"&&(d+=An(a.clientWidth,s.clientWidth)-o),{width:o,height:u,x:d,y:f}}const G0=25;function Dk(t,a){const r=Mn(t),s=Ra(t),o=r.visualViewport;let u=s.clientWidth,d=s.clientHeight,f=0,p=0;if(o){u=o.width,d=o.height;const x=cp();(!x||x&&a==="fixed")&&(f=o.offsetLeft,p=o.offsetTop)}const m=Bu(s);if(m<=0){const x=s.ownerDocument,y=x.body,w=getComputedStyle(y),S=x.compatMode==="CSS1Compat"&&parseFloat(w.marginLeft)+parseFloat(w.marginRight)||0,j=Math.abs(s.clientWidth-y.clientWidth-S);j<=G0&&(u-=j)}else m<=G0&&(u+=m);return{width:u,height:d,x:f,y:p}}const Lk=new Set(["absolute","fixed"]);function zk(t,a){const r=Rl(t,!0,a==="fixed"),s=r.top+t.clientTop,o=r.left+t.clientLeft,u=ja(t)?Cs(t):Sa(1),d=t.clientWidth*u.x,f=t.clientHeight*u.y,p=o*u.x,m=s*u.y;return{width:d,height:f,x:p,y:m}}function K0(t,a,r){let s;if(a==="viewport")s=Dk(t,r);else if(a==="document")s=kk(Ra(t));else if(ua(a))s=zk(a,r);else{const o=hw(t);s={x:a.x-o.x,y:a.y-o.y,width:a.width,height:a.height}}return pu(s)}function pw(t,a){const r=Kr(t);return r===a||!ua(r)||Rs(r)?!1:da(r).position==="fixed"||pw(r,a)}function Pk(t,a){const r=a.get(t);if(r)return r;let s=li(t,[],!1).filter(f=>ua(f)&&Bs(f)!=="body"),o=null;const u=da(t).position==="fixed";let d=u?Kr(t):t;for(;ua(d)&&!Rs(d);){const f=da(d),p=ip(d);!p&&f.position==="fixed"&&(o=null),(u?!p&&!o:!p&&f.position==="static"&&!!o&&Lk.has(o.position)||mi(d)&&!p&&pw(t,d))?s=s.filter(x=>x!==d):o=f,d=Kr(d)}return a.set(t,s),s}function Uk(t){let{element:a,boundary:r,rootBoundary:s,strategy:o}=t;const d=[...r==="clippingAncestors"?Uu(a)?[]:Pk(a,this._c):[].concat(r),s],f=d[0],p=d.reduce((m,x)=>{const y=K0(a,x,o);return m.top=An(y.top,m.top),m.right=Gr(y.right,m.right),m.bottom=Gr(y.bottom,m.bottom),m.left=An(y.left,m.left),m},K0(a,f,o));return{width:p.right-p.left,height:p.bottom-p.top,x:p.left,y:p.top}}function Hk(t){const{width:a,height:r}=fw(t);return{width:a,height:r}}function Bk(t,a,r){const s=ja(a),o=Ra(a),u=r==="fixed",d=Rl(t,!0,u,a);let f={scrollLeft:0,scrollTop:0};const p=Sa(0);function m(){p.x=Bu(o)}if(s||!s&&!u)if((Bs(a)!=="body"||mi(o))&&(f=Hu(a)),s){const S=Rl(a,!0,u,a);p.x=S.x+a.clientLeft,p.y=S.y+a.clientTop}else o&&m();u&&!s&&o&&m();const x=o&&!s&&!u?mw(o,f):Sa(0),y=d.left+f.scrollLeft-p.x-x.x,w=d.top+f.scrollTop-p.y-x.y;return{x:y,y:w,width:d.width,height:d.height}}function Bh(t){return da(t).position==="static"}function Y0(t,a){if(!ja(t)||da(t).position==="fixed")return null;if(a)return a(t);let r=t.offsetParent;return Ra(t)===r&&(r=r.ownerDocument.body),r}function gw(t,a){const r=Mn(t);if(Uu(t))return r;if(!ja(t)){let o=Kr(t);for(;o&&!Rs(o);){if(ua(o)&&!Bh(o))return o;o=Kr(o)}return r}let s=Y0(t,a);for(;s&&Sk(s)&&Bh(s);)s=Y0(s,a);return s&&Rs(s)&&Bh(s)&&!ip(s)?r:s||Ek(t)||r}const Fk=async function(t){const a=this.getOffsetParent||gw,r=this.getDimensions,s=await r(t.floating);return{reference:Bk(t.reference,await a(t.floating),t.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function $k(t){return da(t).direction==="rtl"}const Ik={convertOffsetParentRelativeRectToViewportRelativeRect:Ak,getDocumentElement:Ra,getClippingRect:Uk,getOffsetParent:gw,getElementRects:Fk,getClientRects:Mk,getDimensions:Hk,getScale:Cs,isElement:ua,isRTL:$k};function vw(t,a){return t.x===a.x&&t.y===a.y&&t.width===a.width&&t.height===a.height}function qk(t,a){let r=null,s;const o=Ra(t);function u(){var f;clearTimeout(s),(f=r)==null||f.disconnect(),r=null}function d(f,p){f===void 0&&(f=!1),p===void 0&&(p=1),u();const m=t.getBoundingClientRect(),{left:x,top:y,width:w,height:S}=m;if(f||a(),!w||!S)return;const j=Vc(y),_=Vc(o.clientWidth-(x+w)),E=Vc(o.clientHeight-(y+S)),O=Vc(x),N={rootMargin:-j+"px "+-_+"px "+-E+"px "+-O+"px",threshold:An(0,Gr(1,p))||1};let A=!0;function L(z){const C=z[0].intersectionRatio;if(C!==p){if(!A)return d();C?d(!1,C):s=setTimeout(()=>{d(!1,1e-7)},1e3)}C===1&&!vw(m,t.getBoundingClientRect())&&d(),A=!1}try{r=new IntersectionObserver(L,{...N,root:o.ownerDocument})}catch{r=new IntersectionObserver(L,N)}r.observe(t)}return d(!0),u}function Vk(t,a,r,s){s===void 0&&(s={});const{ancestorScroll:o=!0,ancestorResize:u=!0,elementResize:d=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:p=!1}=s,m=up(t),x=o||u?[...m?li(m):[],...li(a)]:[];x.forEach(O=>{o&&O.addEventListener("scroll",r,{passive:!0}),u&&O.addEventListener("resize",r)});const y=m&&f?qk(m,r):null;let w=-1,S=null;d&&(S=new ResizeObserver(O=>{let[R]=O;R&&R.target===m&&S&&(S.unobserve(a),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var N;(N=S)==null||N.observe(a)})),r()}),m&&!p&&S.observe(m),S.observe(a));let j,_=p?Rl(t):null;p&&E();function E(){const O=Rl(t);_&&!vw(_,O)&&r(),_=O,j=requestAnimationFrame(E)}return r(),()=>{var O;x.forEach(R=>{o&&R.removeEventListener("scroll",r),u&&R.removeEventListener("resize",r)}),y?.(),(O=S)==null||O.disconnect(),S=null,p&&cancelAnimationFrame(j)}}const Gk=gk,Kk=vk,Yk=hk,Xk=xk,Qk=mk,X0=fk,Zk=yk,Jk=(t,a,r)=>{const s=new Map,o={platform:Ik,...r},u={...o.platform,_c:s};return dk(t,a,{...o,platform:u})};var Wk=typeof document<"u",eD=function(){},eu=Wk?v.useLayoutEffect:eD;function gu(t,a){if(t===a)return!0;if(typeof t!=typeof a)return!1;if(typeof t=="function"&&t.toString()===a.toString())return!0;let r,s,o;if(t&&a&&typeof t=="object"){if(Array.isArray(t)){if(r=t.length,r!==a.length)return!1;for(s=r;s--!==0;)if(!gu(t[s],a[s]))return!1;return!0}if(o=Object.keys(t),r=o.length,r!==Object.keys(a).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(a,o[s]))return!1;for(s=r;s--!==0;){const u=o[s];if(!(u==="_owner"&&t.$$typeof)&&!gu(t[u],a[u]))return!1}return!0}return t!==t&&a!==a}function yw(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function Q0(t,a){const r=yw(t);return Math.round(a*r)/r}function Fh(t){const a=v.useRef(t);return eu(()=>{a.current=t}),a}function tD(t){t===void 0&&(t={});const{placement:a="bottom",strategy:r="absolute",middleware:s=[],platform:o,elements:{reference:u,floating:d}={},transform:f=!0,whileElementsMounted:p,open:m}=t,[x,y]=v.useState({x:0,y:0,strategy:r,placement:a,middlewareData:{},isPositioned:!1}),[w,S]=v.useState(s);gu(w,s)||S(s);const[j,_]=v.useState(null),[E,O]=v.useState(null),R=v.useCallback(H=>{H!==z.current&&(z.current=H,_(H))},[]),N=v.useCallback(H=>{H!==C.current&&(C.current=H,O(H))},[]),A=u||j,L=d||E,z=v.useRef(null),C=v.useRef(null),B=v.useRef(x),q=p!=null,D=Fh(p),G=Fh(o),te=Fh(m),re=v.useCallback(()=>{if(!z.current||!C.current)return;const H={placement:a,strategy:r,middleware:w};G.current&&(H.platform=G.current),Jk(z.current,C.current,H).then(fe=>{const pe={...fe,isPositioned:te.current!==!1};le.current&&!gu(B.current,pe)&&(B.current=pe,Ms.flushSync(()=>{y(pe)}))})},[w,a,r,G,te]);eu(()=>{m===!1&&B.current.isPositioned&&(B.current.isPositioned=!1,y(H=>({...H,isPositioned:!1})))},[m]);const le=v.useRef(!1);eu(()=>(le.current=!0,()=>{le.current=!1}),[]),eu(()=>{if(A&&(z.current=A),L&&(C.current=L),A&&L){if(D.current)return D.current(A,L,re);re()}},[A,L,re,D,q]);const V=v.useMemo(()=>({reference:z,floating:C,setReference:R,setFloating:N}),[R,N]),M=v.useMemo(()=>({reference:A,floating:L}),[A,L]),P=v.useMemo(()=>{const H={position:r,left:0,top:0};if(!M.floating)return H;const fe=Q0(M.floating,x.x),pe=Q0(M.floating,x.y);return f?{...H,transform:"translate("+fe+"px, "+pe+"px)",...yw(M.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:fe,top:pe}},[r,f,M.floating,x.x,x.y]);return v.useMemo(()=>({...x,update:re,refs:V,elements:M,floatingStyles:P}),[x,re,V,M,P])}const nD=t=>{function a(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:t,fn(r){const{element:s,padding:o}=typeof t=="function"?t(r):t;return s&&a(s)?s.current!=null?X0({element:s.current,padding:o}).fn(r):{}:s?X0({element:s,padding:o}).fn(r):{}}}},aD=(t,a)=>({...Gk(t),options:[t,a]}),rD=(t,a)=>({...Kk(t),options:[t,a]}),lD=(t,a)=>({...Zk(t),options:[t,a]}),sD=(t,a)=>({...Yk(t),options:[t,a]}),oD=(t,a)=>({...Xk(t),options:[t,a]}),iD=(t,a)=>({...Qk(t),options:[t,a]}),cD=(t,a)=>({...nD(t),options:[t,a]});var uD="Arrow",xw=v.forwardRef((t,a)=>{const{children:r,width:s=10,height:o=5,...u}=t;return c.jsx(We.svg,{...u,ref:a,width:s,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:c.jsx("polygon",{points:"0,0 30,0 15,10"})})});xw.displayName=uD;var dD=xw;function dp(t){const[a,r]=v.useState(void 0);return cn(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const s=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const u=o[0];let d,f;if("borderBoxSize"in u){const p=u.borderBoxSize,m=Array.isArray(p)?p[0]:p;d=m.inlineSize,f=m.blockSize}else d=t.offsetWidth,f=t.offsetHeight;r({width:d,height:f})});return s.observe(t,{box:"border-box"}),()=>s.unobserve(t)}else r(void 0)},[t]),a}var fp="Popper",[bw,Fs]=Ea(fp),[fD,ww]=bw(fp),Sw=t=>{const{__scopePopper:a,children:r}=t,[s,o]=v.useState(null);return c.jsx(fD,{scope:a,anchor:s,onAnchorChange:o,children:r})};Sw.displayName=fp;var _w="PopperAnchor",jw=v.forwardRef((t,a)=>{const{__scopePopper:r,virtualRef:s,...o}=t,u=ww(_w,r),d=v.useRef(null),f=bt(a,d),p=v.useRef(null);return v.useEffect(()=>{const m=p.current;p.current=s?.current||d.current,m!==p.current&&u.onAnchorChange(p.current)}),s?null:c.jsx(We.div,{...o,ref:f})});jw.displayName=_w;var hp="PopperContent",[hD,mD]=bw(hp),Nw=v.forwardRef((t,a)=>{const{__scopePopper:r,side:s="bottom",sideOffset:o=0,align:u="center",alignOffset:d=0,arrowPadding:f=0,avoidCollisions:p=!0,collisionBoundary:m=[],collisionPadding:x=0,sticky:y="partial",hideWhenDetached:w=!1,updatePositionStrategy:S="optimized",onPlaced:j,..._}=t,E=ww(hp,r),[O,R]=v.useState(null),N=bt(a,se=>R(se)),[A,L]=v.useState(null),z=dp(A),C=z?.width??0,B=z?.height??0,q=s+(u!=="center"?"-"+u:""),D=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},G=Array.isArray(m)?m:[m],te=G.length>0,re={padding:D,boundary:G.filter(gD),altBoundary:te},{refs:le,floatingStyles:V,placement:M,isPositioned:P,middlewareData:H}=tD({strategy:"fixed",placement:q,whileElementsMounted:(...se)=>Vk(...se,{animationFrame:S==="always"}),elements:{reference:E.anchor},middleware:[aD({mainAxis:o+B,alignmentAxis:d}),p&&rD({mainAxis:!0,crossAxis:!1,limiter:y==="partial"?lD():void 0,...re}),p&&sD({...re}),oD({...re,apply:({elements:se,rects:Re,availableWidth:J,availableHeight:we})=>{const{width:Ce,height:Ee}=Re.reference,Pe=se.floating.style;Pe.setProperty("--radix-popper-available-width",`${J}px`),Pe.setProperty("--radix-popper-available-height",`${we}px`),Pe.setProperty("--radix-popper-anchor-width",`${Ce}px`),Pe.setProperty("--radix-popper-anchor-height",`${Ee}px`)}}),A&&cD({element:A,padding:f}),vD({arrowWidth:C,arrowHeight:B}),w&&iD({strategy:"referenceHidden",...re})]}),[fe,pe]=Rw(M),k=Ir(j);cn(()=>{P&&k?.()},[P,k]);const U=H.arrow?.x,X=H.arrow?.y,ne=H.arrow?.centerOffset!==0,[oe,ye]=v.useState();return cn(()=>{O&&ye(window.getComputedStyle(O).zIndex)},[O]),c.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...V,transform:P?V.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:oe,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:c.jsx(hD,{scope:r,placedSide:fe,onArrowChange:L,arrowX:U,arrowY:X,shouldHideArrow:ne,children:c.jsx(We.div,{"data-side":fe,"data-align":pe,..._,ref:N,style:{..._.style,animation:P?void 0:"none"}})})})});Nw.displayName=hp;var Cw="PopperArrow",pD={top:"bottom",right:"left",bottom:"top",left:"right"},Ew=v.forwardRef(function(a,r){const{__scopePopper:s,...o}=a,u=mD(Cw,s),d=pD[u.placedSide];return c.jsx("span",{ref:u.onArrowChange,style:{position:"absolute",left:u.arrowX,top:u.arrowY,[d]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[u.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[u.placedSide],visibility:u.shouldHideArrow?"hidden":void 0},children:c.jsx(dD,{...o,ref:r,style:{...o.style,display:"block"}})})});Ew.displayName=Cw;function gD(t){return t!==null}var vD=t=>({name:"transformOrigin",options:t,fn(a){const{placement:r,rects:s,middlewareData:o}=a,d=o.arrow?.centerOffset!==0,f=d?0:t.arrowWidth,p=d?0:t.arrowHeight,[m,x]=Rw(r),y={start:"0%",center:"50%",end:"100%"}[x],w=(o.arrow?.x??0)+f/2,S=(o.arrow?.y??0)+p/2;let j="",_="";return m==="bottom"?(j=d?y:`${w}px`,_=`${-p}px`):m==="top"?(j=d?y:`${w}px`,_=`${s.floating.height+p}px`):m==="right"?(j=`${-p}px`,_=d?y:`${S}px`):m==="left"&&(j=`${s.floating.width+p}px`,_=d?y:`${S}px`),{data:{x:j,y:_}}}});function Rw(t){const[a,r="center"]=t.split("-");return[a,r]}var mp=Sw,Fu=jw,pp=Nw,gp=Ew,$u="Popover",[Tw]=Ea($u,[Fs]),pi=Fs(),[yD,Xr]=Tw($u),Ow=t=>{const{__scopePopover:a,children:r,open:s,defaultOpen:o,onOpenChange:u,modal:d=!1}=t,f=pi(a),p=v.useRef(null),[m,x]=v.useState(!1),[y,w]=er({prop:s,defaultProp:o??!1,onChange:u,caller:$u});return c.jsx(mp,{...f,children:c.jsx(yD,{scope:a,contentId:on(),triggerRef:p,open:y,onOpenChange:w,onOpenToggle:v.useCallback(()=>w(S=>!S),[w]),hasCustomAnchor:m,onCustomAnchorAdd:v.useCallback(()=>x(!0),[]),onCustomAnchorRemove:v.useCallback(()=>x(!1),[]),modal:d,children:r})})};Ow.displayName=$u;var Aw="PopoverAnchor",xD=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=Xr(Aw,r),u=pi(r),{onCustomAnchorAdd:d,onCustomAnchorRemove:f}=o;return v.useEffect(()=>(d(),()=>f()),[d,f]),c.jsx(Fu,{...u,...s,ref:a})});xD.displayName=Aw;var Mw="PopoverTrigger",kw=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=Xr(Mw,r),u=pi(r),d=bt(a,o.triggerRef),f=c.jsx(We.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Uw(o.open),...s,ref:d,onClick:Ve(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?f:c.jsx(Fu,{asChild:!0,...u,children:f})});kw.displayName=Mw;var vp="PopoverPortal",[bD,wD]=Tw(vp,{forceMount:void 0}),Dw=t=>{const{__scopePopover:a,forceMount:r,children:s,container:o}=t,u=Xr(vp,a);return c.jsx(bD,{scope:a,forceMount:r,children:c.jsx(sr,{present:r||u.open,children:c.jsx(Mu,{asChild:!0,container:o,children:s})})})};Dw.displayName=vp;var Ts="PopoverContent",Lw=v.forwardRef((t,a)=>{const r=wD(Ts,t.__scopePopover),{forceMount:s=r.forceMount,...o}=t,u=Xr(Ts,t.__scopePopover);return c.jsx(sr,{present:s||u.open,children:u.modal?c.jsx(_D,{...o,ref:a}):c.jsx(jD,{...o,ref:a})})});Lw.displayName=Ts;var SD=Es("PopoverContent.RemoveScroll"),_D=v.forwardRef((t,a)=>{const r=Xr(Ts,t.__scopePopover),s=v.useRef(null),o=bt(a,s),u=v.useRef(!1);return v.useEffect(()=>{const d=s.current;if(d)return Gm(d)},[]),c.jsx(Du,{as:SD,allowPinchZoom:!0,children:c.jsx(zw,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ve(t.onCloseAutoFocus,d=>{d.preventDefault(),u.current||r.triggerRef.current?.focus()}),onPointerDownOutside:Ve(t.onPointerDownOutside,d=>{const f=d.detail.originalEvent,p=f.button===0&&f.ctrlKey===!0,m=f.button===2||p;u.current=m},{checkForDefaultPrevented:!1}),onFocusOutside:Ve(t.onFocusOutside,d=>d.preventDefault(),{checkForDefaultPrevented:!1})})})}),jD=v.forwardRef((t,a)=>{const r=Xr(Ts,t.__scopePopover),s=v.useRef(!1),o=v.useRef(!1);return c.jsx(zw,{...t,ref:a,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:u=>{t.onCloseAutoFocus?.(u),u.defaultPrevented||(s.current||r.triggerRef.current?.focus(),u.preventDefault()),s.current=!1,o.current=!1},onInteractOutside:u=>{t.onInteractOutside?.(u),u.defaultPrevented||(s.current=!0,u.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const d=u.target;r.triggerRef.current?.contains(d)&&u.preventDefault(),u.detail.originalEvent.type==="focusin"&&o.current&&u.preventDefault()}})}),zw=v.forwardRef((t,a)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:u,disableOutsidePointerEvents:d,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:x,...y}=t,w=Xr(Ts,r),S=pi(r);return Vm(),c.jsx(Au,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:o,onUnmountAutoFocus:u,children:c.jsx(fi,{asChild:!0,disableOutsidePointerEvents:d,onInteractOutside:x,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onDismiss:()=>w.onOpenChange(!1),children:c.jsx(pp,{"data-state":Uw(w.open),role:"dialog",id:w.contentId,...S,...y,ref:a,style:{...y.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Pw="PopoverClose",ND=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=Xr(Pw,r);return c.jsx(We.button,{type:"button",...s,ref:a,onClick:Ve(t.onClick,()=>o.onOpenChange(!1))})});ND.displayName=Pw;var CD="PopoverArrow",ED=v.forwardRef((t,a)=>{const{__scopePopover:r,...s}=t,o=pi(r);return c.jsx(gp,{...o,...s,ref:a})});ED.displayName=CD;function Uw(t){return t?"open":"closed"}var RD=Ow,TD=kw,OD=Dw,AD=Lw;function Iu({...t}){return c.jsx(RD,{"data-slot":"popover",...t})}function qu({...t}){return c.jsx(TD,{"data-slot":"popover-trigger",...t})}function Vu({className:t,align:a="center",sideOffset:r=4,...s}){return c.jsx(OD,{children:c.jsx(AD,{"data-slot":"popover-content",align:a,sideOffset:r,className:Xe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden animate-fade-in",t),...s})})}function Rt({options:t,value:a,onChange:r,placeholder:s="Select an option...",searchPlaceholder:o="Search...",emptyPlaceholder:u="No options found."}){const[d,f]=v.useState(!1),p=t.find(m=>m.value===a);return c.jsxs(Iu,{open:d,onOpenChange:f,children:[c.jsx(qu,{asChild:!0,children:c.jsxs(ve,{variant:"outline",role:"combobox","aria-expanded":d,className:"w-full justify-between transition-all-ease hover:scale-[1.02] active:scale-[0.98]",children:[p?p.label:s,c.jsx(Im,{className:"ml-2 h-4 w-4 shrink-0 opacity-50 transition-transform duration-200 group-data-[state=open]:rotate-180"})]})}),c.jsx(Vu,{className:"w-[--radix-popover-trigger-width] p-0 animate-fade-in",children:c.jsxs(Wm,{children:[c.jsx(ep,{placeholder:o}),c.jsxs(tp,{children:[c.jsx(np,{children:u}),c.jsx(ap,{children:t.map(m=>c.jsxs(rp,{value:m.value,onSelect:x=>{r(x===a?"":x),f(!1)},className:"transition-all-ease hover:bg-accent hover:text-accent-foreground",children:[c.jsx(zs,{className:Xe("mr-2 h-4 w-4 transition-opacity",a===m.value?"opacity-100":"opacity-0")}),m.label]},m.value))})]})]})})]})}const MD=v.forwardRef(({options:t,value:a,onChange:r,onEnter:s,searchPlaceholder:o="Search...",emptyPlaceholder:u="No options found.",inputPlaceholder:d="Type or select..."},f)=>{const[p,m]=v.useState(!1),[x,y]=v.useState(a||""),w=v.useRef(null);v.useImperativeHandle(f,()=>w.current),v.useEffect(()=>{y(a||"")},[a]);const S=O=>{const R=O.target.value;y(R),r(R)},j=O=>{O.key==="Enter"&&x.trim()&&s&&(s(x.trim()),y(""))},_=O=>{y(O),r(O),s&&(s(O),y("")),m(!1)},E=()=>x;return v.useImperativeHandle(f,()=>({...w.current,value:x,getCurrentValue:E,clearInput:()=>{y(""),r("")}})),c.jsxs("div",{className:"relative",children:[c.jsx(lt,{ref:w,value:x,onChange:S,onKeyDown:j,placeholder:d,className:"pr-10"}),c.jsxs(Iu,{open:p,onOpenChange:m,children:[c.jsx(qu,{asChild:!0,children:c.jsx(ve,{variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",children:c.jsx(Im,{className:"h-4 w-4 opacity-50"})})}),c.jsx(Vu,{className:"w-[--radix-popover-trigger-width] p-0 animate-fade-in",children:c.jsxs(Wm,{children:[c.jsx(ep,{placeholder:o}),c.jsxs(tp,{children:[c.jsx(np,{children:u}),c.jsx(ap,{children:t.map(O=>c.jsxs(rp,{value:O.value,onSelect:()=>_(O.value),className:"transition-all-ease hover:bg-accent hover:text-accent-foreground",children:[c.jsx(zs,{className:Xe("mr-2 h-4 w-4 transition-opacity",a===O.value?"opacity-100":"opacity-0")}),O.label]},O.value))})]})]})})]})]})});function kD(){const{t}=un(),{config:a,setConfig:r}=Yr(),[s,o]=v.useState(null),[u,d]=v.useState(null),[f,p]=v.useState({}),[m,x]=v.useState({}),[y,w]=v.useState({}),[S,j]=v.useState([]),[_,E]=v.useState(null),[O,R]=v.useState(!1),[N,A]=v.useState([]),[L,z]=v.useState({}),[C,B]=v.useState(null),[q,D]=v.useState(null),[G,te]=v.useState(""),[re,le]=v.useState([]),[V,M]=v.useState([]),P=v.useRef(null);if(v.useEffect(()=>{(async()=>{try{const ce=await fetch("https://pub-0dc3e1677e894f07bbea11b17a29e032.r2.dev/providers.json");if(ce.ok){const me=await ce.json();A(me||[])}else console.error("Failed to fetch provider templates")}catch(ce){console.error("Failed to fetch provider templates:",ce)}})()},[]),v.useEffect(()=>{(async()=>{try{const ce=await nt.get("/transformers");j(ce.transformers)}catch(ce){console.error("Failed to fetch transformers:",ce)}})()},[]),v.useEffect(()=>{const ue=async()=>{try{const me=await nt.getProviderHealth();le(me.states||[])}catch(me){console.error("Failed to fetch provider health:",me)}};ue();const ce=setInterval(ue,3e4);return()=>clearInterval(ce)},[]),v.useEffect(()=>{const ue=async()=>{try{const me=await nt.getProviderQuota();M(me.quotas||[])}catch(me){console.error("Failed to fetch provider quota:",me)}};ue();const ce=setInterval(ue,3e4);return()=>clearInterval(ce)},[]),!a)return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"flex flex-row items-center justify-between border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("providers.title")})}),c.jsx(Xn,{className:"flex-grow flex items-center justify-center p-4",children:c.jsx("div",{className:"text-gray-500",children:"Loading providers configuration..."})})]});const H=Array.isArray(a.Providers)?a.Providers:[],fe=()=>{const ue={name:"",api_base_url:"",api_key:"",models:[]};o(a.Providers.length),E(ue),R(!0),z(ce=>({...ce,[a.Providers.length]:!1})),B(null),D(null)},pe=ue=>{const ce=H.indexOf(Qe[ue]),me=a.Providers[ce];o(ce),E(JSON.parse(JSON.stringify(me))),R(!1),z(xe=>({...xe,[ce]:!1})),B(null),D(null)},k=()=>{if(!_)return;if(!_.name||_.name.trim()===""){D(t("providers.name_required"));return}const ue=_.name.trim();if(a.Providers.some((me,xe)=>!O&&xe===s?!1:me.name.toLowerCase()===ue.toLowerCase())){D(t("providers.name_duplicate"));return}if(!_.api_key||_.api_key.trim()===""){B(t("providers.api_key_required"));return}if(B(null),D(null),s!==null&&_){const me=[...a.Providers];O?me.push(_):me[s]=_,r({...a,Providers:me})}s!==null&&z(me=>{const xe={...me};return delete xe[s],xe}),o(null),E(null),R(!1)},U=()=>{s!==null&&(p(ue=>{const ce={...ue};return delete ce[s],ce}),z(ue=>{const ce={...ue};return delete ce[s],ce})),o(null),E(null),R(!1),B(null),D(null)},X=ue=>{d(ue)},ne=ue=>{const ce=H.indexOf(Qe[ue]),me=[...a.Providers];me.splice(ce,1),r({...a,Providers:me}),d(null)},oe=(ue,ce,me)=>{if(_){const xe={..._,[ce]:me};E(xe)}},ye=(ue,ce)=>{if(!ce||!_)return;const me={..._};me.transformer||(me.transformer={use:[]}),me.transformer.use=[...me.transformer.use,ce],E(me)},se=(ue,ce)=>{if(!_)return;const me={..._};if(me.transformer){const xe=[...me.transformer.use];xe.splice(ce,1),me.transformer.use=xe,xe.length===0&&Object.keys(me.transformer).length===1&&delete me.transformer}E(me)},Re=(ue,ce,me)=>{if(!me||!_)return;const xe={..._};xe.transformer||(xe.transformer={use:[]}),xe.transformer[ce]||(xe.transformer[ce]={use:[]}),xe.transformer[ce].use=[...xe.transformer[ce].use,me],E(xe)},J=(ue,ce,me)=>{if(!_)return;const xe={..._};if(xe.transformer&&xe.transformer[ce]){const Be=[...xe.transformer[ce].use];Be.splice(me,1),xe.transformer[ce].use=Be,Be.length===0&&Object.keys(xe.transformer[ce]).length===1&&delete xe.transformer[ce]}E(xe)},we=(ue,ce,me,xe)=>{if(!_)return;const Be={..._};if(Be.transformer||(Be.transformer={use:[]}),Be.transformer.use&&Be.transformer.use.length>ce){const Oe=Be.transformer.use[ce];if(Array.isArray(Oe)){const Ge=[...Oe];if(Ge.length>1&&typeof Ge[1]=="object"&&Ge[1]!==null){const bn={...Ge[1],[me]:xe};Ge[1]=bn}else if(Ge.length>1){const wt={[me]:xe};Ge.splice(1,Ge.length-1,wt)}else{const wt={[me]:xe};Ge.push(wt)}Be.transformer.use[ce]=Ge}else{const Ge={[me]:xe};Be.transformer.use[ce]=[Oe,Ge]}}E(Be)},Ce=(ue,ce,me)=>{if(!_)return;const xe={..._};if(!xe.transformer?.use||xe.transformer.use.length<=ce)return;const Be=xe.transformer.use[ce];if(Array.isArray(Be)&&Be.length>1){const Oe=[...Be];if(typeof Oe[1]=="object"&&Oe[1]!==null){const Ge={...Oe[1]};delete Ge[me],Object.keys(Ge).length===0?Oe.splice(1,1):Oe[1]=Ge,xe.transformer.use[ce]=Oe,E(xe)}}},Ee=(ue,ce,me,xe,Be)=>{if(!_)return;const Oe={..._};if(Oe.transformer||(Oe.transformer={use:[]}),Oe.transformer[ce]||(Oe.transformer[ce]={use:[]}),Oe.transformer[ce].use&&Oe.transformer[ce].use.length>me){const Ge=Oe.transformer[ce].use[me];if(Array.isArray(Ge)){const wt=[...Ge];if(wt.length>1&&typeof wt[1]=="object"&&wt[1]!==null){const an={...wt[1],[xe]:Be};wt[1]=an}else if(wt.length>1){const bn={[xe]:Be};wt.splice(1,wt.length-1,bn)}else{const bn={[xe]:Be};wt.push(bn)}Oe.transformer[ce].use[me]=wt}else{const wt={[xe]:Be};Oe.transformer[ce].use[me]=[Ge,wt]}}E(Oe)},Pe=(ue,ce,me,xe)=>{if(!_)return;const Be={..._};if(!Be.transformer?.[ce]?.use||Be.transformer[ce].use.length<=me)return;const Oe=Be.transformer[ce].use[me];if(Array.isArray(Oe)&&Oe.length>1){const Ge=[...Oe];if(typeof Ge[1]=="object"&&Ge[1]!==null){const wt={...Ge[1]};delete wt[xe],Object.keys(wt).length===0?Ge.splice(1,1):Ge[1]=wt,Be.transformer[ce].use[me]=Ge,E(Be)}}},gt=(ue,ce)=>{if(!ce.trim()||!_)return;const me={..._},xe=Array.isArray(me.models)?[...me.models]:[];xe.includes(ce.trim())||(xe.push(ce.trim()),me.models=xe,E(me))},Se=ue=>{if(ue)try{const ce=JSON.parse(ue);if(ce){const me=_?.name,xe=JSON.parse(JSON.stringify(ce));!O&&me&&(xe.name=me),E(xe)}}catch(ce){console.error("Failed to parse template",ce)}},qe=(ue,ce)=>{if(!_)return;const me={..._},xe=Array.isArray(me.models)?[...me.models]:[];ce>=0&&ce<xe.length&&(xe.splice(ce,1),me.models=xe,E(me))},Ue=_||(s!==null?H[s]:null),Qe=H.filter(ue=>{if(!G)return!0;const ce=G.toLowerCase();return ue.name&&ue.name.toLowerCase().includes(ce)||ue.api_base_url&&ue.api_base_url.toLowerCase().includes(ce)?!0:ue.models&&Array.isArray(ue.models)?ue.models.some(me=>me&&me.toLowerCase().includes(ce)):!1});return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsxs(ia,{className:"flex flex-col border-b p-4 gap-3",children:[c.jsxs("div",{className:"flex flex-row items-center justify-between",children:[c.jsxs(ca,{className:"text-lg",children:[t("providers.title")," ",c.jsxs("span",{className:"text-sm font-normal text-gray-500",children:["(",Qe.length,"/",H.length,")"]})]}),c.jsx(ve,{onClick:fe,children:t("providers.add")})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx(qm,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500"}),c.jsx(lt,{placeholder:t("providers.search"),value:G,onChange:ue=>te(ue.target.value),className:"pl-8"})]}),G&&c.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>te(""),children:c.jsx(b1,{className:"h-4 w-4"})})]})]}),c.jsx(Xn,{className:"flex-grow overflow-y-auto p-4",children:c.jsx(TM,{providers:Qe,healthStates:re,quotaUsages:V,onEdit:pe,onRemove:X})}),c.jsx(xa,{open:s!==null,onOpenChange:ue=>{ue||U()},children:c.jsxs(la,{className:"max-h-[80vh] flex flex-col sm:max-w-2xl",children:[c.jsx(sa,{children:c.jsx(oa,{children:t("providers.edit")})}),Ue&&s!==null&&c.jsxs("div",{className:"space-y-4 p-4 overflow-y-auto flex-grow",children:[N.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("providers.import_from_template")}),c.jsx(Rt,{options:N.map(ue=>({label:ue.name,value:JSON.stringify(ue)})),value:"",onChange:Se,placeholder:t("providers.select_template"),emptyPlaceholder:t("providers.no_templates_found")})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"name",children:t("providers.name")}),c.jsx(lt,{id:"name",value:Ue.name||"",onChange:ue=>{oe(s,"name",ue.target.value),q&&D(null)},className:q?"border-red-500":""}),q&&c.jsx("p",{className:"text-sm text-red-500",children:q})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"api_base_url",children:t("providers.api_base_url")}),c.jsx(lt,{id:"api_base_url",value:Ue.api_base_url||"",onChange:ue=>oe(s,"api_base_url",ue.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"api_key",children:t("providers.api_key")}),c.jsxs("div",{className:"relative",children:[c.jsx(lt,{id:"api_key",type:L[s||0]?"text":"password",value:Ue.api_key||"",onChange:ue=>oe(s,"api_key",ue.target.value),className:C?"border-red-500":""}),c.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 transform -translate-y-1/2 h-8 w-8",onClick:()=>{const ue=s||0;z(ce=>({...ce,[ue]:!ce[ue]}))},children:L[s||0]?c.jsx(cO,{className:"h-4 w-4"}):c.jsx(dO,{className:"h-4 w-4"})})]}),C&&c.jsx("p",{className:"text-sm text-red-500",children:C})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{htmlFor:"models",children:t("providers.models")}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx("div",{className:"flex-1",children:f[s]?c.jsx(MD,{ref:P,options:(Ue.models||[]).map(ue=>({label:ue,value:ue})),value:"",onChange:()=>{},onEnter:ue=>{s!==null&&gt(s,ue)},inputPlaceholder:t("providers.models_placeholder")}):c.jsx(lt,{id:"models",placeholder:t("providers.models_placeholder"),onKeyDown:ue=>{ue.key==="Enter"&&ue.currentTarget.value.trim()&&s!==null&&(gt(s,ue.currentTarget.value),ue.currentTarget.value="")}})}),c.jsx(ve,{onClick:()=>{if(f[s]&&P.current){const ue=P.current,ce=ue.getCurrentValue();ce&&ce.trim()&&s!==null&&(gt(s,ce.trim()),ue.clearInput())}else{const ue=document.getElementById("models");ue&&ue.value.trim()&&s!==null&&(gt(s,ue.value),ue.value="")}},children:t("providers.add_model")})]}),c.jsx("div",{className:"flex flex-wrap gap-2 pt-2",children:(Ue.models||[]).map((ue,ce)=>c.jsxs(Ur,{variant:"outline",className:"font-normal flex items-center gap-1",children:[ue,c.jsx("button",{type:"button",className:"ml-1 rounded-full hover:bg-gray-200",onClick:()=>s!==null&&qe(s,ce),children:c.jsx(Wa,{className:"h-3 w-3"})})]},ce))})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("providers.provider_transformer")}),c.jsx("div",{className:"flex gap-2",children:c.jsx(Rt,{options:S.map(ue=>({label:ue.name,value:ue.name})),value:"",onChange:ue=>{s!==null&&ye(s,ue)},placeholder:t("providers.select_transformer"),emptyPlaceholder:t("providers.no_transformers")})}),Ue.transformer?.use&&Ue.transformer.use.length>0&&c.jsxs("div",{className:"space-y-2 mt-2",children:[c.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("providers.selected_transformers")}),Ue.transformer.use.map((ue,ce)=>c.jsxs("div",{className:"border rounded-md p-3",children:[c.jsxs("div",{className:"flex gap-2 items-center mb-2",children:[c.jsx("div",{className:"flex-1 bg-gray-50 rounded p-2 text-sm",children:typeof ue=="string"?ue:Array.isArray(ue)?String(ue[0]):String(ue)}),c.jsx(ve,{variant:"outline",size:"icon",onClick:()=>{s!==null&&se(s,ce)},children:c.jsx(kn,{className:"h-4 w-4"})})]}),c.jsxs("div",{className:"mt-2 pl-4 border-l-2 border-gray-200",children:[c.jsx(Te,{className:"text-sm",children:t("providers.transformer_parameters")}),c.jsxs("div",{className:"space-y-2 mt-1",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx(lt,{placeholder:t("providers.parameter_name"),value:m[`provider-${s}-transformer-${ce}`]?.name||"",onChange:me=>{const xe=`provider-${s}-transformer-${ce}`;x(Be=>({...Be,[xe]:{...Be[xe]||{name:"",value:""},name:me.target.value}}))}}),c.jsx(lt,{placeholder:t("providers.parameter_value"),value:m[`provider-${s}-transformer-${ce}`]?.value||"",onChange:me=>{const xe=`provider-${s}-transformer-${ce}`;x(Be=>({...Be,[xe]:{...Be[xe]||{name:"",value:""},value:me.target.value}}))}}),c.jsx(ve,{size:"sm",onClick:()=>{if(s!==null){const me=`provider-${s}-transformer-${ce}`,xe=m[me];xe&&xe.name&&xe.value&&(we(s,ce,xe.name,xe.value),x(Be=>({...Be,[me]:{name:"",value:""}})))}},children:c.jsx(du,{className:"h-4 w-4"})})]}),(()=>{if(!Ue.transformer?.use||Ue.transformer.use.length<=ce)return null;const me=Ue.transformer.use[ce];let xe={};return Array.isArray(me)&&me.length>1&&typeof me[1]=="object"&&me[1]!==null&&(xe=me[1]),Object.keys(xe).length>0?c.jsx("div",{className:"space-y-1",children:Object.entries(xe).map(([Be,Oe])=>c.jsxs("div",{className:"flex items-center justify-between bg-gray-50 rounded p-2",children:[c.jsxs("div",{className:"text-sm",children:[c.jsxs("span",{className:"font-medium",children:[Be,":"]})," ",String(Oe)]}),c.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>{s!==null&&Ce(s,ce,Be)},children:c.jsx(Wa,{className:"h-3 w-3"})})]},Be))}):null})()]})]})]},ce))]})]}),Ue.models&&Ue.models.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("providers.model_transformers")}),c.jsx("div",{className:"space-y-3",children:(Ue.models||[]).map((ue,ce)=>c.jsxs("div",{className:"border rounded-md p-3",children:[c.jsx("div",{className:"font-medium text-sm mb-2",children:ue}),c.jsx("div",{className:"flex gap-2",children:c.jsx("div",{className:"flex-1 flex gap-2",children:c.jsx(Rt,{options:S.map(me=>({label:me.name,value:me.name})),value:"",onChange:me=>{s!==null&&Re(s,ue,me)},placeholder:t("providers.select_transformer"),emptyPlaceholder:t("providers.no_transformers")})})}),Ue.transformer?.[ue]?.use&&Ue.transformer[ue].use.length>0&&c.jsxs("div",{className:"space-y-2 mt-2",children:[c.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("providers.selected_transformers")}),Ue.transformer[ue].use.map((me,xe)=>c.jsxs("div",{className:"border rounded-md p-3",children:[c.jsxs("div",{className:"flex gap-2 items-center mb-2",children:[c.jsx("div",{className:"flex-1 bg-gray-50 rounded p-2 text-sm",children:typeof me=="string"?me:Array.isArray(me)?String(me[0]):String(me)}),c.jsx(ve,{variant:"outline",size:"icon",onClick:()=>{s!==null&&J(s,ue,xe)},children:c.jsx(kn,{className:"h-4 w-4"})})]}),c.jsxs("div",{className:"mt-2 pl-4 border-l-2 border-gray-200",children:[c.jsx(Te,{className:"text-sm",children:t("providers.transformer_parameters")}),c.jsxs("div",{className:"space-y-2 mt-1",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx(lt,{placeholder:t("providers.parameter_name"),value:y[`model-${s}-${ue}-transformer-${xe}`]?.name||"",onChange:Be=>{const Oe=`model-${s}-${ue}-transformer-${xe}`;w(Ge=>({...Ge,[Oe]:{...Ge[Oe]||{name:"",value:""},name:Be.target.value}}))}}),c.jsx(lt,{placeholder:t("providers.parameter_value"),value:y[`model-${s}-${ue}-transformer-${xe}`]?.value||"",onChange:Be=>{const Oe=`model-${s}-${ue}-transformer-${xe}`;w(Ge=>({...Ge,[Oe]:{...Ge[Oe]||{name:"",value:""},value:Be.target.value}}))}}),c.jsx(ve,{size:"sm",onClick:()=>{if(s!==null){const Be=`model-${s}-${ue}-transformer-${xe}`,Oe=y[Be];Oe&&Oe.name&&Oe.value&&(Ee(s,ue,xe,Oe.name,Oe.value),w(Ge=>({...Ge,[Be]:{name:"",value:""}})))}},children:c.jsx(du,{className:"h-4 w-4"})})]}),(()=>{if(!Ue.transformer?.[ue]?.use||Ue.transformer[ue].use.length<=xe)return null;const Be=Ue.transformer[ue].use[xe];let Oe={};return Array.isArray(Be)&&Be.length>1&&typeof Be[1]=="object"&&Be[1]!==null&&(Oe=Be[1]),Object.keys(Oe).length>0?c.jsx("div",{className:"space-y-1",children:Object.entries(Oe).map(([Ge,wt])=>c.jsxs("div",{className:"flex items-center justify-between bg-gray-50 rounded p-2",children:[c.jsxs("div",{className:"text-sm",children:[c.jsxs("span",{className:"font-medium",children:[Ge,":"]})," ",String(wt)]}),c.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>{s!==null&&Pe(s,ue,xe,Ge)},children:c.jsx(Wa,{className:"h-3 w-3"})})]},Ge))}):null})()]})]})]},xe))]})]},ce))})]})]}),c.jsx("div",{className:"space-y-3 mt-auto",children:c.jsx("div",{className:"flex justify-end gap-2",children:c.jsx(ve,{onClick:k,children:t("app.save")})})})]})}),c.jsx(xa,{open:u!==null,onOpenChange:()=>d(null),children:c.jsxs(la,{children:[c.jsxs(sa,{children:[c.jsx(oa,{children:t("providers.delete")}),c.jsx(Nl,{children:t("providers.delete_provider_confirm")})]}),c.jsxs(qr,{children:[c.jsx(ve,{variant:"outline",onClick:()=>d(null),children:t("providers.cancel")}),c.jsx(ve,{variant:"destructive",onClick:()=>u!==null&&ne(u),children:t("providers.delete")})]})]})})]})}function DD(){const{t}=un(),{config:a,setConfig:r}=Yr();if(!a)return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("router.title")})}),c.jsx(Xn,{className:"flex-grow flex items-center justify-center p-4",children:c.jsx("div",{className:"text-gray-500",children:"Loading router configuration..."})})]});const s=a.Router||{default:"",background:"",think:"",longContext:"",longContextThreshold:6e4,webSearch:"",image:""},o=(p,m)=>{const y={...a.Router||{},[p]:m};r({...a,Router:y})},u=p=>{r({...a,forceUseImageAgent:p})},f=(Array.isArray(a.Providers)?a.Providers:[]).flatMap(p=>{if(!p)return[];const m=Array.isArray(p.models)?p.models:[],x=p.name||"Unknown Provider";return m.map(y=>({value:`${x},${y||"Unknown Model"}`,label:`${x}, ${y||"Unknown Model"}`}))});return c.jsxs(Yn,{className:"flex h-full flex-col rounded-lg border shadow-sm",children:[c.jsx(ia,{className:"border-b p-4",children:c.jsx(ca,{className:"text-lg",children:t("router.title")})}),c.jsxs(Xn,{className:"flex-grow space-y-5 overflow-y-auto p-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.default")}),c.jsx(Rt,{options:f,value:s.default||"",onChange:p=>o("default",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.background")}),c.jsx(Rt,{options:f,value:s.background||"",onChange:p=>o("background",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.think")}),c.jsx(Rt,{options:f,value:s.think||"",onChange:p=>o("think",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsx("div",{className:"space-y-2",children:c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsxs("div",{className:"flex-1",children:[c.jsx(Te,{children:t("router.longContext")}),c.jsx(Rt,{options:f,value:s.longContext||"",onChange:p=>o("longContext",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"w-48",children:[c.jsx(Te,{children:t("router.longContextThreshold")}),c.jsx(lt,{type:"number",value:s.longContextThreshold||6e4,onChange:p=>o("longContextThreshold",parseInt(p.target.value)||6e4),placeholder:"60000"})]})]})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Te,{children:t("router.webSearch")}),c.jsx(Rt,{options:f,value:s.webSearch||"",onChange:p=>o("webSearch",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsx("div",{className:"space-y-2",children:c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsxs("div",{className:"flex-1",children:[c.jsxs(Te,{children:[t("router.image")," (beta)"]}),c.jsx(Rt,{options:f,value:s.image||"",onChange:p=>o("image",p),placeholder:t("router.selectModel"),searchPlaceholder:t("router.searchModel"),emptyPlaceholder:t("router.noModelFound")})]}),c.jsxs("div",{className:"w-48",children:[c.jsx(Te,{htmlFor:"forceUseImageAgent",children:t("router.forceUseImageAgent")}),c.jsxs("select",{id:"forceUseImageAgent",value:a.forceUseImageAgent?"true":"false",onChange:p=>u(p.target.value==="true"),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[c.jsx("option",{value:"false",children:t("common.no")}),c.jsx("option",{value:"true",children:t("common.yes")})]})]})]})})]})]})}function Z0(t,a){(a==null||a>t.length)&&(a=t.length);for(var r=0,s=Array(a);r<a;r++)s[r]=t[r];return s}function LD(t){if(Array.isArray(t))return t}function zD(t,a,r){return(a=ID(a))in t?Object.defineProperty(t,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[a]=r,t}function PD(t,a){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var s,o,u,d,f=[],p=!0,m=!1;try{if(u=(r=r.call(t)).next,a!==0)for(;!(p=(s=u.call(r)).done)&&(f.push(s.value),f.length!==a);p=!0);}catch(x){m=!0,o=x}finally{try{if(!p&&r.return!=null&&(d=r.return(),Object(d)!==d))return}finally{if(m)throw o}}return f}}function UD(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
63
63
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function J0(t,a){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);a&&(s=s.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,s)}return r}function W0(t){for(var a=1;a<arguments.length;a++){var r=arguments[a]!=null?arguments[a]:{};a%2?J0(Object(r),!0).forEach(function(s){zD(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):J0(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}function HD(t,a){if(t==null)return{};var r,s,o=BD(t,a);if(Object.getOwnPropertySymbols){var u=Object.getOwnPropertySymbols(t);for(s=0;s<u.length;s++)r=u[s],a.indexOf(r)===-1&&{}.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function BD(t,a){if(t==null)return{};var r={};for(var s in t)if({}.hasOwnProperty.call(t,s)){if(a.indexOf(s)!==-1)continue;r[s]=t[s]}return r}function FD(t,a){return LD(t)||PD(t,a)||qD(t,a)||UD()}function $D(t,a){if(typeof t!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,a);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function ID(t){var a=$D(t,"string");return typeof a=="symbol"?a:a+""}function qD(t,a){if(t){if(typeof t=="string")return Z0(t,a);var r={}.toString.call(t).slice(8,-1);return r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set"?Array.from(t):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Z0(t,a):void 0}}function VD(t,a,r){return a in t?Object.defineProperty(t,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[a]=r,t}function eb(t,a){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);a&&(s=s.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,s)}return r}function tb(t){for(var a=1;a<arguments.length;a++){var r=arguments[a]!=null?arguments[a]:{};a%2?eb(Object(r),!0).forEach(function(s){VD(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):eb(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}function GD(){for(var t=arguments.length,a=new Array(t),r=0;r<t;r++)a[r]=arguments[r];return function(s){return a.reduceRight(function(o,u){return u(o)},s)}}function Vo(t){return function a(){for(var r=this,s=arguments.length,o=new Array(s),u=0;u<s;u++)o[u]=arguments[u];return o.length>=t.length?t.apply(this,o):function(){for(var d=arguments.length,f=new Array(d),p=0;p<d;p++)f[p]=arguments[p];return a.apply(r,[].concat(o,f))}}}function vu(t){return{}.toString.call(t).includes("Object")}function KD(t){return!Object.keys(t).length}function si(t){return typeof t=="function"}function YD(t,a){return Object.prototype.hasOwnProperty.call(t,a)}function XD(t,a){return vu(a)||Br("changeType"),Object.keys(a).some(function(r){return!YD(t,r)})&&Br("changeField"),a}function QD(t){si(t)||Br("selectorType")}function ZD(t){si(t)||vu(t)||Br("handlerType"),vu(t)&&Object.values(t).some(function(a){return!si(a)})&&Br("handlersType")}function JD(t){t||Br("initialIsRequired"),vu(t)||Br("initialType"),KD(t)&&Br("initialContent")}function WD(t,a){throw new Error(t[a]||t.default)}var e4={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},Br=Vo(WD)(e4),Gc={changes:XD,selector:QD,handler:ZD,initial:JD};function t4(t){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Gc.initial(t),Gc.handler(a);var r={current:t},s=Vo(r4)(r,a),o=Vo(a4)(r),u=Vo(Gc.changes)(t),d=Vo(n4)(r);function f(){var m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(x){return x};return Gc.selector(m),m(r.current)}function p(m){GD(s,o,u,d)(m)}return[f,p]}function n4(t,a){return si(a)?a(t.current):a}function a4(t,a){return t.current=tb(tb({},t.current),a),a}function r4(t,a,r){return si(a)?a(t.current):Object.keys(r).forEach(function(s){var o;return(o=a[s])===null||o===void 0?void 0:o.call(a,t.current[s])}),r}var l4={create:t4},s4={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function o4(t){return function a(){for(var r=this,s=arguments.length,o=new Array(s),u=0;u<s;u++)o[u]=arguments[u];return o.length>=t.length?t.apply(this,o):function(){for(var d=arguments.length,f=new Array(d),p=0;p<d;p++)f[p]=arguments[p];return a.apply(r,[].concat(o,f))}}}function i4(t){return{}.toString.call(t).includes("Object")}function c4(t){return t||nb("configIsRequired"),i4(t)||nb("configType"),t.urls?(u4(),{paths:{vs:t.urls.monacoBase}}):t}function u4(){console.warn(Hw.deprecation)}function d4(t,a){throw new Error(t[a]||t.default)}var Hw={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
64
64
  You are using deprecated way of configuration.
65
65
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wengine-ai/claude-code-router",
3
- "version": "2.0.50",
3
+ "version": "2.0.51",
4
4
  "description": "CLI for Claude Code Router",
5
5
  "bin": {
6
6
  "ccr": "dist/cli.js"
@@ -14,7 +14,7 @@
14
14
  "author": "musistudio",
15
15
  "license": "MIT",
16
16
  "dependencies": {
17
- "@wengine-ai/llms": "^2.0.45",
17
+ "@wengine-ai/llms": "^2.0.46",
18
18
  "lru-cache": "^11.2.2"
19
19
  },
20
20
  "devDependencies": {