@wengine-ai/llms 2.3.2411 → 2.3.2412
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cjs/server.cjs +11 -11
- package/dist/cjs/server.cjs.map +3 -3
- package/dist/esm/server.mjs +4 -4
- package/dist/esm/server.mjs.map +3 -3
- package/package.json +2 -2
package/dist/esm/server.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; import { fileURLToPath as __fileURLToPath } from "node:url"; import { dirname as __pathDirname } from "node:path"; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __pathDirname(__filename);
|
|
2
2
|
var to=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var oc=Object.getOwnPropertyNames;var rc=Object.prototype.hasOwnProperty;var Xe=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var E=(n,e)=>()=>(n&&(e=n(n=0)),e);var no=(n,e)=>{for(var t in e)to(n,t,{get:e[t],enumerable:!0})},sc=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of oc(e))!rc.call(n,r)&&r!==t&&to(n,r,{get:()=>e[r],enumerable:!(o=nc(e,r))||o.enumerable});return n};var ic=n=>sc(to({},"__esModule",{value:!0}),n);import{ProxyAgent as ac}from"undici";function lc(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(cc.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 Kr(n){let e=[];for(let t of Wr){let o=n[t];if(o==null)continue;let r=lc(o);r.ok||e.push({key:t,error:r.error})}return e}function Rt(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 Gr(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 ce(n,e){let t=Rt(n);if(t)return Gr(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=uc(n),t=St.get(e);if(t)return t;let o=new ac(e);return St.set(e,o),o}async function oo(){let n=Array.from(St.values());St.clear(),await Promise.allSettled(n.map(e=>e.close()))}function uc(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 Wr,cc,St,oe=E(()=>{"use strict";Wr=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],cc=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;St=new Map});import{readFileSync as dc,existsSync as Vr}from"fs";import{join as Qr}from"path";import{config as pc}from"dotenv";import fc from"json5";var Re,ro=E(()=>{"use strict";oe();Re=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:Qr(process.cwd(),this.options.jsonPath);if(Vr(e))try{let t=dc(e,"utf-8"),o=fc.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:Qr(process.cwd(),this.options.envPath);if(Vr(e))try{let t=pc({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 Rt(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 J(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 Yr(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 wt=E(()=>{"use strict"});function io(n){so=n}function Et(){return so}function Pt(n){return so||n.get("DEBUG_LOG")===!0}function qr(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?we:{maxBodyLength:e.maxBodyLength??we.maxBodyLength,maxStreamChunks:e.maxStreamChunks??we.maxStreamChunks}}function Ot(n){let e={};for(let[t,o]of Object.entries(n))mc.has(t.toLowerCase())?e[t]="***MASKED***":e[t]=o;return e}function At(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function es(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:Ot(t.headers),body:At(o,we.maxBodyLength)})}function ts(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Ot(t.headers),...t.body!==void 0?{body:At(t.body,we.maxBodyLength)}:{}})}function Xr(n,e,t,o){let r=gc(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:At(o,we.maxBodyLength)})}function gc(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:At(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 ns(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let i="";for(;;){let{done:a,value:l}=await r.read();if(a)break;i+=l;let c=i.split(`
|
|
3
3
|
|
|
4
|
-
`);i=c.pop()||"";for(let u of c)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++)}i.trim()&&(s<o.maxStreamChunks&&Xr(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 mc,we,so,Ze=E(()=>{"use strict";mc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),we={maxBodyLength:4096,maxStreamChunks:100},so=!1});function os(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,a=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),a.addEventListener("abort",u),i=c.signal}else i=a;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:i};return t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Ot(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:hc(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function hc(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 rs=E(()=>{oe();Ze()});var It,ao=E(()=>{It="2.3.2411"});var ss={};no(ss,{getFallbackPromotionStore:()=>Ee,resetFallbackPromotionStore:()=>kc});function Ee(n){return ve||(ve=new co,n&&ve.configure(n)),ve}function kc(){ve&&(ve.clearAll(),ve=null)}var _c,co,ve,Mt=E(()=>{"use strict";re();_c=600*1e3,co=class{promotions=new Map;enabled=!0;ttlMs=_c;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 a=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(a,{promotedModel:l,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[l,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(l,u))return this.promotions.delete(s),null;let p=r.find(h=>h.name.toLowerCase()===l.toLowerCase()),m=p?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!p||!m||p.enabled===!1?(this.promotions.delete(s),null):`${p.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}},ve=null});import{existsSync as cs,mkdirSync as bc,readFileSync as Tc,writeFileSync as vc}from"fs";import{join as ls}from"path";import{HOME_DIR as xc}from"@wengine-ai/claude-code-router-shared";function wc(n){try{if(!cs(po))return;let e=JSON.parse(Tc(po,"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 as(n){try{let e=n.getAllStates();if(e.length===0)return;cs(uo)||bc(uo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));vc(po,JSON.stringify(t,null,2),"utf-8")}catch{}}function fo(){if(is)return;is=!0;let n=U();wc(n),Rc=setInterval(()=>as(n),6e4),process.on("exit",()=>as(n))}function U(n){return lo||(lo=new Nt(n)),lo}var Cc,Sc,Nt,uo,po,is,Rc,lo,re=E(()=>{"use strict";Cc=120,Sc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Nt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Sc,...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}=(Mt(),ic(ss));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 a=(o??Cc)*1e3;i.rateLimitUntil=Date.now()+a}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)}},uo=ls(xc,"runtime"),po=ls(uo,"provider-health.json"),is=!1,Rc=null;lo=null});import{existsSync as ms,mkdirSync as Ec,readFileSync as Pc,writeFileSync as Oc}from"fs";import{join as gs}from"path";import{HOME_DIR as Ac}from"@wengine-ai/claude-code-router-shared";function qe(n,e,t){let o=a=>{if(t instanceof Headers)return t.get(a);let l=Object.keys(t).find(c=>c.toLowerCase()===a);return l?t[l]:null},r=mo(o,Ic),s=mo(o,Mc),i=mo(o,Nc);(r||s||i)&&Pe.set(n,{provider:n,remaining:ps(r),limit:ps(s),reset:Lc(i),capturedAt:Date.now()})}function $c(n){return Pe.get(n)}function yo(){return Array.from(Pe.values())}function mo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ps(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Lc(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=Dc(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Dc(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 Fc(){try{if(!ms(ho))return;let n=JSON.parse(Pc(ho,"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;Pe.set(t.provider,t)}}catch{}}function fs(){try{if(Pe.size===0)return;ms(go)||Ec(go,{recursive:!0}),Oc(ho,JSON.stringify(Array.from(Pe.values()),null,2),"utf-8")}catch{}}function et(){us||(us=!0,Fc(),ds=setInterval(fs,6e4),ds.unref?.(),process.on("exit",fs))}var go,ho,Pe,us,ds,Ic,Mc,Nc,Oe=E(()=>{"use strict";go=gs(Ac,"runtime"),ho=gs(go,"rate-limit.json"),Pe=new Map,us=!1,ds=null,Ic=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Mc=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Nc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Lt(){return _o||(_o=new bo),_o}function vo(){return ko||(ko=new To),ko}function Uc(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function hs(n){let e=Uc(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function ys(n,e){let t=Lt(),o=n?.[$t];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[$t]=t.acquire(e)}function xo(n){let e=n?.[$t];e&&Lt().release(e)}function _s(n,e){let t=hs(n),o=n?.[$t],r=t?vo().get(t)!==void 0:!1;!o&&!r||(t&&vo().bind(t,e),ys(n,e))}function jc(n,e,t){let o=Lt(),r=null,s=1/0;for(let i of e){if(!i||typeof i!="string")continue;let a=t(i);if(!a||a===n)continue;let l=o.count(a);l<s&&(r=a,s=l)}return r}function ks(n,e,t){let o=hs(n),r=vo(),s=Lt(),i=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,a;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(a=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(a=e)}if(!a){let l=s.count(e);if(l>=i){let c=jc(e,t.fallbackModels,t.resolve);c&&(a=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${i}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}a=a||e,o&&r.bind(o,a)}return ys(n,a),a}var bo,To,_o,ko,$t,Dt=E(()=>{"use strict";bo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},To=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},_o=null,ko=null;$t="__concurrencyLease"});async function F(n){let e=await n.text();return Hc(e,n.status)}function Hc(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function bs(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function tt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let i=0;i<8;i++){let{value:a,done:l}=await o.read();if(l||(a&&(s+=r.decode(a,{stream:!0})),tt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:tt(s)}}async function fe(n){try{let e=await n.text();if(tt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=E(()=>{"use strict"});var Ae,Co=E(()=>{"use strict";V();Ae=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 pe(e);if(o?.isSSE&&o.body){let r=new Response(o.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(r)}if(o?.body)e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(o===null){let r=await fe(e);if(r.isSSE)return this.transformResponseOut(r.response);e=r.response}}if(t.includes("application/json")){let o=await F(e);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,p="",m=!1,h=this,g=new ReadableStream({async start(f){let _=c.getReader(),k=-1,y="",b=T=>(T!==y&&(k++,y=T),k);try{for(;;){let{done:T,value:C}=await _.read();if(T){m||f.enqueue(d.encode(`data: [DONE]
|
|
4
|
+
`);i=c.pop()||"";for(let u of c)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++)}i.trim()&&(s<o.maxStreamChunks&&Xr(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 mc,we,so,Ze=E(()=>{"use strict";mc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),we={maxBodyLength:4096,maxStreamChunks:100},so=!1});function os(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,a=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),a.addEventListener("abort",u),i=c.signal}else i=a;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:i};return t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Ot(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:hc(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function hc(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 rs=E(()=>{oe();Ze()});var It,ao=E(()=>{It="2.3.2412"});var ss={};no(ss,{getFallbackPromotionStore:()=>Ee,resetFallbackPromotionStore:()=>kc});function Ee(n){return ve||(ve=new co,n&&ve.configure(n)),ve}function kc(){ve&&(ve.clearAll(),ve=null)}var _c,co,ve,Mt=E(()=>{"use strict";re();_c=600*1e3,co=class{promotions=new Map;enabled=!0;ttlMs=_c;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 a=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(a,{promotedModel:l,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[l,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(l,u))return this.promotions.delete(s),null;let p=r.find(h=>h.name.toLowerCase()===l.toLowerCase()),m=p?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!p||!m||p.enabled===!1?(this.promotions.delete(s),null):`${p.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}},ve=null});import{existsSync as cs,mkdirSync as bc,readFileSync as Tc,writeFileSync as vc}from"fs";import{join as ls}from"path";import{HOME_DIR as xc}from"@wengine-ai/claude-code-router-shared";function wc(n){try{if(!cs(po))return;let e=JSON.parse(Tc(po,"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 as(n){try{let e=n.getAllStates();if(e.length===0)return;cs(uo)||bc(uo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));vc(po,JSON.stringify(t,null,2),"utf-8")}catch{}}function fo(){if(is)return;is=!0;let n=U();wc(n),Rc=setInterval(()=>as(n),6e4),process.on("exit",()=>as(n))}function U(n){return lo||(lo=new Nt(n)),lo}var Cc,Sc,Nt,uo,po,is,Rc,lo,re=E(()=>{"use strict";Cc=120,Sc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Nt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Sc,...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}=(Mt(),ic(ss));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 a=(o??Cc)*1e3;i.rateLimitUntil=Date.now()+a}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)}},uo=ls(xc,"runtime"),po=ls(uo,"provider-health.json"),is=!1,Rc=null;lo=null});import{existsSync as ms,mkdirSync as Ec,readFileSync as Pc,writeFileSync as Oc}from"fs";import{join as gs}from"path";import{HOME_DIR as Ac}from"@wengine-ai/claude-code-router-shared";function qe(n,e,t){let o=a=>{if(t instanceof Headers)return t.get(a);let l=Object.keys(t).find(c=>c.toLowerCase()===a);return l?t[l]:null},r=mo(o,Ic),s=mo(o,Mc),i=mo(o,Nc);(r||s||i)&&Pe.set(n,{provider:n,remaining:ps(r),limit:ps(s),reset:Lc(i),capturedAt:Date.now()})}function $c(n){return Pe.get(n)}function yo(){return Array.from(Pe.values())}function mo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ps(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Lc(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=Dc(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Dc(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 Fc(){try{if(!ms(ho))return;let n=JSON.parse(Pc(ho,"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;Pe.set(t.provider,t)}}catch{}}function fs(){try{if(Pe.size===0)return;ms(go)||Ec(go,{recursive:!0}),Oc(ho,JSON.stringify(Array.from(Pe.values()),null,2),"utf-8")}catch{}}function et(){us||(us=!0,Fc(),ds=setInterval(fs,6e4),ds.unref?.(),process.on("exit",fs))}var go,ho,Pe,us,ds,Ic,Mc,Nc,Oe=E(()=>{"use strict";go=gs(Ac,"runtime"),ho=gs(go,"rate-limit.json"),Pe=new Map,us=!1,ds=null,Ic=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Mc=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Nc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Lt(){return _o||(_o=new bo),_o}function vo(){return ko||(ko=new To),ko}function Uc(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function hs(n){let e=Uc(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function ys(n,e){let t=Lt(),o=n?.[$t];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[$t]=t.acquire(e)}function xo(n){let e=n?.[$t];e&&Lt().release(e)}function _s(n,e){let t=hs(n),o=n?.[$t],r=t?vo().get(t)!==void 0:!1;!o&&!r||(t&&vo().bind(t,e),ys(n,e))}function jc(n,e,t){let o=Lt(),r=null,s=1/0;for(let i of e){if(!i||typeof i!="string")continue;let a=t(i);if(!a||a===n)continue;let l=o.count(a);l<s&&(r=a,s=l)}return r}function ks(n,e,t){let o=hs(n),r=vo(),s=Lt(),i=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,a;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(a=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(a=e)}if(!a){let l=s.count(e);if(l>=i){let c=jc(e,t.fallbackModels,t.resolve);c&&(a=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${i}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}a=a||e,o&&r.bind(o,a)}return ys(n,a),a}var bo,To,_o,ko,$t,Dt=E(()=>{"use strict";bo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},To=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},_o=null,ko=null;$t="__concurrencyLease"});async function F(n){let e=await n.text();return Hc(e,n.status)}function Hc(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function bs(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function tt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let i=0;i<8;i++){let{value:a,done:l}=await o.read();if(l||(a&&(s+=r.decode(a,{stream:!0})),tt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:tt(s)}}async function fe(n){try{let e=await n.text();if(tt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=E(()=>{"use strict"});var Ae,Co=E(()=>{"use strict";V();Ae=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 pe(e);if(o?.isSSE&&o.body){let r=new Response(o.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(r)}if(o?.body)e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(o===null){let r=await fe(e);if(r.isSSE)return this.transformResponseOut(r.response);e=r.response}}if(t.includes("application/json")){let o=await F(e);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,p="",m=!1,h=this,g=new ReadableStream({async start(f){let _=c.getReader(),k=-1,y="",b=T=>(T!==y&&(k++,y=T),k);try{for(;;){let{done:T,value:C}=await _.read();if(T){m||f.enqueue(d.encode(`data: [DONE]
|
|
5
5
|
|
|
6
6
|
`));break}let v=u.decode(C,{stream:!0});p+=v;let S=p.split(/\r?\n/);p=S.pop()||"";for(let x of S)if(x.trim())try{if(x.startsWith("event: "))continue;if(x.startsWith("data: ")){let w=x.slice(5).trim();if(w==="[DONE]"){m=!0,f.enqueue(d.encode(`data: [DONE]
|
|
7
7
|
|
|
@@ -39,7 +39,7 @@ data: ${JSON.stringify($)}
|
|
|
39
39
|
`),x=(M,$=[])=>({id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:M,model:s,output:$,usage:this.buildResponsesUsage()}),w=()=>{k||(k=!0,P.enqueue(S("response.created",{type:"response.created",response:x("in_progress")})),P.enqueue(S("response.in_progress",{type:"response.in_progress",response:x("in_progress")})))},R=(M,$)=>{P.enqueue(S("response.output_item.done",{type:"response.output_item.done",output_index:M,item:{...$,status:"completed"}}))},O=M=>{if(!T){if(T=!0,y){let $=v.find(L=>L.type==="message");$&&($.content=[{type:"output_text",text:a}],$.status="completed")}for(let $ of v)$.type==="function_call"&&($.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:M?{...this.buildResponsesUsage(M)}:this.buildResponsesUsage()}})}},P;return new ReadableStream({async start(M){P=M;try{let $=e.getReader(),L="";for(;;){let{done:N,value:D}=await $.read();if(N)break;L+=o.decode(D,{stream:!0});let W=L.split(`
|
|
40
40
|
`);L=W.pop()||"";for(let Te of W){let j=Te.trim();if(!j||j.startsWith("event:")||!j.startsWith("data:"))continue;let Y=j.slice(5).trim();if(Y==="[DONE]")continue;let z;try{z=JSON.parse(Y)}catch{continue}if(z.type==="message_start"&&(i=z.message?.id||i,w()),z.type==="content_block_start"){let A=z.content_block;if(C=A?.type||null,A?.type==="tool_use"){u=A.id||"",d=A.name||"",p="",m=_++;let B={id:u,type:"function_call",status:"in_progress",call_id:u,name:d,arguments:""};v.push(B),P.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:m,item:B}))}if(A?.type==="thinking"&&(h=A.thinking||"",!b)){b=!0,f=_++,g=`rs_${i}`;let B={id:g,type:"reasoning",status:"in_progress",summary:[]};v.push(B),P.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:f,item:B}))}if(A?.type==="text"&&(a=A?.text||"",!y)){y=!0,c=_++,l=`${i}_msg`;let B={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(B),P.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:c,item:B}))}}if(z.type==="content_block_delta"){let A=z.delta;if(A?.type==="text_delta"){if(!y){y=!0,c=_++,l=`${i}_msg`;let B={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(B),P.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:c,item:B}))}a+=A.text||"",P.enqueue(S("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:A.text||""}))}A?.type==="thinking_delta"&&(h+=A.thinking||"",P.enqueue(S("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:g||`rs_${i}`,output_index:f>=0?f:0,summary_index:0,delta:A.thinking||""}))),A?.type==="input_json_delta"&&(p+=A.partial_json||"",P.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:A.partial_json||""})))}if(z.type==="content_block_stop"){if(C==="tool_use"&&u){P.enqueue(S("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:m,arguments:p}));let A=v.find(B=>B.call_id===u);A&&(A.arguments=p,A.status="completed"),A&&R(m,A)}if(C==="text"&&y){P.enqueue(S("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:c,content_index:0,text:a}));let A=v.find(B=>B.type==="message");A&&(A.content=[{type:"output_text",text:a}],R(c,A))}if(C==="thinking"&&b){let A=v.find(B=>B.type==="reasoning");A&&(A.summary=[{type:"summary_text",text:h}],R(f,A))}C=null}if(z.type==="message_delta"){let A=O(z.usage);A&&P.enqueue(A)}if(z.type==="message_stop"){let A=O();A&&P.enqueue(A),P.enqueue(r.encode(`data: [DONE]
|
|
41
41
|
|
|
42
|
-
`))}}}w();let H=O();H&&P.enqueue(H),L="",P.close()}catch($){P.error($)}}})}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,a=null;if(t&&t.reasoning&&(a={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 p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&u.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&u.push(p)}}),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:a,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 So,X,Ft=E(()=>{"use strict";So=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)}},X=new So(100)});import{existsSync as Cs,mkdirSync as zc,readFileSync as Bc,writeFileSync as Jc}from"fs";import{join as Ss}from"path";import{HOME_DIR as Wc}from"@wengine-ai/claude-code-router-shared";function Eo(n,e){n&&Ie.set(n,{...e,provider:n,capturedAt:Date.now()})}function Ut(n){let e=Ie.get(n);return e?{...e}:void 0}function Po(){return Array.from(Ie.values()).map(n=>({...n}))}function Kc(){try{if(!Cs(wo))return;let n=JSON.parse(Bc(wo,"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;Ie.set(t.provider,t)}}catch{}}function xs(){try{if(Ie.size===0)return;Cs(Ro)||zc(Ro,{recursive:!0}),Jc(wo,JSON.stringify(Array.from(Ie.values()),null,2),"utf-8")}catch{}}function nt(){Ts||(Ts=!0,Kc(),vs=setInterval(xs,6e4),vs.unref?.(),process.on("exit",xs))}var Ro,wo,Ie,Ts,vs,Me=E(()=>{"use strict";Ro=Ss(Wc,"runtime"),wo=Ss(Ro,"quota-store.json"),Ie=new Map,Ts=!1,vs=null});function me(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Gc.test(e)))return e}function ge(n){if(!n)return;if(typeof n=="object")return me(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=me(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return me(e.slice(o+t.length))}var Gc,Ne=E(()=>{"use strict";Gc=/^[A-Za-z0-9_-]+$/});import{existsSync as Es}from"fs";import{readFile as Vc,readdir as Qc}from"fs/promises";import{homedir as Yc}from"os";import{isAbsolute as Xc,join as ot,normalize as Zc}from"path";import qc from"better-sqlite3";function al(){if($e.size<=Rs)return;let n=[...$e.keys()].slice(0,$e.size-Rs);for(let e of n)$e.delete(e)}function cl(){if(Le.size<=ws)return;let n=[...Le].slice(0,Le.size-ws);for(let e of n)Le.delete(e)}function ll(n){let e=n.trim();if(!e||e==="."||e===".."||/[/\\\0]/.test(e))return[];let t=e.replace(/^sess_/,"");return[...new Set([e,t,`sess_${t}`])].filter(Boolean)}function ul(n,e){let t;try{t=new qc(n,{readonly:!0,fileMustExist:!0});let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let i=o.get(r,r)?.workspace_path;if(typeof i=="string"&&i.trim())return i.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function dl(n,e){let t;try{t=await Qc(n)}catch{return null}for(let o of t)for(let r of e){let s=ot(n,o,`${r}.json`);if(Es(s))try{let i=JSON.parse(await Vc(s,"utf8")),a=i?.meta?.workspacePath??i?.workspacePath;if(typeof a=="string"&&a.trim())return a.trim()}catch{}}return null}async function Ps(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=$e.get(e);if(t)return t;let o=async()=>{let r=ll(e);if(r.length===0)return null;let s=ot(el(),tl),i=ot(s,nl);if(Es(i)){let a=ul(i,r);if(a)return a}return dl(ot(s,ol),r)};try{let r=await o();if(!r&&!Le.has(e)){Le.add(e),cl();for(let i=0;i<rl&&!r;i++)await il(sl),r=await o()}if(!r||!Xc(r))return null;let s=Zc(r);return $e.set(e,s),al(),s}catch{return null}}var el,tl,nl,ol,Rs,ws,rl,sl,$e,Le,il,Os=E(()=>{"use strict";el=()=>process.env.CCR_ZCODE_DIR||ot(Yc(),".zcode"),tl="v2",nl="tasks-index.sqlite",ol="sessions",Rs=500,ws=500,rl=3,sl=50,$e=new Map,Le=new Set,il=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as pl}from"node:crypto";import{CCR_PROJECT_HEADER as Oo}from"@wengine-ai/claude-code-router-shared";function Ms(n){return typeof n=="string"&&n.length<=fl}function ml(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Is){let{value:t}=jt(n,e);if(!Ms(t))continue;let o=me(t);if(o)return o}}function hl(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 yl(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 jt(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function As(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function rt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Ao(n,e,t=!0){let o=ge(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function $s(n){return typeof n=="string"&&gl.includes(n)}function Rl(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function De(n){if($s(n?.clientType))return n.clientType;let e=yl(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=hl(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";if(jt(n,Oo).present||jt(n,"x-session-affinity").present)return"pi";if(Rl(t,o))return"zcode";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 a=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(a)?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(a).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Ls(n){return Ns[n]}function wl(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||pl();return n.__ccrRequestScopeId=e,e}function xe(n,e={}){let t=De(n),o=Ls(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:wl(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,As(n,Oo),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let i of Is)As(n,i);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function El(){}var Is,fl,gl,_l,kl,bl,Tl,vl,xl,Cl,Sl,Ns,Fe=E(()=>{"use strict";Ne();Is=["x-session-affinity","x-session-id","x-litellm-session-id"],fl=256;gl=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];_l={type:"claude-code",createContext(n){return Ao(n,"claude-code")}},kl={type:"zcode",createContext(n){return Ao(n,"zcode")}},bl={type:"pi",createContext(n){let e=jt(n,Oo),t=ml(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||ge(n?.body?.metadata?.user_id),o=Ms(t)?t:void 0;return{...rt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Tl={type:"qwen-code",createContext(n){return Ao(n,"qwen-code")}},vl={type:"opencode",createContext(){return rt("opencode")}},xl={type:"codex",createContext(){return rt("codex")}},Cl={type:"api",createContext(){return rt("api")}},Sl={type:"unknown",createContext(){return rt("unknown")}},Ns={"claude-code":_l,zcode:kl,pi:bl,"qwen-code":Tl,opencode:vl,codex:xl,api:Cl,unknown:Sl}});import{get_encoding as Ol}from"tiktoken";import{readFile as Io}from"fs/promises";import{opendir as Al,stat as Il}from"fs/promises";import{join as Mo}from"path";import{CLAUDE_PROJECTS_DIR as Ds,HOME_DIR as Fs,getClaudeProjectId as Us,isZcodeProjectTakeoverActive as Ml}from"@wengine-ai/claude-code-router-shared";function Z(n,e,t,o){let r=Js(e,t);if(r.code==="model_unhealthy"){let a=K(e,t,!0);if(a)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),a}let s=n.sessionId||n.clientContext?.stableSessionId,i=Bs[r.code]||502;throw new q(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:i})}function zt(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 it(n){let e=zt(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 $l(n,e){if(!e||!n)return null;let t=zt(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=it(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let i=zt(r);if(i&&t.includes(i))return s}return null}function Ll(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function Ht(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 st(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 Js(n,e){let t=Ht(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 l=Ut(s.name);if(l){let c=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,u=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.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 K(n,e,t,o,r,s,i){let a=Ht(n);if(!a)return i?null:n;let{providerName:l,routeModel:c}=a,u=st(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let p=Ee(),m=p.getPromotion(l,c,o,e);if(m){let h=Ht(m);if(h){let g=st(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let p=Ee(),m=p.getPromotion(l,c,o,e);if(m){let h=Ht(m);if(h){let g=st(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}if(!t&&!U().isAvailable(u.provider.name,u.model))return null;let d=Ut(u.provider.name);if(d){let p=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(p||m)return null}return`${u.provider.name},${u.model}`}function Q(n,e,t,o,r,s){let i=U(),a=[t?.[n],o?.[n]];for(let l of a)if(!(!Array.isArray(l)||l.length===0))for(let c of l){let u=K(c,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Dl(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 No(n){let e=zt(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 Ws(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Ll(e))}function Ks(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Fl(n,e,t,o,r,s,i,a,l,c,u,d){let p=n.clientContext,m=p?.longContextThreshold??t.longContextThreshold??l??6e4,h=Ws(e,r,p),g=n.modelFamily,f=Ks(p,t,c),_=p?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||h>f)&&t.extendedContext){let b=K(t.extendedContext,o,!1,"extendedContext",a,d,u);if(b)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:b,scenarioType:"extendedContext",isFallback:!1};let T=a?Q("extendedContext",o,t.fallback,i,g,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let C=Z(n,t.extendedContext,o,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(h>m&&(t.longContext||t.fallback?.longContext?.length||i?.longContext?.length)){let b=t.longContext?K(t.longContext,o,!1,"longContext",a,d,u):null;if(b)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:b,scenarioType:"longContext",isFallback:!1};let T=a?Q("longContext",o,t.fallback,i,g,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let C=Z(n,t.longContext,o,"longContext");if(C)return{model:C,scenarioType:"longContext",isFallback:!1}}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=K(t.webSearch,o,!1,"webSearch",a,d,u);if(b)return{model:b,scenarioType:"webSearch",isFallback:!1};let T=a?Q("webSearch",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let C=Z(n,t.webSearch,o,"webSearch");if(C)return{model:C,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let b=K(t.think,o,!1,"think",a,d,u);if(b)return{model:b,scenarioType:"think",isFallback:!1};let T=a?Q("think",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let C=Z(n,t.think,o,"think");if(C)return{model:C,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let b=K(t.default,o,!1,"default",a,d,u);if(b)return{model:b,scenarioType:"default",isFallback:!1};let T=a?Q("default",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let C=Z(n,t.default,o,"default");if(C)return{model:C,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function Bl(){if(Ce.size<=js)return;let n=[...Ce.keys()].slice(0,Ce.size-js);for(let e of n)Ce.delete(e)}function Jl(){if(Ue.size<=Hs)return;let n=[...Ue].slice(0,Ue.size-Hs);for(let e of n)Ue.delete(e)}var Bs,q,le,Bt,Nl,Ul,Jt,Ce,js,Ue,Hs,jl,Hl,zl,zs,Gs,je=E(()=>{"use strict";Ft();re();Me();Mt();Dt();Ne();Os();Fe();Bs={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,invalid_project_id:400,project_config_not_found:404},q=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Bs[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Ol("cl100k_base"),Bt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{s.type==="text"?o+=le.encode(s.text).length:s.type==="tool_use"?o+=le.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(o+=le.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},Nl=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new q(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Gs(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Ps(n.sessionId);s&&Ml(s)&&(r=Us(s))}if(r){n.projectId=r;let s=Mo(Fs,r,"config.json");if(!t&&n.sessionId){let i=Mo(Fs,r,`${n.sessionId}.json`);try{let a=JSON.parse(await Io(i,"utf8"));if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch{}}try{let i=JSON.parse(await Io(s,"utf8"));if(t&&(typeof i?.projectPath!="string"||Us(i.projectPath)!==o))throw new q(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){if(i instanceof q)throw i;if(t&&i?.code==="ENOENT")throw new q(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!i||i.code!=="ENOENT"){let a=n.sessionId||n.clientContext?.stableSessionId;throw new q(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${i.message}. Session: "${a||"unknown"}".`,{sessionId:a,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};Ul=async(n,e,t,o,r,s)=>{let i=t.get("providers")||[],a=r||t.get("Router"),l=a?.enableFallback===!0,c=l?a?.fallback:void 0,u=l&&!s?c||t.get("fallback"):c,d=!s,p=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>`,""),p=v[1])}let{family:m,extended:h,isCcrAlias:g}=it(n.body.model),f=a?.families?.[m||""];if(f&&a?.enableFamilyRouting){n.log.info(`Using model family routing for: ${m}${h?" (1M)":""}`),n.modelFamily=m,n.familyFallback=f.fallback;let v=Fl(n,e,f,i,o,h,u,l,a?.longContextThreshold,a?.extendedContextThreshold,s,d);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=K(n.body.model,i,!1,"default",l,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let S=l?Q("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 _=g&&!a?.enableFamilyRouting?null:$l(n.body.model,a?.models);if(_){let v=K(_,i,!1,"modelMapping",l,d,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${_}`),{model:v,scenarioType:"modelMapping"};let S=l?Q("modelMapping",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};if(s){let x=Z(n,_,i,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let k=n.clientContext,y=Ws(e,o,k),b=Ks(k,void 0,a?.extendedContextThreshold);if(y>b&&a?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${y}, estimated: ${e}, threshold: ${b}`);let v=K(a.extendedContext,i,!1,"extendedContext",l,d,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let S=l?Q("extendedContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};if(s){let x=Z(n,a.extendedContext,i,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext"}}}let T=k?.longContextThreshold??a?.longContextThreshold??6e4;if(y>T&&a?.longContext){n.log.info(`Using long context model due to token count: ${y}, estimated: ${e}, threshold: ${T}`);let v=K(a.longContext,i,!1,"longContext",l,d,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let S=l?Q("longContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};if(s){let x=Z(n,a.longContext,i,"longContext");if(x)return{model:x,scenarioType:"longContext"}}}if(!s&&p)return n.subagentOverrideModel=p,{model:p,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&a?.background){n.log.info(`Using background model for ${n.body.model}`);let v=K(a.background,i,!1,"background",l,d,s);if(v)return{model:v,scenarioType:"background"};let S=l?Q("background",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};if(s){let x=Z(n,a.background,i,"background");if(x)return{model:x,scenarioType:"background"}}n.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&a?.webSearch){let v=K(a.webSearch,i,!1,"webSearch",l,d,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let S=l?Q("webSearch",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};if(s){let x=Z(n,a.webSearch,i,"webSearch");if(x)return{model:x,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&a?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=K(a.think,i,!1,"think",l,d,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let S=l?Q("think",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};if(s){let x=Z(n,a.think,i,"think");if(x)return{model:x,scenarioType:"think"}}}if(a?.default){let v=K(a.default,i,!1,"default",l,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let S=l?Q("default",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};let x=K(a.default,i,!0,"default",l,d,s);if(x)return n.log.warn(`No fallback available; retrying default model ${a.default} despite fail-pool state (strict=${s})`),{model:x,scenarioType:"default"}}if(s){let v=Z(n,a?.default||n.body.model,i,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Jt=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,o.getAll());let s=await Nl(n,o),i=s||o.get("Router"),a=i?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=a,n.strictProjectRouting=c,n.fallbackConfig=c?i?.fallback:i?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??X.get(n.usageCacheKey):void 0,{messages:d,system:p=[],tools:m}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&p.length>1&&p[1]?.text?.includes("<env>")){let g=await Io(h,"utf-8");p[1].text=`${g}<env>${p[1].text.split("<env>").pop()}`}try{let[g,f]=n.body.model.split(","),_=t.tokenizerService?.getTokenizerConfigForModel(g,f),k;t.tokenizerService?k=(await t.tokenizerService.countTokens({messages:d,system:p,tools:m},_,g)).tokenCount:k=Bt(d,p,m),n.tokenCount=k;let y,b=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(b)try{y=await Xe(b)(n,o.getAll(),{event:r})}catch(S){n.log.error(`failed to load custom router: ${S.message}`)}if(y)n.scenarioType="default";else{let S=await Ul(n,k,o,u,s,!!s);y=S.model,n.scenarioType=S.scenarioType}let{family:T}=it(n.originalModel||n.body.model),C=i?.enableFamilyRouting&&T?i.families?.[T]:void 0,v=[C?.image,i?.image].filter((S,x,w)=>!!S&&w.indexOf(S)===x);if(v.length>0&&Dl(n)&&!No(y))if(v.includes(y))n.scenarioType="image";else{let S=v.map(x=>K(x,l,!1,"image",a,!c,c)).find(x=>!!x);if(S)n.log.info(`Using image model fallback for ${y}`),y=S,n.scenarioType="image";else{let x=a?Q("image",l,C?.fallback,n.fallbackConfig,T||void 0,c):null;if(x)n.log.info(`Using image fallback model: ${x}`),y=x,n.scenarioType="image";else if(c){let w=Z(n,v[0],l,"image");w&&(y=w,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${y}`),n.scenarioType="image"}}if(i?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof y=="string"&&y.trim()){let S=n.scenarioType||"default",x=[...(n.familyFallback||{})[S]||[],...(n.fallbackConfig||{})[S]||[]];y=ks(n,y,{threshold:Number(i?.concurrencyThreshold)||3,fallbackModels:x,resolve:w=>K(w,l,!1,S,a,!c,c),log:w=>n.log.info(w)})}typeof y=="string"&&y.trim()?n.body.model=y:(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(g){if(g instanceof q)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),c){let f=n.sessionId||n.clientContext?.stableSessionId;throw new q(`Project routing error: router failure in project mode. ${g.message}. Session: "${f||"unknown"}".`,{sessionId:f,configuredTarget:i?.default,code:"project_router_failure",statusCode:502})}n.body.model=i?.default,n.scenarioType="default"}},Ce=new Map,js=1e3,Ue=new Set,Hs=1e3,jl=3,Hl=50,zl=n=>new Promise(e=>setTimeout(e,n));zs=async n=>{let e=await Al(Ds),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let i=Mo(Ds,s,`${n}.jsonl`);try{return(await Il(i)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Gs=async n=>{let e=me(n);if(!e)return null;if(Ce.has(e))return Ce.get(e)||null;try{let t=await zs(e);if(!t&&!Ue.has(e)){Ue.add(e),Jl();for(let o=0;o<jl&&!t;o++)await zl(Hl),t=await zs(e)}return t?(Ce.set(e,t),Bl(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function at(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
|
+
`))}}}w();let H=O();H&&P.enqueue(H),L="",P.close()}catch($){P.error($)}}})}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,a=null;if(t&&t.reasoning&&(a={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 p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&u.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&u.push(p)}}),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:a,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 So,X,Ft=E(()=>{"use strict";So=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)}},X=new So(100)});import{existsSync as Cs,mkdirSync as zc,readFileSync as Bc,writeFileSync as Jc}from"fs";import{join as Ss}from"path";import{HOME_DIR as Wc}from"@wengine-ai/claude-code-router-shared";function Eo(n,e){n&&Ie.set(n,{...e,provider:n,capturedAt:Date.now()})}function Ut(n){let e=Ie.get(n);return e?{...e}:void 0}function Po(){return Array.from(Ie.values()).map(n=>({...n}))}function Kc(){try{if(!Cs(wo))return;let n=JSON.parse(Bc(wo,"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;Ie.set(t.provider,t)}}catch{}}function xs(){try{if(Ie.size===0)return;Cs(Ro)||zc(Ro,{recursive:!0}),Jc(wo,JSON.stringify(Array.from(Ie.values()),null,2),"utf-8")}catch{}}function nt(){Ts||(Ts=!0,Kc(),vs=setInterval(xs,6e4),vs.unref?.(),process.on("exit",xs))}var Ro,wo,Ie,Ts,vs,Me=E(()=>{"use strict";Ro=Ss(Wc,"runtime"),wo=Ss(Ro,"quota-store.json"),Ie=new Map,Ts=!1,vs=null});function me(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Gc.test(e)))return e}function ge(n){if(!n)return;if(typeof n=="object")return me(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=me(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return me(e.slice(o+t.length))}var Gc,Ne=E(()=>{"use strict";Gc=/^[A-Za-z0-9_-]+$/});import{existsSync as Es}from"fs";import{readFile as Vc,readdir as Qc}from"fs/promises";import{homedir as Yc}from"os";import{isAbsolute as Xc,join as ot,normalize as Zc}from"path";import{openSqliteDatabase as qc}from"@wengine-ai/claude-code-router-shared";function al(){if($e.size<=Rs)return;let n=[...$e.keys()].slice(0,$e.size-Rs);for(let e of n)$e.delete(e)}function cl(){if(Le.size<=ws)return;let n=[...Le].slice(0,Le.size-ws);for(let e of n)Le.delete(e)}function ll(n){let e=n.trim();if(!e||e==="."||e===".."||/[/\\\0]/.test(e))return[];let t=e.replace(/^sess_/,"");return[...new Set([e,t,`sess_${t}`])].filter(Boolean)}function ul(n,e){let t;try{t=qc(n,{readonly:!0}).db;let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let i=o.get(r,r)?.workspace_path;if(typeof i=="string"&&i.trim())return i.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function dl(n,e){let t;try{t=await Qc(n)}catch{return null}for(let o of t)for(let r of e){let s=ot(n,o,`${r}.json`);if(Es(s))try{let i=JSON.parse(await Vc(s,"utf8")),a=i?.meta?.workspacePath??i?.workspacePath;if(typeof a=="string"&&a.trim())return a.trim()}catch{}}return null}async function Ps(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=$e.get(e);if(t)return t;let o=async()=>{let r=ll(e);if(r.length===0)return null;let s=ot(el(),tl),i=ot(s,nl);if(Es(i)){let a=ul(i,r);if(a)return a}return dl(ot(s,ol),r)};try{let r=await o();if(!r&&!Le.has(e)){Le.add(e),cl();for(let i=0;i<rl&&!r;i++)await il(sl),r=await o()}if(!r||!Xc(r))return null;let s=Zc(r);return $e.set(e,s),al(),s}catch{return null}}var el,tl,nl,ol,Rs,ws,rl,sl,$e,Le,il,Os=E(()=>{"use strict";el=()=>process.env.CCR_ZCODE_DIR||ot(Yc(),".zcode"),tl="v2",nl="tasks-index.sqlite",ol="sessions",Rs=500,ws=500,rl=3,sl=50,$e=new Map,Le=new Set,il=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as pl}from"node:crypto";import{CCR_PROJECT_HEADER as Oo}from"@wengine-ai/claude-code-router-shared";function Ms(n){return typeof n=="string"&&n.length<=fl}function ml(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Is){let{value:t}=jt(n,e);if(!Ms(t))continue;let o=me(t);if(o)return o}}function hl(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 yl(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 jt(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function As(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function rt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Ao(n,e,t=!0){let o=ge(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function $s(n){return typeof n=="string"&&gl.includes(n)}function Rl(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function De(n){if($s(n?.clientType))return n.clientType;let e=yl(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=hl(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";if(jt(n,Oo).present||jt(n,"x-session-affinity").present)return"pi";if(Rl(t,o))return"zcode";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 a=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(a)?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(a).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Ls(n){return Ns[n]}function wl(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||pl();return n.__ccrRequestScopeId=e,e}function xe(n,e={}){let t=De(n),o=Ls(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:wl(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,As(n,Oo),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let i of Is)As(n,i);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function El(){}var Is,fl,gl,_l,kl,bl,Tl,vl,xl,Cl,Sl,Ns,Fe=E(()=>{"use strict";Ne();Is=["x-session-affinity","x-session-id","x-litellm-session-id"],fl=256;gl=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];_l={type:"claude-code",createContext(n){return Ao(n,"claude-code")}},kl={type:"zcode",createContext(n){return Ao(n,"zcode")}},bl={type:"pi",createContext(n){let e=jt(n,Oo),t=ml(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||ge(n?.body?.metadata?.user_id),o=Ms(t)?t:void 0;return{...rt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Tl={type:"qwen-code",createContext(n){return Ao(n,"qwen-code")}},vl={type:"opencode",createContext(){return rt("opencode")}},xl={type:"codex",createContext(){return rt("codex")}},Cl={type:"api",createContext(){return rt("api")}},Sl={type:"unknown",createContext(){return rt("unknown")}},Ns={"claude-code":_l,zcode:kl,pi:bl,"qwen-code":Tl,opencode:vl,codex:xl,api:Cl,unknown:Sl}});import{get_encoding as Ol}from"tiktoken";import{readFile as Io}from"fs/promises";import{opendir as Al,stat as Il}from"fs/promises";import{join as Mo}from"path";import{CLAUDE_PROJECTS_DIR as Ds,HOME_DIR as Fs,getClaudeProjectId as Us,isZcodeProjectTakeoverActive as Ml}from"@wengine-ai/claude-code-router-shared";function Z(n,e,t,o){let r=Js(e,t);if(r.code==="model_unhealthy"){let a=K(e,t,!0);if(a)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),a}let s=n.sessionId||n.clientContext?.stableSessionId,i=Bs[r.code]||502;throw new q(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:i})}function zt(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 it(n){let e=zt(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 $l(n,e){if(!e||!n)return null;let t=zt(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=it(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let i=zt(r);if(i&&t.includes(i))return s}return null}function Ll(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function Ht(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 st(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 Js(n,e){let t=Ht(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 l=Ut(s.name);if(l){let c=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,u=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.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 K(n,e,t,o,r,s,i){let a=Ht(n);if(!a)return i?null:n;let{providerName:l,routeModel:c}=a,u=st(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let p=Ee(),m=p.getPromotion(l,c,o,e);if(m){let h=Ht(m);if(h){let g=st(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let p=Ee(),m=p.getPromotion(l,c,o,e);if(m){let h=Ht(m);if(h){let g=st(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}if(!t&&!U().isAvailable(u.provider.name,u.model))return null;let d=Ut(u.provider.name);if(d){let p=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(p||m)return null}return`${u.provider.name},${u.model}`}function Q(n,e,t,o,r,s){let i=U(),a=[t?.[n],o?.[n]];for(let l of a)if(!(!Array.isArray(l)||l.length===0))for(let c of l){let u=K(c,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Dl(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 No(n){let e=zt(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 Ws(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Ll(e))}function Ks(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Fl(n,e,t,o,r,s,i,a,l,c,u,d){let p=n.clientContext,m=p?.longContextThreshold??t.longContextThreshold??l??6e4,h=Ws(e,r,p),g=n.modelFamily,f=Ks(p,t,c),_=p?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||h>f)&&t.extendedContext){let b=K(t.extendedContext,o,!1,"extendedContext",a,d,u);if(b)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:b,scenarioType:"extendedContext",isFallback:!1};let T=a?Q("extendedContext",o,t.fallback,i,g,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let C=Z(n,t.extendedContext,o,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(h>m&&(t.longContext||t.fallback?.longContext?.length||i?.longContext?.length)){let b=t.longContext?K(t.longContext,o,!1,"longContext",a,d,u):null;if(b)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:b,scenarioType:"longContext",isFallback:!1};let T=a?Q("longContext",o,t.fallback,i,g,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let C=Z(n,t.longContext,o,"longContext");if(C)return{model:C,scenarioType:"longContext",isFallback:!1}}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=K(t.webSearch,o,!1,"webSearch",a,d,u);if(b)return{model:b,scenarioType:"webSearch",isFallback:!1};let T=a?Q("webSearch",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let C=Z(n,t.webSearch,o,"webSearch");if(C)return{model:C,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let b=K(t.think,o,!1,"think",a,d,u);if(b)return{model:b,scenarioType:"think",isFallback:!1};let T=a?Q("think",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let C=Z(n,t.think,o,"think");if(C)return{model:C,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let b=K(t.default,o,!1,"default",a,d,u);if(b)return{model:b,scenarioType:"default",isFallback:!1};let T=a?Q("default",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let C=Z(n,t.default,o,"default");if(C)return{model:C,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function Bl(){if(Ce.size<=js)return;let n=[...Ce.keys()].slice(0,Ce.size-js);for(let e of n)Ce.delete(e)}function Jl(){if(Ue.size<=Hs)return;let n=[...Ue].slice(0,Ue.size-Hs);for(let e of n)Ue.delete(e)}var Bs,q,le,Bt,Nl,Ul,Jt,Ce,js,Ue,Hs,jl,Hl,zl,zs,Gs,je=E(()=>{"use strict";Ft();re();Me();Mt();Dt();Ne();Os();Fe();Bs={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,invalid_project_id:400,project_config_not_found:404},q=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Bs[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Ol("cl100k_base"),Bt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{s.type==="text"?o+=le.encode(s.text).length:s.type==="tool_use"?o+=le.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(o+=le.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},Nl=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new q(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Gs(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Ps(n.sessionId);s&&Ml(s)&&(r=Us(s))}if(r){n.projectId=r;let s=Mo(Fs,r,"config.json");if(!t&&n.sessionId){let i=Mo(Fs,r,`${n.sessionId}.json`);try{let a=JSON.parse(await Io(i,"utf8"));if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch{}}try{let i=JSON.parse(await Io(s,"utf8"));if(t&&(typeof i?.projectPath!="string"||Us(i.projectPath)!==o))throw new q(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){if(i instanceof q)throw i;if(t&&i?.code==="ENOENT")throw new q(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!i||i.code!=="ENOENT"){let a=n.sessionId||n.clientContext?.stableSessionId;throw new q(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${i.message}. Session: "${a||"unknown"}".`,{sessionId:a,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};Ul=async(n,e,t,o,r,s)=>{let i=t.get("providers")||[],a=r||t.get("Router"),l=a?.enableFallback===!0,c=l?a?.fallback:void 0,u=l&&!s?c||t.get("fallback"):c,d=!s,p=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>`,""),p=v[1])}let{family:m,extended:h,isCcrAlias:g}=it(n.body.model),f=a?.families?.[m||""];if(f&&a?.enableFamilyRouting){n.log.info(`Using model family routing for: ${m}${h?" (1M)":""}`),n.modelFamily=m,n.familyFallback=f.fallback;let v=Fl(n,e,f,i,o,h,u,l,a?.longContextThreshold,a?.extendedContextThreshold,s,d);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=K(n.body.model,i,!1,"default",l,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let S=l?Q("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 _=g&&!a?.enableFamilyRouting?null:$l(n.body.model,a?.models);if(_){let v=K(_,i,!1,"modelMapping",l,d,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${_}`),{model:v,scenarioType:"modelMapping"};let S=l?Q("modelMapping",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};if(s){let x=Z(n,_,i,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let k=n.clientContext,y=Ws(e,o,k),b=Ks(k,void 0,a?.extendedContextThreshold);if(y>b&&a?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${y}, estimated: ${e}, threshold: ${b}`);let v=K(a.extendedContext,i,!1,"extendedContext",l,d,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let S=l?Q("extendedContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};if(s){let x=Z(n,a.extendedContext,i,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext"}}}let T=k?.longContextThreshold??a?.longContextThreshold??6e4;if(y>T&&a?.longContext){n.log.info(`Using long context model due to token count: ${y}, estimated: ${e}, threshold: ${T}`);let v=K(a.longContext,i,!1,"longContext",l,d,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let S=l?Q("longContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};if(s){let x=Z(n,a.longContext,i,"longContext");if(x)return{model:x,scenarioType:"longContext"}}}if(!s&&p)return n.subagentOverrideModel=p,{model:p,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&a?.background){n.log.info(`Using background model for ${n.body.model}`);let v=K(a.background,i,!1,"background",l,d,s);if(v)return{model:v,scenarioType:"background"};let S=l?Q("background",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};if(s){let x=Z(n,a.background,i,"background");if(x)return{model:x,scenarioType:"background"}}n.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&a?.webSearch){let v=K(a.webSearch,i,!1,"webSearch",l,d,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let S=l?Q("webSearch",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};if(s){let x=Z(n,a.webSearch,i,"webSearch");if(x)return{model:x,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&a?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=K(a.think,i,!1,"think",l,d,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let S=l?Q("think",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};if(s){let x=Z(n,a.think,i,"think");if(x)return{model:x,scenarioType:"think"}}}if(a?.default){let v=K(a.default,i,!1,"default",l,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let S=l?Q("default",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};let x=K(a.default,i,!0,"default",l,d,s);if(x)return n.log.warn(`No fallback available; retrying default model ${a.default} despite fail-pool state (strict=${s})`),{model:x,scenarioType:"default"}}if(s){let v=Z(n,a?.default||n.body.model,i,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Jt=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,o.getAll());let s=await Nl(n,o),i=s||o.get("Router"),a=i?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=a,n.strictProjectRouting=c,n.fallbackConfig=c?i?.fallback:i?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??X.get(n.usageCacheKey):void 0,{messages:d,system:p=[],tools:m}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&p.length>1&&p[1]?.text?.includes("<env>")){let g=await Io(h,"utf-8");p[1].text=`${g}<env>${p[1].text.split("<env>").pop()}`}try{let[g,f]=n.body.model.split(","),_=t.tokenizerService?.getTokenizerConfigForModel(g,f),k;t.tokenizerService?k=(await t.tokenizerService.countTokens({messages:d,system:p,tools:m},_,g)).tokenCount:k=Bt(d,p,m),n.tokenCount=k;let y,b=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(b)try{y=await Xe(b)(n,o.getAll(),{event:r})}catch(S){n.log.error(`failed to load custom router: ${S.message}`)}if(y)n.scenarioType="default";else{let S=await Ul(n,k,o,u,s,!!s);y=S.model,n.scenarioType=S.scenarioType}let{family:T}=it(n.originalModel||n.body.model),C=i?.enableFamilyRouting&&T?i.families?.[T]:void 0,v=[C?.image,i?.image].filter((S,x,w)=>!!S&&w.indexOf(S)===x);if(v.length>0&&Dl(n)&&!No(y))if(v.includes(y))n.scenarioType="image";else{let S=v.map(x=>K(x,l,!1,"image",a,!c,c)).find(x=>!!x);if(S)n.log.info(`Using image model fallback for ${y}`),y=S,n.scenarioType="image";else{let x=a?Q("image",l,C?.fallback,n.fallbackConfig,T||void 0,c):null;if(x)n.log.info(`Using image fallback model: ${x}`),y=x,n.scenarioType="image";else if(c){let w=Z(n,v[0],l,"image");w&&(y=w,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${y}`),n.scenarioType="image"}}if(i?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof y=="string"&&y.trim()){let S=n.scenarioType||"default",x=[...(n.familyFallback||{})[S]||[],...(n.fallbackConfig||{})[S]||[]];y=ks(n,y,{threshold:Number(i?.concurrencyThreshold)||3,fallbackModels:x,resolve:w=>K(w,l,!1,S,a,!c,c),log:w=>n.log.info(w)})}typeof y=="string"&&y.trim()?n.body.model=y:(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(g){if(g instanceof q)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),c){let f=n.sessionId||n.clientContext?.stableSessionId;throw new q(`Project routing error: router failure in project mode. ${g.message}. Session: "${f||"unknown"}".`,{sessionId:f,configuredTarget:i?.default,code:"project_router_failure",statusCode:502})}n.body.model=i?.default,n.scenarioType="default"}},Ce=new Map,js=1e3,Ue=new Set,Hs=1e3,jl=3,Hl=50,zl=n=>new Promise(e=>setTimeout(e,n));zs=async n=>{let e=await Al(Ds),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let i=Mo(Ds,s,`${n}.jsonl`);try{return(await Il(i)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Gs=async n=>{let e=me(n);if(!e)return null;if(Ce.has(e))return Ce.get(e)||null;try{let t=await zs(e);if(!t&&!Ue.has(e)){Ue.add(e),Jl();for(let o=0;o<jl&&!t;o++)await zl(Hl),t=await zs(e)}return t?(Ce.set(e,t),Bl(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function at(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(`
|
|
43
43
|
`):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
|
|
44
44
|
${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 Vs(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&at(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&Wl.test(r.model)&&await Jt(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,...p]=u.split(","),m=t.providerService.getProvider(d);m&&(i=m,r.model=p.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw J(`Provider '${s}' not found`,404,"provider_not_found");n.provider=i.name||s;let a=Ql(n),l=o.endPoint==="/v1/messages"&&a;a&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=l,n.codexDetected=a;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&at(r);let{requestBody:c,config:u,bypass:d}=await Ys(r,i,o,n.headers,{req:n});if(c?.messages&&!d&&!n.isTargetAnthropic){let g=c.messages,f=new Set,_=[],k=[];for(let y of g){if(y?.role!=="system"){k.push(y);continue}let b=JSON.stringify(y.content??"");f.has(b)||(f.add(b),_.push(y))}_.length>0&&k.length>0&&(c.messages=[..._,...k])}let p=await Xs(c,u,i,t,d,o,{req:n});try{i?.baseUrl&&p?.headers&&qe(s,i.baseUrl,p.headers)}catch{}let m=await Zs(c,p,i,o,d,{req:n,isCodexOnMessagesEndpoint:l});m=await Qs(r,m,i.name||s);let h=qs(m,e,r,t);try{let g=r.model||n.originalModel;s&&g&&U().recordSuccess(s,g)}catch{}return h}catch(c){if(c instanceof q)throw c;if(!n.__retryAttempted){n.__retryAttempted=!0;try{return await Vs(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let u=await Kl(n,e,t,o,c);if(u)return u;throw n.__fallbackExhausted=!0,c}}async function Qs(n,e,t){if(!n?.stream||!e?.body)return e;let o=e.body.getReader(),r=new TextDecoder,s=[],i="";for(let c=0;c<8;c++){let u=await o.read();if(u.done||(u.value&&(s.push(u.value),i+=r.decode(u.value,{stream:!0})),i.split(`
|
|
45
45
|
`).some(d=>d.startsWith("data:"))))break}if(i+=r.decode(),s.length===0)throw o.releaseLock(),J(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(i.includes("event: error")){o.releaseLock();let c=i.length<500?i:i.slice(0,500);throw J(`Provider ${t} returned error in SSE stream: ${c}`,400,"provider_response_error")}if(i.split(`
|
|
@@ -313,7 +313,7 @@ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.valu
|
|
|
313
313
|
${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
|
|
314
314
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
|
|
315
315
|
${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
316
|
-
`):`${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 pt,ur=E(()=>{"use strict";pt=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||{},a={data:e};return r&&(a.timestamp=new Date().toISOString()),s&&(a.prefix=s),i&&Object.keys(i).length>0&&(a.metadata=i),a}async sendRequest(e,t,o,r,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:i.signal});if(clearTimeout(a),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(a),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,i){let a=null;for(let l=1;l<=i.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(a=c,l===i.maxAttempts)break;let u=i.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${i.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw a}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}`)}}}});import{lstat as Mn,opendir as Ju,unlink as Wu}from"node:fs/promises";import{join as Zi,resolve as fr}from"node:path";import{tmpdir as Ku}from"node:os";async function Nn(n,e){let t=fr(n),o=In.get(t),r,s=new Promise(i=>{r=i});In.set(t,s);try{return await o,await e()}finally{r(),In.get(t)===s&&In.delete(t)}}function qi(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Xi(n,e){try{let t=await Mn(n);return t.isDirectory()&&!t.isSymbolicLink()&&qi(e,t)}catch{return!1}}function Xu(){return new Promise(n=>{setTimeout(n,10).unref()})}async function ea(n,e,t,o){let r=fr(n);if(o?.aborted||dr.has(r))return 0;dr.add(r);let s=0;try{let i=await Mn(r);if(!i.isDirectory()||i.isSymbolicLink()||o?.aborted)return 0;let a=await Ju(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of a){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let d=Zi(r,u.name);try{let p=await Mn(d);if(!p.isFile()||p.isSymbolicLink()||p.mtimeMs>=e)continue;await Nn(d,async()=>{if(o?.aborted||!await Xi(r,i))return!1;let h=await Mn(d);return!h.isFile()||h.isSymbolicLink()||!qi(p,h)||h.mtimeMs!==p.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await Wu(d),!0)})&&s++}catch{}}finally{++l%64===0&&(await Xu(),c=!o?.aborted&&await Xi(r,i))}}}finally{await a.close().catch(()=>{})}}catch{}finally{dr.delete(r)}return s}function ta(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,i=t?`.${t}`:"";return ea(n,Date.now()-o,a=>Yu.test(a)?!0:!a.endsWith(".tmp")&&a.startsWith(s)&&a.endsWith(i),r)}function Zu(n,e){let t=Date.now()-Gu;return ea(n,t,o=>{let r=Qu.exec(o);return r!==null&&Number(r[1])<t},e)}function mr(n,e,t){let o=pr.get(n);if(!o){let s=new AbortController,i,a=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(a(),i=setInterval(a,Vu),i.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),i&&clearInterval(i)}},pr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),pr.delete(n)))}}function na(n=Zi(Ku(),"claude-code-router")){return mr(`legacy:${fr(n)}`,e=>Zu(n,e),1e3)}var Gu,Vu,Qu,Yu,dr,In,pr,gr=E(()=>{"use strict";Gu=3600*1e3,Vu=600*1e3,Qu=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,Yu=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,dr=new Set,In=new Map,pr=new Map});import{lstat as qu,mkdir as ed,open as td,rename as nd,unlink as od}from"node:fs/promises";import{randomUUID as rd}from"node:crypto";import{sanitizeTempFileKey as sd}from"@wengine-ai/claude-code-router-shared";import{basename as id,join as hr,resolve as ad}from"node:path";import{tmpdir as cd}from"node:os";var ft,yr=E(()=>{"use strict";gr();ft=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=ad(hr(cd(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=mr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await ed(this.baseDir,{recursive:!0});let e=await qu(this.baseDir);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Unsafe temp output directory")}getFilePath(e){let t=this.config.prefix||"session",o=this.config.extension?`.${this.config.extension}`:"",r=this.config.includeTimestamp?`-${Date.now()}`:"",s=`${t}-${sd(e)}${r}${o}`;if(id(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return hr(this.baseDir,s)}async output(e,t={}){try{let o=t.metadata?.sessionId;if(!o)return!1;let r=JSON.stringify({...e,timestamp:Date.now(),sessionId:o},null,2),s=this.getFilePath(o);return await Nn(s,async()=>{await this.ensureDir();let i=hr(this.baseDir,`.ccr-tmp-${process.pid}-${rd()}.tmp`);return Nn(i,async()=>{let a=!1;try{let l=await td(i,"wx");a=!0;try{await l.writeFile(r,"utf-8")}finally{await l.close()}return await nd(i,s),!0}finally{a&&await od(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return ta(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var _r,Ge,oa=E(()=>{"use strict";lr();ur();yr();_r=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 dt(e.config);case"webhook":return new pt(e.config);case"temp-file":return new ft(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,a])=>{try{await a.output(e,o)?r.success.push(i):r.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),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 a=>{let l=this.handlers.get(a);if(!l){console.warn(`[OutputManager] Handler ${a} not found`),s.failed.push(a);return}try{await l.output(t,r)?s.success.push(a):s.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),s.failed.push(a)}});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)}},Ge=new _r});var kr=E(()=>{"use strict";Yi();lr();ur();yr();oa()});import ld from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as ud}from"@wengine-ai/claude-code-router-shared";function $n(){return{subdirectory:ud,extension:"json",includeTimestamp:!1,prefix:"session"}}function ra(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,dd);return Math.round(n/o)}function gt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function sa(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,statsKey:n.statsKey},...t};for(let a of e)try{await Ge.outputToType(a,s,i)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${a}:`,l)}}var mt,br,dd,Ln,ia=E(()=>{"use strict";cr();kr();Ne();mt=new Map,br=new Map,dd=1,Ln={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:ld(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)Ge.registerHandlers(t.outputHandlers);else{let i=[];for(let a of o)a==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?i.push({type:"temp-file",enabled:!0,config:$n()}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&Ge.registerHandlers(i)}t.outputOptions&&Ge.setDefaultOptions(t.outputOptions);let r=async i=>{let a=n.tokenizerService;if(!a)return n.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let l=i.provider,c=i.model,u=`${l}:${c}`;if(br.has(u))return br.get(u);let d=a.getTokenizerConfigForModel(l,c);if(!d)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let p=await a.getTokenizer(d,l);return br.set(u,p),n.log?.info(`Created tokenizer for ${l}:${c} - ${p.name}`),p}catch(p){return n.log?.warn(`Failed to create tokenizer for ${l}:${c}: ${p.message}`),null}},s=i=>{let a=new URL(`http://127.0.0.1${i}`).pathname;return a.endsWith("/v1/messages")||a.endsWith("/v1/responses")};n.addHook("onRequest",async i=>{s(i.url)&&(i.requestStartTime=performance.now())}),n.addHook("onSend",async(i,a,l)=>{let c=i.requestStartTime;if(!c)return;let u=i.id||Date.now().toString(),d=i.usageSessionId||u,p=i.sessionId;if(!p)try{p=ge(i.body?.metadata?.user_id)||d}catch{p=d}let m=await r(i);if(l instanceof ReadableStream){mt.set(u,{requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[_,k]=l.tee(),y=async()=>{let b=null,T=async C=>{let v=mt.get(u);if(!v)return;let S=v.firstTokenTime?v.firstTokenTime-v.startTime:0,w=(C?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=ra(v.tokenCount,w,S),await sa(v,o,t.outputOptions,C).catch(R=>{n.log?.warn(`Failed to output streaming stats: ${R.message}`)})};try{let v=k.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();for(b=setInterval(async()=>{mt.get(u)&&await T(!1)},1e3);;){let{done:S,value:x}=await v.read();if(S)break;let w=x,R=mt.get(u);if(!R)continue;let O=performance.now(),P=w.event||w.data?.type,M=w.event==="content_block_start"||w.event==="content_block_delta"||w.event==="text_block"||w.event==="content_block"||P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta";!R.firstTokenTime&&M&&(R.firstTokenTime=O,R.timeToFirstToken=Math.round(O-R.startTime));let $="";if(w.event==="content_block_delta"&&w.data?.delta){let L=w.data.delta.type;L==="text_delta"?$=w.data.delta.text||"":L==="input_json_delta"?$=w.data.delta.partial_json||"":L==="thinking_delta"&&($=w.data.delta.thinking||"")}if((P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta")&&($=typeof w.data?.delta=="string"?w.data.delta:""),$){let L=m&&m.encodeText?m.encodeText($).length:gt($);R.tokenCount+=L,R.lastTokenTime=O}(w.event==="message_stop"||P==="response.completed"||P==="response.failed")&&(b&&(clearInterval(b),b=null),await T(!0),mt.delete(u))}}catch(C){b&&clearInterval(b),C.name!=="AbortError"&&C.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${C.message}`)}};return i.tokenSpeedCapturePromise=y().catch(b=>{console.log(b),n.log?.warn(`Background stats processing failed: ${b.message}`)}),_}let h=performance.now(),g=0,f=!1;if(l&&typeof l=="string")try{let _=JSON.parse(l);if(typeof _.usage?.output_tokens=="number")g=_.usage.output_tokens,f=!0;else{let k=_.content??_.message?.content;if(k!==void 0)if(f=!0,m)Array.isArray(k)?g=k.reduce((y,b)=>{if(b.type==="text"){let T=b.text||"";return y+(m.encodeText?m.encodeText(T).length:gt(T))}return y},0):typeof k=="string"&&(g=m.encodeText?m.encodeText(k).length:gt(k));else{let y=Array.isArray(k)?k.map(b=>b.text).join(""):typeof k=="string"?k:"";g=gt(y)}}}catch{}if(f){let _=h-c,k={requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:h,tokenCount:g,tokensPerSecond:ra(g,_),stream:!1};await sa(k,o,t.outputOptions,!0)}return l})})}});var Tr=E(()=>{"use strict";Vi();Qi();ia();kr()});import ee from"node:fs/promises";import aa from"json5";import Se from"node:path";import{CONFIG_FILE as te,HOME_DIR as Dn,PLUGINS_DIR as pd}from"@wengine-ai/claude-code-router-shared";function ca(){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 vr,ht,Fn,xr,ne,Un,_e,fd,Cr,jn=E(()=>{"use strict";vr=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(vr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=vr(o);return e}return n},ht=async n=>{try{await ee.access(n)}catch{await ee.mkdir(n,{recursive:!0})}},Fn=async()=>{await ht(Dn),await ht(pd),await ht(Se.join(Dn,"logs"))},xr=async()=>{let n=await ee.readFile(te,"utf-8");return aa.parse(n)},ne=async()=>{try{let n=await ee.readFile(te,"utf-8");try{let e=aa.parse(n);return vr(e)}catch(e){console.error(`Failed to parse config file at ${te}`),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 Fn();let e=await Un();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await _e(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 ${te}`),console.error("Error details:",n.message),process.exit(1)}};Un=async()=>{ca();try{if(await ee.access(te).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${te}.${n}.bak`;await ee.copyFile(te,e);try{let t=Se.dirname(te),o=Se.basename(te),s=(await ee.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 a=Se.join(t,s[i]);await ee.unlink(a)}}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},_e=async n=>{ca(),await ht(Dn),await fd();let e=`${JSON.stringify(n,null,2)}`;await ee.writeFile(te,e)},fd=async()=>{if(!await ee.access(te).then(()=>!0).catch(()=>!1))return;let e=Se.join(Dn,"config-history");await ht(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Se.join(e,`config-${t}.json`);await ee.copyFile(te,o);try{let s=(await ee.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.unlink(Se.join(e,i))}catch(r){console.warn("Failed to prune config-history:",r)}},Cr=async()=>{let n=await ne();return Object.assign(process.env,n),n}});function md(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function gd(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 Ve(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:md(n),cache_creation_input_tokens:gd(n)}}function Hn(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 Sr=E(()=>{"use strict"});function zn(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(Rr(r,s))}return}if(Array.isArray(n)){for(let o of n)zn(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))zn(o,e,t)}}function la(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 a of i)a&&o.add(Rr(s,a))}return zn(n?.Router,t,o),zn(n?.fallback,t,o),o}function yt(n,e){try{let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=la(n),r=0;for(let s of t.getAllStates()||[]){let i=s?.provider,a=s?.model;!i||!a||o.has(Rr(i,a))||(t.recover(i,a),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 Bn(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 hd,Rr,Jn=E(()=>{"use strict";re();hd="\0",Rr=(n,e)=>`${n}${hd}${e}`});function yd(n){return/\[1m\]/i.test(n)?1e6:2e5}function _d(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function kd(n,e=n){let t=yd(n),o=_d(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 Wn(n){let e=new Map,t=(o,r=o)=>{!o||e.has(o)||e.set(o,kd(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 wr=E(()=>{"use strict"});function bd(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var Kn,Er=E(()=>{"use strict";Kn=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||bd(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 a=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(a)?a[0]:a||"";if(!l){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(l.startsWith("Bearer")?c=l.split(" ")[1]:c=l,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 ka={};no(ka,{append:()=>vt,clear:()=>Ir,close:()=>zd,getOldestRecordTimestamp:()=>Bd,query:()=>Ar,querySummary:()=>xt,readTokenSpeedStats:()=>Mr});import{existsSync as pa,mkdirSync as Td,readFileSync as fa}from"fs";import{join as Qn}from"path";import{tmpdir as vd}from"os";import xd from"better-sqlite3";import{HOME_DIR as Cd,sanitizeTempFileKey as Sd,TOKEN_SPEED_TEMP_SUBDIRECTORY as Rd}from"@wengine-ai/claude-code-router-shared";function Ad(){pa(Vn)||Td(Vn,{recursive:!0})}function Tt(){if(be)return be;Ad();let n=new xd(wd);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&&(Id(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")),Nd(n),ha(n,!0),Or=n.prepare(`
|
|
316
|
+
`):`${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 pt,ur=E(()=>{"use strict";pt=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||{},a={data:e};return r&&(a.timestamp=new Date().toISOString()),s&&(a.prefix=s),i&&Object.keys(i).length>0&&(a.metadata=i),a}async sendRequest(e,t,o,r,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:i.signal});if(clearTimeout(a),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(a),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,i){let a=null;for(let l=1;l<=i.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(a=c,l===i.maxAttempts)break;let u=i.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${i.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw a}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}`)}}}});import{lstat as Mn,opendir as Ju,unlink as Wu}from"node:fs/promises";import{join as Zi,resolve as fr}from"node:path";import{tmpdir as Ku}from"node:os";async function Nn(n,e){let t=fr(n),o=In.get(t),r,s=new Promise(i=>{r=i});In.set(t,s);try{return await o,await e()}finally{r(),In.get(t)===s&&In.delete(t)}}function qi(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Xi(n,e){try{let t=await Mn(n);return t.isDirectory()&&!t.isSymbolicLink()&&qi(e,t)}catch{return!1}}function Xu(){return new Promise(n=>{setTimeout(n,10).unref()})}async function ea(n,e,t,o){let r=fr(n);if(o?.aborted||dr.has(r))return 0;dr.add(r);let s=0;try{let i=await Mn(r);if(!i.isDirectory()||i.isSymbolicLink()||o?.aborted)return 0;let a=await Ju(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of a){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let d=Zi(r,u.name);try{let p=await Mn(d);if(!p.isFile()||p.isSymbolicLink()||p.mtimeMs>=e)continue;await Nn(d,async()=>{if(o?.aborted||!await Xi(r,i))return!1;let h=await Mn(d);return!h.isFile()||h.isSymbolicLink()||!qi(p,h)||h.mtimeMs!==p.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await Wu(d),!0)})&&s++}catch{}}finally{++l%64===0&&(await Xu(),c=!o?.aborted&&await Xi(r,i))}}}finally{await a.close().catch(()=>{})}}catch{}finally{dr.delete(r)}return s}function ta(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,i=t?`.${t}`:"";return ea(n,Date.now()-o,a=>Yu.test(a)?!0:!a.endsWith(".tmp")&&a.startsWith(s)&&a.endsWith(i),r)}function Zu(n,e){let t=Date.now()-Gu;return ea(n,t,o=>{let r=Qu.exec(o);return r!==null&&Number(r[1])<t},e)}function mr(n,e,t){let o=pr.get(n);if(!o){let s=new AbortController,i,a=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(a(),i=setInterval(a,Vu),i.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),i&&clearInterval(i)}},pr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),pr.delete(n)))}}function na(n=Zi(Ku(),"claude-code-router")){return mr(`legacy:${fr(n)}`,e=>Zu(n,e),1e3)}var Gu,Vu,Qu,Yu,dr,In,pr,gr=E(()=>{"use strict";Gu=3600*1e3,Vu=600*1e3,Qu=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,Yu=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,dr=new Set,In=new Map,pr=new Map});import{lstat as qu,mkdir as ed,open as td,rename as nd,unlink as od}from"node:fs/promises";import{randomUUID as rd}from"node:crypto";import{sanitizeTempFileKey as sd}from"@wengine-ai/claude-code-router-shared";import{basename as id,join as hr,resolve as ad}from"node:path";import{tmpdir as cd}from"node:os";var ft,yr=E(()=>{"use strict";gr();ft=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=ad(hr(cd(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=mr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await ed(this.baseDir,{recursive:!0});let e=await qu(this.baseDir);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Unsafe temp output directory")}getFilePath(e){let t=this.config.prefix||"session",o=this.config.extension?`.${this.config.extension}`:"",r=this.config.includeTimestamp?`-${Date.now()}`:"",s=`${t}-${sd(e)}${r}${o}`;if(id(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return hr(this.baseDir,s)}async output(e,t={}){try{let o=t.metadata?.sessionId;if(!o)return!1;let r=JSON.stringify({...e,timestamp:Date.now(),sessionId:o},null,2),s=this.getFilePath(o);return await Nn(s,async()=>{await this.ensureDir();let i=hr(this.baseDir,`.ccr-tmp-${process.pid}-${rd()}.tmp`);return Nn(i,async()=>{let a=!1;try{let l=await td(i,"wx");a=!0;try{await l.writeFile(r,"utf-8")}finally{await l.close()}return await nd(i,s),!0}finally{a&&await od(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return ta(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var _r,Ge,oa=E(()=>{"use strict";lr();ur();yr();_r=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 dt(e.config);case"webhook":return new pt(e.config);case"temp-file":return new ft(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,a])=>{try{await a.output(e,o)?r.success.push(i):r.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),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 a=>{let l=this.handlers.get(a);if(!l){console.warn(`[OutputManager] Handler ${a} not found`),s.failed.push(a);return}try{await l.output(t,r)?s.success.push(a):s.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),s.failed.push(a)}});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)}},Ge=new _r});var kr=E(()=>{"use strict";Yi();lr();ur();yr();oa()});import ld from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as ud}from"@wengine-ai/claude-code-router-shared";function $n(){return{subdirectory:ud,extension:"json",includeTimestamp:!1,prefix:"session"}}function ra(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,dd);return Math.round(n/o)}function gt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function sa(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,statsKey:n.statsKey},...t};for(let a of e)try{await Ge.outputToType(a,s,i)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${a}:`,l)}}var mt,br,dd,Ln,ia=E(()=>{"use strict";cr();kr();Ne();mt=new Map,br=new Map,dd=1,Ln={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:ld(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)Ge.registerHandlers(t.outputHandlers);else{let i=[];for(let a of o)a==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?i.push({type:"temp-file",enabled:!0,config:$n()}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&Ge.registerHandlers(i)}t.outputOptions&&Ge.setDefaultOptions(t.outputOptions);let r=async i=>{let a=n.tokenizerService;if(!a)return n.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let l=i.provider,c=i.model,u=`${l}:${c}`;if(br.has(u))return br.get(u);let d=a.getTokenizerConfigForModel(l,c);if(!d)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let p=await a.getTokenizer(d,l);return br.set(u,p),n.log?.info(`Created tokenizer for ${l}:${c} - ${p.name}`),p}catch(p){return n.log?.warn(`Failed to create tokenizer for ${l}:${c}: ${p.message}`),null}},s=i=>{let a=new URL(`http://127.0.0.1${i}`).pathname;return a.endsWith("/v1/messages")||a.endsWith("/v1/responses")};n.addHook("onRequest",async i=>{s(i.url)&&(i.requestStartTime=performance.now())}),n.addHook("onSend",async(i,a,l)=>{let c=i.requestStartTime;if(!c)return;let u=i.id||Date.now().toString(),d=i.usageSessionId||u,p=i.sessionId;if(!p)try{p=ge(i.body?.metadata?.user_id)||d}catch{p=d}let m=await r(i);if(l instanceof ReadableStream){mt.set(u,{requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[_,k]=l.tee(),y=async()=>{let b=null,T=async C=>{let v=mt.get(u);if(!v)return;let S=v.firstTokenTime?v.firstTokenTime-v.startTime:0,w=(C?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=ra(v.tokenCount,w,S),await sa(v,o,t.outputOptions,C).catch(R=>{n.log?.warn(`Failed to output streaming stats: ${R.message}`)})};try{let v=k.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();for(b=setInterval(async()=>{mt.get(u)&&await T(!1)},1e3);;){let{done:S,value:x}=await v.read();if(S)break;let w=x,R=mt.get(u);if(!R)continue;let O=performance.now(),P=w.event||w.data?.type,M=w.event==="content_block_start"||w.event==="content_block_delta"||w.event==="text_block"||w.event==="content_block"||P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta";!R.firstTokenTime&&M&&(R.firstTokenTime=O,R.timeToFirstToken=Math.round(O-R.startTime));let $="";if(w.event==="content_block_delta"&&w.data?.delta){let L=w.data.delta.type;L==="text_delta"?$=w.data.delta.text||"":L==="input_json_delta"?$=w.data.delta.partial_json||"":L==="thinking_delta"&&($=w.data.delta.thinking||"")}if((P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta")&&($=typeof w.data?.delta=="string"?w.data.delta:""),$){let L=m&&m.encodeText?m.encodeText($).length:gt($);R.tokenCount+=L,R.lastTokenTime=O}(w.event==="message_stop"||P==="response.completed"||P==="response.failed")&&(b&&(clearInterval(b),b=null),await T(!0),mt.delete(u))}}catch(C){b&&clearInterval(b),C.name!=="AbortError"&&C.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${C.message}`)}};return i.tokenSpeedCapturePromise=y().catch(b=>{console.log(b),n.log?.warn(`Background stats processing failed: ${b.message}`)}),_}let h=performance.now(),g=0,f=!1;if(l&&typeof l=="string")try{let _=JSON.parse(l);if(typeof _.usage?.output_tokens=="number")g=_.usage.output_tokens,f=!0;else{let k=_.content??_.message?.content;if(k!==void 0)if(f=!0,m)Array.isArray(k)?g=k.reduce((y,b)=>{if(b.type==="text"){let T=b.text||"";return y+(m.encodeText?m.encodeText(T).length:gt(T))}return y},0):typeof k=="string"&&(g=m.encodeText?m.encodeText(k).length:gt(k));else{let y=Array.isArray(k)?k.map(b=>b.text).join(""):typeof k=="string"?k:"";g=gt(y)}}}catch{}if(f){let _=h-c,k={requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:h,tokenCount:g,tokensPerSecond:ra(g,_),stream:!1};await sa(k,o,t.outputOptions,!0)}return l})})}});var Tr=E(()=>{"use strict";Vi();Qi();ia();kr()});import ee from"node:fs/promises";import aa from"json5";import Se from"node:path";import{CONFIG_FILE as te,HOME_DIR as Dn,PLUGINS_DIR as pd}from"@wengine-ai/claude-code-router-shared";function ca(){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 vr,ht,Fn,xr,ne,Un,_e,fd,Cr,jn=E(()=>{"use strict";vr=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(vr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=vr(o);return e}return n},ht=async n=>{try{await ee.access(n)}catch{await ee.mkdir(n,{recursive:!0})}},Fn=async()=>{await ht(Dn),await ht(pd),await ht(Se.join(Dn,"logs"))},xr=async()=>{let n=await ee.readFile(te,"utf-8");return aa.parse(n)},ne=async()=>{try{let n=await ee.readFile(te,"utf-8");try{let e=aa.parse(n);return vr(e)}catch(e){console.error(`Failed to parse config file at ${te}`),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 Fn();let e=await Un();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await _e(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 ${te}`),console.error("Error details:",n.message),process.exit(1)}};Un=async()=>{ca();try{if(await ee.access(te).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${te}.${n}.bak`;await ee.copyFile(te,e);try{let t=Se.dirname(te),o=Se.basename(te),s=(await ee.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 a=Se.join(t,s[i]);await ee.unlink(a)}}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},_e=async n=>{ca(),await ht(Dn),await fd();let e=`${JSON.stringify(n,null,2)}`;await ee.writeFile(te,e)},fd=async()=>{if(!await ee.access(te).then(()=>!0).catch(()=>!1))return;let e=Se.join(Dn,"config-history");await ht(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Se.join(e,`config-${t}.json`);await ee.copyFile(te,o);try{let s=(await ee.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.unlink(Se.join(e,i))}catch(r){console.warn("Failed to prune config-history:",r)}},Cr=async()=>{let n=await ne();return Object.assign(process.env,n),n}});function md(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function gd(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 Ve(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:md(n),cache_creation_input_tokens:gd(n)}}function Hn(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 Sr=E(()=>{"use strict"});function zn(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(Rr(r,s))}return}if(Array.isArray(n)){for(let o of n)zn(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))zn(o,e,t)}}function la(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 a of i)a&&o.add(Rr(s,a))}return zn(n?.Router,t,o),zn(n?.fallback,t,o),o}function yt(n,e){try{let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=la(n),r=0;for(let s of t.getAllStates()||[]){let i=s?.provider,a=s?.model;!i||!a||o.has(Rr(i,a))||(t.recover(i,a),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 Bn(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 hd,Rr,Jn=E(()=>{"use strict";re();hd="\0",Rr=(n,e)=>`${n}${hd}${e}`});function yd(n){return/\[1m\]/i.test(n)?1e6:2e5}function _d(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function kd(n,e=n){let t=yd(n),o=_d(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 Wn(n){let e=new Map,t=(o,r=o)=>{!o||e.has(o)||e.set(o,kd(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 wr=E(()=>{"use strict"});function bd(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var Kn,Er=E(()=>{"use strict";Kn=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||bd(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 a=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(a)?a[0]:a||"";if(!l){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(l.startsWith("Bearer")?c=l.split(" ")[1]:c=l,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 ka={};no(ka,{append:()=>vt,clear:()=>Ir,close:()=>zd,getOldestRecordTimestamp:()=>Bd,query:()=>Ar,querySummary:()=>xt,readTokenSpeedStats:()=>Mr});import{existsSync as pa,mkdirSync as Td,readFileSync as fa}from"fs";import{join as Qn}from"path";import{tmpdir as vd}from"os";import{openSqliteDatabase as xd}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Cd,sanitizeTempFileKey as Sd,TOKEN_SPEED_TEMP_SUBDIRECTORY as Rd}from"@wengine-ai/claude-code-router-shared";function Ad(){pa(Vn)||Td(Vn,{recursive:!0})}function Tt(){if(be)return be;Ad();let n=xd(wd),e=n.db;n.driver==="node:sqlite"&&console.error(`[usage] better-sqlite3 unavailable, using built-in node:sqlite fallback. Reason: ${n.fallbackReason}`),e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("busy_timeout = 5000");let t=e.pragma("user_version",{simple:!0})||0;return t<1&&(Id(e),e.pragma("user_version = 1")),t<2&&(e.prepare("PRAGMA table_info(usage_records)").all().some(r=>r.name==="upstream_model")||e.exec("ALTER TABLE usage_records ADD COLUMN upstream_model TEXT"),e.pragma("user_version = 2")),Nd(e),ha(e,!0),Or=e.prepare(`
|
|
317
317
|
INSERT INTO usage_records (
|
|
318
318
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
319
319
|
scenario_type, client_type,
|
|
@@ -327,7 +327,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
327
327
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
328
328
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
329
329
|
)
|
|
330
|
-
`),be=
|
|
330
|
+
`),be=e,be}function Id(n){n.exec(`
|
|
331
331
|
CREATE TABLE IF NOT EXISTS usage_records (
|
|
332
332
|
id TEXT PRIMARY KEY,
|
|
333
333
|
timestamp TEXT NOT NULL,
|