@wengine-ai/llms 2.3.238 → 2.3.2391

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.
@@ -1,331 +1,331 @@
1
- "use strict";var Xa=Object.create;var Xt=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var qa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,ec=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var Yt=(n,e)=>{for(var t in e)Xt(n,t,{get:e[t],enumerable:!0})},Hr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qa(e))!ec.call(n,r)&&r!==t&&Xt(n,r,{get:()=>e[r],enumerable:!(o=Ya(e,r))||o.enumerable});return n};var Y=(n,e,t)=>(t=n!=null?Xa(Za(n)):{},Hr(e||!n||!n.__esModule?Xt(t,"default",{value:n,enumerable:!0}):t,n)),Jr=n=>Hr(Xt({},"__esModule",{value:!0}),n);function nc(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(tc.test(e))return{ok:!0};try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:`Unsupported proxy protocol: ${t.protocol}. Only http:// and https:// are allowed.`}:{ok:!0}}catch{return{ok:!1,error:`Invalid proxy URL: ${e}`}}}function Gr(n){let e=[];for(let t of Wr){let o=n[t];if(o==null)continue;let r=nc(o);r.ok||e.push({key:t,error:r.error})}return e}function ct(n){for(let e of Wr){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function go(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=ct(n);if(t)return go(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function K(n){let e=oc(n),t=qt.get(e);if(t)return t;let o=new Br.ProxyAgent(e);return qt.set(e,o),o}async function Zt(){let n=Array.from(qt.values());qt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function oc(n){let e=n.trim();if(!e)throw new TypeError("Proxy URL must not be empty");let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new TypeError(`Unsupported proxy protocol: ${t.protocol}`);return t.toString()}var Br,Wr,tc,qt,ae=P(()=>{"use strict";Br=require("undici"),Wr=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],tc=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;qt=new Map});var lt,ho,Vr,Qr,Se,yo=P(()=>{"use strict";lt=require("fs"),ho=require("path"),Vr=require("dotenv"),Qr=Y(require("json5"),1);ae();Se=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,ho.join)(process.cwd(),this.options.jsonPath);if((0,lt.existsSync)(e))try{let t=(0,lt.readFileSync)(e,"utf-8"),o=Qr.default.parse(t);this.config={...this.config,...o},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,ho.join)(process.cwd(),this.options.envPath);if((0,lt.existsSync)(e))try{let t=(0,Vr.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 o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return ct(this)}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 V(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Kr(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var en=P(()=>{"use strict"});function tn(n){_o=n}function ut(){return _o}function nn(n){return _o||n.get("DEBUG_LOG")===!0}function qr(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Ue:{maxBodyLength:e.maxBodyLength??Ue.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Ue.maxStreamChunks}}function on(n){let e={};for(let[t,o]of Object.entries(n))rc.has(t.toLowerCase())?e[t]="***MASKED***":e[t]=o;return e}function rn(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Zr(n,e,t){let o=typeof t.body=="string"?t.body:JSON.stringify(t.body);n.info({debug_log:!0,reqId:e,phase:"provider_request",url:t.url,headers:on(t.headers),body:rn(o,Ue.maxBodyLength)})}function es(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:on(t.headers),...t.body!==void 0?{body:rn(t.body,Ue.maxBodyLength)}:{}})}function Xr(n,e,t,o){let r=sc(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:rn(o,Ue.maxBodyLength)})}function sc(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:rn(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Yr(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function ts(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:l,value:c}=await r.read();if(l)break;a+=c;let i=a.split(`
1
+ "use strict";var Pa=Object.create;var Wt=Object.defineProperty;var Ea=Object.getOwnPropertyDescriptor;var Oa=Object.getOwnPropertyNames;var Aa=Object.getPrototypeOf,Ia=Object.prototype.hasOwnProperty;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var Gt=(n,e)=>{for(var t in e)Wt(n,t,{get:e[t],enumerable:!0})},Mr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Oa(e))!Ia.call(n,r)&&r!==t&&Wt(n,r,{get:()=>e[r],enumerable:!(o=Ea(e,r))||o.enumerable});return n};var Y=(n,e,t)=>(t=n!=null?Pa(Aa(n)):{},Mr(e||!n||!n.__esModule?Wt(t,"default",{value:n,enumerable:!0}):t,n)),$r=n=>Mr(Wt({},"__esModule",{value:!0}),n);function $a(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Ma.test(e))return{ok:!0};try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:`Unsupported proxy protocol: ${t.protocol}. Only http:// and https:// are allowed.`}:{ok:!0}}catch{return{ok:!1,error:`Invalid proxy URL: ${e}`}}}function Dr(n){let e=[];for(let t of Lr){let o=n[t];if(o==null)continue;let r=$a(o);r.ok||e.push({key:t,error:r.error})}return e}function st(n){for(let e of Lr){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function ao(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function le(n,e){let t=st(n);if(t)return ao(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function Q(n){let e=Na(n),t=Kt.get(e);if(t)return t;let o=new Nr.ProxyAgent(e);return Kt.set(e,o),o}async function Qt(){let n=Array.from(Kt.values());Kt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function Na(n){let e=n.trim();if(!e)throw new TypeError("Proxy URL must not be empty");let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new TypeError(`Unsupported proxy protocol: ${t.protocol}`);return t.toString()}var Nr,Lr,Ma,Kt,se=w(()=>{"use strict";Nr=require("undici"),Lr=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Ma=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Kt=new Map});var it,co,Fr,Ur,ve,lo=w(()=>{"use strict";it=require("fs"),co=require("path"),Fr=require("dotenv"),Ur=Y(require("json5"),1);se();ve=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,co.join)(process.cwd(),this.options.jsonPath);if((0,it.existsSync)(e))try{let t=(0,it.readFileSync)(e,"utf-8"),o=Ur.default.parse(t);this.config={...this.config,...o},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,co.join)(process.cwd(),this.options.envPath);if((0,it.existsSync)(e))try{let t=(0,Fr.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 o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return st(this)}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 G(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function jr(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var Vt=w(()=>{"use strict"});function Yt(n){uo=n}function at(){return uo}function Xt(n){return uo||n.get("DEBUG_LOG")===!0}function Br(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function qt(n){let e={};for(let[t,o]of Object.entries(n))La.has(t.toLowerCase())?e[t]="***MASKED***":e[t]=o;return e}function Zt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Jr(n,e,t){let o=typeof t.body=="string"?t.body:JSON.stringify(t.body);n.info({debug_log:!0,reqId:e,phase:"provider_request",url:t.url,headers:qt(t.headers),body:Zt(o,Le.maxBodyLength)})}function Wr(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:qt(t.headers),...t.body!==void 0?{body:Zt(t.body,Le.maxBodyLength)}:{}})}function Hr(n,e,t,o){let r=Da(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Zt(o,Le.maxBodyLength)})}function Da(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Zt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function zr(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Gr(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let i="";for(;;){let{done:l,value:a}=await r.read();if(l)break;i+=a;let c=i.split(`
2
2
 
3
- `);a=i.pop()||"";for(let u of i)u.trim()&&(s<o.maxStreamChunks?Xr(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Xr(e,t,s,a.trim()),s++),Yr(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Yr(e,t,s)}finally{r.releaseLock()}})()}var rc,Ue,_o,dt=P(()=>{"use strict";rc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Ue={maxBodyLength:4096,maxStreamChunks:100},_o=!1});function ns(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([i,u])=>{u&&s.set(i,u)});let a,l=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let i=new AbortController,u=()=>i.abort();t.signal.addEventListener("abort",u),l.addEventListener("abort",u),a=i.signal}else a=l;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return t.httpsProxy&&(c.dispatcher=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:on(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:ic(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function ic(n){if(!(typeof n!="string"||!n.trim()))try{let e=new URL(n);return e.username||e.password?(e.username="",e.password="",`${e.toString()} (credentials redacted)`):e.toString()}catch{return"[invalid proxy URL]"}}var os=P(()=>{ae();dt()});var sn,ko=P(()=>{sn="2.3.238"});var rs={};Yt(rs,{getFallbackPromotionStore:()=>De,resetFallbackPromotionStore:()=>lc});function De(n){return Pe||(Pe=new bo,n&&Pe.configure(n)),Pe}function lc(){Pe&&(Pe.clearAll(),Pe=null)}var cc,bo,Pe,an=P(()=>{"use strict";ce();cc=600*1e3,bo=class{promotions=new Map;enabled=!0;ttlMs=cc;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let l=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(l,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...i]=a.promotedModel.split(","),u=i.join(",");if(!D().isAvailable(c,u))return this.promotions.delete(s),null;let m=r.find(y=>y.name.toLowerCase()===c.toLowerCase()),g=m?.models?.find(y=>String(y).toLowerCase()===u.toLowerCase());return!m||!g||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${g}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},Pe=null});function fc(n){try{if(!(0,ge.existsSync)(To))return;let e=JSON.parse((0,ge.readFileSync)(To,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function is(n){try{let e=n.getAllStates();if(e.length===0)return;(0,ge.existsSync)(Co)||(0,ge.mkdirSync)(Co,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,ge.writeFileSync)(To,JSON.stringify(t,null,2),"utf-8")}catch{}}function cn(){if(ss)return;ss=!0;let n=D();fc(n),pc=setInterval(()=>is(n),6e4),process.on("exit",()=>is(n))}function D(n){return xo||(xo=new pt(n)),xo}var ge,vo,as,uc,dc,pt,Co,To,ss,pc,xo,ce=P(()=>{"use strict";ge=require("fs"),vo=require("path"),as=require("@wengine-ai/claude-code-router-shared"),uc=120,dc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},pt=class{states=new Map;config;probeTimer;constructor(e){this.config={...dc,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.successCount++,!r.rateLimitUntil&&(r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0)))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(an(),Jr(rs));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let r=this.getState(e,t);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;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,o]of this.states)o.status==="open"&&e.push(t);return e}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let l=(o??uc)*1e3;a.rateLimitUntil=Date.now()+l}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Co=(0,vo.join)(as.HOME_DIR,"runtime"),To=(0,vo.join)(Co,"provider-health.json"),ss=!1,pc=null;xo=null});function ft(n,e,t){let o=l=>{if(t instanceof Headers)return t.get(l);let c=Object.keys(t).find(i=>i.toLowerCase()===l);return c?t[c]:null},r=Ro(o,mc),s=Ro(o,gc),a=Ro(o,hc);(r||s||a)&&je.set(n,{provider:n,remaining:us(r),limit:us(s),reset:yc(a),capturedAt:Date.now()})}function fs(n){return je.get(n)}function ln(){return Array.from(je.values())}function Ro(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function us(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function yc(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):t>1e9?Math.floor(t):Math.floor(Date.now()/1e3+t);let o=Date.parse(e);if(Number.isFinite(o))return Math.floor(o/1e3);let r=_c(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function _c(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function kc(){try{if(!(0,he.existsSync)(So))return;let n=JSON.parse((0,he.readFileSync)(So,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;je.set(t.provider,t)}}catch{}}function ds(){try{if(je.size===0)return;(0,he.existsSync)(wo)||(0,he.mkdirSync)(wo,{recursive:!0}),(0,he.writeFileSync)(So,JSON.stringify(Array.from(je.values()),null,2),"utf-8")}catch{}}function ze(){cs||(cs=!0,kc(),ls=setInterval(ds,6e4),ls.unref?.(),process.on("exit",ds))}var he,Po,ps,wo,So,je,cs,ls,mc,gc,hc,He=P(()=>{"use strict";he=require("fs"),Po=require("path"),ps=require("@wengine-ai/claude-code-router-shared"),wo=(0,Po.join)(ps.HOME_DIR,"runtime"),So=(0,Po.join)(wo,"rate-limit.json"),je=new Map,cs=!1,ls=null,mc=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],gc=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],hc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var Je,Ao=P(()=>{"use strict";Je=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let t=e.headers.get("Content-Type")||"";if(t.includes("application/json")){let o=await e.json();if(o.object==="response"&&o.output){let r=this.convertResponseToChat(o);return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return o.type==="message"&&Array.isArray(o.content)?new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let[o,r]=e.body.tee(),s=o.getReader(),a="";try{let{value:f,done:_}=await s.read();!_&&f&&(a=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let f=this.prependToStream(a,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let f=this.prependToStream(a,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let i=this.prependToStream(a,r),u=new TextDecoder,d=new TextEncoder,m="",g=!1,y=this,p=new ReadableStream({async start(f){let _=i.getReader(),k=-1,h="",b=x=>(x!==h&&(k++,h=x),k);try{for(;;){let{done:x,value:v}=await _.read();if(x){g||f.enqueue(d.encode(`data: [DONE]
3
+ `);i=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Hr(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}i.trim()&&(s<o.maxStreamChunks&&Hr(e,t,s,i.trim()),s++),zr(e,t,s)}catch(i){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,i),zr(e,t,s)}finally{r.releaseLock()}})()}var La,Le,uo,ct=w(()=>{"use strict";La=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Le={maxBodyLength:4096,maxStreamChunks:100},uo=!1});function Kr(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([c,u])=>{u&&s.set(c,u)});let i,l=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),l.addEventListener("abort",u),i=c.signal}else i=l;let a={method:"POST",headers:s,body:JSON.stringify(e),signal:i};return t.httpsProxy&&(a.dispatcher=Q(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:qt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Fa(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),a)}function Fa(n){if(!(typeof n!="string"||!n.trim()))try{let e=new URL(n);return e.username||e.password?(e.username="",e.password="",`${e.toString()} (credentials redacted)`):e.toString()}catch{return"[invalid proxy URL]"}}var Qr=w(()=>{se();ct()});var en,po=w(()=>{en="2.3.239"});var Vr={};Gt(Vr,{getFallbackPromotionStore:()=>De,resetFallbackPromotionStore:()=>Ha});function De(n){return xe||(xe=new fo,n&&xe.configure(n)),xe}function Ha(){xe&&(xe.clearAll(),xe=null)}var ja,fo,xe,tn=w(()=>{"use strict";ie();ja=600*1e3,fo=class{promotions=new Map;enabled=!0;ttlMs=ja;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,i){if(!this.enabled)return;let l=this.getKey(e,t,o),a=`${r},${s}`;this.promotions.set(l,{promotedModel:a,timestamp:Date.now(),ttlMs:i??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),i=this.promotions.get(s);if(!i)return null;if(Date.now()-i.timestamp>=i.ttlMs)return this.promotions.delete(s),null;let[a,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(a,u))return this.promotions.delete(s),null;let g=r.find(y=>y.name.toLowerCase()===a.toLowerCase()),m=g?.models?.find(y=>String(y).toLowerCase()===u.toLowerCase());return!g||!m||g.enabled===!1?(this.promotions.delete(s),null):`${g.name},${m}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});function Wa(n){try{if(!(0,pe.existsSync)(ho))return;let e=JSON.parse((0,pe.readFileSync)(ho,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Xr(n){try{let e=n.getAllStates();if(e.length===0)return;(0,pe.existsSync)(go)||(0,pe.mkdirSync)(go,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,pe.writeFileSync)(ho,JSON.stringify(t,null,2),"utf-8")}catch{}}function nn(){if(Yr)return;Yr=!0;let n=U();Wa(n),Ja=setInterval(()=>Xr(n),6e4),process.on("exit",()=>Xr(n))}function U(n){return mo||(mo=new lt(n)),mo}var pe,yo,qr,za,Ba,lt,go,ho,Yr,Ja,mo,ie=w(()=>{"use strict";pe=require("fs"),yo=require("path"),qr=require("@wengine-ai/claude-code-router-shared"),za=120,Ba={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},lt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ba,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.successCount++,!r.rateLimitUntil&&(r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0)))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(tn(),$r(Vr));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let r=this.getState(e,t);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;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,o]of this.states)o.status==="open"&&e.push(t);return e}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let i=this.states.get(s);i?(i.status="open",i.lastFailureTime=Date.now(),i.lastError=r||"rate-limited",i.lastProbeTime=0):(i={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,i));let l=(o??za)*1e3;i.rateLimitUntil=Date.now()+l}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},go=(0,yo.join)(qr.HOME_DIR,"runtime"),ho=(0,yo.join)(go,"provider-health.json"),Yr=!1,Ja=null;mo=null});function ut(n,e,t){let o=l=>{if(t instanceof Headers)return t.get(l);let a=Object.keys(t).find(c=>c.toLowerCase()===l);return a?t[a]:null},r=_o(o,Ga),s=_o(o,Ka),i=_o(o,Qa);(r||s||i)&&Fe.set(n,{provider:n,remaining:ts(r),limit:ts(s),reset:Va(i),capturedAt:Date.now()})}function rs(n){return Fe.get(n)}function on(){return Array.from(Fe.values())}function _o(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ts(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Va(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):t>1e9?Math.floor(t):Math.floor(Date.now()/1e3+t);let o=Date.parse(e);if(Number.isFinite(o))return Math.floor(o/1e3);let r=Ya(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Ya(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),i=r[2].toLowerCase();if(Number.isFinite(s))switch(i){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function Xa(){try{if(!(0,fe.existsSync)(bo))return;let n=JSON.parse((0,fe.readFileSync)(bo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Fe.set(t.provider,t)}}catch{}}function ns(){try{if(Fe.size===0)return;(0,fe.existsSync)(ko)||(0,fe.mkdirSync)(ko,{recursive:!0}),(0,fe.writeFileSync)(bo,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function Ue(){Zr||(Zr=!0,Xa(),es=setInterval(ns,6e4),es.unref?.(),process.on("exit",ns))}var fe,To,os,ko,bo,Fe,Zr,es,Ga,Ka,Qa,je=w(()=>{"use strict";fe=require("fs"),To=require("path"),os=require("@wengine-ai/claude-code-router-shared"),ko=(0,To.join)(os.HOME_DIR,"runtime"),bo=(0,To.join)(ko,"rate-limit.json"),Fe=new Map,Zr=!1,es=null,Ga=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Ka=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Qa=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var He,Co=w(()=>{"use strict";He=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let i="";typeof s=="string"?i=s:s&&typeof s=="object"&&"text"in s&&(i=s.text),t.push({role:"system",content:i})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(i=>this.normalizeRequestContent(i,r.role)).filter(i=>i!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let t=e.headers.get("Content-Type")||"";if(t.includes("application/json")){let o=await e.json();if(o.object==="response"&&o.output){let r=this.convertResponseToChat(o);return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return o.type==="message"&&Array.isArray(o.content)?new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let[o,r]=e.body.tee(),s=o.getReader(),i="";try{let{value:f,done:_}=await s.read();!_&&f&&(i=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let c=this.prependToStream(i,r),u=new TextDecoder,d=new TextEncoder,g="",m=!1,y=this,p=new ReadableStream({async start(f){let _=c.getReader(),k=-1,h="",b=T=>(T!==h&&(k++,h=T),k);try{for(;;){let{done:T,value:x}=await _.read();if(T){m||f.enqueue(d.encode(`data: [DONE]
4
4
 
5
- `));break}let C=u.decode(v,{stream:!0});m+=C;let R=m.split(/\r?\n/);m=R.pop()||"";for(let T of R)if(T.trim())try{if(T.startsWith("event: "))continue;if(T.startsWith("data: ")){let O=T.slice(5).trim();if(O==="[DONE]"){g=!0,f.enqueue(d.encode(`data: [DONE]
5
+ `));break}let v=u.decode(x,{stream:!0});g+=v;let S=g.split(/\r?\n/);g=S.pop()||"";for(let C of S)if(C.trim())try{if(C.startsWith("event: "))continue;if(C.startsWith("data: ")){let P=C.slice(5).trim();if(P==="[DONE]"){m=!0,f.enqueue(d.encode(`data: [DONE]
6
6
 
7
- `));continue}try{let w=JSON.parse(O);if(w.type==="response.output_text.delta"){let E={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:b(w.type),delta:{content:w.delta||""},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
7
+ `));continue}try{let R=JSON.parse(P);if(R.type==="response.output_text.delta"){let A={id:R.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model,choices:[{index:b(R.type),delta:{content:R.delta||""},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
8
8
 
9
- `))}else if(w.type==="response.output_item.added"&&w.item?.type==="function_call"){let E={id:w.item.call_id||w.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex-",choices:[{index:b(w.type),delta:{role:"assistant",tool_calls:[{index:0,id:w.item.call_id||w.item.id,function:{name:w.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
9
+ `))}else if(R.type==="response.output_item.added"&&R.item?.type==="function_call"){let A={id:R.item.call_id||R.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model||"gpt-5-codex-",choices:[{index:b(R.type),delta:{role:"assistant",tool_calls:[{index:0,id:R.item.call_id||R.item.id,function:{name:R.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
10
10
 
11
- `))}else if(w.type==="response.output_item.added"&&w.item?.type==="message"){let E=[];(w.item.content||[]).forEach(I=>{I.type==="output_text"&&E.push({type:"text",text:I.text||""})});let A={role:"assistant"};if(E.length===1&&E[0].type==="text"?A.content=E[0].text:E.length>0&&(A.content=E),A.content){let I={id:w.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:b(w.type),delta:A,finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(I)}
11
+ `))}else if(R.type==="response.output_item.added"&&R.item?.type==="message"){let A=[];(R.item.content||[]).forEach(I=>{I.type==="output_text"&&A.push({type:"text",text:I.text||""})});let E={role:"assistant"};if(A.length===1&&A[0].type==="text"?E.content=A[0].text:A.length>0&&(E.content=A),E.content){let I={id:R.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model,choices:[{index:b(R.type),delta:E,finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(I)}
12
12
 
13
- `))}}else if(w.type==="response.output_text.annotation.added"){let E={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex",choices:[{index:b(w.type),delta:{annotations:[{type:"url_citation",url_citation:{url:w.annotation?.url||"",title:w.annotation?.title||"",content:"",start_index:w.annotation?.start_index||0,end_index:w.annotation?.end_index||0}}]},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
13
+ `))}}else if(R.type==="response.output_text.annotation.added"){let A={id:R.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model||"gpt-5-codex",choices:[{index:b(R.type),delta:{annotations:[{type:"url_citation",url_citation:{url:R.annotation?.url||"",title:R.annotation?.title||"",content:"",start_index:R.annotation?.start_index||0,end_index:R.annotation?.end_index||0}}]},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
14
14
 
15
- `))}else if(w.type==="response.function_call_arguments.delta"){let E={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex-",choices:[{index:b(w.type),delta:{tool_calls:[{index:0,function:{arguments:w.delta||""}}]},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
15
+ `))}else if(R.type==="response.function_call_arguments.delta"){let A={id:R.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model||"gpt-5-codex-",choices:[{index:b(R.type),delta:{tool_calls:[{index:0,function:{arguments:R.delta||""}}]},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
16
16
 
17
- `))}else if(w.type==="response.completed"){let E=w.response?.output?.some(I=>I.type==="function_call")?"tool_calls":"stop",A={id:w.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:E}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
17
+ `))}else if(R.type==="response.completed"){let A=R.response?.output?.some(I=>I.type==="function_call")?"tool_calls":"stop",E={id:R.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:A}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
18
18
 
19
- `)),g=!0}else if(w.type==="response.reasoning_summary_text.delta"){let E={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:b(w.type),delta:{thinking:{content:w.delta||""}},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
19
+ `)),m=!0}else if(R.type==="response.reasoning_summary_text.delta"){let A={id:R.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model,choices:[{index:b(R.type),delta:{thinking:{content:R.delta||""}},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
20
20
 
21
- `))}else if(w.type==="response.reasoning_summary_part.done"&&w.part){let E={id:w.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:w.response?.model,choices:[{index:k,delta:{thinking:{signature:w.item_id}},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(E)}
21
+ `))}else if(R.type==="response.reasoning_summary_part.done"&&R.part){let A={id:R.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:R.response?.model,choices:[{index:k,delta:{thinking:{signature:R.item_id}},finish_reason:null}]};f.enqueue(d.encode(`data: ${JSON.stringify(A)}
22
22
 
23
- `))}}catch{f.enqueue(d.encode(T+`
24
- `))}}else f.enqueue(d.encode(T+`
25
- `))}catch(O){console.error("Error processing line:",T,O),f.enqueue(d.encode(T+`
26
- `))}}m.trim()&&f.enqueue(d.encode(m+`
27
- `)),g||f.enqueue(d.encode(`data: [DONE]
23
+ `))}}catch{f.enqueue(d.encode(C+`
24
+ `))}}else f.enqueue(d.encode(C+`
25
+ `))}catch(P){console.error("Error processing line:",C,P),f.enqueue(d.encode(C+`
26
+ `))}}g.trim()&&f.enqueue(d.encode(g+`
27
+ `)),m||f.enqueue(d.encode(`data: [DONE]
28
28
 
29
- `))}catch(x){console.error("Stream error:",x),f.error(x)}finally{try{_.releaseLock()}catch(x){console.error("Error releasing reader lock:",x)}f.close()}}});return new Response(p,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),l="";try{let{value:m,done:g}=await a.read();!g&&m&&(l=new TextDecoder().decode(m))}finally{a.releaseLock()}r.cancel().catch(()=>{});let c=l.includes("message_start")||l.includes("content_block_start"),i=l.includes("chat.completion.chunk");if(l.includes("response.created")||l.includes("response.output_text.delta")||l.includes("response.in_progress")||l.includes("response.output_item.added"))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(i&&!c){let m=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(m,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let d=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,t){let r=new TextEncoder().encode(e),s=t.getReader(),a=!1;return new ReadableStream({async pull(l){a||(a=!0,l.enqueue(r));try{let{done:c,value:i}=await s.read();c?l.close():l.enqueue(i)}catch(c){l.error(c)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,l=0,c=!1,i=!1,u="",d=-1,m=[],g=(p,f)=>r.encode(`event: ${p}
29
+ `))}catch(T){console.error("Stream error:",T),f.error(T)}finally{try{_.releaseLock()}catch(T){console.error("Error releasing reader lock:",T)}f.close()}}});return new Response(p,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),i=r.getReader(),l="";try{let{value:g,done:m}=await i.read();!m&&g&&(l=new TextDecoder().decode(g))}finally{i.releaseLock()}r.cancel().catch(()=>{});let a=l.includes("message_start")||l.includes("content_block_start"),c=l.includes("chat.completion.chunk");if(l.includes("response.created")||l.includes("response.output_text.delta")||l.includes("response.in_progress")||l.includes("response.output_item.added"))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(c&&!a){let g=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(g,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let d=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,t){let r=new TextEncoder().encode(e),s=t.getReader(),i=!1;return new ReadableStream({async pull(l){i||(i=!0,l.enqueue(r));try{let{done:a,value:c}=await s.read();a?l.close():l.enqueue(c)}catch(a){l.error(a)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",i=`resp_${Date.now()}`,l=0,a=!1,c=!1,u="",d=-1,g=[],m=(p,f)=>r.encode(`event: ${p}
30
30
  data: ${JSON.stringify(f)}
31
31
 
32
- `),y=(p,f=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:p,model:s,output:f,usage:this.buildResponsesUsage()});return new ReadableStream({async start(p){try{let f=e.getReader(),_="",k=!1,h=b=>{if(!k){k=!0;for(let x of m)if(x.type==="function_call"){let v=m.indexOf(x);p.enqueue(g("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:x.call_id||x.id,output_index:v,arguments:x.arguments||""})),x.status="completed",p.enqueue(g("response.output_item.done",{type:"response.output_item.done",output_index:v,item:x}))}for(let x of m)if(x.type==="message"){let v=m.indexOf(x);x.status="completed",p.enqueue(g("response.output_item.done",{type:"response.output_item.done",output_index:v,item:x}))}p.enqueue(g("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:b?.model||s,output:m.slice(),usage:b?.usage?{...this.buildResponsesUsage(b.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:b,value:x}=await f.read();if(b)break;_+=o.decode(x,{stream:!0});let v=_.split(`
33
- `);_=v.pop()||"";for(let C of v){let R=C.trim();if(!R||R.startsWith("event:")||!R.startsWith("data:"))continue;let T=R.slice(5).trim();if(T==="[DONE]"){h({}),p.enqueue(r.encode(`data: [DONE]
32
+ `),y=(p,f=[])=>({id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:p,model:s,output:f,usage:this.buildResponsesUsage()});return new ReadableStream({async start(p){try{let f=e.getReader(),_="",k=!1,h=b=>{if(!k){k=!0;for(let T of g)if(T.type==="function_call"){let x=g.indexOf(T);p.enqueue(m("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:x,arguments:T.arguments||""})),T.status="completed",p.enqueue(m("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}for(let T of g)if(T.type==="message"){let x=g.indexOf(T);T.status="completed",p.enqueue(m("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}p.enqueue(m("response.completed",{type:"response.completed",response:{id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:b?.model||s,output:g.slice(),usage:b?.usage?{...this.buildResponsesUsage(b.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:b,value:T}=await f.read();if(b)break;_+=o.decode(T,{stream:!0});let x=_.split(`
33
+ `);_=x.pop()||"";for(let v of x){let S=v.trim();if(!S||S.startsWith("event:")||!S.startsWith("data:"))continue;let C=S.slice(5).trim();if(C==="[DONE]"){h({}),p.enqueue(r.encode(`data: [DONE]
34
34
 
35
- `));continue}let O;try{O=JSON.parse(T)}catch{continue}c||(c=!0,p.enqueue(g("response.created",{type:"response.created",response:y("in_progress")})),p.enqueue(g("response.in_progress",{type:"response.in_progress",response:y("in_progress")})));let w=O.choices?.[0];if(!w)continue;let E=w.delta;if(E?.content){if(!i){i=!0;let A=l++,I={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};m.push(I),p.enqueue(g("response.output_item.added",{type:"response.output_item.added",output_index:A,item:I}))}p.enqueue(g("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:l-1,content_index:0,delta:E.content}))}if(Array.isArray(E?.tool_calls))for(let A of E.tool_calls){if(A.id){u=A.id,d=l++;let I={id:A.id,type:"function_call",status:"in_progress",call_id:A.id,name:A.function?.name||"",arguments:""};m.push(I),p.enqueue(g("response.output_item.added",{type:"response.output_item.added",output_index:d,item:I}))}if(A.function?.arguments){p.enqueue(g("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:d,delta:A.function.arguments}));let I=m.find(L=>L.call_id===u);I&&(I.arguments+=A.function.arguments)}}w.finish_reason&&h(O)}}k||h({}),p.close()}catch(f){p.error(f)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,l="",c="",i=-1,u="",d="",m="",g=-1,y="",p="",f=-1,_=0,k=!1,h=!1,b=!1,x=!1,v=null,C=[],R=(I,L)=>r.encode(`event: ${I}
35
+ `));continue}let P;try{P=JSON.parse(C)}catch{continue}a||(a=!0,p.enqueue(m("response.created",{type:"response.created",response:y("in_progress")})),p.enqueue(m("response.in_progress",{type:"response.in_progress",response:y("in_progress")})));let R=P.choices?.[0];if(!R)continue;let A=R.delta;if(A?.content){if(!c){c=!0;let E=l++,I={id:`${i}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};g.push(I),p.enqueue(m("response.output_item.added",{type:"response.output_item.added",output_index:E,item:I}))}p.enqueue(m("response.output_text.delta",{type:"response.output_text.delta",item_id:`${i}_msg`,output_index:l-1,content_index:0,delta:A.content}))}if(Array.isArray(A?.tool_calls))for(let E of A.tool_calls){if(E.id){u=E.id,d=l++;let I={id:E.id,type:"function_call",status:"in_progress",call_id:E.id,name:E.function?.name||"",arguments:""};g.push(I),p.enqueue(m("response.output_item.added",{type:"response.output_item.added",output_index:d,item:I}))}if(E.function?.arguments){p.enqueue(m("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:d,delta:E.function.arguments}));let I=g.find(L=>L.call_id===u);I&&(I.arguments+=E.function.arguments)}}R.finish_reason&&h(P)}}k||h({}),p.close()}catch(f){p.error(f)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",i=`resp_${Date.now()}`,l="",a="",c=-1,u="",d="",g="",m=-1,y="",p="",f=-1,_=0,k=!1,h=!1,b=!1,T=!1,x=null,v=[],S=(I,L)=>r.encode(`event: ${I}
36
36
  data: ${JSON.stringify(L)}
37
37
 
38
- `),T=(I,L=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:I,model:s,output:L,usage:this.buildResponsesUsage()}),O=()=>{k||(k=!0,A.enqueue(R("response.created",{type:"response.created",response:T("in_progress")})),A.enqueue(R("response.in_progress",{type:"response.in_progress",response:T("in_progress")})))},w=(I,L)=>{A.enqueue(R("response.output_item.done",{type:"response.output_item.done",output_index:I,item:{...L,status:"completed"}}))},E=I=>{if(!x){if(x=!0,h){let L=C.find(U=>U.type==="message");L&&(L.content=[{type:"output_text",text:l}],L.status="completed")}for(let L of C)L.type==="function_call"&&(L.status="completed");return R("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:C,usage:I?{...this.buildResponsesUsage(I)}:this.buildResponsesUsage()}})}},A;return new ReadableStream({async start(I){A=I;try{let L=e.getReader(),U="";for(;;){let{done:N,value:F}=await L.read();if(N)break;U+=o.decode(F,{stream:!0});let Q=U.split(`
39
- `);U=Q.pop()||"";for(let we of Q){let H=we.trim();if(!H||H.startsWith("event:")||!H.startsWith("data:"))continue;let oe=H.slice(5).trim();if(oe==="[DONE]")continue;let B;try{B=JSON.parse(oe)}catch{continue}if(B.type==="message_start"&&(a=B.message?.id||a,O()),B.type==="content_block_start"){let M=B.content_block;if(v=M?.type||null,M?.type==="tool_use"){u=M.id||"",d=M.name||"",m="",g=_++;let G={id:u,type:"function_call",status:"in_progress",call_id:u,name:d,arguments:""};C.push(G),A.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:g,item:G}))}if(M?.type==="thinking"&&(y=M.thinking||"",!b)){b=!0,f=_++,p=`rs_${a}`;let G={id:p,type:"reasoning",status:"in_progress",summary:[]};C.push(G),A.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:f,item:G}))}if(M?.type==="text"&&(l=M?.text||"",!h)){h=!0,i=_++,c=`${a}_msg`;let G={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};C.push(G),A.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:i,item:G}))}}if(B.type==="content_block_delta"){let M=B.delta;if(M?.type==="text_delta"){if(!h){h=!0,i=_++,c=`${a}_msg`;let G={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};C.push(G),A.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:i,item:G}))}l+=M.text||"",A.enqueue(R("response.output_text.delta",{type:"response.output_text.delta",item_id:c,output_index:i,content_index:0,delta:M.text||""}))}M?.type==="thinking_delta"&&(y+=M.thinking||"",A.enqueue(R("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:p||`rs_${a}`,output_index:f>=0?f:0,summary_index:0,delta:M.thinking||""}))),M?.type==="input_json_delta"&&(m+=M.partial_json||"",A.enqueue(R("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:g>=0?g:0,delta:M.partial_json||""})))}if(B.type==="content_block_stop"){if(v==="tool_use"&&u){A.enqueue(R("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:g,arguments:m}));let M=C.find(G=>G.call_id===u);M&&(M.arguments=m,M.status="completed"),M&&w(g,M)}if(v==="text"&&h){A.enqueue(R("response.output_text.done",{type:"response.output_text.done",item_id:c,output_index:i,content_index:0,text:l}));let M=C.find(G=>G.type==="message");M&&(M.content=[{type:"output_text",text:l}],w(i,M))}if(v==="thinking"&&b){let M=C.find(G=>G.type==="reasoning");M&&(M.summary=[{type:"summary_text",text:y}],w(f,M))}v=null}if(B.type==="message_delta"){let M=E(B.usage);M&&A.enqueue(M)}if(B.type==="message_stop"){let M=E();M&&A.enqueue(M),A.enqueue(r.encode(`data: [DONE]
38
+ `),C=(I,L=[])=>({id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:I,model:s,output:L,usage:this.buildResponsesUsage()}),P=()=>{k||(k=!0,E.enqueue(S("response.created",{type:"response.created",response:C("in_progress")})),E.enqueue(S("response.in_progress",{type:"response.in_progress",response:C("in_progress")})))},R=(I,L)=>{E.enqueue(S("response.output_item.done",{type:"response.output_item.done",output_index:I,item:{...L,status:"completed"}}))},A=I=>{if(!T){if(T=!0,h){let L=v.find(F=>F.type==="message");L&&(L.content=[{type:"output_text",text:l}],L.status="completed")}for(let L of v)L.type==="function_call"&&(L.status="completed");return S("response.completed",{type:"response.completed",response:{id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:I?{...this.buildResponsesUsage(I)}:this.buildResponsesUsage()}})}},E;return new ReadableStream({async start(I){E=I;try{let L=e.getReader(),F="";for(;;){let{done:N,value:D}=await L.read();if(N)break;F+=o.decode(D,{stream:!0});let K=F.split(`
39
+ `);F=K.pop()||"";for(let Ce of K){let H=Ce.trim();if(!H||H.startsWith("event:")||!H.startsWith("data:"))continue;let te=H.slice(5).trim();if(te==="[DONE]")continue;let B;try{B=JSON.parse(te)}catch{continue}if(B.type==="message_start"&&(i=B.message?.id||i,P()),B.type==="content_block_start"){let M=B.content_block;if(x=M?.type||null,M?.type==="tool_use"){u=M.id||"",d=M.name||"",g="",m=_++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:d,arguments:""};v.push(W),E.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if(M?.type==="thinking"&&(y=M.thinking||"",!b)){b=!0,f=_++,p=`rs_${i}`;let W={id:p,type:"reasoning",status:"in_progress",summary:[]};v.push(W),E.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if(M?.type==="text"&&(l=M?.text||"",!h)){h=!0,c=_++,a=`${i}_msg`;let W={id:a,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),E.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}}if(B.type==="content_block_delta"){let M=B.delta;if(M?.type==="text_delta"){if(!h){h=!0,c=_++,a=`${i}_msg`;let W={id:a,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),E.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}l+=M.text||"",E.enqueue(S("response.output_text.delta",{type:"response.output_text.delta",item_id:a,output_index:c,content_index:0,delta:M.text||""}))}M?.type==="thinking_delta"&&(y+=M.thinking||"",E.enqueue(S("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:p||`rs_${i}`,output_index:f>=0?f:0,summary_index:0,delta:M.thinking||""}))),M?.type==="input_json_delta"&&(g+=M.partial_json||"",E.enqueue(S("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:m>=0?m:0,delta:M.partial_json||""})))}if(B.type==="content_block_stop"){if(x==="tool_use"&&u){E.enqueue(S("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:m,arguments:g}));let M=v.find(W=>W.call_id===u);M&&(M.arguments=g,M.status="completed"),M&&R(m,M)}if(x==="text"&&h){E.enqueue(S("response.output_text.done",{type:"response.output_text.done",item_id:a,output_index:c,content_index:0,text:l}));let M=v.find(W=>W.type==="message");M&&(M.content=[{type:"output_text",text:l}],R(c,M))}if(x==="thinking"&&b){let M=v.find(W=>W.type==="reasoning");M&&(M.summary=[{type:"summary_text",text:y}],R(f,M))}x=null}if(B.type==="message_delta"){let M=A(B.usage);M&&E.enqueue(M)}if(B.type==="message_stop"){let M=A();M&&E.enqueue(M),E.enqueue(r.encode(`data: [DONE]
40
40
 
41
- `))}}}O();let J=E();J&&A.enqueue(J),U="",A.close()}catch(L){A.error(L)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(i=>i.type==="message"),o=e.output?.find(i=>i.type==="function_call"),r;t?.content?.length&&t?.content[0].annotations&&(r=t.content[0].annotations.map(i=>({type:"url_citation",url_citation:{url:i.url||"",title:i.title||"",content:"",start_index:i.start_index||0,end_index:i.end_index||0}}))),this.logger.debug({data:r,type:"url_citation"});let s=null,a=null,l=null;if(t&&t.reasoning&&(l={content:t.reasoning}),t&&t.content){let i=[],u=[];if(t.content.forEach(d=>{if(d.type==="output_text")i.push(d.text||"");else if(d.type==="output_image"){let m=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});m&&u.push(m)}else if(d.type==="output_image_base64"){let m=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});m&&u.push(m)}}),u.length>0){let d=[];i.length>0&&d.push({type:"text",text:i.join("")}),d.push(...u),s=d}else s=i.join("")}return o&&(a=[{id:o.call_id||o.id,function:{name:o.name,arguments:o.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:a,thinking:l,annotations:r},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var Oo,Z,un=P(()=>{"use strict";Oo=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},Z=new Oo(100)});function dn(n,e){n&&Be.set(n,{...e,provider:n,capturedAt:Date.now()})}function mt(n){let e=Be.get(n);return e?{...e}:void 0}function pn(){return Array.from(Be.values()).map(n=>({...n}))}function bc(){try{if(!(0,ye.existsSync)(Io))return;let n=JSON.parse((0,ye.readFileSync)(Io,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;Be.set(t.provider,t)}}catch{}}function hs(){try{if(Be.size===0)return;(0,ye.existsSync)(Eo)||(0,ye.mkdirSync)(Eo,{recursive:!0}),(0,ye.writeFileSync)(Io,JSON.stringify(Array.from(Be.values()),null,2),"utf-8")}catch{}}function We(){ms||(ms=!0,bc(),gs=setInterval(hs,6e4),gs.unref?.(),process.on("exit",hs))}var ye,Mo,ys,Eo,Io,Be,ms,gs,Ge=P(()=>{"use strict";ye=require("fs"),Mo=require("path"),ys=require("@wengine-ai/claude-code-router-shared"),Eo=(0,Mo.join)(ys.HOME_DIR,"runtime"),Io=(0,Mo.join)(Eo,"quota-store.json"),Be=new Map,ms=!1,gs=null});function Ae(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!xc.test(e)))return e}function Ve(n){if(!n)return;if(typeof n=="object")return Ae(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=Ae(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return Ae(e.slice(o+t.length))}var xc,gt=P(()=>{"use strict";xc=/^[A-Za-z0-9_-]+$/});function Tc(n){if(typeof n=="string")return n.slice(0,1e3);if(Array.isArray(n)){let e=n.find(t=>t&&typeof t.text=="string");return e?String(e.text).slice(0,1e3):""}return""}function vc(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function ht(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function ks(n,e,t=!0){let o=Ve(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function No(n){return typeof n=="string"&&Cc.includes(n)}function ke(n){if(No(n?.clientType))return n.clientType;let e=vc(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Tc(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";let a=t["x-anthropic-billing-header"];if(typeof a=="string"&&a.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let l=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(l)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(l).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Lo(n){return $o[n]}function Ic(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,_s.randomUUID)();return n.__ccrRequestScopeId=e,e}function be(n,e={}){let t=ke(n),o=Lo(t).createContext(n,e),r=o.stableSessionId||Ic(n),s=o.usageScope==="session"?"session":"request";return n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function bs(){}var _s,Cc,Rc,wc,Sc,Pc,Ac,Oc,Ec,$o,Qe=P(()=>{"use strict";_s=require("node:crypto");gt();Cc=["claude-code","pi","qwen-code","opencode","codex","api","unknown"];Rc={type:"claude-code",createContext(n){return ks(n,"claude-code")}},wc={type:"pi",createContext(){return ht("pi",!1)}},Sc={type:"qwen-code",createContext(n){return ks(n,"qwen-code")}},Pc={type:"opencode",createContext(){return ht("opencode")}},Ac={type:"codex",createContext(){return ht("codex")}},Oc={type:"api",createContext(){return ht("api")}},Ec={type:"unknown",createContext(){return ht("unknown")}},$o={"claude-code":Rc,pi:wc,"qwen-code":Sc,opencode:Pc,codex:Ac,api:Oc,unknown:Ec}});function re(n,e,t,o){let r=Fo(e,t),s=n.sessionId||n.clientContext?.stableSessionId,a=Rs[r.code]||502;throw new pe(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function hn(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function ws(n){let e=hn(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function $c(n,e){if(!e||!n)return null;let t=hn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=ws(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=hn(r);if(a&&t.includes(a))return s}return null}function Nc(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function fn(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function yt(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Fo(n,e){let t=fn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(i=>i.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(i=>String(i).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!D().isAvailable(s.name,String(a)))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let c=mt(s.name);if(c){let i=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,u=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(i||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function q(n,e,t,o,r,s,a){let l=fn(n);if(!l)return a?null:n;let{providerName:c,routeModel:i}=l,u=yt(e,c,i);if(!u){if(r===!0&&o&&!t&&s!==!1){let m=De(),g=m.getPromotion(c,i,o,e);if(g){let y=fn(g);if(y){let p=yt(e,y.providerName,y.routeModel);if(p)return`${p.provider.name},${p.model}`}m.clear(c,i,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let m=De(),g=m.getPromotion(c,i,o,e);if(g){let y=fn(g);if(y){let p=yt(e,y.providerName,y.routeModel);if(p)return`${p.provider.name},${p.model}`}m.clear(c,i,o)}}if(!t&&!D().isAvailable(u.provider.name,u.model))return null;let d=mt(u.provider.name);if(d){let m=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,g=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(m||g)return null}return`${u.provider.name},${u.model}`}function ee(n,e,t,o,r,s){let a=D(),l=[t?.[n],o?.[n]];for(let c of l)if(!(!Array.isArray(c)||c.length===0))for(let i of c){let u=q(i,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Lc(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function Fc(n){let e=hn(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function Ss(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Nc(e))}function Ps(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Uc(n,e,t,o,r,s,a,l,c,i,u,d){let m=n.clientContext,g=m?.longContextThreshold??t.longContextThreshold??c??6e4,y=Ss(e,r,m),p=n.modelFamily,f=Ps(m,t,i),_=m?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||y>f)&&t.extendedContext){let b=q(t.extendedContext,o,!1,"extendedContext",l,d,u);if(b)return n.log.info(`Family: using extended context model (1M+), tokens: ${y}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:b,scenarioType:"extendedContext",isFallback:!1};let x=l?ee("extendedContext",o,t.fallback,a,p,u):null;if(x)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${y}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:x,scenarioType:"extendedContext",isFallback:!0};u&&re(n,t.extendedContext,o,"extendedContext"),n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(y>g&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let b=t.longContext?q(t.longContext,o,!1,"longContext",l,d,u):null;if(b)return n.log.info(`Family: using long context model, tokens: ${y}, estimated: ${e}`),{model:b,scenarioType:"longContext",isFallback:!1};let x=l?ee("longContext",o,t.fallback,a,p,u):null;if(x)return n.log.info(`Family: using long context fallback model, tokens: ${y}, estimated: ${e}`),{model:x,scenarioType:"longContext",isFallback:!0};u&&t.longContext&&re(n,t.longContext,o,"longContext"),n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(b=>b.type?.startsWith("web_search"))&&t.webSearch){let b=q(t.webSearch,o,!1,"webSearch",l,d,u);if(b)return{model:b,scenarioType:"webSearch",isFallback:!1};let x=l?ee("webSearch",o,t.fallback,a,p,u):null;if(x)return n.log.info("Family: using webSearch fallback model"),{model:x,scenarioType:"webSearch",isFallback:!0};u&&re(n,t.webSearch,o,"webSearch"),n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let b=q(t.think,o,!1,"think",l,d,u);if(b)return{model:b,scenarioType:"think",isFallback:!1};let x=l?ee("think",o,t.fallback,a,p,u):null;if(x)return n.log.info("Family: using think fallback model"),{model:x,scenarioType:"think",isFallback:!0};u&&re(n,t.think,o,"think"),n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let b=q(t.default,o,!1,"default",l,d,u);if(b)return{model:b,scenarioType:"default",isFallback:!1};let x=l?ee("default",o,t.fallback,a,p,u):null;if(x)return n.log.info("Family: using default fallback model"),{model:x,scenarioType:"default",isFallback:!0};u&&re(n,t.default,o,"default"),n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function Jc(){if(Oe.size<=xs)return;let n=[...Oe.keys()].slice(0,Oe.size-xs);for(let e of n)Oe.delete(e)}function Bc(){if(Ke.size<=Cs)return;let n=[...Ke].slice(0,Ke.size-Cs);for(let e of n)Ke.delete(e)}var vs,mn,yn,gn,Xe,Rs,pe,_e,_t,Mc,Dc,kt,Oe,xs,Ke,Cs,jc,zc,Hc,Ts,Uo,bt=P(()=>{"use strict";vs=require("tiktoken");un();mn=require("fs/promises"),yn=require("fs/promises"),gn=require("path"),Xe=require("@wengine-ai/claude-code-router-shared");ce();Ge();an();gt();Qe();Rs={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500},pe=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Rs[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};_e=(0,vs.get_encoding)("cl100k_base"),_t=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=_e.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{s.type==="text"?o+=_e.encode(s.text).length:s.type==="tool_use"?o+=_e.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(o+=_e.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?o+=_e.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=_e.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=_e.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=_e.encode(r.name+r.description).length),r.input_schema&&(o+=_e.encode(JSON.stringify(r.input_schema)).length)}),o},Mc=async(n,e)=>{if(n.sessionId){let t=await Uo(n.sessionId);if(t){let o=(0,gn.join)(Xe.HOME_DIR,t,"config.json"),r=(0,gn.join)(Xe.HOME_DIR,t,`${n.sessionId}.json`);try{let s=JSON.parse(await(0,mn.readFile)(r,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}try{let s=JSON.parse(await(0,mn.readFile)(o,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch(s){if(s&&s.code!=="ENOENT"){let a=n.sessionId||n.clientContext?.stableSessionId;throw new pe(`Project routing error: project config.json is malformed or unreadable in project "${t}". ${s.message}. Session: "${a||"unknown"}".`,{sessionId:a,configuredTarget:o,code:"project_config_error",statusCode:500})}}}}};Dc=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],l=r||t.get("Router"),c=l?.enableFallback===!0,i=c?l?.fallback:void 0,u=c&&!s?i||t.get("fallback"):i,d=!s,m=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),m=C[1])}if(n.body.model.includes(",")&&!s){let C=q(n.body.model,a,!1,"default",c,d,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let R=c?ee("default",a,void 0,u,void 0,s):null;if(R)return n.log.info(`Using fallback for explicit model: ${R}`),{model:R,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let{family:g,extended:y,isCcrAlias:p}=ws(n.body.model),f=l?.families?.[g||""];if(f&&l?.enableFamilyRouting){n.log.info(`Using model family routing for: ${g}${y?" (1M)":""}`),n.modelFamily=g,n.familyFallback=f.fallback;let C=Uc(n,e,f,a,o,y,u,c,l?.longContextThreshold,l?.extendedContextThreshold,s,d);if(C)return{model:C.model,scenarioType:C.scenarioType}}let _=p&&!l?.enableFamilyRouting?null:$c(n.body.model,l?.models);if(_){let C=q(_,a,!1,"modelMapping",c,d,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${_}`),{model:C,scenarioType:"modelMapping"};let R=c?ee("modelMapping",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"modelMapping"};s&&re(n,_,a,"modelMapping"),n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let k=n.clientContext,h=Ss(e,o,k),b=Ps(k,void 0,l?.extendedContextThreshold);if(h>b&&l?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${h}, estimated: ${e}, threshold: ${b}`);let C=q(l.extendedContext,a,!1,"extendedContext",c,d,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${l.extendedContext} unavailable (fail pool), trying fallback`);let R=c?ee("extendedContext",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"extendedContext"};s&&re(n,l.extendedContext,a,"extendedContext")}let x=k?.longContextThreshold??l?.longContextThreshold??6e4;if(h>x&&l?.longContext){n.log.info(`Using long context model due to token count: ${h}, estimated: ${e}, threshold: ${x}`);let C=q(l.longContext,a,!1,"longContext",c,d,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${l.longContext} unavailable (fail pool), trying fallback`);let R=c?ee("longContext",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"longContext"};s&&re(n,l.longContext,a,"longContext")}if(!s&&m)return{model:m,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&l?.background){n.log.info(`Using background model for ${n.body.model}`);let C=q(l.background,a,!1,"background",c,d,s);if(C)return{model:C,scenarioType:"background"};let R=c?ee("background",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"background"};s&&re(n,l.background,a,"background"),n.log.warn(`Background model ${l.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&l?.webSearch){let C=q(l.webSearch,a,!1,"webSearch",c,d,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${l.webSearch} unavailable (fail pool), trying fallback`);let R=c?ee("webSearch",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"webSearch"};s&&re(n,l.webSearch,a,"webSearch")}if(n.body.thinking?.type==="enabled"&&l?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=q(l.think,a,!1,"think",c,d,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${l.think} unavailable (fail pool), trying fallback`);let R=c?ee("think",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"think"};s&&re(n,l.think,a,"think")}if(l?.default){let C=q(l.default,a,!1,"default",c,d,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${l.default} unavailable (fail pool), trying fallback`);let R=c?ee("default",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"default"};if(!s){let T=q(l.default,a,!0,"default",c,d,s);if(T)return n.log.warn(`No fallback available; retrying default model ${l.default} despite fail-pool state`),{model:T,scenarioType:"default"}}}return s&&re(n,l?.default||n.body.model,a,"default"),{model:void 0,scenarioType:"default"}},kt=async(n,e,t)=>{let{configService:o,event:r}=t;n.originalModel=n.body.model,be(n,o.getAll());let s=await Mc(n,o),a=s||o.get("Router"),l=a?.enableFallback===!0,c=o.get("providers")||[],i=!!s;n.enableFallback=l,n.strictProjectRouting=i,n.fallbackConfig=i?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Z.get(n.usageCacheKey):void 0,{messages:d,system:m=[],tools:g}=n.body,y=o.get("REWRITE_SYSTEM_PROMPT");if(y&&m.length>1&&m[1]?.text?.includes("<env>")){let p=await(0,mn.readFile)(y,"utf-8");m[1].text=`${p}<env>${m[1].text.split("<env>").pop()}`}try{let[p,f]=n.body.model.split(","),_=t.tokenizerService?.getTokenizerConfigForModel(p,f),k;t.tokenizerService?k=(await t.tokenizerService.countTokens({messages:d,system:m,tools:g},_,p)).tokenCount:k=_t(d,m,g),n.tokenCount=k;let h,b=i?void 0:o.get("CUSTOM_ROUTER_PATH");if(b)try{h=await require(b)(n,o.getAll(),{event:r})}catch(x){n.log.error(`failed to load custom router: ${x.message}`)}if(h)n.scenarioType="default";else{let x=await Dc(n,k,o,u,s,!!s);h=x.model,n.scenarioType=x.scenarioType}if(a?.image&&h!==a.image&&Lc(n)&&!Fc(h)){let x=q(a.image,c,!1,"image",l,!i,i);if(x)n.log.info(`Using image model fallback for ${h}`),h=x,n.scenarioType="image";else{let v=l?ee("image",c,void 0,n.fallbackConfig,void 0,i):null;v?(n.log.info(`Using image fallback model: ${v}`),h=v,n.scenarioType="image"):i?re(n,a.image,c,"image"):(n.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${h}`),n.scenarioType="image")}}typeof h=="string"&&h.trim()?n.body.model=h:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(p){if(p instanceof pe)throw p;if(n.log.error(`Error in router middleware: ${p.message}`),i){let f=n.sessionId||n.clientContext?.stableSessionId;throw new pe(`Project routing error: router failure in project mode. ${p.message}. Session: "${f||"unknown"}".`,{sessionId:f,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Oe=new Map,xs=1e3,Ke=new Set,Cs=1e3,jc=3,zc=50,Hc=n=>new Promise(e=>setTimeout(e,n));Ts=async n=>{let e=await(0,yn.opendir)(Xe.CLAUDE_PROJECTS_DIR),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=(0,gn.join)(Xe.CLAUDE_PROJECTS_DIR,s,`${n}.jsonl`);try{return(await(0,yn.stat)(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Uo=async n=>{let e=Ae(n);if(!e)return null;if(Oe.has(e))return Oe.get(e)||null;try{let t=await Ts(e);if(!t&&!Ke.has(e)){Ke.add(e),Bc();for(let o=0;o<jc&&!t;o++)await Hc(zc),t=await Ts(e)}return t?(Oe.set(e,t),Jc(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function xt(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
41
+ `))}}}P();let z=A();z&&E.enqueue(z),F="",E.close()}catch(L){E.error(L)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(c=>c.type==="message"),o=e.output?.find(c=>c.type==="function_call"),r;t?.content?.length&&t?.content[0].annotations&&(r=t.content[0].annotations.map(c=>({type:"url_citation",url_citation:{url:c.url||"",title:c.title||"",content:"",start_index:c.start_index||0,end_index:c.end_index||0}}))),this.logger.debug({data:r,type:"url_citation"});let s=null,i=null,l=null;if(t&&t.reasoning&&(l={content:t.reasoning}),t&&t.content){let c=[],u=[];if(t.content.forEach(d=>{if(d.type==="output_text")c.push(d.text||"");else if(d.type==="output_image"){let g=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});g&&u.push(g)}else if(d.type==="output_image_base64"){let g=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});g&&u.push(g)}}),u.length>0){let d=[];c.length>0&&d.push({type:"text",text:c.join("")}),d.push(...u),s=d}else s=c.join("")}return o&&(i=[{id:o.call_id||o.id,function:{name:o.name,arguments:o.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:l,annotations:r},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var vo,q,rn=w(()=>{"use strict";vo=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},q=new vo(100)});function sn(n,e){n&&ze.set(n,{...e,provider:n,capturedAt:Date.now()})}function dt(n){let e=ze.get(n);return e?{...e}:void 0}function an(){return Array.from(ze.values()).map(n=>({...n}))}function qa(){try{if(!(0,me.existsSync)(So))return;let n=JSON.parse((0,me.readFileSync)(So,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;ze.set(t.provider,t)}}catch{}}function as(){try{if(ze.size===0)return;(0,me.existsSync)(xo)||(0,me.mkdirSync)(xo,{recursive:!0}),(0,me.writeFileSync)(So,JSON.stringify(Array.from(ze.values()),null,2),"utf-8")}catch{}}function Be(){ss||(ss=!0,qa(),is=setInterval(as,6e4),is.unref?.(),process.on("exit",as))}var me,Ro,cs,xo,So,ze,ss,is,Je=w(()=>{"use strict";me=require("fs"),Ro=require("path"),cs=require("@wengine-ai/claude-code-router-shared"),xo=(0,Ro.join)(cs.HOME_DIR,"runtime"),So=(0,Ro.join)(xo,"quota-store.json"),ze=new Map,ss=!1,is=null});function Se(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Za.test(e)))return e}function We(n){if(!n)return;if(typeof n=="object")return Se(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=Se(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return Se(e.slice(o+t.length))}var Za,pt=w(()=>{"use strict";Za=/^[A-Za-z0-9_-]+$/});function tc(n){if(typeof n=="string")return n.slice(0,1e3);if(Array.isArray(n)){let e=n.find(t=>t&&typeof t.text=="string");return e?String(e.text).slice(0,1e3):""}return""}function nc(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function ft(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function us(n,e,t=!0){let o=We(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Po(n){return typeof n=="string"&&ec.includes(n)}function Re(n){if(Po(n?.clientType))return n.clientType;let e=nc(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=tc(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";let i=t["x-anthropic-billing-header"];if(typeof i=="string"&&i.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let l=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(l)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(l).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Eo(n){return wo[n]}function uc(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,ls.randomUUID)();return n.__ccrRequestScopeId=e,e}function he(n,e={}){let t=Re(n),o=Eo(t).createContext(n,e),r=o.stableSessionId||uc(n),s=o.usageScope==="session"?"session":"request";return n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function ds(){}var ls,ec,oc,rc,sc,ic,ac,cc,lc,wo,Ge=w(()=>{"use strict";ls=require("node:crypto");pt();ec=["claude-code","pi","qwen-code","opencode","codex","api","unknown"];oc={type:"claude-code",createContext(n){return us(n,"claude-code")}},rc={type:"pi",createContext(){return ft("pi",!1)}},sc={type:"qwen-code",createContext(n){return us(n,"qwen-code")}},ic={type:"opencode",createContext(){return ft("opencode")}},ac={type:"codex",createContext(){return ft("codex")}},cc={type:"api",createContext(){return ft("api")}},lc={type:"unknown",createContext(){return ft("unknown")}},wo={"claude-code":oc,pi:rc,"qwen-code":sc,opencode:ic,codex:ac,api:cc,unknown:lc}});function ne(n,e,t,o){let r=Oo(e,t),s=n.sessionId||n.clientContext?.stableSessionId,i=hs[r.code]||502;throw new ue(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:i})}function dn(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function ht(n){let e=dn(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function pc(n,e){if(!e||!n)return null;let t=dn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=ht(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let i=dn(r);if(i&&t.includes(i))return s}return null}function fc(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function cn(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function mt(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Oo(n,e){let t=cn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(c=>c.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let i=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!i)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!U().isAvailable(s.name,String(i)))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let a=dt(s.name);if(a){let c=a.limitDaily!==void 0&&a.usedDailyBalance!==void 0&&a.usedDailyBalance>=a.limitDaily,u=a.totalBalance!==void 0&&a.usedBalance!==void 0&&a.usedBalance>=a.totalBalance;if(c||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function X(n,e,t,o,r,s,i){let l=cn(n);if(!l)return i?null:n;let{providerName:a,routeModel:c}=l,u=mt(e,a,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let g=De(),m=g.getPromotion(a,c,o,e);if(m){let y=cn(m);if(y){let p=mt(e,y.providerName,y.routeModel);if(p)return`${p.provider.name},${p.model}`}g.clear(a,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let g=De(),m=g.getPromotion(a,c,o,e);if(m){let y=cn(m);if(y){let p=mt(e,y.providerName,y.routeModel);if(p)return`${p.provider.name},${p.model}`}g.clear(a,c,o)}}if(!t&&!U().isAvailable(u.provider.name,u.model))return null;let d=dt(u.provider.name);if(d){let g=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,m=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(g||m)return null}return`${u.provider.name},${u.model}`}function Z(n,e,t,o,r,s){let i=U(),l=[t?.[n],o?.[n]];for(let a of l)if(!(!Array.isArray(a)||a.length===0))for(let c of a){let u=X(c,e,!1,n,void 0,void 0,s);if(u)return u}return null}function mc(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function Ao(n){let e=dn(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function ys(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,fc(e))}function _s(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function gc(n,e,t,o,r,s,i,l,a,c,u,d){let g=n.clientContext,m=g?.longContextThreshold??t.longContextThreshold??a??6e4,y=ys(e,r,g),p=n.modelFamily,f=_s(g,t,c),_=g?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||y>f)&&t.extendedContext){let b=X(t.extendedContext,o,!1,"extendedContext",l,d,u);if(b)return n.log.info(`Family: using extended context model (1M+), tokens: ${y}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:b,scenarioType:"extendedContext",isFallback:!1};let T=l?Z("extendedContext",o,t.fallback,i,p,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${y}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:T,scenarioType:"extendedContext",isFallback:!0};u&&ne(n,t.extendedContext,o,"extendedContext"),n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(y>m&&(t.longContext||t.fallback?.longContext?.length||i?.longContext?.length)){let b=t.longContext?X(t.longContext,o,!1,"longContext",l,d,u):null;if(b)return n.log.info(`Family: using long context model, tokens: ${y}, estimated: ${e}`),{model:b,scenarioType:"longContext",isFallback:!1};let T=l?Z("longContext",o,t.fallback,i,p,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${y}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};u&&t.longContext&&ne(n,t.longContext,o,"longContext"),n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(b=>b.type?.startsWith("web_search"))&&t.webSearch){let b=X(t.webSearch,o,!1,"webSearch",l,d,u);if(b)return{model:b,scenarioType:"webSearch",isFallback:!1};let T=l?Z("webSearch",o,t.fallback,i,p,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};u&&ne(n,t.webSearch,o,"webSearch"),n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let b=X(t.think,o,!1,"think",l,d,u);if(b)return{model:b,scenarioType:"think",isFallback:!1};let T=l?Z("think",o,t.fallback,i,p,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};u&&ne(n,t.think,o,"think"),n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let b=X(t.default,o,!1,"default",l,d,u);if(b)return{model:b,scenarioType:"default",isFallback:!1};let T=l?Z("default",o,t.fallback,i,p,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};u&&ne(n,t.default,o,"default"),n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function bc(){if(we.size<=ps)return;let n=[...we.keys()].slice(0,we.size-ps);for(let e of n)we.delete(e)}function Tc(){if(Ke.size<=fs)return;let n=[...Ke].slice(0,Ke.size-fs);for(let e of n)Ke.delete(e)}var gs,ln,pn,un,Qe,hs,ue,ge,gt,dc,hc,yt,we,ps,Ke,fs,yc,_c,kc,ms,Io,Ve=w(()=>{"use strict";gs=require("tiktoken");rn();ln=require("fs/promises"),pn=require("fs/promises"),un=require("path"),Qe=require("@wengine-ai/claude-code-router-shared");ie();Je();tn();pt();Ge();hs={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500},ue=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||hs[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};ge=(0,gs.get_encoding)("cl100k_base"),gt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=ge.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{s.type==="text"?o+=ge.encode(s.text).length:s.type==="tool_use"?o+=ge.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(o+=ge.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?o+=ge.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=ge.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=ge.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=ge.encode(r.name+r.description).length),r.input_schema&&(o+=ge.encode(JSON.stringify(r.input_schema)).length)}),o},dc=async(n,e)=>{if(n.sessionId){let t=await Io(n.sessionId);if(t){let o=(0,un.join)(Qe.HOME_DIR,t,"config.json"),r=(0,un.join)(Qe.HOME_DIR,t,`${n.sessionId}.json`);try{let s=JSON.parse(await(0,ln.readFile)(r,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch{}try{let s=JSON.parse(await(0,ln.readFile)(o,"utf8"));if(s&&s.Router&&Object.keys(s.Router).length>0)return s.Router}catch(s){if(s&&s.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new ue(`Project routing error: project config.json is malformed or unreadable in project "${t}". ${s.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:o,code:"project_config_error",statusCode:500})}}}}};hc=async(n,e,t,o,r,s)=>{let i=t.get("providers")||[],l=r||t.get("Router"),a=l?.enableFallback===!0,c=a?l?.fallback:void 0,u=a&&!s?c||t.get("fallback"):c,d=!s,g=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let v=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);v&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${v[1]}</CCR-SUBAGENT-MODEL>`,""),g=v[1])}let{family:m,extended:y,isCcrAlias:p}=ht(n.body.model),f=l?.families?.[m||""];if(f&&l?.enableFamilyRouting){n.log.info(`Using model family routing for: ${m}${y?" (1M)":""}`),n.modelFamily=m,n.familyFallback=f.fallback;let v=gc(n,e,f,i,o,y,u,a,l?.longContextThreshold,l?.extendedContextThreshold,s,d);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=X(n.body.model,i,!1,"default",a,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let S=a?Z("default",i,void 0,u,void 0,s):null;if(S)return n.log.info(`Using fallback for explicit model: ${S}`),{model:S,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let _=p&&!l?.enableFamilyRouting?null:pc(n.body.model,l?.models);if(_){let v=X(_,i,!1,"modelMapping",a,d,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${_}`),{model:v,scenarioType:"modelMapping"};let S=a?Z("modelMapping",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};s&&ne(n,_,i,"modelMapping"),n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let k=n.clientContext,h=ys(e,o,k),b=_s(k,void 0,l?.extendedContextThreshold);if(h>b&&l?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${h}, estimated: ${e}, threshold: ${b}`);let v=X(l.extendedContext,i,!1,"extendedContext",a,d,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${l.extendedContext} unavailable (fail pool), trying fallback`);let S=a?Z("extendedContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};s&&ne(n,l.extendedContext,i,"extendedContext")}let T=k?.longContextThreshold??l?.longContextThreshold??6e4;if(h>T&&l?.longContext){n.log.info(`Using long context model due to token count: ${h}, estimated: ${e}, threshold: ${T}`);let v=X(l.longContext,i,!1,"longContext",a,d,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${l.longContext} unavailable (fail pool), trying fallback`);let S=a?Z("longContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};s&&ne(n,l.longContext,i,"longContext")}if(!s&&g)return{model:g,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&l?.background){n.log.info(`Using background model for ${n.body.model}`);let v=X(l.background,i,!1,"background",a,d,s);if(v)return{model:v,scenarioType:"background"};let S=a?Z("background",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};s&&ne(n,l.background,i,"background"),n.log.warn(`Background model ${l.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&l?.webSearch){let v=X(l.webSearch,i,!1,"webSearch",a,d,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${l.webSearch} unavailable (fail pool), trying fallback`);let S=a?Z("webSearch",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};s&&ne(n,l.webSearch,i,"webSearch")}if(n.body.thinking?.type==="enabled"&&l?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=X(l.think,i,!1,"think",a,d,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${l.think} unavailable (fail pool), trying fallback`);let S=a?Z("think",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};s&&ne(n,l.think,i,"think")}if(l?.default){let v=X(l.default,i,!1,"default",a,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${l.default} unavailable (fail pool), trying fallback`);let S=a?Z("default",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};if(!s){let C=X(l.default,i,!0,"default",a,d,s);if(C)return n.log.warn(`No fallback available; retrying default model ${l.default} despite fail-pool state`),{model:C,scenarioType:"default"}}}return s&&ne(n,l?.default||n.body.model,i,"default"),{model:void 0,scenarioType:"default"}},yt=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),he(n,o.getAll());let s=await dc(n,o),i=s||o.get("Router"),l=i?.enableFallback===!0,a=o.get("providers")||[],c=!!s;n.enableFallback=l,n.strictProjectRouting=c,n.fallbackConfig=c?i?.fallback:i?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??q.get(n.usageCacheKey):void 0,{messages:d,system:g=[],tools:m}=n.body,y=o.get("REWRITE_SYSTEM_PROMPT");if(y&&g.length>1&&g[1]?.text?.includes("<env>")){let p=await(0,ln.readFile)(y,"utf-8");g[1].text=`${p}<env>${g[1].text.split("<env>").pop()}`}try{let[p,f]=n.body.model.split(","),_=t.tokenizerService?.getTokenizerConfigForModel(p,f),k;t.tokenizerService?k=(await t.tokenizerService.countTokens({messages:d,system:g,tools:m},_,p)).tokenCount:k=gt(d,g,m),n.tokenCount=k;let h,b=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(b)try{h=await require(b)(n,o.getAll(),{event:r})}catch(S){n.log.error(`failed to load custom router: ${S.message}`)}if(h)n.scenarioType="default";else{let S=await hc(n,k,o,u,s,!!s);h=S.model,n.scenarioType=S.scenarioType}let{family:T}=ht(n.originalModel||n.body.model),x=i?.enableFamilyRouting&&T?i.families?.[T]:void 0,v=[x?.image,i?.image].filter((S,C,P)=>!!S&&P.indexOf(S)===C);if(v.length>0&&mc(n)&&!Ao(h))if(v.includes(h))n.scenarioType="image";else{let S=v.map(C=>X(C,a,!1,"image",l,!c,c)).find(C=>!!C);if(S)n.log.info(`Using image model fallback for ${h}`),h=S,n.scenarioType="image";else{let C=l?Z("image",a,x?.fallback,n.fallbackConfig,T||void 0,c):null;C?(n.log.info(`Using image fallback model: ${C}`),h=C,n.scenarioType="image"):c?ne(n,v[0],a,"image"):(n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${h}`),n.scenarioType="image")}}typeof h=="string"&&h.trim()?n.body.model=h:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(p){if(p instanceof ue)throw p;if(n.log.error(`Error in router middleware: ${p.message}`),c){let f=n.sessionId||n.clientContext?.stableSessionId;throw new ue(`Project routing error: router failure in project mode. ${p.message}. Session: "${f||"unknown"}".`,{sessionId:f,configuredTarget:i?.default,code:"project_router_failure",statusCode:502})}n.body.model=i?.default,n.scenarioType="default"}},we=new Map,ps=1e3,Ke=new Set,fs=1e3,yc=3,_c=50,kc=n=>new Promise(e=>setTimeout(e,n));ms=async n=>{let e=await(0,pn.opendir)(Qe.CLAUDE_PROJECTS_DIR),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let i=(0,un.join)(Qe.CLAUDE_PROJECTS_DIR,s,`${n}.jsonl`);try{return(await(0,pn.stat)(i)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Io=async n=>{let e=Se(n);if(!e)return null;if(we.has(e))return we.get(e)||null;try{let t=await ms(e);if(!t&&!Ke.has(e)){Ke.add(e),Tc();for(let o=0;o<yc&&!t;o++)await kc(_c),t=await ms(e)}return t?(we.set(e,t),bc(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function _t(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
42
42
  `):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
43
- ${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function As(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&xt(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&Wc.test(r.model)&&await kt(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let s=n.provider;if(!s&&r?.model){let i=r.model.split(",");i.length>1&&(s=i[0],r.model=i.slice(1).join(","))}let a=s?t.providerService.getProvider(s):void 0;if(!a&&r?.model){let i=t.providerService.resolveModelRoute(r.model);i&&(a=i.provider,r.model=i.targetModel)}if(!a&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[d,...m]=u.split(","),g=t.providerService.getProvider(d);g&&(a=g,r.model=m.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!a)throw V(`Provider '${s}' not found`,404,"provider_not_found");n.provider=a.name||s;let l=Qc(n),c=o.endPoint==="/v1/messages"&&l;l&&e.header("X-Codex-Detected","true"),c&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=c,n.codexDetected=l;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&xt(r);let{requestBody:i,config:u,bypass:d}=await Es(r,a,o,n.headers,{req:n});if(i?.messages&&!d&&!n.isTargetAnthropic){let p=i.messages,f=new Set,_=[],k=[];for(let h of p){if(h?.role!=="system"){k.push(h);continue}let b=JSON.stringify(h.content??"");f.has(b)||(f.add(b),_.push(h))}_.length>0&&k.length>0&&(i.messages=[..._,...k])}let m=await Is(i,u,a,t,d,o,{req:n});try{a?.baseUrl&&m?.headers&&ft(s,a.baseUrl,m.headers)}catch{}let g=await Ms(i,m,a,o,d,{req:n,isCodexOnMessagesEndpoint:c});g=await Os(r,g,a.name||s);let y=$s(g,e,r,t);try{let p=r.model||n.originalModel;s&&p&&D().recordSuccess(s,p)}catch{}return y}catch(i){if(i instanceof pe)throw i;if(!n.__retryAttempted){n.__retryAttempted=!0;try{return await As(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;i=d}}let u=await Gc(n,e,t,o,i);if(u)return u;throw n.__fallbackExhausted=!0,i}}async function Os(n,e,t){if(!n?.stream||!e?.body)return e;let o=e.body.getReader(),r=await o.read();if(r.done)throw o.releaseLock(),V(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");let s=new TextDecoder().decode(r.value);if(s.includes("event: error")){o.releaseLock();let c=s.length<500?s:s.slice(0,500);throw V(`Provider ${t} returned error in SSE stream: ${c}`,400,"provider_response_error")}if(s.split(`
44
- `).filter(c=>c.startsWith("data:")&&c.trim().length>5).length===0){o.releaseLock();let c=s.length<500?s:s.slice(0,500);throw V(`Provider ${t} returned streaming response with no SSE data lines: ${c}`,400,"provider_response_error")}let l=new ReadableStream({start:c=>{c.enqueue(r.value);let i=()=>{o.read().then(({done:u,value:d})=>{u?c.close():(c.enqueue(d),i())}).catch(u=>c.error(u))};i()},cancel:()=>{o.cancel()}});return new Response(l,{headers:e.headers,status:e.status,statusText:e.statusText})}async function Gc(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,l=n.modelFamily,c=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),i=D(),u=n.provider||"",d=n.body.model||"",m=new Set,g=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&_n(r.rawBody)||r?.message&&_n(r.message);if(u&&d&&(g?(i.markRateLimited(u,d,120,r?.message),n.log.warn(`Primary model ${u},${d} rate-limited, will try fallbacks`)):i.recordFailure(u,d,r?.message),m.add(`${u},${d}`),t.recordUsage?.({provider:u,model:d,originalModel:n.originalModel||d,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let p=k=>{let[h,...b]=k.split(","),x=h?.trim(),v=b.join(",").trim();return!x||!v?null:{provider:x,model:v,key:`${x},${v}`}},f=[];if(l){let k=a?.[s];if(Array.isArray(k)&&k.length>0)f.push({name:`${l}/${s}`,models:k});else{let h=n.strictProjectRouting;n.log.warn(`No ${l} fallback configured for ${s}; ${h?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(c?.[s])&&c[s].length>0&&f.push({name:`global/${s}`,models:c[s]}),f.length===0&&s!=="image"&&n.body?.messages?.some(b=>b.role==="user"&&Array.isArray(b.content)&&b.content.some(x=>x.type==="image"||x.type==="image_url"||Array.isArray(x?.content)&&x.content.some(v=>v.type==="image"||v.type==="image_url")))&&Array.isArray(c?.image)&&c.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),f.push({name:"global/image (auto-detected)",models:c.image})),f.length===0)return null;let _=f.reduce((k,h)=>k+h.models.length,0);n.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${f.length} fallback stage(s)`);for(let k of f){n.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let h of k.models){let b=p(h);if(!b){n.log.warn(`Fallback model '${h}' is invalid, skipping`);continue}if(m.has(b.key))continue;m.add(b.key);let x=t.providerService.getProviders(),v=yt(x,b.provider,b.model);if(!v){n.log.warn(`Fallback model ${h} is not configured or provider is disabled, skipping`);continue}let C=v.provider.name,R=v.model;if(!i.isAvailable(C,R)){n.log.warn(`Fallback model ${h} unavailable (fail pool), skipping`);continue}let T;for(let O=1;O<=2;O++)try{n.log.info(`Trying fallback model: ${C},${R}${O>1?" (retry)":""}`);let w={...n.body};w.model=R;let E={...n,provider:C,body:w},A=v.provider,{requestBody:I,config:L,bypass:U}=await Es(w,A,o,n.headers,{req:E}),J=await Is(I,L,A,t,U,o,{req:E});try{A?.baseUrl&&J?.headers&&ft(C,A.baseUrl,J.headers)}catch{}let N=await Ms(I,J,A,o,U,{req:E,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1});return N=await Os(w,N,C),n.log.info(`Fallback model ${C},${R} succeeded`),i.recordSuccess(C,R),u&&d&&!n.strictProjectRouting&&(De().promote(u,d,s,C,R),n.log.info(`Promoted fallback model ${C},${R} for ${u},${d}:${s}`),g?n.log.info(`Rate-limited original model ${u},${d} already marked unavailable with cooldown`):(i.forceOpen(u,d,r?.message),n.log.info(`Marked original model ${u},${d} as unavailable`))),n.provider=C,n.body=w,$s(N,e,w,t)}catch(w){if(T=w,O===1){n.log.warn(`Fallback model ${C},${R} failed, retrying once: ${w.message}`);continue}}i.recordFailure(C,R,T?.message),n.log.warn(`Fallback model ${C},${R} failed after retry: ${T?.message}`),t.recordUsage?.({provider:C,model:R,originalModel:n.originalModel||d||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:T?.message||String(T),sessionId:n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Es(n,e,t,o,r){let s=JSON.parse(JSON.stringify(n)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let i=0;i<a.length;i++){let u=a[i],d=typeof u=="string"?u:u?.text??"";if(d.includes("cch=")){let m=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof u=="string"?a[i]=m:typeof u?.text=="string"&&(u.text=m)}}let l={},c=!1;if(c=Vc(e,t,n),c&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!c&&typeof t.transformRequestOut=="function"){let i=await t.transformRequestOut(s);i.body?(s=i.body,l=i.config||{}):s=i}if(!c&&e.transformer?.use?.length)for(let i of e.transformer.use){if(!i||typeof i.transformRequestIn!="function")continue;let u=await i.transformRequestIn(s,e,r);u.body?(s=u.body,l={...l,...u.config}):s=u}if(!c&&e.transformer?.[n.model]?.use?.length)for(let i of e.transformer[n.model].use)!i||typeof i.transformRequestIn!="function"||(s=await i.transformRequestIn(s,e,r));return{requestBody:s,config:l,bypass:c}}function Vc(n,e,t){return e.endPoint==="/v1/chat/completions"&&Array.isArray(t?.system)?!1:n.transformer?.use?.length===1&&n.transformer.use[0].name===e.name&&(!n.transformer?.[t.model]?.use.length||n.transformer?.[t.model]?.use.length===1&&n.transformer?.[t.model]?.use[0].name===e.name)}function Qc(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Is(n,e,t,o,r,s,a){let l=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let u=o.configService.get("API_TIMEOUT_MS");u&&(e.TIMEOUT=typeof u=="string"?parseInt(u,10):u)}if(r&&typeof s.auth=="function"){let u=await s.auth(n,t);if(u.body){n=u.body;let d=e.headers||{};u.config?.headers&&(d={...d,...u.config.headers},delete d.host,delete u.config.headers),e={...e,...u.config,headers:d}}else n=u}let c={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};for(let u in c)(c[u]==="undefined"||["authorization","Authorization"].includes(u)&&c[u]?.includes("undefined"))&&delete c[u];nn(o.configService)&&Zr(o.log,a.req.id,{url:String(l),headers:c,body:n});let i=await ns(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:de(o.configService,t)},a,o.log);if(!i.ok){let u=await i.text();o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${i.status}): ${u}`);let d=V(`Error from provider(${t.name},${n.model}: ${i.status}): ${u}`,i.status,"provider_response_error");throw d.isRateLimit=i.status===429||_n(u),d.rawBody=u,d}if(i.ok){let u=i.headers.get("content-type")||"",d=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${d} contentType=${u} ok=${i.ok} status=${i.status} hasBody=${!!i.body}`),!d||u.includes("application/json")){let m=i.clone(),g="";try{if(g=await m.text(),!g||g.trim()==="")throw new SyntaxError("Empty JSON body");let y=JSON.parse(g);if(y&&typeof y=="object"&&y.error&&(typeof y.error=="string"||typeof y.error=="object"&&Object.keys(y.error).length>0)){o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${i.status}): ${g}`);let f=_n(g),_=V(`Error from provider(${t.name},${n.model}: ${i.status}): ${g}`,400,"provider_response_error");throw _.isRateLimit=f,_.rawBody=g,_}}catch(y){if(y instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let p=V(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw p.rawBody=g,p}throw y}}}if(!n.stream&&nn(o.configService)){let d=await i.clone().text();es(o.log,a.req.id,{status:i.status,headers:Object.fromEntries(i.headers.entries()),body:d})}return i}async function Ms(n,e,t,o,r,s){let a=e;if(!r&&t.transformer?.use?.length)for(let l of Array.from(t.transformer.use).reverse())!l||typeof l.transformResponseOut!="function"||(a=await l.transformResponseOut(a,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let l of Array.from(t.transformer[n.model].use).reverse())!l||typeof l.transformResponseOut!="function"||(a=await l.transformResponseOut(a,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),a=await o.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Je().transformResponseIn(a,{...s,provider:t})}catch(l){console.error("Failed to apply Responses API conversion for codex client:",l)}return a}function $s(n,e,t,o){if(n.ok||e.code(n.status),t.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&nn(o.configService)){let[s,a]=n.body.tee(),l=qr(o.configService);return ts(s,o.log,e.request.id,l),e.send(a)}return e.send(n.body)}else return n.json()}function _n(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function Kc(n){try{return new URL(n),!0}catch{return!1}}var Wc,Ns,kn=P(()=>{"use strict";os();en();dt();ko();ce();He();an();Ao();bt();ae();Wc=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Ns=async n=>{n.get("/",async()=>({message:"LLMs API",version:sn})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:D().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>As(o,r,n,t));n.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"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:l}=t.body;if(!r?.trim())throw V("Provider name is required",400,"invalid_request");if(!s||!Kc(s))throw V("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw V("API key is required",400,"invalid_request");if(!l||!Array.isArray(l)||l.length===0)throw V("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw V(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw V("Provider not found",404,"provider_not_found");return o}),n.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"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw V("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw V("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.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,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw V("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var fe,bn=P(()=>{"use strict";fe=class{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;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 o={};t.transformer&&Object.keys(t.transformer).forEach(r=>{r==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(t.transformer[r]?.use)&&(o[r]={use:t.transformer[r].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,l={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,l),this.modelRoutes.has(s)||this.modelRoutes.set(s,l)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var Ls,Fs=P(()=>{Ls=n=>n<=0?"none":n<=1024?"low":n<=8192?"medium":"high"});var Us,Ds=P(()=>{Us=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Xc(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function js(n){let e=[],t=[],o=m=>{if(typeof m=="string"){t.push({type:"text",text:m});return}Array.isArray(m)&&m.forEach(g=>{if(typeof g=="string"){t.push({type:"text",text:g});return}g&&typeof g=="object"&&g.type==="text"&&g.text&&t.push({...g})})},r=()=>{let m=new Map;for(let g=0;g<t.length;g++){let y=t[g],p=y?.text??JSON.stringify(y),f=m.get(p);if(f===void 0){m.set(p,g);continue}!t[f]?.cache_control&&y?.cache_control&&(t[f]=y),t.splice(g,1),g--}};n.messages.forEach(m=>{m.role==="system"?o(m.content):e.push(m)}),r();let s=[];for(let m=0;m<e.length;m++){let g=e[m];if(g.role==="tool"){let y=g.content;try{typeof g.content=="string"&&(y=JSON.parse(g.content))}catch{}y!=null&&typeof y!="object"&&typeof y!="string"&&(y=String(y));let p={type:"tool_result",tool_use_id:g.tool_call_id,content:y};g.cache_control&&(p.cache_control=g.cache_control);let f=s[s.length-1];f&&f.role==="user"&&Array.isArray(f.content)?f.content.push(p):s.push({role:"user",content:[p]})}else if(g.role==="user"){let y=[];typeof g.content=="string"?y.push({type:"text",text:g.content}):Array.isArray(g.content)&&g.content.forEach(f=>{f&&typeof f=="object"&&f.type==="image_url"&&f.image_url?.url?y.push({type:"image",source:{type:"base64",media_type:f.media_type||"image/jpeg",data:f.image_url.url.split(",")[1]||f.image_url.url}}):y.push(f)});let p=s[s.length-1];p&&p.role==="user"&&Array.isArray(p.content)?p.content.push(...y):s.push({role:"user",content:y.length>0?y:[{type:"text",text:" "}]})}else if(g.role==="assistant"){let y=[];g.content&&(typeof g.content=="string"?y.push({type:"text",text:g.content}):Array.isArray(g.content)&&y.push(...g.content)),g.tool_calls&&g.tool_calls.length>0&&g.tool_calls.forEach(f=>{let _={};try{_=JSON.parse(f.function.arguments)}catch{_=f.function.arguments}y.push({type:"tool_use",id:f.id,name:f.function.name,input:_})}),g.thinking&&y.unshift({type:"thinking",thinking:g.thinking.content,signature:g.thinking.signature});let p=s[s.length-1];p&&p.role==="assistant"&&Array.isArray(p.content)?p.content.push(...y):s.push({role:"assistant",content:y.length>0?y:[{type:"text",text:" "}]})}}let a=()=>{let m=t.filter(g=>g?.cache_control).length;for(let g of s)Array.isArray(g.content)&&(m+=g.content.filter(y=>y?.cache_control).length);return m},l=m=>m&&typeof m=="object"?{...m}:{type:"ephemeral"},c=()=>{for(let m=s.length-1;m>=0;m--){let g=s[m]?.content;if(!Array.isArray(g))continue;let y=g.find(p=>p?.cache_control);if(y?.cache_control)return y.cache_control}for(let m=t.length-1;m>=0;m--)if(t[m]?.cache_control)return t[m].cache_control;return{type:"ephemeral"}},i=(m,g)=>{if(!Array.isArray(m?.content)||m.content.some(p=>p?.cache_control))return!1;let y=m.content.find(p=>p&&typeof p=="object"&&!p.cache_control);return y?(y.cache_control=l(g),!0):!1};(()=>{let m=4-a();if(m<=0||s.length===0)return;let g=s,y=c(),p=[];for(let f=g.length-1;f>=0;f--)g[f]?.role!=="user"||!Array.isArray(g[f].content)||p.push(f);for(let f of p){if(m<=0)break;i(g[f],y)&&m--}})();let d={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(t.length>0){let m=t.some(g=>g?.cache_control);d.system=m?t:t.map(g=>g.text||"").join(`
43
+ ${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function ks(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&_t(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&Cc.test(r.model)&&await yt(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let s=n.provider;if(!s&&r?.model){let c=r.model.split(",");c.length>1&&(s=c[0],r.model=c.slice(1).join(","))}let i=s?t.providerService.getProvider(s):void 0;if(!i&&r?.model){let c=t.providerService.resolveModelRoute(r.model);c&&(i=c.provider,r.model=c.targetModel)}if(!i&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[d,...g]=u.split(","),m=t.providerService.getProvider(d);m&&(i=m,r.model=g.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw G(`Provider '${s}' not found`,404,"provider_not_found");n.provider=i.name||s;let l=Sc(n),a=o.endPoint==="/v1/messages"&&l;l&&e.header("X-Codex-Detected","true"),a&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=a,n.codexDetected=l;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&_t(r);let{requestBody:c,config:u,bypass:d}=await Ts(r,i,o,n.headers,{req:n});if(c?.messages&&!d&&!n.isTargetAnthropic){let p=c.messages,f=new Set,_=[],k=[];for(let h of p){if(h?.role!=="system"){k.push(h);continue}let b=JSON.stringify(h.content??"");f.has(b)||(f.add(b),_.push(h))}_.length>0&&k.length>0&&(c.messages=[..._,...k])}let g=await Cs(c,u,i,t,d,o,{req:n});try{i?.baseUrl&&g?.headers&&ut(s,i.baseUrl,g.headers)}catch{}let m=await vs(c,g,i,o,d,{req:n,isCodexOnMessagesEndpoint:a});m=await bs(r,m,i.name||s);let y=xs(m,e,r,t);try{let p=r.model||n.originalModel;s&&p&&U().recordSuccess(s,p)}catch{}return y}catch(c){if(c instanceof ue)throw c;if(!n.__retryAttempted){n.__retryAttempted=!0;try{return await ks(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let u=await vc(n,e,t,o,c);if(u)return u;throw n.__fallbackExhausted=!0,c}}async function bs(n,e,t){if(!n?.stream||!e?.body)return e;let o=e.body.getReader(),r=await o.read();if(r.done)throw o.releaseLock(),G(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");let s=new TextDecoder().decode(r.value);if(s.includes("event: error")){o.releaseLock();let a=s.length<500?s:s.slice(0,500);throw G(`Provider ${t} returned error in SSE stream: ${a}`,400,"provider_response_error")}if(s.split(`
44
+ `).filter(a=>a.startsWith("data:")&&a.trim().length>5).length===0){o.releaseLock();let a=s.length<500?s:s.slice(0,500);throw G(`Provider ${t} returned streaming response with no SSE data lines: ${a}`,400,"provider_response_error")}let l=new ReadableStream({start:a=>{a.enqueue(r.value);let c=()=>{o.read().then(({done:u,value:d})=>{u?a.close():(a.enqueue(d),c())}).catch(u=>a.error(u))};c()},cancel:()=>{o.cancel()}});return new Response(l,{headers:e.headers,status:e.status,statusText:e.statusText})}async function vc(n,e,t,o,r){let s=n.scenarioType||"default",i=n.familyFallback,l=n.modelFamily,a=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),c=U(),u=n.provider||"",d=n.body.model||"",g=new Set,m=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&fn(r.rawBody)||r?.message&&fn(r.message);if(u&&d&&(m?(c.markRateLimited(u,d,120,r?.message),n.log.warn(`Primary model ${u},${d} rate-limited, will try fallbacks`)):c.recordFailure(u,d,r?.message),g.add(`${u},${d}`),t.recordUsage?.({provider:u,model:d,originalModel:n.originalModel||d,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let p=k=>{let[h,...b]=k.split(","),T=h?.trim(),x=b.join(",").trim();return!T||!x?null:{provider:T,model:x,key:`${T},${x}`}},f=[];if(l){let k=i?.[s];if(Array.isArray(k)&&k.length>0)f.push({name:`${l}/${s}`,models:k});else{let h=n.strictProjectRouting;n.log.warn(`No ${l} fallback configured for ${s}; ${h?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(a?.[s])&&a[s].length>0&&f.push({name:`global/${s}`,models:a[s]}),f.length===0&&s!=="image"&&n.body?.messages?.some(b=>b.role==="user"&&Array.isArray(b.content)&&b.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(x=>x.type==="image"||x.type==="image_url")))&&Array.isArray(a?.image)&&a.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),f.push({name:"global/image (auto-detected)",models:a.image})),f.length===0)return null;let _=f.reduce((k,h)=>k+h.models.length,0);n.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${f.length} fallback stage(s)`);for(let k of f){n.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let h of k.models){let b=p(h);if(!b){n.log.warn(`Fallback model '${h}' is invalid, skipping`);continue}if(g.has(b.key))continue;g.add(b.key);let T=t.providerService.getProviders(),x=mt(T,b.provider,b.model);if(!x){n.log.warn(`Fallback model ${h} is not configured or provider is disabled, skipping`);continue}let v=x.provider.name,S=x.model;if(!c.isAvailable(v,S)){n.log.warn(`Fallback model ${h} unavailable (fail pool), skipping`);continue}let C;for(let P=1;P<=2;P++)try{n.log.info(`Trying fallback model: ${v},${S}${P>1?" (retry)":""}`);let R={...n.body};R.model=S;let A={...n,provider:v,body:R},E=x.provider,{requestBody:I,config:L,bypass:F}=await Ts(R,E,o,n.headers,{req:A}),z=await Cs(I,L,E,t,F,o,{req:A});try{E?.baseUrl&&z?.headers&&ut(v,E.baseUrl,z.headers)}catch{}let N=await vs(I,z,E,o,F,{req:A,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1});return N=await bs(R,N,v),n.log.info(`Fallback model ${v},${S} succeeded`),c.recordSuccess(v,S),u&&d&&!n.strictProjectRouting&&(De().promote(u,d,s,v,S),n.log.info(`Promoted fallback model ${v},${S} for ${u},${d}:${s}`),m?n.log.info(`Rate-limited original model ${u},${d} already marked unavailable with cooldown`):(c.forceOpen(u,d,r?.message),n.log.info(`Marked original model ${u},${d} as unavailable`))),n.provider=v,n.body=R,xs(N,e,R,t)}catch(R){if(C=R,P===1){n.log.warn(`Fallback model ${v},${S} failed, retrying once: ${R.message}`);continue}}c.recordFailure(v,S,C?.message),n.log.warn(`Fallback model ${v},${S} failed after retry: ${C?.message}`),t.recordUsage?.({provider:v,model:S,originalModel:n.originalModel||d||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:C?.message||String(C),sessionId:n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Ts(n,e,t,o,r){let s=JSON.parse(JSON.stringify(n)),i=s?.system;if(typeof i=="string"&&i.includes("cch="))s.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let c=0;c<i.length;c++){let u=i[c],d=typeof u=="string"?u:u?.text??"";if(d.includes("cch=")){let g=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof u=="string"?i[c]=g:typeof u?.text=="string"&&(u.text=g)}}let l={},a=!1;if(a=xc(e,t,n),a&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!a&&typeof t.transformRequestOut=="function"){let c=await t.transformRequestOut(s);c.body?(s=c.body,l=c.config||{}):s=c}if(!a&&e.transformer?.use?.length)for(let c of e.transformer.use){if(!c||typeof c.transformRequestIn!="function")continue;let u=await c.transformRequestIn(s,e,r);u.body?(s=u.body,l={...l,...u.config}):s=u}if(!a&&e.transformer?.[n.model]?.use?.length)for(let c of e.transformer[n.model].use)!c||typeof c.transformRequestIn!="function"||(s=await c.transformRequestIn(s,e,r));return{requestBody:s,config:l,bypass:a}}function xc(n,e,t){return e.endPoint==="/v1/chat/completions"&&Array.isArray(t?.system)?!1:n.transformer?.use?.length===1&&n.transformer.use[0].name===e.name&&(!n.transformer?.[t.model]?.use.length||n.transformer?.[t.model]?.use.length===1&&n.transformer?.[t.model]?.use[0].name===e.name)}function Sc(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Cs(n,e,t,o,r,s,i){let l=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let u=o.configService.get("API_TIMEOUT_MS");u&&(e.TIMEOUT=typeof u=="string"?parseInt(u,10):u)}if(r&&typeof s.auth=="function"){let u=await s.auth(n,t);if(u.body){n=u.body;let d=e.headers||{};u.config?.headers&&(d={...d,...u.config.headers},delete d.host,delete u.config.headers),e={...e,...u.config,headers:d}}else n=u}let a={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};for(let u in a)(a[u]==="undefined"||["authorization","Authorization"].includes(u)&&a[u]?.includes("undefined"))&&delete a[u];Xt(o.configService)&&Jr(o.log,i.req.id,{url:String(l),headers:a,body:n});let c=await Kr(l,n,{...e,headers:JSON.parse(JSON.stringify(a)),httpsProxy:le(o.configService,t)},i,o.log);if(!c.ok){let u=await c.text();o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${c.status}): ${u}`);let d=G(`Error from provider(${t.name},${n.model}: ${c.status}): ${u}`,c.status,"provider_response_error");throw d.isRateLimit=c.status===429||fn(u),d.rawBody=u,d}if(c.ok){let u=c.headers.get("content-type")||"",d=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${d} contentType=${u} ok=${c.ok} status=${c.status} hasBody=${!!c.body}`),!d||u.includes("application/json")){let g=c.clone(),m="";try{if(m=await g.text(),!m||m.trim()==="")throw new SyntaxError("Empty JSON body");let y=JSON.parse(m);if(y&&typeof y=="object"&&y.error&&(typeof y.error=="string"||typeof y.error=="object"&&Object.keys(y.error).length>0)){o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${c.status}): ${m}`);let f=fn(m),_=G(`Error from provider(${t.name},${n.model}: ${c.status}): ${m}`,400,"provider_response_error");throw _.isRateLimit=f,_.rawBody=m,_}}catch(y){if(y instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${m}"`);let p=G(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw p.rawBody=m,p}throw y}}}if(!n.stream&&Xt(o.configService)){let d=await c.clone().text();Wr(o.log,i.req.id,{status:c.status,headers:Object.fromEntries(c.headers.entries()),body:d})}return c}async function vs(n,e,t,o,r,s){let i=e;if(!r&&t.transformer?.use?.length)for(let l of Array.from(t.transformer.use).reverse())!l||typeof l.transformResponseOut!="function"||(i=await l.transformResponseOut(i,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let l of Array.from(t.transformer[n.model].use).reverse())!l||typeof l.transformResponseOut!="function"||(i=await l.transformResponseOut(i,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),i=await o.transformResponseIn(i,s)),s?.isCodexOnMessagesEndpoint)try{i=await new He().transformResponseIn(i,{...s,provider:t})}catch(l){console.error("Failed to apply Responses API conversion for codex client:",l)}return i}function xs(n,e,t,o){if(n.ok||e.code(n.status),t.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&Xt(o.configService)){let[s,i]=n.body.tee(),l=Br(o.configService);return Gr(s,o.log,e.request.id,l),e.send(i)}return e.send(n.body)}else return n.json()}function fn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function Rc(n){try{return new URL(n),!0}catch{return!1}}var Cc,Ss,mn=w(()=>{"use strict";Qr();Vt();ct();po();ie();je();tn();Co();Ve();se();Cc=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Ss=async n=>{n.get("/",async()=>({message:"LLMs API",version:en})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:U().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>ks(o,r,n,t));n.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"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:i,models:l}=t.body;if(!r?.trim())throw G("Provider name is required",400,"invalid_request");if(!s||!Rc(s))throw G("Valid base URL is required",400,"invalid_request");if(!i?.trim())throw G("API key is required",400,"invalid_request");if(!l||!Array.isArray(l)||l.length===0)throw G("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw G(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw G("Provider not found",404,"provider_not_found");return o}),n.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"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw G("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw G("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.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,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw G("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var de,gn=w(()=>{"use strict";de=class{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;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 o={};t.transformer&&Object.keys(t.transformer).forEach(r=>{r==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return new i(s[1])}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?new i:i}}).filter(s=>typeof s<"u")):Array.isArray(t.transformer[r]?.use)&&(o[r]={use:t.transformer[r].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return new i(s[1])}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?new i:i}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let i=`${o.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let i=`${o.name},${s}`,l={provider:o.name,model:s,fullModel:i};this.modelRoutes.set(i,l),this.modelRoutes.has(s)||this.modelRoutes.set(s,l)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(i=>i.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var Rs,ws=w(()=>{Rs=n=>n<=0?"none":n<=1024?"low":n<=8192?"medium":"high"});var Ps,Es=w(()=>{Ps=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function wc(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Os(n){let e=[],t=[],o=g=>{if(typeof g=="string"){t.push({type:"text",text:g});return}Array.isArray(g)&&g.forEach(m=>{if(typeof m=="string"){t.push({type:"text",text:m});return}m&&typeof m=="object"&&m.type==="text"&&m.text&&t.push({...m})})},r=()=>{let g=new Map;for(let m=0;m<t.length;m++){let y=t[m],p=y?.text??JSON.stringify(y),f=g.get(p);if(f===void 0){g.set(p,m);continue}!t[f]?.cache_control&&y?.cache_control&&(t[f]=y),t.splice(m,1),m--}};n.messages.forEach(g=>{g.role==="system"?o(g.content):e.push(g)}),r();let s=[];for(let g=0;g<e.length;g++){let m=e[g];if(m.role==="tool"){let y=m.content;try{typeof m.content=="string"&&(y=JSON.parse(m.content))}catch{}y!=null&&typeof y!="object"&&typeof y!="string"&&(y=String(y));let p={type:"tool_result",tool_use_id:m.tool_call_id,content:y};m.cache_control&&(p.cache_control=m.cache_control);let f=s[s.length-1];f&&f.role==="user"&&Array.isArray(f.content)?f.content.push(p):s.push({role:"user",content:[p]})}else if(m.role==="user"){let y=[];typeof m.content=="string"?y.push({type:"text",text:m.content}):Array.isArray(m.content)&&m.content.forEach(f=>{f&&typeof f=="object"&&f.type==="image_url"&&f.image_url?.url?y.push({type:"image",source:{type:"base64",media_type:f.media_type||"image/jpeg",data:f.image_url.url.split(",")[1]||f.image_url.url}}):y.push(f)});let p=s[s.length-1];p&&p.role==="user"&&Array.isArray(p.content)?p.content.push(...y):s.push({role:"user",content:y.length>0?y:[{type:"text",text:" "}]})}else if(m.role==="assistant"){let y=[];m.content&&(typeof m.content=="string"?y.push({type:"text",text:m.content}):Array.isArray(m.content)&&y.push(...m.content)),m.tool_calls&&m.tool_calls.length>0&&m.tool_calls.forEach(f=>{let _={};try{_=JSON.parse(f.function.arguments)}catch{_=f.function.arguments}y.push({type:"tool_use",id:f.id,name:f.function.name,input:_})}),m.thinking&&y.unshift({type:"thinking",thinking:m.thinking.content,signature:m.thinking.signature});let p=s[s.length-1];p&&p.role==="assistant"&&Array.isArray(p.content)?p.content.push(...y):s.push({role:"assistant",content:y.length>0?y:[{type:"text",text:" "}]})}}let i=()=>{let g=t.filter(m=>m?.cache_control).length;for(let m of s)Array.isArray(m.content)&&(g+=m.content.filter(y=>y?.cache_control).length);return g},l=g=>g&&typeof g=="object"?{...g}:{type:"ephemeral"},a=()=>{for(let g=s.length-1;g>=0;g--){let m=s[g]?.content;if(!Array.isArray(m))continue;let y=m.find(p=>p?.cache_control);if(y?.cache_control)return y.cache_control}for(let g=t.length-1;g>=0;g--)if(t[g]?.cache_control)return t[g].cache_control;return{type:"ephemeral"}},c=(g,m)=>{if(!Array.isArray(g?.content)||g.content.some(p=>p?.cache_control))return!1;let y=g.content.find(p=>p&&typeof p=="object"&&!p.cache_control);return y?(y.cache_control=l(m),!0):!1};(()=>{let g=4-i();if(g<=0||s.length===0)return;let m=s,y=a(),p=[];for(let f=m.length-1;f>=0;f--)m[f]?.role!=="user"||!Array.isArray(m[f].content)||p.push(f);for(let f of p){if(g<=0)break;c(m[f],y)&&g--}})();let d={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(t.length>0){let g=t.some(m=>m?.cache_control);d.system=g?t:t.map(m=>m.text||"").join(`
45
45
 
46
- `)}return n.tools&&n.tools.length>0&&(d.tools=Xc(n.tools),n.tool_choice&&(n.tool_choice==="auto"?d.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?d.tool_choice={type:"any"}:typeof n.tool_choice=="string"?d.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(d.tool_choice={type:"tool",name:n.tool_choice.function.name}))),d}var zs=P(()=>{});var xn,Cn,Hs=P(()=>{"use strict";xn=require("uuid");Fs();en();Ds();zs();Cn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}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 s=e.system.filter(a=>a.type==="text"&&a.text).map(a=>({type:"text",text:a.text,cache_control:a.cache_control}));t.push({role:"system",content:s})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(s=>{s.role==="system"&&t.push({role:"system",content:s.content})}),o?.forEach(s=>{if(s.role!=="system"&&(s.role==="user"||s.role==="assistant")){if(typeof s.content=="string"){t.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let a=s.content.filter(c=>c.type==="tool_result"&&c.tool_use_id);a.length&&a.forEach(c=>{let i={role:"tool",content:typeof c.content=="string"?c.content:JSON.stringify(c.content),tool_call_id:c.tool_use_id,cache_control:c.cache_control};t.push(i)});let l=s.content.filter(c=>c.type==="text"&&c.text||c.type==="image"&&c.source);l.length&&t.push({role:"user",content:l.map(c=>c?.type==="image"?{type:"image_url",image_url:{url:c.source?.type==="base64"?Us(c.source.data,c.source.media_type):c.source.url},media_type:c.source.media_type}:c)})}else if(s.role==="assistant"){let a={role:"assistant",content:""},l=s.content.filter(u=>u.type==="text"&&u.text);l.length&&(a.content=l.map(u=>u.text).join(`
47
- `));let c=s.content.filter(u=>u.type==="tool_use"&&u.id);c.length&&(a.tool_calls=c.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input||{})}})));let i=s.content.find(u=>u.type==="thinking");i&&(a.thinking={content:i.thinking,signature:i.signature}),t.push(a)}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:Ls(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 transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=js(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;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(),s=this.convertOpenAIResponseToAnthropic(r,t);return new Response(JSON.stringify(s),{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 s=new TextEncoder,a=`msg_${Date.now()}`,l=null,c="unknown",i=!1,u=!1,d=!1,m=new Map,g=new Map,y=0,p=0,f=0,_=!1,k=!1,h=0,b=-1,x=()=>{let T=h;return h++,T},v=T=>{if(!_)try{r.enqueue(T);let O=new TextDecoder().decode(T);this.logger.debug({reqId:t.req.id,data:O,type:"send data"})}catch(O){if(O instanceof TypeError&&O.message.includes("Controller is already closed"))_=!0;else throw this.logger.debug({reqId:t.req.id,error:O instanceof Error?O.message:String(O),type:"send data error"}),O}},C=()=>{if(!_)try{if(!i){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),_=!0;return}if(b>=0){let O={type:"content_block_stop",index:b};v(s.encode(`event: content_block_stop
48
- data: ${JSON.stringify(O)}
46
+ `)}return n.tools&&n.tools.length>0&&(d.tools=wc(n.tools),n.tool_choice&&(n.tool_choice==="auto"?d.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?d.tool_choice={type:"any"}:typeof n.tool_choice=="string"?d.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(d.tool_choice={type:"tool",name:n.tool_choice.function.name}))),d}var As=w(()=>{});var hn,yn,Is=w(()=>{"use strict";hn=require("uuid");ws();Vt();Es();As();yn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}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 s=e.system.filter(i=>i.type==="text"&&i.text).map(i=>({type:"text",text:i.text,cache_control:i.cache_control}));t.push({role:"system",content:s})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(s=>{s.role==="system"&&t.push({role:"system",content:s.content})}),o?.forEach(s=>{if(s.role!=="system"&&(s.role==="user"||s.role==="assistant")){if(typeof s.content=="string"){t.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let i=s.content.filter(a=>a.type==="tool_result"&&a.tool_use_id);i.length&&i.forEach(a=>{let c={role:"tool",content:typeof a.content=="string"?a.content:JSON.stringify(a.content),tool_call_id:a.tool_use_id,cache_control:a.cache_control};t.push(c)});let l=s.content.filter(a=>a.type==="text"&&a.text||a.type==="image"&&a.source);l.length&&t.push({role:"user",content:l.map(a=>a?.type==="image"?{type:"image_url",image_url:{url:a.source?.type==="base64"?Ps(a.source.data,a.source.media_type):a.source.url},media_type:a.source.media_type}:a)})}else if(s.role==="assistant"){let i={role:"assistant",content:""},l=s.content.filter(u=>u.type==="text"&&u.text);l.length&&(i.content=l.map(u=>u.text).join(`
47
+ `));let a=s.content.filter(u=>u.type==="tool_use"&&u.id);a.length&&(i.tool_calls=a.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input||{})}})));let c=s.content.find(u=>u.type==="thinking");c&&(i.thinking={content:c.thinking,signature:c.signature}),t.push(i)}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:Rs(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 transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=Os(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;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(),s=this.convertOpenAIResponseToAnthropic(r,t);return new Response(JSON.stringify(s),{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 s=new TextEncoder,i=`msg_${Date.now()}`,l=null,a="unknown",c=!1,u=!1,d=!1,g=new Map,m=new Map,y=0,p=0,f=0,_=!1,k=!1,h=0,b=-1,T=()=>{let C=h;return h++,C},x=C=>{if(!_)try{r.enqueue(C);let P=new TextDecoder().decode(C);this.logger.debug({reqId:t.req.id,data:P,type:"send data"})}catch(P){if(P instanceof TypeError&&P.message.includes("Controller is already closed"))_=!0;else throw this.logger.debug({reqId:t.req.id,error:P instanceof Error?P.message:String(P),type:"send data error"}),P}},v=()=>{if(!_)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),_=!0;return}if(b>=0){let P={type:"content_block_stop",index:b};x(s.encode(`event: content_block_stop
48
+ data: ${JSON.stringify(P)}
49
49
 
50
- `)),b=-1}if(l)v(s.encode(`event: message_delta
50
+ `)),b=-1}if(l)x(s.encode(`event: message_delta
51
51
  data: ${JSON.stringify(l)}
52
52
 
53
- `)),l=null;else{let O=t?.req?.tokenCount||0;v(s.encode(`event: message_delta
54
- data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:O,output_tokens:0,cache_read_input_tokens:0}})}
53
+ `)),l=null;else{let P=t?.req?.tokenCount||0;x(s.encode(`event: message_delta
54
+ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:P,output_tokens:0,cache_read_input_tokens:0}})}
55
55
 
56
- `))}let T={type:"message_stop"};v(s.encode(`event: message_stop
57
- data: ${JSON.stringify(T)}
56
+ `))}let C={type:"message_stop"};x(s.encode(`event: message_stop
57
+ data: ${JSON.stringify(C)}
58
58
 
59
- `)),r.close(),_=!0}catch(T){if(T instanceof TypeError&&T.message.includes("Controller is already closed"))_=!0;else throw T}},R=null;try{R=e.getReader();let T=new TextDecoder,O="";for(;!_;){let{done:w,value:E}=await R.read();if(w)break;O+=T.decode(E,{stream:!0});let A=O.split(`
60
- `);O=A.pop()||"";for(let I of A){if(_)break;if(!I.startsWith("data:"))continue;let L=I.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:L}),L!=="[DONE]")try{let U=JSON.parse(L);if(y++,this.logger.debug({reqId:t.req.id,response:U,tppe:"Original Response"}),U.error){t?.req&&(t.req.sseError=U.error);let N={type:"error",message:{type:"api_error",message:JSON.stringify(U.error)}};v(s.encode(`event: error
59
+ `)),r.close(),_=!0}catch(C){if(C instanceof TypeError&&C.message.includes("Controller is already closed"))_=!0;else throw C}},S=null;try{S=e.getReader();let C=new TextDecoder,P="";for(;!_;){let{done:R,value:A}=await S.read();if(R)break;P+=C.decode(A,{stream:!0});let E=P.split(`
60
+ `);P=E.pop()||"";for(let I of E){if(_)break;if(!I.startsWith("data:"))continue;let L=I.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:L}),L!=="[DONE]")try{let F=JSON.parse(L);if(y++,this.logger.debug({reqId:t.req.id,response:F,tppe:"Original Response"}),F.error){t?.req&&(t.req.sseError=F.error);let N={type:"error",message:{type:"api_error",message:JSON.stringify(F.error)}};x(s.encode(`event: error
61
61
  data: ${JSON.stringify(N)}
62
62
 
63
- `));continue}if(c=U.model||c,!i&&!_&&!d){i=!0;let N=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:c,stop_reason:null,stop_sequence:null,usage:{input_tokens:N,output_tokens:0}}};v(s.encode(`event: message_start
64
- data: ${JSON.stringify(F)}
63
+ `));continue}if(a=F.model||a,!c&&!_&&!d){c=!0;let N=t?.req?.tokenCount||0,D={type:"message_start",message:{id:i,type:"message",role:"assistant",content:[],model:a,stop_reason:null,stop_sequence:null,usage:{input_tokens:N,output_tokens:0}}};x(s.encode(`event: message_start
64
+ data: ${JSON.stringify(D)}
65
65
 
66
- `))}let J=U.choices?.[0];if(U.usage){let N=U.usage?.prompt_tokens_details?.cached_tokens||0,Q=(U.usage?.prompt_tokens||0)-N,we=U.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:U.usage,mappedUsage:{input_tokens:Q,output_tokens:we,cache_read_input_tokens:N},choicesLength:Array.isArray(U.choices)?U.choices.length:void 0,finishReason:J?.finish_reason});let H={input_tokens:Q,output_tokens:we,cache_read_input_tokens:N};if(!l)l={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...H}};else{let oe=l.usage||{};l.usage={input_tokens:H.input_tokens||oe.input_tokens||0,output_tokens:H.output_tokens||oe.output_tokens||0,cache_read_input_tokens:H.cache_read_input_tokens||oe.cache_read_input_tokens||0}}}if(!J)continue;if(J?.delta?.thinking&&!_&&!d&&!u){if(!k){let N=x(),F={type:"content_block_start",index:N,content_block:{type:"thinking",thinking:""}};v(s.encode(`event: content_block_start
67
- data: ${JSON.stringify(F)}
66
+ `))}let z=F.choices?.[0];if(F.usage){let N=F.usage?.prompt_tokens_details?.cached_tokens||0,K=(F.usage?.prompt_tokens||0)-N,Ce=F.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:F.usage,mappedUsage:{input_tokens:K,output_tokens:Ce,cache_read_input_tokens:N},choicesLength:Array.isArray(F.choices)?F.choices.length:void 0,finishReason:z?.finish_reason});let H={input_tokens:K,output_tokens:Ce,cache_read_input_tokens:N};if(!l)l={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...H}};else{let te=l.usage||{};l.usage={input_tokens:H.input_tokens||te.input_tokens||0,output_tokens:H.output_tokens||te.output_tokens||0,cache_read_input_tokens:H.cache_read_input_tokens||te.cache_read_input_tokens||0}}}if(!z)continue;if(z?.delta?.thinking&&!_&&!d&&!u){if(!k){let N=T(),D={type:"content_block_start",index:N,content_block:{type:"thinking",thinking:""}};x(s.encode(`event: content_block_start
67
+ data: ${JSON.stringify(D)}
68
68
 
69
- `)),b=N,k=!0}if(J.delta.thinking.signature){let N={type:"content_block_delta",index:b,delta:{type:"signature_delta",signature:J.delta.thinking.signature}};v(s.encode(`event: content_block_delta
69
+ `)),b=N,k=!0}if(z.delta.thinking.signature){let N={type:"content_block_delta",index:b,delta:{type:"signature_delta",signature:z.delta.thinking.signature}};x(s.encode(`event: content_block_delta
70
70
  data: ${JSON.stringify(N)}
71
71
 
72
- `));let F={type:"content_block_stop",index:b};v(s.encode(`event: content_block_stop
73
- data: ${JSON.stringify(F)}
72
+ `));let D={type:"content_block_stop",index:b};x(s.encode(`event: content_block_stop
73
+ data: ${JSON.stringify(D)}
74
74
 
75
- `)),b=-1}else if(J.delta.thinking.content){let N={type:"content_block_delta",index:b,delta:{type:"thinking_delta",thinking:J.delta.thinking.content||""}};v(s.encode(`event: content_block_delta
75
+ `)),b=-1}else if(z.delta.thinking.content){let N={type:"content_block_delta",index:b,delta:{type:"thinking_delta",thinking:z.delta.thinking.content||""}};x(s.encode(`event: content_block_delta
76
76
  data: ${JSON.stringify(N)}
77
77
 
78
- `))}}if(J?.delta?.content&&!_&&!d){if(p++,b>=0&&!u){let F={type:"content_block_stop",index:b};v(s.encode(`event: content_block_stop
79
- data: ${JSON.stringify(F)}
78
+ `))}}if(z?.delta?.content&&!_&&!d){if(p++,b>=0&&!u){let D={type:"content_block_stop",index:b};x(s.encode(`event: content_block_stop
79
+ data: ${JSON.stringify(D)}
80
80
 
81
- `)),b=-1}if(!u&&!d){u=!0;let N=x(),F={type:"content_block_start",index:N,content_block:{type:"text",text:""}};v(s.encode(`event: content_block_start
82
- data: ${JSON.stringify(F)}
81
+ `)),b=-1}if(!u&&!d){u=!0;let N=T(),D={type:"content_block_start",index:N,content_block:{type:"text",text:""}};x(s.encode(`event: content_block_start
82
+ data: ${JSON.stringify(D)}
83
83
 
84
- `)),b=N}if(!_&&!d){let N={type:"content_block_delta",index:b,delta:{type:"text_delta",text:J.delta.content}};v(s.encode(`event: content_block_delta
84
+ `)),b=N}if(!_&&!d){let N={type:"content_block_delta",index:b,delta:{type:"text_delta",text:z.delta.content}};x(s.encode(`event: content_block_delta
85
85
  data: ${JSON.stringify(N)}
86
86
 
87
- `))}}if(J?.delta?.annotations?.length&&!_&&!d){if(b>=0&&u){let N={type:"content_block_stop",index:b};v(s.encode(`event: content_block_stop
87
+ `))}}if(z?.delta?.annotations?.length&&!_&&!d){if(b>=0&&u){let N={type:"content_block_stop",index:b};x(s.encode(`event: content_block_stop
88
88
  data: ${JSON.stringify(N)}
89
89
 
90
- `)),b=-1,u=!1}J?.delta?.annotations.forEach(N=>{let F=x(),Q={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${(0,xn.v4)()}`,content:[{type:"web_search_result",title:N.url_citation.title,url:N.url_citation.url}]}};v(s.encode(`event: content_block_start
91
- data: ${JSON.stringify(Q)}
90
+ `)),b=-1,u=!1}z?.delta?.annotations.forEach(N=>{let D=T(),K={type:"content_block_start",index:D,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${(0,hn.v4)()}`,content:[{type:"web_search_result",title:N.url_citation.title,url:N.url_citation.url}]}};x(s.encode(`event: content_block_start
91
+ data: ${JSON.stringify(K)}
92
92
 
93
- `));let we={type:"content_block_stop",index:F};v(s.encode(`event: content_block_stop
94
- data: ${JSON.stringify(we)}
93
+ `));let Ce={type:"content_block_stop",index:D};x(s.encode(`event: content_block_stop
94
+ data: ${JSON.stringify(Ce)}
95
95
 
96
- `)),b=-1})}if(J?.delta?.tool_calls&&!_&&!d){f++;let N=new Set;for(let F of J.delta.tool_calls){if(_)break;let Q=F.index??0;if(N.has(Q))continue;if(N.add(Q),!g.has(Q)){if(b>=0){let Ka={type:"content_block_stop",index:b};v(s.encode(`event: content_block_stop
97
- data: ${JSON.stringify(Ka)}
96
+ `)),b=-1})}if(z?.delta?.tool_calls&&!_&&!d){f++;let N=new Set;for(let D of z.delta.tool_calls){if(_)break;let K=D.index??0;if(N.has(K))continue;if(N.add(K),!m.has(K)){if(b>=0){let wa={type:"content_block_stop",index:b};x(s.encode(`event: content_block_stop
97
+ data: ${JSON.stringify(wa)}
98
98
 
99
- `)),b=-1}let H=x();g.set(Q,H);let oe=F.id||`call_ccr_${Q}`,B=F.function?.name||`tool_${Q}`,M={type:"content_block_start",index:H,content_block:{type:"tool_use",id:oe,name:B,input:{}}};v(s.encode(`event: content_block_start
99
+ `)),b=-1}let H=T();m.set(K,H);let te=D.id||`call_ccr_${K}`,B=D.function?.name||`tool_${K}`,M={type:"content_block_start",index:H,content_block:{type:"tool_use",id:te,name:B,input:{}}};x(s.encode(`event: content_block_start
100
100
  data: ${JSON.stringify(M)}
101
101
 
102
- `)),b=H;let G={id:oe,name:B,arguments:"",contentBlockIndex:H};m.set(Q,G)}else if(F.id&&F.function?.name){let H=m.get(Q);H.id.startsWith("call_")&&H.name.startsWith("tool_")&&(H.id=F.id,H.name=F.function.name)}if(F.function?.arguments&&!_&&!d){let H=g.get(Q);if(H===void 0)continue;let oe=m.get(Q);oe&&(oe.arguments+=F.function.arguments);try{let B={type:"content_block_delta",index:H,delta:{type:"input_json_delta",partial_json:F.function.arguments}};v(s.encode(`event: content_block_delta
102
+ `)),b=H;let W={id:te,name:B,arguments:"",contentBlockIndex:H};g.set(K,W)}else if(D.id&&D.function?.name){let H=g.get(K);H.id.startsWith("call_")&&H.name.startsWith("tool_")&&(H.id=D.id,H.name=D.function.name)}if(D.function?.arguments&&!_&&!d){let H=m.get(K);if(H===void 0)continue;let te=g.get(K);te&&(te.arguments+=D.function.arguments);try{let B={type:"content_block_delta",index:H,delta:{type:"input_json_delta",partial_json:D.function.arguments}};x(s.encode(`event: content_block_delta
103
103
  data: ${JSON.stringify(B)}
104
104
 
105
- `))}catch{try{let B=F.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),M={type:"content_block_delta",index:H,delta:{type:"input_json_delta",partial_json:B}};v(s.encode(`event: content_block_delta
105
+ `))}catch{try{let B=D.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),M={type:"content_block_delta",index:H,delta:{type:"input_json_delta",partial_json:B}};x(s.encode(`event: content_block_delta
106
106
  data: ${JSON.stringify(M)}
107
107
 
108
- `))}catch(B){console.error(B)}}}}}if(J?.finish_reason&&!_&&!d){if(p===0&&f===0&&console.error("Warning: No content in the stream response!"),b>=0){let N={type:"content_block_stop",index:b};v(s.encode(`event: content_block_stop
108
+ `))}catch(B){console.error(B)}}}}}if(z?.finish_reason&&!_&&!d){if(p===0&&f===0&&console.error("Warning: No content in the stream response!"),b>=0){let N={type:"content_block_stop",index:b};x(s.encode(`event: content_block_stop
109
109
  data: ${JSON.stringify(N)}
110
110
 
111
- `)),b=-1}if(!_){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[J.finish_reason]||"end_turn";l?l.delta={...l.delta,stop_reason:F,stop_sequence:null}:l={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}d=!0}}catch(U){this.logger?.error(`parseError: ${U.name} message: ${U.message} stack: ${U.stack} data: ${L}`)}}}C()}catch(T){if(!_)try{r.error(T)}catch(O){console.error(O)}}finally{if(R)try{R.releaseLock()}catch(T){console.error(T)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let c=`srvtoolu_${(0,xn.v4)()}`;r.push({type:"server_tool_use",id:c,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:c,content:o.message.annotations.map(i=>({type:"web_search_result",url:i.url_citation.url,title:i.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(c=>{let i={};try{let u=c.function.arguments||"{}";typeof u=="object"?i=u:typeof u=="string"&&(i=JSON.parse(u))}catch{i={text:c.function.arguments||""}}r.push({type:"tool_use",id:c.id,name:c.function.name,input:i})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,a=(e.usage?.prompt_tokens||0)-s,l={id:e.id?.startsWith("msg_")?e.id:`msg_${(0,xn.v4)().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:l},"Conversion complete, final Anthropic response"),l}catch{throw V(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Yc(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ye).includes(o)?o:Ye.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ye).includes(r)?r:Ye.TYPE_UNSPECIFIED})}}}function Ct(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&Yc(n.type,e);for(let[a,l]of Object.entries(n))if(l!=null)if(a=="type"){if(l==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(l))continue;let c=l.toUpperCase();e.type=Object.values(Ye).includes(c)?c:Ye.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=Ct(l);else if(o.includes(a)){let c=[];for(let i of l){if(i.type=="null"){e.nullable=!0;continue}c.push(Ct(i))}e[a]=c}else if(r.includes(a)){let c={};for(let[i,u]of Object.entries(l))c[i]=Ct(u);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=l}return e}function qc(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Ct(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Ct(e.response));return n}function Tn(n){let e=[],t=n.tools?.filter(c=>c.function.name!=="web_search")?.map(c=>({name:c.function.name,description:c.function.description,parametersJsonSchema:c.function.parameters}));t?.length&&e.push(qc({functionDeclarations:t})),n.tools?.find(c=>c.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(c=>c.role==="tool");n.messages.filter(c=>c.role!=="tool").forEach(c=>{let i;c.role==="assistant"?i="model":(["user","system"].includes(c.role),i="user");let u=[];if(typeof c.content=="string"){let d={text:c.content};c.thinking?.signature&&(d.thoughtSignature=c.thinking.signature),u.push(d)}else Array.isArray(c.content)?u.push(...c.content.map(d=>{if(d.type==="text")return{text:d.text||""};if(d.type==="image_url")return d.image_url.url.startsWith("http")?{file_data:{mime_type:d.media_type,file_uri:d.image_url.url}}:{inlineData:{mime_type:d.media_type,data:d.image_url.url?.split(",")?.pop()||d.image_url.url}}})):c.content&&typeof c.content=="object"&&(c.content.text?u.push({text:c.content.text}):u.push({text:JSON.stringify(c.content)}));if(Array.isArray(c.tool_calls)&&u.push(...c.tool_calls.map(d=>{let m={functionCall:{id:d.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:d.function.name,args:JSON.parse(d.function.arguments||"{}")}};return c.thinking?.signature&&(m.thoughtSignature=c.thinking.signature),m})),u.length===0&&u.push({text:""}),r.push({role:i,parts:u}),i==="model"&&c.tool_calls){let d=c.tool_calls.map(m=>{let g=s.find(y=>y.tool_call_id===m.id);return{functionResponse:{name:m?.function?.name,response:{result:g?.content}}}});r.push({role:"user",parts:d})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let c=n.model.includes("pro")?[128,32768]:[0,24576],i,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=c[0]&&u<=c[1]?i=u:u<c[0]?i=c[0]:u>c[1]&&(i=c[1]),a.thinkingConfig.thinkingBudget=i)}let l={contents:r,tools:e.length?e:void 0,generationConfig:a};if(n.tool_choice){let c={functionCallingConfig:{}};n.tool_choice==="auto"?c.functionCallingConfig.mode="auto":n.tool_choice==="none"?c.functionCallingConfig.mode="none":n.tool_choice==="required"?c.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(c.functionCallingConfig.mode="any",c.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),l.toolConfig=c}return l}function vn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,l=n.tool_choice,c={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:l};return Array.isArray(e)&&e.forEach(i=>{typeof i=="string"?c.messages.push({role:"user",content:i}):typeof i.text=="string"?c.messages.push({role:"user",content:i.text||null}):i.role==="user"?c.messages.push({role:"user",content:i?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):i.role==="model"&&c.messages.push({role:"assistant",content:i?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(c.tools=[],t.forEach(i=>{Array.isArray(i.functionDeclarations)&&i.functionDeclarations.forEach(u=>{c.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),c}async function Rn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],l=[];for(let d of a)d.text&&d.thought===!0?r+=d.text:l.push(d);s=a.find(d=>d.thoughtSignature)?.thoughtSignature;let c=l?.filter(d=>d.functionCall)?.map(d=>({id:d.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:d.functionCall?.name,arguments:JSON.stringify(d.functionCall?.args||{})}}))||[],i=l?.filter(d=>d.text)?.map(d=>d.text)?.join(`
112
- `)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:i,role:"assistant",tool_calls:c.length>0?c:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,l=!1,c="",i=0,u=-1,d=new ReadableStream({async start(m){let g=async(f,_)=>{if(f.startsWith("data: ")){let k=f.slice(6).trim();if(k){t?.debug({chunkStr:k},`${e} chunk:`);try{let h=JSON.parse(k);if(!h.candidates||!h.candidates[0]){t?.debug({chunkStr:k},"Invalid chunk structure");return}let b=h.candidates[0],x=b.content?.parts||[];x.filter(T=>T.text&&T.thought===!0).forEach(T=>{l||(l=!0);let O={choices:[{delta:{role:"assistant",content:null,thinking:{content:T.text}},finish_reason:null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(O)}
111
+ `)),b=-1}if(!_){let D={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[z.finish_reason]||"end_turn";l?l.delta={...l.delta,stop_reason:D,stop_sequence:null}:l={type:"message_delta",delta:{stop_reason:D,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}d=!0}}catch(F){this.logger?.error(`parseError: ${F.name} message: ${F.message} stack: ${F.stack} data: ${L}`)}}}v()}catch(C){if(!_)try{r.error(C)}catch(P){console.error(P)}}finally{if(S)try{S.releaseLock()}catch(C){console.error(C)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let a=`srvtoolu_${(0,hn.v4)()}`;r.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:a,content:o.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(a=>{let c={};try{let u=a.function.arguments||"{}";typeof u=="object"?c=u:typeof u=="string"&&(c=JSON.parse(u))}catch{c={text:a.function.arguments||""}}r.push({type:"tool_use",id:a.id,name:a.function.name,input:c})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,i=(e.usage?.prompt_tokens||0)-s,l={id:e.id?.startsWith("msg_")?e.id:`msg_${(0,hn.v4)().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:i,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:l},"Conversion complete, final Anthropic response"),l}catch{throw G(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Pc(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ye).includes(o)?o:Ye.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ye).includes(r)?r:Ye.TYPE_UNSPECIFIED})}}}function kt(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&Pc(n.type,e);for(let[i,l]of Object.entries(n))if(l!=null)if(i=="type"){if(l==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(l))continue;let a=l.toUpperCase();e.type=Object.values(Ye).includes(a)?a:Ye.TYPE_UNSPECIFIED}else if(t.includes(i))e[i]=kt(l);else if(o.includes(i)){let a=[];for(let c of l){if(c.type=="null"){e.nullable=!0;continue}a.push(kt(c))}e[i]=a}else if(r.includes(i)){let a={};for(let[c,u]of Object.entries(l))a[c]=kt(u);e[i]=a}else{if(i==="additionalProperties")continue;e[i]=l}return e}function Ec(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=kt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=kt(e.response));return n}function _n(n){let e=[],t=n.tools?.filter(a=>a.function.name!=="web_search")?.map(a=>({name:a.function.name,description:a.function.description,parametersJsonSchema:a.function.parameters}));t?.length&&e.push(Ec({functionDeclarations:t})),n.tools?.find(a=>a.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(a=>a.role==="tool");n.messages.filter(a=>a.role!=="tool").forEach(a=>{let c;a.role==="assistant"?c="model":(["user","system"].includes(a.role),c="user");let u=[];if(typeof a.content=="string"){let d={text:a.content};a.thinking?.signature&&(d.thoughtSignature=a.thinking.signature),u.push(d)}else Array.isArray(a.content)?u.push(...a.content.map(d=>{if(d.type==="text")return{text:d.text||""};if(d.type==="image_url")return d.image_url.url.startsWith("http")?{file_data:{mime_type:d.media_type,file_uri:d.image_url.url}}:{inlineData:{mime_type:d.media_type,data:d.image_url.url?.split(",")?.pop()||d.image_url.url}}})):a.content&&typeof a.content=="object"&&(a.content.text?u.push({text:a.content.text}):u.push({text:JSON.stringify(a.content)}));if(Array.isArray(a.tool_calls)&&u.push(...a.tool_calls.map(d=>{let g={functionCall:{id:d.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:d.function.name,args:JSON.parse(d.function.arguments||"{}")}};return a.thinking?.signature&&(g.thoughtSignature=a.thinking.signature),g})),u.length===0&&u.push({text:""}),r.push({role:c,parts:u}),c==="model"&&a.tool_calls){let d=a.tool_calls.map(g=>{let m=s.find(y=>y.tool_call_id===g.id);return{functionResponse:{name:g?.function?.name,response:{result:m?.content}}}});r.push({role:"user",parts:d})}});let i={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(i.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))i.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let a=n.model.includes("pro")?[128,32768]:[0,24576],c,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=a[0]&&u<=a[1]?c=u:u<a[0]?c=a[0]:u>a[1]&&(c=a[1]),i.thinkingConfig.thinkingBudget=c)}let l={contents:r,tools:e.length?e:void 0,generationConfig:i};if(n.tool_choice){let a={functionCallingConfig:{}};n.tool_choice==="auto"?a.functionCallingConfig.mode="auto":n.tool_choice==="none"?a.functionCallingConfig.mode="none":n.tool_choice==="required"?a.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(a.functionCallingConfig.mode="any",a.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),l.toolConfig=a}return l}function kn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,i=n.stream,l=n.tool_choice,a={messages:[],model:o,max_tokens:r,temperature:s,stream:i,tool_choice:l};return Array.isArray(e)&&e.forEach(c=>{typeof c=="string"?a.messages.push({role:"user",content:c}):typeof c.text=="string"?a.messages.push({role:"user",content:c.text||null}):c.role==="user"?a.messages.push({role:"user",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):c.role==="model"&&a.messages.push({role:"assistant",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(a.tools=[],t.forEach(c=>{Array.isArray(c.functionDeclarations)&&c.functionDeclarations.forEach(u=>{a.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),a}async function bn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",i=o.candidates[0]?.content?.parts||[],l=[];for(let d of i)d.text&&d.thought===!0?r+=d.text:l.push(d);s=i.find(d=>d.thoughtSignature)?.thoughtSignature;let a=l?.filter(d=>d.functionCall)?.map(d=>({id:d.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:d.functionCall?.name,arguments:JSON.stringify(d.functionCall?.args||{})}}))||[],c=l?.filter(d=>d.text)?.map(d=>d.text)?.join(`
112
+ `)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:c,role:"assistant",tool_calls:a.length>0?a:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,i=!1,l=!1,a="",c=0,u=-1,d=new ReadableStream({async start(g){let m=async(f,_)=>{if(f.startsWith("data: ")){let k=f.slice(6).trim();if(k){t?.debug({chunkStr:k},`${e} chunk:`);try{let h=JSON.parse(k);if(!h.candidates||!h.candidates[0]){t?.debug({chunkStr:k},"Invalid chunk structure");return}let b=h.candidates[0],T=b.content?.parts||[];T.filter(C=>C.text&&C.thought===!0).forEach(C=>{l||(l=!0);let P={choices:[{delta:{role:"assistant",content:null,thinking:{content:C.text}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(P)}
113
113
 
114
- `))});let v=x.find(T=>T.thoughtSignature)?.thoughtSignature;if(v&&!s){if(!l){let O={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(O)}
114
+ `))});let x=T.find(C=>C.thoughtSignature)?.thoughtSignature;if(x&&!s){if(!l){let P={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(P)}
115
115
 
116
- `))}let T={choices:[{delta:{role:"assistant",content:null,thinking:{signature:v}},finish_reason:null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(_.enqueue(r.encode(`data: ${JSON.stringify(T)}
116
+ `))}let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:x}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(_.enqueue(r.encode(`data: ${JSON.stringify(C)}
117
117
 
118
- `)),s=!0,i++,c){let O={choices:[{delta:{role:"assistant",content:c},finish_reason:null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(O)}
118
+ `)),s=!0,c++,a){let P={choices:[{delta:{role:"assistant",content:a},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(P)}
119
119
 
120
- `)),c="",a||(a=!0)}}let C=x.filter(T=>T.functionCall).map(T=>({id:T.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:T.functionCall?.name,arguments:JSON.stringify(T.functionCall?.args||{})}})),R=x.filter(T=>T.text&&T.thought!==!0).map(T=>T.text).join(`
121
- `);if(!R&&s&&!a){let T={choices:[{delta:{role:"assistant",content:"(no content)"},index:i,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(T)}
120
+ `)),a="",i||(i=!0)}}let v=T.filter(C=>C.functionCall).map(C=>({id:C.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})}})),S=T.filter(C=>C.text&&C.thought!==!0).map(C=>C.text).join(`
121
+ `);if(!S&&s&&!i){let C={choices:[{delta:{role:"assistant",content:"(no content)"},index:c,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(C)}
122
122
 
123
- `)),a||(a=!0)}if(l&&R&&!s)if(h.modelVersion.includes("3")){c+=R;return}else{let T={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(T)}
123
+ `)),i||(i=!0)}if(l&&S&&!s)if(h.modelVersion.includes("3")){a+=S;return}else{let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(C)}
124
124
 
125
- `)),s=!0}if(R){c||i++;let T={choices:[{delta:{role:"assistant",content:R},finish_reason:b.finishReason?.toLowerCase()||null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:h.usageMetadata?.candidatesTokenCount||0,prompt_tokens:h.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:h.usageMetadata?.cachedContentTokenCount||0},total_tokens:h.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:h.usageMetadata?.thoughtsTokenCount||0}}};b?.groundingMetadata?.groundingChunks?.length&&(T.choices[0].delta.annotations=b.groundingMetadata.groundingChunks.map((O,w)=>{let E=b?.groundingMetadata?.groundingSupports?.filter(A=>A.groundingChunkIndices?.includes(w));return{type:"url_citation",url_citation:{url:O?.web?.uri||"",title:O?.web?.title||"",content:E?.[0]?.segment?.text||"",start_index:E?.[0]?.segment?.startIndex||0,end_index:E?.[0]?.segment?.endIndex||0}}})),_.enqueue(r.encode(`data: ${JSON.stringify(T)}
125
+ `)),s=!0}if(S){a||c++;let C={choices:[{delta:{role:"assistant",content:S},finish_reason:b.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:h.usageMetadata?.candidatesTokenCount||0,prompt_tokens:h.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:h.usageMetadata?.cachedContentTokenCount||0},total_tokens:h.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:h.usageMetadata?.thoughtsTokenCount||0}}};b?.groundingMetadata?.groundingChunks?.length&&(C.choices[0].delta.annotations=b.groundingMetadata.groundingChunks.map((P,R)=>{let A=b?.groundingMetadata?.groundingSupports?.filter(E=>E.groundingChunkIndices?.includes(R));return{type:"url_citation",url_citation:{url:P?.web?.uri||"",title:P?.web?.title||"",content:A?.[0]?.segment?.text||"",start_index:A?.[0]?.segment?.startIndex||0,end_index:A?.[0]?.segment?.endIndex||0}}})),_.enqueue(r.encode(`data: ${JSON.stringify(C)}
126
126
 
127
- `)),!a&&R&&(a=!0)}C.length>0&&(C.forEach(T=>{i++,u++;let O={choices:[{delta:{role:"assistant",tool_calls:[{...T,index:u}]},finish_reason:b.finishReason?.toLowerCase()||null,index:i,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:h.usageMetadata?.candidatesTokenCount||0,prompt_tokens:h.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:h.usageMetadata?.cachedContentTokenCount||0},total_tokens:h.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:h.usageMetadata?.thoughtsTokenCount||0}}};b?.groundingMetadata?.groundingChunks?.length&&(O.choices[0].delta.annotations=b.groundingMetadata.groundingChunks.map((w,E)=>{let A=b?.groundingMetadata?.groundingSupports?.filter(I=>I.groundingChunkIndices?.includes(E));return{type:"url_citation",url_citation:{url:w?.web?.uri||"",title:w?.web?.title||"",content:A?.[0]?.segment?.text||"",start_index:A?.[0]?.segment?.startIndex||0,end_index:A?.[0]?.segment?.endIndex||0}}})),_.enqueue(r.encode(`data: ${JSON.stringify(O)}
127
+ `)),!i&&S&&(i=!0)}v.length>0&&(v.forEach(C=>{c++,u++;let P={choices:[{delta:{role:"assistant",tool_calls:[{...C,index:u}]},finish_reason:b.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:h.responseId||"",model:h.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:h.usageMetadata?.candidatesTokenCount||0,prompt_tokens:h.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:h.usageMetadata?.cachedContentTokenCount||0},total_tokens:h.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:h.usageMetadata?.thoughtsTokenCount||0}}};b?.groundingMetadata?.groundingChunks?.length&&(P.choices[0].delta.annotations=b.groundingMetadata.groundingChunks.map((R,A)=>{let E=b?.groundingMetadata?.groundingSupports?.filter(I=>I.groundingChunkIndices?.includes(A));return{type:"url_citation",url_citation:{url:R?.web?.uri||"",title:R?.web?.title||"",content:E?.[0]?.segment?.text||"",start_index:E?.[0]?.segment?.startIndex||0,end_index:E?.[0]?.segment?.endIndex||0}}})),_.enqueue(r.encode(`data: ${JSON.stringify(P)}
128
128
 
129
- `))}),!a&&R&&(a=!0))}catch(h){t?.error(`Error parsing ${e} stream chunk`,k,h.message)}}}},y=n.body.getReader(),p="";try{for(;;){let{done:f,value:_}=await y.read();if(f){p&&await g(p,m);break}p+=o.decode(_,{stream:!0});let k=p.split(`
130
- `);p=k.pop()||"";for(let h of k)await g(h,m)}}catch(f){m.error(f)}finally{m.close()}}});return new Response(d,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ye,Do=P(()=>{"use strict";Ye={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var wn,Js=P(()=>{"use strict";Do();wn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:Tn(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=vn;async transformResponseOut(e){return Rn(e,this.name,this.logger)}}});async function Zc(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
129
+ `))}),!i&&S&&(i=!0))}catch(h){t?.error(`Error parsing ${e} stream chunk`,k,h.message)}}}},y=n.body.getReader(),p="";try{for(;;){let{done:f,value:_}=await y.read();if(f){p&&await m(p,g);break}p+=o.decode(_,{stream:!0});let k=p.split(`
130
+ `);p=k.pop()||"";for(let h of k)await m(h,g)}}catch(f){g.error(f)}finally{g.close()}}});return new Response(d,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ye,Mo=w(()=>{"use strict";Ye={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var Tn,Ms=w(()=>{"use strict";Mo();Tn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:_n(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=kn;async transformResponseOut(e){return bn(e,this.name,this.logger)}}});async function Oc(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
131
131
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
132
132
  2. Run "gcloud auth application-default login"
133
- 3. Use Google Cloud environment with default service account`)}}var Sn,Bs=P(()=>{"use strict";Do();Sn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(l);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Zc();return{body:Tn(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return vn(e)}async transformResponseOut(e){return Rn(e,this.name)}}});var Pn,Ws=P(()=>{"use strict";Pn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,l="";if(typeof r.content=="string"){let i=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);i&&(l=i[1].trim(),r.content=r.content.replace(i[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):l&&(r.reasoning_content=l),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",l=new ReadableStream({async start(c){let i=e.body.getReader(),u=(m,g,y)=>{let p=m.split(`
134
- `);for(let f of p)f.trim()&&g.enqueue(y.encode(f+`
135
- `))},d=(m,g)=>{let{controller:y,encoder:p}=g;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let f=JSON.parse(m.slice(6));if(f.choices?.[0]?.delta?.reasoning_content){g.appendReasoningContent(f.choices[0].delta.reasoning_content);let _={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,thinking:{content:f.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
133
+ 3. Use Google Cloud environment with default service account`)}}var Cn,$s=w(()=>{"use strict";Mo();Cn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),a=JSON.parse(l);a&&a.project_id&&(o=a.project_id)}catch(i){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Oc();return{body:_n(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return kn(e)}async transformResponseOut(e){return bn(e,this.name)}}});var vn,Ns=w(()=>{"use strict";vn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,i=r.thinking?.signature,l="";if(typeof r.content=="string"){let c=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);c&&(l=c[1].trim(),r.content=r.content.replace(c[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,i&&(r.reasoning_content_signature=i)):l&&(r.reasoning_content=l),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,i="",l=new ReadableStream({async start(a){let c=e.body.getReader(),u=(g,m,y)=>{let p=g.split(`
134
+ `);for(let f of p)f.trim()&&m.enqueue(y.encode(f+`
135
+ `))},d=(g,m)=>{let{controller:y,encoder:p}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let f=JSON.parse(g.slice(6));if(f.choices?.[0]?.delta?.reasoning_content){m.appendReasoningContent(f.choices[0].delta.reasoning_content);let _={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,thinking:{content:f.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
136
136
 
137
- `;y.enqueue(p.encode(k));return}if(f.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let _="ccr_think_signature",k=f.choices[0].delta.content,h={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:_}}}]};delete h.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(h)}
137
+ `;y.enqueue(p.encode(k));return}if(f.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let _="ccr_think_signature",k=f.choices[0].delta.content,h={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:_}}}]};delete h.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(h)}
138
138
 
139
- `;y.enqueue(p.encode(b));let x={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,content:k}}]};delete x.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(x)}
139
+ `;y.enqueue(p.encode(b));let T={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,content:k}}]};delete T.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(T)}
140
140
 
141
- `;y.enqueue(p.encode(v));return}if(f.choices[0]?.delta?.reasoning_content&&delete f.choices[0].delta.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0){let _=`data: ${JSON.stringify(f)}
141
+ `;y.enqueue(p.encode(x));return}if(f.choices[0]?.delta?.reasoning_content&&delete f.choices[0].delta.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0){let _=`data: ${JSON.stringify(f)}
142
142
 
143
- `;y.enqueue(p.encode(_))}}catch{y.enqueue(p.encode(m+`
144
- `))}else y.enqueue(p.encode(m+`
145
- `))};try{for(;;){let{done:m,value:g}=await i.read();if(m){a.trim()&&u(a,c,o);break}let y=t.decode(g,{stream:!0});a+=y;let p=a.split(`
146
- `);a=p.pop()||"";for(let f of p)if(f.trim())try{d(f,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:_=>r+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",f,_),c.enqueue(o.encode(f+`
147
- `))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{i.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var An,Gs=P(()=>{"use strict";An=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
143
+ `;y.enqueue(p.encode(_))}}catch{y.enqueue(p.encode(g+`
144
+ `))}else y.enqueue(p.encode(g+`
145
+ `))};try{for(;;){let{done:g,value:m}=await c.read();if(g){i.trim()&&u(i,a,o);break}let y=t.decode(m,{stream:!0});i+=y;let p=i.split(`
146
+ `);i=p.pop()||"";for(let f of p)if(f.trim())try{d(f,{controller:a,encoder:o,reasoningContent:()=>r,appendReasoningContent:_=>r+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",f,_),a.enqueue(o.encode(f+`
147
+ `))}}}catch(g){console.error("Stream error:",g),a.error(g)}finally{try{c.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}a.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var xn,Ls=w(()=>{"use strict";xn=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
148
148
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
149
149
  Examples:
150
150
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
151
- 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",a="",l=new ReadableStream({async start(c){let i=e.body.getReader(),u=(m,g,y)=>{let p=m.split(`
152
- `);for(let f of p)f.trim()&&g.enqueue(y.encode(f+`
153
- `))},d=(m,g)=>{let{controller:y,encoder:p,exitToolIndex:f,setExitToolIndex:_,appendExitToolResponse:k}=g;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let h=JSON.parse(m.slice(6));if(h.choices[0]?.delta?.tool_calls?.length){let b=h.choices[0].delta.tool_calls[0];if(b.function?.name==="ExitTool"){_(b.index);return}else if(f()>-1&&b.index===f()&&b.function.arguments){k(b.function.arguments);try{let x=JSON.parse(g.exitToolResponse());h.choices=[{delta:{role:"assistant",content:x.response||""}}];let v=`data: ${JSON.stringify(h)}
151
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",i="",l=new ReadableStream({async start(a){let c=e.body.getReader(),u=(g,m,y)=>{let p=g.split(`
152
+ `);for(let f of p)f.trim()&&m.enqueue(y.encode(f+`
153
+ `))},d=(g,m)=>{let{controller:y,encoder:p,exitToolIndex:f,setExitToolIndex:_,appendExitToolResponse:k}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let h=JSON.parse(g.slice(6));if(h.choices[0]?.delta?.tool_calls?.length){let b=h.choices[0].delta.tool_calls[0];if(b.function?.name==="ExitTool"){_(b.index);return}else if(f()>-1&&b.index===f()&&b.function.arguments){k(b.function.arguments);try{let T=JSON.parse(m.exitToolResponse());h.choices=[{delta:{role:"assistant",content:T.response||""}}];let x=`data: ${JSON.stringify(h)}
154
154
 
155
- `;y.enqueue(p.encode(v))}catch{}return}}if(h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){let b=`data: ${JSON.stringify(h)}
155
+ `;y.enqueue(p.encode(x))}catch{}return}}if(h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){let b=`data: ${JSON.stringify(h)}
156
156
 
157
- `;y.enqueue(p.encode(b))}}catch{y.enqueue(p.encode(m+`
158
- `))}else y.enqueue(p.encode(m+`
159
- `))};try{for(;;){let{done:m,value:g}=await i.read();if(m){a.trim()&&u(a,c,o);break}let y=t.decode(g,{stream:!0});a+=y;let p=a.split(`
160
- `);a=p.pop()||"";for(let f of p)if(f.trim())try{d(f,{controller:c,encoder:o,exitToolIndex:()=>r,setExitToolIndex:_=>r=_,exitToolResponse:()=>s,appendExitToolResponse:_=>s+=_})}catch(_){console.error("Error processing line:",f,_),c.enqueue(o.encode(f+`
161
- `))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{i.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Vs,On,Qs=P(()=>{"use strict";Vs=require("uuid"),On=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,l=!1,c="",i=new ReadableStream({async start(u){let d=e.body.getReader(),m=(y,p,f)=>{let _=y.split(`
157
+ `;y.enqueue(p.encode(b))}}catch{y.enqueue(p.encode(g+`
158
+ `))}else y.enqueue(p.encode(g+`
159
+ `))};try{for(;;){let{done:g,value:m}=await c.read();if(g){i.trim()&&u(i,a,o);break}let y=t.decode(m,{stream:!0});i+=y;let p=i.split(`
160
+ `);i=p.pop()||"";for(let f of p)if(f.trim())try{d(f,{controller:a,encoder:o,exitToolIndex:()=>r,setExitToolIndex:_=>r=_,exitToolResponse:()=>s,appendExitToolResponse:_=>s+=_})}catch(_){console.error("Error processing line:",f,_),a.enqueue(o.encode(f+`
161
+ `))}}}catch(g){console.error("Stream error:",g),a.error(g)}finally{try{c.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}a.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Ds,Sn,Fs=w(()=>{"use strict";Ds=require("uuid"),Sn=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",i=!1,l=!1,a="",c=new ReadableStream({async start(u){let d=e.body.getReader(),g=(y,p,f)=>{let _=y.split(`
162
162
  `);for(let k of _)k.trim()&&p.enqueue(f.encode(k+`
163
- `))},g=(y,p)=>{let{controller:f,encoder:_}=p;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let k=y.slice(6);try{let h=JSON.parse(k);if(h.usage&&(this.logger?.debug({usage:h.usage,hasToolCall:l},"usage"),h.choices[0].finish_reason=l?"tool_calls":"stop"),h.choices?.[0]?.finish_reason==="error"){f.enqueue(_.encode(`data: ${JSON.stringify({error:h.choices?.[0].error})}
163
+ `))},m=(y,p)=>{let{controller:f,encoder:_}=p;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let k=y.slice(6);try{let h=JSON.parse(k);if(h.usage&&(this.logger?.debug({usage:h.usage,hasToolCall:l},"usage"),h.choices[0].finish_reason=l?"tool_calls":"stop"),h.choices?.[0]?.finish_reason==="error"){f.enqueue(_.encode(`data: ${JSON.stringify({error:h.choices?.[0].error})}
164
164
 
165
- `));return}h.choices?.[0]?.delta?.content&&!p.hasTextContent()&&p.setHasTextContent(!0);let b=h.choices?.[0]?.delta?.reasoning||h.choices?.[0]?.delta?.reasoning_content;if(b){p.appendReasoningContent(b);let T={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,thinking:{content:b}}}]};T.choices?.[0]?.delta&&(delete T.choices[0].delta.reasoning,delete T.choices[0].delta.reasoning_content);let O=`data: ${JSON.stringify(T)}
165
+ `));return}h.choices?.[0]?.delta?.content&&!p.hasTextContent()&&p.setHasTextContent(!0);let b=h.choices?.[0]?.delta?.reasoning||h.choices?.[0]?.delta?.reasoning_content;if(b){p.appendReasoningContent(b);let C={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,thinking:{content:b}}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let P=`data: ${JSON.stringify(C)}
166
166
 
167
- `;f.enqueue(_.encode(O));return}if(h.choices?.[0]?.delta?.content&&p.reasoningContent()&&!p.isReasoningComplete()){p.setReasoningComplete(!0);let T="ccr_think_signature",O=h.choices[0].delta.content,w={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,content:null,thinking:{content:p.reasoningContent(),signature:T}}}]};w.choices?.[0]?.delta&&delete w.choices[0].delta.reasoning;let E=`data: ${JSON.stringify(w)}
167
+ `;f.enqueue(_.encode(P));return}if(h.choices?.[0]?.delta?.content&&p.reasoningContent()&&!p.isReasoningComplete()){p.setReasoningComplete(!0);let C="ccr_think_signature",P=h.choices[0].delta.content,R={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,content:null,thinking:{content:p.reasoningContent(),signature:C}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let A=`data: ${JSON.stringify(R)}
168
168
 
169
- `;f.enqueue(_.encode(E));let A={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,content:O}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content);let I=`data: ${JSON.stringify(A)}
169
+ `;f.enqueue(_.encode(A));let E={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,content:P}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let I=`data: ${JSON.stringify(E)}
170
170
 
171
- `;f.enqueue(_.encode(I));return}h.choices?.[0]?.delta?.reasoning&&delete h.choices[0].delta.reasoning,h.choices?.[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(h.choices?.[0]?.delta?.tool_calls[0].id,10))&&h.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${(0,Vs.v4)()}`}),h.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0);let x=h.choices?.[0]?.delta,v=x&&Object.keys(x).length>0,C=h.choices?.[0]?.finish_reason,R=h.usage;if(v||C||R){let T=`data: ${JSON.stringify(h)}
171
+ `;f.enqueue(_.encode(I));return}h.choices?.[0]?.delta?.reasoning&&delete h.choices[0].delta.reasoning,h.choices?.[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(h.choices?.[0]?.delta?.tool_calls[0].id,10))&&h.choices?.[0]?.delta?.tool_calls.forEach(C=>{C.id=`call_${(0,Ds.v4)()}`}),h.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0);let T=h.choices?.[0]?.delta,x=T&&Object.keys(T).length>0,v=h.choices?.[0]?.finish_reason,S=h.usage;if(x||v||S){let C=`data: ${JSON.stringify(h)}
172
172
 
173
- `;f.enqueue(_.encode(T))}}catch{f.enqueue(_.encode(y+`
173
+ `;f.enqueue(_.encode(C))}}catch{f.enqueue(_.encode(y+`
174
174
  `))}}else f.enqueue(_.encode(y+`
175
- `))};try{for(;;){let{done:y,value:p}=await d.read();if(y){c.trim()&&m(c,u,o);break}if(!p||p.length===0)continue;let f;try{f=t.decode(p,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(f.length===0)continue;if(c+=f,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
176
- `);c=k.pop()||"";for(let h of k)if(h.trim())try{g(h,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",h,b),u.enqueue(o.encode(h+`
177
- `))}continue}let _=c.split(`
178
- `);c=_.pop()||"";for(let k of _)if(k.trim())try{g(k,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>a,setReasoningComplete:h=>a=h})}catch(h){console.error("Error processing line:",k,h),u.enqueue(o.encode(k+`
179
- `))}}}catch(y){console.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}u.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var En,Ks=P(()=>{"use strict";En=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});var Xs,In,Ys=P(()=>{"use strict";Xs=require("uuid"),In=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,l="",c=new ReadableStream({async start(i){let u=e.body.getReader(),d=(g,y,p)=>{let f=g.split(`
175
+ `))};try{for(;;){let{done:y,value:p}=await d.read();if(y){a.trim()&&g(a,u,o);break}if(!p||p.length===0)continue;let f;try{f=t.decode(p,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(f.length===0)continue;if(a+=f,a.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=a.split(`
176
+ `);a=k.pop()||"";for(let h of k)if(h.trim())try{m(h,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>i,setReasoningComplete:b=>i=b})}catch(b){console.error("Error processing line:",h,b),u.enqueue(o.encode(h+`
177
+ `))}continue}let _=a.split(`
178
+ `);a=_.pop()||"";for(let k of _)if(k.trim())try{m(k,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>i,setReasoningComplete:h=>i=h})}catch(h){console.error("Error processing line:",k,h),u.enqueue(o.encode(k+`
179
+ `))}}}catch(y){console.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Rn,Us=w(()=>{"use strict";Rn=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});var js,wn,Hs=w(()=>{"use strict";js=require("uuid"),wn=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",i=!1,l="",a=new ReadableStream({async start(c){let u=e.body.getReader(),d=(m,y,p)=>{let f=m.split(`
180
180
  `);for(let _ of f)_.trim()&&y.enqueue(p.encode(_+`
181
- `))},m=(g,y)=>{let{controller:p,encoder:f}=y;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let _=g.slice(6);try{let k=JSON.parse(_);if(k.error)throw new Error(JSON.stringify(k));k.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),k.choices?.[0]?.delta?.tool_calls?.length&&k.choices?.[0]?.delta?.tool_calls.forEach(b=>{b.id=`call_${(0,Xs.v4)()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof k.choices[0].index=="number"?k.choices[0].index+=1:k.choices[0].index=1);let h=`data: ${JSON.stringify(k)}
181
+ `))},g=(m,y)=>{let{controller:p,encoder:f}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let _=m.slice(6);try{let k=JSON.parse(_);if(k.error)throw new Error(JSON.stringify(k));k.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),k.choices?.[0]?.delta?.tool_calls?.length&&k.choices?.[0]?.delta?.tool_calls.forEach(b=>{b.id=`call_${(0,js.v4)()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof k.choices[0].index=="number"?k.choices[0].index+=1:k.choices[0].index=1);let h=`data: ${JSON.stringify(k)}
182
182
 
183
- `;p.enqueue(f.encode(h))}catch{p.enqueue(f.encode(g+`
184
- `))}}else p.enqueue(f.encode(g+`
185
- `))};try{for(;;){let{done:g,value:y}=await u.read();if(g){l.trim()&&d(l,i,o);break}if(!y||y.length===0)continue;let p;try{p=t.decode(y,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(p.length===0)continue;if(l+=p,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=l.split(`
186
- `);l=_.pop()||"";for(let k of _)if(k.trim())try{m(k,{controller:i,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>a,setReasoningComplete:h=>a=h})}catch(h){console.error("Error processing line:",k,h),i.enqueue(o.encode(k+`
183
+ `;p.enqueue(f.encode(h))}catch{p.enqueue(f.encode(m+`
184
+ `))}}else p.enqueue(f.encode(m+`
185
+ `))};try{for(;;){let{done:m,value:y}=await u.read();if(m){l.trim()&&d(l,c,o);break}if(!y||y.length===0)continue;let p;try{p=t.decode(y,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(p.length===0)continue;if(l+=p,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=l.split(`
186
+ `);l=_.pop()||"";for(let k of _)if(k.trim())try{g(k,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>i,setReasoningComplete:h=>i=h})}catch(h){console.error("Error processing line:",k,h),c.enqueue(o.encode(k+`
187
187
  `))}continue}let f=l.split(`
188
- `);l=f.pop()||"";for(let _ of f)if(_.trim())try{m(_,{controller:i,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),i.enqueue(o.encode(_+`
189
- `))}}}catch(g){console.error("Stream error:",g),i.error(g)}finally{try{u.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}i.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Mn,qs=P(()=>{"use strict";Mn=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),e}}});function jo(n,e){if(!n||n.trim()===""||n==="{}")return"{}";try{return JSON.parse(n),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),n}catch(t){try{let o=Zs.default.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=(0,ei.jsonrepair)(n);return e?.debug("Tool arguments safely repaired"),r}catch(r){return e?.error(`JSON parsing failed: ${t.message}. JSON5 parsing failed: ${o.message}. JSON repair failed: ${r.message}. Input data: ${JSON.stringify(n)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Zs,ei,ti=P(()=>{Zs=Y(require("json5")),ei=require("jsonrepair")});var $n,ni=P(()=>{"use strict";ti();$n=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message?.tool_calls?.length)for(let o of t.choices[0].message.tool_calls)o.function?.arguments&&(o.function.arguments=jo(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",l=!1,c=!1,i="",u=new ReadableStream({async start(d){let m=e.body.getReader(),g=(f,_,k)=>{let h=f.split(`
188
+ `);l=f.pop()||"";for(let _ of f)if(_.trim())try{g(_,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>i,setReasoningComplete:k=>i=k})}catch(k){console.error("Error processing line:",_,k),c.enqueue(o.encode(_+`
189
+ `))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{u.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}c.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Pn,zs=w(()=>{"use strict";Pn=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),e}}});function $o(n,e){if(!n||n.trim()===""||n==="{}")return"{}";try{return JSON.parse(n),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),n}catch(t){try{let o=Bs.default.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=(0,Js.jsonrepair)(n);return e?.debug("Tool arguments safely repaired"),r}catch(r){return e?.error(`JSON parsing failed: ${t.message}. JSON5 parsing failed: ${o.message}. JSON repair failed: ${r.message}. Input data: ${JSON.stringify(n)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Bs,Js,Ws=w(()=>{Bs=Y(require("json5")),Js=require("jsonrepair")});var En,Gs=w(()=>{"use strict";Ws();En=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message?.tool_calls?.length)for(let o of t.choices[0].message.tool_calls)o.function?.arguments&&(o.function.arguments=$o(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,i="",l=!1,a=!1,c="",u=new ReadableStream({async start(d){let g=e.body.getReader(),m=(f,_,k)=>{let h=f.split(`
190
190
  `);for(let b of h)b.trim()&&_.enqueue(k.encode(b+`
191
- `))},y=(f,_,k)=>{let h="";try{h=jo(r.arguments||"",this.logger)}catch(C){console.error(`${C.message} ${C.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),h=r.arguments||""}let b={role:"assistant",tool_calls:[{function:{name:r.name,arguments:h},id:r.id,index:r.index,type:"function"}]},x={...f,choices:[{...f.choices[0],delta:b}]};x.choices[0].delta.content!==void 0&&delete x.choices[0].delta.content;let v=`data: ${JSON.stringify(x)}
191
+ `))},y=(f,_,k)=>{let h="";try{h=$o(r.arguments||"",this.logger)}catch(v){console.error(`${v.message} ${v.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),h=r.arguments||""}let b={role:"assistant",tool_calls:[{function:{name:r.name,arguments:h},id:r.id,index:r.index,type:"function"}]},T={...f,choices:[{...f.choices[0],delta:b}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let x=`data: ${JSON.stringify(T)}
192
192
 
193
- `;_.enqueue(k.encode(v))},p=(f,_)=>{let{controller:k,encoder:h}=_;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let b=f.slice(6);try{let x=JSON.parse(b);if(x.choices?.[0]?.delta?.tool_calls?.length){let C=x.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:C.index,name:C.function?.name||"",id:C.id||"",arguments:C.function?.arguments||""},C.function?.arguments&&(C.function.arguments="");let R=`data: ${JSON.stringify(x)}
193
+ `;_.enqueue(k.encode(x))},p=(f,_)=>{let{controller:k,encoder:h}=_;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let b=f.slice(6);try{let T=JSON.parse(b);if(T.choices?.[0]?.delta?.tool_calls?.length){let v=T.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""},v.function?.arguments&&(v.function.arguments="");let S=`data: ${JSON.stringify(T)}
194
194
 
195
- `;k.enqueue(h.encode(R));return}else if(r.index===C.index){C.function?.arguments&&(r.arguments+=C.function.arguments);return}else{y(x,k,h),r={index:C.index,name:C.function?.name||"",id:C.id||"",arguments:C.function?.arguments||""};return}}if(x.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){y(x,k,h),r={};return}x.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof x.choices[0].index=="number"?x.choices[0].index+=1:x.choices[0].index=1);let v=`data: ${JSON.stringify(x)}
195
+ `;k.enqueue(h.encode(S));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{y(T,k,h),r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){y(T,k,h),r={};return}T.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let x=`data: ${JSON.stringify(T)}
196
196
 
197
- `;k.enqueue(h.encode(v))}catch{k.enqueue(h.encode(f+`
197
+ `;k.enqueue(h.encode(x))}catch{k.enqueue(h.encode(f+`
198
198
  `))}}else k.enqueue(h.encode(f+`
199
- `))};try{for(;;){let{done:f,value:_}=await m.read();if(f){i.trim()&&g(i,d,o);break}if(!_||_.length===0)continue;let k;try{k=t.decode(_,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(k.length===0)continue;if(i+=k,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=i.split(`
200
- `);i=b.pop()||"";for(let x of b)if(x.trim())try{p(x,{controller:d,encoder:o,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>a,appendReasoningContent:v=>a+=v,isReasoningComplete:()=>l,setReasoningComplete:v=>l=v})}catch(v){console.error("Error processing line:",x,v),d.enqueue(o.encode(x+`
201
- `))}continue}let h=i.split(`
202
- `);i=h.pop()||"";for(let b of h)if(b.trim())try{p(b,{controller:d,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>l,setReasoningComplete:x=>l=x})}catch(x){console.error("Error processing line:",b,x),d.enqueue(o.encode(b+`
203
- `))}}}catch(f){console.error("Stream error:",f),d.error(f)}finally{try{m.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}d.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Nn,oi=P(()=>{"use strict";Nn=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",l=new ReadableStream({async start(c){let i=e.body.getReader(),u=(m,g,y)=>{let p=m.split(`
204
- `);for(let f of p)f.trim()&&g.enqueue(y.encode(f+`
205
- `))},d=(m,g)=>{let{controller:y,encoder:p}=g;if(this.logger?.debug({line:m},"Processing reason line"),m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let f=JSON.parse(m.slice(6));if(console.log(JSON.stringify(f)),f.choices?.[0]?.delta?.reasoning_content){g.appendReasoningContent(f.choices[0].delta.reasoning_content);let _={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,thinking:{content:f.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
199
+ `))};try{for(;;){let{done:f,value:_}=await g.read();if(f){c.trim()&&m(c,d,o);break}if(!_||_.length===0)continue;let k;try{k=t.decode(_,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(k.length===0)continue;if(c+=k,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
200
+ `);c=b.pop()||"";for(let T of b)if(T.trim())try{p(T,{controller:d,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>i,appendReasoningContent:x=>i+=x,isReasoningComplete:()=>l,setReasoningComplete:x=>l=x})}catch(x){console.error("Error processing line:",T,x),d.enqueue(o.encode(T+`
201
+ `))}continue}let h=c.split(`
202
+ `);c=h.pop()||"";for(let b of h)if(b.trim())try{p(b,{controller:d,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>i,appendReasoningContent:T=>i+=T,isReasoningComplete:()=>l,setReasoningComplete:T=>l=T})}catch(T){console.error("Error processing line:",b,T),d.enqueue(o.encode(b+`
203
+ `))}}}catch(f){console.error("Stream error:",f),d.error(f)}finally{try{g.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}d.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var On,Ks=w(()=>{"use strict";On=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,i="",l=new ReadableStream({async start(a){let c=e.body.getReader(),u=(g,m,y)=>{let p=g.split(`
204
+ `);for(let f of p)f.trim()&&m.enqueue(y.encode(f+`
205
+ `))},d=(g,m)=>{let{controller:y,encoder:p}=m;if(this.logger?.debug({line:g},"Processing reason line"),g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let f=JSON.parse(g.slice(6));if(console.log(JSON.stringify(f)),f.choices?.[0]?.delta?.reasoning_content){m.appendReasoningContent(f.choices[0].delta.reasoning_content);let _={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,thinking:{content:f.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
206
206
 
207
- `;y.enqueue(p.encode(k));return}if(f.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let _="ccr_think_signature",k=f.choices[0].delta.content,h={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:_}}}]};delete h.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(h)}
207
+ `;y.enqueue(p.encode(k));return}if(f.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let _="ccr_think_signature",k=f.choices[0].delta.content,h={...f,choices:[{...f.choices[0],delta:{...f.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:_}}}]};delete h.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(h)}
208
208
 
209
- `;y.enqueue(p.encode(b))}if(f.choices?.[0]?.delta?.reasoning_content&&delete f.choices[0].delta.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0){g.isReasoningComplete()&&f.choices[0].index++;let _=`data: ${JSON.stringify(f)}
209
+ `;y.enqueue(p.encode(b))}if(f.choices?.[0]?.delta?.reasoning_content&&delete f.choices[0].delta.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0){m.isReasoningComplete()&&f.choices[0].index++;let _=`data: ${JSON.stringify(f)}
210
210
 
211
- `;y.enqueue(p.encode(_))}}catch{y.enqueue(p.encode(m+`
212
- `))}else y.enqueue(p.encode(m+`
213
- `))};try{for(;;){let{done:m,value:g}=await i.read();if(m){a.trim()&&u(a,c,o);break}let y=t.decode(g,{stream:!0});a+=y;let p=a.split(`
214
- `);a=p.pop()||"";for(let f of p)if(f.trim())try{d(f,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:_=>r+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",f,_),c.enqueue(o.encode(f+`
215
- `))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{i.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Ln,ri=P(()=>{"use strict";Ln=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var Fn,si=P(()=>{"use strict";Fn=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ii(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",l=[];typeof r.content=="string"?l.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(c=>{c.type==="text"?l.push({type:"text",text:c.text||""}):c.type==="image_url"&&l.push({type:"image",source:{type:"base64",media_type:c.media_type||"image/jpeg",data:c.image_url.url}})}),!(!s&&l.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&l.length===0&&r.tool_calls&&l.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:l}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function ai(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function ci(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(l,c)=>{if(l.startsWith("data: ")){let i=l.slice(6).trim();if(i){t?.debug({chunkStr:i},`${e} chunk:`);try{let u=JSON.parse(i);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let d={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
211
+ `;y.enqueue(p.encode(_))}}catch{y.enqueue(p.encode(g+`
212
+ `))}else y.enqueue(p.encode(g+`
213
+ `))};try{for(;;){let{done:g,value:m}=await c.read();if(g){i.trim()&&u(i,a,o);break}let y=t.decode(m,{stream:!0});i+=y;let p=i.split(`
214
+ `);i=p.pop()||"";for(let f of p)if(f.trim())try{d(f,{controller:a,encoder:o,reasoningContent:()=>r,appendReasoningContent:_=>r+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",f,_),a.enqueue(o.encode(f+`
215
+ `))}}}catch(g){console.error("Stream error:",g),a.error(g)}finally{try{c.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}a.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var An,Qs=w(()=>{"use strict";An=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var In,Vs=w(()=>{"use strict";In=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function Ys(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,i=r.role==="assistant",l=[];typeof r.content=="string"?l.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(a=>{a.type==="text"?l.push({type:"text",text:a.text||""}):a.type==="image_url"&&l.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/jpeg",data:a.image_url.url}})}),!(!s&&l.length===0&&!r.tool_calls&&!r.content)&&(s&&i&&l.length===0&&r.tool_calls&&l.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:l}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function Xs(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(i=>i.type==="text"?{type:"text",text:i.text||""}:i.type==="image"&&i.source?{type:"image_url",image_url:{url:i.source.data},media_type:i.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function qs(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:JSON.stringify(i.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(l,a)=>{if(l.startsWith("data: ")){let c=l.slice(6).trim();if(c){t?.debug({chunkStr:c},`${e} chunk:`);try{let u=JSON.parse(c);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let d={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};a.enqueue(r.encode(`data: ${JSON.stringify(d)}
216
216
 
217
- `))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let d={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
217
+ `))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let d={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};a.enqueue(r.encode(`data: ${JSON.stringify(d)}
218
218
 
219
- `))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let d={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
219
+ `))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let d={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};a.enqueue(r.encode(`data: ${JSON.stringify(d)}
220
220
 
221
- `))}else if(u.type==="message_delta"){let d={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
221
+ `))}else if(u.type==="message_delta"){let d={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};a.enqueue(r.encode(`data: ${JSON.stringify(d)}
222
222
 
223
- `))}else if(u.type==="message_stop")c.enqueue(r.encode(`data: [DONE]
223
+ `))}else if(u.type==="message_stop")a.enqueue(r.encode(`data: [DONE]
224
224
 
225
- `));else{let d={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
225
+ `));else{let d={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};a.enqueue(r.encode(`data: ${JSON.stringify(d)}
226
226
 
227
- `))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,i,u.message)}}}},a=new ReadableStream({async start(l){let c=n.body.getReader(),i="";try{for(;;){let{done:u,value:d}=await c.read();if(u){i&&s(i,l);break}i+=o.decode(d,{stream:!0});let m=i.split(`
228
- `);i=m.pop()||"";for(let g of m)s(g,l)}}catch(u){l.error(u)}finally{l.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var li=P(()=>{"use strict"});async function el(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
227
+ `))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,c,u.message)}}}},i=new ReadableStream({async start(l){let a=n.body.getReader(),c="";try{for(;;){let{done:u,value:d}=await a.read();if(u){c&&s(c,l);break}c+=o.decode(d,{stream:!0});let g=c.split(`
228
+ `);c=g.pop()||"";for(let m of g)s(m,l)}}catch(u){l.error(u)}finally{l.close()}}});return new Response(i,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var Zs=w(()=>{"use strict"});async function Ac(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
229
229
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
230
230
  2. Run "gcloud auth application-default login"
231
- 3. Use Google Cloud environment with default service account`)}}var Un,ui=P(()=>{"use strict";li();Un=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(l);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await el();return{body:ii(e),config:{url:new URL(`/v1/projects/${o}/locations/${r}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${r}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return ai(e)}async transformResponseOut(e){return ci(e,this.name,this.logger)}}});var Dn,di=P(()=>{"use strict";Dn=class{name="cerebras";async transformRequestIn(e,t){let o=JSON.parse(JSON.stringify(e));return o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}}});var jn,pi=P(()=>{"use strict";jn=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var zn,fi=P(()=>{"use strict";zn=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Hn,mi=P(()=>{"use strict";Hn=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let t={...e},o=Object.entries(this.options);for(let[r,s]of o)if(r in t)if(typeof t[r]=="object"&&typeof s=="object"&&!Array.isArray(t[r])&&!Array.isArray(s)&&t[r]!==null&&s!==null)t[r]=this.deepMergeObjects(t[r],s);else continue;else t[r]=this.cloneValue(s);return t}async transformResponseOut(e){return e}deepMergeObjects(e,t){let o={...e};for(let[r,s]of Object.entries(t))r in o&&typeof o[r]=="object"&&typeof s=="object"&&!Array.isArray(o[r])&&!Array.isArray(s)&&o[r]!==null&&s!==null?o[r]=this.deepMergeObjects(o[r],s):o[r]=this.cloneValue(s);return o}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>this.cloneValue(o));let t={};for(let[o,r]of Object.entries(e))t[o]=this.cloneValue(r);return t}}});var gi,Jn,hi=P(()=>{"use strict";gi=require("uuid"),Jn=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,l=!1,c="",i=new ReadableStream({async start(u){let d=e.body.getReader(),m=(y,p,f)=>{let _=y.split(`
231
+ 3. Use Google Cloud environment with default service account`)}}var Mn,ei=w(()=>{"use strict";Zs();Mn=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),a=JSON.parse(l);a&&a.project_id&&(o=a.project_id)}catch(i){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Ac();return{body:Ys(e),config:{url:new URL(`/v1/projects/${o}/locations/${r}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${r}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return Xs(e)}async transformResponseOut(e){return qs(e,this.name,this.logger)}}});var $n,ti=w(()=>{"use strict";$n=class{name="cerebras";async transformRequestIn(e,t){let o=JSON.parse(JSON.stringify(e));return o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}}});var Nn,ni=w(()=>{"use strict";Nn=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Ln,oi=w(()=>{"use strict";Ln=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Dn,ri=w(()=>{"use strict";Dn=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let t={...e},o=Object.entries(this.options);for(let[r,s]of o)if(r in t)if(typeof t[r]=="object"&&typeof s=="object"&&!Array.isArray(t[r])&&!Array.isArray(s)&&t[r]!==null&&s!==null)t[r]=this.deepMergeObjects(t[r],s);else continue;else t[r]=this.cloneValue(s);return t}async transformResponseOut(e){return e}deepMergeObjects(e,t){let o={...e};for(let[r,s]of Object.entries(t))r in o&&typeof o[r]=="object"&&typeof s=="object"&&!Array.isArray(o[r])&&!Array.isArray(s)&&o[r]!==null&&s!==null?o[r]=this.deepMergeObjects(o[r],s):o[r]=this.cloneValue(s);return o}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>this.cloneValue(o));let t={};for(let[o,r]of Object.entries(e))t[o]=this.cloneValue(r);return t}}});var si,Fn,ii=w(()=>{"use strict";si=require("uuid"),Fn=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",i=!1,l=!1,a="",c=new ReadableStream({async start(u){let d=e.body.getReader(),g=(y,p,f)=>{let _=y.split(`
232
232
  `);for(let k of _)k.trim()&&p.enqueue(f.encode(k+`
233
- `))},g=(y,p)=>{let{controller:f,encoder:_}=p;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let k=y.slice(6);try{let h=JSON.parse(k);if(h.usage&&(this.logger?.debug({usage:h.usage,hasToolCall:l},"usage"),h.choices[0].finish_reason=l?"tool_calls":"stop"),h.choices?.[0]?.finish_reason==="error"&&f.enqueue(_.encode(`data: ${JSON.stringify({error:h.choices?.[0].error})}
233
+ `))},m=(y,p)=>{let{controller:f,encoder:_}=p;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let k=y.slice(6);try{let h=JSON.parse(k);if(h.usage&&(this.logger?.debug({usage:h.usage,hasToolCall:l},"usage"),h.choices[0].finish_reason=l?"tool_calls":"stop"),h.choices?.[0]?.finish_reason==="error"&&f.enqueue(_.encode(`data: ${JSON.stringify({error:h.choices?.[0].error})}
234
234
 
235
- `)),h.choices?.[0]?.delta?.content&&!p.hasTextContent()&&p.setHasTextContent(!0),h.choices?.[0]?.delta?.reasoning){p.appendReasoningContent(h.choices[0].delta.reasoning);let x={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,thinking:{content:h.choices[0].delta.reasoning}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(x)}
235
+ `)),h.choices?.[0]?.delta?.content&&!p.hasTextContent()&&p.setHasTextContent(!0),h.choices?.[0]?.delta?.reasoning){p.appendReasoningContent(h.choices[0].delta.reasoning);let T={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,thinking:{content:h.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(T)}
236
236
 
237
- `;f.enqueue(_.encode(v));return}if(h.choices?.[0]?.delta?.content&&p.reasoningContent()&&!p.isReasoningComplete()){p.setReasoningComplete(!0);let v={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,content:null,thinking:{content:p.reasoningContent(),signature:"ccr_think_signature"}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let C=`data: ${JSON.stringify(v)}
237
+ `;f.enqueue(_.encode(x));return}if(h.choices?.[0]?.delta?.content&&p.reasoningContent()&&!p.isReasoningComplete()){p.setReasoningComplete(!0);let x={...h,choices:[{...h.choices?.[0],delta:{...h.choices[0].delta,content:null,thinking:{content:p.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(x)}
238
238
 
239
- `;f.enqueue(_.encode(C))}h.choices?.[0]?.delta?.reasoning&&delete h.choices[0].delta.reasoning,h.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(h.choices?.[0]?.delta?.tool_calls[0].id,10))&&h.choices?.[0]?.delta?.tool_calls.forEach(x=>{x.id=`call_${(0,gi.v4)()}`}),h.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0),h.choices?.[0]?.delta?.tool_calls?.length&&p.hasTextContent()&&(typeof h.choices[0].index=="number"?h.choices[0].index+=1:h.choices[0].index=1);let b=`data: ${JSON.stringify(h)}
239
+ `;f.enqueue(_.encode(v))}h.choices?.[0]?.delta?.reasoning&&delete h.choices[0].delta.reasoning,h.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(h.choices?.[0]?.delta?.tool_calls[0].id,10))&&h.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${(0,si.v4)()}`}),h.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0),h.choices?.[0]?.delta?.tool_calls?.length&&p.hasTextContent()&&(typeof h.choices[0].index=="number"?h.choices[0].index+=1:h.choices[0].index=1);let b=`data: ${JSON.stringify(h)}
240
240
 
241
241
  `;f.enqueue(_.encode(b))}catch{f.enqueue(_.encode(y+`
242
242
  `))}}else f.enqueue(_.encode(y+`
243
- `))};try{for(;;){let{done:y,value:p}=await d.read();if(y){c.trim()&&m(c,u,o);break}if(!p||p.length===0)continue;let f;try{f=t.decode(p,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(f.length===0)continue;if(c+=f,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
244
- `);c=k.pop()||"";for(let h of k)if(h.trim())try{g(h,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",h,b),u.enqueue(o.encode(h+`
245
- `))}continue}let _=c.split(`
246
- `);c=_.pop()||"";for(let k of _)if(k.trim())try{g(k,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>a,setReasoningComplete:h=>a=h})}catch(h){console.error("Error processing line:",k,h),u.enqueue(o.encode(k+`
247
- `))}}}catch(y){console.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}u.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var zo,tl,Bn,yi=P(()=>{"use strict";zo=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
243
+ `))};try{for(;;){let{done:y,value:p}=await d.read();if(y){a.trim()&&g(a,u,o);break}if(!p||p.length===0)continue;let f;try{f=t.decode(p,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(f.length===0)continue;if(a+=f,a.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=a.split(`
244
+ `);a=k.pop()||"";for(let h of k)if(h.trim())try{m(h,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>i,setReasoningComplete:b=>i=b})}catch(b){console.error("Error processing line:",h,b),u.enqueue(o.encode(h+`
245
+ `))}continue}let _=a.split(`
246
+ `);a=_.pop()||"";for(let k of _)if(k.trim())try{m(k,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>i,setReasoningComplete:h=>i=h})}catch(h){console.error("Error processing line:",k,h),u.enqueue(o.encode(k+`
247
+ `))}}}catch(y){console.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var No,Ic,Un,ai=w(()=>{"use strict";No=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
248
248
 
249
249
  Output format:
250
250
  <reasoning_content>
251
251
  Your detailed thinking process goes here
252
252
  </reasoning_content>
253
- Your final answer must follow after the closing tag above.`,tl=10,Bn=class{name="forcereasoning";async transformRequestIn(e){let t=0;e.messages.filter(r=>r.role==="assistant").reverse().forEach(r=>{r.thinking&&(r.thinking.content&&(!r.content||t<tl)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
254
- ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:zo}):o.content=[{type:"text",text:zo},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:zo}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=r.choices[0]?.message.content.match(s);a&&a[1]&&(r.thinking={content:a[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,a=new TextEncoder,l=new ReadableStream({async start(c){let i=e.body.getReader(),u="",d="SEARCHING",m="",g="",y=(p,f)=>{if(typeof f!="string"){p.choices?.[0]?.delta&&Object.keys(p.choices[0].delta).length>0&&!p.choices[0].delta.content&&(p.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(p)}
253
+ Your final answer must follow after the closing tag above.`,Ic=10,Un=class{name="forcereasoning";async transformRequestIn(e){let t=0;e.messages.filter(r=>r.role==="assistant").reverse().forEach(r=>{r.thinking&&(r.thinking.content&&(!r.content||t<Ic)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
254
+ ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:No}):o.content=[{type:"text",text:No},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:No}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,i=r.choices[0]?.message.content.match(s);i&&i[1]&&(r.thinking={content:i[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,i=new TextEncoder,l=new ReadableStream({async start(a){let c=e.body.getReader(),u="",d="SEARCHING",g="",m="",y=(p,f)=>{if(typeof f!="string"){p.choices?.[0]?.delta&&Object.keys(p.choices[0].delta).length>0&&!p.choices[0].delta.content&&(p.choices[0].index=r,a.enqueue(i.encode(`data: ${JSON.stringify(p)}
255
255
 
256
- `)));return}let _=m+f;for(m="";_.length>0;)if(d==="SEARCHING"){let k=_.indexOf(t);if(k!==-1)_=_.substring(k+t.length),d="REASONING";else{for(let h=t.length-1;h>0;h--)if(_.endsWith(t.substring(0,h))){m=_.substring(_.length-h);break}_=""}}else if(d==="REASONING"){let k=_.indexOf(o);if(k!==-1){let h=_.substring(0,k);if(h.length>0){let v={...p.choices[0].delta,thinking:{content:h}};delete v.content;let C={...p,choices:[{...p.choices[0],delta:v,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(C)}
256
+ `)));return}let _=g+f;for(g="";_.length>0;)if(d==="SEARCHING"){let k=_.indexOf(t);if(k!==-1)_=_.substring(k+t.length),d="REASONING";else{for(let h=t.length-1;h>0;h--)if(_.endsWith(t.substring(0,h))){g=_.substring(_.length-h);break}_=""}}else if(d==="REASONING"){let k=_.indexOf(o);if(k!==-1){let h=_.substring(0,k);if(h.length>0){let x={...p.choices[0].delta,thinking:{content:h}};delete x.content;let v={...p,choices:[{...p.choices[0],delta:x,index:r}]};a.enqueue(i.encode(`data: ${JSON.stringify(v)}
257
257
 
258
- `))}let b={...p.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete b.content;let x={...p,choices:[{...p.choices[0],delta:b,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(x)}
258
+ `))}let b={...p.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete b.content;let T={...p,choices:[{...p.choices[0],delta:b,index:r}]};a.enqueue(i.encode(`data: ${JSON.stringify(T)}
259
259
 
260
- `)),r++,_=_.substring(k+o.length),d="FINAL"}else{let h=_;for(let b=o.length-1;b>0;b--)if(_.endsWith(o.substring(0,b))){m=_.substring(_.length-b),h=_.substring(0,_.length-b);break}if(h.length>0){let b={...p.choices[0].delta,thinking:{content:h}};delete b.content;let x={...p,choices:[{...p.choices[0],delta:b,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(x)}
260
+ `)),r++,_=_.substring(k+o.length),d="FINAL"}else{let h=_;for(let b=o.length-1;b>0;b--)if(_.endsWith(o.substring(0,b))){g=_.substring(_.length-b),h=_.substring(0,_.length-b);break}if(h.length>0){let b={...p.choices[0].delta,thinking:{content:h}};delete b.content;let T={...p,choices:[{...p.choices[0],delta:b,index:r}]};a.enqueue(i.encode(`data: ${JSON.stringify(T)}
261
261
 
262
- `))}_=""}}else if(d==="FINAL"){if(_.length>0)if(/^\s*$/.test(_))g+=_;else{let h=g+_,b={...p.choices[0].delta,content:h};b.thinking&&delete b.thinking;let x={...p,choices:[{...p.choices[0],delta:b}]};c.enqueue(a.encode(`data: ${JSON.stringify(x)}
262
+ `))}_=""}}else if(d==="FINAL"){if(_.length>0)if(/^\s*$/.test(_))m+=_;else{let h=m+_,b={...p.choices[0].delta,content:h};b.thinking&&delete b.thinking;let T={...p,choices:[{...p.choices[0],delta:b}]};a.enqueue(i.encode(`data: ${JSON.stringify(T)}
263
263
 
264
- `)),g=""}r++,_=""}};try{for(;;){let{done:p,value:f}=await i.read();if(p)break;let _=s.decode(f,{stream:!0});u+=_;let k=u.split(`
265
- `);u=k.pop()||"";for(let h of k)if(h.trim()){if(h.trim()==="data: [DONE]"){c.enqueue(a.encode(h+`
264
+ `)),m=""}r++,_=""}};try{for(;;){let{done:p,value:f}=await c.read();if(p)break;let _=s.decode(f,{stream:!0});u+=_;let k=u.split(`
265
+ `);u=k.pop()||"";for(let h of k)if(h.trim()){if(h.trim()==="data: [DONE]"){a.enqueue(i.encode(h+`
266
266
 
267
- `));break}if(h.startsWith("data:"))try{let b=JSON.parse(h.slice(5));y(b,b.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(h+`
268
- `))}else c.enqueue(a.encode(h+`
269
- `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{i.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}if(d==="REASONING"){let f={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};c.enqueue(a.encode(`data: ${JSON.stringify(f)}
267
+ `));break}if(h.startsWith("data:"))try{let b=JSON.parse(h.slice(5));y(b,b.choices?.[0]?.delta?.content)}catch{a.enqueue(i.encode(h+`
268
+ `))}else a.enqueue(i.encode(h+`
269
+ `))}}}catch(p){console.error("Stream error:",p),a.error(p)}finally{try{c.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}if(d==="REASONING"){let f={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};a.enqueue(i.encode(`data: ${JSON.stringify(f)}
270
270
 
271
- `))}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Wn,_i=P(()=>{"use strict";Wn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",l=new ReadableStream({async start(c){let i=e.body.getReader();try{for(;;){let{done:u,value:d}=await i.read();if(u){a.trim()&&c.enqueue(r.encode(a+`
272
- `));break}let m=o.decode(d,{stream:!0});a+=m;let g=a.split(`
273
- `);a=g.pop()||"";for(let y of g)if(y.trim())if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]")try{let p=JSON.parse(y.slice(6));if(p.choices?.[0]?.delta?.reasoning_content){s+=p.choices[0].delta.reasoning_content;let f={...p,choices:[{...p.choices[0],delta:{thinking:{content:p.choices[0].delta.reasoning_content}}}]};delete f.choices[0].delta.reasoning_content,c.enqueue(r.encode(`data: ${JSON.stringify(f)}
271
+ `))}a.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var jn,ci=w(()=>{"use strict";jn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",i="",l=new ReadableStream({async start(a){let c=e.body.getReader();try{for(;;){let{done:u,value:d}=await c.read();if(u){i.trim()&&a.enqueue(r.encode(i+`
272
+ `));break}let g=o.decode(d,{stream:!0});i+=g;let m=i.split(`
273
+ `);i=m.pop()||"";for(let y of m)if(y.trim())if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]")try{let p=JSON.parse(y.slice(6));if(p.choices?.[0]?.delta?.reasoning_content){s+=p.choices[0].delta.reasoning_content;let f={...p,choices:[{...p.choices[0],delta:{thinking:{content:p.choices[0].delta.reasoning_content}}}]};delete f.choices[0].delta.reasoning_content,a.enqueue(r.encode(`data: ${JSON.stringify(f)}
274
274
 
275
- `));continue}if(p.choices?.[0]?.delta?.content&&s&&!p.choices[0]?.delta?.reasoning_content){let f=Date.now().toString(),_={...p,choices:[{...p.choices[0],delta:{content:null,thinking:{content:s,signature:f}}}]};c.enqueue(r.encode(`data: ${JSON.stringify(_)}
275
+ `));continue}if(p.choices?.[0]?.delta?.content&&s&&!p.choices[0]?.delta?.reasoning_content){let f=Date.now().toString(),_={...p,choices:[{...p.choices[0],delta:{content:null,thinking:{content:s,signature:f}}}]};a.enqueue(r.encode(`data: ${JSON.stringify(_)}
276
276
 
277
- `)),s=""}p.choices?.[0]?.delta?.reasoning_content&&delete p.choices[0].delta.reasoning_content,p.choices?.[0]?.delta&&Object.keys(p.choices[0].delta).length>0&&c.enqueue(r.encode(`data: ${JSON.stringify(p)}
277
+ `)),s=""}p.choices?.[0]?.delta?.reasoning_content&&delete p.choices[0].delta.reasoning_content,p.choices?.[0]?.delta&&Object.keys(p.choices[0].delta).length>0&&a.enqueue(r.encode(`data: ${JSON.stringify(p)}
278
278
 
279
- `))}catch{c.enqueue(r.encode(y+`
280
- `))}else c.enqueue(r.encode(y+`
281
- `))}}catch(u){c.error(u)}finally{try{i.releaseLock()}catch{}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await e.json();return o.choices?.[0]?.message?.reasoning_content&&(o.choices[0].message.thinking={content:o.choices[0].message.reasoning_content},delete o.choices[0].message.reasoning_content),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}}});var ki,Gn,bi=P(()=>{"use strict";ki=require("uuid"),Gn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,l=!1,c="",i=new ReadableStream({async start(u){let d=e.body.getReader(),m=(y,p,f)=>{let _=y.split(`
279
+ `))}catch{a.enqueue(r.encode(y+`
280
+ `))}else a.enqueue(r.encode(y+`
281
+ `))}}catch(u){a.error(u)}finally{try{c.releaseLock()}catch{}a.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await e.json();return o.choices?.[0]?.message?.reasoning_content&&(o.choices[0].message.thinking={content:o.choices[0].message.reasoning_content},delete o.choices[0].message.reasoning_content),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}}});var li,Hn,ui=w(()=>{"use strict";li=require("uuid"),Hn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",i=!1,l=!1,a="",c=new ReadableStream({async start(u){let d=e.body.getReader(),g=(y,p,f)=>{let _=y.split(`
282
282
  `);for(let k of _)k.trim()&&p.enqueue(f.encode(k+`
283
- `))},g=(y,p)=>{let{controller:f,encoder:_}=p;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]")try{let k=JSON.parse(y.slice(6));if(k.usage&&(k.choices[0].finish_reason=l?"tool_calls":"stop"),k.choices?.[0]?.finish_reason==="error"){f.enqueue(_.encode(`data: ${JSON.stringify({error:k.choices?.[0]?.error})}
283
+ `))},m=(y,p)=>{let{controller:f,encoder:_}=p;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]")try{let k=JSON.parse(y.slice(6));if(k.usage&&(k.choices[0].finish_reason=l?"tool_calls":"stop"),k.choices?.[0]?.finish_reason==="error"){f.enqueue(_.encode(`data: ${JSON.stringify({error:k.choices?.[0]?.error})}
284
284
 
285
- `));return}k.choices?.[0]?.delta?.content&&!p.hasTextContent()&&p.setHasTextContent(!0);let h=k.choices?.[0]?.delta?.reasoning||k.choices?.[0]?.delta?.reasoning_content;if(h){p.appendReasoningContent(h);let R={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,thinking:{content:h}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),f.enqueue(_.encode(`data: ${JSON.stringify(R)}
285
+ `));return}k.choices?.[0]?.delta?.content&&!p.hasTextContent()&&p.setHasTextContent(!0);let h=k.choices?.[0]?.delta?.reasoning||k.choices?.[0]?.delta?.reasoning_content;if(h){p.appendReasoningContent(h);let S={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,thinking:{content:h}}}]};S.choices?.[0]?.delta&&(delete S.choices[0].delta.reasoning,delete S.choices[0].delta.reasoning_content),f.enqueue(_.encode(`data: ${JSON.stringify(S)}
286
286
 
287
- `));return}if(k.choices?.[0]?.delta?.content&&p.reasoningContent()&&!p.isReasoningComplete()){p.setReasoningComplete(!0);let R="ccr_think_signature",T=k.choices[0].delta.content,O={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,content:null,thinking:{content:p.reasoningContent(),signature:R}}}]};O.choices?.[0]?.delta&&(delete O.choices[0].delta.reasoning,delete O.choices[0].delta.reasoning_content),f.enqueue(_.encode(`data: ${JSON.stringify(O)}
287
+ `));return}if(k.choices?.[0]?.delta?.content&&p.reasoningContent()&&!p.isReasoningComplete()){p.setReasoningComplete(!0);let S="ccr_think_signature",C=k.choices[0].delta.content,P={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,content:null,thinking:{content:p.reasoningContent(),signature:S}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content),f.enqueue(_.encode(`data: ${JSON.stringify(P)}
288
288
 
289
- `));let w={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,content:T}}]};w.choices?.[0]?.delta&&(delete w.choices[0].delta.reasoning,delete w.choices[0].delta.reasoning_content),f.enqueue(_.encode(`data: ${JSON.stringify(w)}
289
+ `));let R={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,content:C}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),f.enqueue(_.encode(`data: ${JSON.stringify(R)}
290
290
 
291
- `));return}k.choices?.[0]?.delta?.reasoning&&delete k.choices[0].delta.reasoning,k.choices?.[0]?.delta?.reasoning_content&&delete k.choices[0].delta.reasoning_content,k.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(k.choices?.[0]?.delta?.tool_calls[0].id,10))&&k.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${(0,ki.v4)()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0);let b=k.choices?.[0]?.delta,x=b&&Object.keys(b).length>0,v=k.choices?.[0]?.finish_reason,C=k.usage;(x||v||C)&&f.enqueue(_.encode(`data: ${JSON.stringify(k)}
291
+ `));return}k.choices?.[0]?.delta?.reasoning&&delete k.choices[0].delta.reasoning,k.choices?.[0]?.delta?.reasoning_content&&delete k.choices[0].delta.reasoning_content,k.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(k.choices?.[0]?.delta?.tool_calls[0].id,10))&&k.choices?.[0]?.delta?.tool_calls.forEach(S=>{S.id=`call_${(0,li.v4)()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0);let b=k.choices?.[0]?.delta,T=b&&Object.keys(b).length>0,x=k.choices?.[0]?.finish_reason,v=k.usage;(T||x||v)&&f.enqueue(_.encode(`data: ${JSON.stringify(k)}
292
292
 
293
293
  `))}catch{f.enqueue(_.encode(y+`
294
294
  `))}else f.enqueue(_.encode(y+`
295
- `))};try{for(;;){let{done:y,value:p}=await d.read();if(y){c.trim()&&m(c,u,o);break}if(!p||p.length===0)continue;let f;try{f=t.decode(p,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(f.length===0)continue;if(c+=f,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
296
- `);c=k.pop()||"";for(let h of k)if(h.trim())try{g(h,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",h,b),u.enqueue(o.encode(h+`
297
- `))}continue}let _=c.split(`
298
- `);c=_.pop()||"";for(let k of _)if(k.trim())try{g(k,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>a,setReasoningComplete:h=>a=h})}catch(h){console.error("Error processing line:",k,h),u.enqueue(o.encode(k+`
299
- `))}}}catch(y){console.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}u.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var xi,Ci=P(()=>{Hs();Js();Bs();Ws();Gs();Qs();Ks();Ys();qs();ni();oi();ri();si();ui();di();pi();fi();mi();hi();Ao();yi();_i();bi();xi={AnthropicTransformer:Cn,GeminiTransformer:wn,VertexGeminiTransformer:Sn,VertexClaudeTransformer:Un,DeepseekTransformer:Pn,TooluseTransformer:An,OpenrouterTransformer:On,OpenAITransformer:zn,MaxTokenTransformer:En,GroqTransformer:In,CleancacheTransformer:Mn,EnhanceToolTransformer:$n,ReasoningTransformer:Nn,SamplingTransformer:Ln,MaxCompletionTokens:Fn,CerebrasTransformer:Dn,StreamOptionsTransformer:jn,CustomParamsTransformer:Hn,VercelTransformer:Jn,OpenAIResponsesTransformer:Je,ForceReasoningTransformer:Bn,KimiTransformer:Wn,OpenCodeTransformer:Gn}});var Ee,Ho=P(()=>{"use strict";Ci();Ee=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=require(require.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
295
+ `))};try{for(;;){let{done:y,value:p}=await d.read();if(y){a.trim()&&g(a,u,o);break}if(!p||p.length===0)continue;let f;try{f=t.decode(p,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(f.length===0)continue;if(a+=f,a.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=a.split(`
296
+ `);a=k.pop()||"";for(let h of k)if(h.trim())try{m(h,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>i,setReasoningComplete:b=>i=b})}catch(b){console.error("Error processing line:",h,b),u.enqueue(o.encode(h+`
297
+ `))}continue}let _=a.split(`
298
+ `);a=_.pop()||"";for(let k of _)if(k.trim())try{m(k,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:h=>r=h,reasoningContent:()=>s,appendReasoningContent:h=>s+=h,isReasoningComplete:()=>i,setReasoningComplete:h=>i=h})}catch(h){console.error("Error processing line:",k,h),u.enqueue(o.encode(k+`
299
+ `))}}}catch(y){console.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var di,pi=w(()=>{Is();Ms();$s();Ns();Ls();Fs();Us();Hs();zs();Gs();Ks();Qs();Vs();ei();ti();ni();oi();ri();ii();Co();ai();ci();ui();di={AnthropicTransformer:yn,GeminiTransformer:Tn,VertexGeminiTransformer:Cn,VertexClaudeTransformer:Mn,DeepseekTransformer:vn,TooluseTransformer:xn,OpenrouterTransformer:Sn,OpenAITransformer:Ln,MaxTokenTransformer:Rn,GroqTransformer:wn,CleancacheTransformer:Pn,EnhanceToolTransformer:En,ReasoningTransformer:On,SamplingTransformer:An,MaxCompletionTokens:In,CerebrasTransformer:$n,StreamOptionsTransformer:Nn,CustomParamsTransformer:Dn,VercelTransformer:Fn,OpenAIResponsesTransformer:He,ForceReasoningTransformer:Un,KimiTransformer:jn,OpenCodeTransformer:Hn}});var Pe,Lo=w(()=>{"use strict";pi();Pe=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=require(require.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
300
300
  error: ${t.message}
301
301
  stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
302
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(xi).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});var Ti,Tt,vi=P(()=>{"use strict";Ti=require("tiktoken"),Tt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,Ti.get_encoding)(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(l=>{typeof l.content=="string"?o+=t.encode(l.content).length:Array.isArray(l.content)&&l.content.forEach(c=>{if(c.type==="text")o+=t.encode(c.text).length;else if(c.type==="tool_use")o+=t.encode(JSON.stringify(c.input)).length;else if(c.type==="tool_result"){let i=typeof c.content=="string"?c.content:JSON.stringify(c.content);o+=t.encode(i).length}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(l=>{l.type==="text"&&(typeof l.text=="string"?o+=t.encode(l.text).length:Array.isArray(l.text)&&l.text.forEach(c=>{o+=t.encode(c||"").length}))}),a&&a.forEach(l=>{l.description&&(o+=t.encode(l.name+l.description).length),l.input_schema&&(o+=t.encode(JSON.stringify(l.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});var vt,Ri,qe,Rt,wi,Vn,Si=P(()=>{"use strict";vt=require("path"),Ri=require("os"),qe=require("fs"),Rt=require("fs"),wi=require("@huggingface/tokenizers"),Vn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||(0,vt.join)((0,Ri.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,vt.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,vt.join)(e,"tokenizer.json"),tokenizerConfig:(0,vt.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,qe.existsSync)(e)||(0,qe.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,qe.existsSync)(e.tokenizerJson)||!(0,qe.existsSync)(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Rt.promises.readFile(e.tokenizerJson,"utf-8"),Rt.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[l,c]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Rt.promises.writeFile(e.tokenizerJson,JSON.stringify(l,null,2)),Rt.promises.writeFile(e.tokenizerConfig,JSON.stringify(c,null,2))]),{tokenizerJson:l,tokenizerConfig:c}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new wi.Tokenizer(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content))for(let l of a.content)l.type==="text"&&l.text?t.push(l.text):l.type==="tool_use"&&l.input?t.push(JSON.stringify(l.input)):l.type==="tool_result"&&t.push(typeof l.content=="string"?l.content:JSON.stringify(l.content))}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let l of a.text)l&&t.push(l)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Qn,Pi=P(()=>{"use strict";ae();Qn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},l=this.options.resolveProxyUrl?.();l&&(a.dispatcher=K(l));let c=await fetch(this.config.url,a);if(clearTimeout(s),!c.ok)throw new Error(`API tokenizer request failed: ${c.status} ${c.statusText}`);let i=await c.json();return this.extractTokenCount(i)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ie,Jo=P(()=>{"use strict";vi();Si();Pi();ae();Ie=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new Tt("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new Tt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Vn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Qn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function Ai(n){if(!n||typeof n!="object"||cl(n))return null;for(let t of al(n)){let o=il(t);if(o)return o}return null}function il(n){if(!n||typeof n!="object")return null;let e={},t=Kn(n,nl);if(t!==void 0){let a=Oi(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Kn(n,ol);if(o!==void 0){let a=Oi(o);e.usedBalance=a,e.totalBalance=100}let r=Kn(n,rl);if(r!==void 0){let a=Ei(r);a&&(e.resetTime=a)}let s=Kn(n,sl);if(s!==void 0){let a=Ei(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function Oi(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Kn(n,e){for(let t of e){let o=$(n?.[t]);if(o!==void 0)return o}}function al(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function cl(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function Ei(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Xn(n){let e=tr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?hl:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?yl:e==="deepseek.com"||e.endsWith(".deepseek.com")?ll:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?ul:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?dl:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?pl:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?fl:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?ml:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?gl:null:null}function _l(n){let e=tr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function kl(n,e){let t=Zo(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,l=String(a?.apiKey||a?.api_key||"").trim();return l&&o.some(c=>c.includes(l)||l.includes(c))})||t[0]}function Zo(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Zo(e)):Object.values(n).flatMap(e=>Zo(e))}function er(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function tr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function $(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var le,Bo,Wo,Go,Vo,Qo,nl,ol,rl,sl,Ko,Xo,Yo,qo,ll,ul,dl,pl,fl,ml,gl,hl,yl,nr=P(()=>{"use strict";ae();le=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let l={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=K(r));let c=await fetch(e,l);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},Bo=class extends le{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>$(c?.total_balance)!==void 0);if(!a)return null;let l=$(a.total_balance);return l===void 0?null:{totalBalance:l,currency:typeof a.currency=="string"?a.currency:void 0}}},Wo=class extends le{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},l=$(s.limit),c=$(s.limit_remaining),i=$(s.usage),u=$(s.usage_daily);return l!==void 0&&(a.totalBalance=l),c!==void 0&&(a.remainingBalance=c),i!==void 0&&(a.usedBalance=i),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},Go=class extends le{async queryQuota(e,t,o){let r=_l(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let l={},c=$(a.totalBalance),i=$(a.balance);return c!==void 0&&(l.totalBalance=c),i!==void 0&&(l.remainingBalance=i),c!==void 0&&i!==void 0&&(l.usedBalance=Math.max(0,c-i)),this.hasQuotaData(l)?l:null}},Vo=class extends le{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let l=await a.json(),c=Array.isArray(l?.data?.limits)?l.data.limits:[],i=null,u=null,d=null;for(let g of c)g.type==="TOKENS_LIMIT"?g.unit===3?i=g:g.unit===6?u=g:i||(i=g):g.type==="TIME_LIMIT"&&(d=g);let m={};if(i){let g=$(i.currentValue),y=$(i.usage),p=$(i.remaining),f=$(i.percentage);g!==void 0?m.usedDailyBalance=g:f!==void 0&&(m.usedDailyBalance=f,m.limitDaily=100),y!==void 0?m.limitDaily=y:g!==void 0&&p!==void 0&&(m.limitDaily=g+p),i.nextResetTime&&(m.resetTime=new Date(i.nextResetTime).toISOString())}if(u){let g=$(u.currentValue),y=$(u.usage),p=$(u.remaining),f=$(u.percentage);g!==void 0?m.usedBalance=g:f!==void 0&&(m.usedBalance=f,m.totalBalance=100),y!==void 0?m.totalBalance=y:g!==void 0&&p!==void 0&&(m.totalBalance=g+p),u.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(u.nextResetTime).toISOString())}if(d){if(m.usedDailyBalance===void 0){let g=$(d.currentValue);g!==void 0&&(m.usedDailyBalance=g)}if(m.limitDaily===void 0){let g=$(d.usage),y=$(d.currentValue),p=$(d.remaining);g!==void 0?m.limitDaily=g:y!==void 0&&p!==void 0&&(m.limitDaily=y+p)}d.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(d.nextResetTime).toISOString())}return this.hasQuotaData(m)?m:null}catch{return null}}},Qo=class extends le{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=K(o));let l=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!l.ok)return null;let i=(await l.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(i)||i.length===0)return null;let u=i[0]?.codingPlanQuotaInfo;if(!u)return null;let d={},m=$(u.per5HourUsedQuota),g=$(u.per5HourTotalQuota);m!==void 0&&(d.usedDailyBalance=m),g!==void 0&&(d.limitDaily=g);let y=$(u.perWeekUsedQuota),p=$(u.perWeekTotalQuota);return y!==void 0&&(d.usedBalance=y),p!==void 0&&(d.totalBalance=p),this.hasQuotaData(d)?d:null}catch{return null}}};nl=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],ol=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],rl=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],sl=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Ko=class extends le{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=er(e,"cna")||"",l=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:l,region:"cn-beijing",sec_token:t}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=K(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,i);if(!u.ok)return null;let d=await u.json();return Ai(d)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(l.dispatcher=K(o));let c=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,l);if(!c.ok)return null;let i=await c.json();return Ai(i)}catch{return null}}},Xo=class extends le{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(er(e.quotaToken,"atp-auth-token")||er(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let l=await a.json();if(l?.succeed===!1||l?.failed===!0)return null;let c=kl(l,e.apiKey),i=c?.codingPlanUsageDTO||c?.usage||c;if(!i||typeof i!="object")return null;let u={},d=$(i.rp5hUsage),m=$(i.rp5hLimit);d!==void 0&&(u.usedDailyBalance=d),m!==void 0&&(u.limitDaily=m);let g=$(i.rpwUsage),y=$(i.rpwLimit);return g!==void 0&&(u.usedBalance=g),y!==void 0&&(u.totalBalance=y),u.remainingBalance===void 0&&y!==void 0&&g!==void 0&&(u.remainingBalance=Math.max(0,y-g)),this.hasQuotaData(u)?u:null}catch{return null}}},Yo=class extends le{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let l=await a.json(),c={},i=Array.isArray(l?.limits)?l.limits:[];if(i.length>0&&i[0]?.detail){let d=i[0].detail,m=$(d.limit),g=$(d.remaining),y=d.resetTime;m!==void 0&&g!==void 0&&(c.usedDailyBalance=Math.max(0,m-g),c.limitDaily=m),y&&(c.resetTime=new Date(y).toISOString())}let u=l?.usage;if(u){let d=$(u.limit),m=$(u.remaining),g=$(u.used),y=u.resetTime;d!==void 0&&(c.totalBalance=d,g!==void 0?c.usedBalance=g:m!==void 0&&(c.usedBalance=Math.max(0,d-m),c.remainingBalance=m)),y&&(c.resetTime7d=new Date(y).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},qo=class extends le{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=tr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let l=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let b of l)if(c=await this.fetchJson(b,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let b=c.base_resp.status_code;if(b!==void 0&&b!==0)return null}let i=Array.isArray(c?.model_remains)?c.model_remains:[];if(i.length===0)return null;let u=i[0],d={},m=$(u.current_interval_total_count),g=$(u.current_interval_usage_count),y=$(u.current_interval_remaining_percent),p=$(u.end_time);m!==void 0&&g!==void 0&&m>0?(d.usedDailyBalance=Math.max(0,m-g),d.limitDaily=m):y!==void 0&&(d.limitDaily=100,d.usedDailyBalance=Math.max(0,100-y)),p&&(d.resetTime=new Date(p).toISOString());let f=$(u.current_weekly_total_count),_=$(u.current_weekly_usage_count),k=$(u.current_weekly_remaining_percent),h=$(u.weekly_end_time);return f!==void 0&&_!==void 0&&f>0?(d.usedBalance=Math.max(0,f-_),d.remainingBalance=_,d.totalBalance=f):k!==void 0&&(d.totalBalance=100,d.usedBalance=Math.max(0,100-k),d.remainingBalance=k),h&&!d.resetTime&&(d.resetTime=new Date(h).toISOString()),this.hasQuotaData(d)?d:null}catch{return null}}},ll=new Bo,ul=new Wo,dl=new Go,pl=new Vo,fl=new Qo,ml=new Ko,gl=new Xo,hl=new Yo,yl=new qo});function Ii(n){return{[bl]:n,[xl]:sn}}function Tl(n){return n===!0||n==="true"||n===1||n==="1"}function vl(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function Rl(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function wl(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function or(n,e,t){let o=Rl(n.baseUrl);if(!o)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let r={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(r.dispatcher=K(t));let s=await fetch(o,r);if(s.headers&&ft(n.name,n.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(r){return{success:!1,error:r?.message||r?.toString()||"Unknown probe error"}}}async function Sl(n,e,t,o){let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let l={"Content-Type":"application/json",...Ii("scheduled-wakeup")};a?(l["x-api-key"]=n.apiKey,l["anthropic-version"]="2023-06-01"):l.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:l,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=K(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let i=await fetch(s,c);if(i.ok)return{success:!0};let u=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(l){return{success:!1,error:l?.message||l?.toString()||"Unknown wake-up error"}}}async function Pl(n,e,t,o,r){let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let l={"Content-Type":"application/json",...Ii("rate-limit-probe")};a?(l["x-api-key"]=n.apiKey,l["anthropic-version"]="2023-06-01"):l.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:l,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=K(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let i=await fetch(s,c);if(i.ok)return{success:!0};let u=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(l){return{success:!1,error:l?.message||l?.toString()||"Unknown ping error"}}}function rr(n,e,t,o,r){return xe||(xe=new wt(n,e,t,o,r)),xe}function Me(n,e,t,o,r){let s=rr(n,e,t,o,r);return s.start(),s}function Yn(){xe&&xe.stop()}function St(){xe&&(xe.stop(),xe=null)}var bl,xl,Cl,wt,xe,qn=P(()=>{"use strict";ce();He();nr();Ge();ko();ae();bl="x-claude-code-router-source",xl="x-claude-code-router-version";Cl={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};wt=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;running=!1;constructor(e,t,o,r,s){this.config={...Cl,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),t=D();if(e.length===0)return;let o=[];for(let s of e){let a=Xn(s.baseUrl),l=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let i;try{i=new URL(s.baseUrl).hostname}catch{i=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(i?` (host: ${i})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:l,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(i=>{if(i){dn(s.name,i),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=i.limitDaily!==void 0&&i.usedDailyBalance!==void 0&&i.usedDailyBalance>=i.limitDaily,d=i.totalBalance!==void 0&&i.usedBalance!==void 0&&i.usedBalance>=i.totalBalance;if(u||d){let m=u?`Quota exhausted: 5h limit reached (${i.usedDailyBalance}/${i.limitDaily})`:`Quota exhausted: 7d balance depleted (${i.usedBalance}/${i.totalBalance})`;for(let g of l){if(t.getState(s.name,g)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${g}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,g,m)}this.logger?.warn?.(`${m} for ${s.name}, marked as unhealthy`)}else for(let m of l){let g=t.getState(s.name,m);g&&g.status==="open"&&g.lastError?.includes("Quota exhausted")&&(t.recover(s.name,m),this.logger?.info?.(`Quota recovered for ${s.name} (${m}), marked as healthy`))}}})}),wl(s.baseUrl)&&o.push({provider:s.name,models:l,type:"rate-limit-headers",promise:or(s,this.config.probeTimeoutMs,c).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let l=o[s];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${a.reason}`)}}}async runHealthProbe(){let e=D(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>or(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],l=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.success){let i=0;for(let u of l){let d=e.getState(s.name,u);if(d&&d.status==="open"){let m=d.lastError?.includes("Quota exhausted"),g=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(m){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(g||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),i++}i>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let i of l)e.recordFailure(s.name,i,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{for(let c of l)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runRateLimitProbe(){let e=D(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...l]=s.split(","),c=l.join(",");if(!a||!c)continue;let i=e.getState(a,c);if(!i||!i.rateLimitUntil)continue;if(Date.now()>=i.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let u=o.find(d=>d?.name===a&&d.enabled!==!1);if(!u){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await Pl(u,c,r,this.resolveProxyUrl?.(u),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let m=Date.now();i.rateLimitUntil&&i.rateLimitUntil>m?i.rateLimitUntil+=120*1e3:i.rateLimitUntil=m+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=vl(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let c=l.wakeupTime||a,[i,u]=c.split(":"),d=parseInt(i,10),m=parseInt(u,10);if(isNaN(d)||isNaN(m))continue;let g=o>d||o===d&&r>=m,y=(d*60+m)*6e4-(o*60+r)*6e4,p=y>0&&y<=300*1e3;(g||p)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${c}`),Sl(l,3e4,this.resolveProxyUrl?.(l),this.logger).then(f=>{f.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${f.error}`)}).catch(f=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${f}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?Tl(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(a=>a.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let r=await or(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o)),s=Array.isArray(o.models)?o.models:[];if(r.success)for(let a of s)D().recordSuccess(o.name,a);else for(let a of s)D().recordFailure(o.name,a,r.error);return r.success}},xe=null});var Mi=P(()=>{"use strict"});var sr,Ze,$i=P(()=>{"use strict";sr=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Ze=new sr});var ue,ir=P(()=>{"use strict";ue=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
303
- `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,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 $e,ar=P(()=>{"use strict";$e=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
302
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(di).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});var fi,bt,mi=w(()=>{"use strict";fi=require("tiktoken"),bt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,fi.get_encoding)(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:i}=e;return Array.isArray(r)&&r.forEach(l=>{typeof l.content=="string"?o+=t.encode(l.content).length:Array.isArray(l.content)&&l.content.forEach(a=>{if(a.type==="text")o+=t.encode(a.text).length;else if(a.type==="tool_use")o+=t.encode(JSON.stringify(a.input)).length;else if(a.type==="tool_result"){let c=typeof a.content=="string"?a.content:JSON.stringify(a.content);o+=t.encode(c).length}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(l=>{l.type==="text"&&(typeof l.text=="string"?o+=t.encode(l.text).length:Array.isArray(l.text)&&l.text.forEach(a=>{o+=t.encode(a||"").length}))}),i&&i.forEach(l=>{l.description&&(o+=t.encode(l.name+l.description).length),l.input_schema&&(o+=t.encode(JSON.stringify(l.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});var Tt,gi,Xe,Ct,hi,zn,yi=w(()=>{"use strict";Tt=require("path"),gi=require("os"),Xe=require("fs"),Ct=require("fs"),hi=require("@huggingface/tokenizers"),zn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||(0,Tt.join)((0,gi.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,Tt.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,Tt.join)(e,"tokenizer.json"),tokenizerConfig:(0,Tt.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Xe.existsSync)(e)||(0,Xe.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Xe.existsSync)(e.tokenizerJson)||!(0,Xe.existsSync)(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Ct.promises.readFile(e.tokenizerJson,"utf-8"),Ct.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,i]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[l,a]=await Promise.all([s.json(),i.ok?i.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Ct.promises.writeFile(e.tokenizerJson,JSON.stringify(l,null,2)),Ct.promises.writeFile(e.tokenizerConfig,JSON.stringify(a,null,2))]),{tokenizerJson:l,tokenizerConfig:a}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new hi.Tokenizer(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let i of o)if(typeof i.content=="string")t.push(i.content);else if(Array.isArray(i.content))for(let l of i.content)l.type==="text"&&l.text?t.push(l.text):l.type==="tool_use"&&l.input?t.push(JSON.stringify(l.input)):l.type==="tool_result"&&t.push(typeof l.content=="string"?l.content:JSON.stringify(l.content))}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let i of r)if(i.type==="text"){if(typeof i.text=="string")t.push(i.text);else if(Array.isArray(i.text))for(let l of i.text)l&&t.push(l)}}if(s)for(let i of s)i.name&&t.push(i.name),i.description&&t.push(i.description),i.input_schema&&t.push(JSON.stringify(i.input_schema));return t.join(" ")}}});var Bn,_i=w(()=>{"use strict";se();Bn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),i={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},l=this.options.resolveProxyUrl?.();l&&(i.dispatcher=Q(l));let a=await fetch(this.config.url,i);if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let c=await a.json();return this.extractTokenCount(c)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ee,Do=w(()=>{"use strict";mi();yi();_i();se();Ee=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new bt("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new bt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new zn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Bn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return le(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function ki(n){if(!n||typeof n!="object"||Uc(n))return null;for(let t of Fc(n)){let o=Dc(t);if(o)return o}return null}function Dc(n){if(!n||typeof n!="object")return null;let e={},t=Jn(n,Mc);if(t!==void 0){let i=bi(t);e.usedDailyBalance=i,e.limitDaily=100}let o=Jn(n,$c);if(o!==void 0){let i=bi(o);e.usedBalance=i,e.totalBalance=100}let r=Jn(n,Nc);if(r!==void 0){let i=Ti(r);i&&(e.resetTime=i)}let s=Jn(n,Lc);if(s!==void 0){let i=Ti(s);i&&(e.resetTime7d=i,e.resetTime||(e.resetTime=i))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function bi(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Jn(n,e){for(let t of e){let o=$(n?.[t]);if(o!==void 0)return o}}function Fc(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let i of o)s[i]&&typeof s[i]=="object"&&r(s[i])}};return r(n),e}function Uc(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function Ti(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Wn(n){let e=Vo(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Kc:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Qc:e==="deepseek.com"||e.endsWith(".deepseek.com")?jc:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Hc:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?zc:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Bc:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Jc:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Wc:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Gc:null:null}function Vc(n){let e=Vo(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Yc(n,e){let t=Ko(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let i=s?.codingPlanAppCredentialDTO||s?.appCredential||s,l=String(i?.apiKey||i?.api_key||"").trim();return l&&o.some(a=>a.includes(l)||l.includes(a))})||t[0]}function Ko(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Ko(e)):Object.values(n).flatMap(e=>Ko(e))}function Qo(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Vo(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function $(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var ae,Fo,Uo,jo,Ho,zo,Mc,$c,Nc,Lc,Bo,Jo,Wo,Go,jc,Hc,zc,Bc,Jc,Wc,Gc,Kc,Qc,Yo=w(()=>{"use strict";se();ae=class{async fetchJson(e,t,o,r,s){let i=s||t.apiKey;if(!i)return null;let l={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${i}`},signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=Q(r));let a=await fetch(e,l);return a.ok?await a.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},Fo=class extends ae{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),i=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(a=>$(a?.total_balance)!==void 0);if(!i)return null;let l=$(i.total_balance);return l===void 0?null:{totalBalance:l,currency:typeof i.currency=="string"?i.currency:void 0}}},Uo=class extends ae{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let i={},l=$(s.limit),a=$(s.limit_remaining),c=$(s.usage),u=$(s.usage_daily);return l!==void 0&&(i.totalBalance=l),a!==void 0&&(i.remainingBalance=a),c!==void 0&&(i.usedBalance=c),u!==void 0&&(i.usedDailyBalance=u),this.hasQuotaData(i)?i:null}},jo=class extends ae{async queryQuota(e,t,o){let r=Vc(e.baseUrl),i=(await this.fetchJson(r,e,t,o))?.data;if(!i||typeof i!="object")return null;let l={},a=$(i.totalBalance),c=$(i.balance);return a!==void 0&&(l.totalBalance=a),c!==void 0&&(l.remainingBalance=c),a!==void 0&&c!==void 0&&(l.usedBalance=Math.max(0,a-c)),this.hasQuotaData(l)?l:null}},Ho=class extends ae{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Q(o));let i=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!i.ok)return null;let l=await i.json(),a=Array.isArray(l?.data?.limits)?l.data.limits:[],c=null,u=null,d=null;for(let m of a)m.type==="TOKENS_LIMIT"?m.unit===3?c=m:m.unit===6?u=m:c||(c=m):m.type==="TIME_LIMIT"&&(d=m);let g={};if(c){let m=$(c.currentValue),y=$(c.usage),p=$(c.remaining),f=$(c.percentage);m!==void 0?g.usedDailyBalance=m:f!==void 0&&(g.usedDailyBalance=f,g.limitDaily=100),y!==void 0?g.limitDaily=y:m!==void 0&&p!==void 0&&(g.limitDaily=m+p),c.nextResetTime&&(g.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let m=$(u.currentValue),y=$(u.usage),p=$(u.remaining),f=$(u.percentage);m!==void 0?g.usedBalance=m:f!==void 0&&(g.usedBalance=f,g.totalBalance=100),y!==void 0?g.totalBalance=y:m!==void 0&&p!==void 0&&(g.totalBalance=m+p),u.nextResetTime&&!g.resetTime&&(g.resetTime=new Date(u.nextResetTime).toISOString())}if(d){if(g.usedDailyBalance===void 0){let m=$(d.currentValue);m!==void 0&&(g.usedDailyBalance=m)}if(g.limitDaily===void 0){let m=$(d.usage),y=$(d.currentValue),p=$(d.remaining);m!==void 0?g.limitDaily=m:y!==void 0&&p!==void 0&&(g.limitDaily=y+p)}d.nextResetTime&&!g.resetTime&&(g.resetTime=new Date(d.nextResetTime).toISOString())}return this.hasQuotaData(g)?g:null}catch{return null}}},zo=class extends ae{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),i=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=Q(o));let l=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:i});if(!l.ok)return null;let c=(await l.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(c)||c.length===0)return null;let u=c[0]?.codingPlanQuotaInfo;if(!u)return null;let d={},g=$(u.per5HourUsedQuota),m=$(u.per5HourTotalQuota);g!==void 0&&(d.usedDailyBalance=g),m!==void 0&&(d.limitDaily=m);let y=$(u.perWeekUsedQuota),p=$(u.perWeekTotalQuota);return y!==void 0&&(d.usedBalance=y),p!==void 0&&(d.totalBalance=p),this.hasQuotaData(d)?d:null}catch{return null}}};Mc=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],$c=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Nc=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Lc=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Bo=class extends ae{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let i=await this.queryOfficialEndpoint(r,s,t,o);if(i)return i}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",i=Qo(e,"cna")||"",l=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":i}}}),a=new URLSearchParams({params:l,region:"cn-beijing",sec_token:t}).toString(),c={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:a,signal:AbortSignal.timeout(o)};try{r&&(c.dispatcher=Q(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,c);if(!u.ok)return null;let d=await u.json();return ki(d)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),i=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:i,signal:AbortSignal.timeout(t)};try{o&&(l.dispatcher=Q(o));let a=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,l);if(!a.ok)return null;let c=await a.json();return ki(c)}catch{return null}}},Jo=class extends ae{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Qo(e.quotaToken,"atp-auth-token")||Qo(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Q(o));let i=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!i.ok)return null;let l=await i.json();if(l?.succeed===!1||l?.failed===!0)return null;let a=Yc(l,e.apiKey),c=a?.codingPlanUsageDTO||a?.usage||a;if(!c||typeof c!="object")return null;let u={},d=$(c.rp5hUsage),g=$(c.rp5hLimit);d!==void 0&&(u.usedDailyBalance=d),g!==void 0&&(u.limitDaily=g);let m=$(c.rpwUsage),y=$(c.rpwLimit);return m!==void 0&&(u.usedBalance=m),y!==void 0&&(u.totalBalance=y),u.remainingBalance===void 0&&y!==void 0&&m!==void 0&&(u.remainingBalance=Math.max(0,y-m)),this.hasQuotaData(u)?u:null}catch{return null}}},Wo=class extends ae{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Q(o));let i=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!i.ok)return null;let l=await i.json(),a={},c=Array.isArray(l?.limits)?l.limits:[];if(c.length>0&&c[0]?.detail){let d=c[0].detail,g=$(d.limit),m=$(d.remaining),y=d.resetTime;g!==void 0&&m!==void 0&&(a.usedDailyBalance=Math.max(0,g-m),a.limitDaily=g),y&&(a.resetTime=new Date(y).toISOString())}let u=l?.usage;if(u){let d=$(u.limit),g=$(u.remaining),m=$(u.used),y=u.resetTime;d!==void 0&&(a.totalBalance=d,m!==void 0?a.usedBalance=m:g!==void 0&&(a.usedBalance=Math.max(0,d-g),a.remainingBalance=g)),y&&(a.resetTime7d=new Date(y).toISOString(),a.resetTime||(a.resetTime=a.resetTime7d))}return this.hasQuotaData(a)?a:null}catch{return null}}},Go=class extends ae{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Vo(e.baseUrl)||"api.minimaxi.com",i=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let l=[`https://${i}/v1/token_plan/remains`,`https://${i}/v1/api/openplatform/coding_plan/remains`],a=null;for(let b of l)if(a=await this.fetchJson(b,e,t,o,r.trim()),a)break;if(!a)return null;if(a?.base_resp){let b=a.base_resp.status_code;if(b!==void 0&&b!==0)return null}let c=Array.isArray(a?.model_remains)?a.model_remains:[];if(c.length===0)return null;let u=c[0],d={},g=$(u.current_interval_total_count),m=$(u.current_interval_usage_count),y=$(u.current_interval_remaining_percent),p=$(u.end_time);g!==void 0&&m!==void 0&&g>0?(d.usedDailyBalance=Math.max(0,g-m),d.limitDaily=g):y!==void 0&&(d.limitDaily=100,d.usedDailyBalance=Math.max(0,100-y)),p&&(d.resetTime=new Date(p).toISOString());let f=$(u.current_weekly_total_count),_=$(u.current_weekly_usage_count),k=$(u.current_weekly_remaining_percent),h=$(u.weekly_end_time);return f!==void 0&&_!==void 0&&f>0?(d.usedBalance=Math.max(0,f-_),d.remainingBalance=_,d.totalBalance=f):k!==void 0&&(d.totalBalance=100,d.usedBalance=Math.max(0,100-k),d.remainingBalance=k),h&&!d.resetTime&&(d.resetTime=new Date(h).toISOString()),this.hasQuotaData(d)?d:null}catch{return null}}},jc=new Fo,Hc=new Uo,zc=new jo,Bc=new Ho,Jc=new zo,Wc=new Bo,Gc=new Jo,Kc=new Wo,Qc=new Go});function Ci(n){return{[Xc]:n,[qc]:en}}function el(n){return n===!0||n==="true"||n===1||n==="1"}function tl(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function nl(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function ol(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Xo(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o)),s=nl(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let i={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(i.dispatcher=Q(t));let l=await fetch(s,i);if(l.headers&&ut(n.name,n.baseUrl,l.headers),l.ok)return{success:!0,headers:l.headers,latencyMs:r()};if(l.status===429)return{success:!1,error:`HTTP 429: ${(await l.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:l.headers,latencyMs:r(),errorKind:"http"};if(l.status>=400&&l.status<500)return{success:!0,headers:l.headers,latencyMs:r()};let a=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${a.slice(0,100)}`,headers:l.headers,latencyMs:r(),errorKind:"http"}}catch(i){let l=i?.message||i?.toString()||"Unknown probe error",a=i?.name==="TimeoutError"||i?.name==="AbortError"||i?.code===20||i?.code==="ABORT_ERR";return{success:!1,error:l,latencyMs:r(),errorKind:a?"timeout":"network"}}}async function rl(n,e,t,o){let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,i=n.baseUrl.includes("/messages")||r.includes("claude");try{let l={"Content-Type":"application/json",...Ci("scheduled-wakeup")};i?(l["x-api-key"]=n.apiKey,l["anthropic-version"]="2023-06-01"):l.Authorization=`Bearer ${n.apiKey}`;let a={method:"POST",headers:l,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(a.dispatcher=Q(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let c=await fetch(s,a);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(l){return{success:!1,error:l?.message||l?.toString()||"Unknown wake-up error"}}}async function sl(n,e,t,o,r){let s=n.baseUrl,i=n.baseUrl.includes("/messages")||e.includes("claude");try{let l={"Content-Type":"application/json",...Ci("rate-limit-probe")};i?(l["x-api-key"]=n.apiKey,l["anthropic-version"]="2023-06-01"):l.Authorization=`Bearer ${n.apiKey}`;let a={method:"POST",headers:l,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(a.dispatcher=Q(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let c=await fetch(s,a);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(l){return{success:!1,error:l?.message||l?.toString()||"Unknown ping error"}}}function qo(n,e,t,o,r){return ye||(ye=new vt(n,e,t,o,r)),ye}function Oe(n,e,t,o,r){let s=qo(n,e,t,o,r);return s.start(),s}function Gn(){ye&&ye.stop()}function xt(){ye&&(ye.stop(),ye=null)}var Xc,qc,Zc,vt,ye,Kn=w(()=>{"use strict";ie();je();Yo();Je();po();se();Xc="x-claude-code-router-source",qc="x-claude-code-router-version";Zc={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};vt=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s){this.config={...Zc,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,i;t.success?i=s?"slow":"healthy":i=t.errorKind==="timeout"?"timeout":"error";let l=this.probeTelemetry.get(e),a={provider:e,latencyMs:t.latencyMs,status:i,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:l?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,a),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),a}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),t=U();if(e.length===0)return;let o=[];for(let s of e){let i=Wn(s.baseUrl),l=Array.isArray(s.models)?s.models:[],a=this.resolveProxyUrl?.(s);if(!i){let c;try{c=new URL(s.baseUrl).hostname}catch{c=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(c?` (host: ${c})`:"")+" \u2014 skipping quota probe")}i&&o.push({provider:s.name,models:l,type:"quota-adapter",promise:i.queryQuota(s,this.config.probeTimeoutMs,a).then(c=>{if(c){sn(s.name,c),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,d=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(u||d){let g=u?`Quota exhausted: 5h limit reached (${c.usedDailyBalance}/${c.limitDaily})`:`Quota exhausted: 7d balance depleted (${c.usedBalance}/${c.totalBalance})`;for(let m of l){if(t.getState(s.name,m)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${m}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,m,g)}this.logger?.warn?.(`${g} for ${s.name}, marked as unhealthy`)}else for(let g of l){let m=t.getState(s.name,g);m&&m.status==="open"&&m.lastError?.includes("Quota exhausted")&&(t.recover(s.name,g),this.logger?.info?.(`Quota recovered for ${s.name} (${g}), marked as healthy`))}}})}),ol(s.baseUrl)&&o.push({provider:s.name,models:l,type:"rate-limit-headers",promise:Xo(s,this.config.probeTimeoutMs,a).then(c=>{this.recordProbe(s.name,c,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let i=r[s];if(i.status==="rejected"){let l=o[s];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${i.reason}`)}}}async runHealthProbe(){let e=U(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Xo(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],i=o[r],l=Array.isArray(s.models)?s.models:[];if(i.status==="fulfilled"){let a=i.value;if(this.recordProbe(s.name,a,"health"),a.success){let c=0;for(let u of l){let d=e.getState(s.name,u);if(d&&d.status==="open"){let g=d.lastError?.includes("Quota exhausted"),m=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(g){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(m||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),c++}c>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let c of l)e.recordFailure(s.name,c,a.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${a.error}`)}}else{this.recordProbe(s.name,{success:!1,error:i.reason?.message||String(i.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let a of l)e.recordFailure(s.name,a,i.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${i.reason}`)}}}async runRateLimitProbe(){let e=U(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[i,...l]=s.split(","),a=l.join(",");if(!i||!a)continue;let c=e.getState(i,a);if(!c||!c.rateLimitUntil)continue;if(Date.now()>=c.rateLimitUntil){e.recover(i,a),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let u=o.find(d=>d?.name===i&&d.enabled!==!1);if(!u){this.logger?.warn?.(`Provider ${i} not found or disabled for rate-limit probe`);continue}try{let d=await sl(u,a,r,this.resolveProxyUrl?.(u),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(i,a);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let g=Date.now();c.rateLimitUntil&&c.rateLimitUntil>g?c.rateLimitUntil+=120*1e3:c.rateLimitUntil=g+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=tl(t),i=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let a=l.wakeupTime||i,[c,u]=a.split(":"),d=parseInt(c,10),g=parseInt(u,10);if(isNaN(d)||isNaN(g))continue;let m=o>d||o===d&&r>=g,y=(d*60+g)*6e4-(o*60+r)*6e4,p=y>0&&y<=300*1e3;(m||p)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${a}`),rl(l,3e4,this.resolveProxyUrl?.(l),this.logger).then(f=>{f.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${f.error}`)}).catch(f=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${f}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?el(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(l=>l.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Xo(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o)),s=this.recordProbe(o.name,r,"manual"),i=Array.isArray(o.models)?o.models:[];if(r.success)for(let l of i)U().recordSuccess(o.name,l);else for(let l of i)U().recordFailure(o.name,l,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},ye=null});var vi=w(()=>{"use strict"});var Zo,qe,xi=w(()=>{"use strict";Zo=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},qe=new Zo});var ce,er=w(()=>{"use strict";ce=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
303
+ `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,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 Ae,tr=w(()=>{"use strict";Ae=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
304
304
  `),e.id&&(o+=`id: ${e.id}
305
305
  `),e.retry&&(o+=`retry: ${e.retry}
306
306
  `),e.data&&(e.data.type==="done"?o+=`data: [DONE]
307
307
  `:o+=`data: ${JSON.stringify(e.data)}
308
308
  `),o+=`
309
- `,t.enqueue(o)}})}}});var Pt,cr=P(()=>{"use strict";Pt=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var lr=P(()=>{"use strict";ir();ar();cr()});var Ni=P(()=>{"use strict"});var At,ur=P(()=>{"use strict";At=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},l="";if(r){let c=new Date().toISOString();l+=this.config.colors?`${this.colors.cyan}[${c}]${this.colors.reset} `:`[${c}] `}switch(s&&(l+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":l+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?l+=this.toMarkdown(e):l+=String(e);break;case"text":default:typeof e=="object"?l+=JSON.stringify(e,null,2):l+=String(e);break}return a&&Object.keys(a).length>0&&(l+=`
310
- `+(this.config.colors?`${this.colors.dim}`:""),l+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(l+=this.colors.reset)),l}toMarkdown(e,t=0){let o=" ".repeat(t);return Array.isArray(e)?e.map(r=>typeof r=="object"?`${o}-
309
+ `,t.enqueue(o)}})}}});var St,nr=w(()=>{"use strict";St=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let i=await e(s,o);i!==void 0&&o.enqueue(i)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var or=w(()=>{"use strict";er();tr();nr()});var Si=w(()=>{"use strict"});var Rt,rr=w(()=>{"use strict";Rt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:i}=t||{},l="";if(r){let a=new Date().toISOString();l+=this.config.colors?`${this.colors.cyan}[${a}]${this.colors.reset} `:`[${a}] `}switch(s&&(l+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":l+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?l+=this.toMarkdown(e):l+=String(e);break;case"text":default:typeof e=="object"?l+=JSON.stringify(e,null,2):l+=String(e);break}return i&&Object.keys(i).length>0&&(l+=`
310
+ `+(this.config.colors?`${this.colors.dim}`:""),l+="Metadata: "+JSON.stringify(i,null,2),this.config.colors&&(l+=this.colors.reset)),l}toMarkdown(e,t=0){let o=" ".repeat(t);return Array.isArray(e)?e.map(r=>typeof r=="object"?`${o}-
311
311
  ${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
312
312
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
313
313
  ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
314
- `):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var Ot,dr=P(()=>{"use strict";Ot=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:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},l={data:e};return r&&(l.timestamp=new Date().toISOString()),s&&(l.prefix=s),a&&Object.keys(a).length>0&&(l.metadata=a),l}async sendRequest(e,t,o,r,s){let a=new AbortController,l=setTimeout(()=>a.abort(),s);try{let c=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(l),!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);return c}catch(c){throw clearTimeout(l),c}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let l=null;for(let c=1;c<=a.maxAttempts;c++)try{return await this.sendRequest(e,t,o,r,s)}catch(i){if(l=i,c===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,c-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${c}/${a.maxAttempts}), retrying in ${u}ms...`,i.message),await this.delay(u)}throw l}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var et,pr,Li,Et,fr=P(()=>{"use strict";et=require("fs"),pr=require("path"),Li=require("os"),Et=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let t=(0,Li.tmpdir)();this.baseDir=(0,pr.join)(t,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,et.existsSync)(this.baseDir)||(0,et.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}getFilePath(e){let t=this.config.prefix||"session",o=this.config.extension?`.${this.config.extension}`:"",r;if(this.config.includeTimestamp){let s=Date.now();r=`${t}-${e}-${s}${o}`}else r=`${t}-${e}${o}`;return(0,pr.join)(this.baseDir,r)}async output(e,t={}){try{let o=t.metadata?.sessionId;if(!o)return!1;let r={...e,timestamp:Date.now(),sessionId:o},s=this.getFilePath(o);return(0,et.writeFileSync)(s,JSON.stringify(r,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var mr,tt,Fi=P(()=>{"use strict";ur();dr();fr();mr=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 o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new At(e.config);case"webhook":return new Ot(e.config);case"temp-file":return new Et(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 o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,l])=>{try{await l.output(e,o)?r.success.push(a):r.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async l=>{let c=this.handlers.get(l);if(!c){console.warn(`[OutputManager] Handler ${l} not found`),s.failed.push(l);return}try{await c.output(t,r)?s.success.push(l):s.failed.push(l)}catch(i){console.error(`[OutputManager] Handler ${l} failed:`,i),s.failed.push(l)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},tt=new mr});var gr=P(()=>{"use strict";Ni();ur();dr();fr();Fi()});function Ui(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Al);return Math.round(n/o)}function Mt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Di(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId},...t};for(let l of e)try{await tt.outputToType(l,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${l}:`,c)}}var ji,It,hr,Al,$t,zi=P(()=>{"use strict";ji=Y(require("fastify-plugin"),1);lr();gr();gt();It=new Map,hr=new Map,Al=1,$t={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,ji.default)(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)tt.registerHandlers(t.outputHandlers);else{let a=[];for(let l of o)l==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):l==="temp-file"?a.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):l==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&tt.registerHandlers(a)}t.outputOptions&&tt.setDefaultOptions(t.outputOptions);let r=async a=>{let l=n.tokenizerService;if(!l)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,i=a.model,u=`${c}:${i}`;if(hr.has(u))return hr.get(u);let d=l.getTokenizerConfigForModel(c,i);if(!d)return n.log?.debug(`No tokenizer config for ${c}:${i}, using fallback`),null;try{let m=await l.getTokenizer(d,c);return hr.set(u,m),n.log?.info(`Created tokenizer for ${c}:${i} - ${m.name}`),m}catch(m){return n.log?.warn(`Failed to create tokenizer for ${c}:${i}: ${m.message}`),null}},s=a=>{let l=new URL(`http://127.0.0.1${a}`).pathname;return l.endsWith("/v1/messages")||l.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,l,c)=>{let i=a.requestStartTime;if(!i)return;let u=a.id||Date.now().toString(),d=a.usageSessionId;if(!d)try{d=Ve(a.body?.metadata?.user_id)}catch{}if(!d){let f=a.headers?.["x-request-id"],_=Array.isArray(f)?f[0]:f;d=(typeof _=="string"?_:void 0)||u}let m=await r(a);if(c instanceof ReadableStream){It.set(u,{requestId:u,sessionId:d,startTime:i,lastTokenTime:i,tokenCount:0,tokensPerSecond:0,stream:!0});let[f,_]=c.tee(),k=async()=>{let h=null,b=async x=>{let v=It.get(u);if(!v)return;let C=v.firstTokenTime?v.firstTokenTime-v.startTime:0,T=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Ui(v.tokenCount,T,C),await Di(v,o,t.outputOptions,x).catch(O=>{n.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let v=_.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();for(h=setInterval(async()=>{It.get(u)&&await b(!1)},1e3);;){let{done:C,value:R}=await v.read();if(C)break;let T=R,O=It.get(u);if(!O)continue;let w=performance.now(),E=T.event||T.data?.type,A=T.event==="content_block_start"||T.event==="content_block_delta"||T.event==="text_block"||T.event==="content_block"||E==="response.output_text.delta"||E==="response.function_call_arguments.delta"||E==="response.reasoning_summary_text.delta";!O.firstTokenTime&&A&&(O.firstTokenTime=w,O.timeToFirstToken=Math.round(w-O.startTime));let I="";if(T.event==="content_block_delta"&&T.data?.delta){let L=T.data.delta.type;L==="text_delta"?I=T.data.delta.text||"":L==="input_json_delta"?I=T.data.delta.partial_json||"":L==="thinking_delta"&&(I=T.data.delta.thinking||"")}if((E==="response.output_text.delta"||E==="response.function_call_arguments.delta"||E==="response.reasoning_summary_text.delta")&&(I=typeof T.data?.delta=="string"?T.data.delta:""),I){let L=m&&m.encodeText?m.encodeText(I).length:Mt(I);O.tokenCount+=L,O.lastTokenTime=w}(T.event==="message_stop"||E==="response.completed"||E==="response.failed")&&(h&&(clearInterval(h),h=null),await b(!0),It.delete(u))}}catch(x){h&&clearInterval(h),x.name!=="AbortError"&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${x.message}`)}};return a.tokenSpeedCapturePromise=k().catch(h=>{console.log(h),n.log?.warn(`Background stats processing failed: ${h.message}`)}),f}let g=performance.now(),y=0,p=!1;if(c&&typeof c=="string")try{let f=JSON.parse(c);if(typeof f.usage?.output_tokens=="number")y=f.usage.output_tokens,p=!0;else{let _=f.content??f.message?.content;if(_!==void 0)if(p=!0,m)Array.isArray(_)?y=_.reduce((k,h)=>{if(h.type==="text"){let b=h.text||"";return k+(m.encodeText?m.encodeText(b).length:Mt(b))}return k},0):typeof _=="string"&&(y=m.encodeText?m.encodeText(_).length:Mt(_));else{let k=Array.isArray(_)?_.map(h=>h.text).join(""):typeof _=="string"?_:"";y=Mt(k)}}}catch{}if(p){let f=Math.round(g-i),_=g-i,k={requestId:u,sessionId:d,startTime:i,lastTokenTime:g,tokenCount:y,tokensPerSecond:Ui(y,_),timeToFirstToken:f,stream:!1};await Di(k,o,t.outputOptions,!0)}return c})})}});var yr=P(()=>{"use strict";Mi();$i();zi();gr()});function Hi(){if(process.env.VITEST||process.env.CI)throw new Error("Config write attempted during test/CI. Set CCR_CONFIG_DIR to a temp dir to isolate.")}var te,kr,Ce,W,_r,Nt,Lt,Zn,z,Ft,ne,Ol,eo,Ut=P(()=>{"use strict";te=Y(require("node:fs/promises"),1),kr=Y(require("json5"),1),Ce=Y(require("node:path"),1),W=require("@wengine-ai/claude-code-router-shared"),_r=n=>{if(typeof n=="string")return n.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,t,o)=>{let r=t||o;return process.env[r]||e});if(Array.isArray(n))return n.map(_r);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=_r(o);return e}return n},Nt=async n=>{try{await te.default.access(n)}catch{await te.default.mkdir(n,{recursive:!0})}},Lt=async()=>{await Nt(W.HOME_DIR),await Nt(W.PLUGINS_DIR),await Nt(Ce.default.join(W.HOME_DIR,"logs"))},Zn=async()=>{let n=await te.default.readFile(W.CONFIG_FILE,"utf-8");return kr.default.parse(n)},z=async()=>{try{let n=await te.default.readFile(W.CONFIG_FILE,"utf-8");try{let e=kr.default.parse(n);return _r(e)}catch(e){console.error(`Failed to parse config file at ${W.CONFIG_FILE}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await Lt();let e=await Ft();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await ne(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${W.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};Ft=async()=>{Hi();try{if(await te.default.access(W.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${W.CONFIG_FILE}.${n}.bak`;await te.default.copyFile(W.CONFIG_FILE,e);try{let t=Ce.default.dirname(W.CONFIG_FILE),o=Ce.default.basename(W.CONFIG_FILE),s=(await te.default.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let l=Ce.default.join(t,s[a]);await te.default.unlink(l)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},ne=async n=>{Hi(),await Nt(W.HOME_DIR),await Ol();let e=`${JSON.stringify(n,null,2)}`;await te.default.writeFile(W.CONFIG_FILE,e)},Ol=async()=>{if(!await te.default.access(W.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=Ce.default.join(W.HOME_DIR,"config-history");await Nt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ce.default.join(e,`config-${t}.json`);await te.default.copyFile(W.CONFIG_FILE,o);try{let s=(await te.default.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await te.default.unlink(Ce.default.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},eo=async()=>{let n=await z();return Object.assign(process.env,n),n}});function El(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function Il(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Ne(n){if(!(!n||typeof n!="object"))return{...n,input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:El(n),cache_creation_input_tokens:Il(n)}}function Dt(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var br=P(()=>{"use strict"});function to(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(xr(r,s))}return}if(Array.isArray(n)){for(let o of n)to(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))to(o,e,t)}}function Cr(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let l of a)l&&o.add(xr(s,l))}return to(n?.Router,t,o),to(n?.fallback,t,o),o}function nt(n,e){try{let t=D();if(!t?.getAllStates||!t?.recover)return 0;let o=Cr(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,l=s?.model;!a||!l||o.has(xr(a,l))||(t.recover(a,l),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function jt(n,e){try{if(!n)return 0;let t=D();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var Ml,xr,no=P(()=>{"use strict";ce();Ml="\0",xr=(n,e)=>`${n}${Ml}${e}`});function $l(n){return/\[1m\]/i.test(n)?1e6:2e5}function Nl(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Ll(n,e=n){let t=$l(n),o=Nl(n);return{type:"model",id:n,display_name:e,created_at:"2024-01-01T00:00:00Z",context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o,capabilities:{context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o}}}function zt(n){let e=new Map,t=(o,r=o)=>{!o||e.has(o)||e.set(o,Ll(o,r))};t("ccr-opus","CCR Opus"),t("ccr-sonnet","CCR Sonnet"),t("ccr-haiku","CCR Haiku"),t("ccr-opus[1m]","CCR Opus 1M"),t("ccr-sonnet[1m]","CCR Sonnet 1M"),t("ccr-haiku[1m]","CCR Haiku 1M");for(let o of n.Providers||n.providers||[])if(!(!o?.name||!Array.isArray(o.models)))for(let r of o.models)typeof r!="string"||!r||(t(r,r),t(`${o.name},${r}`,`${o.name}/${r}`));return Array.from(e.values())}var Tr=P(()=>{"use strict"});function Fl(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var Ht,vr=P(()=>{"use strict";Ht=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Fl(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let l=e.headers.authorization||e.headers["x-api-key"],c=Array.isArray(l)?l[0]:l||"";if(!c){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let i="";if(c.startsWith("Bearer")?i=c.split(" ")[1]:i=c,i!==a){t.log.warn({url:e.url,gotPrefix:i.slice(0,10),gotSuffix:i.slice(-6),gotLen:i.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var Or={};Yt(Or,{append:()=>Gt,clear:()=>Pr,close:()=>Xl,getOldestRecordTimestamp:()=>Yl,query:()=>Sr,querySummary:()=>Vt,readTokenSpeedStats:()=>Ar});function Hl(){(0,se.existsSync)(oo)||(0,se.mkdirSync)(oo,{recursive:!0})}function Wt(){if(ve)return ve;Hl();let n=new Wi.default(Ul);n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.pragma("busy_timeout = 5000");let e=n.pragma("user_version",{simple:!0})||0;return e<1&&(Jl(n),n.pragma("user_version = 1")),e<2&&(n.prepare("PRAGMA table_info(usage_records)").all().some(o=>o.name==="upstream_model")||n.exec("ALTER TABLE usage_records ADD COLUMN upstream_model TEXT"),n.pragma("user_version = 2")),Wl(n),Ki(n,!0),wr=n.prepare(`
314
+ `):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var wt,sr=w(()=>{"use strict";wt=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:o="json",timestamp:r=!0,prefix:s,metadata:i}=t||{},l={data:e};return r&&(l.timestamp=new Date().toISOString()),s&&(l.prefix=s),i&&Object.keys(i).length>0&&(l.metadata=i),l}async sendRequest(e,t,o,r,s){let i=new AbortController,l=setTimeout(()=>i.abort(),s);try{let a=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:i.signal});if(clearTimeout(l),!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);return a}catch(a){throw clearTimeout(l),a}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,i){let l=null;for(let a=1;a<=i.maxAttempts;a++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(l=c,a===i.maxAttempts)break;let u=i.backoffMs*Math.pow(2,a-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${a}/${i.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw l}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),i=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var Ze,ir,Ri,Pt,ar=w(()=>{"use strict";Ze=require("fs"),ir=require("path"),Ri=require("os"),Pt=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let t=(0,Ri.tmpdir)();this.baseDir=(0,ir.join)(t,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Ze.existsSync)(this.baseDir)||(0,Ze.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}getFilePath(e){let t=this.config.prefix||"session",o=this.config.extension?`.${this.config.extension}`:"",r;if(this.config.includeTimestamp){let s=Date.now();r=`${t}-${e}-${s}${o}`}else r=`${t}-${e}${o}`;return(0,ir.join)(this.baseDir,r)}async output(e,t={}){try{let o=t.metadata?.sessionId;if(!o)return!1;let r={...e,timestamp:Date.now(),sessionId:o},s=this.getFilePath(o);return(0,Ze.writeFileSync)(s,JSON.stringify(r,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var cr,et,wi=w(()=>{"use strict";rr();sr();ar();cr=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 o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new Rt(e.config);case"webhook":return new wt(e.config);case"temp-file":return new Pt(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 o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([i,l])=>{try{await l.output(e,o)?r.success.push(i):r.failed.push(i)}catch(a){console.error(`[OutputManager] Handler ${i} failed:`,a),r.failed.push(i)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},i=e.map(async l=>{let a=this.handlers.get(l);if(!a){console.warn(`[OutputManager] Handler ${l} not found`),s.failed.push(l);return}try{await a.output(t,r)?s.success.push(l):s.failed.push(l)}catch(c){console.error(`[OutputManager] Handler ${l} failed:`,c),s.failed.push(l)}});return await Promise.all(i),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,i])=>i.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},et=new cr});var lr=w(()=>{"use strict";Si();rr();sr();ar();wi()});function Pi(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,il);return Math.round(n/o)}function Ot(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Ei(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},i={prefix:r,metadata:{sessionId:n.sessionId},...t};for(let l of e)try{await et.outputToType(l,s,i)}catch(a){console.error(`[TokenSpeedPlugin] Failed to output to ${l}:`,a)}}var Oi,Et,ur,il,At,Ai=w(()=>{"use strict";Oi=Y(require("fastify-plugin"),1);or();lr();pt();Et=new Map,ur=new Map,il=1,At={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,Oi.default)(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)et.registerHandlers(t.outputHandlers);else{let i=[];for(let l of o)l==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):l==="temp-file"?i.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):l==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&et.registerHandlers(i)}t.outputOptions&&et.setDefaultOptions(t.outputOptions);let r=async i=>{let l=n.tokenizerService;if(!l)return n.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let a=i.provider,c=i.model,u=`${a}:${c}`;if(ur.has(u))return ur.get(u);let d=l.getTokenizerConfigForModel(a,c);if(!d)return n.log?.debug(`No tokenizer config for ${a}:${c}, using fallback`),null;try{let g=await l.getTokenizer(d,a);return ur.set(u,g),n.log?.info(`Created tokenizer for ${a}:${c} - ${g.name}`),g}catch(g){return n.log?.warn(`Failed to create tokenizer for ${a}:${c}: ${g.message}`),null}},s=i=>{let l=new URL(`http://127.0.0.1${i}`).pathname;return l.endsWith("/v1/messages")||l.endsWith("/v1/responses")};n.addHook("onRequest",async i=>{s(i.url)&&(i.requestStartTime=performance.now())}),n.addHook("onSend",async(i,l,a)=>{let c=i.requestStartTime;if(!c)return;let u=i.id||Date.now().toString(),d=i.usageSessionId;if(!d)try{d=We(i.body?.metadata?.user_id)}catch{}if(!d){let f=i.headers?.["x-request-id"],_=Array.isArray(f)?f[0]:f;d=(typeof _=="string"?_:void 0)||u}let g=await r(i);if(a instanceof ReadableStream){Et.set(u,{requestId:u,sessionId:d,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[f,_]=a.tee(),k=async()=>{let h=null,b=async T=>{let x=Et.get(u);if(!x)return;let v=x.firstTokenTime?x.firstTokenTime-x.startTime:0,C=(T?x.lastTokenTime:performance.now())-x.startTime;x.tokensPerSecond=Pi(x.tokenCount,C,v),await Ei(x,o,t.outputOptions,T).catch(P=>{n.log?.warn(`Failed to output streaming stats: ${P.message}`)})};try{let x=_.pipeThrough(new TextDecoderStream).pipeThrough(new ce).getReader();for(h=setInterval(async()=>{Et.get(u)&&await b(!1)},1e3);;){let{done:v,value:S}=await x.read();if(v)break;let C=S,P=Et.get(u);if(!P)continue;let R=performance.now(),A=C.event||C.data?.type,E=C.event==="content_block_start"||C.event==="content_block_delta"||C.event==="text_block"||C.event==="content_block"||A==="response.output_text.delta"||A==="response.function_call_arguments.delta"||A==="response.reasoning_summary_text.delta";!P.firstTokenTime&&E&&(P.firstTokenTime=R,P.timeToFirstToken=Math.round(R-P.startTime));let I="";if(C.event==="content_block_delta"&&C.data?.delta){let L=C.data.delta.type;L==="text_delta"?I=C.data.delta.text||"":L==="input_json_delta"?I=C.data.delta.partial_json||"":L==="thinking_delta"&&(I=C.data.delta.thinking||"")}if((A==="response.output_text.delta"||A==="response.function_call_arguments.delta"||A==="response.reasoning_summary_text.delta")&&(I=typeof C.data?.delta=="string"?C.data.delta:""),I){let L=g&&g.encodeText?g.encodeText(I).length:Ot(I);P.tokenCount+=L,P.lastTokenTime=R}(C.event==="message_stop"||A==="response.completed"||A==="response.failed")&&(h&&(clearInterval(h),h=null),await b(!0),Et.delete(u))}}catch(T){h&&clearInterval(h),T.name!=="AbortError"&&T.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${T.message}`)}};return i.tokenSpeedCapturePromise=k().catch(h=>{console.log(h),n.log?.warn(`Background stats processing failed: ${h.message}`)}),f}let m=performance.now(),y=0,p=!1;if(a&&typeof a=="string")try{let f=JSON.parse(a);if(typeof f.usage?.output_tokens=="number")y=f.usage.output_tokens,p=!0;else{let _=f.content??f.message?.content;if(_!==void 0)if(p=!0,g)Array.isArray(_)?y=_.reduce((k,h)=>{if(h.type==="text"){let b=h.text||"";return k+(g.encodeText?g.encodeText(b).length:Ot(b))}return k},0):typeof _=="string"&&(y=g.encodeText?g.encodeText(_).length:Ot(_));else{let k=Array.isArray(_)?_.map(h=>h.text).join(""):typeof _=="string"?_:"";y=Ot(k)}}}catch{}if(p){let f=Math.round(m-c),_=m-c,k={requestId:u,sessionId:d,startTime:c,lastTokenTime:m,tokenCount:y,tokensPerSecond:Pi(y,_),timeToFirstToken:f,stream:!1};await Ei(k,o,t.outputOptions,!0)}return a})})}});var dr=w(()=>{"use strict";vi();xi();Ai();lr()});function Ii(){if(process.env.VITEST||process.env.CI)throw new Error("Config write attempted during test/CI. Set CCR_CONFIG_DIR to a temp dir to isolate.")}var ee,fr,_e,J,pr,It,Mt,Qn,oe,$t,Ie,al,Vn,Yn=w(()=>{"use strict";ee=Y(require("node:fs/promises"),1),fr=Y(require("json5"),1),_e=Y(require("node:path"),1),J=require("@wengine-ai/claude-code-router-shared"),pr=n=>{if(typeof n=="string")return n.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,t,o)=>{let r=t||o;return process.env[r]||e});if(Array.isArray(n))return n.map(pr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=pr(o);return e}return n},It=async n=>{try{await ee.default.access(n)}catch{await ee.default.mkdir(n,{recursive:!0})}},Mt=async()=>{await It(J.HOME_DIR),await It(J.PLUGINS_DIR),await It(_e.default.join(J.HOME_DIR,"logs"))},Qn=async()=>{let n=await ee.default.readFile(J.CONFIG_FILE,"utf-8");return fr.default.parse(n)},oe=async()=>{try{let n=await ee.default.readFile(J.CONFIG_FILE,"utf-8");try{let e=fr.default.parse(n);return pr(e)}catch(e){console.error(`Failed to parse config file at ${J.CONFIG_FILE}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await Mt();let e=await $t();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await Ie(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${J.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};$t=async()=>{Ii();try{if(await ee.default.access(J.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${J.CONFIG_FILE}.${n}.bak`;await ee.default.copyFile(J.CONFIG_FILE,e);try{let t=_e.default.dirname(J.CONFIG_FILE),o=_e.default.basename(J.CONFIG_FILE),s=(await ee.default.readdir(t)).filter(i=>i.startsWith(o)&&i.endsWith(".bak")).sort().reverse();if(s.length>3)for(let i=3;i<s.length;i++){let l=_e.default.join(t,s[i]);await ee.default.unlink(l)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},Ie=async n=>{Ii(),await It(J.HOME_DIR),await al();let e=`${JSON.stringify(n,null,2)}`;await ee.default.writeFile(J.CONFIG_FILE,e)},al=async()=>{if(!await ee.default.access(J.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=_e.default.join(J.HOME_DIR,"config-history");await It(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=_e.default.join(e,`config-${t}.json`);await ee.default.copyFile(J.CONFIG_FILE,o);try{let s=(await ee.default.readdir(e)).filter(i=>i.startsWith("config-")&&i.endsWith(".json")).sort().reverse();if(s.length>50)for(let i of s.slice(50))await ee.default.unlink(_e.default.join(e,i))}catch(r){console.warn("Failed to prune config-history:",r)}},Vn=async()=>{let n=await oe();return Object.assign(process.env,n),n}});function cl(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function ll(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Me(n){if(!(!n||typeof n!="object"))return{...n,input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:cl(n),cache_creation_input_tokens:ll(n)}}function Nt(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var mr=w(()=>{"use strict"});function Xn(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(gr(r,s))}return}if(Array.isArray(n)){for(let o of n)Xn(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))Xn(o,e,t)}}function hr(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let i=Array.isArray(r?.models)?r.models:[];for(let l of i)l&&o.add(gr(s,l))}return Xn(n?.Router,t,o),Xn(n?.fallback,t,o),o}function tt(n,e){try{let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=hr(n),r=0;for(let s of t.getAllStates()||[]){let i=s?.provider,l=s?.model;!i||!l||o.has(gr(i,l))||(t.recover(i,l),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function Lt(n,e){try{if(!n)return 0;let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var ul,gr,qn=w(()=>{"use strict";ie();ul="\0",gr=(n,e)=>`${n}${ul}${e}`});function dl(n){return/\[1m\]/i.test(n)?1e6:2e5}function pl(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function fl(n,e=n){let t=dl(n),o=pl(n);return{type:"model",id:n,display_name:e,created_at:"2024-01-01T00:00:00Z",context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o,capabilities:{context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o}}}function Dt(n){let e=new Map,t=(o,r=o)=>{!o||e.has(o)||e.set(o,fl(o,r))};t("ccr-opus","CCR Opus"),t("ccr-sonnet","CCR Sonnet"),t("ccr-haiku","CCR Haiku"),t("ccr-opus[1m]","CCR Opus 1M"),t("ccr-sonnet[1m]","CCR Sonnet 1M"),t("ccr-haiku[1m]","CCR Haiku 1M");for(let o of n.Providers||n.providers||[])if(!(!o?.name||!Array.isArray(o.models)))for(let r of o.models)typeof r!="string"||!r||(t(r,r),t(`${o.name},${r}`,`${o.name}/${r}`));return Array.from(e.values())}var yr=w(()=>{"use strict"});function ml(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var Ft,_r=w(()=>{"use strict";Ft=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||ml(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let i=n.APIKEY;if(!i){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let l=e.headers.authorization||e.headers["x-api-key"],a=Array.isArray(l)?l[0]:l||"";if(!a){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let c="";if(a.startsWith("Bearer")?c=a.split(" ")[1]:c=a,c!==i){t.log.warn({url:e.url,gotPrefix:c.slice(0,10),gotSuffix:c.slice(-6),gotLen:c.length,expectedPrefix:i.slice(0,6),expectedSuffix:i.slice(-6),expectedLen:i.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var xr={};Gt(xr,{append:()=>zt,clear:()=>Cr,close:()=>Ol,getOldestRecordTimestamp:()=>Al,query:()=>Tr,querySummary:()=>Bt,readTokenSpeedStats:()=>vr});function kl(){(0,re.existsSync)(eo)||(0,re.mkdirSync)(eo,{recursive:!0})}function Ht(){if(be)return be;kl();let n=new Ni.default(gl);n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.pragma("busy_timeout = 5000");let e=n.pragma("user_version",{simple:!0})||0;return e<1&&(bl(n),n.pragma("user_version = 1")),e<2&&(n.prepare("PRAGMA table_info(usage_records)").all().some(o=>o.name==="upstream_model")||n.exec("ALTER TABLE usage_records ADD COLUMN upstream_model TEXT"),n.pragma("user_version = 2")),Cl(n),Fi(n,!0),br=n.prepare(`
315
315
  INSERT INTO usage_records (
316
316
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
317
- scenario_type, client_type, codex_account_id, codex_account_email,
317
+ scenario_type, client_type,
318
318
  stream, input_tokens, output_tokens, cache_read_input_tokens,
319
319
  cache_creation_input_tokens, ttft, tokens_per_second, duration_ms,
320
320
  status, error_message, response_body
321
321
  ) VALUES (
322
322
  @id, @timestamp, @session_id, @provider, @original_model, @model, @upstream_model,
323
- @model_family, @scenario_type, @client_type, @codex_account_id,
324
- @codex_account_email, @stream, @input_tokens, @output_tokens,
323
+ @model_family, @scenario_type, @client_type,
324
+ @stream, @input_tokens, @output_tokens,
325
325
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
326
326
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
327
327
  )
328
- `),ve=n,ve}function Jl(n){n.exec(`
328
+ `),be=n,be}function bl(n){n.exec(`
329
329
  CREATE TABLE IF NOT EXISTS usage_records (
330
330
  id TEXT PRIMARY KEY,
331
331
  timestamp TEXT NOT NULL,
@@ -337,8 +337,6 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
337
337
  model_family TEXT NOT NULL,
338
338
  scenario_type TEXT NOT NULL,
339
339
  client_type TEXT,
340
- codex_account_id TEXT,
341
- codex_account_email TEXT,
342
340
  stream INTEGER NOT NULL,
343
341
  input_tokens INTEGER NOT NULL,
344
342
  output_tokens INTEGER NOT NULL,
@@ -364,31 +362,51 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
364
362
  CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
365
363
  CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
366
364
  CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
367
- `)}function Bl(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Jt(n,e,t){n.prepare(`
365
+ `)}function Tl(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ut(n,e,t){n.prepare(`
368
366
  INSERT INTO usage_meta (key, value)
369
367
  VALUES (?, ?)
370
368
  ON CONFLICT(key) DO UPDATE SET value = excluded.value
371
- `).run(e,t)}function Wl(n){if(Bl(n,Ji)||!(0,se.existsSync)(Rr))return;let e=Vl(n,"INSERT OR IGNORE"),t=(0,se.readFileSync)(Rr,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let l of t.split(`
372
- `)){let c=l.trim();if(c)try{let i=JSON.parse(c);if(!Gl(i)){r++;continue}e.run(Vi(so(i))).changes>0?o++:s++}catch{r++}}Jt(n,Ji,new Date().toISOString()),Jt(n,"legacy_usage_jsonl_migrated_path",Rr),Jt(n,"legacy_usage_jsonl_imported_count",String(o)),Jt(n,"legacy_usage_jsonl_skipped_count",String(r)),Jt(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function Gl(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.timestamp=="string"&&e.timestamp.length>0}function Vl(n,e="INSERT"){return n.prepare(`
369
+ `).run(e,t)}function Cl(n){if(Tl(n,Mi)||!(0,re.existsSync)(kr))return;let e=xl(n,"INSERT OR IGNORE"),t=(0,re.readFileSync)(kr,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let l of t.split(`
370
+ `)){let a=l.trim();if(a)try{let c=JSON.parse(a);if(!vl(c)){r++;continue}e.run(Di(no(c))).changes>0?o++:s++}catch{r++}}Ut(n,Mi,new Date().toISOString()),Ut(n,"legacy_usage_jsonl_migrated_path",kr),Ut(n,"legacy_usage_jsonl_imported_count",String(o)),Ut(n,"legacy_usage_jsonl_skipped_count",String(r)),Ut(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function vl(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.timestamp=="string"&&e.timestamp.length>0}function xl(n,e="INSERT"){return n.prepare(`
373
371
  ${e} INTO usage_records (
374
372
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
375
- scenario_type, client_type, codex_account_id, codex_account_email,
373
+ scenario_type, client_type,
376
374
  stream, input_tokens, output_tokens, cache_read_input_tokens,
377
375
  cache_creation_input_tokens, ttft, tokens_per_second, duration_ms,
378
376
  status, error_message, response_body
379
377
  ) VALUES (
380
378
  @id, @timestamp, @session_id, @provider, @original_model, @model, @upstream_model,
381
- @model_family, @scenario_type, @client_type, @codex_account_id,
382
- @codex_account_email, @stream, @input_tokens, @output_tokens,
379
+ @model_family, @scenario_type, @client_type,
380
+ @stream, @input_tokens, @output_tokens,
383
381
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
384
382
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
385
383
  )
386
- `)}function Ql(n,e,t){if(n<=0||e==null||!Number.isFinite(e))return null;let o=t!=null&&Number.isFinite(t)?t:0,r=Math.max((e-o)/1e3,Dl);return Math.round(n/r)}function so(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=Le(n.ttft);return{...n,ttft:r,tokensPerSecond:Ql(e,o,r)}}function Te(n){return typeof n=="string"?n:n==null?"":String(n)}function ot(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function Bt(n){let e=Number(n);return Number.isFinite(e)?e:0}function Gi(n){return n==="success"?"success":"error"}function Vi(n){let e=so(n);return{id:Te(e.id),timestamp:Te(e.timestamp),session_id:Te(e.sessionId),provider:Te(e.provider),original_model:Te(e.originalModel),model:Te(e.model),upstream_model:ot(e.upstreamModel)??null,model_family:Te(e.modelFamily),scenario_type:Te(e.scenarioType),client_type:ot(e.clientType)??null,codex_account_id:ot(e.codexAccountId)??null,codex_account_email:ot(e.codexAccountEmail)??null,stream:e.stream?1:0,input_tokens:Math.trunc(Bt(e.inputTokens)),output_tokens:Math.trunc(Bt(e.outputTokens)),cache_read_input_tokens:Math.trunc(Bt(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(Bt(e.cacheCreationInputTokens)),ttft:Le(e.ttft),tokens_per_second:Le(e.tokensPerSecond),duration_ms:Math.trunc(Bt(e.durationMs)),status:Gi(e.status),error_message:ot(e.errorMessage)??null,response_body:ot(e.responseBody)??null}}function Qi(n){return so({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,codexAccountId:n.codex_account_id??void 0,codexAccountEmail:n.codex_account_email??void 0,stream:n.stream===1,inputTokens:n.input_tokens,outputTokens:n.output_tokens,cacheReadInputTokens:n.cache_read_input_tokens,cacheCreationInputTokens:n.cache_creation_input_tokens,ttft:n.ttft,tokensPerSecond:n.tokens_per_second,durationMs:n.duration_ms,status:Gi(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function Kl(){return new Date(Date.now()-jl*24*60*60*1e3).toISOString()}function Ki(n,e=!1){let t=Date.now();!e&&t-Bi<zl||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(Kl()),Bi=t)}function Xi(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function Yi(n,e){let t=Xi(e);return n.prepare(`SELECT * FROM usage_records ${t.sql}`).all(...t.params).map(Qi)}function qi(n){let e={totalRequests:n.length,successCount:0,errorCount:0,totalInputTokens:0,totalOutputTokens:0,totalCacheReadInputTokens:0,totalCacheCreationInputTokens:0,avgTtft:null,avgTokensPerSecond:null,byModel:{},byProvider:{},byScenario:{},byFamily:{},byDay:{},byClient:{}},t=0,o=0,r=0,s=0;for(let a of n){let l=a.status==="success";l?e.successCount++:e.errorCount++;let c=l&&a.inputTokens||0,i=l&&a.outputTokens||0,u=l&&a.cacheReadInputTokens||0,d=l&&a.cacheCreationInputTokens||0;e.totalInputTokens+=c,e.totalOutputTokens+=i,e.totalCacheReadInputTokens+=u,e.totalCacheCreationInputTokens+=d,l&&a.ttft!=null&&(t+=a.ttft,o++),l&&a.tokensPerSecond!=null&&(r+=a.tokensPerSecond,s++);let m=a.timestamp.slice(0,10);if(rt(e.byModel,a.model,c,i,u,d),rt(e.byProvider,a.provider,c,i,u,d),rt(e.byScenario,a.scenarioType,c,i,u,d),a.modelFamily){let g=`${a.modelFamily}/${a.scenarioType}`;rt(e.byFamily,g,c,i,u,d)}rt(e.byDay,m,c,i,u,d),rt(e.byClient,a.clientType||"unknown",c,i,u,d)}return o>0&&(e.avgTtft=Math.round(t/o)),s>0&&(e.avgTokensPerSecond=Math.round(r/s)),e}function rt(n,e,t,o,r,s){n[e]||(n[e]={count:0,inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0}),n[e].count++,n[e].inputTokens+=t,n[e].outputTokens+=o,n[e].cacheReadInputTokens+=r,n[e].cacheCreationInputTokens+=s}function Gt(n){let e=Wt(),t=so(n);wr.run(Vi(t)),Ki(e)}function Sr(n){let e=Wt(),t=Xi(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.floor(n.pageSize):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),l=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),c=qi(Yi(e,n));return{records:l.map(Qi),summary:c,total:a.count,page:o,pageSize:r}}function Vt(n,e,t){let o=Wt();return qi(Yi(o,{startTime:n,endTime:e,status:t}))}function Pr(n){let e=Wt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Xl(){ve&&(ve.pragma("wal_checkpoint(TRUNCATE)"),ve.close(),ve=null,wr=null)}function Le(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function Ar(n){let e=(0,Fe.join)((0,ro.tmpdir)(),"claude-code-router"),t=(0,Fe.join)(e,`session-${n}.json`);if((0,se.existsSync)(t))try{let o=(0,se.readFileSync)(t,"utf-8"),r=JSON.parse(o);return{ttft:Le(r.timeToFirstToken),tokensPerSecond:Le(r.tokensPerSecond)}}catch{}try{let o=(0,se.readdirSync)(e),r=new RegExp(`^session-${n}-\\d+\\.json$`),s=o.filter(a=>r.test(a));if(s.length>0){let a=s.sort().reverse(),l=(0,Fe.join)(e,a[0]);try{let c=(0,se.readFileSync)(l,"utf-8"),i=JSON.parse(c);return{ttft:Le(i.timeToFirstToken),tokensPerSecond:Le(i.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}}catch{}return{ttft:null,tokensPerSecond:null}}function Yl(n,e,t){return Wt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var se,Fe,ro,Wi,oo,Ul,Rr,Dl,jl,zl,Ji,ve,wr,Bi,Qt=P(()=>{"use strict";se=require("fs"),Fe=require("path"),ro=require("os"),Wi=Y(require("better-sqlite3"),1),oo=(0,Fe.join)((0,ro.homedir)(),".claude-code-router","data"),Ul=(0,Fe.join)(oo,"usage.sqlite"),Rr=(0,Fe.join)(oo,"usage.jsonl"),Dl=1,jl=180,zl=3600*1e3,Ji="legacy_usage_jsonl_migrated_at",ve=null,wr=null,Bi=0});async function oa(){let n=(0,ea.homedir)(),e=(0,ta.join)(n,".claude.json");if(!(0,Zi.existsSync)(e)){let o={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await(0,na.writeFile)(e,JSON.stringify(o,null,2))}}var Zi,ea,ta,na,ra=P(()=>{"use strict";Zi=require("fs"),ea=require("os"),ta=require("path"),na=require("fs/promises")});function ql(n){let e=n.Clients?.codex?.autoSwitchUsageThreshold;return typeof e=="number"&&Number.isFinite(e)?Math.min(100,Math.max(1,e)):95}function Zl(n){try{let e=(0,aa.join)(ie.HOME_DIR,"codex-accounts",`${n}.auth.json`);if(!(0,io.existsSync)(e))return{};let t=JSON.parse((0,io.readFileSync)(e,"utf8"));return{accessToken:t?.tokens?.access_token,chatGptAccountId:t?.tokens?.account_id||n}}catch{return{}}}function eu(n){let e=n?.rate_limit;if(!e)return null;let t=e.primary_window,o=e.secondary_window;return{used5h:typeof t?.used_percent=="number"?t.used_percent:void 0,used7d:typeof o?.used_percent=="number"?o.used_percent:void 0,resetAfter5h:typeof t?.reset_after_seconds=="number"?t.reset_after_seconds:void 0,resetAfter7d:typeof o?.reset_after_seconds=="number"?o.reset_after_seconds:void 0}}async function tu(n){let{accessToken:e,chatGptAccountId:t}=Zl(n);if(!e)return null;let o={Authorization:`Bearer ${e}`,"ChatGPT-Account-Id":t||n,originator:"codex_cli_rs",Accept:"application/json","Accept-Encoding":"gzip, deflate","User-Agent":"codex_cli_rs/0.0.0"},r=["https://chatgpt.com/backend-api/wham/usage","https://chatgpt.com/backend-api/codex/usage"];for(let s of r)try{let a=await fetch(s,{headers:o,signal:AbortSignal.timeout(15e3)});if(!a.ok)continue;let l=eu(await a.json());if(l)return l}catch{}return null}function nu(n,e){let t=typeof n.used7d=="number"&&n.used7d>=e,o=typeof n.used5h=="number"&&n.used5h>=e;return t?{window:"7d",used:n.used7d,retryAfterSeconds:n.resetAfter7d}:o?{window:"5h",used:n.used5h,retryAfterSeconds:n.resetAfter5h}:null}async function ou(){try{let n=await z(),e=(0,ie.getActiveCodexAccount)(n);return{id:e?.id,email:e?.email}}catch{return{}}}async function ca(){try{let n=await z();if((n.Clients?.codex||{}).autoSwitchAccounts===!1)return;let t=ql(n),o=Math.max(1,(0,ie.listCodexAccounts)(n).accounts.length);for(let r=0;r<o;r+=1){let s=(0,ie.getActiveCodexAccount)(n);if(!s?.id)return;let a=await tu(s.id);if(!a)return;let l=nu(a,t);if(!l)return;let c=`Codex ${l.window} usage reached ${Math.round(l.used)}% (auto-switch threshold ${t}%)`,i=(0,ie.markActiveCodexAccountLimitedAndSwitch)(n,c,l.retryAfterSeconds);if(await ne(i.config),!i.switchedAccount){console.warn(`[Codex] ${c}; no available Codex account could be switched to`);return}console.warn(`[Codex] ${c}; switched account to ${i.switchedAccount.email||i.switchedAccount.id}`),n=i.config}}catch(n){console.error("Failed to auto-switch Codex account before usage limit:",n)}}async function ao(n){try{let e=await z();if((e.Clients?.codex||{}).autoSwitchAccounts===!1)return;let o=(0,ie.markActiveCodexAccountLimitedAndSwitch)(e,n);await ne(o.config),o.switchedAccount?console.warn(`[Codex] Rate limit detected; switched account to ${o.switchedAccount.email||o.switchedAccount.id}`):console.warn("[Codex] Rate limit detected, but no available Codex account could be switched to")}catch(e){console.error("Failed to auto-switch Codex account after rate limit:",e)}}async function ia(){try{let n=await z();if(n.Clients?.codex?.autoRefreshTokens===!1)return;let e=await(0,ie.refreshDueCodexAccounts)(n);for(let t of e)t.refreshed?console.log(`[Codex] Refreshed tokens for account ${t.label} (${t.id})`):console.warn(`[Codex] Failed to refresh tokens for account ${t.label} (${t.id}): ${t.error}`)}catch(n){console.error("[Codex] Token refresh cycle failed:",n)}}function la(){if(sa)return;sa=!0,setTimeout(()=>void ia(),6e4).unref(),setInterval(()=>void ia(),ru).unref()}function co(n,e){return n===429||!!(e&&/rate[\s_]limit|too many|限流|频率限制|qps_limit|token_limit|quota exhausted|usage limit|limit reached/i.test(e))}async function ua(){return ou()}var io,aa,ie,ru,sa,Er=P(()=>{"use strict";io=require("fs"),aa=require("path"),ie=require("@wengine-ai/claude-code-router-shared");Ut();ru=1800*1e3,sa=!1});function pa(n=(0,Ir.join)(fa.HOME_DIR,"logs")){try{if(!(0,Re.existsSync)(n))return;let e=Date.now()-iu;for(let t of(0,Re.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,Ir.join)(n,t),r=(0,Re.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,Re.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function ma(){da||(da=!0,pa(),setInterval(pa,au).unref())}var Re,Ir,fa,su,iu,au,da,ga=P(()=>{"use strict";Re=require("fs"),Ir=require("path"),fa=require("@wengine-ai/claude-code-router-shared"),su=7,iu=su*24*60*60*1e3,au=1440*60*1e3,da=!1});async function ha(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":Ze.registerPlugin($t,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await Ze.enablePlugins(n)}var ya=P(()=>{"use strict";yr()});function _a(n){if(!(typeof n!="number"||!Number.isFinite(n)))return new Date(n*1e3).toISOString()}function ba(){if(!(0,me.existsSync)($r))return{};try{let n=JSON.parse((0,me.readFileSync)($r,"utf8"));return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function xa(n){(0,me.mkdirSync)(ka,{recursive:!0}),(0,me.writeFileSync)($r,`${JSON.stringify(n,null,2)}
387
- `,"utf8")}function uu(n,e){let t=!1,o={};for(let[r,s]of Object.entries(n))e.has(r)?o[r]=s:t=!0;return t&&xa(o),t?o:n}function du(n,e){if(!n?.fetchedAt)return!1;let t=Date.parse(n.fetchedAt),o=e?cu:lu;return Number.isFinite(t)&&Date.now()-t<o}function pu(n){let e=n?.rate_limit;if(!e)return null;let t=e.primary_window,o=e.secondary_window,r={planType:typeof n.plan_type=="string"?n.plan_type:void 0,rateLimitReachedType:typeof n.rate_limit_reached_type?.type=="string"?n.rate_limit_reached_type.type:null};return typeof t?.used_percent=="number"&&(r.used5h=t.used_percent,r.reset5h=_a(t.reset_at)),typeof o?.used_percent=="number"&&(r.used7d=o.used_percent,r.reset7d=_a(o.reset_at)),r.used5h!==void 0||r.used7d!==void 0?r:null}function fu(n){let e=(0,lo.join)(Kt.HOME_DIR,"codex-accounts",`${n}.auth.json`);if(!(0,me.existsSync)(e))return null;try{return JSON.parse((0,me.readFileSync)(e,"utf8"))}catch{return null}}async function mu(n){let e=fu(n),t=e?.tokens?.access_token,o=e?.tokens?.account_id||n;if(!t)return null;let r={Authorization:`Bearer ${t}`,"ChatGPT-Account-Id":o,originator:"codex_cli_rs",Accept:"application/json","Accept-Encoding":"gzip, deflate","User-Agent":"codex_cli_rs/0.0.0"},s=["https://chatgpt.com/backend-api/wham/usage","https://chatgpt.com/backend-api/codex/usage"];for(let a of s)try{let l=await fetch(a,{headers:r,signal:AbortSignal.timeout(15e3)});if(!l.ok)continue;let c=await l.json(),i=pu(c);if(i)return i}catch{}return null}function gu(n,e){return e?{...n,plan:e.planType||n.plan,limitedWindow:e.rateLimitReachedType?n.limitedWindow||"unknown":n.limitedWindow,usage:{used5h:e.used5h??0,used7d:e.used7d??0,limit5h:e.used5h!==void 0?100:void 0,limit7d:e.used7d!==void 0?100:void 0,reset5h:e.reset5h,reset7d:e.reset7d}}:n}function hu(n){for(let e of n){if(Mr.has(e))continue;let t=(async()=>{let o=await mu(e);if(!o)return;let r=ba();r[e]={...o,fetchedAt:new Date().toISOString()},xa(r)})().catch(o=>{console.error(`Failed to refresh Codex usage for ${e}:`,o)}).finally(()=>{Mr.delete(e)});Mr.set(e,t)}}async function st(n){let e=(0,Kt.listCodexAccounts)(n),t=new Set(e.accounts.map(a=>a.id)),o=uu(ba(),t),r=e.accounts.filter(a=>!du(o[a.id],a.active)).map(a=>a.id);r.length>0&&hu(r);let s=e.accounts.map(a=>gu(a,o[a.id]));return{...e,accounts:s}}var me,lo,Kt,ka,$r,cu,lu,Mr,Ca=P(()=>{"use strict";me=require("fs"),lo=require("path"),Kt=require("@wengine-ai/claude-code-router-shared"),ka=(0,lo.join)(Kt.HOME_DIR,"data"),$r=(0,lo.join)(ka,"codex-usage-cache.json"),cu=60*1e3,lu=1800*1e3,Mr=new Map});function yu(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=Vt(t,e),s=Vt(o,e),a=[],l=new Set;for(let c of n||[])c&&c.name&&l.add(c.name);for(let c of Object.keys(r.byProvider||{}))l.add(c);for(let c of Object.keys(s.byProvider||{}))l.add(c);for(let c of l){let i=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},d=(i.inputTokens||0)+(i.outputTokens||0),m=(u.inputTokens||0)+(u.outputTokens||0),g,y,p=(n||[]).find(f=>f&&f.name===c);p&&p.quota&&(g=p.quota.limit5h,y=p.quota.limit7d),a.push({provider:c,used5h:d,used7d:m,limit5h:g,limit7d:y})}return a}async function Sa(n,e){let t=n.app;ze(),We(),t.register(Ra.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let l=zt(e);return{object:"list",data:l,first_id:l[0]?.id||null,last_id:l[l.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(l,c)=>{let i=decodeURIComponent(l.params.modelId),u=zt(e).find(d=>d.id===i);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${i}`}})}),t.post("/v1/messages/count_tokens",async(l,c)=>{let{messages:i,tools:u,system:d,model:m}=l.body,g=t._server.tokenizerService;if(m&&m.includes(",")&&g)try{let[p,f]=m.split(",");l.log?.info(`Looking up tokenizer for provider: ${p}, model: ${f}`);let _=g.getTokenizerConfigForModel(p,f);_?l.log?.info(`Using tokenizer config: ${JSON.stringify(_)}`):l.log?.warn(`No tokenizer config found for ${p},${f}, using default tiktoken`);let k=await g.countTokens({messages:i,system:d,tools:u},_,p);return{input_tokens:k.tokenCount,tokenizer:k.tokenizerUsed}}catch(p){l.log?.error(`Error using configured tokenizer: ${p.message}`),l.log?.error(p.stack)}else m?m.includes(",")?g||l.log?.warn("TokenizerService not available, using default tiktoken"):l.log?.info(`Model "${m}" does not contain comma, using default tiktoken`):l.log?.info("No model specified, using default tiktoken");return{input_tokens:_t(i,d,u)}}),t.get("/api/config",async(l,c)=>await Zn()),t.get("/api/transformers",async(l,c)=>{let i=t._server.transformerService.getAllTransformers();return{transformers:Array.from(i.entries()).map(([d,m])=>({name:d,endpoint:m.endPoint||null}))}}),t.post("/api/config",async(l,c)=>{let i=l.body,u=Gr(i||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(g=>`${g.key}: ${g.error}`).join("; "),proxyErrors:u};let d=await Ft();d&&console.log(`Backed up existing configuration file to ${d}`),await ne(i);let m;try{m=await(0,S.syncGlobalProjectTakeovers)(i),m.failed.length>0&&t.log?.warn?.({projectTakeoverSync:m},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}try{let g=t._server;if(g?.configService){g.configService.reload();let y=i?.Providers||i?.providers;if(Array.isArray(y)&&g.configService.set("providers",y),fe&&g.transformerService&&(g.providerService=new fe(g.configService,g.transformerService,t.log)),nt(i,t.log),Me&&St){try{St()}catch{}let p={enabled:g.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:g.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:g.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:g.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:g.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};g.activeProbeService=Me(()=>g.providerService.getProviders(),p,f=>de(g.configService,f),t.log,f=>g.configService.get(f))}}}catch(g){t.log?.warn?.(`Config saved but runtime reload failed: ${g?.message||g}`)}return{success:!0,message:"Config saved successfully",projectTakeoverSync:m}}),t.get("/api/clients",async(l,c)=>{try{let i=await z();return{clients:(0,S.listClientStatuses)(i)}}catch(i){console.error("Failed to get client integrations:",i),c.status(500).send({error:i.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(l,c)=>{try{let i=l.body,u=Array.isArray(i?.enabled)?i.enabled:[],d=await z(),m=(0,S.applyClientSelection)(d,u);return await ne(m.config),m}catch(i){console.error("Failed to apply client integrations:",i),c.status(500).send({error:i.message||"Failed to apply client integrations"})}});async function o(l,c,i){try{let{id:u}=l.params;if(!(0,S.isClientId)(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let d=await z(),m=i==="enable"?(0,S.enableClient)(d,u):i==="restore"?(0,S.restoreClient)(d,u):(0,S.disableClient)(d,u);return await ne(d),{success:m.success,result:m,results:[m],clients:(0,S.listClientStatuses)(d),config:d}}catch(u){console.error(`Failed to ${i} client integration:`,u),c.status(500).send({error:u.message||`Failed to ${i} client integration`})}}t.post("/api/clients/:id/enable",async(l,c)=>o(l,c,"enable")),t.post("/api/clients/:id/disable",async(l,c)=>o(l,c,"disable")),t.post("/api/clients/:id/restore",async(l,c)=>o(l,c,"restore")),t.get("/api/clients/codex/accounts",async(l,c)=>{try{let i=await z();return await st(i)}catch(i){console.error("Failed to get Codex accounts:",i),c.status(500).send({error:i.message||"Failed to get Codex accounts"})}}),t.post("/api/clients/codex/accounts/import-current",async(l,c)=>{try{let i=l.body,u=await z(),d=(0,S.importCurrentCodexAccount)(u,i?.label);await ne(d.config);let m=await st(d.config);return{...d,...m}}catch(i){console.error("Failed to import current Codex account:",i),c.status(500).send({error:i.message||"Failed to import current Codex account"})}}),t.post("/api/clients/codex/accounts/import-rt",async(l,c)=>{try{let i=l.body,u=await z(),d=await(0,S.importCodexAccountFromRefreshToken)(u,i?.refreshToken||"",i?.label);await ne(d.config);let m=await st(d.config);return{...d,...m}}catch(i){console.error("Failed to import Codex account from refresh token:",i),c.status(500).send({error:i.message||"Failed to import Codex account from refresh token"})}}),t.post("/api/clients/codex/accounts/:accountId/activate",async(l,c)=>{try{let{accountId:i}=l.params,u=await z(),d=(0,S.activateCodexAccount)(u,i);await ne(d.config);let m=await st(d.config);return{...d,...m}}catch(i){console.error("Failed to activate Codex account:",i),c.status(500).send({error:i.message||"Failed to activate Codex account"})}}),t.post("/api/clients/codex/accounts/:accountId/export-rt",async(l,c)=>{try{let{accountId:i}=l.params,u=await z();return(0,S.exportCodexRefreshToken)(u,i)}catch(i){console.error("Failed to export Codex refresh token:",i),c.status(500).send({error:i.message||"Failed to export Codex refresh token"})}}),t.post("/api/clients/codex/accounts/export-rt",async(l,c)=>{try{let i=await z();return(0,S.exportCodexRefreshToken)(i)}catch(i){console.error("Failed to export active Codex refresh token:",i),c.status(500).send({error:i.message||"Failed to export active Codex refresh token"})}}),t.delete("/api/clients/codex/accounts/:accountId",async(l,c)=>{try{let{accountId:i}=l.params,u=await z(),d=(0,S.deleteCodexAccount)(u,i);await ne(d.config);let m=await st(d.config);return{...d,...m}}catch(i){console.error("Failed to delete Codex account:",i),c.status(500).send({error:i.message||"Failed to delete Codex account"})}}),t.get("/api/projects",async(l,c)=>{try{let i=await(0,S.listProjectConfigs)();return{projects:await Promise.all(i.map(async d=>{let m=await(0,S.getProjectTakeoverClients)(d.path);return{...d,ccrTakeoverClients:m,ccrTakeover:m.length>0}}))}}catch(i){console.error("Failed to list project configs:",i),c.status(500).send({error:i.message||"Failed to list project configs"})}}),t.post("/api/projects",async(l,c)=>{try{let{path:i}=l.body||{};if(!i||typeof i!="string"||!(0,X.isAbsolute)(i)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,X.normalize)(i).replace(/[\\/]+$/,"")||i;if(await(0,S.readProjectConfig)(u)){c.status(409).send({error:"Project is already configured"});return}await(0,S.writeProjectConfig)(u,{Router:{}});try{let g=await z();await(0,S.setProjectTakeover)(u,["claudeCode"],g)}catch(g){console.error("Failed to auto-enable ccr takeover for new project:",g)}let m=await(0,S.getProjectTakeoverClients)(u);return{id:(0,S.getClaudeProjectId)(u),path:u,configPath:(0,S.getProjectConfigPath)(u),Router:{},ccrTakeoverClients:m,ccrTakeover:m.length>0}}catch(i){console.error("Failed to add project config:",i),c.status(500).send({error:i.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(l,c)=>{try{let{id:i}=l.params,{Router:u}=l.body||{};if(!u||typeof u!="object"){c.status(400).send({error:"Router must be an object"});return}let d=await(0,S.readProjectConfigById)(i);if(!d){c.status(404).send({error:"Project config not found"});return}if(await(0,S.writeProjectConfig)(d.path,{Router:u}),Object.keys(u).length===0){let y=await z();await(0,S.refreshProjectTakeovers)(d.path,y)}let g=await(0,S.getProjectTakeoverClients)(d.path);return{id:i,path:d.path,configPath:d.configPath,Router:u,ccrTakeoverClients:g,ccrTakeover:g.length>0}}catch(i){console.error("Failed to update project config:",i),c.status(500).send({error:i.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(l,c)=>{try{let{id:i}=l.params,u=l.body||{},d;if(Array.isArray(u.clients))d=u.clients.filter(S.isProjectTakeoverClient);else if(typeof u.enabled=="boolean")d=u.enabled?["claudeCode"]:[];else{c.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let m=await(0,S.readProjectConfigById)(i);if(!m){c.status(404).send({error:"Project config not found"});return}let g=await z(),y=await(0,S.setProjectTakeover)(m.path,d,g);return{id:i,path:m.path,ccrTakeoverClients:y,ccrTakeover:y.length>0}}catch(i){console.error("Failed to update ccr takeover status:",i),c.status(500).send({error:i.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(l,c)=>{try{let{id:i}=l.params,u=await(0,S.readProjectConfigById)(i);if(!u){c.status(404).send({error:"Project config not found"});return}try{let d=await z();await(0,S.setProjectTakeover)(u.path,[],d)}catch(d){console.error("Failed to remove ccr takeover while deleting project:",d)}return await(0,S.deleteProjectConfig)(u.path),{success:!0}}catch(i){console.error("Failed to delete project config:",i),c.status(500).send({error:i.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:(0,X.dirname)((0,Ta.fileURLToPath)(void 0)),s=(0,j.existsSync)((0,X.join)(r,"index.html"))?r:(0,j.existsSync)((0,X.join)(r,"..","index.html"))?(0,X.join)(r,".."):(0,X.join)(r,"..","dist");t.register(va.default,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(l,c)=>c.redirect("/ui/")),t.get("/api/logs/files",async(l,c)=>{try{let i=(0,X.join)((0,uo.homedir)(),".claude-code-router","logs"),u=[];if((0,j.existsSync)(i)){let d=(0,j.readdirSync)(i);for(let m of d)if(m.endsWith(".log")){let g=(0,X.join)(i,m),y=(0,j.statSync)(g);u.push({name:m,path:g,size:y.size,lastModified:y.mtime.toISOString()})}u.sort((m,g)=>new Date(g.lastModified).getTime()-new Date(m.lastModified).getTime())}return u}catch(i){console.error("Failed to get log files:",i),c.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(l,c)=>{try{let i=l.query.file,u;return i?u=i:u=(0,X.join)((0,uo.homedir)(),".claude-code-router","logs","app.log"),(0,j.existsSync)(u)?(0,j.readFileSync)(u,"utf8").split(`
388
- `).filter(g=>g.trim()):[]}catch(i){console.error("Failed to get logs:",i),c.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(l,c)=>{try{let i=l.query.file,u;return i?u=i:u=(0,X.join)((0,uo.homedir)(),".claude-code-router","logs","app.log"),(0,j.existsSync)(u)&&(0,j.writeFileSync)(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(i){console.error("Failed to clear logs:",i),c.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:ut()})),t.put("/api/debug-log",async l=>{let{enabled:c}=l.body;return tn(c),{enabled:ut()}}),t.get("/api/usage",async(l,c)=>{try{let i=l.query;return Sr({startTime:i.startDate,endTime:i.endDate,model:i.model,provider:i.provider,scenario:i.scenario,clientType:i.clientType,sessionId:i.sessionId,status:i.status,page:i.page?parseInt(i.page,10):void 0,pageSize:i.pageSize?parseInt(i.pageSize,10):void 0})}catch(i){console.error("Failed to query usage:",i),c.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(l,c)=>{try{let i=l.query;return Vt(i.startDate,i.endDate,i.status)}catch(i){console.error("Failed to query usage summary:",i),c.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(l,c)=>{try{let i=l.query;return Pr(i.beforeDate),{success:!0,message:i.beforeDate?"Usage data cleared before "+i.beforeDate:"All usage data cleared"}}catch(i){console.error("Failed to clear usage:",i),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(l,c)=>{try{return{states:D().getAllStates().map(d=>({provider:d.provider,model:d.model,status:d.status,failureCount:d.failureCount,successCount:d.successCount,lastFailureTime:d.lastFailureTime,lastError:d.lastError,rateLimitUntil:d.rateLimitUntil??null})),timestamp:new Date().toISOString()}}catch(i){console.error("Failed to get provider health:",i),c.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(l,c)=>{try{let{providerName:i}=l.body;if(!i)return c.status(400),{error:"providerName is required"};let d=t._server?.activeProbeService;if(!d?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let m=await d.probeProviderManually(i);return m&&jt(i,l.log),{provider:i,success:m,timestamp:new Date().toISOString()}}catch(i){console.error("Failed to probe provider:",i),c.status(500).send({error:i.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(l,c)=>{try{let i=t._server,u=i?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let d=(i?.providerService?.getProviders?.()||[]).filter(g=>g?.name&&g.enabled!==!1),m=await Promise.all(d.map(async g=>{let y=await u.probeProviderManually(g.name);return y&&jt(g.name,l?.log),{provider:g.name,success:y}}));return{results:m,successCount:m.filter(g=>g.success).length,total:m.length,timestamp:new Date().toISOString()}}catch(i){console.error("Failed to probe all providers:",i),c.status(500).send({error:i.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(l,c)=>{try{let u=(await z()).Providers||[],d=yu(u),m=new Map(d.map(p=>[p.provider,p])),g=ln();for(let p of d){let f=g.find(_=>_.provider===p.provider);f&&f.limit!=null&&(p.limit5h=f.limit,p.used5h=f.limit-(f.remaining??0),f.reset&&(p.reset5h=new Date(f.reset*1e3).toISOString()))}let y=pn();for(let p of y){let f=m.get(p.provider);f||(f={provider:p.provider,used5h:0,used7d:0},d.push(f),m.set(p.provider,f)),typeof p.totalBalance=="number"?(f.limit7d=p.totalBalance,f.type7d=p.currency?"balance":"rateLimit",p.currency&&(f.currency=p.currency),typeof p.usedBalance=="number"?f.used7d=p.usedBalance:typeof p.remainingBalance=="number"?f.used7d=Math.max(0,p.totalBalance-p.remainingBalance):(f.used7d=0,f.limit7d=p.totalBalance)):typeof p.usedBalance=="number"&&(f.used7d=p.usedBalance),typeof p.usedDailyBalance=="number"&&(f.used5h=p.usedDailyBalance,f.type5h="rateLimit"),typeof p.limitDaily=="number"&&(f.limit5h=p.limitDaily,f.type5h="rateLimit"),typeof p.resetTime=="string"&&(p.limitDaily!==void 0?f.reset5h=p.resetTime:f.reset7d=p.resetTime),typeof p.resetTime7d=="string"&&(f.reset7d=p.resetTime7d)}return{quotas:d,timestamp:new Date().toISOString()}}catch(i){console.error("Failed to compute provider quota:",i),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(l,c)=>{try{let i=(0,X.join)(S.HOME_DIR,"presets");if(!(0,j.existsSync)(i))return{presets:[]};let d=(0,j.readdirSync)(i,{withFileTypes:!0}).filter(g=>g.isDirectory()&&!g.name.startsWith(".")).map(g=>g.name),m=[];for(let g of d){let y=(0,X.join)(i,g);try{let p=(0,X.join)(y,"manifest.json"),f=(0,j.readFileSync)(p,"utf-8"),_=JSON.parse(f),{Providers:k,Router:h,PORT:b,HOST:x,API_TIMEOUT_MS:v,PROXY_URL:C,PROXY_GLOBAL_ENABLED:R,LOG:T,LOG_LEVEL:O,StatusLine:w,NON_INTERACTIVE_MODE:E,...A}=_;m.push({id:g,name:A.name||g,version:A.version||"1.0.0",description:A.description,author:A.author,homepage:A.homepage,repository:A.repository,license:A.license,keywords:A.keywords,ccrVersion:A.ccrVersion,source:A.source,sourceType:A.sourceType,checksum:A.checksum,installed:!0})}catch(p){console.error(`Failed to read preset ${g}:`,p)}}return{presets:m}}catch(i){console.error("Failed to get presets:",i),c.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(l,c)=>{try{let{name:i}=l.params,u=(0,S.getPresetDir)(i);if(!(0,j.existsSync)(u)){c.status(404).send({error:"Preset not found"});return}let d=await(0,S.readManifestFromDir)(u);return{...(0,S.manifestToPresetFile)(d),config:(0,S.loadConfigFromManifest)(d,u),userValues:d.userValues||{}}}catch(i){console.error("Failed to get preset:",i),c.status(500).send({error:i.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(l,c)=>{try{let{name:i}=l.params,{secrets:u}=l.body,d=(0,S.getPresetDir)(i);if(!(0,j.existsSync)(d)){c.status(404).send({error:"Preset not found"});return}let g={...await(0,S.readManifestFromDir)(d)};return u&&Object.keys(u).length>0&&(g.userValues={...g.userValues,...u}),await(0,S.saveManifest)(i,g),{success:!0,message:"Preset applied successfully"}}catch(i){console.error("Failed to apply preset:",i),c.status(500).send({error:i.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(l,c)=>{try{let{name:i}=l.params,u=(0,S.getPresetDir)(i);if(!(0,j.existsSync)(u)){c.status(404).send({error:"Preset not found"});return}return(0,j.rmSync)(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(i){console.error("Failed to delete preset:",i),c.status(500).send({error:i.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(l,c)=>{try{return{presets:await(0,S.getMarketPresets)()}}catch(i){console.error("Failed to get market presets:",i),c.status(500).send({error:i.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(l,c)=>{try{let{presetName:i}=l.body;if(!i){c.status(400).send({error:"Preset name is required"});return}let u=await(0,S.findMarketPresetByName)(i);if(!u){c.status(400).send({error:"Preset not found in marketplace",message:`Preset '${i}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){c.status(400).send({error:"Invalid preset data",message:`Preset '${i}' does not have repository information`});return}let d=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!d){c.status(400).send({error:"Invalid GitHub repository URL"});return}let[,m,g]=d,y=u.name||i;if(await(0,S.isPresetInstalled)(y)){c.status(409).send({error:"Preset already installed",message:`Preset '${y}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:y});return}let p=`https://github.com/${m}/${g}/archive/refs/heads/main.zip`,f=await(0,S.downloadPresetToTemp)(p),_=await a(f);if(await(0,S.isPresetInstalled)(y)){(0,j.unlinkSync)(f),c.status(409).send({error:"Preset already installed",message:`Preset '${y}' was installed while downloading. Please try again.`,presetName:y});return}let k=(0,S.getPresetDir)(y);await(0,S.extractPreset)(f,k);let h=await(0,S.readManifestFromDir)(k);return h.repository=u.repo,u.url&&(h.source=u.url),await(0,S.saveManifest)(y,h),(0,j.unlinkSync)(f),{success:!0,presetName:y,preset:{..._.metadata,installed:!0}}}catch(i){console.error("Failed to install preset from GitHub:",i),c.status(500).send({error:i.message||"Failed to install preset from GitHub"})}});async function a(l){let c=new wa.default(l),i=c.getEntry("manifest.json");if(i||(i=c.getEntries().find(m=>m.entryName.includes("manifest.json"))||null),!i)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(i.getData().toString("utf-8"));return(0,S.manifestToPresetFile)(u)}return n}var X,Ta,va,j,uo,S,Ra,wa,Pa=P(()=>{"use strict";bt();He();Ge();bn();qn();ae();dt();ce();no();Ut();X=require("path"),Ta=require("url"),va=Y(require("@fastify/static"),1),j=require("fs"),uo=require("os"),S=require("@wengine-ai/claude-code-router-shared"),Ra=Y(require("@fastify/multipart"),1),wa=Y(require("adm-zip"),1);Qt();Ca();Tr()});function _u(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function ku(n){let e=_u(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function bu(n){return n.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}var Nr,po,Lr,Aa,Oa=P(()=>{"use strict";Nr=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},po=new Nr;Lr=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){if(!t.Router.image||e.body.model===t.Router.image||!bu(e.body.messages))return!1;let r=e.body.messages[e.body.messages.length-1];if(!t.forceUseImageAgent){if(ku(e.body.model))return!1;if(e.body.model=t.Router.image,r.role==="user"&&Array.isArray(r.content)){let s=[];r.content.filter(a=>a.type==="tool_result").forEach(a=>{Array.isArray(a.content)&&(a.content.forEach(l=>{l.type==="image"&&s.push(l)}),a.content="read image successfully")}),r.content.push(...s)}return!1}return!0}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(l=>{let c=po.getImage(`${t.req.id}_Image#${l}`);c&&o.push({type:"image",source:c})});else{let l=po.getImage(`${t.req.id}_Image#${e.imageId}`);l&&o.push({type:"image",source:l})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let l=s.content.filter(c=>c.type==="text"&&!c.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...l)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:t.config.Router.image,system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
384
+ `)}function Sl(n,e,t){if(n<=0||e==null||!Number.isFinite(e))return null;let o=t!=null&&Number.isFinite(t)?t:0,r=Math.max((e-o)/1e3,hl);return Math.round(n/r)}function no(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=$e(n.ttft);return{...n,ttft:r,tokensPerSecond:Sl(e,o,r)}}function ke(n){return typeof n=="string"?n:n==null?"":String(n)}function Zn(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function jt(n){let e=Number(n);return Number.isFinite(e)?e:0}function Li(n){return n==="success"?"success":"error"}function Di(n){let e=no(n);return{id:ke(e.id),timestamp:ke(e.timestamp),session_id:ke(e.sessionId),provider:ke(e.provider),original_model:ke(e.originalModel),model:ke(e.model),upstream_model:Zn(e.upstreamModel)??null,model_family:ke(e.modelFamily),scenario_type:ke(e.scenarioType),client_type:Zn(e.clientType)??null,stream:e.stream?1:0,input_tokens:Math.trunc(jt(e.inputTokens)),output_tokens:Math.trunc(jt(e.outputTokens)),cache_read_input_tokens:Math.trunc(jt(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(jt(e.cacheCreationInputTokens)),ttft:$e(e.ttft),tokens_per_second:$e(e.tokensPerSecond),duration_ms:Math.trunc(jt(e.durationMs)),status:Li(e.status),error_message:Zn(e.errorMessage)??null,response_body:Zn(e.responseBody)??null}}function Rl(n){return no({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,stream:n.stream===1,inputTokens:n.input_tokens,outputTokens:n.output_tokens,cacheReadInputTokens:n.cache_read_input_tokens,cacheCreationInputTokens:n.cache_creation_input_tokens,ttft:n.ttft,tokensPerSecond:n.tokens_per_second,durationMs:n.duration_ms,status:Li(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function wl(){return new Date(Date.now()-yl*24*60*60*1e3).toISOString()}function Fi(n,e=!1){let t=Date.now();!e&&t-$i<_l||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(wl()),$i=t)}function Ui(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function nt(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
385
+ SELECT ${t} AS key, ${Pl}
386
+ FROM usage_records ${r}
387
+ GROUP BY key
388
+ `).all(...e.params),i={};for(let l of s)l.key!=null&&(i[String(l.key)]={count:l.count,inputTokens:l.inputTokens,outputTokens:l.outputTokens,cacheReadInputTokens:l.cacheReadInputTokens,cacheCreationInputTokens:l.cacheCreationInputTokens});return i}function ji(n,e){let t=Ui(e),o=n.prepare(`
389
+ SELECT
390
+ COUNT(*) AS totalRequests,
391
+ COALESCE(SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END), 0) AS successCount,
392
+ COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS totalInputTokens,
393
+ COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS totalOutputTokens,
394
+ COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS totalCacheReadInputTokens,
395
+ COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS totalCacheCreationInputTokens,
396
+ AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
397
+ AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
398
+ FROM usage_records ${t.sql}
399
+ `).get(...t.params);return{totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:nt(n,t,"model"),byProvider:nt(n,t,"provider"),byScenario:nt(n,t,"scenario_type"),byFamily:nt(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:nt(n,t,"date(timestamp, 'localtime')"),byClient:nt(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function zt(n){let e=Ht(),t=no(n);br.run(Di(t)),Fi(e)}function Tr(n){let e=Ht(),t=Ui(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.min(Math.floor(n.pageSize),El):50,s=(o-1)*r,i=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),l=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),a=ji(e,n);return{records:l.map(Rl),summary:a,total:i.count,page:o,pageSize:r}}function Bt(n,e,t){let o=Ht();return ji(o,{startTime:n,endTime:e,status:t})}function Cr(n){let e=Ht();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Ol(){be&&(be.pragma("wal_checkpoint(TRUNCATE)"),be.close(),be=null,br=null)}function $e(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function vr(n){let e=(0,Ne.join)((0,to.tmpdir)(),"claude-code-router"),t=(0,Ne.join)(e,`session-${n}.json`);if((0,re.existsSync)(t))try{let o=(0,re.readFileSync)(t,"utf-8"),r=JSON.parse(o);return{ttft:$e(r.timeToFirstToken),tokensPerSecond:$e(r.tokensPerSecond)}}catch{}try{let o=(0,re.readdirSync)(e),r=new RegExp(`^session-${n}-\\d+\\.json$`),s=o.filter(i=>r.test(i));if(s.length>0){let i=s.sort().reverse(),l=(0,Ne.join)(e,i[0]);try{let a=(0,re.readFileSync)(l,"utf-8"),c=JSON.parse(a);return{ttft:$e(c.timeToFirstToken),tokensPerSecond:$e(c.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}}catch{}return{ttft:null,tokensPerSecond:null}}function Al(n,e,t){return Ht().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var re,Ne,to,Ni,eo,gl,kr,hl,yl,_l,Mi,be,br,$i,Pl,El,Jt=w(()=>{"use strict";re=require("fs"),Ne=require("path"),to=require("os"),Ni=Y(require("better-sqlite3"),1),eo=(0,Ne.join)((0,to.homedir)(),".claude-code-router","data"),gl=(0,Ne.join)(eo,"usage.sqlite"),kr=(0,Ne.join)(eo,"usage.jsonl"),hl=1,yl=180,_l=3600*1e3,Mi="legacy_usage_jsonl_migrated_at",be=null,br=null,$i=0;Pl=`
400
+ COUNT(*) AS count,
401
+ COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
402
+ COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
403
+ COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
404
+ COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
405
+ `;El=200});async function Wi(){let n=(0,zi.homedir)(),e=(0,Bi.join)(n,".claude.json");if(!(0,Hi.existsSync)(e)){let o={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await(0,Ji.writeFile)(e,JSON.stringify(o,null,2))}}var Hi,zi,Bi,Ji,Gi=w(()=>{"use strict";Hi=require("fs"),zi=require("os"),Bi=require("path"),Ji=require("fs/promises")});function Qi(n=(0,Sr.join)(Vi.HOME_DIR,"logs")){try{if(!(0,Te.existsSync)(n))return;let e=Date.now()-Ml;for(let t of(0,Te.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,Sr.join)(n,t),r=(0,Te.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,Te.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function Yi(){Ki||(Ki=!0,Qi(),setInterval(Qi,$l).unref())}var Te,Sr,Vi,Il,Ml,$l,Ki,Xi=w(()=>{"use strict";Te=require("fs"),Sr=require("path"),Vi=require("@wengine-ai/claude-code-router-shared"),Il=7,Ml=Il*24*60*60*1e3,$l=1440*60*1e3,Ki=!1});async function qi(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:i={}}=o;switch(r){case"token-speed":qe.registerPlugin(At,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}],...i});break;default:console.warn(`Unknown plugin: ${r}`);break}}await qe.enablePlugins(n)}var Zi=w(()=>{"use strict";dr()});function Nl(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=Bt(t,e),s=Bt(o,e),i=[],l=new Set;for(let a of n||[])a&&a.name&&l.add(a.name);for(let a of Object.keys(r.byProvider||{}))l.add(a);for(let a of Object.keys(s.byProvider||{}))l.add(a);for(let a of l){let c=r.byProvider[a]||{inputTokens:0,outputTokens:0},u=s.byProvider[a]||{inputTokens:0,outputTokens:0},d=(c.inputTokens||0)+(c.outputTokens||0),g=(u.inputTokens||0)+(u.outputTokens||0),m,y,p=(n||[]).find(f=>f&&f.name===a);p&&p.quota&&(m=p.quota.limit5h,y=p.quota.limit7d),i.push({provider:a,used5h:d,used7d:g,limit5h:m,limit7d:y})}return i}async function ra(n,e){let t=n.app;Ue(),Be(),t.register(na.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let l=Dt(e);return{object:"list",data:l,first_id:l[0]?.id||null,last_id:l[l.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(l,a)=>{let c=decodeURIComponent(l.params.modelId),u=Dt(e).find(d=>d.id===c);return u||(a.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${c}`}})}),t.post("/v1/messages/count_tokens",async(l,a)=>{let{messages:c,tools:u,system:d,model:g}=l.body,m=t._server.tokenizerService;if(g&&g.includes(",")&&m)try{let[p,f]=g.split(",");l.log?.info(`Looking up tokenizer for provider: ${p}, model: ${f}`);let _=m.getTokenizerConfigForModel(p,f);_?l.log?.info(`Using tokenizer config: ${JSON.stringify(_)}`):l.log?.warn(`No tokenizer config found for ${p},${f}, using default tiktoken`);let k=await m.countTokens({messages:c,system:d,tools:u},_,p);return{input_tokens:k.tokenCount,tokenizer:k.tokenizerUsed}}catch(p){l.log?.error(`Error using configured tokenizer: ${p.message}`),l.log?.error(p.stack)}else g?g.includes(",")?m||l.log?.warn("TokenizerService not available, using default tiktoken"):l.log?.info(`Model "${g}" does not contain comma, using default tiktoken`):l.log?.info("No model specified, using default tiktoken");return{input_tokens:gt(c,d,u)}}),t.get("/api/config",async(l,a)=>await Qn()),t.get("/api/transformers",async(l,a)=>{let c=t._server.transformerService.getAllTransformers();return{transformers:Array.from(c.entries()).map(([d,g])=>({name:d,endpoint:g.endPoint||null}))}}),t.post("/api/config",async(l,a)=>{let c=l.body,u=Dr(c||{});if(u.length>0)return a.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(m=>`${m.key}: ${m.error}`).join("; "),proxyErrors:u};let d=await $t();d&&console.log(`Backed up existing configuration file to ${d}`),await Ie(c);let g;try{g=await(0,O.syncGlobalProjectTakeovers)(c),g.failed.length>0&&t.log?.warn?.({projectTakeoverSync:g},"Config saved but some global project takeovers failed to sync")}catch(m){t.log?.warn?.(`Config saved but global project takeover sync failed: ${m?.message||m}`)}try{let m=t._server;if(m?.configService){m.configService.reload();let y=c?.Providers||c?.providers;if(Array.isArray(y)&&m.configService.set("providers",y),de&&m.transformerService&&(m.providerService=new de(m.configService,m.transformerService,t.log)),tt(c,t.log),Oe&&xt){try{xt()}catch{}let p={enabled:m.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:m.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:m.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(m.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:m.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:m.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};m.activeProbeService=Oe(()=>m.providerService.getProviders(),p,f=>le(m.configService,f),t.log,f=>m.configService.get(f))}}}catch(m){t.log?.warn?.(`Config saved but runtime reload failed: ${m?.message||m}`)}return{success:!0,message:"Config saved successfully",projectTakeoverSync:g}}),t.get("/api/clients",async(l,a)=>{try{let c=await oe();return{clients:(0,O.listClientStatuses)(c)}}catch(c){console.error("Failed to get client integrations:",c),a.status(500).send({error:c.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(l,a)=>{try{let c=l.body,u=Array.isArray(c?.enabled)?c.enabled:[],d=await oe(),g=(0,O.applyClientSelection)(d,u);return await Ie(g.config),g}catch(c){console.error("Failed to apply client integrations:",c),a.status(500).send({error:c.message||"Failed to apply client integrations"})}});async function o(l,a,c){try{let{id:u}=l.params;if(!(0,O.isClientId)(u)){a.status(404).send({error:`Unknown client: ${u}`});return}let d=await oe(),g=c==="enable"?(0,O.enableClient)(d,u):c==="restore"?(0,O.restoreClient)(d,u):(0,O.disableClient)(d,u);return await Ie(d),{success:g.success,result:g,results:[g],clients:(0,O.listClientStatuses)(d),config:d}}catch(u){console.error(`Failed to ${c} client integration:`,u),a.status(500).send({error:u.message||`Failed to ${c} client integration`})}}t.post("/api/clients/:id/enable",async(l,a)=>o(l,a,"enable")),t.post("/api/clients/:id/disable",async(l,a)=>o(l,a,"disable")),t.post("/api/clients/:id/restore",async(l,a)=>o(l,a,"restore")),t.get("/api/projects",async(l,a)=>{try{let c=await(0,O.listProjectConfigs)();return{projects:await Promise.all(c.map(async d=>{let g=await(0,O.getProjectTakeoverClients)(d.path);return{...d,ccrTakeoverClients:g,ccrTakeover:g.length>0}}))}}catch(c){console.error("Failed to list project configs:",c),a.status(500).send({error:c.message||"Failed to list project configs"})}}),t.post("/api/projects",async(l,a)=>{try{let{path:c}=l.body||{};if(!c||typeof c!="string"||!(0,V.isAbsolute)(c)){a.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,V.normalize)(c).replace(/[\\/]+$/,"")||c;if(await(0,O.readProjectConfig)(u)){a.status(409).send({error:"Project is already configured"});return}await(0,O.writeProjectConfig)(u,{Router:{}});try{let m=await oe();await(0,O.setProjectTakeover)(u,["claudeCode"],m)}catch(m){console.error("Failed to auto-enable ccr takeover for new project:",m)}let g=await(0,O.getProjectTakeoverClients)(u);return{id:(0,O.getClaudeProjectId)(u),path:u,configPath:(0,O.getProjectConfigPath)(u),Router:{},ccrTakeoverClients:g,ccrTakeover:g.length>0}}catch(c){console.error("Failed to add project config:",c),a.status(500).send({error:c.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(l,a)=>{try{let{id:c}=l.params,{Router:u}=l.body||{};if(!u||typeof u!="object"){a.status(400).send({error:"Router must be an object"});return}let d=await(0,O.readProjectConfigById)(c);if(!d){a.status(404).send({error:"Project config not found"});return}if(await(0,O.writeProjectConfig)(d.path,{Router:u}),Object.keys(u).length===0){let y=await oe();await(0,O.refreshProjectTakeovers)(d.path,y)}let m=await(0,O.getProjectTakeoverClients)(d.path);return{id:c,path:d.path,configPath:d.configPath,Router:u,ccrTakeoverClients:m,ccrTakeover:m.length>0}}catch(c){console.error("Failed to update project config:",c),a.status(500).send({error:c.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(l,a)=>{try{let{id:c}=l.params,u=l.body||{},d;if(Array.isArray(u.clients))d=u.clients.filter(O.isProjectTakeoverClient);else if(typeof u.enabled=="boolean")d=u.enabled?["claudeCode"]:[];else{a.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let g=await(0,O.readProjectConfigById)(c);if(!g){a.status(404).send({error:"Project config not found"});return}let m=await oe(),y=await(0,O.setProjectTakeover)(g.path,d,m);return{id:c,path:g.path,ccrTakeoverClients:y,ccrTakeover:y.length>0}}catch(c){console.error("Failed to update ccr takeover status:",c),a.status(500).send({error:c.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(l,a)=>{try{let{id:c}=l.params,u=await(0,O.readProjectConfigById)(c);if(!u){a.status(404).send({error:"Project config not found"});return}try{let d=await oe();await(0,O.setProjectTakeover)(u.path,[],d)}catch(d){console.error("Failed to remove ccr takeover while deleting project:",d)}return await(0,O.deleteProjectConfig)(u.path),{success:!0}}catch(c){console.error("Failed to delete project config:",c),a.status(500).send({error:c.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:(0,V.dirname)((0,ea.fileURLToPath)(void 0)),s=(0,j.existsSync)((0,V.join)(r,"index.html"))?r:(0,j.existsSync)((0,V.join)(r,"..","index.html"))?(0,V.join)(r,".."):(0,V.join)(r,"..","dist");t.register(ta.default,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(l,a)=>a.redirect("/ui/")),t.get("/api/logs/files",async(l,a)=>{try{let c=(0,V.join)((0,oo.homedir)(),".claude-code-router","logs"),u=[];if((0,j.existsSync)(c)){let d=(0,j.readdirSync)(c);for(let g of d)if(g.endsWith(".log")){let m=(0,V.join)(c,g),y=(0,j.statSync)(m);u.push({name:g,path:m,size:y.size,lastModified:y.mtime.toISOString()})}u.sort((g,m)=>new Date(m.lastModified).getTime()-new Date(g.lastModified).getTime())}return u}catch(c){console.error("Failed to get log files:",c),a.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(l,a)=>{try{let c=l.query.file,u;return c?u=c:u=(0,V.join)((0,oo.homedir)(),".claude-code-router","logs","app.log"),(0,j.existsSync)(u)?(0,j.readFileSync)(u,"utf8").split(`
406
+ `).filter(m=>m.trim()):[]}catch(c){console.error("Failed to get logs:",c),a.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(l,a)=>{try{let c=l.query.file,u;return c?u=c:u=(0,V.join)((0,oo.homedir)(),".claude-code-router","logs","app.log"),(0,j.existsSync)(u)&&(0,j.writeFileSync)(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(c){console.error("Failed to clear logs:",c),a.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:at()})),t.put("/api/debug-log",async l=>{let{enabled:a}=l.body;return Yt(a),{enabled:at()}}),t.get("/api/usage",async(l,a)=>{try{let c=l.query;return Tr({startTime:c.startDate,endTime:c.endDate,model:c.model,provider:c.provider,scenario:c.scenario,clientType:c.clientType,sessionId:c.sessionId,status:c.status,page:c.page?parseInt(c.page,10):void 0,pageSize:c.pageSize?parseInt(c.pageSize,10):void 0})}catch(c){console.error("Failed to query usage:",c),a.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(l,a)=>{try{let c=l.query;return Bt(c.startDate,c.endDate,c.status)}catch(c){console.error("Failed to query usage summary:",c),a.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(l,a)=>{try{let c=l.query;return Cr(c.beforeDate),{success:!0,message:c.beforeDate?"Usage data cleared before "+c.beforeDate:"All usage data cleared"}}catch(c){console.error("Failed to clear usage:",c),a.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(l,a)=>{try{let u=U().getAllStates(),g=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(m=>({provider:m.provider,model:m.model,status:m.status,failureCount:m.failureCount,successCount:m.successCount,lastFailureTime:m.lastFailureTime,lastError:m.lastError,rateLimitUntil:m.rateLimitUntil??null})),probes:g,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to get provider health:",c),a.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(l,a)=>{try{let{providerName:c}=l.body;if(!c)return a.status(400),{error:"providerName is required"};let d=t._server?.activeProbeService;if(!d?.probeProviderManually)return a.status(503),{error:"Active probe service is not available"};let g=await d.probeProviderManually(c);return g.success&&Lt(c,l.log),{provider:c,success:g.success,latencyMs:g.latencyMs,status:g.status,isSlow:g.isSlow,errorKind:g.errorKind??null,error:g.error,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe provider:",c),a.status(500).send({error:c.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(l,a)=>{try{let c=t._server,u=c?.activeProbeService;if(!u?.probeProviderManually)return a.status(503),{error:"Active probe service is not available"};let d=(c?.providerService?.getProviders?.()||[]).filter(m=>m?.name&&m.enabled!==!1),g=await Promise.all(d.map(async m=>{let y=await u.probeProviderManually(m.name);return y.success&&Lt(m.name,l?.log),{provider:m.name,success:y.success,latencyMs:y.latencyMs,status:y.status,isSlow:y.isSlow,errorKind:y.errorKind??null,error:y.error}}));return{results:g,successCount:g.filter(m=>m.success).length,total:g.length,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe all providers:",c),a.status(500).send({error:c.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(l,a)=>{try{let u=(await oe()).Providers||[],d=Nl(u),g=new Map(d.map(p=>[p.provider,p])),m=on();for(let p of d){let f=m.find(_=>_.provider===p.provider);f&&f.limit!=null&&(p.limit5h=f.limit,p.used5h=f.limit-(f.remaining??0),f.reset&&(p.reset5h=new Date(f.reset*1e3).toISOString()))}let y=an();for(let p of y){let f=g.get(p.provider);f||(f={provider:p.provider,used5h:0,used7d:0},d.push(f),g.set(p.provider,f)),typeof p.totalBalance=="number"?(f.limit7d=p.totalBalance,f.type7d=p.currency?"balance":"rateLimit",p.currency&&(f.currency=p.currency),typeof p.usedBalance=="number"?f.used7d=p.usedBalance:typeof p.remainingBalance=="number"?f.used7d=Math.max(0,p.totalBalance-p.remainingBalance):(f.used7d=0,f.limit7d=p.totalBalance)):typeof p.usedBalance=="number"&&(f.used7d=p.usedBalance),typeof p.usedDailyBalance=="number"&&(f.used5h=p.usedDailyBalance,f.type5h="rateLimit"),typeof p.limitDaily=="number"&&(f.limit5h=p.limitDaily,f.type5h="rateLimit"),typeof p.resetTime=="string"&&(p.limitDaily!==void 0?f.reset5h=p.resetTime:f.reset7d=p.resetTime),typeof p.resetTime7d=="string"&&(f.reset7d=p.resetTime7d)}return{quotas:d,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to compute provider quota:",c),a.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(l,a)=>{try{let c=(0,V.join)(O.HOME_DIR,"presets");if(!(0,j.existsSync)(c))return{presets:[]};let d=(0,j.readdirSync)(c,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).map(m=>m.name),g=[];for(let m of d){let y=(0,V.join)(c,m);try{let p=(0,V.join)(y,"manifest.json"),f=(0,j.readFileSync)(p,"utf-8"),_=JSON.parse(f),{Providers:k,Router:h,PORT:b,HOST:T,API_TIMEOUT_MS:x,PROXY_URL:v,PROXY_GLOBAL_ENABLED:S,LOG:C,LOG_LEVEL:P,StatusLine:R,NON_INTERACTIVE_MODE:A,...E}=_;g.push({id:m,name:E.name||m,version:E.version||"1.0.0",description:E.description,author:E.author,homepage:E.homepage,repository:E.repository,license:E.license,keywords:E.keywords,ccrVersion:E.ccrVersion,source:E.source,sourceType:E.sourceType,checksum:E.checksum,installed:!0})}catch(p){console.error(`Failed to read preset ${m}:`,p)}}return{presets:g}}catch(c){console.error("Failed to get presets:",c),a.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(l,a)=>{try{let{name:c}=l.params,u=(0,O.getPresetDir)(c);if(!(0,j.existsSync)(u)){a.status(404).send({error:"Preset not found"});return}let d=await(0,O.readManifestFromDir)(u);return{...(0,O.manifestToPresetFile)(d),config:(0,O.loadConfigFromManifest)(d,u),userValues:d.userValues||{}}}catch(c){console.error("Failed to get preset:",c),a.status(500).send({error:c.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(l,a)=>{try{let{name:c}=l.params,{secrets:u}=l.body,d=(0,O.getPresetDir)(c);if(!(0,j.existsSync)(d)){a.status(404).send({error:"Preset not found"});return}let m={...await(0,O.readManifestFromDir)(d)};return u&&Object.keys(u).length>0&&(m.userValues={...m.userValues,...u}),await(0,O.saveManifest)(c,m),{success:!0,message:"Preset applied successfully"}}catch(c){console.error("Failed to apply preset:",c),a.status(500).send({error:c.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(l,a)=>{try{let{name:c}=l.params,u=(0,O.getPresetDir)(c);if(!(0,j.existsSync)(u)){a.status(404).send({error:"Preset not found"});return}return(0,j.rmSync)(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(c){console.error("Failed to delete preset:",c),a.status(500).send({error:c.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(l,a)=>{try{return{presets:await(0,O.getMarketPresets)()}}catch(c){console.error("Failed to get market presets:",c),a.status(500).send({error:c.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(l,a)=>{try{let{presetName:c}=l.body;if(!c){a.status(400).send({error:"Preset name is required"});return}let u=await(0,O.findMarketPresetByName)(c);if(!u){a.status(400).send({error:"Preset not found in marketplace",message:`Preset '${c}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){a.status(400).send({error:"Invalid preset data",message:`Preset '${c}' does not have repository information`});return}let d=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!d){a.status(400).send({error:"Invalid GitHub repository URL"});return}let[,g,m]=d,y=u.name||c;if(await(0,O.isPresetInstalled)(y)){a.status(409).send({error:"Preset already installed",message:`Preset '${y}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:y});return}let p=`https://github.com/${g}/${m}/archive/refs/heads/main.zip`,f=await(0,O.downloadPresetToTemp)(p),_=await i(f);if(await(0,O.isPresetInstalled)(y)){(0,j.unlinkSync)(f),a.status(409).send({error:"Preset already installed",message:`Preset '${y}' was installed while downloading. Please try again.`,presetName:y});return}let k=(0,O.getPresetDir)(y);await(0,O.extractPreset)(f,k);let h=await(0,O.readManifestFromDir)(k);return h.repository=u.repo,u.url&&(h.source=u.url),await(0,O.saveManifest)(y,h),(0,j.unlinkSync)(f),{success:!0,presetName:y,preset:{..._.metadata,installed:!0}}}catch(c){console.error("Failed to install preset from GitHub:",c),a.status(500).send({error:c.message||"Failed to install preset from GitHub"})}});async function i(l){let a=new oa.default(l),c=a.getEntry("manifest.json");if(c||(c=a.getEntries().find(g=>g.entryName.includes("manifest.json"))||null),!c)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(c.getData().toString("utf-8"));return(0,O.manifestToPresetFile)(u)}return n}var V,ea,ta,j,oo,O,na,oa,sa=w(()=>{"use strict";Ve();je();Je();gn();Kn();se();ct();ie();qn();Yn();V=require("path"),ea=require("url"),ta=Y(require("@fastify/static"),1),j=require("fs"),oo=require("os"),O=require("@wengine-ai/claude-code-router-shared"),na=Y(require("@fastify/multipart"),1),oa=Y(require("adm-zip"),1);Jt();yr()});function Ll(n,e){let t=n?.Router,{family:o}=ht(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function ia(n){return n?.Router?.image}function Dl(n){return n.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function Fl(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var Rr,ro,wr,aa,ca=w(()=>{"use strict";Ve();Rr=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},ro=new Rr;wr=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Ll(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Dl(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&Ao(e.body.model)?!1:(Fl(e.body.messages),s&&!!ia(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(l=>{let a=ro.getImage(`${t.req.id}_Image#${l}`);a&&o.push({type:"image",source:a})});else{let l=ro.getImage(`${t.req.id}_Image#${e.imageId}`);l&&o.push({type:"image",source:l})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let l=s.content.filter(a=>a.type==="text"&&!a.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...l)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let i=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:ia(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
389
407
  When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
390
408
  Do not ignore or deviate from the task.
391
- Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(l=>l.json()).catch(l=>null);return!a||!a.content?"analyzeImage Error":a.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
409
+ Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(l=>l.json()).catch(l=>null);return!i||!i.content?"analyzeImage Error":i.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
392
410
  If the user requests you to view, analyze, or extract information from an image, you **must** call the \`analyzeImage\` tool.
393
411
 
394
412
  When invoking this tool, you must pass the correct \`imageId\` extracted from the prior conversation.
@@ -398,5 +416,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
398
416
 
399
417
  Do not attempt to describe or analyze the image directly yourself.
400
418
  Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
401
- Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(l=>l.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image"?(po.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++):a.type==="text"&&a.text.includes("[Image #")?a.text=a.text.replace(/\[Image #\d+\]/g,""):a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(l=>l.type==="image")&&(po.storeImage(`${e.id}_Image#${r}`,a.content[0].source),a.content=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++)})})}},Aa=new Lr});var Fr,Ea,fo,Ia=P(()=>{"use strict";Oa();Fr=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}},Ea=new Fr;Ea.registerAgent(Aa);fo=Ea});function La(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&be(n,e)}function Dr(n){return n.usageSessionId||n.id}function mo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Dr(n)}`}function it(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function xu(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Ne(e.usage):e.response?.usage?Ne(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Cu(n,e,t){if(await new Promise((r,s)=>{let a=l=>l?s(l):r();Ht(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){La(n,t);let r=mo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Z.get(r))}if((n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses"))&&n.clientType==="codex"){await ca();let r=await ua();n.codexAccountId=r.id,n.codexAccountEmail=r.email}}async function Tu(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of fo.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function Fa(n){return{authCodex:(e,t)=>Cu(e,t,n),agent:(e,t)=>Tu(e,t,n)}}function Ua(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Ur.performance.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let l=c=>c?a(c):s();Ht(e)(t,o,l).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Ma.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),l=t.pathname?.endsWith("/v1/responses");if(a||l){La(t,e);let c=Dr(t),i=mo(t);if(r instanceof ReadableStream){if(a&&t.agents){let y=new AbortController,p=r.pipeThrough(new ue),f,_=-1,k="",h="",b="",x=[],v=[];return s(null,Pt(p,async(C,R)=>{try{if(C.event==="content_block_start"&&C?.data?.content_block?.name){let T=t.agents.find(O=>fo.getAgent(O)?.tools.get(C.data.content_block.name));if(T){f=fo.getAgent(T),_=C.data.index,k=C.data.content_block.name,b=C.data.content_block.id;return}}if(_>-1&&C.data.index===_&&C.data?.delta?.type==="input_json_delta"){h+=C.data?.delta?.partial_json;return}if(_>-1&&C.data.index===_&&C.data?.type==="content_block_stop"){try{let T=Na.default.parse(h);v.push({type:"tool_use",id:b,name:k,input:T});let O=await f?.tools.get(k)?.handler(T,{req:t,config:e});x.push({tool_use_id:b,type:"tool_result",content:O}),f=void 0,_=-1,k="",h="",b=""}catch(T){console.log(T)}return}if(C.event==="message_delta"&&x.length){t.body.messages.push({role:"assistant",content:v}),t.body.messages.push({role:"user",content:x});let T=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!T.ok)return;let w=T.body.pipeThrough(new ue).getReader();for(;;)try{let{value:E,done:A}=await w.read();if(A)break;let I=E;if(["message_start","message_stop"].includes(I.event))continue;if(!R.desiredSize)break;R.enqueue(I)}catch(E){if(E.name==="AbortError"||E.code==="ERR_STREAM_PREMATURE_CLOSE"){y.abort();break}throw E}return}return C}catch(T){if(console.error("Unexpected error in stream processing:",T),T.code==="ERR_STREAM_PREMATURE_CLOSE"){y.abort();return}throw T}}).pipeThrough(new $e))}let[d,m]=r.tee(),g=async y=>{let f=y.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();try{for(;;){let{done:_,value:k}=await f.read();if(_)break;let h=k.event,b=k.data;if(h==="message_start"&&b?.message?.model&&(t.upstreamModel=b.message.model),h==="response.completed"&&b?.response?.model&&(t.upstreamModel=b.response.model),b?.usage){let x=Z.get(i)||{},v=Ne(b.usage),C=Dt(x,v,h==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:h,provider:t.provider,model:it(t),usageSessionId:c,capturedUsage:v,mergedUsage:C}),(v?.cache_read_input_tokens||v?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:v?.cache_read_input_tokens,cache_creation:v?.cache_creation_input_tokens}),Z.put(i,C)}if(b?.response?.usage){let x=Ne(b.response.usage),v=Z.get(i)||{},C=Dt(v,x,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:h,provider:t.provider,model:it(t),usageSessionId:c,capturedUsage:x,mergedUsage:C}),Z.put(i,C)}}}catch(_){_.name==="AbortError"||_.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",_)}finally{f.releaseLock()}};return t.usageCapturePromise=g(m),s(null,d)}let u=xu(r);if(u?.usage&&Z.put(i,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(Ma.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{t.usageCapturePromise&&await t.usageCapturePromise,t.tokenSpeedCapturePromise&&await t.tokenSpeedCapturePromise;let r=Dr(t),s=o.statusCode>=400,a=s?void 0:Z.get(mo(t)),l=Ar(r),c=D(),i,u,d=t.sseError,m=d&&(d.type||d.code||d.message),g=a?.output_tokens&&a.output_tokens>0,y=s||m&&!g;if(y){i=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,m&&(i=i||JSON.stringify(d),u=JSON.stringify(d)),u=u||t.errorResponseBody;let h=it(t);co(o.statusCode,i)?(c.markRateLimited(t.provider||"",h,120,i),(t.clientType||ke(t))==="codex"&&await ao(i)):c.recordFailure(t.provider||"",h,i)}else{let h=it(t);c.recordSuccess(t.provider||"",h)}let p=a?.cache_read_input_tokens??0,_=a?.input_tokens||0||t.tokenCount||0;!p&&t.tokenCount&&a?.input_tokens&&a.input_tokens<t.tokenCount&&(p=t.tokenCount-a.input_tokens,p&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:a.input_tokens,impliedCache:p}));let k=y?0:a?.output_tokens||0;!y&&t.body?.stream&&_===0&&k===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:it(t),usageSessionId:r,tokenCount:t.tokenCount,cachedUsage:a,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),Gt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:r,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:it(t),upstreamModel:t.upstreamModel,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||ke(t),codexAccountId:t.codexAccountId,codexAccountEmail:t.codexAccountEmail,stream:t.body?.stream??!1,inputTokens:_,outputTokens:k,cacheReadInputTokens:p,cacheCreationInputTokens:a?.cache_creation_input_tokens||0,ttft:y?null:l.ttft,tokensPerSecond:y?null:l.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Ur.performance.now()-t.requestStartTime):0,status:y?"error":"success",errorMessage:i,responseBody:u}),t.clientContext?.usageScope!=="session"&&Z.delete(mo(t))}catch(r){console.error("Usage tracking error:",r)}})}var $a,Ur,Na,Ma,Da=P(()=>{"use strict";$a=require("node:events"),Ur=require("node:perf_hooks"),Na=Y(require("json5"),1);Qe();un();ce();ir();ar();cr();Qt();br();Ia();vr();kn();Er();Ma=new $a.EventEmitter});var Ja={};Yt(Ja,{createCcrServer:()=>vu});async function vu(n={}){await oa(),await Lt();let e=await eo();la();let t=e.Providers||e.providers||[],o=t&&t.length>0,r=e.HOST||"127.0.0.1";o?(r=e.HOST,e.APIKEY||(r="127.0.0.1")):(r="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let s=n.port??e.PORT??3456,a=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):s,l=p=>(p>9?"":"0")+p,c=(p,f)=>{let _;p?typeof p=="number"?_=new Date(p):_=p:_=new Date;let k=_.getFullYear()+""+l(_.getMonth()+1),h=l(_.getDate()),b=l(_.getHours()),x=l(_.getMinutes());return`./logs/ccr-${k}${h}${b}${x}${l(_.getSeconds())}${f?`_${f}`:""}.log`},i;n.logger!==void 0?i=n.logger:(ma(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),i={level:e.LOG_LEVEL||"error",stream:(0,Ha.createStream)(c,{path:at.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):i=!1);let u=await(0,at.listPresets)(),d=new jr({jsonPath:at.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:r,PORT:a,LOG_FILE:(0,za.join)((0,ja.homedir)(),".claude-code-router","claude-code-router.log")},logger:i});await d.ready(),await Sa(d,e),d.recordUsage=p=>{try{let f=p.req?p.req.clientType||ke(p.req):"unknown";f==="codex"&&co(0,p.errorMessage)&&ao(p.errorMessage),Gt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:p.sessionId||"",provider:p.provider||"",originalModel:p.originalModel||"",model:p.model||"",modelFamily:p.modelFamily||"",scenarioType:p.scenarioType||"default",clientType:f,codexAccountId:p.req?.codexAccountId,codexAccountEmail:p.req?.codexAccountEmail,stream:p.stream??!1,inputTokens:p.inputTokens||0,outputTokens:0,cacheReadInputTokens:p.cacheReadInputTokens||0,cacheCreationInputTokens:p.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:p.errorMessage,responseBody:void 0})}catch(f){console.error("Fallback usage tracking error:",f)}},Ua(d,e),d.ccrPreHandlerCallbacks=Fa(e),(await Promise.allSettled(u.map(async p=>await d.registerNamespace(`/preset/${p.name}`,p.config)))).forEach((p,f)=>{if(p.status==="rejected"){let _=u[f],k=p.reason instanceof Error?p.reason.message:String(p.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await ha(d,e),nt(e,d.app?.log);let g=p=>{d.app.log.error({err:p},"Uncaught exception")},y=(p,f)=>{d.app.log.error({reason:p,promise:f},"Unhandled rejection")};return process.on("uncaughtException",g),process.on("unhandledRejection",y),d.app.addHook("onClose",async()=>{process.off("uncaughtException",g),process.off("unhandledRejection",y)}),d}var ja,za,Ha,at,Ba=P(()=>{"use strict";ja=require("os"),za=require("path");Wa();Ha=require("rotating-file-stream"),at=require("@wengine-ai/claude-code-router-shared");ra();Ut();Er();ga();ya();Pa();Da();no();Qt();Qe()});var Su={};Yt(Su,{ActiveProbeService:()=>wt,ConfigService:()=>Se,ProjectRoutingError:()=>pe,ProviderHealthStore:()=>pt,ProviderService:()=>fe,SSEParserTransform:()=>ue,SSESerializerTransform:()=>$e,TokenizerService:()=>Ie,TransformerService:()=>Ee,apiKeyAuth:()=>Ht,applyClientAdapter:()=>be,backupConfigFile:()=>Ft,builtinClientAdapterRegistry:()=>$o,calculateTokenCount:()=>_t,clearClientAdapterCaches:()=>bs,clearProviderHealth:()=>jt,closeProxyDispatchers:()=>Zt,collectReachableModelKeys:()=>Cr,createCcrServer:()=>Qa,default:()=>jr,detectClientType:()=>ke,diagnoseResolutionFailure:()=>Fo,extractSessionIdFromUserId:()=>Ve,getActiveProbeService:()=>rr,getAllQuotaResults:()=>pn,getAllRateLimitInfo:()=>ln,getClientAdapter:()=>Lo,getConfiguredProxyUrl:()=>ct,getHealthStore:()=>D,getProxyDispatcher:()=>K,getQuotaAdapter:()=>Xn,getQuotaResult:()=>mt,getRateLimitInfo:()=>fs,getRuntimeDebugLog:()=>ut,getServer:()=>wu,initConfig:()=>eo,initDir:()=>Lt,initProviderHealthPersistence:()=>cn,initQuotaStorePersistence:()=>We,initRateLimitPersistence:()=>ze,isClientType:()=>No,isGlobalProxyEnabled:()=>go,listAnthropicCompatibleModels:()=>zt,mergeUsageCapture:()=>Dt,normalizeSessionId:()=>Ae,normalizeUsagePayload:()=>Ne,pluginManager:()=>Ze,readConfigFile:()=>z,readConfigFileRaw:()=>Zn,reconcileHealthStore:()=>nt,resetActiveProbeService:()=>St,resolveProviderProxyUrl:()=>de,rewriteStream:()=>Pt,router:()=>kt,searchProjectBySession:()=>Uo,sessionUsageCache:()=>Z,setRuntimeDebugLog:()=>tn,startActiveProbe:()=>Me,stopActiveProbe:()=>Yn,storeQuotaResult:()=>dn,tokenSpeedPlugin:()=>$t,usageStore:()=>Or,writeConfigFile:()=>ne});module.exports=Jr(Su);function Ru(n={}){let e=(0,Ga.default)({bodyLimit:52428800,...n});return e.setErrorHandler(Kr),e.register(Va.default),e}async function Qa(n={}){return(await Promise.resolve().then(()=>(Ba(),Ja))).createCcrServer(n)}var Ga,Va,zr,jr,wu,Wa=P(()=>{Ga=Y(require("fastify"),1),Va=Y(require("@fastify/cors"),1);yo();en();kn();bn();Ho();Jo();bt();un();qn();ce();He();Ge();ae();Qe();kn();gt();Qe();bt();yo();bn();Ho();Jo();yr();lr();ce();He();nr();Ge();ce();qn();dt();ae();Ut();br();no();Tr();vr();Qt();zr=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:l,...c}=e;this.app=Ru({...c,logger:c.logger??!0}),this.app._server=this;let i={initialConfig:t};o!==void 0&&(i.jsonPath=o),r!==void 0&&(i.envPath=r),s!==void 0&&(i.useEnvFile=s),a!==void 0&&(i.useJsonFile=a),l!==void 0&&(i.useEnvironmentVariables=l),this.configService=new Se(i),this.transformerService=new Ee(this.configService,this.app.log),this.tokenizerService=new Ie(this.configService,this.app.log),this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.providerService=new fe(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Se({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ee(o,this.app.log),a=new Ie(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),s=new fe(o,r,this.app.log)}let l=async c=>{c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(i,u)=>{let d=new URL(`http://127.0.0.1${i.url}`);i.pathname=d.pathname;let m=d.pathname.endsWith("/v1/messages"),g=d.pathname.endsWith("/v1/responses");if(!m&&!g||!i.body||typeof i.body!="object")return;let y=i.ccrHookOrder||=[];if(y.push("request-normalize"),g&&i.body.input&&!i.body.messages&&xt(i.body),i.body.stream===void 0&&(i.body.stream=!1),i.log.info({data:i.body,type:"request body"}),y.push("adapter"),!i.originalModel&&i.body.model&&(i.originalModel=i.body.model),be(i,o.getAll()),y.push("auth-codex"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authCodex(i,u),u.sent))&&(y.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(i,u),u.sent)))){y.push("router"),i.body?.model&&await kt(i,u,{configService:o,tokenizerService:a}),i.usageCacheKey&&Z.put(i.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),y.push("provider-model-normalize");try{let p=i.body;if(!p||!p.model)return u.code(400).send({error:"Missing model in request body"});let f=p.model.split(","),_=p.model;if(f.length>1){let[k,...h]=f;_=h.join(","),p.model=_,i.provider=k}i.model=_}catch(p){return i.log.error({error:p},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Ns(c)};e==="/"?(await this.app.register(l),this.mainNamespaceRegistered=!0):await this.app.register(l,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{Yn()}catch{}await this.app.close(),process.exit(0)},o=()=>void t("SIGINT"),r=()=>void t("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",r),this.app.addHook("onClose",async()=>{process.off("SIGINT",o),process.off("SIGTERM",r),this.signalHandlersRegistered=!1;try{this.tokenizerService.dispose()}catch{}await Zt()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{ze()}catch{}try{We()}catch{}try{cn()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Me(()=>this.providerService.getProviders(),t,o=>de(this.configService,o),this.app.log,o=>this.configService.get(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},jr=zr;wu=Qa});Wa();0&&(module.exports={ActiveProbeService,ConfigService,ProjectRoutingError,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,apiKeyAuth,applyClientAdapter,backupConfigFile,builtinClientAdapterRegistry,calculateTokenCount,clearClientAdapterCaches,clearProviderHealth,closeProxyDispatchers,collectReachableModelKeys,createCcrServer,detectClientType,diagnoseResolutionFailure,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getClientAdapter,getConfiguredProxyUrl,getHealthStore,getProxyDispatcher,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,getServer,initConfig,initDir,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,isClientType,isGlobalProxyEnabled,listAnthropicCompatibleModels,mergeUsageCapture,normalizeSessionId,normalizeUsagePayload,pluginManager,readConfigFile,readConfigFileRaw,reconcileHealthStore,resetActiveProbeService,resolveProviderProxyUrl,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin,usageStore,writeConfigFile});
419
+ Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(i=>i.type==="image"||Array.isArray(i.content)&&i.content.some(l=>l.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(i=>{if(i.type==="image")ro.storeImage(`${e.id}_Image#${r}`,i.source),i.type="text",delete i.source,i.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(i.type==="text"&&i.text.includes("[Image #"))i.text=i.text.replace(/\[Image #\d+\]/g,"");else if(i.type==="tool_result"&&Array.isArray(i.content)&&i.content.some(l=>l.type==="image")){let l=[],a=i.content.filter(u=>u.type!=="image"?!0:(ro.storeImage(`${e.id}_Image#${r}`,u.source),l.push(`[Image #${r}]`),r++,!1)),c=`${l.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;i.content=a.length>0?[{type:"text",text:c},...a]:c}})})}},aa=new wr});var Pr,la,so,ua=w(()=>{"use strict";ca();Pr=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}},la=new Pr;la.registerAgent(aa);so=la});function Ul(n,e){return n===429||!!(e&&/rate[\s_]limit|too many|限流|频率限制|qps_limit|token_limit|quota exhausted|usage limit|limit reached/i.test(e))}function ma(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&he(n,e)}function Or(n){return n.usageSessionId||n.id}function io(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Or(n)}`}function ot(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function jl(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Me(e.usage):e.response?.usage?Me(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Hl(n,e,t){if(await new Promise((r,s)=>{let i=l=>l?s(l):r();Ft(t)(n,e,i).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){ma(n,t);let r=io(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=q.get(r))}}async function zl(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of so.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function ga(n){return{authClient:(e,t)=>Hl(e,t,n),agent:(e,t)=>zl(e,t,n)}}function ha(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Er.performance.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,i)=>{let l=a=>a?i(a):s();Ft(e)(t,o,l).then(()=>s(),i)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",da.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let i=t.pathname?.endsWith("/v1/messages"),l=t.pathname?.endsWith("/v1/responses");if(i||l){ma(t,e);let a=Or(t),c=io(t);if(r instanceof ReadableStream){if(i&&t.agents){let y=new AbortController,p=r.pipeThrough(new ce),f,_=-1,k="",h="",b="",T=[],x=[];return s(null,St(p,async(v,S)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let C=t.agents.find(P=>so.getAgent(P)?.tools.get(v.data.content_block.name));if(C){f=so.getAgent(C),_=v.data.index,k=v.data.content_block.name,b=v.data.content_block.id;return}}if(_>-1&&v.data.index===_&&v.data?.delta?.type==="input_json_delta"){h+=v.data?.delta?.partial_json;return}if(_>-1&&v.data.index===_&&v.data?.type==="content_block_stop"){try{let C=fa.default.parse(h);x.push({type:"tool_use",id:b,name:k,input:C});let P=await f?.tools.get(k)?.handler(C,{req:t,config:e});T.push({tool_use_id:b,type:"tool_result",content:P}),f=void 0,_=-1,k="",h="",b=""}catch(C){console.log(C)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:T});let C=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!C.ok)return;let R=C.body.pipeThrough(new ce).getReader();for(;;)try{let{value:A,done:E}=await R.read();if(E)break;let I=A;if(["message_start","message_stop"].includes(I.event))continue;if(!S.desiredSize)break;S.enqueue(I)}catch(A){if(A.name==="AbortError"||A.code==="ERR_STREAM_PREMATURE_CLOSE"){y.abort();break}throw A}return}return v}catch(C){if(console.error("Unexpected error in stream processing:",C),C.code==="ERR_STREAM_PREMATURE_CLOSE"){y.abort();return}throw C}}).pipeThrough(new Ae))}let[d,g]=r.tee(),m=async y=>{let f=y.pipeThrough(new TextDecoderStream).pipeThrough(new ce).getReader();try{for(;;){let{done:_,value:k}=await f.read();if(_)break;let h=k.event,b=k.data;if(h==="message_start"&&b?.message?.model&&(t.upstreamModel=b.message.model),h==="response.completed"&&b?.response?.model&&(t.upstreamModel=b.response.model),b?.usage){let T=q.get(c)||{},x=Me(b.usage),v=Nt(T,x,h==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:h,provider:t.provider,model:ot(t),usageSessionId:a,capturedUsage:x,mergedUsage:v}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),q.put(c,v)}if(b?.response?.usage){let T=Me(b.response.usage),x=q.get(c)||{},v=Nt(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:h,provider:t.provider,model:ot(t),usageSessionId:a,capturedUsage:T,mergedUsage:v}),q.put(c,v)}}}catch(_){_.name==="AbortError"||_.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",_)}finally{f.releaseLock()}};return t.usageCapturePromise=m(g),s(null,d)}let u=jl(r);if(u?.usage&&q.put(c,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(da.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{t.usageCapturePromise&&await t.usageCapturePromise,t.tokenSpeedCapturePromise&&await t.tokenSpeedCapturePromise;let r=Or(t),s=o.statusCode>=400,i=s?void 0:q.get(io(t)),l=vr(r),a=U(),c,u,d=t.sseError,g=d&&(d.type||d.code||d.message),m=i?.output_tokens&&i.output_tokens>0,y=s||g&&!m;if(y){c=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,g&&(c=c||JSON.stringify(d),u=JSON.stringify(d)),u=u||t.errorResponseBody;let h=ot(t);Ul(o.statusCode,c)?a.markRateLimited(t.provider||"",h,120,c):a.recordFailure(t.provider||"",h,c)}else{let h=ot(t);a.recordSuccess(t.provider||"",h)}let p=i?.cache_read_input_tokens??0,_=i?.input_tokens||0||t.tokenCount||0;!p&&t.tokenCount&&i?.input_tokens&&i.input_tokens<t.tokenCount&&(p=t.tokenCount-i.input_tokens,p&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:i.input_tokens,impliedCache:p}));let k=y?0:i?.output_tokens||0;!y&&t.body?.stream&&_===0&&k===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:ot(t),usageSessionId:r,tokenCount:t.tokenCount,cachedUsage:i,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),zt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:r,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:ot(t),upstreamModel:t.upstreamModel,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Re(t),stream:t.body?.stream??!1,inputTokens:_,outputTokens:k,cacheReadInputTokens:p,cacheCreationInputTokens:i?.cache_creation_input_tokens||0,ttft:y?null:l.ttft,tokensPerSecond:y?null:l.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Er.performance.now()-t.requestStartTime):0,status:y?"error":"success",errorMessage:c,responseBody:u}),t.clientContext?.usageScope!=="session"&&q.delete(io(t))}catch(r){console.error("Usage tracking error:",r)}})}var pa,Er,fa,da,ya=w(()=>{"use strict";pa=require("node:events"),Er=require("node:perf_hooks"),fa=Y(require("json5"),1);Ge();rn();ie();er();tr();nr();Jt();mr();ua();_r();mn();da=new pa.EventEmitter});var Ta={};Gt(Ta,{createCcrServer:()=>Bl});async function Bl(n={}){await Wi(),await Mt();let e=await Vn(),t=e.Providers||e.providers||[],o=t&&t.length>0,r=e.HOST||"127.0.0.1";o?(r=e.HOST,e.APIKEY||(r="127.0.0.1")):(r="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let s=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):s,l=p=>(p>9?"":"0")+p,a=(p,f)=>{let _;p?typeof p=="number"?_=new Date(p):_=p:_=new Date;let k=_.getFullYear()+""+l(_.getMonth()+1),h=l(_.getDate()),b=l(_.getHours()),T=l(_.getMinutes());return`./logs/ccr-${k}${h}${b}${T}${l(_.getSeconds())}${f?`_${f}`:""}.log`},c;n.logger!==void 0?c=n.logger:(Yi(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),c={level:e.LOG_LEVEL||"error",stream:(0,ba.createStream)(a,{path:rt.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):c=!1);let u=await(0,rt.listPresets)(),d=new Ar({jsonPath:rt.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:r,PORT:i,LOG_FILE:(0,ka.join)((0,_a.homedir)(),".claude-code-router","claude-code-router.log")},logger:c});await d.ready(),await ra(d,e),d.recordUsage=p=>{try{let f=p.req?p.req.clientType||Re(p.req):"unknown";zt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:p.sessionId||"",provider:p.provider||"",originalModel:p.originalModel||"",model:p.model||"",modelFamily:p.modelFamily||"",scenarioType:p.scenarioType||"default",clientType:f,stream:p.stream??!1,inputTokens:p.inputTokens||0,outputTokens:0,cacheReadInputTokens:p.cacheReadInputTokens||0,cacheCreationInputTokens:p.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:p.errorMessage,responseBody:void 0})}catch(f){console.error("Fallback usage tracking error:",f)}},ha(d,e),d.ccrPreHandlerCallbacks=ga(e),(await Promise.allSettled(u.map(async p=>await d.registerNamespace(`/preset/${p.name}`,p.config)))).forEach((p,f)=>{if(p.status==="rejected"){let _=u[f],k=p.reason instanceof Error?p.reason.message:String(p.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await qi(d,e),tt(e,d.app?.log);let m=p=>{d.app.log.error({err:p},"Uncaught exception")},y=(p,f)=>{d.app.log.error({reason:p,promise:f},"Unhandled rejection")};return process.on("uncaughtException",m),process.on("unhandledRejection",y),d.app.addHook("onClose",async()=>{process.off("uncaughtException",m),process.off("unhandledRejection",y)}),d}var _a,ka,ba,rt,Ca=w(()=>{"use strict";_a=require("os"),ka=require("path");va();ba=require("rotating-file-stream"),rt=require("@wengine-ai/claude-code-router-shared");Gi();Yn();Xi();Zi();sa();ya();qn();Jt();Ge()});var Gl={};Gt(Gl,{ActiveProbeService:()=>vt,ConfigService:()=>ve,ProjectRoutingError:()=>ue,ProviderHealthStore:()=>lt,ProviderService:()=>de,SSEParserTransform:()=>ce,SSESerializerTransform:()=>Ae,TokenizerService:()=>Ee,TransformerService:()=>Pe,apiKeyAuth:()=>Ft,applyClientAdapter:()=>he,backupConfigFile:()=>$t,builtinClientAdapterRegistry:()=>wo,calculateTokenCount:()=>gt,clearClientAdapterCaches:()=>ds,clearProviderHealth:()=>Lt,closeProxyDispatchers:()=>Qt,collectReachableModelKeys:()=>hr,createCcrServer:()=>Ra,default:()=>Ar,detectClientType:()=>Re,diagnoseResolutionFailure:()=>Oo,extractSessionIdFromUserId:()=>We,getActiveProbeService:()=>qo,getAllQuotaResults:()=>an,getAllRateLimitInfo:()=>on,getClientAdapter:()=>Eo,getConfiguredProxyUrl:()=>st,getHealthStore:()=>U,getProxyDispatcher:()=>Q,getQuotaAdapter:()=>Wn,getQuotaResult:()=>dt,getRateLimitInfo:()=>rs,getRuntimeDebugLog:()=>at,getServer:()=>Wl,initConfig:()=>Vn,initDir:()=>Mt,initProviderHealthPersistence:()=>nn,initQuotaStorePersistence:()=>Be,initRateLimitPersistence:()=>Ue,isClientType:()=>Po,isGlobalProxyEnabled:()=>ao,listAnthropicCompatibleModels:()=>Dt,mergeUsageCapture:()=>Nt,normalizeSessionId:()=>Se,normalizeUsagePayload:()=>Me,pluginManager:()=>qe,readConfigFile:()=>oe,readConfigFileRaw:()=>Qn,reconcileHealthStore:()=>tt,resetActiveProbeService:()=>xt,resolveProviderProxyUrl:()=>le,rewriteStream:()=>St,router:()=>yt,searchProjectBySession:()=>Io,sessionUsageCache:()=>q,setRuntimeDebugLog:()=>Yt,startActiveProbe:()=>Oe,stopActiveProbe:()=>Gn,storeQuotaResult:()=>sn,tokenSpeedPlugin:()=>At,usageStore:()=>xr,writeConfigFile:()=>Ie});module.exports=$r(Gl);function Jl(n={}){let e=(0,xa.default)({bodyLimit:52428800,...n});return e.setErrorHandler(jr),e.register(Sa.default),e}async function Ra(n={}){return(await Promise.resolve().then(()=>(Ca(),Ta))).createCcrServer(n)}var xa,Sa,Ir,Ar,Wl,va=w(()=>{xa=Y(require("fastify"),1),Sa=Y(require("@fastify/cors"),1);lo();Vt();mn();gn();Lo();Do();Ve();rn();Kn();ie();je();Je();se();Ge();mn();pt();Ge();Ve();lo();gn();Lo();Do();dr();or();ie();je();Yo();Je();ie();Kn();ct();se();Yn();mr();qn();yr();_r();Jt();Ir=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:i,useEnvironmentVariables:l,...a}=e;this.app=Jl({...a,logger:a.logger??!0}),this.app._server=this;let c={initialConfig:t};o!==void 0&&(c.jsonPath=o),r!==void 0&&(c.envPath=r),s!==void 0&&(c.useEnvFile=s),i!==void 0&&(c.useJsonFile=i),l!==void 0&&(c.useEnvironmentVariables=l),this.configService=new ve(c),this.transformerService=new Pe(this.configService,this.app.log),this.tokenizerService=new Ee(this.configService,this.app.log),this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.providerService=new de(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,i=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new ve({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Pe(o,this.app.log),i=new Ee(o,this.app.log),await Promise.all([r.initialize(),i.initialize()]),s=new de(o,r,this.app.log)}let l=async a=>{a.decorate("configService",o),a.decorate("transformerService",r),a.decorate("providerService",s),a.decorate("tokenizerService",i),a.decorate("recordUsage",this.recordUsage||(()=>{})),a.addHook("preHandler",async(c,u)=>{let d=new URL(`http://127.0.0.1${c.url}`);c.pathname=d.pathname;let g=d.pathname.endsWith("/v1/messages"),m=d.pathname.endsWith("/v1/responses");if(!g&&!m||!c.body||typeof c.body!="object")return;let y=c.ccrHookOrder||=[];if(y.push("request-normalize"),m&&c.body.input&&!c.body.messages&&_t(c.body),c.body.stream===void 0&&(c.body.stream=!1),c.log.info({data:c.body,type:"request body"}),y.push("adapter"),!c.originalModel&&c.body.model&&(c.originalModel=c.body.model),he(c,o.getAll()),y.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(c,u),u.sent))&&(y.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(c,u),u.sent)))){y.push("router"),c.body?.model&&await yt(c,u,{configService:o,tokenizerService:i}),c.usageCacheKey&&q.put(c.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),y.push("provider-model-normalize");try{let p=c.body;if(!p||!p.model)return u.code(400).send({error:"Missing model in request body"});let f=p.model.split(","),_=p.model;if(f.length>1){let[k,...h]=f;_=h.join(","),p.model=_,c.provider=k}c.model=_}catch(p){return c.log.error({error:p},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Ss(a)};e==="/"?(await this.app.register(l),this.mainNamespaceRegistered=!0):await this.app.register(l,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{Gn()}catch{}await this.app.close(),process.exit(0)},o=()=>void t("SIGINT"),r=()=>void t("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",r),this.app.addHook("onClose",async()=>{process.off("SIGINT",o),process.off("SIGTERM",r),this.signalHandlersRegistered=!1;try{this.tokenizerService.dispose()}catch{}await Qt()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{Ue()}catch{}try{Be()}catch{}try{nn()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Oe(()=>this.providerService.getProviders(),t,o=>le(this.configService,o),this.app.log,o=>this.configService.get(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},Ar=Ir;Wl=Ra});va();0&&(module.exports={ActiveProbeService,ConfigService,ProjectRoutingError,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,apiKeyAuth,applyClientAdapter,backupConfigFile,builtinClientAdapterRegistry,calculateTokenCount,clearClientAdapterCaches,clearProviderHealth,closeProxyDispatchers,collectReachableModelKeys,createCcrServer,detectClientType,diagnoseResolutionFailure,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getClientAdapter,getConfiguredProxyUrl,getHealthStore,getProxyDispatcher,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,getServer,initConfig,initDir,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,isClientType,isGlobalProxyEnabled,listAnthropicCompatibleModels,mergeUsageCapture,normalizeSessionId,normalizeUsagePayload,pluginManager,readConfigFile,readConfigFileRaw,reconcileHealthStore,resetActiveProbeService,resolveProviderProxyUrl,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin,usageStore,writeConfigFile});
402
420
  //# sourceMappingURL=server.cjs.map