@thxp/llms 3.2.19 → 3.2.21

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.
@@ -69,7 +69,7 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var rd
69
69
  ${this.toMarkdown(s,r+1)}`:`${n}- ${s}`).join(`
70
70
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([s,i])=>typeof i=="object"&&i!==null?`${n}${s}:
71
71
  ${this.toMarkdown(i,r+1)}`:`${n}${s}: ${i}`).join(`
72
- `):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var yo,xd=Be(()=>{"use strict";yo=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 r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:s=!0,prefix:i,metadata:u}=r||{},c={data:e};return s&&(c.timestamp=new Date().toISOString()),i&&(c.prefix=i),u&&Object.keys(u).length>0&&(c.metadata=u),c}async sendRequest(e,r,n,s,i){let u=new AbortController,c=setTimeout(()=>u.abort(),i);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(s),signal:u.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,s,i,u){let c=null;for(let l=1;l<=u.maxAttempts;l++)try{return await this.sendRequest(e,r,n,s,i)}catch(d){if(c=d,l===u.maxAttempts)break;let h=u.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${u.maxAttempts}), retrying in ${h}ms...`,d.message),await this.delay(h)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let s=this.buildHeaders(),i=this.buildBody(e,r),u=await this.sendWithRetry(this.config.url,this.config.method,s,i,n,this.config.retry);return!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}});var hs,Fd,r0,_o,Pd=Be(()=>{"use strict";hs=require("fs"),Fd=require("path"),r0=require("os"),_o=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=(0,r0.tmpdir)();this.baseDir=(0,Fd.join)(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,hs.existsSync)(this.baseDir)||(0,hs.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",s;if(this.config.includeTimestamp){let i=Date.now();s=`${r}-${e}-${i}${n}`}else s=`${r}-${e}${n}`;return(0,Fd.join)(this.baseDir,s)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let s={...e,timestamp:Date.now(),sessionId:n},i=this.getFilePath(n);return(0,hs.writeFileSync)(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Id,ps,n0=Be(()=>{"use strict";Od();xd();Pd();Id=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),s=r.type+"_"+Date.now();this.registerHandler(s,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new go(e.config);case"webhook":return new yo(e.config);case"temp-file":return new _o(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,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([u,c])=>{try{await c.output(e,n)?s.success.push(u):s.failed.push(u)}catch(l){console.error(`[OutputManager] Handler ${u} failed:`,l),s.failed.push(u)}});return await Promise.all(i),s}async outputTo(e,r,n){let s={...this.defaultOptions,...n},i={success:[],failed:[]},u=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),i.failed.push(c);return}try{await l.output(r,s)?i.success.push(c):i.failed.push(c)}catch(d){console.error(`[OutputManager] Handler ${c} failed:`,d),i.failed.push(c)}});return await Promise.all(u),i}async outputToType(e,r,n){let s=Array.from(this.handlers.entries()).filter(([i,u])=>u.type===e).map(([i])=>i);return this.outputTo(s,r,n)}},ps=new Id});var dT={};vu(dT,{ConfigService:()=>nn,ProviderService:()=>an,SSEParserTransform:()=>_r,SSESerializerTransform:()=>on,TokenizerService:()=>Cn,TransformerService:()=>bn,calculateTokenCount:()=>Sd,default:()=>lT,getModelUsage:()=>Bn,pluginManager:()=>Td,recordModelUsage:()=>Zo,rewriteStream:()=>vs,router:()=>Za,searchProjectBySession:()=>kd,sessionUsageCache:()=>uh,tokenSpeedPlugin:()=>Bd});module.exports=V_(dT);var i0=je(require("fastify"),1),a0=je(require("@fastify/cors"),1);var ks=require("fs"),Mu=require("path"),Qf=require("dotenv"),Zf=je(ju(),1),nn=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,Mu.join)(process.cwd(),this.options.jsonPath);if((0,ks.existsSync)(e))try{let r=(0,ks.readFileSync)(e,"utf-8"),n=Zf.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,Mu.join)(process.cwd(),this.options.envPath);if((0,ks.existsSync)(e))try{let r=(0,Qf.config)({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")||process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy}has(e){return this.config[e]!==void 0}set(e,r){this.config[e]=r}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 Xe(t,e=500,r="internal_error",n="api_error"){let s=new Error(t);return s.statusCode=e,s.code=r,s.type=n,s}async function eh(t,e,r){e.log.error(t);let n=t.statusCode||500,s={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(s)}var th=require("undici");function rh(t,e,r,n,s){let i=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([d,h])=>{h&&i.set(d,h)});let u,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let d=new AbortController,h=()=>d.abort();r.signal.addEventListener("abort",h),c.addEventListener("abort",h),u=d.signal}else u=c;let l={method:"POST",headers:i,body:JSON.stringify(e),signal:u};return r.httpsProxy&&(l.dispatcher=new th.ProxyAgent(new URL(r.httpsProxy).toString())),s?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(i.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var Nn=require("fs"),nh=require("path"),sh=require("@thxp/shared"),Lu=(0,nh.join)(sh.HOME_DIR,"daily_usage.json"),sn=null;function nb(){let t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function oh(){let t=nb();if(sn&&sn.date===t)return sn;try{if((0,Nn.existsSync)(Lu)){let e=JSON.parse((0,Nn.readFileSync)(Lu,"utf-8"));if(e?.date===t)return sn=e,e}}catch{}return sn={date:t,models:{}},ih(sn),sn}function ih(t){try{(0,Nn.writeFileSync)(Lu,JSON.stringify(t,null,2),"utf-8")}catch{}}function Zo(t,e,r){let n=oh(),s=`${t.toLowerCase()},${e.toLowerCase()}`;n.models[s]=(n.models[s]||0)+r,ih(n)}function Bn(t,e){return oh().models[`${t.toLowerCase()},${e.toLowerCase()}`]||0}var ah="3.2.19";var ei=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}has(e){return this.cache.has(e)}del(e){return this.cache.delete(e)}clear(){this.cache.clear()}values(){return Array.from(this.cache.values())}},uh=new ei(100),ob=300*1e3,Uu=new ei(1e3),ch=t=>{Uu.put(t,Date.now())},Ds=t=>{let e=Uu.get(t);return e===void 0?!1:Date.now()-e>ob?(Uu.del(t),!1):!0};var Ts=(t,e)=>`${t},${e}`;var _r=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
72
+ `):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var yo,xd=Be(()=>{"use strict";yo=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 r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:s=!0,prefix:i,metadata:u}=r||{},c={data:e};return s&&(c.timestamp=new Date().toISOString()),i&&(c.prefix=i),u&&Object.keys(u).length>0&&(c.metadata=u),c}async sendRequest(e,r,n,s,i){let u=new AbortController,c=setTimeout(()=>u.abort(),i);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(s),signal:u.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,s,i,u){let c=null;for(let l=1;l<=u.maxAttempts;l++)try{return await this.sendRequest(e,r,n,s,i)}catch(d){if(c=d,l===u.maxAttempts)break;let h=u.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${u.maxAttempts}), retrying in ${h}ms...`,d.message),await this.delay(h)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let s=this.buildHeaders(),i=this.buildBody(e,r),u=await this.sendWithRetry(this.config.url,this.config.method,s,i,n,this.config.retry);return!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}});var hs,Fd,r0,_o,Pd=Be(()=>{"use strict";hs=require("fs"),Fd=require("path"),r0=require("os"),_o=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=(0,r0.tmpdir)();this.baseDir=(0,Fd.join)(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,hs.existsSync)(this.baseDir)||(0,hs.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",s;if(this.config.includeTimestamp){let i=Date.now();s=`${r}-${e}-${i}${n}`}else s=`${r}-${e}${n}`;return(0,Fd.join)(this.baseDir,s)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let s={...e,timestamp:Date.now(),sessionId:n},i=this.getFilePath(n);return(0,hs.writeFileSync)(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Id,ps,n0=Be(()=>{"use strict";Od();xd();Pd();Id=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),s=r.type+"_"+Date.now();this.registerHandler(s,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new go(e.config);case"webhook":return new yo(e.config);case"temp-file":return new _o(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,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([u,c])=>{try{await c.output(e,n)?s.success.push(u):s.failed.push(u)}catch(l){console.error(`[OutputManager] Handler ${u} failed:`,l),s.failed.push(u)}});return await Promise.all(i),s}async outputTo(e,r,n){let s={...this.defaultOptions,...n},i={success:[],failed:[]},u=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),i.failed.push(c);return}try{await l.output(r,s)?i.success.push(c):i.failed.push(c)}catch(d){console.error(`[OutputManager] Handler ${c} failed:`,d),i.failed.push(c)}});return await Promise.all(u),i}async outputToType(e,r,n){let s=Array.from(this.handlers.entries()).filter(([i,u])=>u.type===e).map(([i])=>i);return this.outputTo(s,r,n)}},ps=new Id});var dT={};vu(dT,{ConfigService:()=>nn,ProviderService:()=>an,SSEParserTransform:()=>_r,SSESerializerTransform:()=>on,TokenizerService:()=>Cn,TransformerService:()=>bn,calculateTokenCount:()=>Sd,default:()=>lT,getModelUsage:()=>Bn,pluginManager:()=>Td,recordModelUsage:()=>Zo,rewriteStream:()=>vs,router:()=>Za,searchProjectBySession:()=>kd,sessionUsageCache:()=>uh,tokenSpeedPlugin:()=>Bd});module.exports=V_(dT);var i0=je(require("fastify"),1),a0=je(require("@fastify/cors"),1);var ks=require("fs"),Mu=require("path"),Qf=require("dotenv"),Zf=je(ju(),1),nn=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,Mu.join)(process.cwd(),this.options.jsonPath);if((0,ks.existsSync)(e))try{let r=(0,ks.readFileSync)(e,"utf-8"),n=Zf.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,Mu.join)(process.cwd(),this.options.envPath);if((0,ks.existsSync)(e))try{let r=(0,Qf.config)({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")||process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy}has(e){return this.config[e]!==void 0}set(e,r){this.config[e]=r}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 Xe(t,e=500,r="internal_error",n="api_error"){let s=new Error(t);return s.statusCode=e,s.code=r,s.type=n,s}async function eh(t,e,r){e.log.error(t);let n=t.statusCode||500,s={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(s)}var th=require("undici");function rh(t,e,r,n,s){let i=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([d,h])=>{h&&i.set(d,h)});let u,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let d=new AbortController,h=()=>d.abort();r.signal.addEventListener("abort",h),c.addEventListener("abort",h),u=d.signal}else u=c;let l={method:"POST",headers:i,body:JSON.stringify(e),signal:u};return r.httpsProxy&&(l.dispatcher=new th.ProxyAgent(new URL(r.httpsProxy).toString())),s?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(i.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var Nn=require("fs"),nh=require("path"),sh=require("@thxp/shared"),Lu=(0,nh.join)(sh.HOME_DIR,"daily_usage.json"),sn=null;function nb(){let t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function oh(){let t=nb();if(sn&&sn.date===t)return sn;try{if((0,Nn.existsSync)(Lu)){let e=JSON.parse((0,Nn.readFileSync)(Lu,"utf-8"));if(e?.date===t)return sn=e,e}}catch{}return sn={date:t,models:{}},ih(sn),sn}function ih(t){try{(0,Nn.writeFileSync)(Lu,JSON.stringify(t,null,2),"utf-8")}catch{}}function Zo(t,e,r){let n=oh(),s=`${t.toLowerCase()},${e.toLowerCase()}`;n.models[s]=(n.models[s]||0)+r,ih(n)}function Bn(t,e){return oh().models[`${t.toLowerCase()},${e.toLowerCase()}`]||0}var ah="3.2.21";var ei=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}has(e){return this.cache.has(e)}del(e){return this.cache.delete(e)}clear(){this.cache.clear()}values(){return Array.from(this.cache.values())}},uh=new ei(100),ob=300*1e3,Uu=new ei(1e3),ch=t=>{Uu.put(t,Date.now())},Ds=t=>{let e=Uu.get(t);return e===void 0?!1:Date.now()-e>ob?(Uu.del(t),!1):!0};var Ts=(t,e)=>`${t},${e}`;var _r=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
73
73
  `);this.buffer=n.pop()||"";for(let s of n){let i=this.processLine(s);i&&r.enqueue(i)}},flush:e=>{if(this.buffer.trim()){let r=[];this.processLine(this.buffer.trim(),r),r.forEach(n=>e.enqueue(n))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,r){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let n={...this.currentEvent};return this.currentEvent={},r?(r.push(n),null):n}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let n=e.slice(5).trim();if(n==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(n)}catch{this.currentEvent.data={raw:n,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var on=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
74
74
  `),e.id&&(n+=`id: ${e.id}
75
75
  `),e.retry&&(n+=`retry: ${e.retry}