@wengine-ai/llms 2.3.2413 → 2.3.2415
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 +2 -1
- package/THIRD_PARTY_NOTICES.md +3 -0
- package/dist/api/plugin-request-state.d.ts +22 -0
- package/dist/api/plugin-response-error.d.ts +5 -0
- package/dist/api/routes.d.ts +2 -0
- package/dist/ccr/plugin-install-routes.d.ts +79 -0
- package/dist/cjs/server.cjs +213 -209
- package/dist/cjs/server.cjs.map +4 -4
- package/dist/esm/server.mjs +213 -209
- package/dist/esm/server.mjs.map +4 -4
- package/dist/index.html +41 -41
- package/dist/provider-plugins/host.d.ts +11 -0
- package/dist/provider-plugins/loader.d.ts +33 -0
- package/dist/provider-plugins/registry.d.ts +39 -0
- package/dist/provider-plugins/transformer-hook.d.ts +3 -0
- package/dist/provider-plugins/types.d.ts +182 -0
- package/dist/server.d.ts +8 -0
- package/dist/services/active-probe.d.ts +2 -1
- package/dist/services/provider-health.d.ts +1 -1
- package/dist/services/provider.d.ts +2 -0
- package/dist/services/proxy.d.ts +19 -1
- package/dist/services/transformer.d.ts +2 -0
- package/dist/transformer/openai.responses.transformer.d.ts +0 -6
- package/dist/types/llm.d.ts +4 -0
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +0 -1
package/dist/cjs/server.cjs
CHANGED
|
@@ -1,318 +1,322 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Sl=Object.create;var _n=Object.defineProperty;var Rl=Object.getOwnPropertyDescriptor;var wl=Object.getOwnPropertyNames;var Pl=Object.getPrototypeOf,El=Object.prototype.hasOwnProperty;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var bn=(n,e)=>{for(var t in e)_n(n,t,{get:e[t],enumerable:!0})},zs=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wl(e))!El.call(n,r)&&r!==t&&_n(n,r,{get:()=>e[r],enumerable:!(o=Rl(e,r))||o.enumerable});return n};var q=(n,e,t)=>(t=n!=null?Sl(Pl(n)):{},zs(e||!n||!n.__esModule?_n(t,"default",{value:n,enumerable:!0}):t,n)),Bs=n=>zs(_n({},"__esModule",{value:!0}),n);function Al(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Ol.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 Ks(n){let e=[];for(let t of[...Js,Ws]){let o=n[t];if(o==null)continue;let r=Al(o);r.ok||e.push({key:t,error:r.error})}return e}function Go(){return Ko||(Ko=new Tn.Agent({connect:{timeout:15e3}})),Ko}function Gs(n){let e=n.get(Ws);return(typeof e=="string"?e.trim():"")||void 0}function Vs(n){return n?Y(n):Go()}function Rt(n){for(let e of Js){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Vo(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 me(n,e){let t=Rt(n);if(t)return Vo(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function Y(n){let e=Il(n),t=kn.get(e);if(t)return t;let o=new Tn.ProxyAgent(e);return kn.set(e,o),o}async function vn(){let n=Array.from(kn.values());kn.clear(),await Promise.allSettled(n.map(e=>e.close()))}function Il(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 Tn,Js,Ws,Ol,kn,Ko,ae=w(()=>{"use strict";Tn=require("undici"),Js=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Ws="SUBSCRIPTION_PROXY_URL",Ol=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;kn=new Map});var wt,Qo,Qs,Ys,Ue,Yo=w(()=>{"use strict";wt=require("fs"),Qo=require("path"),Qs=require("dotenv"),Ys=q(require("json5"),1);ae();Ue=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,Qo.join)(process.cwd(),this.options.jsonPath);if((0,wt.existsSync)(e))try{let t=(0,wt.readFileSync)(e,"utf-8"),o=Ys.default.parse(t);this.config={...this.config,...o},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,Qo.join)(process.cwd(),this.options.envPath);if((0,wt.existsSync)(e))try{let t=(0,Qs.config)({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return 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 G(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Xs(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 xn=w(()=>{"use strict"});function Cn(n){Xo=n}function Pt(){return Xo}function Sn(n){return Xo||n.get("DEBUG_LOG")===!0}function ei(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Ze:{maxBodyLength:e.maxBodyLength??Ze.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Ze.maxStreamChunks}}function Rn(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();Ml.has(r)||Nl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function wn(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function ti(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:Rn(t.headers),body:wn(o,Ze.maxBodyLength)})}function ni(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Rn(t.headers),...t.body!==void 0?{body:wn(t.body,Ze.maxBodyLength)}:{}})}function Zs(n,e,t,o){let r=$l(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:wn(o,Ze.maxBodyLength)})}function $l(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:wn(o,512)})}}if(e.length)return e.length===1?e[0]:e}function qs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function oi(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:c}=await r.read();if(i)break;a+=c;let l=a.split(`
|
|
2
2
|
|
|
3
|
-
`);i=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Cs(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&&Cs(e,t,s,i.trim()),s++),Ss(e,t,s)}catch(i){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,i),Ss(e,t,s)}finally{r.releaseLock()}})()}var Kc,Ge,Lo,bt=E(()=>{"use strict";Kc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Ge={maxBodyLength:4096,maxStreamChunks:100},Lo=!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=Q(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:fn(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Vc(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function Vc(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 As=E(()=>{ae();bt()});var gn,Do=E(()=>{gn="2.3.2413"});var Is={};an(Is,{getFallbackPromotionStore:()=>Ve,resetFallbackPromotionStore:()=>Xc});function Ve(n){return Fe||(Fe=new Fo,n&&Fe.configure(n)),Fe}function Xc(){Fe&&(Fe.clearAll(),Fe=null)}var Yc,Fo,Fe,hn=E(()=>{"use strict";ce();Yc=600*1e3,Fo=class{promotions=new Map;enabled=!0;ttlMs=Yc;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(!j().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}},Fe=null});function tl(n){try{if(!(0,he.existsSync)(Ho))return;let e=JSON.parse((0,he.readFileSync)(Ho,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Ns(n){try{let e=n.getAllStates();if(e.length===0)return;(0,he.existsSync)(jo)||(0,he.mkdirSync)(jo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,he.writeFileSync)(Ho,JSON.stringify(t,null,2),"utf-8")}catch{}}function yn(){if(Ms)return;Ms=!0;let n=j();tl(n),el=setInterval(()=>Ns(n),6e4),process.on("exit",()=>Ns(n))}function j(n){return Uo||(Uo=new Tt(n)),Uo}var he,zo,$s,Zc,qc,Tt,jo,Ho,Ms,el,Uo,ce=E(()=>{"use strict";he=require("fs"),zo=require("path"),$s=require("@wengine-ai/claude-code-router-shared"),Zc=120,qc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Tt=class{states=new Map;config;probeTimer;constructor(e){this.config={...qc,...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}=(hn(),ys(Is));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??Zc)*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)}},jo=(0,zo.join)($s.HOME_DIR,"runtime"),Ho=(0,zo.join)(jo,"provider-health.json"),Ms=!1,el=null;Uo=null});function vt(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=Bo(o,nl),s=Bo(o,ol),i=Bo(o,rl);(r||s||i)&&Qe.set(n,{provider:n,remaining:Fs(r),limit:Fs(s),reset:sl(i),capturedAt:Date.now()})}function Hs(n){return Qe.get(n)}function _n(){return Array.from(Qe.values())}function Bo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function Fs(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function sl(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=il(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function il(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 al(){try{if(!(0,ye.existsSync)(Wo))return;let n=JSON.parse((0,ye.readFileSync)(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>3600*1e3)continue;Qe.set(t.provider,t)}}catch{}}function Us(){try{if(Qe.size===0)return;(0,ye.existsSync)(Jo)||(0,ye.mkdirSync)(Jo,{recursive:!0}),(0,ye.writeFileSync)(Wo,JSON.stringify(Array.from(Qe.values()),null,2),"utf-8")}catch{}}function Ye(){Ls||(Ls=!0,al(),Ds=setInterval(Us,6e4),Ds.unref?.(),process.on("exit",Us))}var ye,Ko,js,Jo,Wo,Qe,Ls,Ds,nl,ol,rl,Xe=E(()=>{"use strict";ye=require("fs"),Ko=require("path"),js=require("@wengine-ai/claude-code-router-shared"),Jo=(0,Ko.join)(js.HOME_DIR,"runtime"),Wo=(0,Ko.join)(Jo,"rate-limit.json"),Qe=new Map,Ls=!1,Ds=null,nl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],ol=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],rl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function bn(){return Go||(Go=new Qo),Go}function Xo(){return Vo||(Vo=new Yo),Vo}function cl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function zs(n){let e=cl(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 Bs(n,e){let t=bn(),o=n?.[kn];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[kn]=t.acquire(e)}function Zo(n){let e=n?.[kn];e&&bn().release(e)}function Js(n,e){let t=zs(n),o=n?.[kn],r=t?Xo().get(t)!==void 0:!1;!o&&!r||(t&&Xo().bind(t,e),Bs(n,e))}function ll(n,e,t){let o=bn(),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 Ws(n,e,t){let o=zs(n),r=Xo(),s=bn(),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=ll(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 Bs(n,a),a}var Qo,Yo,Go,Vo,kn,Tn=E(()=>{"use strict";Qo=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()}},Yo=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()}},Go=null,Vo=null;kn="__concurrencyLease"});async function U(n){let e=await n.text();return ul(e,n.status)}function ul(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 Ks(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function xt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function Ce(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})),xt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:xt(s)}}async function Se(n){try{let e=await n.text();if(xt(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 q=E(()=>{"use strict"});var Ze,qo=E(()=>{"use strict";q();Ze=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 Ce(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 Se(e);if(r.isSSE)return this.transformResponseOut(r.response);e=r.response}}if(t.includes("application/json")){let o=await U(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]
|
|
3
|
+
`);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?Zs(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Zs(e,t,s,a.trim()),s++),qs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),qs(e,t,s)}finally{r.releaseLock()}})()}var Ml,Nl,Ze,Xo,Et=w(()=>{"use strict";Ml=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Nl=/token|secret|credential|passwd|password/i,Ze={maxBodyLength:4096,maxStreamChunks:100},Xo=!1});function ri(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([l,u])=>{u&&s.set(l,u)});let a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let l=new AbortController,u=()=>l.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=l.signal}else a=i;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?c.dispatcher=t.dispatcher:t.httpsProxy&&(c.dispatcher=Y(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Rn(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Ll(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function Ll(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 si=w(()=>{ae();Et()});function Dl(n,e){return`${n.name}|${e?.name??""}`}function Zo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function qe(n,e,t){let o=Zo(n),r=Dl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function qo(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(qe(n,e,o).terminalError=t,!0)}var ii=w(()=>{"use strict"});var er=w(()=>{"use strict"});function ci(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var ai,Ot,Fl,nr,Pn=w(()=>{"use strict";ai=q(require("fastify"),1);er();Ot=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let f of this.plugins.values()){for(let g of s.runtimes.keys())if(f.runtimes.has(g))throw new Error(`managed runtime "${g}" is already registered`);for(let g of s.transformers.keys())if(f.transformers.has(g))throw new Error(`transformer "${g}" is already registered`)}let m=[...this.transformerServices].flatMap(f=>[...s.transformers].map(([g,_])=>{if(f.hasTransformer(g))throw new Error(`transformer "${g}" is already registered`);return{service:f,name:g,value:f.preparePluginTransformer(_)}})),h=[];try{for(let f of m)h.push(f),f.service.registerTransformer(f.name,f.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(f){for(let g of h)g.service.removeTransformer(g.name);throw a="aborted",f}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:d??p}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=(0,ai.default)({logger:!1});try{for(let i of e){let c=i(s);c!==s&&await c}for(let i of this.plugins.values())for(let c of i.preparedRoutes)a.route(c);for(let i of r){let c=Array.isArray(i.method)?i.method:[i.method];for(let l of c)if(t.hasRoute({method:l,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${l} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},Fl=new Ot,nr=()=>Fl});async function je(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e===0||e>=500};try{await n.noteUpstreamError?.(i)}catch{}let c=ci(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}var li=w(()=>{"use strict";Pn()});var En,or=w(()=>{En="2.3.2415"});var ui={};bn(ui,{getFallbackPromotionStore:()=>et,resetFallbackPromotionStore:()=>Hl});function et(n){return He||(He=new rr,n&&He.configure(n)),He}function Hl(){He&&(He.clearAll(),He=null)}var jl,rr,He,On=w(()=>{"use strict";le();jl=600*1e3,rr=class{promotions=new Map;enabled=!0;ttlMs=jl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!j().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),m=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!m||d.enabled===!1?(this.promotions.delete(s),null):`${d.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}},He=null});function Wl(n){try{if(!(0,be.existsSync)(ar))return;let e=JSON.parse((0,be.readFileSync)(ar,"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 pi(n){try{let e=n.getAllStates();if(e.length===0)return;(0,be.existsSync)(ir)||(0,be.mkdirSync)(ir,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,be.writeFileSync)(ar,JSON.stringify(t,null,2),"utf-8")}catch{}}function An(){if(di)return;di=!0;let n=j();Wl(n),Jl=setInterval(()=>pi(n),6e4),process.on("exit",()=>pi(n))}function j(n){return sr||(sr=new At(n)),sr}var be,cr,fi,zl,Bl,At,ir,ar,di,Jl,sr,le=w(()=>{"use strict";be=require("fs"),cr=require("path"),fi=require("@wengine-ai/claude-code-router-shared"),zl=120,Bl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},At=class{states=new Map;config;probeTimer;constructor(e){this.config={...Bl,...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);if(!r||(r.successCount++,r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,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),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(On(),Bs(ui));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,o=!1){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let s=this.getState(e,t);return s?s.status==="open"&&s.rateLimitUntil?!(Date.now()<s.rateLimitUntil):s.status==="open"&&o&&Date.now()-Math.max(s.lastFailureTime,s.lastProbeTime)>=this.config.probeIntervalMinutes*6e4?(s.status="half-open",s.successCount=0,s.lastProbeTime=Date.now(),!0):s.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??zl)*1e3;a.rateLimitUntil=Date.now()+i}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)}},ir=(0,cr.join)(fi.HOME_DIR,"runtime"),ar=(0,cr.join)(ir,"provider-health.json"),di=!1,Jl=null;sr=null});function It(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let c=Object.keys(t).find(l=>l.toLowerCase()===i);return c?t[c]:null},r=lr(o,Kl),s=lr(o,Gl),a=lr(o,Vl);(r||s||a)&&tt.set(n,{provider:n,remaining:hi(r),limit:hi(s),reset:Ql(a),capturedAt:Date.now()})}function bi(n){return tt.get(n)}function In(){return Array.from(tt.values())}function lr(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function hi(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Ql(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=Yl(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Yl(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function Xl(){try{if(!(0,ke.existsSync)(dr))return;let n=JSON.parse((0,ke.readFileSync)(dr,"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;tt.set(t.provider,t)}}catch{}}function yi(){try{if(tt.size===0)return;(0,ke.existsSync)(ur)||(0,ke.mkdirSync)(ur,{recursive:!0}),(0,ke.writeFileSync)(dr,JSON.stringify(Array.from(tt.values()),null,2),"utf-8")}catch{}}function nt(){mi||(mi=!0,Xl(),gi=setInterval(yi,6e4),gi.unref?.(),process.on("exit",yi))}var ke,pr,_i,ur,dr,tt,mi,gi,Kl,Gl,Vl,ot=w(()=>{"use strict";ke=require("fs"),pr=require("path"),_i=require("@wengine-ai/claude-code-router-shared"),ur=(0,pr.join)(_i.HOME_DIR,"runtime"),dr=(0,pr.join)(ur,"rate-limit.json"),tt=new Map,mi=!1,gi=null,Kl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Gl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Vl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Nn(){return fr||(fr=new gr),fr}function yr(){return mr||(mr=new hr),mr}function Zl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function ki(n){let e=Zl(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 Ti(n,e){let t=Nn(),o=n?.[Mn];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[Mn]=t.acquire(e)}function _r(n){let e=n?.[Mn];e&&Nn().release(e)}function vi(n,e){let t=ki(n),o=n?.[Mn],r=t?yr().get(t)!==void 0:!1;!o&&!r||(t&&yr().bind(t,e),Ti(n,e))}function ql(n,e,t){let o=Nn(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function xi(n,e,t){let o=ki(n),r=yr(),s=Nn(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let c=r.get(o);if(c&&c!==e){let l=t.resolve(c);l?(i=l,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${l}`)):r.unbind(o)}else c&&(i=e)}if(!i){let c=s.count(e);if(c>=a){let l=ql(e,t.fallbackModels,t.resolve);l&&(i=l,t.log?.(`Concurrency priority: model ${e} has ${c} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${l}`))}i=i||e,o&&r.bind(o,i)}return Ti(n,i),i}var gr,hr,fr,mr,Mn,$n=w(()=>{gr=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()}},hr=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()}},fr=null,mr=null;Mn="__concurrencyLease"});async function U(n){let e=await n.text();return eu(e,n.status)}function eu(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 Ci(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function Mt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function Te(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 a=0;a<8;a++){let{value:i,done:c}=await o.read();if(c||(i&&(s+=r.decode(i,{stream:!0})),Mt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:Mt(s)}}async function Pe(n){try{let e=await n.text();if(Mt(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 te=w(()=>{"use strict"});var rt,br=w(()=>{"use strict";te();rt=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let t=e.headers.get("Content-Type")||"";if(!t.includes("text/event-stream")&&!t.includes("application/json")&&e.body){let o=await Te(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)}o?.body&&(e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(t.includes("application/json")){let o=await Te(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 Pe(e);if(r.isSSE)return this.transformResponseOut(r.response);e=r.response}}if(t.includes("application/json")){let o=await U(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(),a="";try{let{value:f,done:g}=await s.read();!g&&f&&(a=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start"))return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers});if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added"))return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers});let l=new TextDecoder,u=new TextEncoder,p="",d=!1,m=this,h=new ReadableStream({async start(f){let g=r.getReader(),_=-1,b="",y=k=>(k!==b&&(_++,b=k),_);try{for(;;){let{done:k,value:T}=await g.read();if(k){d||f.enqueue(u.encode(`data: [DONE]
|
|
4
4
|
|
|
5
|
-
`));break}let
|
|
5
|
+
`));break}let S=l.decode(T,{stream:!0});p+=S;let v=p.split(/\r?\n/);p=v.pop()||"";for(let R of v)if(R.trim())try{if(R.startsWith("event: "))continue;if(R.startsWith("data: ")){let C=R.slice(5).trim();if(C==="[DONE]"){d=!0,f.enqueue(u.encode(`data: [DONE]
|
|
6
6
|
|
|
7
|
-
`));continue}try{let
|
|
7
|
+
`));continue}try{let x=JSON.parse(C);if(x.type==="response.output_text.delta"){let O={id:x.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model,choices:[{index:y(x.type),delta:{content:x.delta||""},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(O)}
|
|
8
8
|
|
|
9
|
-
`))}else if(
|
|
9
|
+
`))}else if(x.type==="response.output_item.added"&&x.item?.type==="function_call"){let O={id:x.item.call_id||x.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model||"gpt-5-codex-",choices:[{index:y(x.type),delta:{role:"assistant",tool_calls:[{index:0,id:x.item.call_id||x.item.id,function:{name:x.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(O)}
|
|
10
10
|
|
|
11
|
-
`))}else if(
|
|
11
|
+
`))}else if(x.type==="response.output_item.added"&&x.item?.type==="message"){let O=[];(x.item.content||[]).forEach(E=>{E.type==="output_text"&&O.push({type:"text",text:E.text||""})});let A={role:"assistant"};if(O.length===1&&O[0].type==="text"?A.content=O[0].text:O.length>0&&(A.content=O),A.content){let E={id:x.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model,choices:[{index:y(x.type),delta:A,finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(E)}
|
|
12
12
|
|
|
13
|
-
`))}}else if(
|
|
13
|
+
`))}}else if(x.type==="response.output_text.annotation.added"){let O={id:x.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model||"gpt-5-codex",choices:[{index:y(x.type),delta:{annotations:[{type:"url_citation",url_citation:{url:x.annotation?.url||"",title:x.annotation?.title||"",content:"",start_index:x.annotation?.start_index||0,end_index:x.annotation?.end_index||0}}]},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(O)}
|
|
14
14
|
|
|
15
|
-
`))}else if(
|
|
15
|
+
`))}else if(x.type==="response.function_call_arguments.delta"){let O={id:x.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model||"gpt-5-codex-",choices:[{index:y(x.type),delta:{tool_calls:[{index:0,function:{arguments:x.delta||""}}]},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(O)}
|
|
16
16
|
|
|
17
|
-
`))}else if(
|
|
17
|
+
`))}else if(x.type==="response.completed"){let O=x.response?.output?.some(E=>E.type==="function_call")?"tool_calls":"stop",A={id:x.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:O}]};f.enqueue(u.encode(`data: ${JSON.stringify(A)}
|
|
18
18
|
|
|
19
|
-
`)),
|
|
19
|
+
`)),d=!0}else if(x.type==="response.reasoning_summary_text.delta"){let O={id:x.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model,choices:[{index:y(x.type),delta:{thinking:{content:x.delta||""}},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(O)}
|
|
20
20
|
|
|
21
|
-
`))}else if(
|
|
21
|
+
`))}else if(x.type==="response.reasoning_summary_part.done"&&x.part){let O={id:x.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:x.response?.model,choices:[{index:_,delta:{thinking:{signature:x.item_id}},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(O)}
|
|
22
22
|
|
|
23
|
-
`))}}catch{f.enqueue(
|
|
24
|
-
`))}}else f.enqueue(
|
|
25
|
-
`))}catch(
|
|
26
|
-
`))}}p.trim()&&f.enqueue(
|
|
27
|
-
`)),
|
|
23
|
+
`))}}catch{f.enqueue(u.encode(R+`
|
|
24
|
+
`))}}else f.enqueue(u.encode(R+`
|
|
25
|
+
`))}catch(C){console.error("Error processing line:",R,C),f.enqueue(u.encode(R+`
|
|
26
|
+
`))}}p.trim()&&f.enqueue(u.encode(p+`
|
|
27
|
+
`)),d||f.enqueue(u.encode(`data: [DONE]
|
|
28
28
|
|
|
29
|
-
`))}catch(
|
|
30
|
-
data: ${JSON.stringify(
|
|
29
|
+
`))}catch(k){console.error("Stream error:",k),f.error(k)}finally{try{g.releaseLock()}catch(k){console.error("Error releasing reader lock:",k)}f.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{let{value:d,done:m}=await a.read();!m&&d&&(i=new TextDecoder().decode(d))}finally{a.releaseLock()}r.cancel().catch(()=>{});let c=i.includes("message_start")||i.includes("content_block_start"),l=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added"))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(l&&!c){let d=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let p=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await U(e);return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i=0,c=!1,l=!1,u="",p=-1,d=[],m=(f,g)=>r.encode(`event: ${f}
|
|
30
|
+
data: ${JSON.stringify(g)}
|
|
31
31
|
|
|
32
|
-
`),h=(g
|
|
33
|
-
`);_=
|
|
32
|
+
`),h=(f,g=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:f,model:s,output:g,usage:this.buildResponsesUsage()});return new ReadableStream({async start(f){try{let g=e.getReader(),_="",b=!1,y=k=>{if(!b){b=!0;for(let T of d)if(T.type==="function_call"){let S=d.indexOf(T);f.enqueue(m("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:S,arguments:T.arguments||""})),T.status="completed",f.enqueue(m("response.output_item.done",{type:"response.output_item.done",output_index:S,item:T}))}for(let T of d)if(T.type==="message"){let S=d.indexOf(T);T.status="completed",f.enqueue(m("response.output_item.done",{type:"response.output_item.done",output_index:S,item:T}))}f.enqueue(m("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:T}=await g.read();if(k)break;_+=o.decode(T,{stream:!0});let S=_.split(`
|
|
33
|
+
`);_=S.pop()||"";for(let v of S){let R=v.trim();if(!R||R.startsWith("event:")||!R.startsWith("data:"))continue;let C=R.slice(5).trim();if(C==="[DONE]"){y({}),f.enqueue(r.encode(`data: [DONE]
|
|
34
34
|
|
|
35
|
-
`));continue}let
|
|
36
|
-
data: ${JSON.stringify(
|
|
35
|
+
`));continue}let x;try{x=JSON.parse(C)}catch{continue}c||(c=!0,f.enqueue(m("response.created",{type:"response.created",response:h("in_progress")})),f.enqueue(m("response.in_progress",{type:"response.in_progress",response:h("in_progress")})));let O=x.choices?.[0];if(!O)continue;let A=O.delta;if(A?.content){if(!l){l=!0;let E=i++,N={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(N),f.enqueue(m("response.output_item.added",{type:"response.output_item.added",output_index:E,item:N}))}f.enqueue(m("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:A.content}))}if(Array.isArray(A?.tool_calls))for(let E of A.tool_calls){if(E.id){u=E.id,p=i++;let N={id:E.id,type:"function_call",status:"in_progress",call_id:E.id,name:E.function?.name||"",arguments:""};d.push(N),f.enqueue(m("response.output_item.added",{type:"response.output_item.added",output_index:p,item:N}))}if(E.function?.arguments){f.enqueue(m("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:E.function.arguments}));let N=d.find($=>$.call_id===u);N&&(N.arguments+=E.function.arguments)}}O.finish_reason&&y(x)}}b||y({}),f.close()}catch(g){f.error(g)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",c="",l=-1,u="",p="",d="",m=-1,h="",f="",g=-1,_=0,b=!1,y=!1,k=!1,T=!1,S=null,v=[],R=(N,$)=>r.encode(`event: ${N}
|
|
36
|
+
data: ${JSON.stringify($)}
|
|
37
37
|
|
|
38
|
-
`),
|
|
39
|
-
`);D=
|
|
38
|
+
`),C=(N,$=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:N,model:s,output:$,usage:this.buildResponsesUsage()}),x=()=>{b||(b=!0,E.enqueue(R("response.created",{type:"response.created",response:C("in_progress")})),E.enqueue(R("response.in_progress",{type:"response.in_progress",response:C("in_progress")})))},O=(N,$)=>{E.enqueue(R("response.output_item.done",{type:"response.output_item.done",output_index:N,item:{...$,status:"completed"}}))},A=N=>{if(!T){if(T=!0,y){let $=v.find(D=>D.type==="message");$&&($.content=[{type:"output_text",text:i}],$.status="completed")}for(let $ of v)$.type==="function_call"&&($.status="completed");return R("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:N?{...this.buildResponsesUsage(N)}:this.buildResponsesUsage()}})}},E;return new ReadableStream({async start(N){E=N;try{let $=e.getReader(),D="";for(;;){let{done:L,value:F}=await $.read();if(L)break;D+=o.decode(F,{stream:!0});let J=D.split(`
|
|
39
|
+
`);D=J.pop()||"";for(let we of J){let B=we.trim();if(!B||B.startsWith("event:")||!B.startsWith("data:"))continue;let ie=B.slice(5).trim();if(ie==="[DONE]")continue;let K;try{K=JSON.parse(ie)}catch{continue}if(K.type==="message_start"&&(a=K.message?.id||a,x()),K.type==="content_block_start"){let I=K.content_block;if(S=I?.type||null,I?.type==="tool_use"){u=I.id||"",p=I.name||"",d="",m=_++;let Q={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};v.push(Q),E.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:m,item:Q}))}if(I?.type==="thinking"&&(h=I.thinking||"",!k)){k=!0,g=_++,f=`rs_${a}`;let Q={id:f,type:"reasoning",status:"in_progress",summary:[]};v.push(Q),E.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:g,item:Q}))}if(I?.type==="text"&&(i=I?.text||"",!y)){y=!0,l=_++,c=`${a}_msg`;let Q={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(Q),E.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:l,item:Q}))}}if(K.type==="content_block_delta"){let I=K.delta;if(I?.type==="text_delta"){if(!y){y=!0,l=_++,c=`${a}_msg`;let Q={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(Q),E.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:l,item:Q}))}i+=I.text||"",E.enqueue(R("response.output_text.delta",{type:"response.output_text.delta",item_id:c,output_index:l,content_index:0,delta:I.text||""}))}I?.type==="thinking_delta"&&(h+=I.thinking||"",E.enqueue(R("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:f||`rs_${a}`,output_index:g>=0?g:0,summary_index:0,delta:I.thinking||""}))),I?.type==="input_json_delta"&&(d+=I.partial_json||"",E.enqueue(R("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:m>=0?m:0,delta:I.partial_json||""})))}if(K.type==="content_block_stop"){if(S==="tool_use"&&u){E.enqueue(R("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:m,arguments:d}));let I=v.find(Q=>Q.call_id===u);I&&(I.arguments=d,I.status="completed"),I&&O(m,I)}if(S==="text"&&y){E.enqueue(R("response.output_text.done",{type:"response.output_text.done",item_id:c,output_index:l,content_index:0,text:i}));let I=v.find(Q=>Q.type==="message");I&&(I.content=[{type:"output_text",text:i}],O(l,I))}if(S==="thinking"&&k){let I=v.find(Q=>Q.type==="reasoning");I&&(I.summary=[{type:"summary_text",text:h}],O(g,I))}S=null}if(K.type==="message_delta"){let I=A(K.usage);I&&E.enqueue(I)}if(K.type==="message_stop"){let I=A();I&&E.enqueue(I),E.enqueue(r.encode(`data: [DONE]
|
|
40
40
|
|
|
41
|
-
`))}}}w();let B=A();B&&P.enqueue(B),D="",P.close()}catch(L){P.error(L)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(c=>c.type==="message"),o=e.output?.find(c=>c.type==="function_call"),r;t?.content?.length&&t?.content[0].annotations&&(r=t.content[0].annotations.map(c=>({type:"url_citation",url_citation:{url:c.url||"",title:c.title||"",content:"",start_index:c.start_index||0,end_index:c.end_index||0}}))),this.logger.debug({data:r,type:"url_citation"});let s=null,i=null,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 er,ee,vn=E(()=>{"use strict";er=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)}},ee=new er(100)});function xn(n,e){n&&qe.set(n,{...e,provider:n,capturedAt:Date.now()})}function Ct(n){let e=qe.get(n);return e?{...e}:void 0}function Cn(){return Array.from(qe.values()).map(n=>({...n}))}function dl(){try{if(!(0,_e.existsSync)(nr))return;let n=JSON.parse((0,_e.readFileSync)(nr,"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;qe.set(t.provider,t)}}catch{}}function Qs(){try{if(qe.size===0)return;(0,_e.existsSync)(tr)||(0,_e.mkdirSync)(tr,{recursive:!0}),(0,_e.writeFileSync)(nr,JSON.stringify(Array.from(qe.values()),null,2),"utf-8")}catch{}}function et(){Gs||(Gs=!0,dl(),Vs=setInterval(Qs,6e4),Vs.unref?.(),process.on("exit",Qs))}var _e,or,Ys,tr,nr,qe,Gs,Vs,tt=E(()=>{"use strict";_e=require("fs"),or=require("path"),Ys=require("@wengine-ai/claude-code-router-shared"),tr=(0,or.join)(Ys.HOME_DIR,"runtime"),nr=(0,or.join)(tr,"quota-store.json"),qe=new Map,Gs=!1,Vs=null});function ke(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!pl.test(e)))return e}function be(n){if(!n)return;if(typeof n=="object")return ke(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=ke(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return ke(e.slice(o+t.length))}var pl,nt=E(()=>{"use strict";pl=/^[A-Za-z0-9_-]+$/});function bl(){if(ot.size<=Xs)return;let n=[...ot.keys()].slice(0,ot.size-Xs);for(let e of n)ot.delete(e)}function Tl(){if(rt.size<=Zs)return;let n=[...rt].slice(0,rt.size-Zs);for(let e of n)rt.delete(e)}function vl(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 xl(n,e){let t;try{t=(0,ei.openSqliteDatabase)(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 Cl(n,e){let t;try{t=await(0,Sn.readdir)(n)}catch{return null}for(let o of t)for(let r of e){let s=(0,fe.join)(n,o,`${r}.json`);if((0,rr.existsSync)(s))try{let i=JSON.parse(await(0,Sn.readFile)(s,"utf8")),a=i?.meta?.workspacePath??i?.workspacePath;if(typeof a=="string"&&a.trim())return a.trim()}catch{}}return null}async function ti(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=ot.get(e);if(t)return t;let o=async()=>{let r=vl(e);if(r.length===0)return null;let s=(0,fe.join)(fl(),ml),i=(0,fe.join)(s,gl);if((0,rr.existsSync)(i)){let a=xl(i,r);if(a)return a}return Cl((0,fe.join)(s,hl),r)};try{let r=await o();if(!r&&!rt.has(e)){rt.add(e),Tl();for(let i=0;i<yl&&!r;i++)await kl(_l),r=await o()}if(!r||!(0,fe.isAbsolute)(r))return null;let s=(0,fe.normalize)(r);return ot.set(e,s),bl(),s}catch{return null}}var rr,Sn,qs,fe,ei,fl,ml,gl,hl,Xs,Zs,yl,_l,ot,rt,kl,ni=E(()=>{"use strict";rr=require("fs"),Sn=require("fs/promises"),qs=require("os"),fe=require("path"),ei=require("@wengine-ai/claude-code-router-shared"),fl=()=>process.env.CCR_ZCODE_DIR||(0,fe.join)((0,qs.homedir)(),".zcode"),ml="v2",gl="tasks-index.sqlite",hl="sessions",Xs=500,Zs=500,yl=3,_l=50,ot=new Map,rt=new Set,kl=n=>new Promise(e=>setTimeout(e,n))});function ii(n){return typeof n=="string"&&n.length<=Sl}function Rl(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of si){let{value:t}=Rn(n,e);if(!ii(t))continue;let o=ke(t);if(o)return o}}function El(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 Pl(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 Rn(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 oi(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 St(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function sr(n,e,t=!0){let o=be(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function ar(n){return typeof n=="string"&&wl.includes(n)}function Fl(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Ue(n){if(ar(n?.clientType))return n.clientType;let e=Pl(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=El(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(Rn(n,wn.CCR_PROJECT_HEADER).present||Rn(n,"x-session-affinity").present)return"pi";if(Fl(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 cr(n){return ir[n]}function Ul(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,ri.randomUUID)();return n.__ccrRequestScopeId=e,e}function Re(n,e={}){let t=Ue(n),o=cr(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Ul(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,oi(n,wn.CCR_PROJECT_HEADER),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let i of si)oi(n,i);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function ai(){}var ri,wn,si,Sl,wl,Ol,Al,Il,Ml,Nl,$l,Ll,Dl,ir,st=E(()=>{"use strict";ri=require("node:crypto"),wn=require("@wengine-ai/claude-code-router-shared");nt();si=["x-session-affinity","x-session-id","x-litellm-session-id"],Sl=256;wl=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Ol={type:"claude-code",createContext(n){return sr(n,"claude-code")}},Al={type:"zcode",createContext(n){return sr(n,"zcode")}},Il={type:"pi",createContext(n){let e=Rn(n,wn.CCR_PROJECT_HEADER),t=Rl(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||be(n?.body?.metadata?.user_id),o=ii(t)?t:void 0;return{...St("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Ml={type:"qwen-code",createContext(n){return sr(n,"qwen-code")}},Nl={type:"opencode",createContext(){return St("opencode")}},$l={type:"codex",createContext(){return St("codex")}},Ll={type:"api",createContext(){return St("api")}},Dl={type:"unknown",createContext(){return St("unknown")}},ir={"claude-code":Ol,zcode:Al,pi:Il,"qwen-code":Ml,opencode:Nl,codex:$l,api:Ll,unknown:Dl}});function se(n,e,t,o){let r=lr(e,t);if(r.code==="model_unhealthy"){let a=Y(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=pi[r.code]||502;throw new ne(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:i})}function An(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 Et(n){let e=An(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 zl(n,e){if(!e||!n)return null;let t=An(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=Et(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let i=An(r);if(i&&t.includes(i))return s}return null}function Bl(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function En(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 Rt(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 lr(n,e){let t=En(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(!j().isAvailable(s.name,String(i)))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let l=Ct(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 Y(n,e,t,o,r,s,i){let a=En(n);if(!a)return i?null:n;let{providerName:l,routeModel:c}=a,u=Rt(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let p=Ve(),m=p.getPromotion(l,c,o,e);if(m){let h=En(m);if(h){let g=Rt(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=Ve(),m=p.getPromotion(l,c,o,e);if(m){let h=En(m);if(h){let g=Rt(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}if(!t&&!j().isAvailable(u.provider.name,u.model))return null;let d=Ct(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 te(n,e,t,o,r,s){let i=j(),a=[t?.[n],o?.[n]];for(let l of a)if(!(!Array.isArray(l)||l.length===0))for(let c of l){let u=Y(c,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Jl(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 ur(n){let e=An(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 fi(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Bl(e))}function mi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Wl(n,e,t,o,r,s,i,a,l,c,u,d){let p=n.clientContext,m=p?.longContextThreshold??t.longContextThreshold??l??6e4,h=fi(e,r,p),g=n.modelFamily,f=mi(p,t,c),_=p?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||h>f)&&t.extendedContext){let b=Y(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?te("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=se(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?Y(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?te("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=se(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=Y(t.webSearch,o,!1,"webSearch",a,d,u);if(b)return{model:b,scenarioType:"webSearch",isFallback:!1};let T=a?te("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=se(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=Y(t.think,o,!1,"think",a,d,u);if(b)return{model:b,scenarioType:"think",isFallback:!1};let T=a?te("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=se(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=Y(t.default,o,!1,"default",a,d,u);if(b)return{model:b,scenarioType:"default",isFallback:!1};let T=a?te("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=se(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 Yl(){if(je.size<=ci)return;let n=[...je.keys()].slice(0,je.size-ci);for(let e of n)je.delete(e)}function Xl(){if(it.size<=li)return;let n=[...it].slice(0,it.size-li);for(let e of n)it.delete(e)}var di,Pn,In,On,le,pi,ne,Te,wt,Hl,Kl,Pt,je,ci,it,li,Gl,Vl,Ql,ui,dr,at=E(()=>{"use strict";di=require("tiktoken");vn();Pn=require("fs/promises"),In=require("fs/promises"),On=require("path"),le=require("@wengine-ai/claude-code-router-shared");ce();tt();hn();Tn();nt();ni();st();pi={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},ne=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||pi[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};Te=(0,di.get_encoding)("cl100k_base"),wt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=Te.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{s.type==="text"?o+=Te.encode(s.text).length:s.type==="tool_use"?o+=Te.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(o+=Te.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?o+=Te.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=Te.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=Te.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=Te.encode(r.name+r.description).length),r.input_schema&&(o+=Te.encode(JSON.stringify(r.input_schema)).length)}),o},Hl=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 ne(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await dr(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await ti(n.sessionId);s&&(0,le.isZcodeProjectTakeoverActive)(s)&&(r=(0,le.getClaudeProjectId)(s))}if(r){n.projectId=r;let s=(0,On.join)(le.HOME_DIR,r,"config.json");if(!t&&n.sessionId){let i=(0,On.join)(le.HOME_DIR,r,`${n.sessionId}.json`);try{let a=JSON.parse(await(0,Pn.readFile)(i,"utf8"));if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch{}}try{let i=JSON.parse(await(0,Pn.readFile)(s,"utf8"));if(t&&(typeof i?.projectPath!="string"||(0,le.getClaudeProjectId)(i.projectPath)!==o))throw new ne(`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 ne)throw i;if(t&&i?.code==="ENOENT")throw new ne(`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 ne(`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})}}}};Kl=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}=Et(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=Wl(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=Y(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?te("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:zl(n.body.model,a?.models);if(_){let v=Y(_,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?te("modelMapping",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};if(s){let x=se(n,_,i,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let k=n.clientContext,y=fi(e,o,k),b=mi(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=Y(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?te("extendedContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};if(s){let x=se(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=Y(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?te("longContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};if(s){let x=se(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=Y(a.background,i,!1,"background",l,d,s);if(v)return{model:v,scenarioType:"background"};let S=l?te("background",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};if(s){let x=se(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=Y(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?te("webSearch",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};if(s){let x=se(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=Y(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?te("think",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};if(s){let x=se(n,a.think,i,"think");if(x)return{model:x,scenarioType:"think"}}}if(a?.default){let v=Y(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?te("default",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};let x=Y(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=se(n,a?.default||n.body.model,i,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Pt=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)&&Re(n,o.getAll());let s=await Hl(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??ee.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(0,Pn.readFile)(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=wt(d,p,m),n.tokenCount=k;let y,b=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(b)try{y=await require(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 Kl(n,k,o,u,s,!!s);y=S.model,n.scenarioType=S.scenarioType}let{family:T}=Et(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&&Jl(n)&&!ur(y))if(v.includes(y))n.scenarioType="image";else{let S=v.map(x=>Y(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?te("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=se(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=Ws(n,y,{threshold:Number(i?.concurrencyThreshold)||3,fallbackModels:x,resolve:w=>Y(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 ne)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),c){let f=n.sessionId||n.clientContext?.stableSessionId;throw new ne(`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"}},je=new Map,ci=1e3,it=new Set,li=1e3,Gl=3,Vl=50,Ql=n=>new Promise(e=>setTimeout(e,n));ui=async n=>{let e=await(0,In.opendir)(le.CLAUDE_PROJECTS_DIR),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let i=(0,On.join)(le.CLAUDE_PROJECTS_DIR,s,`${n}.jsonl`);try{return(await(0,In.stat)(i)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},dr=async n=>{let e=ke(n);if(!e)return null;if(je.has(e))return je.get(e)||null;try{let t=await ui(e);if(!t&&!it.has(e)){it.add(e),Xl();for(let o=0;o<Gl&&!t;o++)await Ql(Vl),t=await ui(e)}return t?(je.set(e,t),Yl(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function Ot(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
41
|
+
`))}}}x();let W=A();W&&E.enqueue(W),D="",E.close()}catch($){E.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(l=>l.type==="message"),o=e.output?.find(l=>l.type==="function_call"),r;t?.content?.length&&t?.content[0].annotations&&(r=t.content[0].annotations.map(l=>({type:"url_citation",url_citation:{url:l.url||"",title:l.title||"",content:"",start_index:l.start_index||0,end_index:l.end_index||0}}))),this.logger.debug({data:r,type:"url_citation"});let s=null,a=null,i=null;if(t&&t.reasoning&&(i={content:t.reasoning}),t&&t.content){let l=[],u=[];if(t.content.forEach(p=>{if(p.type==="output_text")l.push(p.text||"");else if(p.type==="output_image"){let d=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});d&&u.push(d)}else if(p.type==="output_image_base64"){let d=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});d&&u.push(d)}}),u.length>0){let p=[];l.length>0&&p.push({type:"text",text:l.join("")}),p.push(...u),s=p}else s=l.join("")}return o&&(a=[{id:o.call_id||o.id,function:{name:o.name,arguments:o.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:a,thinking:i,annotations:r},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var kr,ne,Ln=w(()=>{"use strict";kr=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)}},ne=new kr(100)});function Dn(n,e){n&&st.set(n,{...e,provider:n,capturedAt:Date.now()})}function Nt(n){let e=st.get(n);return e?{...e}:void 0}function Fn(){return Array.from(st.values()).map(n=>({...n}))}function tu(){try{if(!(0,ve.existsSync)(vr))return;let n=JSON.parse((0,ve.readFileSync)(vr,"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;st.set(t.provider,t)}}catch{}}function wi(){try{if(st.size===0)return;(0,ve.existsSync)(Tr)||(0,ve.mkdirSync)(Tr,{recursive:!0}),(0,ve.writeFileSync)(vr,JSON.stringify(Array.from(st.values()),null,2),"utf-8")}catch{}}function it(){Si||(Si=!0,tu(),Ri=setInterval(wi,6e4),Ri.unref?.(),process.on("exit",wi))}var ve,xr,Pi,Tr,vr,st,Si,Ri,at=w(()=>{"use strict";ve=require("fs"),xr=require("path"),Pi=require("@wengine-ai/claude-code-router-shared"),Tr=(0,xr.join)(Pi.HOME_DIR,"runtime"),vr=(0,xr.join)(Tr,"quota-store.json"),st=new Map,Si=!1,Ri=null});function xe(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!nu.test(e)))return e}function Ce(n){if(!n)return;if(typeof n=="object")return xe(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=xe(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return xe(e.slice(o+t.length))}var nu,ct=w(()=>{"use strict";nu=/^[A-Za-z0-9_-]+$/});function uu(){if(lt.size<=Ei)return;let n=[...lt.keys()].slice(0,lt.size-Ei);for(let e of n)lt.delete(e)}function du(){if(ut.size<=Oi)return;let n=[...ut].slice(0,ut.size-Oi);for(let e of n)ut.delete(e)}function pu(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 fu(n,e){let t;try{t=(0,Ii.openSqliteDatabase)(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 a=o.get(r,r)?.workspace_path;if(typeof a=="string"&&a.trim())return a.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function mu(n,e){let t;try{t=await(0,Un.readdir)(n)}catch{return null}for(let o of t)for(let r of e){let s=(0,ge.join)(n,o,`${r}.json`);if((0,Cr.existsSync)(s))try{let a=JSON.parse(await(0,Un.readFile)(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Mi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=lt.get(e);if(t)return t;let o=async()=>{let r=pu(e);if(r.length===0)return null;let s=(0,ge.join)(ou(),ru),a=(0,ge.join)(s,su);if((0,Cr.existsSync)(a)){let i=fu(a,r);if(i)return i}return mu((0,ge.join)(s,iu),r)};try{let r=await o();if(!r&&!ut.has(e)){ut.add(e),du();for(let a=0;a<au&&!r;a++)await lu(cu),r=await o()}if(!r||!(0,ge.isAbsolute)(r))return null;let s=(0,ge.normalize)(r);return lt.set(e,s),uu(),s}catch{return null}}var Cr,Un,Ai,ge,Ii,ou,ru,su,iu,Ei,Oi,au,cu,lt,ut,lu,Ni=w(()=>{"use strict";Cr=require("fs"),Un=require("fs/promises"),Ai=require("os"),ge=require("path"),Ii=require("@wengine-ai/claude-code-router-shared"),ou=()=>process.env.CCR_ZCODE_DIR||(0,ge.join)((0,Ai.homedir)(),".zcode"),ru="v2",su="tasks-index.sqlite",iu="sessions",Ei=500,Oi=500,au=3,cu=50,lt=new Map,ut=new Set,lu=n=>new Promise(e=>setTimeout(e,n))});function Fi(n){return typeof n=="string"&&n.length<=gu}function hu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Di){let{value:t}=jn(n,e);if(!Fi(t))continue;let o=xe(t);if(o)return o}}function _u(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 bu(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 jn(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 $i(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 $t(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Sr(n,e,t=!0){let o=Ce(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function wr(n){return typeof n=="string"&&yu.includes(n)}function Pu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function ze(n){if(wr(n?.clientType))return n.clientType;let e=bu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=_u(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(jn(n,Hn.CCR_PROJECT_HEADER).present||jn(n,"x-session-affinity").present)return"pi";if(Pu(t,o))return"zcode";let a=t["x-anthropic-billing-header"];if(typeof a=="string"&&a.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let i=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(i)?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(i).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Pr(n){return Rr[n]}function Eu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,Li.randomUUID)();return n.__ccrRequestScopeId=e,e}function Ee(n,e={}){let t=ze(n),o=Pr(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Eu(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,$i(n,Hn.CCR_PROJECT_HEADER),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Di)$i(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Ui(){}var Li,Hn,Di,gu,yu,ku,Tu,vu,xu,Cu,Su,Ru,wu,Rr,dt=w(()=>{"use strict";Li=require("node:crypto"),Hn=require("@wengine-ai/claude-code-router-shared");ct();Di=["x-session-affinity","x-session-id","x-litellm-session-id"],gu=256;yu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];ku={type:"claude-code",createContext(n){return Sr(n,"claude-code")}},Tu={type:"zcode",createContext(n){return Sr(n,"zcode")}},vu={type:"pi",createContext(n){let e=jn(n,Hn.CCR_PROJECT_HEADER),t=hu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||Ce(n?.body?.metadata?.user_id),o=Fi(t)?t:void 0;return{...$t("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},xu={type:"qwen-code",createContext(n){return Sr(n,"qwen-code")}},Cu={type:"opencode",createContext(){return $t("opencode")}},Su={type:"codex",createContext(){return $t("codex")}},Ru={type:"api",createContext(){return $t("api")}},wu={type:"unknown",createContext(){return $t("unknown")}},Rr={"claude-code":ku,zcode:Tu,pi:vu,"qwen-code":xu,opencode:Cu,codex:Su,api:Ru,unknown:wu}});function ce(n,e,t,o){let r=Er(e,t);if(r.code==="model_unhealthy"){let i=X(e,t,!0);if(i)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),i}let s=n.sessionId||n.clientContext?.stableSessionId,a=Ji[r.code]||502;throw new re(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function Wn(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 Ft(n){let e=Wn(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 Iu(n,e){if(!e||!n)return null;let t=Wn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=Ft(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=Wn(r);if(a&&t.includes(a))return s}return null}function Mu(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function zn(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 Lt(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 Er(n,e){let t=zn(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(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!j().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let c=Nt(s.name);if(c){let l=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,u=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(l||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function X(n,e,t,o,r,s,a){let i=zn(n);if(!i)return a?null:n;let{providerName:c,routeModel:l}=i,u=Lt(e,c,l);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=et(),m=d.getPromotion(c,l,o,e);if(m){let h=zn(m);if(h){let f=Lt(e,h.providerName,h.routeModel);if(f)return`${f.provider.name},${f.model}`}d.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=et(),m=d.getPromotion(c,l,o,e);if(m){let h=zn(m);if(h){let f=Lt(e,h.providerName,h.routeModel);if(f)return`${f.provider.name},${f.model}`}d.clear(c,l,o)}}if(!t&&!j().isAvailable(u.provider.name,u.model,u.provider.apiKey?.startsWith("ccr-managed-")===!0||u.provider.api_key?.startsWith("ccr-managed-")===!0))return null;let p=Nt(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,m=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||m)return null}return`${u.provider.name},${u.model}`}function oe(n,e,t,o,r,s){let a=j(),i=[t?.[n],o?.[n]];for(let c of i)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let u=X(l,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Nu(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 Ut(n){let e=Wn(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 Wi(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Mu(e))}function Ki(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function $u(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,m=d?.longContextThreshold??t.longContextThreshold??c??6e4,h=Wi(e,r,d),f=n.modelFamily,g=Ki(d,t,l),_=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||h>g)&&t.extendedContext){let k=X(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${g}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?oe("extendedContext",o,t.fallback,a,f,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${g}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let S=ce(n,t.extendedContext,o,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(h>m&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?X(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?oe("longContext",o,t.fallback,a,f,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 S=ce(n,t.longContext,o,"longContext");if(S)return{model:S,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(k=>k.type?.startsWith("web_search"))&&t.webSearch){let k=X(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let T=i?oe("webSearch",o,t.fallback,a,f,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let S=ce(n,t.webSearch,o,"webSearch");if(S)return{model:S,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let k=X(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let T=i?oe("think",o,t.fallback,a,f,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let S=ce(n,t.think,o,"think");if(S)return{model:S,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let k=X(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let T=i?oe("default",o,t.fallback,a,f,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let S=ce(n,t.default,o,"default");if(S)return{model:S,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function ju(){if(Be.size<=ji)return;let n=[...Be.keys()].slice(0,Be.size-ji);for(let e of n)Be.delete(e)}function Hu(){if(pt.size<=Hi)return;let n=[...pt].slice(0,pt.size-Hi);for(let e of n)pt.delete(e)}var Bi,Bn,Kn,Jn,ue,Ji,re,he,Dt,Au,Lu,jt,Be,ji,pt,Hi,Du,Fu,Uu,zi,Or,Je=w(()=>{"use strict";Bi=require("tiktoken");Ln();Bn=require("fs/promises"),Kn=require("fs/promises"),Jn=require("path"),ue=require("@wengine-ai/claude-code-router-shared");le();at();On();$n();ct();Ni();dt();Ji={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},re=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Ji[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};he=(0,Bi.get_encoding)("cl100k_base"),Dt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=he.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=he.encode(s.text).length;else if(s.type==="tool_use")o+=he.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=he.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=he.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=he.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=he.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=he.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=he.encode(r.name+r.description).length),r.input_schema&&(o+=he.encode(JSON.stringify(r.input_schema)).length)}),o},Au=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 re(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Or(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Mi(n.sessionId);s&&(0,ue.isZcodeProjectTakeoverActive)(s)&&(r=(0,ue.getClaudeProjectId)(s))}if(r){n.projectId=r;let s=(0,Jn.join)(ue.HOME_DIR,r,"config.json");if(!t&&n.sessionId){let a=(0,Jn.join)(ue.HOME_DIR,r,`${n.sessionId}.json`);try{let i=JSON.parse(await(0,Bn.readFile)(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch{}}try{let a=JSON.parse(await(0,Bn.readFile)(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||(0,ue.getClaudeProjectId)(a.projectPath)!==o))throw new re(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch(a){if(a instanceof re)throw a;if(t&&a?.code==="ENOENT")throw new re(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!a||a.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new re(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${a.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};Lu=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,p=!s,d=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>`,""),d=v[1])}let{family:m,extended:h,isCcrAlias:f}=Ft(n.body.model),g=i?.families?.[m||""];if(g&&i?.enableFamilyRouting){n.log.info(`Using model family routing for: ${m}${h?" (1M)":""}`),n.modelFamily=m,n.familyFallback=g.fallback;let v=$u(n,e,g,a,o,h,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=X(n.body.model,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let R=c?oe("default",a,void 0,u,void 0,s):null;if(R)return n.log.info(`Using fallback for explicit model: ${R}`),{model:R,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let _=f&&!i?.enableFamilyRouting?null:Iu(n.body.model,i?.models);if(_){let v=X(_,a,!1,"modelMapping",c,p,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${_}`),{model:v,scenarioType:"modelMapping"};let R=c?oe("modelMapping",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"modelMapping"};if(s){let C=ce(n,_,a,"modelMapping");if(C)return{model:C,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let b=n.clientContext,y=Wi(e,o,b),k=Ki(b,void 0,i?.extendedContextThreshold);if(y>k&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${y}, estimated: ${e}, threshold: ${k}`);let v=X(i.extendedContext,a,!1,"extendedContext",c,p,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let R=c?oe("extendedContext",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"extendedContext"};if(s){let C=ce(n,i.extendedContext,a,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext"}}}let T=b?.longContextThreshold??i?.longContextThreshold??6e4;if(y>T&&i?.longContext){n.log.info(`Using long context model due to token count: ${y}, estimated: ${e}, threshold: ${T}`);let v=X(i.longContext,a,!1,"longContext",c,p,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let R=c?oe("longContext",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"longContext"};if(s){let C=ce(n,i.longContext,a,"longContext");if(C)return{model:C,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let v=X(i.background,a,!1,"background",c,p,s);if(v)return{model:v,scenarioType:"background"};let R=c?oe("background",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"background"};if(s){let C=ce(n,i.background,a,"background");if(C)return{model:C,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&i?.webSearch){let v=X(i.webSearch,a,!1,"webSearch",c,p,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let R=c?oe("webSearch",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"webSearch"};if(s){let C=ce(n,i.webSearch,a,"webSearch");if(C)return{model:C,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=X(i.think,a,!1,"think",c,p,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let R=c?oe("think",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"think"};if(s){let C=ce(n,i.think,a,"think");if(C)return{model:C,scenarioType:"think"}}}if(i?.default){let v=X(i.default,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let R=c?oe("default",a,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"default"};let C=X(i.default,a,!0,"default",c,p,s);if(C)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:C,scenarioType:"default"}}if(s){let v=ce(n,i?.default||n.body.model,a,"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)&&Ee(n,o.getAll());let s=await Au(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,c=o.get("providers")||[],l=!!s;n.enableFallback=i,n.strictProjectRouting=l,n.fallbackConfig=l?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??ne.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:m}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&d.length>1&&d[1]?.text?.includes("<env>")){let f=await(0,Bn.readFile)(h,"utf-8");d[1].text=`${f}<env>${d[1].text.split("<env>").pop()}`}try{let[f,g]=n.body.model.split(","),_=t.tokenizerService?.getTokenizerConfigForModel(f,g),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:m},_,f)).tokenCount:b=Dt(p,d,m),n.tokenCount=b;let y,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{y=await require(k)(n,o.getAll(),{event:r})}catch(R){n.log.error(`failed to load custom router: ${R.message}`)}if(y)n.scenarioType="default";else{let R=await Lu(n,b,o,u,s,!!s);y=R.model,n.scenarioType=R.scenarioType}let{family:T}=Ft(n.originalModel||n.body.model),S=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[S?.image,a?.image].filter((R,C,x)=>!!R&&x.indexOf(R)===C);if(v.length>0&&Nu(n)&&!Ut(y))if(v.includes(y))n.scenarioType="image";else{let R=v.map(C=>X(C,c,!1,"image",i,!l,l)).find(C=>!!C);if(R)n.log.info(`Using image model fallback for ${y}`),y=R,n.scenarioType="image";else{let C=i?oe("image",c,S?.fallback,n.fallbackConfig,T||void 0,l):null;if(C)n.log.info(`Using image fallback model: ${C}`),y=C,n.scenarioType="image";else if(l){let x=ce(n,v[0],c,"image");x&&(y=x,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${y}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof y=="string"&&y.trim()){let R=n.scenarioType||"default",C=[...(n.familyFallback||{})[R]||[],...(n.fallbackConfig||{})[R]||[]];y=xi(n,y,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:C,resolve:x=>X(x,c,!1,R,i,!l,l),log:x=>n.log.info(x)})}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(f){if(f instanceof re)throw f;if(n.log.error(`Error in router middleware: ${f.message}`),l){let g=n.sessionId||n.clientContext?.stableSessionId;throw new re(`Project routing error: router failure in project mode. ${f.message}. Session: "${g||"unknown"}".`,{sessionId:g,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Be=new Map,ji=1e3,pt=new Set,Hi=1e3,Du=3,Fu=50,Uu=n=>new Promise(e=>setTimeout(e,n));zi=async n=>{let e=await(0,Kn.opendir)(ue.CLAUDE_PROJECTS_DIR),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=(0,Jn.join)(ue.CLAUDE_PROJECTS_DIR,s,`${n}.jsonl`);try{return(await(0,Kn.stat)(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Or=async n=>{let e=xe(n);if(!e)return null;if(Be.has(e))return Be.get(e)||null;try{let t=await zi(e);if(!t&&!pt.has(e)){pt.add(e),Hu();for(let o=0;o<Du&&!t;o++)await Uu(Fu),t=await zi(e)}return t?(Be.set(e,t),ju(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function Ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
42
42
|
`):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
|
|
43
|
-
${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function
|
|
44
|
-
`).some(
|
|
45
|
-
`).filter(c=>c.startsWith("data:")&&c.trim().length>5).length===0){o.releaseLock();let c=i.length<500?i:i.slice(0,500);throw G(`Provider ${t} returned streaming response with no SSE data lines: ${c}`,400,"provider_response_error")}let l=new ReadableStream({start:c=>{for(let d of s)c.enqueue(d);let u=()=>{o.read().then(({done:d,value:p})=>{d?c.close():(c.enqueue(p),u())}).catch(d=>c.error(d))};u()},cancel:()=>{o.cancel()}});return new Response(l,{headers:e.headers,status:e.status,statusText:e.statusText})}async function ql(n,e,t,o,r){let s=n.scenarioType||"default",i=n.familyFallback,a=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),c=j(),u=n.provider||"",d=n.body.model||"",p=new Set,m=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&Mn(r.rawBody)||r?.message&&Mn(r.message);if(u&&d&&(m?(c.markRateLimited(u,d,120,r?.message),n.log.warn(`Primary model ${u},${d} rate-limited, will try fallbacks`)):c.recordFailure(u,d,r?.message),p.add(`${u},${d}`),t.recordUsage?.({provider:u,model:d,originalModel:n.originalModel||d,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let g=k=>{let[y,...b]=k.split(","),T=y?.trim(),C=b.join(",").trim();return!T||!C?null:{provider:T,model:C,key:`${T},${C}`}},f=[];if(a){let k=i?.[s];if(Array.isArray(k)&&k.length>0)f.push({name:`${a}/${s}`,models:k});else{let y=n.strictProjectRouting;n.log.warn(`No ${a} fallback configured for ${s}; ${y?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&f.push({name:`global/${s}`,models:l[s]}),f.length===0&&s!=="image"&&n.body?.messages?.some(b=>b.role==="user"&&Array.isArray(b.content)&&b.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(C=>C.type==="image"||C.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),f.push({name:"global/image (auto-detected)",models:l.image})),f.length===0)return null;let _=f.reduce((k,y)=>k+y.models.length,0);n.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${f.length} fallback stage(s)`);for(let k of f){n.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let y of k.models){let b=g(y);if(!b){n.log.warn(`Fallback model '${y}' is invalid, skipping`);continue}if(p.has(b.key))continue;p.add(b.key);let T=t.providerService.getProviders(),C=Rt(T,b.provider,b.model);if(!C){n.log.warn(`Fallback model ${y} is not configured or provider is disabled, skipping`);continue}let v=C.provider.name,S=C.model;if(!c.isAvailable(v,S)){n.log.warn(`Fallback model ${y} unavailable (fail pool), skipping`);continue}let x;for(let w=1;w<=2;w++)try{n.log.info(`Trying fallback model: ${v},${S}${w>1?" (retry)":""}`);let R={...n.body};R.model=S;let A={...n,provider:v,body:R},P=C.provider,{requestBody:N,config:L,bypass:D}=await yi(R,P,o,n.headers,{req:A}),B=await _i(N,L,P,t,D,o,{req:A});try{P?.baseUrl&&B?.headers&&vt(v,P.baseUrl,B.headers)}catch{}let $=await ki(N,B,P,o,D,{req:A,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1});return $=await hi(R,$,v),n.log.info(`Fallback model ${v},${S} succeeded`),c.recordSuccess(v,S),u&&d&&!n.strictProjectRouting&&(Ve().promote(u,d,s,v,S),n.log.info(`Promoted fallback model ${v},${S} for ${u},${d}:${s}`),m?n.log.info(`Rate-limited original model ${u},${d} already marked unavailable with cooldown`):(c.forceOpen(u,d,r?.message),n.log.info(`Marked original model ${u},${d} as unavailable`))),n.provider=v,n.body=R,Js(n,`${v},${S}`),bi($,e,R,t)}catch(R){if(x=R,w===1){n.log.warn(`Fallback model ${v},${S} failed, retrying once: ${R.message}`);continue}}c.recordFailure(v,S,x?.message),n.log.warn(`Fallback model ${v},${S} failed after retry: ${x?.message}`),t.recordUsage?.({provider:v,model:S,originalModel:n.originalModel||d||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:x?.message||String(x),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function yi(n,e,t,o,r){let s=JSON.parse(JSON.stringify(n)),i=s?.system;if(typeof i=="string"&&i.includes("cch="))s.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let c=0;c<i.length;c++){let u=i[c],d=typeof u=="string"?u:u?.text??"";if(d.includes("cch=")){let p=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof u=="string"?i[c]=p:typeof u?.text=="string"&&(u.text=p)}}let a={},l=!1;if(l=eu(e,t,n),l&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],a.headers=o),!l&&typeof t.transformRequestOut=="function"){let c=await t.transformRequestOut(s);c.body?(s=c.body,a=c.config||{}):s=c}if(!l&&e.transformer?.use?.length)for(let c of e.transformer.use){if(!c||typeof c.transformRequestIn!="function")continue;let u=await c.transformRequestIn(s,e,r);u.body?(s=u.body,a={...a,...u.config}):s=u}if(!l&&e.transformer?.[n.model]?.use?.length)for(let c of e.transformer[n.model].use)!c||typeof c.transformRequestIn!="function"||(s=await c.transformRequestIn(s,e,r));return{requestBody:s,config:a,bypass:l}}function eu(n,e,t){return e.endPoint==="/v1/chat/completions"&&Array.isArray(t?.system)?!1:n.transformer?.use?.length===1&&n.transformer.use[0].name===e.name&&(!n.transformer?.[t.model]?.use.length||n.transformer?.[t.model]?.use.length===1&&n.transformer?.[t.model]?.use[0].name===e.name)}function tu(n,e){if(e?.clientType!=="pi")return;let t=e?.clientContext?.stableSessionId;if(!(typeof t!="string"||!t)){for(let o of Object.keys(n))o.toLowerCase()==="x-litellm-session-id"&&delete n[o];n["x-litellm-session-id"]=t}}function nu(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function _i(n,e,t,o,r,s,i){let a=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let u=o.configService.get("API_TIMEOUT_MS");u&&(e.TIMEOUT=typeof u=="string"?parseInt(u,10):u)}if(r&&typeof s.auth=="function"){let u=await s.auth(n,t);if(u.body){n=u.body;let d=e.headers||{};u.config?.headers&&(d={...d,...u.config.headers},delete d.host,delete u.config.headers),e={...e,...u.config,headers:d}}else n=u}let l={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};tu(l,i?.req);for(let u in l)(l[u]==="undefined"||["authorization","Authorization"].includes(u)&&l[u]?.includes("undefined"))&&delete l[u];pn(o.configService)&&ws(o.log,i.req.id,{url:String(a),headers:l,body:n});let c=await Os(a,n,{...e,headers:JSON.parse(JSON.stringify(l)),httpsProxy:pe(o.configService,t)},i,o.log);if(!c.ok){let u=await c.text();o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${c.status}): ${u}`);let d=G(`Error from provider(${t.name},${n.model}: ${c.status}): ${u}`,c.status,"provider_response_error");throw d.isRateLimit=c.status===429||Mn(u),d.rawBody=u,d}if(c.ok){let u=c.headers.get("content-type")||"",d=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${d} contentType=${u} ok=${c.ok} status=${c.status} hasBody=${!!c.body}`),!d||u.includes("application/json")){let p=c.clone(),m="";try{if(m=await p.text(),!m||m.trim()==="")throw new SyntaxError("Empty JSON body");if(xt(m))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${u}, skipping JSON validation`),c;let h=JSON.parse(m);if(h&&typeof h=="object"&&h.error&&(typeof h.error=="string"||typeof h.error=="object"&&Object.keys(h.error).length>0)){o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${c.status}): ${m}`);let f=Mn(m),_=G(`Error from provider(${t.name},${n.model}: ${c.status}): ${m}`,400,"provider_response_error");throw _.isRateLimit=f,_.rawBody=m,_}}catch(h){if(h instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${m}"`);let g=G(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw g.rawBody=m,g}throw h}}}if(!n.stream&&pn(o.configService)){let d=await c.clone().text();Es(o.log,i.req.id,{status:c.status,headers:Object.fromEntries(c.headers.entries()),body:d})}return c}async function ki(n,e,t,o,r,s){let i=e;if(!r&&t.transformer?.use?.length)for(let a of Array.from(t.transformer.use).reverse())!a||typeof a.transformResponseOut!="function"||(i=await a.transformResponseOut(i,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let a of Array.from(t.transformer[n.model].use).reverse())!a||typeof a.transformResponseOut!="function"||(i=await a.transformResponseOut(i,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),i=await o.transformResponseIn(i,s)),s?.isCodexOnMessagesEndpoint)try{i=await new Ze().transformResponseIn(i,{...s,provider:t})}catch(a){console.error("Failed to apply Responses API conversion for codex client:",a)}return i}async function bi(n,e,t,o){n.ok||e.code(n.status);let r=Ks(n);if(!r){let s=await Ce(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let i=await Se(n);n=i.response,i.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&pn(o.configService)){let[s,i]=n.body.tee(),a=Rs(o.configService);return Ps(s,o.log,e.request.id,a),e.send(i)}return e.send(n.body)}else return U(n)}function Mn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function ou(n){try{return new URL(n),!0}catch{return!1}}var Zl,Ti,Nn=E(()=>{"use strict";As();un();bt();Do();ce();Xe();hn();Tn();qo();q();at();ae();Zl=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Ti=async n=>{n.get("/",async()=>({message:"LLMs API",version:gn})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:j().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>gi(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:i,models:a}=t.body;if(!r?.trim())throw G("Provider name is required",400,"invalid_request");if(!s||!ou(s))throw G("Valid base URL is required",400,"invalid_request");if(!i?.trim())throw G("API key is required",400,"invalid_request");if(!a||!Array.isArray(a)||a.length===0)throw G("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw G(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw G("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw G("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw G("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw G("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var me,$n=E(()=>{"use strict";me=class{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let a=this.transformerService.getTransformer(i[0]);if(a)return new a(i[1])}if(typeof i=="string"){let a=this.transformerService.getTransformer(i);return typeof a=="function"?new a:a}}).filter(i=>typeof i<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let a=this.transformerService.getTransformer(i[0]);if(a)return new a(i[1])}if(typeof i=="string"){let a=this.transformerService.getTransformer(i);return typeof a=="function"?new a:a}}).filter(i=>typeof i<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let i=new s({level:r});o.use=[i,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let i=`${o.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let i=`${o.name},${s}`,a={provider:o.name,model:s,fullModel:i};this.modelRoutes.set(i,a),this.modelRoutes.has(s)||this.modelRoutes.set(s,a)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(i=>i.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var we,Ln,vi,ru,xi,ct=E(()=>{"use strict";we=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",Ln=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,vi=["low","medium","high"],ru={none:"none",off:"none",disabled:"none",min:"low",minimal:"low",light:"low",low:"low",medium:"medium",mid:"medium",high:"high",xhigh:"max",max:"max",maximum:"max",ultra:"max",ultracode:"max"},xi=n=>{if(typeof n=="string")return ru[n.trim().toLowerCase()]}});var Ci,Si=E(()=>{Ci=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function su(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Ri(n){let e=[],t=[],o=p=>{if(typeof p=="string"){t.push({type:"text",text:p});return}Array.isArray(p)&&p.forEach(m=>{if(typeof m=="string"){t.push({type:"text",text:m});return}m&&typeof m=="object"&&m.type==="text"&&m.text&&t.push({...m})})},r=()=>{let p=new Map;for(let m=0;m<t.length;m++){let h=t[m],g=h?.text??JSON.stringify(h),f=p.get(g);if(f===void 0){p.set(g,m);continue}!t[f]?.cache_control&&h?.cache_control&&(t[f]=h),t.splice(m,1),m--}};n.messages.forEach(p=>{p.role==="system"?o(p.content):e.push(p)}),r();let s=[];for(let p=0;p<e.length;p++){let m=e[p];if(m.role==="tool"){let h=m.content;try{typeof m.content=="string"&&(h=JSON.parse(m.content))}catch{}h!=null&&typeof h!="object"&&typeof h!="string"&&(h=String(h));let g={type:"tool_result",tool_use_id:m.tool_call_id,content:h};m.cache_control&&(g.cache_control=m.cache_control);let f=s[s.length-1];f&&f.role==="user"&&Array.isArray(f.content)?f.content.push(g):s.push({role:"user",content:[g]})}else if(m.role==="user"){let h=[];typeof m.content=="string"?h.push({type:"text",text:m.content}):Array.isArray(m.content)&&m.content.forEach(f=>{f&&typeof f=="object"&&f.type==="image_url"&&f.image_url?.url?h.push({type:"image",source:{type:"base64",media_type:f.media_type||"image/jpeg",data:f.image_url.url.split(",")[1]||f.image_url.url}}):h.push(f)});let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"user",content:h.length>0?h:[{type:"text",text:" "}]})}else if(m.role==="assistant"){let h=[];m.content&&(typeof m.content=="string"?h.push({type:"text",text:m.content}):Array.isArray(m.content)&&h.push(...m.content)),m.tool_calls&&m.tool_calls.length>0&&m.tool_calls.forEach(f=>{let _={};try{_=JSON.parse(f.function.arguments)}catch{_=f.function.arguments}h.push({type:"tool_use",id:f.id,name:f.function.name,input:_})}),m.thinking&&h.unshift({type:"thinking",thinking:m.thinking.content,signature:m.thinking.signature});let g=s[s.length-1];g&&g.role==="assistant"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"assistant",content:h.length>0?h:[{type:"text",text:" "}]})}}let i=()=>{let p=t.filter(m=>m?.cache_control).length;for(let m of s)Array.isArray(m.content)&&(p+=m.content.filter(h=>h?.cache_control).length);return p},a=p=>p&&typeof p=="object"?{...p}:{type:"ephemeral"},l=()=>{for(let p=s.length-1;p>=0;p--){let m=s[p]?.content;if(!Array.isArray(m))continue;let h=m.find(g=>g?.cache_control);if(h?.cache_control)return h.cache_control}for(let p=t.length-1;p>=0;p--)if(t[p]?.cache_control)return t[p].cache_control;return{type:"ephemeral"}},c=(p,m)=>{if(!Array.isArray(p?.content)||p.content.some(g=>g?.cache_control))return!1;let h=p.content.find(g=>g&&typeof g=="object"&&!g.cache_control);return h?(h.cache_control=a(m),!0):!1};(()=>{let p=4-i();if(p<=0||s.length===0)return;let m=s,h=l(),g=[];for(let f=m.length-1;f>=0;f--)m[f]?.role!=="user"||!Array.isArray(m[f].content)||g.push(f);for(let f of g){if(p<=0)break;c(m[f],h)&&p--}})();let d={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let p=n.reasoning.max_tokens||Ln(n.reasoning.effort||"medium"),m=Math.min(p,d.max_tokens-1024);m>=1024&&(d.thinking={type:"enabled",budget_tokens:m});let h=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:we(p);vi.includes(h)&&(d.output_config={...d.output_config||{},effort:h})}if(t.length>0){let p=t.some(m=>m?.cache_control);d.system=p?t:t.map(m=>m.text||"").join(`
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
`)
|
|
49
|
-
|
|
43
|
+
${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function Vi(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Zo(n),o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&Ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&zu.test(r.model)&&await jt(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let s=n.provider;if(!s&&r?.model){let l=r.model.split(",");l.length>1&&(s=l[0],r.model=l.slice(1).join(","))}let a=s?t.providerService.getProvider(s):void 0;if(!a&&r?.model){let l=t.providerService.resolveModelRoute(r.model);l&&(a=l.provider,r.model=l.targetModel)}if(!a&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[p,...d]=u.split(","),m=t.providerService.getProvider(p);m&&(a=m,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!a)throw G(`Provider '${s}' not found`,404,"provider_not_found");n.provider=a.name||s;let i=Ku(n),c=o.endPoint==="/v1/messages"&&i;i&&e.header("X-Codex-Detected","true"),c&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=c,n.codexDetected=i;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&Ht(r);let l={req:n,isCodexOnMessagesEndpoint:c,pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Yi(r,a,o,n.headers,l);if(u?.messages&&!d&&!n.isTargetAnthropic){let g=u.messages,_=new Set,b=[],y=[];for(let k of g){if(k?.role!=="system"){y.push(k);continue}let T=JSON.stringify(k.content??"");_.has(T)||(_.add(T),b.push(k))}b.length>0&&y.length>0&&(u.messages=[...b,...y])}let m=await Xi(u,p,a,t,d,o,l);try{a?.baseUrl&&m?.headers&&It(s,a.baseUrl,m.headers)}catch{}let h=await Zi(u,m,a,o,d,l);h=await Qi(r,h,a.name||s);let f=qi(h,e,r,t);try{let g=r.model||n.originalModel;s&&g&&j().recordSuccess(s,g)}catch{}return f}catch(l){if(l instanceof re)throw l;if(!qo(n,t.pluginRegistry.getManagedRuntimeFor(a),l,a)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Vi(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;l=d}}let p=await Bu(n,e,t,o,l);if(p)return p;throw n.__fallbackExhausted=!0,l}}async function Qi(n,e,t){if(!n?.stream||!e?.body)return e;let o=e.body.getReader(),r=new TextDecoder,s=[],a="";for(let l=0;l<8;l++){let u=await o.read();if(u.done||(u.value&&(s.push(u.value),a+=r.decode(u.value,{stream:!0})),a.split(`
|
|
44
|
+
`).some(p=>p.startsWith("data:"))))break}if(a+=r.decode(),s.length===0)throw o.releaseLock(),G(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(a.includes("event: error")){o.releaseLock();let l=a.length<500?a:a.slice(0,500);throw G(`Provider ${t} returned error in SSE stream: ${l}`,400,"provider_response_error")}if(a.split(`
|
|
45
|
+
`).filter(l=>l.startsWith("data:")&&l.trim().length>5).length===0){o.releaseLock();let l=a.length<500?a:a.slice(0,500);throw G(`Provider ${t} returned streaming response with no SSE data lines: ${l}`,400,"provider_response_error")}let c=new ReadableStream({start:l=>{for(let p of s)l.enqueue(p);let u=()=>{o.read().then(({done:p,value:d})=>{p?l.close():(l.enqueue(d),u())}).catch(p=>l.error(p))};u()},cancel:()=>{o.cancel()}});return new Response(c,{headers:e.headers,status:e.status,statusText:e.statusText})}async function Bu(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,c=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),l=j(),u=n.provider||"",p=n.body.model||"",d=new Set,m=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&Gn(r.rawBody)||r?.message&&Gn(r.message);if(u&&p&&(m?(l.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):l.recordFailure(u,p,r?.message),d.add(`${u},${p}`),t.recordUsage?.({provider:u,model:p,originalModel:n.originalModel||p,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let f=b=>{let[y,...k]=b.split(","),T=y?.trim(),S=k.join(",").trim();return!T||!S?null:{provider:T,model:S,key:`${T},${S}`}},g=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)g.push({name:`${i}/${s}`,models:b});else{let y=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${y?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(c?.[s])&&c[s].length>0&&g.push({name:`global/${s}`,models:c[s]}),g.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(S=>S.type==="image"||S.type==="image_url")))&&Array.isArray(c?.image)&&c.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),g.push({name:"global/image (auto-detected)",models:c.image})),g.length===0)return null;let _=g.reduce((b,y)=>b+y.models.length,0);n.log.warn(`Request failed for ${s}, trying ${_} fallback models across ${g.length} fallback stage(s)`);for(let b of g){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let y of b.models){let k=f(y);if(!k){n.log.warn(`Fallback model '${y}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let T=t.providerService.getProviders(),S=Lt(T,k.provider,k.model);if(!S){n.log.warn(`Fallback model ${y} is not configured or provider is disabled, skipping`);continue}let v=S.provider.name,R=S.model;if(!l.isAvailable(v,R,S.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${y} unavailable (fail pool), skipping`);continue}let C=t.pluginRegistry.getManagedRuntimeFor(S.provider);if(C&&qe(n,C,{name:v}).terminalError)continue;let x;for(let O=1;O<=2;O++)try{n.log.info(`Trying fallback model: ${v},${R}${O>1?" (retry)":""}`);let A={...n.body};A.model=R;let E={...n,provider:v,body:A},N=S.provider,$={pluginRegistry:t.pluginRegistry,req:E,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1},{requestBody:D,config:W,bypass:L}=await Yi(A,N,o,n.headers,$),F=await Xi(D,W,N,t,L,o,$);try{N?.baseUrl&&F?.headers&&It(v,N.baseUrl,F.headers)}catch{}let J=await Zi(D,F,N,o,L,$);return J=await Qi(A,J,v),n.log.info(`Fallback model ${v},${R} succeeded`),l.recordSuccess(v,R),u&&p&&!n.strictProjectRouting&&(et().promote(u,p,s,v,R),n.log.info(`Promoted fallback model ${v},${R} for ${u},${p}:${s}`),m?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(l.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=v,n.body=A,vi(n,`${v},${R}`),qi(J,e,A,t)}catch(A){if(x=A,qo(n,C,A,{name:v}))break;if(O===1){n.log.warn(`Fallback model ${v},${R} failed, retrying once: ${A.message}`);continue}}l.recordFailure(v,R,x?.message),n.log.warn(`Fallback model ${v},${R} failed after retry: ${x?.message}`),t.recordUsage?.({provider:v,model:R,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:x?.message||String(x),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Yi(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw G("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=qe(r.req,s,e).terminalError;if(u)throw u;await s.ensureUsable?.()}let a=JSON.parse(JSON.stringify(n)),i=a?.system;if(typeof i=="string"&&i.includes("cch="))a.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let u=0;u<i.length;u++){let p=i[u],d=typeof p=="string"?p:p?.text??"";if(d.includes("cch=")){let m=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?i[u]=m:typeof p?.text=="string"&&(p.text=m)}}let c={},l=!1;if(l=Ju(e,t,n),l&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],c.headers=o),!l&&typeof t.transformRequestOut=="function"){let u=await t.transformRequestOut(a);u.body?(a=u.body,c=u.config||{}):a=u}if(!l&&e.transformer?.use?.length)for(let u of e.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let p=await u.transformRequestIn(a,e,r);p.body?(a=p.body,c={...c,...p.config}):a=p}if(!l&&e.transformer?.[n.model]?.use?.length)for(let u of e.transformer[n.model].use)!u||typeof u.transformRequestIn!="function"||(a=await u.transformRequestIn(a,e,r));return{requestBody:a,config:c,bypass:l}}function Ju(n,e,t){return e.endPoint==="/v1/chat/completions"&&Array.isArray(t?.system)?!1:n.transformer?.use?.length===1&&n.transformer.use[0].name===e.name&&(!n.transformer?.[t.model]?.use.length||n.transformer?.[t.model]?.use.length===1&&n.transformer?.[t.model]?.use[0].name===e.name)}function Wu(n,e){if(e?.clientType!=="pi")return;let t=e?.clientContext?.stableSessionId;if(!(typeof t!="string"||!t)){for(let o of Object.keys(n))o.toLowerCase()==="x-litellm-session-id"&&delete n[o];n["x-litellm-session-id"]=t}}function Ku(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Xi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>Gi(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):Gi(n,e,t,o,r,s,a)}function ft(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
|
|
46
|
+
`):""}async function Gi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);i&&(await i.ensureUsable?.(),await i.lockUpstream?.(e,t));let c=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let d=o.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(r&&typeof s.auth=="function"){let d=await s.auth(n,t,a);if(d.body){n=d.body;let m=e.headers||{};d.config?.headers&&(m={...m,...d.config.headers},delete m.host,delete d.config.headers),e={...e,...d.config,headers:m}}else n=d}let l={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(l=await i.signRequest({headers:l,requestBody:n,provider:t,config:e})),Wu(l,a?.req);for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];!i?.suppressDebugLog&&Sn(o.configService)&&ti(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>ri(c,n,{...e,headers:JSON.parse(JSON.stringify(l)),httpsProxy:i?void 0:me(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await je(i,0,void 0,ft(n),{errorName:d?.name}):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!qe(a.req,i,t).refreshUsed){qe(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(h){throw i?await je(i,u.status,void 0,ft(n)):h}if(i){let h=await je(i,u.status,d,ft(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${h.code}`),h}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let m=G(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw m.isRateLimit=u.status===429||Gn(d),m.rawBody=d,m}if(u.ok){let d=u.headers.get("content-type")||"",m=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${m} contentType=${d} ok=${u.ok} status=${u.status} hasBody=${!!u.body}`),!m||d.includes("application/json")){let h="";try{if(h=await u.clone().text(),!h||h.trim()==="")throw new SyntaxError("Empty JSON body");if(Mt(h))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let g=JSON.parse(h);if(i?.isErrorEnvelope?.(g))throw await je(i,u.status,h,ft(n));if(g&&typeof g=="object"&&g.error&&(typeof g.error=="string"||typeof g.error=="object"&&Object.keys(g.error).length>0)){if(i)throw await je(i,u.status,h,ft(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${h}`);let b=Gn(h),y=G(`Error from provider(${t.name},${n.model}: ${u.status}): ${h}`,400,"provider_response_error");throw y.isRateLimit=b,y.rawBody=h,y}}catch(f){if(i)throw f?.pluginClassified===!0?f:await je(i,u.status,void 0,ft(n));if(f instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${h}"`);let g=G(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw g.rawBody=h,g}throw f}}}if(!i?.suppressDebugLog&&!n.stream&&Sn(o.configService)){let m=await u.clone().text();ni(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:m})}return u}async function Zi(n,e,t,o,r,s){let a=e;if(!r&&t.transformer?.use?.length)for(let i of Array.from(t.transformer.use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let i of Array.from(t.transformer[n.model].use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),a=await o.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new rt().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function qi(n,e,t,o){n.ok||e.code(n.status);let r=Ci(n);if(!r){let s=await Te(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let a=await Pe(n);n=a.response,a.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Sn(o.configService)){let[s,a]=n.body.tee(),i=ei(o.configService);return oi(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return U(n)}function Gn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function Gu(n){try{return new URL(n),!0}catch{return!1}}var zu,ea,Vn=w(()=>{"use strict";si();xn();ii();li();Et();or();le();ot();On();$n();br();te();Je();ae();zu=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;ea=async n=>{n.get("/",async()=>({message:"LLMs API",version:En})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:j().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Vi(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw G("Provider name is required",400,"invalid_request");if(!s||!Gu(s))throw G("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw G("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw G("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw G(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw G("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw G("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw G("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw G("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var We,Ar=w(()=>{"use strict";We=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var Oe,Qn,ta,Vu,na,mt=w(()=>{"use strict";Oe=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",Qn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,ta=["low","medium","high"],Vu={none:"none",off:"none",disabled:"none",min:"low",minimal:"low",light:"low",low:"low",medium:"medium",mid:"medium",high:"high",xhigh:"max",max:"max",maximum:"max",ultra:"max",ultracode:"max"},na=n=>{if(typeof n=="string")return Vu[n.trim().toLowerCase()]}});var Ir,oa=w(()=>{Ir=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Qu(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ra(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(m=>{if(typeof m=="string"){t.push({type:"text",text:m});return}m&&typeof m=="object"&&m.type==="text"&&m.text&&t.push({...m})})},r=()=>{let d=new Map;for(let m=0;m<t.length;m++){let h=t[m],f=h?.text??JSON.stringify(h),g=d.get(f);if(g===void 0){d.set(f,m);continue}!t[g]?.cache_control&&h?.cache_control&&(t[g]=h),t.splice(m,1),m--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let m=e[d];if(m.role==="tool"){let h=m.content;try{typeof m.content=="string"&&(h=JSON.parse(m.content))}catch{}h!=null&&typeof h!="object"&&typeof h!="string"&&(h=String(h));let f={type:"tool_result",tool_use_id:m.tool_call_id,content:h};m.cache_control&&(f.cache_control=m.cache_control);let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(f):s.push({role:"user",content:[f]})}else if(m.role==="user"){let h=[];typeof m.content=="string"?h.push({type:"text",text:m.content}):Array.isArray(m.content)&&m.content.forEach(g=>{g&&typeof g=="object"&&g.type==="image_url"&&g.image_url?.url?h.push({type:"image",source:{type:"base64",media_type:g.media_type||"image/jpeg",data:g.image_url.url.split(",")[1]||g.image_url.url}}):h.push(g)});let f=s[s.length-1];f&&f.role==="user"&&Array.isArray(f.content)?f.content.push(...h):s.push({role:"user",content:h.length>0?h:[{type:"text",text:" "}]})}else if(m.role==="assistant"){let h=[];m.content&&(typeof m.content=="string"?h.push({type:"text",text:m.content}):Array.isArray(m.content)&&h.push(...m.content)),m.tool_calls&&m.tool_calls.length>0&&m.tool_calls.forEach(g=>{let _={};try{_=JSON.parse(g.function.arguments)}catch{_=g.function.arguments}h.push({type:"tool_use",id:g.id,name:g.function.name,input:_})}),m.thinking&&h.unshift({type:"thinking",thinking:m.thinking.content,signature:m.thinking.signature});let f=s[s.length-1];f&&f.role==="assistant"&&Array.isArray(f.content)?f.content.push(...h):s.push({role:"assistant",content:h.length>0?h:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(m=>m?.cache_control).length;for(let m of s)Array.isArray(m.content)&&(d+=m.content.filter(h=>h?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},c=()=>{for(let d=s.length-1;d>=0;d--){let m=s[d]?.content;if(!Array.isArray(m))continue;let h=m.find(f=>f?.cache_control);if(h?.cache_control)return h.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},l=(d,m)=>{if(!Array.isArray(d?.content)||d.content.some(f=>f?.cache_control))return!1;let h=d.content.find(f=>f&&typeof f=="object"&&!f.cache_control);return h?(h.cache_control=i(m),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let m=s,h=c(),f=[];for(let g=m.length-1;g>=0;g--)m[g]?.role!=="user"||!Array.isArray(m[g].content)||f.push(g);for(let g of f){if(d<=0)break;l(m[g],h)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||Qn(n.reasoning.effort||"medium"),m=Math.min(d,p.max_tokens-1024);m>=1024&&(p.thinking={type:"enabled",budget_tokens:m});let h=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:Oe(d);ta.includes(h)&&(p.output_config={...p.output_config||{},effort:h})}if(t.length>0){let d=t.some(m=>m?.cache_control);p.system=d?t:t.map(m=>m.text||"").join(`
|
|
47
|
+
|
|
48
|
+
`)}return n.tools&&n.tools.length>0&&(p.tools=Qu(n.tools),n.tool_choice&&(n.tool_choice==="auto"?p.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?p.tool_choice={type:"any"}:typeof n.tool_choice=="string"?p.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:n.tool_choice.function.name}))),p}var sa=w(()=>{mt()});function Yu(n){if(n===!0)return!0;if(n===!1)return!1;if(typeof n!="string")return;let e=n.trim().toLowerCase();if(e==="enabled"||e==="adaptive"||e==="true")return!0;if(e==="disabled"||e==="off"||e==="none"||e==="false")return!1}var Yn,Xn,ia=w(()=>{"use strict";Yn=require("uuid");mt();xn();te();oa();sa();Je();Xn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(c=>c.type==="text"&&c.text).map(c=>({type:"text",text:c.text,cache_control:c.cache_control}));t.push({role:"system",content:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let c=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(c.length){let u=Ut(String(e.model??"")),p=[];c.forEach(d=>{let m=Array.isArray(d.content)?d.content:null,h=m?m.filter(_=>_?.type==="image"&&_?.source):[],f=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(h.length>0){let _=m.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
|
|
49
|
+
`);u?(f=_||"[tool image]",p.push(...h)):(f=[_,...h.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
|
|
50
|
+
`),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:h.length}))}let g={role:"tool",content:f,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(g)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?Ir(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let l=i.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);l.length&&t.push({role:"user",content:l.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?Ir(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let c={role:"assistant",content:""},l=i.content.filter(d=>d.type==="text"&&d.text);l.length&&(c.content=l.map(d=>d.text).join(`
|
|
51
|
+
`));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(c.tool_calls=u.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let p=i.content.find(d=>d.type==="thinking");p&&(c.thinking={content:p.thinking,signature:p.signature}),t.push(c)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice},s=na(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},l=Yu(e.thinking?.type)??(s!==void 0||(a??0)>0);l!==void 0&&(i.enabled=l),s!==void 0?i.effort=s:a!==void 0&&(i.effort=Oe(a)),a!==void 0&&a>0&&(i.max_tokens=a),Object.keys(i).length>0&&(r.reasoning=i)}return e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=ra(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let r=await this.convertOpenAIStreamToAnthropic(e.body,t);return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let r=await Te(e);if((r?.isSSE??!1)&&r?.body){let l=await this.convertOpenAIStreamToAnthropic(r.body,t);return new Response(l,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let a;if(r?.body)a=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else{let l=await Pe(e);if(l.isSSE){let u=await this.convertOpenAIStreamToAnthropic(l.response.body,t);return new Response(u,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}a=l.response}let i=await U(a),c=this.convertOpenAIResponseToAnthropic(i,t);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,a=`msg_${Date.now()}`,i=null,c="unknown",l=!1,u=!1,p=!1,d=new Map,m=new Map,h=0,f=0,g=0,_=!1,b=!1,y=0,k=-1,T=()=>{let C=y;return y++,C},S=C=>{if(!_)try{r.enqueue(C);let x=new TextDecoder().decode(C);this.logger.debug({reqId:t.req.id,data:x,type:"send data"})}catch(x){if(x instanceof TypeError&&x.message.includes("Controller is already closed"))_=!0;else throw this.logger.debug({reqId:t.req.id,error:x instanceof Error?x.message:String(x),type:"send data error"}),x}},v=()=>{if(!_)try{if(!l){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),_=!0;return}if(k>=0){let x={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
52
|
+
data: ${JSON.stringify(x)}
|
|
50
53
|
|
|
51
|
-
`)),
|
|
52
|
-
data: ${JSON.stringify(
|
|
54
|
+
`)),k=-1}if(i)S(s.encode(`event: message_delta
|
|
55
|
+
data: ${JSON.stringify(i)}
|
|
53
56
|
|
|
54
|
-
`)),
|
|
55
|
-
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:
|
|
57
|
+
`)),i=null;else{let x=t?.req?.tokenCount||0;S(s.encode(`event: message_delta
|
|
58
|
+
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:x,output_tokens:0,cache_read_input_tokens:0}})}
|
|
56
59
|
|
|
57
|
-
`))}let
|
|
58
|
-
data: ${JSON.stringify(
|
|
60
|
+
`))}let C={type:"message_stop"};S(s.encode(`event: message_stop
|
|
61
|
+
data: ${JSON.stringify(C)}
|
|
59
62
|
|
|
60
|
-
`)),r.close(),_=!0}catch(
|
|
61
|
-
`);
|
|
62
|
-
data: ${JSON.stringify(
|
|
63
|
+
`)),r.close(),_=!0}catch(C){if(C instanceof TypeError&&C.message.includes("Controller is already closed"))_=!0;else throw C}},R=null;try{R=e.getReader();let C=new TextDecoder,x="";for(;!_;){let{done:O,value:A}=await R.read();if(O)break;x+=C.decode(A,{stream:!0});let E=x.split(`
|
|
64
|
+
`);x=E.pop()||"";for(let N of E){if(_)break;if(!N.startsWith("data:"))continue;let $=N.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:$}),$!=="[DONE]")try{let D=JSON.parse($);if(h++,this.logger.debug({reqId:t.req.id,response:D,tppe:"Original Response"}),D.error){t?.req&&(t.req.sseError=D.error);let L={type:"error",message:{type:"api_error",message:JSON.stringify(D.error)}};S(s.encode(`event: error
|
|
65
|
+
data: ${JSON.stringify(L)}
|
|
63
66
|
|
|
64
|
-
`));continue}if(
|
|
67
|
+
`));continue}if(c=D.model||c,!l&&!_&&!p){l=!0;let L=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:c,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};S(s.encode(`event: message_start
|
|
65
68
|
data: ${JSON.stringify(F)}
|
|
66
69
|
|
|
67
|
-
`))}let
|
|
70
|
+
`))}let W=D.choices?.[0];if(D.usage){let L=D.usage?.prompt_tokens_details?.cached_tokens??D.usage?.prompt_cache_hit_tokens??0,J=(D.usage?.prompt_tokens||0)-L,we=D.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:D.usage,mappedUsage:{input_tokens:J,output_tokens:we,cache_read_input_tokens:L},choicesLength:Array.isArray(D.choices)?D.choices.length:void 0,finishReason:W?.finish_reason});let B={input_tokens:J,output_tokens:we,cache_read_input_tokens:L};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...B}};else{let ie=i.usage||{};i.usage={input_tokens:B.input_tokens||ie.input_tokens||0,output_tokens:B.output_tokens||ie.output_tokens||0,cache_read_input_tokens:B.cache_read_input_tokens||ie.cache_read_input_tokens||0}}}if(!W)continue;if(W?.delta?.thinking&&!_&&!p&&!u){if(!b){let L=T(),F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};S(s.encode(`event: content_block_start
|
|
68
71
|
data: ${JSON.stringify(F)}
|
|
69
72
|
|
|
70
|
-
`)),b
|
|
71
|
-
data: ${JSON.stringify(
|
|
73
|
+
`)),k=L,b=!0}if(W.delta.thinking.signature){let L={type:"content_block_delta",index:k,delta:{type:"signature_delta",signature:W.delta.thinking.signature}};S(s.encode(`event: content_block_delta
|
|
74
|
+
data: ${JSON.stringify(L)}
|
|
72
75
|
|
|
73
|
-
`));let F={type:"content_block_stop",index:
|
|
76
|
+
`));let F={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
74
77
|
data: ${JSON.stringify(F)}
|
|
75
78
|
|
|
76
|
-
`)),
|
|
77
|
-
data: ${JSON.stringify(
|
|
79
|
+
`)),k=-1}else if(W.delta.thinking.content){let L={type:"content_block_delta",index:k,delta:{type:"thinking_delta",thinking:W.delta.thinking.content||""}};S(s.encode(`event: content_block_delta
|
|
80
|
+
data: ${JSON.stringify(L)}
|
|
78
81
|
|
|
79
|
-
`))}}if(
|
|
82
|
+
`))}}if(W?.delta?.content&&!_&&!p){if(f++,k>=0&&!u){let F={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
80
83
|
data: ${JSON.stringify(F)}
|
|
81
84
|
|
|
82
|
-
`)),
|
|
85
|
+
`)),k=-1}if(!u&&!p){u=!0;let L=T(),F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};S(s.encode(`event: content_block_start
|
|
83
86
|
data: ${JSON.stringify(F)}
|
|
84
87
|
|
|
85
|
-
`)),
|
|
86
|
-
data: ${JSON.stringify(
|
|
88
|
+
`)),k=L}if(!_&&!p){let L={type:"content_block_delta",index:k,delta:{type:"text_delta",text:W.delta.content}};S(s.encode(`event: content_block_delta
|
|
89
|
+
data: ${JSON.stringify(L)}
|
|
87
90
|
|
|
88
|
-
`))}}if(
|
|
89
|
-
data: ${JSON.stringify(
|
|
91
|
+
`))}}if(W?.delta?.annotations?.length&&!_&&!p){if(k>=0&&u){let L={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
92
|
+
data: ${JSON.stringify(L)}
|
|
90
93
|
|
|
91
|
-
`)),
|
|
92
|
-
data: ${JSON.stringify(
|
|
94
|
+
`)),k=-1,u=!1}W?.delta?.annotations.forEach(L=>{let F=T(),J={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${(0,Yn.v4)()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};S(s.encode(`event: content_block_start
|
|
95
|
+
data: ${JSON.stringify(J)}
|
|
93
96
|
|
|
94
|
-
`));let
|
|
95
|
-
data: ${JSON.stringify(
|
|
97
|
+
`));let we={type:"content_block_stop",index:F};S(s.encode(`event: content_block_stop
|
|
98
|
+
data: ${JSON.stringify(we)}
|
|
96
99
|
|
|
97
|
-
`)),
|
|
98
|
-
data: ${JSON.stringify(
|
|
100
|
+
`)),k=-1})}if(W?.delta?.tool_calls&&!_&&!p){g++;let L=new Set;for(let F of W.delta.tool_calls){if(_)break;let J=F.index??0;if(L.has(J))continue;if(L.add(J),!m.has(J)){if(k>=0){let Cl={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
101
|
+
data: ${JSON.stringify(Cl)}
|
|
99
102
|
|
|
100
|
-
`)),
|
|
103
|
+
`)),k=-1}let B=T();m.set(J,B);let ie=F.id||`call_ccr_${J}`,K=F.function?.name||`tool_${J}`,I={type:"content_block_start",index:B,content_block:{type:"tool_use",id:ie,name:K,input:{}}};S(s.encode(`event: content_block_start
|
|
101
104
|
data: ${JSON.stringify(I)}
|
|
102
105
|
|
|
103
|
-
`)),
|
|
104
|
-
data: ${JSON.stringify(
|
|
106
|
+
`)),k=B;let Q={id:ie,name:K,arguments:"",contentBlockIndex:B};d.set(J,Q)}else if(F.id&&F.function?.name){let B=d.get(J);B.id.startsWith("call_")&&B.name.startsWith("tool_")&&(B.id=F.id,B.name=F.function.name)}if(F.function?.arguments&&!_&&!p){let B=m.get(J);if(B===void 0)continue;let ie=d.get(J);ie&&(ie.arguments+=F.function.arguments);try{let K={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:F.function.arguments}};S(s.encode(`event: content_block_delta
|
|
107
|
+
data: ${JSON.stringify(K)}
|
|
105
108
|
|
|
106
|
-
`))}catch{try{let
|
|
109
|
+
`))}catch{try{let K=F.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),I={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:K}};S(s.encode(`event: content_block_delta
|
|
107
110
|
data: ${JSON.stringify(I)}
|
|
108
111
|
|
|
109
|
-
`))}catch(
|
|
110
|
-
data: ${JSON.stringify(
|
|
112
|
+
`))}catch(K){console.error(K)}}}}}if(W?.finish_reason&&!_&&!p){if(f===0&&g===0&&console.error("Warning: No content in the stream response!"),k>=0){let L={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
113
|
+
data: ${JSON.stringify(L)}
|
|
111
114
|
|
|
112
|
-
`)),
|
|
113
|
-
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:
|
|
115
|
+
`)),k=-1}if(!_){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[W.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:F,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(D){this.logger?.error(`parseError: ${D.name} message: ${D.message} stack: ${D.stack} data: ${$}`)}}}v()}catch(C){if(!_)try{r.error(C)}catch(x){console.error(x)}}finally{if(R)try{R.releaseLock()}catch(C){console.error(C)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let c=`srvtoolu_${(0,Yn.v4)()}`;r.push({type:"server_tool_use",id:c,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:c,content:o.message.annotations.map(l=>({type:"web_search_result",url:l.url_citation.url,title:l.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(c=>{let l={};try{let u=c.function.arguments||"{}";typeof u=="object"?l=u:typeof u=="string"&&(l=JSON.parse(u))}catch{l={text:c.function.arguments||""}}r.push({type:"tool_use",id:c.id,name:c.function.name,input:l})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens??e.usage?.prompt_cache_hit_tokens??0,a=(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${(0,Yn.v4)().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw G(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Xu(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(gt).includes(o)?o:gt.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(gt).includes(r)?r:gt.TYPE_UNSPECIFIED})}}}function zt(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&Xu(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let c=i.toUpperCase();e.type=Object.values(gt).includes(c)?c:gt.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=zt(i);else if(o.includes(a)){let c=[];for(let l of i){if(l.type=="null"){e.nullable=!0;continue}c.push(zt(l))}e[a]=c}else if(r.includes(a)){let c={};for(let[l,u]of Object.entries(i))c[l]=zt(u);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=i}return e}function Zu(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=zt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=zt(e.response));return n}function Zn(n){let e=[],t=n.tools?.filter(c=>c.function.name!=="web_search")?.map(c=>({name:c.function.name,description:c.function.description,parametersJsonSchema:c.function.parameters}));t?.length&&e.push(Zu({functionDeclarations:t})),n.tools?.find(c=>c.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(c=>c.role==="tool");n.messages.filter(c=>c.role!=="tool").forEach(c=>{let l;c.role==="assistant"?l="model":(["user","system"].includes(c.role),l="user");let u=[];if(typeof c.content=="string"){let p={text:c.content};c.thinking?.signature&&(p.thoughtSignature=c.thinking.signature),u.push(p)}else Array.isArray(c.content)?u.push(...c.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):c.content&&typeof c.content=="object"&&(c.content.text?u.push({text:c.content.text}):u.push({text:JSON.stringify(c.content)}));if(Array.isArray(c.tool_calls)&&u.push(...c.tool_calls.map(p=>{let d={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return c.thinking?.signature&&(d.thoughtSignature=c.thinking.signature),d})),u.length===0&&u.push({text:""}),r.push({role:l,parts:u}),l==="model"&&c.tool_calls){let p=c.tool_calls.map(d=>{let m=s.find(h=>h.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:m?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let c=n.model.includes("pro")?[128,32768]:[0,24576],l,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=c[0]&&u<=c[1]?l=u:u<c[0]?l=c[0]:u>c[1]&&(l=c[1]),a.thinkingConfig.thinkingBudget=l)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};if(n.tool_choice){let c={functionCallingConfig:{}};n.tool_choice==="auto"?c.functionCallingConfig.mode="auto":n.tool_choice==="none"?c.functionCallingConfig.mode="none":n.tool_choice==="required"?c.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(c.functionCallingConfig.mode="any",c.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),i.toolConfig=c}return i}function qn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,c={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};return Array.isArray(e)&&e.forEach(l=>{typeof l=="string"?c.messages.push({role:"user",content:l}):typeof l.text=="string"?c.messages.push({role:"user",content:l.text||null}):l.role==="user"?c.messages.push({role:"user",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):l.role==="model"&&c.messages.push({role:"assistant",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(c.tools=[],t.forEach(l=>{Array.isArray(l.functionDeclarations)&&l.functionDeclarations.forEach(u=>{c.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),c}async function eo(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],i=[];for(let p of a)p.text&&p.thought===!0?r+=p.text:i.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let c=i?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],l=i?.filter(p=>p.text)?.map(p=>p.text)?.join(`
|
|
116
|
+
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:l,role:"assistant",tool_calls:c.length>0?c:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,c="",l=0,u=-1,p=new ReadableStream({async start(d){let m=async(g,_)=>{if(g.startsWith("data: ")){let b=g.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let y=JSON.parse(b);if(!y.candidates||!y.candidates[0]){t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=y.candidates[0],T=k.content?.parts||[];T.filter(C=>C.text&&C.thought===!0).forEach(C=>{i||(i=!0);let x={choices:[{delta:{role:"assistant",content:null,thinking:{content:C.text}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
114
117
|
|
|
115
|
-
`))});let
|
|
118
|
+
`))});let S=T.find(C=>C.thoughtSignature)?.thoughtSignature;if(S&&!s){if(!i){let x={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
116
119
|
|
|
117
|
-
`))}let
|
|
120
|
+
`))}let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:S}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(_.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
118
121
|
|
|
119
|
-
`)),s=!0,c
|
|
122
|
+
`)),s=!0,l++,c){let x={choices:[{delta:{role:"assistant",content:c},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
120
123
|
|
|
121
|
-
`)),
|
|
122
|
-
`);if(!
|
|
124
|
+
`)),c="",a||(a=!0)}}let v=T.filter(C=>C.functionCall).map(C=>({id:C.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})}})),R=T.filter(C=>C.text&&C.thought!==!0).map(C=>C.text).join(`
|
|
125
|
+
`);if(!R&&s&&!a){let C={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
123
126
|
|
|
124
|
-
`)),
|
|
127
|
+
`)),a||(a=!0)}if(i&&R&&!s)if(y.modelVersion.includes("3")){c+=R;return}else{let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};_.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
125
128
|
|
|
126
|
-
`)),s=!0}if(
|
|
129
|
+
`)),s=!0}if(R){c||l++;let C={choices:[{delta:{role:"assistant",content:R},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:y.usageMetadata?.candidatesTokenCount||0,prompt_tokens:y.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:y.usageMetadata?.cachedContentTokenCount||0},total_tokens:y.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:y.usageMetadata?.thoughtsTokenCount||0}}};k?.groundingMetadata?.groundingChunks?.length&&(C.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((x,O)=>{let A=k?.groundingMetadata?.groundingSupports?.filter(E=>E.groundingChunkIndices?.includes(O));return{type:"url_citation",url_citation:{url:x?.web?.uri||"",title:x?.web?.title||"",content:A?.[0]?.segment?.text||"",start_index:A?.[0]?.segment?.startIndex||0,end_index:A?.[0]?.segment?.endIndex||0}}})),_.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
127
130
|
|
|
128
|
-
`)),!
|
|
131
|
+
`)),!a&&R&&(a=!0)}v.length>0&&(v.forEach(C=>{l++,u++;let x={choices:[{delta:{role:"assistant",tool_calls:[{...C,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:y.usageMetadata?.candidatesTokenCount||0,prompt_tokens:y.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:y.usageMetadata?.cachedContentTokenCount||0},total_tokens:y.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:y.usageMetadata?.thoughtsTokenCount||0}}};k?.groundingMetadata?.groundingChunks?.length&&(x.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((O,A)=>{let E=k?.groundingMetadata?.groundingSupports?.filter(N=>N.groundingChunkIndices?.includes(A));return{type:"url_citation",url_citation:{url:O?.web?.uri||"",title:O?.web?.title||"",content:E?.[0]?.segment?.text||"",start_index:E?.[0]?.segment?.startIndex||0,end_index:E?.[0]?.segment?.endIndex||0}}})),_.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
129
132
|
|
|
130
|
-
`))}),!
|
|
131
|
-
`);
|
|
133
|
+
`))}),!a&&R&&(a=!0))}catch(y){t?.error(`Error parsing ${e} stream chunk`,b,y.message)}}}},h=n.body.getReader(),f="";try{for(;;){let{done:g,value:_}=await h.read();if(g){f&&await m(f,d);break}f+=o.decode(_,{stream:!0});let b=f.split(`
|
|
134
|
+
`);f=b.pop()||"";for(let y of b)await m(y,d)}}catch(g){d.error(g)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var gt,Mr=w(()=>{"use strict";gt={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var to,aa=w(()=>{"use strict";Mr();to=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:Zn(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=qn;async transformResponseOut(e){return eo(e,this.name,this.logger)}}});async function qu(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
132
135
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
133
136
|
2. Run "gcloud auth application-default login"
|
|
134
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
135
|
-
`);for(let
|
|
136
|
-
`))},
|
|
137
|
+
3. Use Google Cloud environment with default service account`)}}var no,ca=w(()=>{"use strict";Mr();no=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(i);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await qu();return{body:Zn(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return qn(e)}async transformResponseOut(e){return eo(e,this.name)}}});var oo,la=w(()=>{"use strict";te();oo=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,i="";if(typeof r.content=="string"){let l=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);l&&(i=l[1].trim(),r.content=r.content.replace(l[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(c){let l=e.body.getReader(),u=(d,m,h)=>{let f=d.split(`
|
|
138
|
+
`);for(let g of f)g.trim()&&m.enqueue(h.encode(g+`
|
|
139
|
+
`))},p=(d,m)=>{let{controller:h,encoder:f}=m;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let g=JSON.parse(d.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){m.appendReasoningContent(g.choices[0].delta.reasoning_content);let _={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(_)}
|
|
137
140
|
|
|
138
|
-
`;h.enqueue(
|
|
141
|
+
`;h.enqueue(f.encode(b));return}if(g.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let _="ccr_think_signature",b=g.choices[0].delta.content,y={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:_}}}]};delete y.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(y)}
|
|
139
142
|
|
|
140
|
-
`;h.enqueue(
|
|
143
|
+
`;h.enqueue(f.encode(k));let T={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:b}}]};delete T.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(T)}
|
|
141
144
|
|
|
142
|
-
`;h.enqueue(
|
|
145
|
+
`;h.enqueue(f.encode(S));return}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){let _=`data: ${JSON.stringify(g)}
|
|
143
146
|
|
|
144
|
-
`;h.enqueue(
|
|
145
|
-
`))}else h.enqueue(
|
|
146
|
-
`))};try{for(;;){let{done:
|
|
147
|
-
`);
|
|
148
|
-
`))}}}catch(
|
|
147
|
+
`;h.enqueue(f.encode(_))}}catch{h.enqueue(f.encode(d+`
|
|
148
|
+
`))}else h.enqueue(f.encode(d+`
|
|
149
|
+
`))};try{for(;;){let{done:d,value:m}=await l.read();if(d){a.trim()&&u(a,c,o);break}let h=t.decode(m,{stream:!0});a+=h;let f=a.split(`
|
|
150
|
+
`);a=f.pop()||"";for(let g of f)if(g.trim())try{p(g,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:_=>r+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",g,_),c.enqueue(o.encode(g+`
|
|
151
|
+
`))}}}catch(d){console.error("Stream error:",d),c.error(d)}finally{try{l.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var ro,ua=w(()=>{"use strict";te();ro=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
|
|
149
152
|
IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
|
|
150
153
|
Examples:
|
|
151
154
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
152
|
-
2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",
|
|
153
|
-
`);for(let
|
|
154
|
-
`))},
|
|
155
|
+
2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",a="",i=new ReadableStream({async start(c){let l=e.body.getReader(),u=(d,m,h)=>{let f=d.split(`
|
|
156
|
+
`);for(let g of f)g.trim()&&m.enqueue(h.encode(g+`
|
|
157
|
+
`))},p=(d,m)=>{let{controller:h,encoder:f,exitToolIndex:g,setExitToolIndex:_,appendExitToolResponse:b}=m;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let y=JSON.parse(d.slice(6));if(y.choices[0]?.delta?.tool_calls?.length){let k=y.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){_(k.index);return}else if(g()>-1&&k.index===g()&&k.function.arguments){b(k.function.arguments);try{let T=JSON.parse(m.exitToolResponse());y.choices=[{delta:{role:"assistant",content:T.response||""}}];let S=`data: ${JSON.stringify(y)}
|
|
155
158
|
|
|
156
|
-
`;h.enqueue(
|
|
159
|
+
`;h.enqueue(f.encode(S))}catch{}return}}if(y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let k=`data: ${JSON.stringify(y)}
|
|
157
160
|
|
|
158
|
-
`;h.enqueue(
|
|
159
|
-
`))}else h.enqueue(
|
|
160
|
-
`))};try{for(;;){let{done:
|
|
161
|
-
`);
|
|
162
|
-
`))}}}catch(
|
|
163
|
-
`);for(let
|
|
164
|
-
`))},m=(h,
|
|
161
|
+
`;h.enqueue(f.encode(k))}}catch{h.enqueue(f.encode(d+`
|
|
162
|
+
`))}else h.enqueue(f.encode(d+`
|
|
163
|
+
`))};try{for(;;){let{done:d,value:m}=await l.read();if(d){a.trim()&&u(a,c,o);break}let h=t.decode(m,{stream:!0});a+=h;let f=a.split(`
|
|
164
|
+
`);a=f.pop()||"";for(let g of f)if(g.trim())try{p(g,{controller:c,encoder:o,exitToolIndex:()=>r,setExitToolIndex:_=>r=_,exitToolResponse:()=>s,appendExitToolResponse:_=>s+=_})}catch(_){console.error("Error processing line:",g,_),c.enqueue(o.encode(g+`
|
|
165
|
+
`))}}}catch(d){console.error("Stream error:",d),c.error(d)}finally{try{l.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var da,so,pa=w(()=>{"use strict";te();da=require("uuid"),so=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,f,g)=>{let _=h.split(`
|
|
166
|
+
`);for(let b of _)b.trim()&&f.enqueue(g.encode(b+`
|
|
167
|
+
`))},m=(h,f)=>{let{controller:g,encoder:_}=f;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let b=h.slice(6);try{let y=JSON.parse(b);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:i},"usage"),y.choices[0].finish_reason=i?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"){g.enqueue(_.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
|
|
165
168
|
|
|
166
|
-
`));return}y.choices?.[0]?.delta?.content&&!
|
|
169
|
+
`));return}y.choices?.[0]?.delta?.content&&!f.hasTextContent()&&f.setHasTextContent(!0);let k=y.choices?.[0]?.delta?.reasoning||y.choices?.[0]?.delta?.reasoning_content;if(k){f.appendReasoningContent(k);let C={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:k}}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let x=`data: ${JSON.stringify(C)}
|
|
167
170
|
|
|
168
|
-
`;
|
|
171
|
+
`;g.enqueue(_.encode(x));return}if(y.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let C="ccr_think_signature",x=y.choices[0].delta.content,O={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:C}}}]};O.choices?.[0]?.delta&&delete O.choices[0].delta.reasoning;let A=`data: ${JSON.stringify(O)}
|
|
169
172
|
|
|
170
|
-
`;
|
|
173
|
+
`;g.enqueue(_.encode(A));let E={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:x}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let N=`data: ${JSON.stringify(E)}
|
|
171
174
|
|
|
172
|
-
`;
|
|
175
|
+
`;g.enqueue(_.encode(N));return}y.choices?.[0]?.delta?.reasoning&&delete y.choices[0].delta.reasoning,y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(y.choices?.[0]?.delta?.tool_calls[0].id,10))&&y.choices?.[0]?.delta?.tool_calls.forEach(C=>{C.id=`call_${(0,da.v4)()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let T=y.choices?.[0]?.delta,S=T&&Object.keys(T).length>0,v=y.choices?.[0]?.finish_reason,R=y.usage;if(S||v||R){let C=`data: ${JSON.stringify(y)}
|
|
173
176
|
|
|
174
|
-
`;
|
|
175
|
-
`))}}else
|
|
176
|
-
`))};try{for(;;){let{done:h,value:
|
|
177
|
-
`);
|
|
178
|
-
`))}continue}let _=
|
|
179
|
-
`);
|
|
180
|
-
`))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{
|
|
181
|
-
`);for(let _ of
|
|
182
|
-
`))},
|
|
177
|
+
`;g.enqueue(_.encode(C))}}catch{g.enqueue(_.encode(h+`
|
|
178
|
+
`))}}else g.enqueue(_.encode(h+`
|
|
179
|
+
`))};try{for(;;){let{done:h,value:f}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!f||f.length===0)continue;let g;try{g=t.decode(f,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(g.length===0)continue;if(c+=g,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
|
|
180
|
+
`);c=b.pop()||"";for(let y of b)if(y.trim())try{m(y,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",y,k),u.enqueue(o.encode(y+`
|
|
181
|
+
`))}continue}let _=c.split(`
|
|
182
|
+
`);c=_.pop()||"";for(let b of _)if(b.trim())try{m(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",b,y),u.enqueue(o.encode(b+`
|
|
183
|
+
`))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var io,fa=w(()=>{"use strict";io=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});var ma,ao,ga=w(()=>{"use strict";te();ma=require("uuid"),ao=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i="",c=new ReadableStream({async start(l){let u=e.body.getReader(),p=(m,h,f)=>{let g=m.split(`
|
|
184
|
+
`);for(let _ of g)_.trim()&&h.enqueue(f.encode(_+`
|
|
185
|
+
`))},d=(m,h)=>{let{controller:f,encoder:g}=h;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let _=m.slice(6);try{let b=JSON.parse(_);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${(0,ma.v4)()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let y=`data: ${JSON.stringify(b)}
|
|
183
186
|
|
|
184
|
-
`;
|
|
185
|
-
`))}}else
|
|
186
|
-
`))};try{for(;;){let{done:m,value:h}=await u.read();if(m){
|
|
187
|
-
`);
|
|
188
|
-
`))}continue}let
|
|
189
|
-
`);
|
|
190
|
-
`))}}}catch(m){console.error("Stream error:",m),
|
|
191
|
-
`);for(let
|
|
192
|
-
`))},h=(
|
|
187
|
+
`;f.enqueue(g.encode(y))}catch{f.enqueue(g.encode(m+`
|
|
188
|
+
`))}}else f.enqueue(g.encode(m+`
|
|
189
|
+
`))};try{for(;;){let{done:m,value:h}=await u.read();if(m){i.trim()&&p(i,l,o);break}if(!h||h.length===0)continue;let f;try{f=t.decode(h,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(f.length===0)continue;if(i+=f,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=i.split(`
|
|
190
|
+
`);i=_.pop()||"";for(let b of _)if(b.trim())try{d(b,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",b,y),l.enqueue(o.encode(b+`
|
|
191
|
+
`))}continue}let g=i.split(`
|
|
192
|
+
`);i=g.pop()||"";for(let _ of g)if(_.trim())try{d(_,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),l.enqueue(o.encode(_+`
|
|
193
|
+
`))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{u.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var co,ha=w(()=>{"use strict";co=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),e}}});function Nr(n,e){if(!n||n.trim()===""||n==="{}")return"{}";try{return JSON.parse(n),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),n}catch(t){try{let o=ya.default.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=(0,_a.jsonrepair)(n);return e?.debug("Tool arguments safely repaired"),r}catch(r){return e?.error(`JSON parsing failed: ${t.message}. JSON5 parsing failed: ${o.message}. JSON repair failed: ${r.message}. Input data: ${JSON.stringify(n)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var ya,_a,ba=w(()=>{ya=q(require("json5")),_a=require("jsonrepair")});var lo,ka=w(()=>{"use strict";ba();te();lo=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);if(t?.choices?.[0]?.message?.tool_calls?.length)for(let o of t.choices[0].message.tool_calls)o.function?.arguments&&(o.function.arguments=Nr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,c=!1,l="",u=new ReadableStream({async start(p){let d=e.body.getReader(),m=(g,_,b)=>{let y=g.split(`
|
|
194
|
+
`);for(let k of y)k.trim()&&_.enqueue(b.encode(k+`
|
|
195
|
+
`))},h=(g,_,b)=>{let y="";try{y=Nr(r.arguments||"",this.logger)}catch(v){console.error(`${v.message} ${v.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),y=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:y},id:r.id,index:r.index,type:"function"}]},T={...g,choices:[{...g.choices[0],delta:k}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let S=`data: ${JSON.stringify(T)}
|
|
193
196
|
|
|
194
|
-
`;_.enqueue(
|
|
197
|
+
`;_.enqueue(b.encode(S))},f=(g,_)=>{let{controller:b,encoder:y}=_;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let k=g.slice(6);try{let T=JSON.parse(k);if(T.choices?.[0]?.delta?.tool_calls?.length){let v=T.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""},v.function?.arguments&&(v.function.arguments="");let R=`data: ${JSON.stringify(T)}
|
|
195
198
|
|
|
196
|
-
`;
|
|
199
|
+
`;b.enqueue(y.encode(R));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{h(T,b,y),r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){h(T,b,y),r={};return}T.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let S=`data: ${JSON.stringify(T)}
|
|
197
200
|
|
|
198
|
-
`;
|
|
199
|
-
`))}}else
|
|
200
|
-
`))};try{for(;;){let{done:
|
|
201
|
-
`);
|
|
202
|
-
`))}continue}let y=
|
|
203
|
-
`);
|
|
204
|
-
`))}}}catch(
|
|
205
|
-
`);for(let
|
|
206
|
-
`))},
|
|
201
|
+
`;b.enqueue(y.encode(S))}catch{b.enqueue(y.encode(g+`
|
|
202
|
+
`))}}else b.enqueue(y.encode(g+`
|
|
203
|
+
`))};try{for(;;){let{done:g,value:_}=await d.read();if(g){l.trim()&&m(l,p,o);break}if(!_||_.length===0)continue;let b;try{b=t.decode(_,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(b.length===0)continue;if(l+=b,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
|
|
204
|
+
`);l=k.pop()||"";for(let T of k)if(T.trim())try{f(T,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:S=>s=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>i,setReasoningComplete:S=>i=S})}catch(S){console.error("Error processing line:",T,S),p.enqueue(o.encode(T+`
|
|
205
|
+
`))}continue}let y=l.split(`
|
|
206
|
+
`);l=y.pop()||"";for(let k of y)if(k.trim())try{f(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",k,T),p.enqueue(o.encode(k+`
|
|
207
|
+
`))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{d.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var uo,Ta=w(()=>{"use strict";te();mt();uo=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens??Qn(e.reasoning.effort||"medium")},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(c){let l=e.body.getReader(),u=(d,m,h)=>{let f=d.split(`
|
|
208
|
+
`);for(let g of f)g.trim()&&m.enqueue(h.encode(g+`
|
|
209
|
+
`))},p=(d,m)=>{let{controller:h,encoder:f}=m;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let g=JSON.parse(d.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){m.appendReasoningContent(g.choices[0].delta.reasoning_content);let _={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(_)}
|
|
207
210
|
|
|
208
|
-
`;h.enqueue(
|
|
211
|
+
`;h.enqueue(f.encode(b));return}if(g.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let _="ccr_think_signature",b=g.choices[0].delta.content,y={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:_}}}]};delete y.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(y)}
|
|
209
212
|
|
|
210
|
-
`;h.enqueue(
|
|
213
|
+
`;h.enqueue(f.encode(k))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){m.isReasoningComplete()&&g.choices[0].index++;let _=`data: ${JSON.stringify(g)}
|
|
211
214
|
|
|
212
|
-
`;h.enqueue(
|
|
213
|
-
`))}else h.enqueue(
|
|
214
|
-
`))};try{for(;;){let{done:
|
|
215
|
-
`);
|
|
216
|
-
`))}}}catch(
|
|
215
|
+
`;h.enqueue(f.encode(_))}}catch{h.enqueue(f.encode(d+`
|
|
216
|
+
`))}else h.enqueue(f.encode(d+`
|
|
217
|
+
`))};try{for(;;){let{done:d,value:m}=await l.read();if(d){a.trim()&&u(a,c,o);break}let h=t.decode(m,{stream:!0});a+=h;let f=a.split(`
|
|
218
|
+
`);a=f.pop()||"";for(let g of f)if(g.trim())try{p(g,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:_=>r+=_,isReasoningComplete:()=>s,setReasoningComplete:_=>s=_})}catch(_){console.error("Error processing line:",g,_),c.enqueue(o.encode(g+`
|
|
219
|
+
`))}}}catch(d){console.error("Stream error:",d),c.error(d)}finally{try{l.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var po,va=w(()=>{"use strict";po=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var fo,xa=w(()=>{"use strict";fo=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function Ca(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(c=>{c.type==="text"?i.push({type:"text",text:c.text||""}):c.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:c.media_type||"image/jpeg",data:c.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function Sa(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function Ra(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,c)=>{if(i.startsWith("data: ")){let l=i.slice(6).trim();if(l){t?.debug({chunkStr:l},`${e} chunk:`);try{let u=JSON.parse(l);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
217
220
|
|
|
218
|
-
`))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let
|
|
221
|
+
`))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
219
222
|
|
|
220
|
-
`))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let
|
|
223
|
+
`))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
221
224
|
|
|
222
|
-
`))}else if(u.type==="message_delta"){let
|
|
225
|
+
`))}else if(u.type==="message_delta"){let p={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
223
226
|
|
|
224
|
-
`))}else if(u.type==="message_stop")
|
|
227
|
+
`))}else if(u.type==="message_stop")c.enqueue(r.encode(`data: [DONE]
|
|
225
228
|
|
|
226
|
-
`));else{let
|
|
229
|
+
`));else{let p={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
227
230
|
|
|
228
|
-
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,
|
|
229
|
-
`);
|
|
231
|
+
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,l,u.message)}}}},a=new ReadableStream({async start(i){let c=n.body.getReader(),l="";try{for(;;){let{done:u,value:p}=await c.read();if(u){l&&s(l,i);break}l+=o.decode(p,{stream:!0});let d=l.split(`
|
|
232
|
+
`);l=d.pop()||"";for(let m of d)s(m,i)}}catch(u){i.error(u)}finally{i.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var wa=w(()=>{"use strict"});async function ed(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
230
233
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
231
234
|
2. Run "gcloud auth application-default login"
|
|
232
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
233
|
-
`);for(let
|
|
234
|
-
`))},m=(h,
|
|
235
|
+
3. Use Google Cloud environment with default service account`)}}var mo,Pa=w(()=>{"use strict";wa();mo=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(i);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await ed();return{body:Ca(e),config:{url:new URL(`/v1/projects/${o}/locations/${r}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${r}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return Sa(e)}async transformResponseOut(e){return Ra(e,this.name,this.logger)}}});var go,Ea=w(()=>{"use strict";go=class{name="cerebras";async transformRequestIn(e,t){let o=JSON.parse(JSON.stringify(e));return o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}}});var ho,Oa=w(()=>{"use strict";ho=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var yo,Aa=w(()=>{"use strict";yo=class{name="OpenAI";endPoint="/v1/chat/completions"}});var _o,Ia=w(()=>{"use strict";_o=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let t={...e},o=Object.entries(this.options);for(let[r,s]of o)if(r in t)if(typeof t[r]=="object"&&typeof s=="object"&&!Array.isArray(t[r])&&!Array.isArray(s)&&t[r]!==null&&s!==null)t[r]=this.deepMergeObjects(t[r],s);else continue;else t[r]=this.cloneValue(s);return t}async transformResponseOut(e){return e}deepMergeObjects(e,t){let o={...e};for(let[r,s]of Object.entries(t))r in o&&typeof o[r]=="object"&&typeof s=="object"&&!Array.isArray(o[r])&&!Array.isArray(s)&&o[r]!==null&&s!==null?o[r]=this.deepMergeObjects(o[r],s):o[r]=this.cloneValue(s);return o}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>this.cloneValue(o));let t={};for(let[o,r]of Object.entries(e))t[o]=this.cloneValue(r);return t}}});var Ma,bo,Na=w(()=>{"use strict";te();Ma=require("uuid"),bo=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,f,g)=>{let _=h.split(`
|
|
236
|
+
`);for(let b of _)b.trim()&&f.enqueue(g.encode(b+`
|
|
237
|
+
`))},m=(h,f)=>{let{controller:g,encoder:_}=f;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let b=h.slice(6);try{let y=JSON.parse(b);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:i},"usage"),y.choices[0].finish_reason=i?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"&&g.enqueue(_.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
|
|
235
238
|
|
|
236
|
-
`)),y.choices?.[0]?.delta?.content&&!
|
|
239
|
+
`)),y.choices?.[0]?.delta?.content&&!f.hasTextContent()&&f.setHasTextContent(!0),y.choices?.[0]?.delta?.reasoning){f.appendReasoningContent(y.choices[0].delta.reasoning);let T={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let S=`data: ${JSON.stringify(T)}
|
|
237
240
|
|
|
238
|
-
`;
|
|
241
|
+
`;g.enqueue(_.encode(S));return}if(y.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let S={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:"ccr_think_signature"}}}]};S.choices?.[0]?.delta&&delete S.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(S)}
|
|
239
242
|
|
|
240
|
-
`;
|
|
243
|
+
`;g.enqueue(_.encode(v))}y.choices?.[0]?.delta?.reasoning&&delete y.choices[0].delta.reasoning,y.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(y.choices?.[0]?.delta?.tool_calls[0].id,10))&&y.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${(0,Ma.v4)()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),y.choices?.[0]?.delta?.tool_calls?.length&&f.hasTextContent()&&(typeof y.choices[0].index=="number"?y.choices[0].index+=1:y.choices[0].index=1);let k=`data: ${JSON.stringify(y)}
|
|
241
244
|
|
|
242
|
-
`;
|
|
243
|
-
`))}}else
|
|
244
|
-
`))};try{for(;;){let{done:h,value:
|
|
245
|
-
`);
|
|
246
|
-
`))}continue}let _=
|
|
247
|
-
`);
|
|
248
|
-
`))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{
|
|
245
|
+
`;g.enqueue(_.encode(k))}catch{g.enqueue(_.encode(h+`
|
|
246
|
+
`))}}else g.enqueue(_.encode(h+`
|
|
247
|
+
`))};try{for(;;){let{done:h,value:f}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!f||f.length===0)continue;let g;try{g=t.decode(f,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(g.length===0)continue;if(c+=g,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
|
|
248
|
+
`);c=b.pop()||"";for(let y of b)if(y.trim())try{m(y,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",y,k),u.enqueue(o.encode(y+`
|
|
249
|
+
`))}continue}let _=c.split(`
|
|
250
|
+
`);c=_.pop()||"";for(let b of _)if(b.trim())try{m(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",b,y),u.enqueue(o.encode(b+`
|
|
251
|
+
`))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var $r,td,ko,$a=w(()=>{"use strict";te();$r=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
249
252
|
|
|
250
253
|
Output format:
|
|
251
254
|
<reasoning_content>
|
|
252
255
|
Your detailed thinking process goes here
|
|
253
256
|
</reasoning_content>
|
|
254
|
-
Your final answer must follow after the closing tag above.`,
|
|
255
|
-
${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text
|
|
257
|
+
Your final answer must follow after the closing tag above.`,td=10,ko=class{name="forcereasoning";async transformRequestIn(e){let t=0;e.messages.filter(r=>r.role==="assistant").reverse().forEach(r=>{r.thinking&&(r.thinking.content&&(!r.content||t<td)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
|
|
258
|
+
${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:$r}):o.content=[{type:"text",text:$r},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:$r}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await U(e);if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=r.choices[0]?.message.content.match(s);a&&a[1]&&(r.thinking={content:a[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,a=new TextEncoder,i=new ReadableStream({async start(c){let l=e.body.getReader(),u="",p="SEARCHING",d="",m="",h=(f,g)=>{if(typeof g!="string"){f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0&&!f.choices[0].delta.content&&(f.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(f)}
|
|
256
259
|
|
|
257
|
-
`)));return}let _=
|
|
260
|
+
`)));return}let _=d+g;for(d="";_.length>0;)if(p==="SEARCHING"){let b=_.indexOf(t);if(b!==-1)_=_.substring(b+t.length),p="REASONING";else{for(let y=t.length-1;y>0;y--)if(_.endsWith(t.substring(0,y))){d=_.substring(_.length-y);break}_=""}}else if(p==="REASONING"){let b=_.indexOf(o);if(b!==-1){let y=_.substring(0,b);if(y.length>0){let S={...f.choices[0].delta,thinking:{content:y}};delete S.content;let v={...f,choices:[{...f.choices[0],delta:S,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
258
261
|
|
|
259
|
-
`))}let
|
|
262
|
+
`))}let k={...f.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let T={...f,choices:[{...f.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
260
263
|
|
|
261
|
-
`)),r++,_=_.substring(
|
|
264
|
+
`)),r++,_=_.substring(b+o.length),p="FINAL"}else{let y=_;for(let k=o.length-1;k>0;k--)if(_.endsWith(o.substring(0,k))){d=_.substring(_.length-k),y=_.substring(0,_.length-k);break}if(y.length>0){let k={...f.choices[0].delta,thinking:{content:y}};delete k.content;let T={...f,choices:[{...f.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
262
265
|
|
|
263
|
-
`))}_=""}}else if(
|
|
266
|
+
`))}_=""}}else if(p==="FINAL"){if(_.length>0)if(/^\s*$/.test(_))m+=_;else{let y=m+_,k={...f.choices[0].delta,content:y};k.thinking&&delete k.thinking;let T={...f,choices:[{...f.choices[0],delta:k}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
264
267
|
|
|
265
|
-
`)),m=""}r++,_=""}};try{for(;;){let{done:
|
|
266
|
-
`);u=
|
|
268
|
+
`)),m=""}r++,_=""}};try{for(;;){let{done:f,value:g}=await l.read();if(f)break;let _=s.decode(g,{stream:!0});u+=_;let b=u.split(`
|
|
269
|
+
`);u=b.pop()||"";for(let y of b)if(y.trim()){if(y.trim()==="data: [DONE]"){c.enqueue(a.encode(y+`
|
|
267
270
|
|
|
268
|
-
`));break}if(y.startsWith("data:"))try{let
|
|
269
|
-
`))}else
|
|
270
|
-
`))}}}catch(
|
|
271
|
+
`));break}if(y.startsWith("data:"))try{let k=JSON.parse(y.slice(5));h(k,k.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(y+`
|
|
272
|
+
`))}else c.enqueue(a.encode(y+`
|
|
273
|
+
`))}}}catch(f){console.error("Stream error:",f),c.error(f)}finally{try{l.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}if(p==="REASONING"){let g={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};c.enqueue(a.encode(`data: ${JSON.stringify(g)}
|
|
271
274
|
|
|
272
|
-
`))}
|
|
273
|
-
`));break}let
|
|
274
|
-
`);
|
|
275
|
+
`))}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var To,La=w(()=>{"use strict";te();To=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(c){let l=e.body.getReader();try{for(;;){let{done:u,value:p}=await l.read();if(u){a.trim()&&c.enqueue(r.encode(a+`
|
|
276
|
+
`));break}let d=o.decode(p,{stream:!0});a+=d;let m=a.split(`
|
|
277
|
+
`);a=m.pop()||"";for(let h of m)if(h.trim())if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let f=JSON.parse(h.slice(6));if(f.choices?.[0]?.delta?.reasoning_content){s+=f.choices[0].delta.reasoning_content;let g={...f,choices:[{...f.choices[0],delta:{thinking:{content:f.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,c.enqueue(r.encode(`data: ${JSON.stringify(g)}
|
|
275
278
|
|
|
276
|
-
`));continue}if(
|
|
279
|
+
`));continue}if(f.choices?.[0]?.delta?.content&&s&&!f.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),_={...f,choices:[{...f.choices[0],delta:{content:null,thinking:{content:s,signature:g}}}]};c.enqueue(r.encode(`data: ${JSON.stringify(_)}
|
|
277
280
|
|
|
278
|
-
`)),s=""}
|
|
281
|
+
`)),s=""}f.choices?.[0]?.delta?.reasoning_content&&delete f.choices[0].delta.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0&&c.enqueue(r.encode(`data: ${JSON.stringify(f)}
|
|
279
282
|
|
|
280
|
-
`))}catch{
|
|
281
|
-
`))}else
|
|
282
|
-
`))}}catch(u){
|
|
283
|
-
`);for(let
|
|
284
|
-
`))},m=(h,
|
|
283
|
+
`))}catch{c.enqueue(r.encode(h+`
|
|
284
|
+
`))}else c.enqueue(r.encode(h+`
|
|
285
|
+
`))}}catch(u){c.error(u)}finally{try{l.releaseLock()}catch{}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await U(e);return o.choices?.[0]?.message?.reasoning_content&&(o.choices[0].message.thinking={content:o.choices[0].message.reasoning_content},delete o.choices[0].message.reasoning_content),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}}});var Lr,vo,Da=w(()=>{"use strict";te();ct();Lr=require("uuid"),vo=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(l=>l.toLowerCase()===a),c=i?r[i]:void 0;return typeof c=="string"&&c.trim()?c.trim():void 0};return s("x-opencode-session")||o?.clientContext?.stableSessionId||o?.sessionId||Ce(e.metadata?.user_id)||s("session_id")||(0,Lr.v4)()}async transformRequestIn(e,t,o){let r=e.reasoning?.enabled||e.messages.some(s=>s.thinking?.content);return e.messages.forEach(s=>{if(Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)}),s.role==="assistant"){let a=s.thinking?.content,i=s.thinking?.signature;a&&typeof a=="string"&&a.trim()?(s.reasoning_content=a,i&&(s.reasoning_content_signature=i)):r&&s.tool_calls?.length&&!s.reasoning_content&&(s.reasoning_content=" "),s.thinking&&delete s.thinking}}),Object.assign(e,this.options||{}),{body:e,config:{headers:{"x-opencode-session":this.resolveSessionId(e,o)}}}}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await U(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,f,g)=>{let _=h.split(`
|
|
286
|
+
`);for(let b of _)b.trim()&&f.enqueue(g.encode(b+`
|
|
287
|
+
`))},m=(h,f)=>{let{controller:g,encoder:_}=f;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let b=JSON.parse(h.slice(6));if(b.usage&&(b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){g.enqueue(_.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
|
|
285
288
|
|
|
286
|
-
`));return}
|
|
289
|
+
`));return}b.choices?.[0]?.delta?.content&&!f.hasTextContent()&&f.setHasTextContent(!0);let y=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(y){f.appendReasoningContent(y);let R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:y}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),g.enqueue(_.encode(`data: ${JSON.stringify(R)}
|
|
287
290
|
|
|
288
|
-
`));return}if(
|
|
291
|
+
`));return}if(b.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let R="ccr_think_signature",C=b.choices[0].delta.content,x={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:R}}}]};x.choices?.[0]?.delta&&(delete x.choices[0].delta.reasoning,delete x.choices[0].delta.reasoning_content),g.enqueue(_.encode(`data: ${JSON.stringify(x)}
|
|
289
292
|
|
|
290
|
-
`));let
|
|
293
|
+
`));let O={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:C}}]};O.choices?.[0]?.delta&&(delete O.choices[0].delta.reasoning,delete O.choices[0].delta.reasoning_content),g.enqueue(_.encode(`data: ${JSON.stringify(O)}
|
|
291
294
|
|
|
292
|
-
`));return}
|
|
295
|
+
`));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${(0,Lr.v4)()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,T=k&&Object.keys(k).length>0,S=b.choices?.[0]?.finish_reason,v=b.usage;(T||S||v)&&g.enqueue(_.encode(`data: ${JSON.stringify(b)}
|
|
293
296
|
|
|
294
|
-
`))}catch{
|
|
295
|
-
`))}else
|
|
296
|
-
`))};try{for(;;){let{done:h,value:
|
|
297
|
-
`);
|
|
298
|
-
`))}continue}let _=
|
|
299
|
-
`);
|
|
300
|
-
`))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{
|
|
297
|
+
`))}catch{g.enqueue(_.encode(h+`
|
|
298
|
+
`))}else g.enqueue(_.encode(h+`
|
|
299
|
+
`))};try{for(;;){let{done:h,value:f}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!f||f.length===0)continue;let g;try{g=t.decode(f,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(g.length===0)continue;if(c+=g,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
|
|
300
|
+
`);c=b.pop()||"";for(let y of b)if(y.trim())try{m(y,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",y,k),u.enqueue(o.encode(y+`
|
|
301
|
+
`))}continue}let _=c.split(`
|
|
302
|
+
`);c=_.pop()||"";for(let b of _)if(b.trim())try{m(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>a,setReasoningComplete:y=>a=y})}catch(y){console.error("Error processing line:",b,y),u.enqueue(o.encode(b+`
|
|
303
|
+
`))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function od(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim();if(!e)return;let t=e.toLowerCase();return["none","low","medium","high","max"].includes(t)?t:/^\d+$/.test(e)?parseInt(e,10):e}function rd(n){let e="";try{e=new URL(String(n||"")).pathname.replace(/\/+$/,"")}catch{return"chat"}return e.endsWith("/messages")?"anthropic":e.endsWith("/responses")?"responses":"chat"}var nd,xo,Fa=w(()=>{"use strict";mt();nd={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};xo=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=od(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=rd(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=Oe(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=nd[o.toLowerCase()];return s?(r==="anthropic"?e.reasoning={enabled:!0,effort:s}:r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e):(r==="chat"?e.reasoning_effort=o:r==="responses"&&(e.reasoning={enabled:!0,effort:o}),e)}}});function Ua(n,e=!1){if(!n||typeof n!="object"||n.thinking)return!1;let t=n.reasoning,o=typeof t=="string"?t:t?.content;return typeof o=="string"&&o.length>0?(e&&typeof t=="object"?n.thinking={content:o}:(n.thinking=typeof t=="string"?{content:o}:{...t},delete n.reasoning),!0):typeof n.reasoning_content=="string"&&n.reasoning_content?(n.thinking={content:n.reasoning_content},!0):!1}var Co,ja=w(()=>{"use strict";mt();te();Co=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),a=!r&&!s&&o.includes("deepseek");if(e==="none")return a||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return a?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return a?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,a=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,a=a||r.effort==="none"):typeof r?.max_tokens=="number"?s=Oe(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!a&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(a=!0));let i=this.resolveEffort(a?"none":s,o);return i?t.reasoning_effort=i:delete t.reasoning_effort,delete t.reasoning,delete t.thinking,delete t.enable_thinking,t}async transformResponseOut(e){let t=e.headers.get("Content-Type")??"";if(t.includes("application/json")){if(!e.body)return e;let o=await Te(e);if(o){let a=new Headers(e.headers);if(o.isSSE&&a.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:a}),o.isSSE)return this.transformStream(e)}else{let a=await Pe(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await U(e);this.liftMessageReasoning(r);let s=new Headers(e.headers);return s.delete("content-length"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}return(t.includes("stream")||t.includes("event-stream"))&&e.body?this.transformStream(e):e}liftMessageReasoning(e){if(Array.isArray(e?.choices))for(let t of e.choices)Ua(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=l=>{if(!l.startsWith("data:"))return l;let u=l.slice(5).trim();if(u==="[DONE]")return l;let p;try{p=JSON.parse(u)}catch{return l}let d=!1,m=Array.isArray(p?.choices)?p.choices:[];for(let h of m)Ua(h?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:l},a=(l,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,m,h="";for(;(m=p.exec(r))!==null&&!(!u&&m[0]==="\r"&&p.lastIndex===r.length);)h+=s(r.slice(d,m.index))+m[0],d=p.lastIndex;r=r.slice(d),u&&(h+=s(r),r=""),h&&l.enqueue(o.encode(h))},i=e.body.pipeThrough(new TransformStream({transform(l,u){r+=t.decode(l,{stream:!0}),a(u)},flush(l){r+=t.decode(),a(l,!0)}})),c=new Headers(e.headers);return c.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:c})}}});var Ha,za=w(()=>{ia();aa();ca();la();ua();pa();fa();ga();ha();ka();Ta();va();xa();Pa();Ea();Oa();Aa();Ia();Na();br();$a();La();Da();Fa();ja();Ha={AnthropicTransformer:Xn,GeminiTransformer:to,VertexGeminiTransformer:no,VertexClaudeTransformer:mo,DeepseekTransformer:oo,TooluseTransformer:ro,OpenrouterTransformer:so,OpenAITransformer:yo,MaxTokenTransformer:io,GroqTransformer:ao,CleancacheTransformer:co,EnhanceToolTransformer:lo,ReasoningTransformer:uo,SamplingTransformer:po,MaxCompletionTokens:fo,CerebrasTransformer:go,StreamOptionsTransformer:ho,CustomParamsTransformer:_o,VercelTransformer:bo,OpenAIResponsesTransformer:rt,ForceReasoningTransformer:ko,KimiTransformer:To,OpenCodeTransformer:vo,DefaultThinkingTransformer:xo,AmdTransformer:Co}});var Ke,Dr=w(()=>{"use strict";za();Ke=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;preparePluginTransformer(e){if(typeof e.TransformerName=="string")return e;let t=new e;if(!t?.name)throw new Error("plugin transformer has no name");return t.logger=this.logger,t}registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=require(require.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
|
|
301
304
|
error: ${t.message}
|
|
302
305
|
stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
303
|
-
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(la).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});var da,It,pa=E(()=>{"use strict";da=require("tiktoken"),It=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,da.get_encoding)(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:i}=e;return Array.isArray(r)&&r.forEach(a=>{typeof a.content=="string"?o+=t.encode(a.content).length:Array.isArray(a.content)&&a.content.forEach(l=>{if(l.type==="text")o+=t.encode(l.text).length;else if(l.type==="tool_use")o+=t.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let c=typeof l.content=="string"?l.content:JSON.stringify(l.content);o+=t.encode(c).length}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(a=>{a.type==="text"&&(typeof a.text=="string"?o+=t.encode(a.text).length:Array.isArray(a.text)&&a.text.forEach(l=>{o+=t.encode(l||"").length}))}),i&&i.forEach(a=>{a.description&&(o+=t.encode(a.name+a.description).length),a.input_schema&&(o+=t.encode(JSON.stringify(a.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});var Mt,fa,ut,Nt,ma,po,ga=E(()=>{"use strict";Mt=require("path"),fa=require("os"),ut=require("fs"),Nt=require("fs"),ma=require("@huggingface/tokenizers"),po=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||(0,Mt.join)((0,fa.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,Mt.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,Mt.join)(e,"tokenizer.json"),tokenizerConfig:(0,Mt.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,ut.existsSync)(e)||(0,ut.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,ut.existsSync)(e.tokenizerJson)||!(0,ut.existsSync)(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Nt.promises.readFile(e.tokenizerJson,"utf-8"),Nt.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,i]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[a,l]=await Promise.all([s.json(),i.ok?i.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Nt.promises.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),Nt.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:a,tokenizerConfig:l}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new ma.Tokenizer(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let i of o)if(typeof i.content=="string")t.push(i.content);else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"&&a.text?t.push(a.text):a.type==="tool_use"&&a.input?t.push(JSON.stringify(a.input)):a.type==="tool_result"&&t.push(typeof a.content=="string"?a.content:JSON.stringify(a.content))}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let i of r)if(i.type==="text"){if(typeof i.text=="string")t.push(i.text);else if(Array.isArray(i.text))for(let a of i.text)a&&t.push(a)}}if(s)for(let i of s)i.name&&t.push(i.name),i.description&&t.push(i.description),i.input_schema&&t.push(JSON.stringify(i.input_schema));return t.join(" ")}}});var fo,ha=E(()=>{"use strict";ae();fo=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),i={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},a=this.options.resolveProxyUrl?.();a&&(i.dispatcher=Q(a));let l=await fetch(this.config.url,i);if(clearTimeout(s),!l.ok)throw new Error(`API tokenizer request failed: ${l.status} ${l.statusText}`);let c=await l.json();return this.extractTokenCount(c)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var ze,yr=E(()=>{"use strict";pa();ga();ha();ae();ze=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new It("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new It(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new po(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new fo(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return pe(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function ya(n){if(!n||typeof n!="object"||Tu(n))return null;for(let t of bu(n)){let o=ku(t);if(o)return o}return null}function ku(n){if(!n||typeof n!="object")return null;let e={},t=mo(n,gu);if(t!==void 0){let i=_a(t);e.usedDailyBalance=i,e.limitDaily=100}let o=mo(n,hu);if(o!==void 0){let i=_a(o);e.usedBalance=i,e.totalBalance=100}let r=mo(n,yu);if(r!==void 0){let i=ka(r);i&&(e.resetTime=i)}let s=mo(n,_u);if(s!==void 0){let i=ka(s);i&&(e.resetTime7d=i,e.resetTime||(e.resetTime=i))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function _a(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function mo(n,e){for(let t of e){let o=M(n?.[t]);if(o!==void 0)return o}}function bu(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let i of o)s[i]&&typeof s[i]=="object"&&r(s[i])}};return r(n),e}function Tu(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function ka(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function go(n){let e=Pr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Pu:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Ou:e==="deepseek.com"||e.endsWith(".deepseek.com")?vu:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?xu:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Cu:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Su:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Ru:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?wu:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Eu:null:null}function Au(n){let e=Pr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Iu(n,e){let t=wr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let i=s?.codingPlanAppCredentialDTO||s?.appCredential||s,a=String(i?.apiKey||i?.api_key||"").trim();return a&&o.some(l=>l.includes(a)||a.includes(l))})||t[0]}function wr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>wr(e)):Object.values(n).flatMap(e=>wr(e))}function Er(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Pr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function M(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var ue,_r,kr,br,Tr,vr,gu,hu,yu,_u,xr,Cr,Sr,Rr,vu,xu,Cu,Su,Ru,wu,Eu,Pu,Ou,Or=E(()=>{"use strict";ae();ue=class{async fetchJson(e,t,o,r,s){let i=s||t.apiKey;if(!i)return null;let a={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${i}`},signal:AbortSignal.timeout(o)};try{r&&(a.dispatcher=Q(r));let l=await fetch(e,a);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},_r=class extends ue{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),i=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(l=>M(l?.total_balance)!==void 0);if(!i)return null;let a=M(i.total_balance);return a===void 0?null:{totalBalance:a,currency:typeof i.currency=="string"?i.currency:void 0}}},kr=class extends ue{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let i={},a=M(s.limit),l=M(s.limit_remaining),c=M(s.usage),u=M(s.usage_daily);return a!==void 0&&(i.totalBalance=a),l!==void 0&&(i.remainingBalance=l),c!==void 0&&(i.usedBalance=c),u!==void 0&&(i.usedDailyBalance=u),this.hasQuotaData(i)?i:null}},br=class extends ue{async queryQuota(e,t,o){let r=Au(e.baseUrl),i=(await this.fetchJson(r,e,t,o))?.data;if(!i||typeof i!="object")return null;let a={},l=M(i.totalBalance),c=M(i.balance);return l!==void 0&&(a.totalBalance=l),c!==void 0&&(a.remainingBalance=c),l!==void 0&&c!==void 0&&(a.usedBalance=Math.max(0,l-c)),this.hasQuotaData(a)?a:null}},Tr=class extends ue{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Q(o));let i=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!i.ok)return null;let a=await i.json(),l=Array.isArray(a?.data?.limits)?a.data.limits:[],c=null,u=null,d=null;for(let m of l)m.type==="TOKENS_LIMIT"?m.unit===3?c=m:m.unit===6?u=m:c||(c=m):m.type==="TIME_LIMIT"&&(d=m);let p={};if(c){let m=M(c.currentValue),h=M(c.usage),g=M(c.remaining),f=M(c.percentage);m!==void 0?p.usedDailyBalance=m:f!==void 0&&(p.usedDailyBalance=f,p.limitDaily=100),h!==void 0?p.limitDaily=h:m!==void 0&&g!==void 0&&(p.limitDaily=m+g),c.nextResetTime&&(p.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let m=M(u.currentValue),h=M(u.usage),g=M(u.remaining),f=M(u.percentage);m!==void 0?p.usedBalance=m:f!==void 0&&(p.usedBalance=f,p.totalBalance=100),h!==void 0?p.totalBalance=h:m!==void 0&&g!==void 0&&(p.totalBalance=m+g),u.nextResetTime&&!p.resetTime&&(p.resetTime=new Date(u.nextResetTime).toISOString())}if(d){if(p.usedDailyBalance===void 0){let m=M(d.currentValue);m!==void 0&&(p.usedDailyBalance=m)}if(p.limitDaily===void 0){let m=M(d.usage),h=M(d.currentValue),g=M(d.remaining);m!==void 0?p.limitDaily=m:h!==void 0&&g!==void 0&&(p.limitDaily=h+g)}d.nextResetTime&&!p.resetTime&&(p.resetTime=new Date(d.nextResetTime).toISOString())}return this.hasQuotaData(p)?p:null}catch{return null}}},vr=class extends ue{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),i=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=Q(o));let a=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:i});if(!a.ok)return null;let c=(await a.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(c)||c.length===0)return null;let u=c[0]?.codingPlanQuotaInfo;if(!u)return null;let d={},p=M(u.per5HourUsedQuota),m=M(u.per5HourTotalQuota);p!==void 0&&(d.usedDailyBalance=p),m!==void 0&&(d.limitDaily=m);let h=M(u.perWeekUsedQuota),g=M(u.perWeekTotalQuota);return h!==void 0&&(d.usedBalance=h),g!==void 0&&(d.totalBalance=g),this.hasQuotaData(d)?d:null}catch{return null}}};gu=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],hu=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],yu=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],_u=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];xr=class extends ue{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let i=await this.queryOfficialEndpoint(r,s,t,o);if(i)return i}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",i=Er(e,"cna")||"",a=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":i}}}),l=new URLSearchParams({params:a,region:"cn-beijing",sec_token:t}).toString(),c={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:l,signal:AbortSignal.timeout(o)};try{r&&(c.dispatcher=Q(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,c);if(!u.ok)return null;let d=await u.json();return ya(d)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),i=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),a={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:i,signal:AbortSignal.timeout(t)};try{o&&(a.dispatcher=Q(o));let l=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,a);if(!l.ok)return null;let c=await l.json();return ya(c)}catch{return null}}},Cr=class extends ue{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Er(e.quotaToken,"atp-auth-token")||Er(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Q(o));let i=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!i.ok)return null;let a=await i.json();if(a?.succeed===!1||a?.failed===!0)return null;let l=Iu(a,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},d=M(c.rp5hUsage),p=M(c.rp5hLimit);d!==void 0&&(u.usedDailyBalance=d),p!==void 0&&(u.limitDaily=p);let m=M(c.rpwUsage),h=M(c.rpwLimit);return m!==void 0&&(u.usedBalance=m),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&m!==void 0&&(u.remainingBalance=Math.max(0,h-m)),this.hasQuotaData(u)?u:null}catch{return null}}},Sr=class extends ue{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Q(o));let i=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!i.ok)return null;let a=await i.json(),l={},c=Array.isArray(a?.limits)?a.limits:[];if(c.length>0&&c[0]?.detail){let d=c[0].detail,p=M(d.limit),m=M(d.remaining),h=d.resetTime;p!==void 0&&m!==void 0&&(l.usedDailyBalance=Math.max(0,p-m),l.limitDaily=p),h&&(l.resetTime=new Date(h).toISOString())}let u=a?.usage;if(u){let d=M(u.limit),p=M(u.remaining),m=M(u.used),h=u.resetTime;d!==void 0&&(l.totalBalance=d,m!==void 0?l.usedBalance=m:p!==void 0&&(l.usedBalance=Math.max(0,d-p),l.remainingBalance=p)),h&&(l.resetTime7d=new Date(h).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Rr=class extends ue{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Pr(e.baseUrl)||"api.minimaxi.com",i=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let a=[`https://${i}/v1/token_plan/remains`,`https://${i}/v1/api/openplatform/coding_plan/remains`],l=null;for(let b of a)if(l=await this.fetchJson(b,e,t,o,r.trim()),l)break;if(!l)return null;if(l?.base_resp){let b=l.base_resp.status_code;if(b!==void 0&&b!==0)return null}let c=Array.isArray(l?.model_remains)?l.model_remains:[];if(c.length===0)return null;let u=c[0],d={},p=M(u.current_interval_total_count),m=M(u.current_interval_usage_count),h=M(u.current_interval_remaining_percent),g=M(u.end_time);p!==void 0&&m!==void 0&&p>0?(d.usedDailyBalance=Math.max(0,p-m),d.limitDaily=p):h!==void 0&&(d.limitDaily=100,d.usedDailyBalance=Math.max(0,100-h)),g&&(d.resetTime=new Date(g).toISOString());let f=M(u.current_weekly_total_count),_=M(u.current_weekly_usage_count),k=M(u.current_weekly_remaining_percent),y=M(u.weekly_end_time);return f!==void 0&&_!==void 0&&f>0?(d.usedBalance=Math.max(0,f-_),d.remainingBalance=_,d.totalBalance=f):k!==void 0&&(d.totalBalance=100,d.usedBalance=Math.max(0,100-k),d.remainingBalance=k),y&&!d.resetTime&&(d.resetTime=new Date(y).toISOString()),this.hasQuotaData(d)?d:null}catch{return null}}},vu=new _r,xu=new kr,Cu=new br,Su=new Tr,Ru=new vr,wu=new xr,Eu=new Cr,Pu=new Sr,Ou=new Rr});function ba(n){return{[Mu]:n,[Nu]:gn}}function Lu(n){return n===!0||n==="true"||n===1||n==="1"}function Du(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function Fu(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function Uu(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Ar(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o)),s=Fu(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let i={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(i.dispatcher=Q(t));let a=await fetch(s,i);if(a.headers&&vt(n.name,n.baseUrl,a.headers),a.ok)return{success:!0,headers:a.headers,latencyMs:r()};if(a.status===429)return{success:!1,error:`HTTP 429: ${(await a.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:a.headers,latencyMs:r(),errorKind:"http"};if(a.status>=400&&a.status<500)return{success:!0,headers:a.headers,latencyMs:r()};let l=await a.text().catch(()=>"");return{success:!1,error:`HTTP ${a.status}: ${l.slice(0,100)}`,headers:a.headers,latencyMs:r(),errorKind:"http"}}catch(i){let a=i?.message||i?.toString()||"Unknown probe error",l=i?.name==="TimeoutError"||i?.name==="AbortError"||i?.code===20||i?.code==="ABORT_ERR";return{success:!1,error:a,latencyMs:r(),errorKind:l?"timeout":"network"}}}async function ju(n,e,t,o){let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,i=n.baseUrl.includes("/messages")||r.includes("claude");try{let a={"Content-Type":"application/json",...ba("scheduled-wakeup")};i?(a["x-api-key"]=n.apiKey,a["anthropic-version"]="2023-06-01"):a.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:a,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(l.dispatcher=Q(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let c=await fetch(s,l);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(a){return{success:!1,error:a?.message||a?.toString()||"Unknown wake-up error"}}}async function Hu(n,e,t,o,r){let s=n.baseUrl,i=n.baseUrl.includes("/messages")||e.includes("claude");try{let a={"Content-Type":"application/json",...ba("rate-limit-probe")};i?(a["x-api-key"]=n.apiKey,a["anthropic-version"]="2023-06-01"):a.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:a,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(l.dispatcher=Q(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let c=await fetch(s,l);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(a){return{success:!1,error:a?.message||a?.toString()||"Unknown ping error"}}}function Ir(n,e,t,o,r){return Ee||(Ee=new $t(n,e,t,o,r)),Ee}function Be(n,e,t,o,r){let s=Ir(n,e,t,o,r);return s.start(),s}function ho(){Ee&&Ee.stop()}function Lt(){Ee&&(Ee.stop(),Ee=null)}var Mu,Nu,$u,$t,Ee,yo=E(()=>{"use strict";ce();Xe();Or();tt();Do();ae();Mu="x-claude-code-router-source",Nu="x-claude-code-router-version";$u={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};$t=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s){this.config={...$u,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,i;t.success?i=s?"slow":"healthy":i=t.errorKind==="timeout"?"timeout":"error";let a=this.probeTelemetry.get(e),l={provider:e,latencyMs:t.latencyMs,status:i,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:a?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,l),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),l}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let i=go(s.baseUrl),a=Array.isArray(s.models)?s.models:[],l=this.resolveProxyUrl?.(s);if(!i){let c;try{c=new URL(s.baseUrl).hostname}catch{c=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(c?` (host: ${c})`:"")+" \u2014 skipping quota probe")}i&&o.push({provider:s.name,models:a,type:"quota-adapter",promise:i.queryQuota(s,this.config.probeTimeoutMs,l).then(c=>{if(c){xn(s.name,c),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,d=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(u||d){let p=u?`Quota exhausted: 5h limit reached (${c.usedDailyBalance}/${c.limitDaily})`:`Quota exhausted: 7d balance depleted (${c.usedBalance}/${c.totalBalance})`;for(let m of a){if(t.getState(s.name,m)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${m}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,m,p)}this.logger?.warn?.(`${p} for ${s.name}, marked as unhealthy`)}else for(let p of a){let m=t.getState(s.name,p);m&&m.status==="open"&&m.lastError?.includes("Quota exhausted")&&(t.recover(s.name,p),this.logger?.info?.(`Quota recovered for ${s.name} (${p}), marked as healthy`))}}})}),Uu(s.baseUrl)&&o.push({provider:s.name,models:a,type:"rate-limit-headers",promise:Ar(s,this.config.probeTimeoutMs,l).then(c=>{this.recordProbe(s.name,c,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let i=r[s];if(i.status==="rejected"){let a=o[s];this.logger?.warn?.(`Quota probe failed for ${a.provider} (${a.type}): ${i.reason}`)}}}async runHealthProbe(){let e=j(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Ar(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],i=o[r],a=Array.isArray(s.models)?s.models:[];if(i.status==="fulfilled"){let l=i.value;if(this.recordProbe(s.name,l,"health"),l.success){let c=0;for(let u of a){let d=e.getState(s.name,u);if(d&&d.status==="open"){let p=d.lastError?.includes("Quota exhausted"),m=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(p){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(m||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),c++}c>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let c of a)e.recordFailure(s.name,c,l.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${l.error}`)}}else{this.recordProbe(s.name,{success:!1,error:i.reason?.message||String(i.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let l of a)e.recordFailure(s.name,l,i.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${i.reason}`)}}}async runRateLimitProbe(){let e=j(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[i,...a]=s.split(","),l=a.join(",");if(!i||!l)continue;let c=e.getState(i,l);if(!c||!c.rateLimitUntil)continue;if(Date.now()>=c.rateLimitUntil){e.recover(i,l),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let u=o.find(d=>d?.name===i&&d.enabled!==!1);if(!u){this.logger?.warn?.(`Provider ${i} not found or disabled for rate-limit probe`);continue}try{let d=await Hu(u,l,r,this.resolveProxyUrl?.(u),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(i,l);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let p=Date.now();c.rateLimitUntil&&c.rateLimitUntil>p?c.rateLimitUntil+=120*1e3:c.rateLimitUntil=p+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&a.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=Du(t),i=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let a of e){let l=a.wakeupTime||i,[c,u]=l.split(":"),d=parseInt(c,10),p=parseInt(u,10);if(isNaN(d)||isNaN(p))continue;let m=o>d||o===d&&r>=p,h=(d*60+p)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(m||g)&&!this.hasWakeupFiredToday(a.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${a.name} at ${l}`),ju(a,3e4,this.resolveProxyUrl?.(a),this.logger).then(f=>{f.success?this.logger?.info?.(`Successfully woke up provider ${a.name}`):this.logger?.error?.(`Failed to wake up provider ${a.name}: ${f.error}`)}).catch(f=>{this.logger?.error?.(`Error in wake-up task for ${a.name}: ${f}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?Lu(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(a=>a.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Ar(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o)),s=this.recordProbe(o.name,r,"manual"),i=Array.isArray(o.models)?o.models:[];if(r.success)for(let a of i)j().recordSuccess(o.name,a);else for(let a of i)j().recordFailure(o.name,a,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},Ee=null});var Ta=E(()=>{"use strict"});var Mr,dt,va=E(()=>{"use strict";Mr=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},dt=new Mr});var de,Nr=E(()=>{"use strict";de=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
304
|
-
`);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Je,$r=E(()=>{"use strict";Je=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
306
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Ha).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});var Ba,Bt,Ja=w(()=>{"use strict";Ba=require("tiktoken"),Bt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,Ba.get_encoding)(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(c=>{if(c.type==="text")o+=t.encode(c.text).length;else if(c.type==="tool_use")o+=t.encode(JSON.stringify(c.input)).length;else if(c.type==="tool_result"){let l=c.content;if(Array.isArray(l))for(let u of l)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof l=="string"?l:JSON.stringify(l);o+=t.encode(u).length}}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(c=>{o+=t.encode(c||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});var Jt,Wa,ht,Wt,Ka,So,Ga=w(()=>{"use strict";Jt=require("path"),Wa=require("os"),ht=require("fs"),Wt=require("fs"),Ka=require("@huggingface/tokenizers"),So=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||(0,Jt.join)((0,Wa.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,Jt.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,Jt.join)(e,"tokenizer.json"),tokenizerConfig:(0,Jt.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,ht.existsSync)(e)||(0,ht.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,ht.existsSync)(e.tokenizerJson)||!(0,ht.existsSync)(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Wt.promises.readFile(e.tokenizerJson,"utf-8"),Wt.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,c]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Wt.promises.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Wt.promises.writeFile(e.tokenizerConfig,JSON.stringify(c,null,2))]),{tokenizerJson:i,tokenizerConfig:c}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new Ka.Tokenizer(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let c of i.content)c?.type!=="image"&&t.push(c?.type==="text"?String(c.text??""):JSON.stringify(c));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Ro,Va=w(()=>{"use strict";ae();Ro=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},i=this.options.resolveProxyUrl?.();i&&(a.dispatcher=Y(i));let c=await fetch(this.config.url,a);if(clearTimeout(s),!c.ok)throw new Error(`API tokenizer request failed: ${c.status} ${c.statusText}`);let l=await c.json();return this.extractTokenCount(l)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
|
|
307
|
+
`):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ge,Fr=w(()=>{"use strict";Ja();Ga();Va();ae();Ge=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new Bt("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new Bt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new So(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Ro(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return me(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function Qa(n){if(!n||typeof n!="object"||dd(n))return null;for(let t of ud(n)){let o=ld(t);if(o)return o}return null}function ld(n){if(!n||typeof n!="object")return null;let e={},t=wo(n,sd);if(t!==void 0){let a=Ya(t);e.usedDailyBalance=a,e.limitDaily=100}let o=wo(n,id);if(o!==void 0){let a=Ya(o);e.usedBalance=a,e.totalBalance=100}let r=wo(n,ad);if(r!==void 0){let a=Xa(r);a&&(e.resetTime=a)}let s=wo(n,cd);if(s!==void 0){let a=Xa(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function Ya(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function wo(n,e){for(let t of e){let o=M(n?.[t]);if(o!==void 0)return o}}function ud(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function dd(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function Xa(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Po(n){let e=Yr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?bd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?kd:e==="deepseek.com"||e.endsWith(".deepseek.com")?pd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?fd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?md:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?gd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?hd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?yd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?_d:null:null}function Td(n){let e=Yr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function vd(n,e){let t=Vr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function Vr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Vr(e)):Object.values(n).flatMap(e=>Vr(e))}function Qr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Yr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function M(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var de,Ur,jr,Hr,zr,Br,sd,id,ad,cd,Jr,Wr,Kr,Gr,pd,fd,md,gd,hd,yd,_d,bd,kd,Xr=w(()=>{"use strict";ae();de=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=Y(r));let c=await fetch(e,i);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},Ur=class extends de{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>M(c?.total_balance)!==void 0);if(!a)return null;let i=M(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},jr=class extends de{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=M(s.limit),c=M(s.limit_remaining),l=M(s.usage),u=M(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},Hr=class extends de{async queryQuota(e,t,o){let r=Td(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=M(a.totalBalance),l=M(a.balance);return c!==void 0&&(i.totalBalance=c),l!==void 0&&(i.remainingBalance=l),c!==void 0&&l!==void 0&&(i.usedBalance=Math.max(0,c-l)),this.hasQuotaData(i)?i:null}},zr=class extends de{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Y(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),c=Array.isArray(i?.data?.limits)?i.data.limits:[],l=null,u=null,p=null;for(let m of c)m.type==="TOKENS_LIMIT"?m.unit===3?l=m:m.unit===6?u=m:l||(l=m):m.type==="TIME_LIMIT"&&(p=m);let d={};if(l){let m=M(l.currentValue),h=M(l.usage),f=M(l.remaining),g=M(l.percentage);m!==void 0?d.usedDailyBalance=m:g!==void 0&&(d.usedDailyBalance=g,d.limitDaily=100),h!==void 0?d.limitDaily=h:m!==void 0&&f!==void 0&&(d.limitDaily=m+f),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let m=M(u.currentValue),h=M(u.usage),f=M(u.remaining),g=M(u.percentage);m!==void 0?d.usedBalance=m:g!==void 0&&(d.usedBalance=g,d.totalBalance=100),h!==void 0?d.totalBalance=h:m!==void 0&&f!==void 0&&(d.totalBalance=m+f),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let m=M(p.currentValue);m!==void 0&&(d.usedDailyBalance=m)}if(d.limitDaily===void 0){let m=M(p.usage),h=M(p.currentValue),f=M(p.remaining);m!==void 0?d.limitDaily=m:h!==void 0&&f!==void 0&&(d.limitDaily=h+f)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},Br=class extends de{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=Y(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let l=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(l)||l.length===0)return null;let u=l[0]?.codingPlanQuotaInfo;if(!u)return null;let p={},d=M(u.per5HourUsedQuota),m=M(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),m!==void 0&&(p.limitDaily=m);let h=M(u.perWeekUsedQuota),f=M(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),f!==void 0&&(p.totalBalance=f),this.hasQuotaData(p)?p:null}catch{return null}}};sd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],id=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],ad=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],cd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Jr=class extends de{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Qr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=Y(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,l);if(!u.ok)return null;let p=await u.json();return Qa(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=Y(o));let c=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!c.ok)return null;let l=await c.json();return Qa(l)}catch{return null}}},Wr=class extends de{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Qr(e.quotaToken,"atp-auth-token")||Qr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Y(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let c=vd(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=M(l.rp5hUsage),d=M(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let m=M(l.rpwUsage),h=M(l.rpwLimit);return m!==void 0&&(u.usedBalance=m),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&m!==void 0&&(u.remainingBalance=Math.max(0,h-m)),this.hasQuotaData(u)?u:null}catch{return null}}},Kr=class extends de{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Y(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),c={},l=Array.isArray(i?.limits)?i.limits:[];if(l.length>0&&l[0]?.detail){let p=l[0].detail,d=M(p.limit),m=M(p.remaining),h=p.resetTime;d!==void 0&&m!==void 0&&(c.usedDailyBalance=Math.max(0,d-m),c.limitDaily=d),h&&(c.resetTime=new Date(h).toISOString())}let u=i?.usage;if(u){let p=M(u.limit),d=M(u.remaining),m=M(u.used),h=u.resetTime;p!==void 0&&(c.totalBalance=p,m!==void 0?c.usedBalance=m:d!==void 0&&(c.usedBalance=Math.max(0,p-d),c.remainingBalance=d)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},Gr=class extends de{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Yr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let k of i)if(c=await this.fetchJson(k,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let k=c.base_resp.status_code;if(k!==void 0&&k!==0)return null}let l=Array.isArray(c?.model_remains)?c.model_remains:[];if(l.length===0)return null;let u=l[0],p={},d=M(u.current_interval_total_count),m=M(u.current_interval_usage_count),h=M(u.current_interval_remaining_percent),f=M(u.end_time);d!==void 0&&m!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-m),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),f&&(p.resetTime=new Date(f).toISOString());let g=M(u.current_weekly_total_count),_=M(u.current_weekly_usage_count),b=M(u.current_weekly_remaining_percent),y=M(u.weekly_end_time);return g!==void 0&&_!==void 0&&g>0?(p.usedBalance=Math.max(0,g-_),p.remainingBalance=_,p.totalBalance=g):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),y&&!p.resetTime&&(p.resetTime=new Date(y).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},pd=new Ur,fd=new jr,md=new Hr,gd=new zr,hd=new Br,yd=new Jr,_d=new Wr,bd=new Kr,kd=new Gr});function Za(n){return{[xd]:n,[Cd]:En}}function Ve(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function Rd(n){return n===!0||n==="true"||n===1||n==="1"}function wd(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function Pd(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function Ed(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Zr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Ve(n))return{success:!1,skipped:!0,error:qr,latencyMs:r()};let s=Pd(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=Y(t));let i=await fetch(s,a);if(i.headers&&It(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let c=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${c.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",c=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:c?"timeout":"network"}}}async function Od(n,e,t,o){if(Ve(n))return{success:!1,skipped:!0,error:qr};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Za("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=Y(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function Ad(n,e,t,o,r){if(Ve(n))return{success:!1,skipped:!0,error:qr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Za("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=Y(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function es(n,e,t,o,r){return Ae||(Ae=new Kt(n,e,t,o,r)),Ae}function yt(n,e,t,o,r){let s=es(n,e,t,o,r);return s.start(),s}function Eo(){Ae&&Ae.stop()}function Oo(){Ae&&(Ae.stop(),Ae=null)}var xd,Cd,Sd,qr,Kt,Ae,Ao=w(()=>{"use strict";le();ot();Xr();at();or();ae();xd="x-claude-code-router-source",Cd="x-claude-code-router-version";Sd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};qr="Managed provider requires its plugin's authenticated model sync";Kt=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s){this.config={...Sd,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),c={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,c),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),c}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!Ve(s)&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let a=Po(s.baseUrl),i=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let l;try{l=new URL(s.baseUrl).hostname}catch{l=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(l?` (host: ${l})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(l=>{if(l){Dn(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,p=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.totalBalance})`;for(let m of i){if(t.getState(s.name,m)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${m}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,m,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let m=t.getState(s.name,d);m&&m.status==="open"&&m.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),Ed(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Zr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=j(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Ve(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Zr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),m=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(m||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let l of i)e.recordFailure(s.name,l,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let c of i)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runRateLimitProbe(){let e=j(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&Ve(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await Ad(p,c,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let m=Date.now();u.rateLimitUntil&&u.rateLimitUntil>m?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=m+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!Ve(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=wd(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),p=parseInt(l,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let m=o>p||o===p&&r>=d,h=(p*60+d)*6e4-(o*60+r)*6e4,f=h>0&&h<=300*1e3;(m||f)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),Od(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(g=>{g.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${g.error}`)}).catch(g=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${g}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?Rd(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Zr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)j().recordSuccess(o.name,i);else for(let i of a)j().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},Ae=null});var qa=w(()=>{"use strict"});var ts,_t,ec=w(()=>{"use strict";ts=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},_t=new ts});var pe,ns=w(()=>{"use strict";pe=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
308
|
+
`);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Qe,os=w(()=>{"use strict";Qe=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
305
309
|
`),e.id&&(o+=`id: ${e.id}
|
|
306
310
|
`),e.retry&&(o+=`retry: ${e.retry}
|
|
307
311
|
`),e.data&&(e.data.type==="done"?o+=`data: [DONE]
|
|
308
312
|
`:o+=`data: ${JSON.stringify(e.data)}
|
|
309
313
|
`),o+=`
|
|
310
|
-
`,t.enqueue(o)}})}}});var
|
|
311
|
-
`+(this.config.colors?`${this.colors.dim}`:""),
|
|
314
|
+
`,t.enqueue(o)}})}}});var Gt,rs=w(()=>{"use strict";Gt=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var ss=w(()=>{"use strict";ns();os();rs()});var tc=w(()=>{"use strict"});var Vt,is=w(()=>{"use strict";Vt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let c=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${c}]${this.colors.reset} `:`[${c}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
|
|
315
|
+
`+(this.config.colors?`${this.colors.dim}`:""),i+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(i+=this.colors.reset)),i}toMarkdown(e,t=0){let o=" ".repeat(t);return Array.isArray(e)?e.map(r=>typeof r=="object"?`${o}-
|
|
312
316
|
${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
|
|
313
317
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
|
|
314
318
|
${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
315
|
-
`):`${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 Ut,Ur=E(()=>{"use strict";Ut=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}`)}}}});async function ko(n,e){let t=(0,We.resolve)(n),o=_o.get(t),r,s=new Promise(i=>{r=i});_o.set(t,s);try{return await o,await e()}finally{r(),_o.get(t)===s&&_o.delete(t)}}function Ra(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Ca(n,e){try{let t=await(0,ve.lstat)(n);return t.isDirectory()&&!t.isSymbolicLink()&&Ra(e,t)}catch{return!1}}function Ku(){return new Promise(n=>{setTimeout(n,10).unref()})}async function wa(n,e,t,o){let r=(0,We.resolve)(n);if(o?.aborted||jr.has(r))return 0;jr.add(r);let s=0;try{let i=await(0,ve.lstat)(r);if(!i.isDirectory()||i.isSymbolicLink()||o?.aborted)return 0;let a=await(0,ve.opendir)(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=(0,We.join)(r,u.name);try{let p=await(0,ve.lstat)(d);if(!p.isFile()||p.isSymbolicLink()||p.mtimeMs>=e)continue;await ko(d,async()=>{if(o?.aborted||!await Ca(r,i))return!1;let h=await(0,ve.lstat)(d);return!h.isFile()||h.isSymbolicLink()||!Ra(p,h)||h.mtimeMs!==p.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await(0,ve.unlink)(d),!0)})&&s++}catch{}}finally{++l%64===0&&(await Ku(),c=!o?.aborted&&await Ca(r,i))}}}finally{await a.close().catch(()=>{})}}catch{}finally{jr.delete(r)}return s}function Ea(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,i=t?`.${t}`:"";return wa(n,Date.now()-o,a=>Wu.test(a)?!0:!a.endsWith(".tmp")&&a.startsWith(s)&&a.endsWith(i),r)}function Gu(n,e){let t=Date.now()-zu;return wa(n,t,o=>{let r=Ju.exec(o);return r!==null&&Number(r[1])<t},e)}function zr(n,e,t){let o=Hr.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,Bu),i.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),i&&clearInterval(i)}},Hr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Hr.delete(n)))}}function Pa(n=(0,We.join)((0,Sa.tmpdir)(),"claude-code-router")){return zr(`legacy:${(0,We.resolve)(n)}`,e=>Gu(n,e),1e3)}var ve,We,Sa,zu,Bu,Ju,Wu,jr,_o,Hr,Br=E(()=>{"use strict";ve=require("node:fs/promises"),We=require("node:path"),Sa=require("node:os"),zu=3600*1e3,Bu=600*1e3,Ju=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,Wu=/^\.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$/,jr=new Set,_o=new Map,Hr=new Map});var ge,Oa,Aa,Pe,Ia,jt,Jr=E(()=>{"use strict";ge=require("node:fs/promises"),Oa=require("node:crypto"),Aa=require("@wengine-ai/claude-code-router-shared"),Pe=require("node:path"),Ia=require("node:os");Br();jt=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=(0,Pe.resolve)((0,Pe.join)((0,Ia.tmpdir)(),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=zr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await(0,ge.mkdir)(this.baseDir,{recursive:!0});let e=await(0,ge.lstat)(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}-${(0,Aa.sanitizeTempFileKey)(e)}${r}${o}`;if((0,Pe.basename)(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return(0,Pe.join)(this.baseDir,s)}async output(e,t={}){try{let o=typeof t.metadata?.statsKey=="string"&&t.metadata.statsKey?t.metadata.statsKey:t.metadata?.sessionId;if(!o)return!1;let r=t.metadata?.sessionId??o,s=JSON.stringify({...e,timestamp:Date.now(),sessionId:r},null,2),i=this.getFilePath(o);return await ko(i,async()=>{await this.ensureDir();let a=(0,Pe.join)(this.baseDir,`.ccr-tmp-${process.pid}-${(0,Oa.randomUUID)()}.tmp`);return ko(a,async()=>{let l=!1;try{let c=await(0,ge.open)(a,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await(0,ge.rename)(a,i),!0}finally{l&&await(0,ge.unlink)(a).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return Ea(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Wr,pt,Ma=E(()=>{"use strict";Fr();Ur();Jr();Wr=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 Ft(e.config);case"webhook":return new Ut(e.config);case"temp-file":return new jt(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)}},pt=new Wr});var Kr=E(()=>{"use strict";xa();Fr();Ur();Jr();Ma()});function bo(){return{subdirectory:Da.TOKEN_SPEED_TEMP_SUBDIRECTORY,extension:"json",includeTimestamp:!1,prefix:"session"}}function Na(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Vu);return Math.round(n/o)}function zt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function $a(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 pt.outputToType(a,s,i)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${a}:`,l)}}var La,Da,Ht,Gr,Vu,Bt,Fa=E(()=>{"use strict";La=Z(require("fastify-plugin"),1);Dr();Kr();nt();Da=require("@wengine-ai/claude-code-router-shared");Ht=new Map,Gr=new Map,Vu=1,Bt={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,La.default)(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)pt.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:bo()}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&pt.registerHandlers(i)}t.outputOptions&&pt.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(Gr.has(u))return Gr.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 Gr.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=be(i.body?.metadata?.user_id)||d}catch{p=d}let m=await r(i);if(l instanceof ReadableStream){Ht.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=Ht.get(u);if(!v)return;let S=v.firstTokenTime?v.firstTokenTime-v.startTime:0,w=(C?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Na(v.tokenCount,w,S),await $a(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 de).getReader();for(b=setInterval(async()=>{Ht.get(u)&&await T(!1)},1e3);;){let{done:S,value:x}=await v.read();if(S)break;let w=x,R=Ht.get(u);if(!R)continue;let A=performance.now(),P=w.event||w.data?.type,N=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&&N&&(R.firstTokenTime=A,R.timeToFirstToken=Math.round(A-R.startTime));let L="";if(w.event==="content_block_delta"&&w.data?.delta){let D=w.data.delta.type;D==="text_delta"?L=w.data.delta.text||"":D==="input_json_delta"?L=w.data.delta.partial_json||"":D==="thinking_delta"&&(L=w.data.delta.thinking||"")}if((P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta")&&(L=typeof w.data?.delta=="string"?w.data.delta:""),L){let D=m&&m.encodeText?m.encodeText(L).length:zt(L);R.tokenCount+=D,R.lastTokenTime=A}(w.event==="message_stop"||P==="response.completed"||P==="response.failed")&&(b&&(clearInterval(b),b=null),await T(!0),Ht.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:zt(T))}return y},0):typeof k=="string"&&(g=m.encodeText?m.encodeText(k).length:zt(k));else{let y=Array.isArray(k)?k.map(b=>b.text).join(""):typeof k=="string"?k:"";g=zt(y)}}}catch{}if(f){let _=h-c,k={requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:h,tokenCount:g,tokensPerSecond:Na(g,_),stream:!1};await $a(k,o,t.outputOptions,!0)}return l})})}});var Vr=E(()=>{"use strict";Ta();va();Fa();Kr()});function Ua(){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 oe,Yr,Oe,W,Qr,Jt,Wt,To,ie,Kt,xe,Qu,vo,xo=E(()=>{"use strict";oe=Z(require("node:fs/promises"),1),Yr=Z(require("json5"),1),Oe=Z(require("node:path"),1),W=require("@wengine-ai/claude-code-router-shared"),Qr=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(Qr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Qr(o);return e}return n},Jt=async n=>{try{await oe.default.access(n)}catch{await oe.default.mkdir(n,{recursive:!0})}},Wt=async()=>{await Jt(W.HOME_DIR),await Jt(W.PLUGINS_DIR),await Jt(Oe.default.join(W.HOME_DIR,"logs"))},To=async()=>{let n=await oe.default.readFile(W.CONFIG_FILE,"utf-8");return Yr.default.parse(n)},ie=async()=>{try{let n=await oe.default.readFile(W.CONFIG_FILE,"utf-8");try{let e=Yr.default.parse(n);return Qr(e)}catch(e){console.error(`Failed to parse config file at ${W.CONFIG_FILE}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await Wt();let e=await Kt();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await xe(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${W.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};Kt=async()=>{Ua();try{if(await oe.default.access(W.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${W.CONFIG_FILE}.${n}.bak`;await oe.default.copyFile(W.CONFIG_FILE,e);try{let t=Oe.default.dirname(W.CONFIG_FILE),o=Oe.default.basename(W.CONFIG_FILE),s=(await oe.default.readdir(t)).filter(i=>i.startsWith(o)&&i.endsWith(".bak")).sort().reverse();if(s.length>3)for(let i=3;i<s.length;i++){let a=Oe.default.join(t,s[i]);await oe.default.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},xe=async n=>{Ua(),await Jt(W.HOME_DIR),await Qu();let e=`${JSON.stringify(n,null,2)}`;await oe.default.writeFile(W.CONFIG_FILE,e)},Qu=async()=>{if(!await oe.default.access(W.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=Oe.default.join(W.HOME_DIR,"config-history");await Jt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Oe.default.join(e,`config-${t}.json`);await oe.default.copyFile(W.CONFIG_FILE,o);try{let s=(await oe.default.readdir(e)).filter(i=>i.startsWith("config-")&&i.endsWith(".json")).sort().reverse();if(s.length>50)for(let i of s.slice(50))await oe.default.unlink(Oe.default.join(e,i))}catch(r){console.warn("Failed to prune config-history:",r)}},vo=async()=>{let n=await ie();return Object.assign(process.env,n),n}});function Yu(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function Xu(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 Ke(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:Yu(n),cache_creation_input_tokens:Xu(n)}}function Gt(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 Xr=E(()=>{"use strict"});function Co(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(Zr(r,s))}return}if(Array.isArray(n)){for(let o of n)Co(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))Co(o,e,t)}}function qr(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(Zr(s,a))}return Co(n?.Router,t,o),Co(n?.fallback,t,o),o}function ft(n,e){try{let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=qr(n),r=0;for(let s of t.getAllStates()||[]){let i=s?.provider,a=s?.model;!i||!a||o.has(Zr(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 Vt(n,e){try{if(!n)return 0;let t=j();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 Zu,Zr,So=E(()=>{"use strict";ce();Zu="\0",Zr=(n,e)=>`${n}${Zu}${e}`});function qu(n){return/\[1m\]/i.test(n)?1e6:2e5}function ed(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function td(n,e=n){let t=qu(n),o=ed(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 Qt(n){let e=new Map,t=(o,r=o)=>{!o||e.has(o)||e.set(o,td(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 es=E(()=>{"use strict"});function nd(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var Yt,ts=E(()=>{"use strict";Yt=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||nd(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 as={};an(as,{append:()=>nn,clear:()=>ss,close:()=>_d,getOldestRecordTimestamp:()=>kd,query:()=>rs,querySummary:()=>on,readTokenSpeedStats:()=>is});function ad(){(0,Me.existsSync)(wo)||(0,Me.mkdirSync)(wo,{recursive:!0})}function tn(){if(Ie)return Ie;ad();let n=(0,Ba.openSqliteDatabase)(od),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&&(cd(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")),ud(e),Ka(e,!0),os=e.prepare(`
|
|
319
|
+
`):`${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 Qt,as=w(()=>{"use strict";Qt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let c=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);return c}catch(c){throw clearTimeout(i),c}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let c=1;c<=a.maxAttempts;c++)try{return await this.sendRequest(e,t,o,r,s)}catch(l){if(i=l,c===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,c-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${c}/${a.maxAttempts}), retrying in ${u}ms...`,l.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});async function Mo(n,e){let t=(0,Ye.resolve)(n),o=Io.get(t),r,s=new Promise(a=>{r=a});Io.set(t,s);try{return await o,await e()}finally{r(),Io.get(t)===s&&Io.delete(t)}}function rc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function nc(n,e){try{let t=await(0,Se.lstat)(n);return t.isDirectory()&&!t.isSymbolicLink()&&rc(e,t)}catch{return!1}}function Dd(){return new Promise(n=>{setTimeout(n,10).unref()})}async function sc(n,e,t,o){let r=(0,Ye.resolve)(n);if(o?.aborted||cs.has(r))return 0;cs.add(r);let s=0;try{let a=await(0,Se.lstat)(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await(0,Se.opendir)(r,{bufferSize:32});try{let c=0,l=!0;for await(let u of i){if(o?.aborted||!l)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let p=(0,Ye.join)(r,u.name);try{let d=await(0,Se.lstat)(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await Mo(p,async()=>{if(o?.aborted||!await nc(r,a))return!1;let h=await(0,Se.lstat)(p);return!h.isFile()||h.isSymbolicLink()||!rc(d,h)||h.mtimeMs!==d.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await(0,Se.unlink)(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await Dd(),l=!o?.aborted&&await nc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{cs.delete(r)}return s}function ic(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return sc(n,Date.now()-o,i=>Ld.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function Fd(n,e){let t=Date.now()-Md;return sc(n,t,o=>{let r=$d.exec(o);return r!==null&&Number(r[1])<t},e)}function us(n,e,t){let o=ls.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},c=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,Nd),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},ls.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),ls.delete(n)))}}function ac(n=(0,Ye.join)((0,oc.tmpdir)(),"claude-code-router")){return us(`legacy:${(0,Ye.resolve)(n)}`,e=>Fd(n,e),1e3)}var Se,Ye,oc,Md,Nd,$d,Ld,cs,Io,ls,ds=w(()=>{"use strict";Se=require("node:fs/promises"),Ye=require("node:path"),oc=require("node:os"),Md=3600*1e3,Nd=600*1e3,$d=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,Ld=/^\.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$/,cs=new Set,Io=new Map,ls=new Map});var ye,cc,lc,Ie,uc,Yt,ps=w(()=>{"use strict";ye=require("node:fs/promises"),cc=require("node:crypto"),lc=require("@wengine-ai/claude-code-router-shared"),Ie=require("node:path"),uc=require("node:os");ds();Yt=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=(0,Ie.resolve)((0,Ie.join)((0,uc.tmpdir)(),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=us(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await(0,ye.mkdir)(this.baseDir,{recursive:!0});let e=await(0,ye.lstat)(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}-${(0,lc.sanitizeTempFileKey)(e)}${r}${o}`;if((0,Ie.basename)(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return(0,Ie.join)(this.baseDir,s)}async output(e,t={}){try{let o=typeof t.metadata?.statsKey=="string"&&t.metadata.statsKey?t.metadata.statsKey:t.metadata?.sessionId;if(!o)return!1;let r=t.metadata?.sessionId??o,s=JSON.stringify({...e,timestamp:Date.now(),sessionId:r},null,2),a=this.getFilePath(o);return await Mo(a,async()=>{await this.ensureDir();let i=(0,Ie.join)(this.baseDir,`.ccr-tmp-${process.pid}-${(0,cc.randomUUID)()}.tmp`);return Mo(i,async()=>{let c=!1;try{let l=await(0,ye.open)(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await(0,ye.rename)(i,a),!0}finally{c&&await(0,ye.unlink)(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return ic(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var fs,bt,dc=w(()=>{"use strict";is();as();ps();fs=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 Vt(e.config);case"webhook":return new Qt(e.config);case"temp-file":return new Yt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let c=this.handlers.get(i);if(!c){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await c.output(t,r)?s.success.push(i):s.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},bt=new fs});var ms=w(()=>{"use strict";tc();is();as();ps();dc()});function No(){return{subdirectory:gc.TOKEN_SPEED_TEMP_SUBDIRECTORY,extension:"json",includeTimestamp:!1,prefix:"session"}}function pc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Ud);return Math.round(n/o)}function Zt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function fc(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await bt.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var mc,gc,Xt,gs,Ud,qt,hc=w(()=>{"use strict";mc=q(require("fastify-plugin"),1);ss();ms();ct();gc=require("@wengine-ai/claude-code-router-shared");Xt=new Map,gs=new Map,Ud=1,qt={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,mc.default)(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)bt.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:No()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&bt.registerHandlers(a)}t.outputOptions&&bt.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,l=a.model,u=`${c}:${l}`;if(gs.has(u))return gs.get(u);let p=i.getTokenizerConfigForModel(c,l);if(!p)return n.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let d=await i.getTokenizer(p,c);return gs.set(u,d),n.log?.info(`Created tokenizer for ${c}:${l} - ${d.name}`),d}catch(d){return n.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${d.message}`),null}},s=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,c)=>{let l=a.requestStartTime;if(!l)return;let u=a.id||Date.now().toString(),p=a.usageSessionId||u,d=a.sessionId;if(!d)try{d=Ce(a.body?.metadata?.user_id)||p}catch{d=p}let m=await r(a);if(c instanceof ReadableStream){Xt.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[_,b]=c.tee(),y=async()=>{let k=null,T=async S=>{let v=Xt.get(u);if(!v)return;let R=v.firstTokenTime?v.firstTokenTime-v.startTime:0,x=(S?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=pc(v.tokenCount,x,R),await fc(v,o,t.outputOptions,S).catch(O=>{n.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new pe).getReader();for(k=setInterval(async()=>{Xt.get(u)&&await T(!1)},1e3);;){let{done:R,value:C}=await v.read();if(R)break;let x=C,O=Xt.get(u);if(!O)continue;let A=performance.now(),E=x.event||x.data?.type,N=x.event==="content_block_start"||x.event==="content_block_delta"||x.event==="text_block"||x.event==="content_block"||E==="response.output_text.delta"||E==="response.function_call_arguments.delta"||E==="response.reasoning_summary_text.delta";!O.firstTokenTime&&N&&(O.firstTokenTime=A,O.timeToFirstToken=Math.round(A-O.startTime));let $="";if(x.event==="content_block_delta"&&x.data?.delta){let D=x.data.delta.type;D==="text_delta"?$=x.data.delta.text||"":D==="input_json_delta"?$=x.data.delta.partial_json||"":D==="thinking_delta"&&($=x.data.delta.thinking||"")}if((E==="response.output_text.delta"||E==="response.function_call_arguments.delta"||E==="response.reasoning_summary_text.delta")&&($=typeof x.data?.delta=="string"?x.data.delta:""),$){let D=m&&m.encodeText?m.encodeText($).length:Zt($);O.tokenCount+=D,O.lastTokenTime=A}(x.event==="message_stop"||E==="response.completed"||E==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),Xt.delete(u))}}catch(S){k&&clearInterval(k),S.name!=="AbortError"&&S.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${S.message}`)}};return a.tokenSpeedCapturePromise=y().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),_}let h=performance.now(),f=0,g=!1;if(c&&typeof c=="string")try{let _=JSON.parse(c);if(typeof _.usage?.output_tokens=="number")f=_.usage.output_tokens,g=!0;else{let b=_.content??_.message?.content;if(b!==void 0)if(g=!0,m)Array.isArray(b)?f=b.reduce((y,k)=>{if(k.type==="text"){let T=k.text||"";return y+(m.encodeText?m.encodeText(T).length:Zt(T))}return y},0):typeof b=="string"&&(f=m.encodeText?m.encodeText(b).length:Zt(b));else{let y=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";f=Zt(y)}}}catch{}if(g){let _=h-l,b={requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:h,tokenCount:f,tokensPerSecond:pc(f,_),stream:!1};await fc(b,o,t.outputOptions,!0)}return c})})}});var hs=w(()=>{"use strict";qa();ec();hc();ms()});function yc(){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 se,_s,Me,V,ys,en,tn,kt,ee,nn,fe,jd,$o,on=w(()=>{"use strict";se=q(require("node:fs/promises"),1),_s=q(require("json5"),1),Me=q(require("node:path"),1),V=require("@wengine-ai/claude-code-router-shared"),ys=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(ys);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=ys(o);return e}return n},en=async n=>{try{await se.default.access(n)}catch{await se.default.mkdir(n,{recursive:!0})}},tn=async()=>{await en(V.HOME_DIR),await en(V.PLUGINS_DIR),await en(Me.default.join(V.HOME_DIR,"logs"))},kt=async()=>{let n=await se.default.readFile(V.CONFIG_FILE,"utf-8");return _s.default.parse(n)},ee=async()=>{try{let n=await se.default.readFile(V.CONFIG_FILE,"utf-8");try{let e=_s.default.parse(n);return ys(e)}catch(e){console.error(`Failed to parse config file at ${V.CONFIG_FILE}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await tn();let e=await nn();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await fe(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 ${V.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};nn=async()=>{yc();try{if(await se.default.access(V.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${V.CONFIG_FILE}.${n}.bak`;await se.default.copyFile(V.CONFIG_FILE,e);try{let t=Me.default.dirname(V.CONFIG_FILE),o=Me.default.basename(V.CONFIG_FILE),s=(await se.default.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=Me.default.join(t,s[a]);await se.default.unlink(i)}}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},fe=async n=>{yc(),await en(V.HOME_DIR),await jd();let e=`${JSON.stringify(n,null,2)}`;await se.default.writeFile(V.CONFIG_FILE,e)},jd=async()=>{if(!await se.default.access(V.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=Me.default.join(V.HOME_DIR,"config-history");await en(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Me.default.join(e,`config-${t}.json`);await se.default.copyFile(V.CONFIG_FILE,o);try{let s=(await se.default.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await se.default.unlink(Me.default.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},$o=async()=>{let n=await ee();return Object.assign(process.env,n),n}});function Hd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function zd(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 Xe(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:Hd(n),cache_creation_input_tokens:zd(n)}}function rn(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 bs=w(()=>{"use strict"});function Lo(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(ks(r,s))}return}if(Array.isArray(n)){for(let o of n)Lo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))Lo(o,e,t)}}function Ts(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let i of a)i&&o.add(ks(s,i))}return Lo(n?.Router,t,o),Lo(n?.fallback,t,o),o}function Tt(n,e){try{let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=Ts(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(ks(a,i))||(t.recover(a,i),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 sn(n,e){try{if(!n)return 0;let t=j();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 Bd,ks,an=w(()=>{"use strict";le();Bd="\0",ks=(n,e)=>`${n}${Bd}${e}`});function Jd(n){return/\[1m\]/i.test(n)?1e6:2e5}function Wd(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Kd(n,e=n){let t=Jd(n),o=Wd(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 cn(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 vs=w(()=>{"use strict"});function Gd(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var ln,xs=w(()=>{"use strict";ln=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Gd(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],c=Array.isArray(i)?i[0]:i||"";if(!c){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let l="";if(c.startsWith("Bearer")?l=c.split(" ")[1]:l=c,l!==a){t.log.warn({url:e.url,gotPrefix:l.slice(0,10),gotSuffix:l.slice(-6),gotLen:l.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var Es={};bn(Es,{append:()=>gn,clear:()=>ws,close:()=>lp,getOldestRecordTimestamp:()=>up,query:()=>Rs,querySummary:()=>hn,readTokenSpeedStats:()=>Ps});function Zd(){(0,Le.existsSync)(Fo)||(0,Le.mkdirSync)(Fo,{recursive:!0})}function mn(){if($e)return $e;Zd();let n=(0,Tc.openSqliteDatabase)(Vd),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&&(qd(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")),tp(e),Cc(e,!0),Ss=e.prepare(`
|
|
316
320
|
INSERT INTO usage_records (
|
|
317
321
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
318
322
|
scenario_type, client_type,
|
|
@@ -326,7 +330,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
326
330
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
327
331
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
328
332
|
)
|
|
329
|
-
`)
|
|
333
|
+
`),$e=e,$e}function qd(n){n.exec(`
|
|
330
334
|
CREATE TABLE IF NOT EXISTS usage_records (
|
|
331
335
|
id TEXT PRIMARY KEY,
|
|
332
336
|
timestamp TEXT NOT NULL,
|
|
@@ -363,12 +367,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
363
367
|
CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
|
|
364
368
|
CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
|
|
365
369
|
CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
|
|
366
|
-
`)}function
|
|
370
|
+
`)}function ep(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function un(n,e,t){n.prepare(`
|
|
367
371
|
INSERT INTO usage_meta (key, value)
|
|
368
372
|
VALUES (?, ?)
|
|
369
373
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
370
|
-
`).run(e,t)}function
|
|
371
|
-
`)){let
|
|
374
|
+
`).run(e,t)}function tp(n){if(ep(n,_c)||!(0,Le.existsSync)(Cs))return;let e=op(n,"INSERT OR IGNORE"),t=(0,Le.readFileSync)(Cs,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
|
|
375
|
+
`)){let c=i.trim();if(c)try{let l=JSON.parse(c);if(!np(l)){r++;continue}e.run(xc(Uo(l))).changes>0?o++:s++}catch{r++}}un(n,_c,new Date().toISOString()),un(n,"legacy_usage_jsonl_migrated_path",Cs),un(n,"legacy_usage_jsonl_imported_count",String(o)),un(n,"legacy_usage_jsonl_skipped_count",String(r)),un(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function np(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.timestamp=="string"&&e.timestamp.length>0}function op(n,e="INSERT"){return n.prepare(`
|
|
372
376
|
${e} INTO usage_records (
|
|
373
377
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
374
378
|
scenario_type, client_type,
|
|
@@ -382,11 +386,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
382
386
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
383
387
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
384
388
|
)
|
|
385
|
-
`)}function
|
|
386
|
-
SELECT ${t} AS key, ${
|
|
389
|
+
`)}function rp(n,e,t){if(n<=0||e==null||!Number.isFinite(e))return null;let o=t!=null&&Number.isFinite(t)?t:0,r=Math.max((e-o)/1e3,Qd);return Math.round(n/r)}function Uo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?pn(n.ttft):null;return{...n,ttft:r,tokensPerSecond:rp(e,o,r)}}function Ne(n){return typeof n=="string"?n:n==null?"":String(n)}function Do(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function dn(n){let e=Number(n);return Number.isFinite(e)?e:0}function vc(n){return n==="success"?"success":"error"}function xc(n){let e=Uo(n);return{id:Ne(e.id),timestamp:Ne(e.timestamp),session_id:Ne(e.sessionId),provider:Ne(e.provider),original_model:Ne(e.originalModel),model:Ne(e.model),upstream_model:Do(e.upstreamModel)??null,model_family:Ne(e.modelFamily),scenario_type:Ne(e.scenarioType),client_type:Do(e.clientType)??null,stream:e.stream?1:0,input_tokens:Math.trunc(dn(e.inputTokens)),output_tokens:Math.trunc(dn(e.outputTokens)),cache_read_input_tokens:Math.trunc(dn(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(dn(e.cacheCreationInputTokens)),ttft:pn(e.ttft),tokens_per_second:pn(e.tokensPerSecond),duration_ms:Math.trunc(dn(e.durationMs)),status:vc(e.status),error_message:Do(e.errorMessage)??null,response_body:Do(e.responseBody)??null}}function sp(n){return Uo({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,stream:n.stream===1,inputTokens:n.input_tokens,outputTokens:n.output_tokens,cacheReadInputTokens:n.cache_read_input_tokens,cacheCreationInputTokens:n.cache_creation_input_tokens,ttft:n.ttft,tokensPerSecond:n.tokens_per_second,durationMs:n.duration_ms,status:vc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function ip(){return new Date(Date.now()-Yd*24*60*60*1e3).toISOString()}function Cc(n,e=!1){let t=Date.now();!e&&t-bc<Xd||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(ip()),bc=t)}function Sc(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function vt(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
|
|
390
|
+
SELECT ${t} AS key, ${ap}
|
|
387
391
|
FROM usage_records ${r}
|
|
388
392
|
GROUP BY key
|
|
389
|
-
`).all(...e.params),
|
|
393
|
+
`).all(...e.params),a={};for(let i of s)i.key!=null&&(a[String(i.key)]={count:i.count,inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadInputTokens:i.cacheReadInputTokens,cacheCreationInputTokens:i.cacheCreationInputTokens});return a}function Rc(n,e){let t=Sc(e),o=n.prepare(`
|
|
390
394
|
SELECT
|
|
391
395
|
COUNT(*) AS totalRequests,
|
|
392
396
|
COALESCE(SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END), 0) AS successCount,
|
|
@@ -397,17 +401,17 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
397
401
|
AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
|
|
398
402
|
AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
|
|
399
403
|
FROM usage_records ${t.sql}
|
|
400
|
-
`).get(...t.params);return{totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:
|
|
404
|
+
`).get(...t.params);return{totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:vt(n,t,"model"),byProvider:vt(n,t,"provider"),byScenario:vt(n,t,"scenario_type"),byFamily:vt(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:vt(n,t,"date(timestamp, 'localtime')"),byClient:vt(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function gn(n){let e=mn(),t=Uo(n);Ss.run(xc(t)),Cc(e)}function Rs(n){let e=mn(),t=Sc(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.min(Math.floor(n.pageSize),cp):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),c=Rc(e,n);return{records:i.map(sp),summary:c,total:a.count,page:o,pageSize:r}}function hn(n,e,t){let o=mn();return Rc(o,{startTime:n,endTime:e,status:t})}function ws(n){let e=mn();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function lp(){$e&&($e.pragma("wal_checkpoint(TRUNCATE)"),$e.close(),$e=null,Ss=null)}function pn(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function Ps(n){let e=(0,fn.join)((0,kc.tmpdir)(),xt.TOKEN_SPEED_TEMP_SUBDIRECTORY,`session-${(0,xt.sanitizeTempFileKey)(n)}.json`);try{let t=JSON.parse((0,Le.readFileSync)(e,"utf-8"));return{ttft:pn(t.timeToFirstToken),tokensPerSecond:pn(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function up(n,e,t){return mn().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var Le,fn,kc,Tc,xt,Fo,Vd,Cs,Qd,Yd,Xd,_c,$e,Ss,bc,ap,cp,yn=w(()=>{"use strict";Le=require("fs"),fn=require("path"),kc=require("os"),Tc=require("@wengine-ai/claude-code-router-shared"),xt=require("@wengine-ai/claude-code-router-shared"),Fo=(0,fn.join)(xt.HOME_DIR,"data"),Vd=(0,fn.join)(Fo,"usage.sqlite"),Cs=(0,fn.join)(Fo,"usage.jsonl"),Qd=1,Yd=180,Xd=3600*1e3,_c="legacy_usage_jsonl_migrated_at",$e=null,Ss=null,bc=0;ap=`
|
|
401
405
|
COUNT(*) AS count,
|
|
402
406
|
COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
|
|
403
407
|
COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
|
|
404
408
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
|
|
405
409
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
|
|
406
|
-
`;yd=200});async function qa(){let n=(0,Ya.homedir)(),e=(0,Xa.join)(n,".claude.json");if(!(0,Qa.existsSync)(e)){let o={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await(0,Za.writeFile)(e,JSON.stringify(o,null,2))}}var Qa,Ya,Xa,Za,ec=E(()=>{"use strict";Qa=require("fs"),Ya=require("os"),Xa=require("path"),Za=require("fs/promises")});function nc(n=(0,cs.join)(oc.HOME_DIR,"logs")){try{if(!(0,Ne.existsSync)(n))return;let e=Date.now()-Td;for(let t of(0,Ne.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,cs.join)(n,t),r=(0,Ne.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,Ne.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function rc(){tc||(tc=!0,nc(),setInterval(nc,vd).unref())}var Ne,cs,oc,bd,Td,vd,tc,sc=E(()=>{"use strict";Ne=require("fs"),cs=require("path"),oc=require("@wengine-ai/claude-code-router-shared"),bd=7,Td=bd*24*60*60*1e3,vd=1440*60*1e3,tc=!1});async function ic(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:i={}}=o;switch(r){case"token-speed":dt.registerPlugin(Bt,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:bo()}],...i});break;default:console.warn(`Unknown plugin: ${r}`);break}}await dt.enablePlugins(n)}var ac=E(()=>{"use strict";Vr()});function cc(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function xd(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=on(t,e),s=on(o,e),i=[],a=new Set;for(let l of n||[])l&&l.name&&a.add(l.name);for(let l of Object.keys(r.byProvider||{}))a.add(l);for(let l of Object.keys(s.byProvider||{}))a.add(l);for(let l of a){let c=r.byProvider[l]||{inputTokens:0,outputTokens:0},u=s.byProvider[l]||{inputTokens:0,outputTokens:0},d=(c.inputTokens||0)+(c.outputTokens||0),p=(u.inputTokens||0)+(u.outputTokens||0),m,h,g=(n||[]).find(f=>f&&f.name===l);g&&g.quota&&(m=g.quota.limit5h,h=g.quota.limit7d),i.push({provider:l,used5h:d,used7d:p,limit5h:m,limit7d:h})}return i}async function mc(n,e){let t=n.app;Ye(),et(),t.register(pc.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let a=Qt(e);return{object:"list",data:a,first_id:a[0]?.id||null,last_id:a[a.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(a,l)=>{let c=decodeURIComponent(a.params.modelId),u=Qt(e).find(d=>d.id===c);return u||(l.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${c}`}})}),t.post("/v1/messages/count_tokens",async(a,l)=>{let{messages:c,tools:u,system:d,model:p}=a.body,m=t._server.tokenizerService;if(p&&p.includes(",")&&m)try{let[g,f]=p.split(",");a.log?.info(`Looking up tokenizer for provider: ${g}, model: ${f}`);let _=m.getTokenizerConfigForModel(g,f);_?a.log?.info(`Using tokenizer config: ${JSON.stringify(_)}`):a.log?.warn(`No tokenizer config found for ${g},${f}, using default tiktoken`);let k=await m.countTokens({messages:c,system:d,tools:u},_,g);return{input_tokens:k.tokenCount,tokenizer:k.tokenizerUsed}}catch(g){a.log?.error(`Error using configured tokenizer: ${g.message}`),a.log?.error(g.stack)}else p?p.includes(",")?m||a.log?.warn("TokenizerService not available, using default tiktoken"):a.log?.info(`Model "${p}" does not contain comma, using default tiktoken`):a.log?.info("No model specified, using default tiktoken");return{input_tokens:wt(c,d,u)}}),t.get("/api/config",async(a,l)=>await To()),t.get("/api/transformers",async(a,l)=>{let c=t._server.transformerService.getAllTransformers();return{transformers:Array.from(c.entries()).map(([d,p])=>({name:d,endpoint:p.endPoint||null}))}}),t.post("/api/config",async(a,l)=>{let c=a.body,u=bs(c||{});if(u.length>0)return l.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(g=>`${g.key}: ${g.error}`).join("; "),proxyErrors:u};let d=await Kt();d&&console.log(`Backed up existing configuration file to ${d}`);let p=null;try{p=await ie()}catch{}let m=(0,lc.ensureCcrSelfProvider)(c,p);await xe(c);let h;try{h=await(0,O.syncGlobalProjectTakeovers)(c),h.failed.length>0&&t.log?.warn?.({projectTakeoverSync:h},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}try{let g=t._server;if(g?.configService){g.configService.reload();let f=c?.Providers||c?.providers;if(Array.isArray(f)&&g.configService.set("providers",f),me&&g.transformerService&&(g.providerService=new me(g.configService,g.transformerService,t.log)),ft(c,t.log),Be&&Lt){try{Lt()}catch{}let _={enabled:g.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:g.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:g.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(g.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:g.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:g.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};g.activeProbeService=Be(()=>g.providerService.getProviders(),_,k=>pe(g.configService,k),t.log,k=>g.configService.get(k))}}}catch(g){t.log?.warn?.(`Config saved but runtime reload failed: ${g?.message||g}`)}return{success:!0,message:"Config saved successfully",projectTakeoverSync:h}}),t.get("/api/clients",async(a,l)=>{try{let c=await ie();return{clients:(0,O.listClientStatuses)(c)}}catch(c){console.error("Failed to get client integrations:",c),l.status(500).send({error:c.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(a,l)=>{try{let c=a.body,u=Array.isArray(c?.enabled)?c.enabled:[],d=await ie(),p=(0,O.applyClientSelection)(d,u);await xe(p.config);let m=await(0,O.syncGlobalProjectTakeovers)(p.config),h=cc(t,m,"clients/apply");return{...p,success:p.success&&h,projectTakeoverSync:m}}catch(c){console.error("Failed to apply client integrations:",c),l.status(500).send({error:c.message||"Failed to apply client integrations"})}});async function o(a,l,c){try{let{id:u}=a.params;if(!(0,O.isClientId)(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let d=await ie(),p=c==="enable"?(0,O.enableClient)(d,u):c==="restore"?(0,O.restoreClient)(d,u):(0,O.disableClient)(d,u);await xe(d);let m=await(0,O.syncGlobalProjectTakeovers)(d),h=cc(t,m,`clients/${u}/${c}`);return{success:p.success&&h,result:p,results:[p],clients:(0,O.listClientStatuses)(d),config:d,projectTakeoverSync:m}}catch(u){console.error(`Failed to ${c} client integration:`,u),l.status(500).send({error:u.message||`Failed to ${c} client integration`})}}t.post("/api/clients/:id/enable",async(a,l)=>o(a,l,"enable")),t.post("/api/clients/:id/disable",async(a,l)=>o(a,l,"disable")),t.post("/api/clients/:id/restore",async(a,l)=>o(a,l,"restore")),t.get("/api/projects",async(a,l)=>{try{let c=await(0,O.listProjectConfigs)();return{projects:await Promise.all(c.map(async d=>{let p=await(0,O.getProjectTakeoverClients)(d.path);return{...d,ccrTakeoverClients:p,ccrTakeover:p.length>0}}))}}catch(c){console.error("Failed to list project configs:",c),l.status(500).send({error:c.message||"Failed to list project configs"})}}),t.post("/api/projects",async(a,l)=>{try{let{path:c}=a.body||{};if(!c||typeof c!="string"||!(0,X.isAbsolute)(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,X.normalize)(c).replace(/[\\/]+$/,"")||c;if(await(0,O.readProjectConfig)(u)){l.status(409).send({error:"Project is already configured"});return}await(0,O.writeProjectConfig)(u,{Router:{}});try{let m=await ie();await(0,O.setProjectTakeover)(u,["claudeCode"],m)}catch(m){console.error("Failed to auto-enable ccr takeover for new project:",m)}let p=await(0,O.getProjectTakeoverClients)(u);return{id:(0,O.getClaudeProjectId)(u),path:u,configPath:(0,O.getProjectConfigPath)(u),Router:{},ccrTakeoverClients:p,ccrTakeover:p.length>0}}catch(c){console.error("Failed to add project config:",c),l.status(500).send({error:c.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(a,l)=>{try{let{id:c}=a.params,{Router:u}=a.body||{};if(!u||typeof u!="object"){l.status(400).send({error:"Router must be an object"});return}let d=await(0,O.readProjectConfigById)(c);if(!d){l.status(404).send({error:"Project config not found"});return}await(0,O.writeProjectConfig)(d.path,{Router:u});let p=await ie();Object.keys(u).length===0?await(0,O.refreshProjectTakeovers)(d.path,p):(await(0,O.refreshCcrProjectTakeover)(d.path,p,u),await(0,O.refreshPiProjectTakeover)(d.path,p,u));let m=await(0,O.getProjectTakeoverClients)(d.path);return{id:c,path:d.path,configPath:d.configPath,Router:u,ccrTakeoverClients:m,ccrTakeover:m.length>0}}catch(c){console.error("Failed to update project config:",c),l.status(500).send({error:c.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(a,l)=>{try{let{id:c}=a.params,u=a.body||{},d;if(Array.isArray(u.clients))d=u.clients.filter(O.isProjectTakeoverClient);else if(typeof u.enabled=="boolean")d=u.enabled?["claudeCode"]:[];else{l.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let p=await(0,O.readProjectConfigById)(c);if(!p){l.status(404).send({error:"Project config not found"});return}let m=await ie(),h=await(0,O.setProjectTakeover)(p.path,d,m);return{id:c,path:p.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(c){console.error("Failed to update ccr takeover status:",c),l.status(500).send({error:c.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(a,l)=>{try{let{id:c}=a.params,u=await(0,O.readProjectConfigById)(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let d=await ie();await(0,O.setProjectTakeover)(u.path,[],d)}catch(d){console.error("Failed to remove ccr takeover while deleting project:",d)}return await(0,O.deleteProjectConfig)(u.path),{success:!0}}catch(c){console.error("Failed to delete project config:",c),l.status(500).send({error:c.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:(0,X.dirname)((0,uc.fileURLToPath)(void 0)),s=(0,H.existsSync)((0,X.join)(r,"index.html"))?r:(0,H.existsSync)((0,X.join)(r,"..","index.html"))?(0,X.join)(r,".."):(0,X.join)(r,"..","dist");t.register(dc.default,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(a,l)=>l.redirect("/ui/")),t.get("/api/logs/files",async(a,l)=>{try{let c=(0,X.join)((0,Po.homedir)(),".claude-code-router","logs"),u=[];if((0,H.existsSync)(c)){let d=(0,H.readdirSync)(c);for(let p of d)if(p.endsWith(".log")){let m=(0,X.join)(c,p),h=(0,H.statSync)(m);u.push({name:p,path:m,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((p,m)=>new Date(m.lastModified).getTime()-new Date(p.lastModified).getTime())}return u}catch(c){console.error("Failed to get log files:",c),l.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(a,l)=>{try{let c=a.query.file,u;return c?u=c:u=(0,X.join)((0,Po.homedir)(),".claude-code-router","logs","app.log"),(0,H.existsSync)(u)?(0,H.readFileSync)(u,"utf8").split(`
|
|
407
|
-
`).filter(m=>m.trim()):[]}catch(c){console.error("Failed to get logs:",c),l.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(a,l)=>{try{let c=a.query.file,u;return c?u=c:u=(0,X.join)((0,Po.homedir)(),".claude-code-router","logs","app.log"),(0,H.existsSync)(u)&&(0,H.writeFileSync)(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(c){console.error("Failed to clear logs:",c),l.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:kt()})),t.put("/api/debug-log",async a=>{let{enabled:l}=a.body;return dn(l),{enabled:kt()}}),t.get("/api/usage",async(a,l)=>{try{let c=a.query;return rs({startTime:c.startDate,endTime:c.endDate,model:c.model,provider:c.provider,scenario:c.scenario,clientType:c.clientType,sessionId:c.sessionId,status:c.status,page:c.page?parseInt(c.page,10):void 0,pageSize:c.pageSize?parseInt(c.pageSize,10):void 0})}catch(c){console.error("Failed to query usage:",c),l.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(a,l)=>{try{let c=a.query;return on(c.startDate,c.endDate,c.status)}catch(c){console.error("Failed to query usage summary:",c),l.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(a,l)=>{try{let c=a.query;return ss(c.beforeDate),{success:!0,message:c.beforeDate?"Usage data cleared before "+c.beforeDate:"All usage data cleared"}}catch(c){console.error("Failed to clear usage:",c),l.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(a,l)=>{try{let u=j().getAllStates(),p=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(m=>({provider:m.provider,model:m.model,status:m.status,failureCount:m.failureCount,successCount:m.successCount,lastFailureTime:m.lastFailureTime,lastError:m.lastError,rateLimitUntil:m.rateLimitUntil??null})),probes:p,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to get provider health:",c),l.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(a,l)=>{try{let{providerName:c}=a.body;if(!c)return l.status(400),{error:"providerName is required"};let d=t._server?.activeProbeService;if(!d?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let p=await d.probeProviderManually(c);return p.success&&Vt(c,a.log),{provider:c,success:p.success,latencyMs:p.latencyMs,status:p.status,isSlow:p.isSlow,errorKind:p.errorKind??null,error:p.error,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe provider:",c),l.status(500).send({error:c.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(a,l)=>{try{let c=t._server,u=c?.activeProbeService;if(!u?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let d=(c?.providerService?.getProviders?.()||[]).filter(m=>m?.name&&m.enabled!==!1),p=await Promise.all(d.map(async m=>{let h=await u.probeProviderManually(m.name);return h.success&&Vt(m.name,a?.log),{provider:m.name,success:h.success,latencyMs:h.latencyMs,status:h.status,isSlow:h.isSlow,errorKind:h.errorKind??null,error:h.error}}));return{results:p,successCount:p.filter(m=>m.success).length,total:p.length,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe all providers:",c),l.status(500).send({error:c.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(a,l)=>{try{let u=(await ie()).Providers||[],d=xd(u),p=new Map(d.map(g=>[g.provider,g])),m=_n();for(let g of d){let f=m.find(_=>_.provider===g.provider);f&&f.limit!=null&&(g.limit5h=f.limit,g.used5h=f.limit-(f.remaining??0),f.reset&&(g.reset5h=new Date(f.reset*1e3).toISOString()))}let h=Cn();for(let g of h){let f=p.get(g.provider);f||(f={provider:g.provider,used5h:0,used7d:0},d.push(f),p.set(g.provider,f)),typeof g.totalBalance=="number"?(f.limit7d=g.totalBalance,f.type7d=g.currency?"balance":"rateLimit",g.currency&&(f.currency=g.currency),typeof g.usedBalance=="number"?f.used7d=g.usedBalance:typeof g.remainingBalance=="number"?f.used7d=Math.max(0,g.totalBalance-g.remainingBalance):(f.used7d=0,f.limit7d=g.totalBalance)):typeof g.usedBalance=="number"&&(f.used7d=g.usedBalance),typeof g.usedDailyBalance=="number"&&(f.used5h=g.usedDailyBalance,f.type5h="rateLimit"),typeof g.limitDaily=="number"&&(f.limit5h=g.limitDaily,f.type5h="rateLimit"),typeof g.resetTime=="string"&&(g.limitDaily!==void 0?f.reset5h=g.resetTime:f.reset7d=g.resetTime),typeof g.resetTime7d=="string"&&(f.reset7d=g.resetTime7d)}return{quotas:d,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to compute provider quota:",c),l.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(a,l)=>{try{let c=(0,X.join)(O.HOME_DIR,"presets");if(!(0,H.existsSync)(c))return{presets:[]};let d=(0,H.readdirSync)(c,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).map(m=>m.name),p=[];for(let m of d){let h=(0,X.join)(c,m);try{let g=(0,X.join)(h,"manifest.json"),f=(0,H.readFileSync)(g,"utf-8"),_=JSON.parse(f),{Providers:k,Router:y,PORT:b,HOST:T,API_TIMEOUT_MS:C,PROXY_URL:v,PROXY_GLOBAL_ENABLED:S,LOG:x,LOG_LEVEL:w,StatusLine:R,NON_INTERACTIVE_MODE:A,...P}=_;p.push({id:m,name:P.name||m,version:P.version||"1.0.0",description:P.description,author:P.author,homepage:P.homepage,repository:P.repository,license:P.license,keywords:P.keywords,ccrVersion:P.ccrVersion,source:P.source,sourceType:P.sourceType,checksum:P.checksum,installed:!0})}catch(g){console.error(`Failed to read preset ${m}:`,g)}}return{presets:p}}catch(c){console.error("Failed to get presets:",c),l.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(a,l)=>{try{let{name:c}=a.params,u=(0,O.getPresetDir)(c);if(!(0,H.existsSync)(u)){l.status(404).send({error:"Preset not found"});return}let d=await(0,O.readManifestFromDir)(u);return{...(0,O.manifestToPresetFile)(d),config:(0,O.loadConfigFromManifest)(d,u),userValues:d.userValues||{}}}catch(c){console.error("Failed to get preset:",c),l.status(500).send({error:c.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(a,l)=>{try{let{name:c}=a.params,{secrets:u}=a.body,d=(0,O.getPresetDir)(c);if(!(0,H.existsSync)(d)){l.status(404).send({error:"Preset not found"});return}let m={...await(0,O.readManifestFromDir)(d)};return u&&Object.keys(u).length>0&&(m.userValues={...m.userValues,...u}),await(0,O.saveManifest)(c,m),{success:!0,message:"Preset applied successfully"}}catch(c){console.error("Failed to apply preset:",c),l.status(500).send({error:c.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(a,l)=>{try{let{name:c}=a.params,u=(0,O.getPresetDir)(c);if(!(0,H.existsSync)(u)){l.status(404).send({error:"Preset not found"});return}return(0,H.rmSync)(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(c){console.error("Failed to delete preset:",c),l.status(500).send({error:c.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(a,l)=>{try{return{presets:await(0,O.getMarketPresets)()}}catch(c){console.error("Failed to get market presets:",c),l.status(500).send({error:c.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(a,l)=>{try{let{presetName:c}=a.body;if(!c){l.status(400).send({error:"Preset name is required"});return}let u=await(0,O.findMarketPresetByName)(c);if(!u){l.status(400).send({error:"Preset not found in marketplace",message:`Preset '${c}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){l.status(400).send({error:"Invalid preset data",message:`Preset '${c}' does not have repository information`});return}let d=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!d){l.status(400).send({error:"Invalid GitHub repository URL"});return}let[,p,m]=d,h=u.name||c;if(await(0,O.isPresetInstalled)(h)){l.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let g=`https://github.com/${p}/${m}/archive/refs/heads/main.zip`,f=await(0,O.downloadPresetToTemp)(g),_=await i(f);if(await(0,O.isPresetInstalled)(h)){(0,H.unlinkSync)(f),l.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let k=(0,O.getPresetDir)(h);await(0,O.extractPreset)(f,k);let y=await(0,O.readManifestFromDir)(k);return y.repository=u.repo,u.url&&(y.source=u.url),await(0,O.saveManifest)(h,y),(0,H.unlinkSync)(f),{success:!0,presetName:h,preset:{..._.metadata,installed:!0}}}catch(c){console.error("Failed to install preset from GitHub:",c),l.status(500).send({error:c.message||"Failed to install preset from GitHub"})}});async function i(a){let l=new fc.default(a),c=l.getEntry("manifest.json");if(c||(c=l.getEntries().find(p=>p.entryName.includes("manifest.json"))||null),!c)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(c.getData().toString("utf-8"));return(0,O.manifestToPresetFile)(u)}return n}var lc,X,uc,dc,H,Po,O,pc,fc,gc=E(()=>{"use strict";at();Xe();tt();$n();yo();ae();bt();ce();So();xo();lc=require("@wengine-ai/claude-code-router-shared"),X=require("path"),uc=require("url"),dc=Z(require("@fastify/static"),1),H=require("fs"),Po=require("os"),O=require("@wengine-ai/claude-code-router-shared"),pc=Z(require("@fastify/multipart"),1),fc=Z(require("adm-zip"),1);rn();es()});function Cd(n,e){let t=n?.Router,{family:o}=Et(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function hc(n){return n?.Router?.image}function Sd(n){return n.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function Rd(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var ls,Oo,us,yc,_c=E(()=>{"use strict";at();ls=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},Oo=new ls;us=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Cd(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Sd(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&ur(e.body.model)?!1:(Rd(e.body.messages),s&&!!hc(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(a=>{let l=Oo.getImage(`${t.req.id}_Image#${a}`);l&&o.push({type:"image",source:l})});else{let a=Oo.getImage(`${t.req.id}_Image#${e.imageId}`);a&&o.push({type:"image",source:a})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let a=s.content.filter(l=>l.type==="text"&&!l.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...a)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let i=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:hc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
410
|
+
`;cp=200});async function Ac(){let n=(0,Pc.homedir)(),e=(0,Ec.join)(n,".claude.json");if(!(0,wc.existsSync)(e)){let o={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await(0,Oc.writeFile)(e,JSON.stringify(o,null,2))}}var wc,Pc,Ec,Oc,Ic=w(()=>{"use strict";wc=require("fs"),Pc=require("os"),Ec=require("path"),Oc=require("fs/promises")});function Nc(n=(0,Os.join)($c.HOME_DIR,"logs")){try{if(!(0,De.existsSync)(n))return;let e=Date.now()-pp;for(let t of(0,De.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,Os.join)(n,t),r=(0,De.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,De.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function Lc(){Mc||(Mc=!0,Nc(),setInterval(Nc,fp).unref())}var De,Os,$c,dp,pp,fp,Mc,Dc=w(()=>{"use strict";De=require("fs"),Os=require("path"),$c=require("@wengine-ai/claude-code-router-shared"),dp=7,pp=dp*24*60*60*1e3,fp=1440*60*1e3,Mc=!1});async function Fc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":_t.registerPlugin(qt,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:No()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await _t.enablePlugins(n)}var Uc=w(()=>{"use strict";hs()});function Ct(n,e,t){if(n?.configService)try{n.configService.reload(),n.reloadProviders?n.reloadProviders(e):(n.configService.set("providers",e?.Providers??e?.providers??[]),n.providerService?.reload()),Tt(e,t),Oo();let o={enabled:n.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:n.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:n.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(n.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:n.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:n.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};n.activeProbeService=yt(()=>n.providerService.getProviders(),o,r=>me(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var jo=w(()=>{"use strict";an();Ao();ae()});function zc(n){try{let e=JSON.parse((0,H.readFileSync)((0,_e.join)(mp(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function Is(n,e){if(!Hc(e))return null;try{let t=(0,H.realpathSync)(n),o=(0,_e.join)(t,"plugins"),r=(0,_e.join)(o,e);return(0,H.lstatSync)(o).isSymbolicLink()||!(0,H.lstatSync)(o).isDirectory()||(0,H.lstatSync)(r).isSymbolicLink()||!(0,H.lstatSync)(r).isDirectory()||(0,H.realpathSync)(o)!==o||(0,H.realpathSync)(r)!==r||!r.startsWith(o+_e.sep)?null:r}catch{return null}}function As(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=Is(n,e);if(!o)throw new Error("unsafe plugin directory");let r=(0,_e.join)(o,t),s=(0,H.lstatSync)(r);if(s.isSymbolicLink()||!s.isFile()||(0,H.realpathSync)(r)!==r)throw new Error("unsafe plugin file");let a=(0,H.openSync)(r,H.constants.O_RDONLY|H.constants.O_NOFOLLOW|H.constants.O_NONBLOCK);try{let i=(0,H.fstatSync)(a),c=(0,H.lstatSync)(r);if(!i.isFile()||c.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==c.dev||i.ino!==c.ino||Is(n,e)!==o||(0,H.realpathSync)(r)!==r)throw new Error("plugin file changed while opening");return(0,H.readFileSync)(a)}finally{(0,H.closeSync)(a)}}function gp(n){let e=n?.configService,t=e?Gs(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Vs(t)}async function Bc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??nr(),r={configDir:e,readConfig:()=>ee(),readRawConfig:()=>kt(),writeConfig:i=>fe(i),reloadRuntime:async i=>Ct(n.getServer(),i??await ee(),t),getDirectDispatcher:Go,getSubscriptionDispatcher:()=>gp(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of zc(e)){let c;try{if(!Hc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let l=Is(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let f=JSON.parse(As(e,i.name,"plugin.json").toString("utf8"));if(!f||typeof f.name!="string"||typeof f.version!="string")throw new Error;u={name:f.name,version:f.version,coreApi:String(f.coreApi??"1"),description:f.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:f=>t.info(`[plugin:${u.name}] ${f}`),warn:f=>t.warn(`[plugin:${u.name}] ${f}`),error:f=>t.error(`[plugin:${u.name}] ${f}`)},r,l);c=p,As(e,i.name,"plugin.js");let d=await import((0,jc.pathToFileURL)((0,_e.join)(l,"plugin.js")).href),m=d?.activate??d?.default?.activate;if(typeof m!="function")throw new Error("entry exports no activate()");await m(p.context);let h=p.cardPath?As(e,i.name,p.cardPath):void 0;await p.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function Jc(n,e=nr()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return zc(n).map(o=>{let r=o.enabled!==!1?t.get(o.name):void 0;return r?{...r,enabled:!0}:{name:o.name,version:null,enabled:o.enabled!==!1,error:"plugin missing or failed to load \u2014 its providers are unavailable until it is reinstalled"}})}var H,_e,jc,Hc,mp,Ms=w(()=>{"use strict";H=require("node:fs"),_e=require("node:path"),jc=require("node:url");er();Pn();jo();on();ae();Hc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),mp=n=>(0,_e.join)(n,"plugins")});async function yp(n,e,t){let o=`${n}/-/v1/search?text=${encodeURIComponent(`keywords:${e}`)}&size=100`,r=await fetch(o,{signal:AbortSignal.timeout(t),headers:{accept:"application/json"}});if(!r.ok)throw new Error(`registry_status_${r.status}`);let s=await r.json();return Array.isArray(s?.objects)?s.objects:[]}async function _p(n,e={}){let t=(e.registryBase??hp).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(Wc.map(d=>yp(t,d,o))),s=new Map,a=!1;for(let d of r)if(d.status==="fulfilled"){a=!0;for(let m of d.value){let h=m?.package,f=typeof h?.name=="string"?h.name:"";if(!f||!Fe.NPM_SPEC_PATTERN.test(f)||!(Array.isArray(h?.keywords)?h.keywords.filter(b=>typeof b=="string"):[]).some(b=>Wc.includes(b)))continue;let _=typeof h?.version=="string"?h.version:"";s.has(f)||s.set(f,{name:f,version:_,description:typeof h?.description=="string"?h.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=(0,Fe.readPluginRecords)(n),c=new Map(i.map(d=>[d.name,d])),l=new Map(i.filter(d=>typeof d.source=="string"&&d.source!=="").map(d=>[d.source,d])),u=d=>{try{let m=JSON.parse((0,Ho.readFileSync)((0,Ns.join)(n,"plugins",d,"plugin.json"),"utf8"));return typeof m?.version=="string"?m.version:null}catch{return null}};return{ok:!0,plugins:[...s.values()].sort((d,m)=>d.name.localeCompare(m.name)).map(d=>{let m=c.get(d.name)??l.get(d.name),h=m!==void 0||(0,Ho.existsSync)((0,Ns.join)(n,"plugins",d.name));return{...d,installed:h,installedVersion:h?u(m?m.name:d.name):null}})}}function bp(n){switch(n){case"invalid_spec":return 400;case"already_installed":case"plugins_json_corrupted":return 409;case"npm_pack_failed":case"npm_pack_timeout":return 502;case"archive_too_large":case"archive_too_many_files":case"unsafe_archive_member":case"extract_failed":case"invalid_manifest":return 422;default:return 500}}function Kc(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),c=n.headers?.host;if(typeof c=="string"&&!i.has(c))return!1;let l=n.headers?.origin;if(l!==void 0&&l!==""){if(typeof l!="string")return!1;let u="";try{let p=new URL(l);if(!["http:","https:"].includes(p.protocol))return!1;u=p.host}catch{return!1}if(!i.has(u))return!1}return!0}function Gc(n,e){let t=e.configuredPort??3456,o=(r,s,a)=>r.status(s).send({ok:!1,error:a});n.get("/api/plugins/catalog",async(r,s)=>{if(!Kc(r,n,t))return o(s,403,"local_only");try{return await _p(e.configDir,{registryBase:e.catalogRegistryBase??e.registry,timeoutMs:e.catalogTimeoutMs})}catch(a){return n.log?.warn?.(`plugin catalog failed: ${a?.code??a?.name??"error"}`),{ok:!0,plugins:[],warning:"registry_unavailable"}}}),n.post("/api/plugins/install",async(r,s)=>{if(!Kc(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,c=a.force===!0;try{let l=await(0,Fe.installPluginFromNpm)({spec:i,configDir:e.configDir,force:c,registry:e.registry,timeoutMs:e.npmTimeoutMs});return n.log?.info?.(`provider plugin installed via API: ${l.manifest.name}@${l.manifest.version} (restart to activate)`),{ok:!0,name:l.manifest.name,version:l.manifest.version,restartRequired:!0}}catch(l){if(l instanceof Fe.PluginInstallError){let u=bp(l.code);return u===502?n.log?.warn?.(`plugin install failed: ${l.code}`):n.log?.warn?.(`plugin install rejected: ${l.code}: ${l.message}`),o(s,u,l.code)}return n.log?.error?.(`plugin install crashed: ${l?.message??l}`),o(s,500,"install_failed")}})}var Ho,Ns,Fe,Wc,hp,Vc=w(()=>{"use strict";Ho=require("node:fs"),Ns=require("node:path"),Fe=require("@wengine-ai/claude-code-router-shared"),Wc=["ccr-provider-plugin","claude-code-router-plugin"],hp="https://registry.npmjs.org"});function Qc(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function kp(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=hn(t,e),s=hn(o,e),a=[],i=new Set;for(let c of n||[])c&&c.name&&i.add(c.name);for(let c of Object.keys(r.byProvider||{}))i.add(c);for(let c of Object.keys(s.byProvider||{}))i.add(c);for(let c of i){let l=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},p=(l.inputTokens||0)+(l.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),m,h,f=(n||[]).find(g=>g&&g.name===c);f&&f.quota&&(m=f.quota.limit5h,h=f.quota.limit7d),a.push({provider:c,used5h:p,used7d:d,limit5h:m,limit7d:h})}return a}async function tl(n,e){let t=n.app;nt(),it(),t.register(qc.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=cn(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,c)=>{let l=decodeURIComponent(i.params.modelId),u=cn(e).find(p=>p.id===l);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${l}`}})}),t.post("/v1/messages/count_tokens",async(i,c)=>{let{messages:l,tools:u,system:p,model:d}=i.body,m=t._server.tokenizerService;if(d&&d.includes(",")&&m)try{let[f,g]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${f}, model: ${g}`);let _=m.getTokenizerConfigForModel(f,g);_?i.log?.info(`Using tokenizer config: ${JSON.stringify(_)}`):i.log?.warn(`No tokenizer config found for ${f},${g}, using default tiktoken`);let b=await m.countTokens({messages:l,system:p,tools:u},_,f);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(f){i.log?.error(`Error using configured tokenizer: ${f.message}`),i.log?.error(f.stack)}else d?d.includes(",")?m||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:Dt(l,p,u)}}),t.get("/api/config",async(i,c)=>await kt()),t.get("/api/transformers",async(i,c)=>{let l=t._server.transformerService.getAllTransformers();return{transformers:Array.from(l.entries()).map(([p,d])=>({name:p,endpoint:d.endPoint||null}))}}),t.post("/api/config",async(i,c)=>{let l=i.body,u=Ks(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(f=>`${f.key}: ${f.error}`).join("; "),proxyErrors:u};let p=await nn();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await ee()}catch{}let m=(0,Yc.ensureCcrSelfProvider)(l,d);n.pluginRegistry.applyConfigProtectors(l,d),await fe(l);let h;try{h=await(0,P.syncGlobalProjectTakeovers)(l),h.failed.length>0&&t.log?.warn?.({projectTakeoverSync:h},"Config saved but some global project takeovers failed to sync")}catch(f){t.log?.warn?.(`Config saved but global project takeover sync failed: ${f?.message||f}`)}return Ct(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:h}}),t.get("/api/clients",async(i,c)=>{try{let l=await ee();return{clients:(0,P.listClientStatuses)(l)}}catch(l){console.error("Failed to get client integrations:",l),c.status(500).send({error:l.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(i,c)=>{try{let l=i.body,u=Array.isArray(l?.enabled)?l.enabled:[],p=await ee(),d=(0,P.applyClientSelection)(p,u);await fe(d.config);let m=await(0,P.syncGlobalProjectTakeovers)(d.config),h=Qc(t,m,"clients/apply");return{...d,success:d.success&&h,projectTakeoverSync:m}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!(0,P.isClientId)(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await ee(),d=l==="enable"?(0,P.enableClient)(p,u):l==="restore"?(0,P.restoreClient)(p,u):(0,P.disableClient)(p,u);await fe(p);let m=await(0,P.syncGlobalProjectTakeovers)(p),h=Qc(t,m,`clients/${u}/${l}`);return{success:d.success&&h,result:d,results:[d],clients:(0,P.listClientStatuses)(p),config:p,projectTakeoverSync:m}}catch(u){console.error(`Failed to ${l} client integration:`,u),c.status(500).send({error:u.message||`Failed to ${l} client integration`})}}t.post("/api/clients/:id/enable",async(i,c)=>o(i,c,"enable")),t.post("/api/clients/:id/disable",async(i,c)=>o(i,c,"disable")),t.post("/api/clients/:id/restore",async(i,c)=>o(i,c,"restore")),t.get("/api/projects",async(i,c)=>{try{let l=await(0,P.listProjectConfigs)();return{projects:await Promise.all(l.map(async p=>{let d=await(0,P.getProjectTakeoverClients)(p.path);return{...p,ccrTakeoverClients:d,ccrTakeover:d.length>0}}))}}catch(l){console.error("Failed to list project configs:",l),c.status(500).send({error:l.message||"Failed to list project configs"})}}),t.post("/api/projects",async(i,c)=>{try{let{path:l}=i.body||{};if(!l||typeof l!="string"||!(0,Z.isAbsolute)(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,Z.normalize)(l).replace(/[\\/]+$/,"")||l;if(await(0,P.readProjectConfig)(u)){c.status(409).send({error:"Project is already configured"});return}await(0,P.writeProjectConfig)(u,{Router:{}});try{let m=await ee();await(0,P.setProjectTakeover)(u,["claudeCode"],m)}catch(m){console.error("Failed to auto-enable ccr takeover for new project:",m)}let d=await(0,P.getProjectTakeoverClients)(u);return{id:(0,P.getClaudeProjectId)(u),path:u,configPath:(0,P.getProjectConfigPath)(u),Router:{},ccrTakeoverClients:d,ccrTakeover:d.length>0}}catch(l){console.error("Failed to add project config:",l),c.status(500).send({error:l.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){c.status(400).send({error:"Router must be an object"});return}let p=await(0,P.readProjectConfigById)(l);if(!p){c.status(404).send({error:"Project config not found"});return}await(0,P.writeProjectConfig)(p.path,{Router:u});let d=await ee();Object.keys(u).length===0?await(0,P.refreshProjectTakeovers)(p.path,d):(await(0,P.refreshCcrProjectTakeover)(p.path,d,u),await(0,P.refreshPiProjectTakeover)(p.path,d,u));let m=await(0,P.getProjectTakeoverClients)(p.path);return{id:l,path:p.path,configPath:p.configPath,Router:u,ccrTakeoverClients:m,ccrTakeover:m.length>0}}catch(l){console.error("Failed to update project config:",l),c.status(500).send({error:l.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(i,c)=>{try{let{id:l}=i.params,u=i.body||{},p;if(Array.isArray(u.clients))p=u.clients.filter(P.isProjectTakeoverClient);else if(typeof u.enabled=="boolean")p=u.enabled?["claudeCode"]:[];else{c.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let d=await(0,P.readProjectConfigById)(l);if(!d){c.status(404).send({error:"Project config not found"});return}let m=await ee(),h=await(0,P.setProjectTakeover)(d.path,p,m);return{id:l,path:d.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await(0,P.readProjectConfigById)(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await ee();await(0,P.setProjectTakeover)(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await(0,P.deleteProjectConfig)(u.path),{success:!0}}catch(l){console.error("Failed to delete project config:",l),c.status(500).send({error:l.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:(0,Z.dirname)((0,Xc.fileURLToPath)(void 0)),s=(0,z.existsSync)((0,Z.join)(r,"index.html"))?r:(0,z.existsSync)((0,Z.join)(r,"..","index.html"))?(0,Z.join)(r,".."):(0,Z.join)(r,"..","dist");t.register(Zc.default,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(i,c)=>c.redirect("/ui/")),t.get("/api/logs/files",async(i,c)=>{try{let l=(0,Z.join)((0,zo.homedir)(),".claude-code-router","logs"),u=[];if((0,z.existsSync)(l)){let p=(0,z.readdirSync)(l);for(let d of p)if(d.endsWith(".log")){let m=(0,Z.join)(l,d),h=(0,z.statSync)(m);u.push({name:d,path:m,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((d,m)=>new Date(m.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(l){console.error("Failed to get log files:",l),c.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=(0,Z.join)((0,zo.homedir)(),".claude-code-router","logs","app.log"),(0,z.existsSync)(u)?(0,z.readFileSync)(u,"utf8").split(`
|
|
411
|
+
`).filter(m=>m.trim()):[]}catch(l){console.error("Failed to get logs:",l),c.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=(0,Z.join)((0,zo.homedir)(),".claude-code-router","logs","app.log"),(0,z.existsSync)(u)&&(0,z.writeFileSync)(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(l){console.error("Failed to clear logs:",l),c.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:Pt()})),t.put("/api/debug-log",async i=>{let{enabled:c}=i.body;return Cn(c),{enabled:Pt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return Rs({startTime:l.startDate,endTime:l.endDate,model:l.model,provider:l.provider,scenario:l.scenario,clientType:l.clientType,sessionId:l.sessionId,status:l.status,page:l.page?parseInt(l.page,10):void 0,pageSize:l.pageSize?parseInt(l.pageSize,10):void 0})}catch(l){console.error("Failed to query usage:",l),c.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(i,c)=>{try{let l=i.query;return hn(l.startDate,l.endDate,l.status)}catch(l){console.error("Failed to query usage summary:",l),c.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(i,c)=>{try{let l=i.query;return ws(l.beforeDate),{success:!0,message:l.beforeDate?"Usage data cleared before "+l.beforeDate:"All usage data cleared"}}catch(l){console.error("Failed to clear usage:",l),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,c)=>{try{let u=j().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(m=>({provider:m.provider,model:m.model,status:m.status,failureCount:m.failureCount,successCount:m.successCount,lastFailureTime:m.lastFailureTime,lastError:m.lastError,rateLimitUntil:m.rateLimitUntil??null})),probes:d,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to get provider health:",l),c.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,c)=>{try{let{providerName:l}=i.body;if(!l)return c.status(400),{error:"providerName is required"};let p=t._server?.activeProbeService;if(!p?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let d=await p.probeProviderManually(l);return d.success&&sn(l,i.log),{provider:l,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.error,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe provider:",l),c.status(500).send({error:l.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,c)=>{try{let l=t._server,u=l?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let p=(l?.providerService?.getProviders?.()||[]).filter(m=>m?.name&&m.enabled!==!1),d=await Promise.all(p.map(async m=>{let h=await u.probeProviderManually(m.name);return h.success&&sn(m.name,i?.log),{provider:m.name,success:h.success,latencyMs:h.latencyMs,status:h.status,isSlow:h.isSlow,errorKind:h.errorKind??null,error:h.error}}));return{results:d,successCount:d.filter(m=>m.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe all providers:",l),c.status(500).send({error:l.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,c)=>{try{let u=(await ee()).Providers||[],p=kp(u),d=new Map(p.map(f=>[f.provider,f])),m=In();for(let f of p){let g=m.find(_=>_.provider===f.provider);g&&g.limit!=null&&(f.limit5h=g.limit,f.used5h=g.limit-(g.remaining??0),g.reset&&(f.reset5h=new Date(g.reset*1e3).toISOString()))}let h=Fn();for(let f of h){let g=d.get(f.provider);g||(g={provider:f.provider,used5h:0,used7d:0},p.push(g),d.set(f.provider,g)),typeof f.totalBalance=="number"?(g.limit7d=f.totalBalance,g.type7d=f.currency?"balance":"rateLimit",f.currency&&(g.currency=f.currency),typeof f.usedBalance=="number"?g.used7d=f.usedBalance:typeof f.remainingBalance=="number"?g.used7d=Math.max(0,f.totalBalance-f.remainingBalance):(g.used7d=0,g.limit7d=f.totalBalance)):typeof f.usedBalance=="number"&&(g.used7d=f.usedBalance),typeof f.usedDailyBalance=="number"&&(g.used5h=f.usedDailyBalance,g.type5h="rateLimit"),typeof f.limitDaily=="number"&&(g.limit5h=f.limitDaily,g.type5h="rateLimit"),typeof f.resetTime=="string"&&(f.limitDaily!==void 0?g.reset5h=f.resetTime:g.reset7d=f.resetTime),typeof f.resetTime7d=="string"&&(g.reset7d=f.resetTime7d)}return{quotas:p,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=(0,Z.join)(P.HOME_DIR,"presets");if(!(0,z.existsSync)(l))return{presets:[]};let p=(0,z.readdirSync)(l,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).map(m=>m.name),d=[];for(let m of p){let h=(0,Z.join)(l,m);try{let f=(0,Z.join)(h,"manifest.json"),g=(0,z.readFileSync)(f,"utf-8"),_=JSON.parse(g),{Providers:b,Router:y,PORT:k,HOST:T,API_TIMEOUT_MS:S,PROXY_URL:v,PROXY_GLOBAL_ENABLED:R,LOG:C,LOG_LEVEL:x,StatusLine:O,NON_INTERACTIVE_MODE:A,...E}=_;d.push({id:m,name:E.name||m,version:E.version||"1.0.0",description:E.description,author:E.author,homepage:E.homepage,repository:E.repository,license:E.license,keywords:E.keywords,ccrVersion:E.ccrVersion,source:E.source,sourceType:E.sourceType,checksum:E.checksum,installed:!0})}catch(f){console.error(`Failed to read preset ${m}:`,f)}}return{presets:d}}catch(l){console.error("Failed to get presets:",l),c.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=(0,P.getPresetDir)(l);if(!(0,z.existsSync)(u)){c.status(404).send({error:"Preset not found"});return}let p=await(0,P.readManifestFromDir)(u);return{...(0,P.manifestToPresetFile)(p),config:(0,P.loadConfigFromManifest)(p,u),userValues:p.userValues||{}}}catch(l){console.error("Failed to get preset:",l),c.status(500).send({error:l.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(i,c)=>{try{let{name:l}=i.params,{secrets:u}=i.body,p=(0,P.getPresetDir)(l);if(!(0,z.existsSync)(p)){c.status(404).send({error:"Preset not found"});return}let m={...await(0,P.readManifestFromDir)(p)};return u&&Object.keys(u).length>0&&(m.userValues={...m.userValues,...u}),await(0,P.saveManifest)(l,m),{success:!0,message:"Preset applied successfully"}}catch(l){console.error("Failed to apply preset:",l),c.status(500).send({error:l.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=(0,P.getPresetDir)(l);if(!(0,z.existsSync)(u)){c.status(404).send({error:"Preset not found"});return}return(0,z.rmSync)(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(l){console.error("Failed to delete preset:",l),c.status(500).send({error:l.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(i,c)=>{try{return{presets:await(0,P.getMarketPresets)()}}catch(l){console.error("Failed to get market presets:",l),c.status(500).send({error:l.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(i,c)=>{try{let{presetName:l}=i.body;if(!l){c.status(400).send({error:"Preset name is required"});return}let u=await(0,P.findMarketPresetByName)(l);if(!u){c.status(400).send({error:"Preset not found in marketplace",message:`Preset '${l}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){c.status(400).send({error:"Invalid preset data",message:`Preset '${l}' does not have repository information`});return}let p=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!p){c.status(400).send({error:"Invalid GitHub repository URL"});return}let[,d,m]=p,h=u.name||l;if(await(0,P.isPresetInstalled)(h)){c.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let f=`https://github.com/${d}/${m}/archive/refs/heads/main.zip`,g=await(0,P.downloadPresetToTemp)(f),_=await a(g);if(await(0,P.isPresetInstalled)(h)){(0,z.unlinkSync)(g),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let b=(0,P.getPresetDir)(h);await(0,P.extractPreset)(g,b);let y=await(0,P.readManifestFromDir)(b);return y.repository=u.repo,u.url&&(y.source=u.url),await(0,P.saveManifest)(h,y),(0,z.unlinkSync)(g),{success:!0,presetName:h,preset:{..._.metadata,installed:!0}}}catch(l){console.error("Failed to install preset from GitHub:",l),c.status(500).send({error:l.message||"Failed to install preset from GitHub"})}});async function a(i){let c=new el.default(i),l=c.getEntry("manifest.json");if(l||(l=c.getEntries().find(d=>d.entryName.includes("manifest.json"))||null),!l)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(l.getData().toString("utf-8"));return(0,P.manifestToPresetFile)(u)}return t.get("/api/plugins",async()=>({plugins:Jc(P.HOME_DIR,n.pluginRegistry)})),Gc(t,{configDir:P.HOME_DIR,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,c)=>{let{name:l,file:u}=i.params,p=n.pluginRegistry.getPublicCard(l,u);return p?(c.header("Content-Type","application/javascript; charset=utf-8"),c.header("X-Content-Type-Options","nosniff"),c.header("Cache-Control","no-store"),c.send(p)):c.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var Yc,Z,Xc,Zc,z,zo,P,qc,el,nl=w(()=>{"use strict";Je();ot();at();ae();Et();le();an();jo();Ms();Vc();on();Yc=require("@wengine-ai/claude-code-router-shared"),Z=require("path"),Xc=require("url"),Zc=q(require("@fastify/static"),1),z=require("fs"),zo=require("os"),P=require("@wengine-ai/claude-code-router-shared"),qc=q(require("@fastify/multipart"),1),el=q(require("adm-zip"),1);yn();vs()});function Tp(n,e){let t=n?.Router,{family:o}=Ft(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function ol(n){return n?.Router?.image}function vp(n){return n.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function xp(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var $s,Bo,Ls,rl,sl=w(()=>{"use strict";Je();$s=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},Bo=new $s;Ls=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Tp(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!vp(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&Ut(e.body.model)?!1:(xp(e.body.messages),s&&!!ol(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let c=Bo.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=Bo.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(c=>c.type==="text"&&!c.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:ol(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
408
412
|
When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
|
|
409
413
|
Do not ignore or deviate from the task.
|
|
410
|
-
Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(
|
|
414
|
+
Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(i=>i.json()).catch(i=>null);return!a||!a.content?"analyzeImage Error":a.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
|
|
411
415
|
If the user requests you to view, analyze, or extract information from an image, you **must** call the \`analyzeImage\` tool.
|
|
412
416
|
|
|
413
417
|
When invoking this tool, you must pass the correct \`imageId\` extracted from the prior conversation.
|
|
@@ -417,5 +421,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
|
|
|
417
421
|
|
|
418
422
|
Do not attempt to describe or analyze the image directly yourself.
|
|
419
423
|
Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
|
|
420
|
-
Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(i=>i.type==="image"||Array.isArray(i.content)&&i.content.some(a=>a.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(i=>{if(i.type==="image")Oo.storeImage(`${e.id}_Image#${r}`,i.source),i.type="text",delete i.source,i.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(i.type==="text"&&i.text.includes("[Image #"))i.text=i.text.replace(/\[Image #\d+\]/g,"");else if(i.type==="tool_result"&&Array.isArray(i.content)&&i.content.some(a=>a.type==="image")){let a=[],l=i.content.filter(u=>u.type!=="image"?!0:(Oo.storeImage(`${e.id}_Image#${r}`,u.source),a.push(`[Image #${r}]`),r++,!1)),c=`${a.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;i.content=l.length>0?[{type:"text",text:c},...l]:c}})})}},yc=new us});var ds,kc,Ao,bc=E(()=>{"use strict";_c();ds=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},kc=new ds;kc.registerAgent(yc);Ao=kc});function wd(n,e){return n===429||!!(e&&/rate[\s_]limit|too many|限流|频率限制|qps_limit|token_limit|quota exhausted|usage limit|limit reached/i.test(e))}function Cc(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,e)}function fs(n){return n.usageSessionId||n.id}function Io(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${fs(n)}`}function ht(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function Ed(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Ke(e.usage):e.response?.usage?Ke(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Pd(n,e,t){if(await new Promise((r,s)=>{let i=a=>a?s(a):r();Yt(t)(n,e,i).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){Cc(n,t);let r=Io(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=ee.get(r))}}async function Od(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of Ao.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function Sc(n){return{authClient:(e,t)=>Pd(e,t,n),agent:(e,t)=>Od(e,t,n)}}function Rc(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=ps.performance.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,i)=>{let a=l=>l?i(l):s();Yt(e)(t,o,a).then(()=>s(),i)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Tc.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let i=t.pathname?.endsWith("/v1/messages"),a=t.pathname?.endsWith("/v1/responses");if(i||a){Cc(t,e);let l=fs(t),c=Io(t);if(r instanceof ReadableStream){if(i&&t.agents){let h=new AbortController,g=r.pipeThrough(new de),f,_=-1,k="",y="",b="",T=[],C=[];return s(null,Dt(g,async(v,S)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let x=t.agents.find(w=>Ao.getAgent(w)?.tools.get(v.data.content_block.name));if(x){f=Ao.getAgent(x),_=v.data.index,k=v.data.content_block.name,b=v.data.content_block.id;return}}if(_>-1&&v.data.index===_&&v.data?.delta?.type==="input_json_delta"){y+=v.data?.delta?.partial_json;return}if(_>-1&&v.data.index===_&&v.data?.type==="content_block_stop"){try{let x=xc.default.parse(y);C.push({type:"tool_use",id:b,name:k,input:x});let w=await f?.tools.get(k)?.handler(x,{req:t,config:e});T.push({tool_use_id:b,type:"tool_result",content:w}),f=void 0,_=-1,k="",y="",b=""}catch(x){console.log(x)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:C}),t.body.messages.push({role:"user",content:T});let x=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!x.ok)return;let R=x.body.pipeThrough(new de).getReader();for(;;)try{let{value:A,done:P}=await R.read();if(P)break;let N=A;if(["message_start","message_stop"].includes(N.event))continue;if(!S.desiredSize)break;S.enqueue(N)}catch(A){if(A.name==="AbortError"||A.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw A}return}return v}catch(x){if(console.error("Unexpected error in stream processing:",x),x.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();return}throw x}}).pipeThrough(new Je))}let[d,p]=r.tee(),m=async h=>{let f=h.pipeThrough(new TextDecoderStream).pipeThrough(new de).getReader();try{for(;;){let{done:_,value:k}=await f.read();if(_)break;let y=k.event,b=k.data;if(y==="message_start"&&b?.message?.model&&(t.upstreamModel=b.message.model),y==="response.completed"&&b?.response?.model&&(t.upstreamModel=b.response.model),b?.usage){let T=ee.get(c)||{},C=Ke(b.usage),v=Gt(T,C,y==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:y,provider:t.provider,model:ht(t),usageSessionId:l,capturedUsage:C,mergedUsage:v}),(C?.cache_read_input_tokens||C?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:C?.cache_read_input_tokens,cache_creation:C?.cache_creation_input_tokens}),ee.put(c,v)}if(b?.response?.usage){let T=Ke(b.response.usage),C=ee.get(c)||{},v=Gt(C,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:y,provider:t.provider,model:ht(t),usageSessionId:l,capturedUsage:T,mergedUsage:v}),ee.put(c,v)}}}catch(_){_.name==="AbortError"||_.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",_)}finally{f.releaseLock()}};return t.usageCapturePromise=m(p),s(null,d)}let u=Ed(r);if(u?.usage&&ee.put(c,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(Tc.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{Zo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Zo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{t.usageCapturePromise&&await t.usageCapturePromise,t.tokenSpeedCapturePromise&&await t.tokenSpeedCapturePromise;let r=fs(t),s=r,i=t.sessionId||r,a=o.statusCode>=400,l=a?void 0:ee.get(Io(t)),c=is(s),u=j(),d,p,m=t.sseError,h=m&&(m.type||m.code||m.message),g=l?.output_tokens&&l.output_tokens>0,f=a||h&&!g;if(f){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(m),p=JSON.stringify(m)),p=p||t.errorResponseBody;let T=ht(t);wd(o.statusCode,d)?u.markRateLimited(t.provider||"",T,120,d):u.recordFailure(t.provider||"",T,d)}else{let T=ht(t);u.recordSuccess(t.provider||"",T)}let _=l?.cache_read_input_tokens??0,y=l?.input_tokens||0||t.tokenCount||0;!_&&t.tokenCount&&l?.input_tokens&&l.input_tokens<t.tokenCount&&(_=t.tokenCount-l.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:l.input_tokens,impliedCache:_}));let b=f?0:l?.output_tokens||0;!f&&t.body?.stream&&y===0&&b===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:ht(t),usageSessionId:i,tokenCount:t.tokenCount,cachedUsage:l,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),nn({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:i,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:ht(t),upstreamModel:t.upstreamModel,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Ue(t),stream:t.body?.stream??!1,inputTokens:y,outputTokens:b,cacheReadInputTokens:_,cacheCreationInputTokens:l?.cache_creation_input_tokens||0,ttft:f||!t.body?.stream?null:c.ttft,tokensPerSecond:f?null:c.tokensPerSecond,durationMs:t.requestStartTime?Math.round(ps.performance.now()-t.requestStartTime):0,status:f?"error":"success",errorMessage:d,responseBody:p}),t.clientContext?.usageScope!=="session"&&ee.delete(Io(t))}catch(r){console.error("Usage tracking error:",r)}})}var vc,ps,xc,Tc,wc=E(()=>{"use strict";vc=require("node:events"),ps=require("node:perf_hooks"),xc=Z(require("json5"),1);st();vn();Tn();ce();Nr();$r();Lr();rn();Xr();bc();ts();Nn();Tc=new vc.EventEmitter});var Ac={};an(Ac,{createCcrServer:()=>Ad});async function Ad(n={}){await qa(),await Wt();let e=await vo();(0,$e.ensureCcrSelfProvider)(e).changed&&(await xe(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let i=n.port??e.PORT??3456,a=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):i;Pa();let l=f=>(f>9?"":"0")+f,c=(f,_)=>{let k;f?typeof f=="number"?k=new Date(f):k=f:k=new Date;let y=k.getFullYear()+""+l(k.getMonth()+1),b=l(k.getDate()),T=l(k.getHours()),C=l(k.getMinutes());return`./logs/ccr-${y}${b}${T}${C}${l(k.getSeconds())}${_?`_${_}`:""}.log`},u;n.logger!==void 0?u=n.logger:(rc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:(0,Oc.createStream)(c,{path:$e.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):u=!1);let d=await(0,$e.listPresets)(),p=new ms({jsonPath:$e.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:a,LOG_FILE:(0,Pc.join)((0,Ec.homedir)(),".claude-code-router","claude-code-router.log")},logger:u});await p.ready(),await mc(p,e),p.recordUsage=f=>{try{let _=f.req?f.req.clientType||Ue(f.req):"unknown";nn({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:f.sessionId||"",provider:f.provider||"",originalModel:f.originalModel||"",model:f.model||"",modelFamily:f.modelFamily||"",scenarioType:f.scenarioType||"default",clientType:_,stream:f.stream??!1,inputTokens:f.inputTokens||0,outputTokens:0,cacheReadInputTokens:f.cacheReadInputTokens||0,cacheCreationInputTokens:f.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:f.errorMessage,responseBody:void 0})}catch(_){console.error("Fallback usage tracking error:",_)}},Rc(p,e),p.ccrPreHandlerCallbacks=Sc(e),(await Promise.allSettled(d.map(async f=>await p.registerNamespace(`/preset/${f.name}`,f.config)))).forEach((f,_)=>{if(f.status==="rejected"){let k=d[_],y=f.reason instanceof Error?f.reason.message:String(f.reason);p.app?.log?.error?.(`Failed to register preset "${k?.name}": ${y}`)}}),await ic(p,e),ft(e,p.app?.log);let h=f=>{p.app.log.error({err:f},"Uncaught exception")},g=(f,_)=>{p.app.log.error({reason:f,promise:_},"Unhandled rejection")};return process.on("uncaughtException",h),process.on("unhandledRejection",g),p.app.addHook("onClose",async()=>{process.off("uncaughtException",h),process.off("unhandledRejection",g)}),p}var Ec,Pc,Oc,$e,Ic=E(()=>{"use strict";Ec=require("os"),Pc=require("path");Mc();Oc=require("rotating-file-stream"),$e=require("@wengine-ai/claude-code-router-shared");ec();xo();sc();Br();ac();gc();wc();So();rn();st()});var Nd={};an(Nd,{ActiveProbeService:()=>$t,ConfigService:()=>De,ProjectRoutingError:()=>ne,ProviderHealthStore:()=>Tt,ProviderService:()=>me,SSEParserTransform:()=>de,SSESerializerTransform:()=>Je,TokenizerService:()=>ze,TransformerService:()=>He,apiKeyAuth:()=>Yt,applyClientAdapter:()=>Re,backupConfigFile:()=>Kt,builtinClientAdapterRegistry:()=>ir,calculateTokenCount:()=>wt,clearClientAdapterCaches:()=>ai,clearProviderHealth:()=>Vt,closeProxyDispatchers:()=>ln,collectReachableModelKeys:()=>qr,createCcrServer:()=>Lc,default:()=>ms,detectClientType:()=>Ue,diagnoseResolutionFailure:()=>lr,extractSessionIdFromUserId:()=>be,getActiveProbeService:()=>Ir,getAllQuotaResults:()=>Cn,getAllRateLimitInfo:()=>_n,getClientAdapter:()=>cr,getConfiguredProxyUrl:()=>yt,getHealthStore:()=>j,getProxyDispatcher:()=>Q,getQuotaAdapter:()=>go,getQuotaResult:()=>Ct,getRateLimitInfo:()=>Hs,getRuntimeDebugLog:()=>kt,getServer:()=>Md,initConfig:()=>vo,initDir:()=>Wt,initProviderHealthPersistence:()=>yn,initQuotaStorePersistence:()=>et,initRateLimitPersistence:()=>Ye,isClientType:()=>ar,isGlobalProxyEnabled:()=>Mo,listAnthropicCompatibleModels:()=>Qt,mergeUsageCapture:()=>Gt,normalizeSessionId:()=>ke,normalizeUsagePayload:()=>Ke,pluginManager:()=>dt,readConfigFile:()=>ie,readConfigFileRaw:()=>To,reconcileHealthStore:()=>ft,resetActiveProbeService:()=>Lt,resolveProviderProxyUrl:()=>pe,rewriteStream:()=>Dt,router:()=>Pt,searchProjectBySession:()=>dr,sessionUsageCache:()=>ee,setRuntimeDebugLog:()=>dn,startActiveProbe:()=>Be,stopActiveProbe:()=>ho,storeQuotaResult:()=>xn,tokenSpeedPlugin:()=>Bt,usageStore:()=>as,writeConfigFile:()=>xe});module.exports=ys(Nd);function Id(n={}){let e=(0,Nc.default)({bodyLimit:52428800,...n});return e.setErrorHandler(xs),e.register($c.default),e}async function Lc(n={}){return(await Promise.resolve().then(()=>(Ic(),Ac))).createCcrServer(n)}var Nc,$c,gs,ms,Md,Mc=E(()=>{Nc=Z(require("fastify"),1),$c=Z(require("@fastify/cors"),1);$o();un();Nn();$n();hr();yr();at();vn();yo();ce();Xe();tt();ae();st();Nn();nt();st();at();$o();$n();hr();yr();Vr();Dr();ce();Xe();Or();tt();ce();yo();bt();ae();xo();Xr();So();es();ts();rn();gs=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:i,useEnvironmentVariables:a,...l}=e;this.app=Id({...l,logger:l.logger??!0}),this.app._server=this;let c={initialConfig:t};o!==void 0&&(c.jsonPath=o),r!==void 0&&(c.envPath=r),s!==void 0&&(c.useEnvFile=s),i!==void 0&&(c.useJsonFile=i),a!==void 0&&(c.useEnvironmentVariables=a),this.configService=new De(c),this.transformerService=new He(this.configService,this.app.log),this.tokenizerService=new ze(this.configService,this.app.log),this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.providerService=new me(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,i=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new De({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new He(o,this.app.log),i=new ze(o,this.app.log),await Promise.all([r.initialize(),i.initialize()]),s=new me(o,r,this.app.log)}let a=async l=>{l.decorate("configService",o),l.decorate("transformerService",r),l.decorate("providerService",s),l.decorate("tokenizerService",i),l.decorate("recordUsage",this.recordUsage||(()=>{})),l.addHook("preHandler",async(c,u)=>{let d=new URL(`http://127.0.0.1${c.url}`);c.pathname=d.pathname;let p=d.pathname.endsWith("/v1/messages"),m=d.pathname.endsWith("/v1/responses");if(!p&&!m||!c.body||typeof c.body!="object")return;let h=c.ccrHookOrder||=[];if(h.push("request-normalize"),m&&c.body.input&&!c.body.messages&&Ot(c.body),c.body.stream===void 0&&(c.body.stream=!1),c.log.info({data:c.body,type:"request body"}),h.push("adapter"),!c.originalModel&&c.body.model&&(c.originalModel=c.body.model),Re(c,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(c,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(c,u),u.sent)))){h.push("router"),c.body?.model&&await Pt(c,u,{configService:o,tokenizerService:i}),c.usageCacheKey&&ee.put(c.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let g=c.body;if(!g||!g.model)return u.code(400).send({error:"Missing model in request body"});let f=g.model.split(","),_=g.model;if(f.length>1){let[k,...y]=f;_=y.join(","),g.model=_,c.provider=k}c.model=_}catch(g){return c.log.error({error:g},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Ti(l)};e==="/"?(await this.app.register(a),this.mainNamespaceRegistered=!0):await this.app.register(a,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{ho()}catch{}await this.app.close(),process.exit(0)},o=()=>void t("SIGINT"),r=()=>void t("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",r),this.app.addHook("onClose",async()=>{process.off("SIGINT",o),process.off("SIGTERM",r),this.signalHandlersRegistered=!1;try{this.tokenizerService.dispose()}catch{}await ln()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{Ye()}catch{}try{et()}catch{}try{yn()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Be(()=>this.providerService.getProviders(),t,o=>pe(this.configService,o),this.app.log,o=>this.configService.get(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},ms=gs;Md=Lc});Mc();0&&(module.exports={ActiveProbeService,ConfigService,ProjectRoutingError,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,apiKeyAuth,applyClientAdapter,backupConfigFile,builtinClientAdapterRegistry,calculateTokenCount,clearClientAdapterCaches,clearProviderHealth,closeProxyDispatchers,collectReachableModelKeys,createCcrServer,detectClientType,diagnoseResolutionFailure,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getClientAdapter,getConfiguredProxyUrl,getHealthStore,getProxyDispatcher,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,getServer,initConfig,initDir,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,isClientType,isGlobalProxyEnabled,listAnthropicCompatibleModels,mergeUsageCapture,normalizeSessionId,normalizeUsagePayload,pluginManager,readConfigFile,readConfigFileRaw,reconcileHealthStore,resetActiveProbeService,resolveProviderProxyUrl,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin,usageStore,writeConfigFile});
|
|
424
|
+
Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")Bo.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],c=a.content.filter(u=>u.type!=="image"?!0:(Bo.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),l=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=c.length>0?[{type:"text",text:l},...c]:l}})})}},rl=new Ls});var Ds,il,Jo,al=w(()=>{"use strict";sl();Ds=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},il=new Ds;il.registerAgent(rl);Jo=il});function Cp(n,e){return n===429||!!(e&&/rate[\s_]limit|too many|限流|频率限制|qps_limit|token_limit|quota exhausted|usage limit|limit reached/i.test(e))}function dl(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ee(n,e)}function Us(n){return n.usageSessionId||n.id}function Wo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Us(n)}`}function St(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function Sp(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Xe(e.usage):e.response?.usage?Xe(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Rp(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();ln(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){dl(n,t);let r=Wo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=ne.get(r))}}async function wp(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of Jo.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function pl(n){return{authClient:(e,t)=>Rp(e,t,n),agent:(e,t)=>wp(e,t,n)}}function fl(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Fs.performance.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=c=>c?a(c):s();ln(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",cl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){dl(t,e);let c=Us(t),l=Wo(t);if(r instanceof ReadableStream){if(a&&t.agents){let h=new AbortController,f=r.pipeThrough(new pe),g,_=-1,b="",y="",k="",T=[],S=[];return s(null,Gt(f,async(v,R)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let C=t.agents.find(x=>Jo.getAgent(x)?.tools.get(v.data.content_block.name));if(C){g=Jo.getAgent(C),_=v.data.index,b=v.data.content_block.name,k=v.data.content_block.id;return}}if(_>-1&&v.data.index===_&&v.data?.delta?.type==="input_json_delta"){y+=v.data?.delta?.partial_json;return}if(_>-1&&v.data.index===_&&v.data?.type==="content_block_stop"){try{let C=ul.default.parse(y);S.push({type:"tool_use",id:k,name:b,input:C});let x=await g?.tools.get(b)?.handler(C,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:x}),g=void 0,_=-1,b="",y="",k=""}catch(C){console.log(C)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:S}),t.body.messages.push({role:"user",content:T});let C=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!C.ok)return;let O=C.body.pipeThrough(new pe).getReader();for(;;)try{let{value:A,done:E}=await O.read();if(E)break;let N=A;if(["message_start","message_stop"].includes(N.event))continue;if(!R.desiredSize)break;R.enqueue(N)}catch(A){if(A.name==="AbortError"||A.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw A}return}return v}catch(C){if(console.error("Unexpected error in stream processing:",C),C.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();return}throw C}}).pipeThrough(new Qe))}let[p,d]=r.tee(),m=async h=>{let g=h.pipeThrough(new TextDecoderStream).pipeThrough(new pe).getReader();try{for(;;){let{done:_,value:b}=await g.read();if(_)break;let y=b.event,k=b.data;if(y==="message_start"&&k?.message?.model&&(t.upstreamModel=k.message.model),y==="response.completed"&&k?.response?.model&&(t.upstreamModel=k.response.model),k?.usage){let T=ne.get(l)||{},S=Xe(k.usage),v=rn(T,S,y==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:y,provider:t.provider,model:St(t),usageSessionId:c,capturedUsage:S,mergedUsage:v}),(S?.cache_read_input_tokens||S?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:S?.cache_read_input_tokens,cache_creation:S?.cache_creation_input_tokens}),ne.put(l,v)}if(k?.response?.usage){let T=Xe(k.response.usage),S=ne.get(l)||{},v=rn(S,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:y,provider:t.provider,model:St(t),usageSessionId:c,capturedUsage:T,mergedUsage:v}),ne.put(l,v)}}}catch(_){_.name==="AbortError"||_.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",_)}finally{g.releaseLock()}};return t.usageCapturePromise=m(d),s(null,p)}let u=Sp(r);if(u?.usage&&ne.put(l,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(cl.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{_r(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),_r(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{t.usageCapturePromise&&await t.usageCapturePromise,t.tokenSpeedCapturePromise&&await t.tokenSpeedCapturePromise;let r=Us(t),s=r,a=t.sessionId||r,i=o.statusCode>=400,c=i?void 0:ne.get(Wo(t)),l=Ps(s),u=j(),p,d,m=t.sseError,h=m&&(m.type||m.code||m.message),f=c?.output_tokens&&c.output_tokens>0,g=i||h&&!f;if(g){p=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(p=p||JSON.stringify(m),d=JSON.stringify(m)),d=d||t.errorResponseBody;let T=St(t);Cp(o.statusCode,p)?u.markRateLimited(t.provider||"",T,120,p):u.recordFailure(t.provider||"",T,p)}else{let T=St(t);u.recordSuccess(t.provider||"",T)}let _=c?.cache_read_input_tokens??0,y=c?.input_tokens||0||t.tokenCount||0;!_&&t.tokenCount&&c?.input_tokens&&c.input_tokens<t.tokenCount&&(_=t.tokenCount-c.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:c.input_tokens,impliedCache:_}));let k=g?0:c?.output_tokens||0;!g&&t.body?.stream&&y===0&&k===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:St(t),usageSessionId:a,tokenCount:t.tokenCount,cachedUsage:c,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),gn({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:a,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:St(t),upstreamModel:t.upstreamModel,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||ze(t),stream:t.body?.stream??!1,inputTokens:y,outputTokens:k,cacheReadInputTokens:_,cacheCreationInputTokens:c?.cache_creation_input_tokens||0,ttft:g||!t.body?.stream?null:l.ttft,tokensPerSecond:g?null:l.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Fs.performance.now()-t.requestStartTime):0,status:g?"error":"success",errorMessage:p,responseBody:d}),t.clientContext?.usageScope!=="session"&&ne.delete(Wo(t))}catch(r){console.error("Usage tracking error:",r)}})}var ll,Fs,ul,cl,ml=w(()=>{"use strict";ll=require("node:events"),Fs=require("node:perf_hooks"),ul=q(require("json5"),1);dt();Ln();$n();le();ns();os();rs();yn();bs();al();xs();Vn();cl=new ll.EventEmitter});var _l={};bn(_l,{createCcrServer:()=>Pp});async function Pp(n={}){await Ac(),await tn();let e=await $o();(0,Re.ensureCcrSelfProvider)(e).changed&&(await fe(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;ac();let c=m=>(m>9?"":"0")+m,l=(m,h)=>{let f;m?typeof m=="number"?f=new Date(m):f=m:f=new Date;let g=f.getFullYear()+""+c(f.getMonth()+1),_=c(f.getDate()),b=c(f.getHours()),y=c(f.getMinutes());return`./logs/ccr-${g}${_}${b}${y}${c(f.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(Lc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:(0,yl.createStream)(l,{path:Re.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await(0,Re.listPresets)(),d=new js({jsonPath:Re.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:(0,hl.join)((0,gl.homedir)(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let m=await Bc({configDir:Re.HOME_DIR,registry:d.pluginRegistry,getServer:()=>d,log:{info:_=>d.app?.log?.info?.(_),warn:_=>d.app?.log?.warn?.(_),error:_=>d.app?.log?.error?.(_)}});m.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${m.failed.map(_=>`${_.name} (${_.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(_=>`${_.name}@${_.version}`).join(", ")}`),m.loaded.length&&Ct(d,e,d.app.log),await tl(d,e),d.recordUsage=_=>{try{let b=_.req?_.req.clientType||ze(_.req):"unknown";gn({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:_.sessionId||"",provider:_.provider||"",originalModel:_.originalModel||"",model:_.model||"",modelFamily:_.modelFamily||"",scenarioType:_.scenarioType||"default",clientType:b,stream:_.stream??!1,inputTokens:_.inputTokens||0,outputTokens:0,cacheReadInputTokens:_.cacheReadInputTokens||0,cacheCreationInputTokens:_.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:_.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},fl(d,e),d.ccrPreHandlerCallbacks=pl(e),(await Promise.allSettled(p.map(async _=>await d.registerNamespace(`/preset/${_.name}`,_.config)))).forEach((_,b)=>{if(_.status==="rejected"){let y=p[b],k=_.reason instanceof Error?_.reason.message:String(_.reason);d.app?.log?.error?.(`Failed to register preset "${y?.name}": ${k}`)}}),await Fc(d,e),Tt(e,d.app?.log);let f=_=>{d.app.log.error({err:_},"Uncaught exception")},g=(_,b)=>{d.app.log.error({reason:_,promise:b},"Unhandled rejection")};return process.on("uncaughtException",f),process.on("unhandledRejection",g),d.app.addHook("onClose",async()=>{process.off("uncaughtException",f),process.off("unhandledRejection",g)}),d}catch(m){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),m}}var gl,hl,yl,Re,bl=w(()=>{"use strict";gl=require("os"),hl=require("path");kl();yl=require("rotating-file-stream"),Re=require("@wengine-ai/claude-code-router-shared");Ic();on();Dc();ds();Uc();nl();Ms();jo();ml();an();yn();dt()});var Ap={};bn(Ap,{ActiveProbeService:()=>Kt,ConfigService:()=>Ue,ProjectRoutingError:()=>re,ProviderHealthStore:()=>At,ProviderService:()=>We,SSEParserTransform:()=>pe,SSESerializerTransform:()=>Qe,TokenizerService:()=>Ge,TransformerService:()=>Ke,apiKeyAuth:()=>ln,applyClientAdapter:()=>Ee,backupConfigFile:()=>nn,builtinClientAdapterRegistry:()=>Rr,calculateTokenCount:()=>Dt,clearClientAdapterCaches:()=>Ui,clearProviderHealth:()=>sn,closeProxyDispatchers:()=>vn,collectReachableModelKeys:()=>Ts,createCcrServer:()=>xl,default:()=>js,detectClientType:()=>ze,diagnoseResolutionFailure:()=>Er,extractSessionIdFromUserId:()=>Ce,getActiveProbeService:()=>es,getAllQuotaResults:()=>Fn,getAllRateLimitInfo:()=>In,getClientAdapter:()=>Pr,getConfiguredProxyUrl:()=>Rt,getHealthStore:()=>j,getProxyDispatcher:()=>Y,getQuotaAdapter:()=>Po,getQuotaResult:()=>Nt,getRateLimitInfo:()=>bi,getRuntimeDebugLog:()=>Pt,getServer:()=>Op,initConfig:()=>$o,initDir:()=>tn,initProviderHealthPersistence:()=>An,initQuotaStorePersistence:()=>it,initRateLimitPersistence:()=>nt,isClientType:()=>wr,isGlobalProxyEnabled:()=>Vo,listAnthropicCompatibleModels:()=>cn,mergeUsageCapture:()=>rn,normalizeSessionId:()=>xe,normalizeUsagePayload:()=>Xe,pluginManager:()=>_t,readConfigFile:()=>ee,readConfigFileRaw:()=>kt,reconcileHealthStore:()=>Tt,resetActiveProbeService:()=>Oo,resolveProviderProxyUrl:()=>me,rewriteStream:()=>Gt,router:()=>jt,searchProjectBySession:()=>Or,sessionUsageCache:()=>ne,setRuntimeDebugLog:()=>Cn,startActiveProbe:()=>yt,stopActiveProbe:()=>Eo,storeQuotaResult:()=>Dn,tokenSpeedPlugin:()=>qt,usageStore:()=>Es,writeConfigFile:()=>fe});module.exports=Bs(Ap);function Ep(n={}){let e=(0,Tl.default)({bodyLimit:52428800,...n});return e.setErrorHandler(Xs),e.register(vl.default),e}async function xl(n={}){return(await Promise.resolve().then(()=>(bl(),_l))).createCcrServer(n)}var Tl,vl,Hs,js,Op,kl=w(()=>{Tl=q(require("fastify"),1),vl=q(require("@fastify/cors"),1);Yo();xn();Vn();Ar();Dr();Fr();Je();Ln();Ao();le();ot();at();ae();dt();Vn();Pn();ct();dt();Je();Yo();Ar();Dr();Fr();hs();ss();le();ot();Xr();at();le();Ao();Et();ae();on();bs();an();vs();xs();yn();Hs=class{app;pluginRegistry=new Ot;namespaceProviders=[];reloadProviders(e){let t=e?.Providers??e?.providers??[];this.configService.set("providers",t),this.providerService.reload();for(let o of this.namespaceProviders)o.providers.reload()}reloadNamespaceProviders(e,t){let o=this.namespaceProviders.find(r=>r.name===e);if(!o)throw new Error(`unknown namespace ${e}`);o.config.set("providers",t),o.providers.reload()}configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:i,...c}=e;this.app=Ep({...c,logger:c.logger??!0}),this.app._server=this,this.app.addHook("onClose",async()=>{this.pluginRegistry.dispose(),this.tokenizerService?.dispose()});let l={initialConfig:t};o!==void 0&&(l.jsonPath=o),r!==void 0&&(l.envPath=r),s!==void 0&&(l.useEnvFile=s),a!==void 0&&(l.useJsonFile=a),i!==void 0&&(l.useEnvironmentVariables=i),this.configService=new Ue(l),this.transformerService=new Ke(this.configService,this.app.log),this.tokenizerService=new Ge(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new We(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Ue({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ke(o,this.app.log),a=new Ge(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new We(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async c=>{c.decorate("pluginRegistry",this.pluginRegistry),c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,u)=>{let p=new URL(`http://127.0.0.1${l.url}`);l.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),m=p.pathname.endsWith("/v1/responses");if(!d&&!m||!l.body||typeof l.body!="object")return;let h=l.ccrHookOrder||=[];if(h.push("request-normalize"),m&&l.body.input&&!l.body.messages&&Ht(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),h.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),Ee(l,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){h.push("router"),l.body?.model&&await jt(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&ne.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let f=l.body;if(!f||!f.model)return u.code(400).send({error:"Missing model in request body"});let g=f.model.split(","),_=f.model;if(g.length>1){let[b,...y]=g;_=y.join(","),f.model=_,l.provider=b}l.model=_}catch(f){return l.log.error({error:f},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await ea(c)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{Eo()}catch{}await this.app.close(),process.exit(0)},o=()=>void t("SIGINT"),r=()=>void t("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",r),this.app.addHook("onClose",async()=>{process.off("SIGINT",o),process.off("SIGTERM",r),this.signalHandlersRegistered=!1;try{this.tokenizerService.dispose()}catch{}await vn()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{nt()}catch{}try{it()}catch{}try{An()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=yt(()=>this.providerService.getProviders(),t,o=>me(this.configService,o),this.app.log,o=>this.configService.get(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},js=Hs;Op=xl});kl();0&&(module.exports={ActiveProbeService,ConfigService,ProjectRoutingError,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,apiKeyAuth,applyClientAdapter,backupConfigFile,builtinClientAdapterRegistry,calculateTokenCount,clearClientAdapterCaches,clearProviderHealth,closeProxyDispatchers,collectReachableModelKeys,createCcrServer,detectClientType,diagnoseResolutionFailure,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getClientAdapter,getConfiguredProxyUrl,getHealthStore,getProxyDispatcher,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,getServer,initConfig,initDir,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,isClientType,isGlobalProxyEnabled,listAnthropicCompatibleModels,mergeUsageCapture,normalizeSessionId,normalizeUsagePayload,pluginManager,readConfigFile,readConfigFileRaw,reconcileHealthStore,resetActiveProbeService,resolveProviderProxyUrl,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin,usageStore,writeConfigFile});
|
|
421
425
|
//# sourceMappingURL=server.cjs.map
|