@thxp/llms 3.2.26 → 3.2.27

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=Me(()=>{"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=Me(()=>{"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=Me(()=>{"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=Le(require("fastify"),1),a0=Le(require("@fastify/cors"),1);var ks=require("fs"),Mu=require("path"),Qf=require("dotenv"),Zf=Le(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.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),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 Qe(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.26";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=Me(()=>{"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=Me(()=>{"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=Me(()=>{"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=Le(require("fastify"),1),a0=Le(require("@fastify/cors"),1);var ks=require("fs"),Mu=require("path"),Qf=require("dotenv"),Zf=Le(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.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),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 Qe(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.27";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}
@@ -144,7 +144,7 @@ data: ${JSON.stringify(xe)}
144
144
  `))}catch(fe){console.error(fe)}}}}}if(ie?.finish_reason&&!m&&!p){if(!U&&G.length>0&&(q(G),G=""),y===0&&_===0&&console.error("Warning: No content in the stream response!"),A>=0){let de={type:"content_block_stop",index:A};x(i.encode(`event: content_block_stop
145
145
  data: ${JSON.stringify(de)}
146
146
 
147
- `)),A=-1}if(!m){let me={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[ie.finish_reason]||"end_turn";c?c.delta={stop_reason:me,stop_sequence:null}:c={type:"message_delta",delta:{stop_reason:me,stop_sequence:null},usage:{input_tokens:Math.max(0,(K.usage?.prompt_tokens||0)-(K.usage?.prompt_tokens_details?.cached_tokens||0)),output_tokens:K.usage?.completion_tokens||0,cache_read_input_tokens:K.usage?.prompt_tokens_details?.cached_tokens||0}}}break}}catch(K){this.logger?.error(`parseError: ${K.name} message: ${K.message} stack: ${K.stack} data: ${V}`)}}}!U&&G.length>0&&(q(G),G=""),oe()}catch(Y){if(!m)try{s.error(Y)}catch(Q){console.error(Q)}}finally{if(re)try{re.releaseLock()}catch(Y){console.error(Y)}}},cancel:s=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${s}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let s=[];if(n.message.annotations){let u=`srvtoolu_${Vt()}`;s.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),s.push({type:"web_search_tool_result",tool_use_id:u,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&s.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(u=>{let c={};try{let l=u.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:u.function.arguments||""}}s.push({type:"tool_use",id:u.id,name:u.function.name,input:c})}),n.message?.thinking?.content&&s.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let i={id:e.id,type:"message",role:"assistant",model:e.model,content:s,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw Qe(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var jn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function gb(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(jn).includes(n)?n:jn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(jn).includes(s)?s:jn.TYPE_UNSPECIFIED})}}}function Rs(t){let e={},r=["items"],n=["anyOf"],s=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let i=t.anyOf;i!=null&&Array.isArray(i)&&i.length==2&&(i[0]&&i[0].type==="null"?(e.nullable=!0,t=i[1]):i[1]&&i[1].type==="null"&&(e.nullable=!0,t=i[0])),t.type&&Array.isArray(t.type)&&gb(t.type,e);for(let[u,c]of Object.entries(t))if(c!=null)if(u=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(jn).includes(l)?l:jn.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=Rs(c);else if(n.includes(u)){let l=[];for(let d of c){if(d.type=="null"){e.nullable=!0;continue}l.push(Rs(d))}e[u]=l}else if(s.includes(u)){let l={};for(let[d,h]of Object.entries(c))l[d]=Rs(h);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function yb(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Rs(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Rs(e.response));return t}function si(t){let e=[],r=t.tools?.filter(d=>d.function.name!=="web_search"&&d.function.name!=="WebSearch")?.map(d=>({name:d.function.name,description:d.function.description,parametersJsonSchema:d.function.parameters}));r?.length&&e.push(yb({functionDeclarations:r}));let n=t.tools?.find(d=>d.function.name==="web_search"||d.function.name==="WebSearch"),s=t.tool_choice==="required"||typeof t.tool_choice=="object";n&&!s&&e.push({googleSearch:{}});let i=[],u=t.messages.filter(d=>d.role==="tool");t.messages.filter(d=>d.role!=="tool").forEach(d=>{let h;d.role==="assistant"?h="model":(["user","system"].includes(d.role),h="user");let p=[];if(typeof d.content=="string"){let g={text:d.content};d?.thinking?.signature&&(g.thoughtSignature=d.thinking.signature),p.push(g)}else Array.isArray(d.content)?p.push(...d.content.map(g=>{if(g.type==="text")return{text:g.text||""};if(g.type==="image_url")return g.image_url.url.startsWith("http")?{file_data:{mime_type:g.media_type,file_uri:g.image_url.url}}:{inlineData:{mime_type:g.media_type,data:g.image_url.url?.split(",")?.pop()||g.image_url.url}}})):d.content&&typeof d.content=="object"&&(d.content.text?p.push({text:d.content.text}):p.push({text:JSON.stringify(d.content)}));if(Array.isArray(d.tool_calls)&&p.push(...d.tool_calls.map((g,k)=>({functionCall:{id:g.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:g.function.name,args:JSON.parse(g.function.arguments||"{}")},thoughtSignature:k===0&&d.thinking?.signature?d.thinking?.signature:void 0}))),p.length===0&&p.push({text:""}),i.push({role:h,parts:p}),h==="model"&&d.tool_calls){let g=d.tool_calls.map(k=>{let E=u.find(y=>y.tool_call_id===k.id);return{functionResponse:{name:k?.function?.name,response:{result:E?.content}}}});i.push({role:"user",parts:g})}});let c={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(c.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))c.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let d=t.model.includes("pro")?[128,32768]:[0,24576],h,p=t.reasoning.max_tokens;typeof p<"u"&&(p>=d[0]&&p<=d[1]?h=p:p<d[0]?h=d[0]:p>d[1]&&(h=d[1]),c.thinkingConfig.thinkingBudget=h)}let l={contents:i,tools:e.length?e:void 0,generationConfig:c};if(t.tool_choice){let d={functionCallingConfig:{}};t.tool_choice==="auto"?d.functionCallingConfig.mode="auto":t.tool_choice==="none"?d.functionCallingConfig.mode="none":t.tool_choice==="required"?d.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(d.functionCallingConfig.mode="any",d.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),l.toolConfig=d}return l}function oi(t){let e=t.contents,r=t.tools,n=t.model,s=t.max_tokens,i=t.temperature,u=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:s,temperature:i,stream:u,tool_choice:c};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?l.messages.push({role:"user",content:d}):typeof d.text=="string"?l.messages.push({role:"user",content:d.text||null}):d.role==="user"?l.messages.push({role:"user",content:d?.parts?.map(h=>({type:"text",text:h.text||""}))||[]}):d.role==="model"&&l.messages.push({role:"assistant",content:d?.parts?.map(h=>({type:"text",text:h.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(d=>{Array.isArray(d.functionDeclarations)&&d.functionDeclarations.forEach(h=>{l.tools.push({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})})})),l}async function ii(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let s=n.candidates?.[0],i=s?.groundingMetadata?.groundingChunks?.length?s.groundingMetadata.groundingChunks.map((k,E)=>{let y=s?.groundingMetadata?.groundingSupports?.filter(_=>_.groundingChunkIndices?.includes(E));return{type:"url_citation",url_citation:{url:k?.web?.uri||"",title:k?.web?.title||"",content:y?.[0]?.segment?.text||"",start_index:y?.[0]?.segment?.startIndex||0,end_index:y?.[0]?.segment?.endIndex||0}}}):void 0,u="",c="",l=s?.content?.parts||[],d=[];for(let k of l)k.text&&k.thought===!0?u+=k.text:d.push(k);c=l.find(k=>k.thoughtSignature)?.thoughtSignature;let h=d?.filter(k=>k.functionCall)?.map(k=>({id:k.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:k.functionCall?.name,arguments:JSON.stringify(k.functionCall?.args||{})}}))||[],p=d?.filter(k=>k.text)?.map(k=>k.text)?.join(`
147
+ `)),A=-1}if(!m){let me={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[ie.finish_reason]||"end_turn";c?c.delta={stop_reason:me,stop_sequence:null}:c={type:"message_delta",delta:{stop_reason:me,stop_sequence:null},usage:{input_tokens:Math.max(0,(K.usage?.prompt_tokens||0)-(K.usage?.prompt_tokens_details?.cached_tokens||0)),output_tokens:K.usage?.completion_tokens||0,cache_read_input_tokens:K.usage?.prompt_tokens_details?.cached_tokens||0}}}break}}catch(K){this.logger?.error(`parseError: ${K.name} message: ${K.message} stack: ${K.stack} data: ${V}`)}}}!U&&G.length>0&&(q(G),G=""),oe()}catch(Y){if(!m)try{s.error(Y)}catch(Q){console.error(Q)}}finally{if(re)try{re.releaseLock()}catch(Y){console.error(Y)}}},cancel:s=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${s}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let s=[];if(n.message.annotations){let u=`srvtoolu_${Vt()}`;s.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),s.push({type:"web_search_tool_result",tool_use_id:u,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}if(n.message.content){let u=n.message.content;u=u.replace(/<\|tool_calls_section_begin\|>[\s\S]*?<\|tool_calls_section_end\|>/g,""),u=u.replace(/<\|tool_call_begin\|>[\s\S]*?<\|tool_call_end\|>/g,""),u=u.replace(/<\|tool_calls_section_begin\|>|<\|tool_call_begin\|>|<\|tool_calls_section_end\|>|<\|tool_call_end\|>/g,""),s.push({type:"text",text:u})}n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(u=>{let c={};try{let l=u.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:u.function.arguments||""}}s.push({type:"tool_use",id:u.id,name:u.function.name,input:c})}),n.message?.thinking?.content&&s.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let i={id:e.id,type:"message",role:"assistant",model:e.model,content:s,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw Qe(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var jn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function gb(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(jn).includes(n)?n:jn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(jn).includes(s)?s:jn.TYPE_UNSPECIFIED})}}}function Rs(t){let e={},r=["items"],n=["anyOf"],s=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let i=t.anyOf;i!=null&&Array.isArray(i)&&i.length==2&&(i[0]&&i[0].type==="null"?(e.nullable=!0,t=i[1]):i[1]&&i[1].type==="null"&&(e.nullable=!0,t=i[0])),t.type&&Array.isArray(t.type)&&gb(t.type,e);for(let[u,c]of Object.entries(t))if(c!=null)if(u=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(jn).includes(l)?l:jn.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=Rs(c);else if(n.includes(u)){let l=[];for(let d of c){if(d.type=="null"){e.nullable=!0;continue}l.push(Rs(d))}e[u]=l}else if(s.includes(u)){let l={};for(let[d,h]of Object.entries(c))l[d]=Rs(h);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function yb(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Rs(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Rs(e.response));return t}function si(t){let e=[],r=t.tools?.filter(d=>d.function.name!=="web_search"&&d.function.name!=="WebSearch")?.map(d=>({name:d.function.name,description:d.function.description,parametersJsonSchema:d.function.parameters}));r?.length&&e.push(yb({functionDeclarations:r}));let n=t.tools?.find(d=>d.function.name==="web_search"||d.function.name==="WebSearch"),s=t.tool_choice==="required"||typeof t.tool_choice=="object";n&&!s&&e.push({googleSearch:{}});let i=[],u=t.messages.filter(d=>d.role==="tool");t.messages.filter(d=>d.role!=="tool").forEach(d=>{let h;d.role==="assistant"?h="model":(["user","system"].includes(d.role),h="user");let p=[];if(typeof d.content=="string"){let g={text:d.content};d?.thinking?.signature&&(g.thoughtSignature=d.thinking.signature),p.push(g)}else Array.isArray(d.content)?p.push(...d.content.map(g=>{if(g.type==="text")return{text:g.text||""};if(g.type==="image_url")return g.image_url.url.startsWith("http")?{file_data:{mime_type:g.media_type,file_uri:g.image_url.url}}:{inlineData:{mime_type:g.media_type,data:g.image_url.url?.split(",")?.pop()||g.image_url.url}}})):d.content&&typeof d.content=="object"&&(d.content.text?p.push({text:d.content.text}):p.push({text:JSON.stringify(d.content)}));if(Array.isArray(d.tool_calls)&&p.push(...d.tool_calls.map((g,k)=>({functionCall:{id:g.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:g.function.name,args:JSON.parse(g.function.arguments||"{}")},thoughtSignature:k===0&&d.thinking?.signature?d.thinking?.signature:void 0}))),p.length===0&&p.push({text:""}),i.push({role:h,parts:p}),h==="model"&&d.tool_calls){let g=d.tool_calls.map(k=>{let E=u.find(y=>y.tool_call_id===k.id);return{functionResponse:{name:k?.function?.name,response:{result:E?.content}}}});i.push({role:"user",parts:g})}});let c={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(c.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))c.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let d=t.model.includes("pro")?[128,32768]:[0,24576],h,p=t.reasoning.max_tokens;typeof p<"u"&&(p>=d[0]&&p<=d[1]?h=p:p<d[0]?h=d[0]:p>d[1]&&(h=d[1]),c.thinkingConfig.thinkingBudget=h)}let l={contents:i,tools:e.length?e:void 0,generationConfig:c};if(t.tool_choice){let d={functionCallingConfig:{}};t.tool_choice==="auto"?d.functionCallingConfig.mode="auto":t.tool_choice==="none"?d.functionCallingConfig.mode="none":t.tool_choice==="required"?d.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(d.functionCallingConfig.mode="any",d.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),l.toolConfig=d}return l}function oi(t){let e=t.contents,r=t.tools,n=t.model,s=t.max_tokens,i=t.temperature,u=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:s,temperature:i,stream:u,tool_choice:c};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?l.messages.push({role:"user",content:d}):typeof d.text=="string"?l.messages.push({role:"user",content:d.text||null}):d.role==="user"?l.messages.push({role:"user",content:d?.parts?.map(h=>({type:"text",text:h.text||""}))||[]}):d.role==="model"&&l.messages.push({role:"assistant",content:d?.parts?.map(h=>({type:"text",text:h.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(d=>{Array.isArray(d.functionDeclarations)&&d.functionDeclarations.forEach(h=>{l.tools.push({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})})})),l}async function ii(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let s=n.candidates?.[0],i=s?.groundingMetadata?.groundingChunks?.length?s.groundingMetadata.groundingChunks.map((k,E)=>{let y=s?.groundingMetadata?.groundingSupports?.filter(_=>_.groundingChunkIndices?.includes(E));return{type:"url_citation",url_citation:{url:k?.web?.uri||"",title:k?.web?.title||"",content:y?.[0]?.segment?.text||"",start_index:y?.[0]?.segment?.startIndex||0,end_index:y?.[0]?.segment?.endIndex||0}}}):void 0,u="",c="",l=s?.content?.parts||[],d=[];for(let k of l)k.text&&k.thought===!0?u+=k.text:d.push(k);c=l.find(k=>k.thoughtSignature)?.thoughtSignature;let h=d?.filter(k=>k.functionCall)?.map(k=>({id:k.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:k.functionCall?.name,arguments:JSON.stringify(k.functionCall?.args||{})}}))||[],p=d?.filter(k=>k.text)?.map(k=>k.text)?.join(`
148
148
  `)||"",g={id:n.responseId,choices:[{finish_reason:h.length>0?"tool_calls":s?.finishReason?.toLowerCase()||null,index:0,message:{content:p,role:"assistant",tool_calls:h.length>0?h:void 0,...i&&{annotations:i},...c&&{thinking:{content:u||"(no content)",signature:c}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(g),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=!1,u=!1,c=!1,l="",d=0,h=-1,p=new ReadableStream({async start(g){let k=async(_,m)=>{if(_.startsWith("data: ")){let D=_.slice(6).trim();if(D){r?.debug({chunkStr:D},`${e} chunk:`);try{let b=JSON.parse(D);if(!b.candidates||!b.candidates[0]){if(b.usageMetadata){let q={choices:[],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};m.enqueue(s.encode(`data: ${JSON.stringify(q)}
149
149
 
150
150
  `))}else r?.debug({chunkStr:D},"Invalid chunk structure");return}let A=b.candidates[0],v=A.content?.parts||[];v.filter(q=>q.text&&q.thought===!0).forEach(q=>{c||(c=!0);let oe={choices:[{delta:{role:"assistant",content:null,thinking:{content:q.text}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(oe)}