@wengine-ai/llms 2.3.2414 → 2.3.2416
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 -0
- package/THIRD_PARTY_NOTICES.md +3 -0
- package/dist/api/empty-answer-guard.d.ts +66 -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/models.d.ts +9 -1
- package/dist/ccr/plugin-install-routes.d.ts +79 -0
- package/dist/cjs/server.cjs +219 -214
- package/dist/cjs/server.cjs.map +4 -4
- package/dist/esm/server.mjs +221 -216
- 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 +236 -0
- package/dist/server.d.ts +8 -0
- package/dist/services/active-probe.d.ts +46 -4
- package/dist/services/provider-health.d.ts +18 -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/esm/server.mjs
CHANGED
|
@@ -1,319 +1,324 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; import { fileURLToPath as __fileURLToPath } from "node:url"; import { dirname as __pathDirname } from "node:path"; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __pathDirname(__filename);
|
|
2
|
-
var
|
|
2
|
+
var fo=Object.defineProperty;var Xc=Object.getOwnPropertyDescriptor;var Zc=Object.getOwnPropertyNames;var qc=Object.prototype.hasOwnProperty;var ot=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var mo=(n,e)=>{for(var t in e)fo(n,t,{get:e[t],enumerable:!0})},el=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zc(e))!qc.call(n,r)&&r!==t&&fo(n,r,{get:()=>e[r],enumerable:!(o=Xc(e,r))||o.enumerable});return n};var tl=n=>el(fo({},"__esModule",{value:!0}),n);import{Agent as nl,ProxyAgent as ol}from"undici";function sl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(rl.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[...bs,_s]){let o=n[t];if(o==null)continue;let r=sl(o);r.ok||e.push({key:t,error:r.error})}return e}function ho(){return go||(go=new nl({connect:{timeout:15e3}})),go}function Ts(n){let e=n.get(_s);return(typeof e=="string"?e.trim():"")||void 0}function vs(n){return n?K(n):ho()}function jt(n){for(let e of bs){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function xs(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 ue(n,e){let t=jt(n);if(t)return xs(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function K(n){let e=il(n),t=Ut.get(e);if(t)return t;let o=new ol(e);return Ut.set(e,o),o}async function yo(){let n=Array.from(Ut.values());Ut.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 bs,_s,rl,Ut,go,q=w(()=>{"use strict";bs=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],_s="SUBSCRIPTION_PROXY_URL",rl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Ut=new Map});import{readFileSync as al,existsSync as Ss}from"fs";import{join as Cs}from"path";import{config as cl}from"dotenv";import ll from"json5";var Ee,bo=w(()=>{"use strict";q();Ee=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:Cs(process.cwd(),this.options.jsonPath);if(Ss(e))try{let t=al(e,"utf-8"),o=ll.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:Cs(process.cwd(),this.options.envPath);if(Ss(e))try{let t=cl({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 jt(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 z(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 Rs(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 Ht=w(()=>{"use strict"});function ko(n){_o=n}function zt(){return _o}function Bt(n){return _o||n.get("DEBUG_LOG")===!0}function Es(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Ae:{maxBodyLength:e.maxBodyLength??Ae.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Ae.maxStreamChunks}}function Jt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();ul.has(r)||dl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Wt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function As(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:Jt(t.headers),body:Wt(o,Ae.maxBodyLength)})}function Os(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Jt(t.headers),...t.body!==void 0?{body:Wt(t.body,Ae.maxBodyLength)}:{}})}function ws(n,e,t,o){let r=pl(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Wt(o,Ae.maxBodyLength)})}function pl(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:Wt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Ps(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Is(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let i="";for(;;){let{done:a,value:l}=await r.read();if(a)break;i+=l;let c=i.split(`
|
|
3
3
|
|
|
4
|
-
`);i=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Xr(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}i.trim()&&(s<o.maxStreamChunks&&Xr(e,t,s,i.trim()),s++),Zr(e,t,s)}catch(i){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,i),Zr(e,t,s)}finally{r.releaseLock()}})()}var mc,we,so,Ze=E(()=>{"use strict";mc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),we={maxBodyLength:4096,maxStreamChunks:100},so=!1});function os(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([c,u])=>{u&&s.set(c,u)});let i,a=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),a.addEventListener("abort",u),i=c.signal}else i=a;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:i};return t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Ot(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:hc(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function hc(n){if(!(typeof n!="string"||!n.trim()))try{let e=new URL(n);return e.username||e.password?(e.username="",e.password="",`${e.toString()} (credentials redacted)`):e.toString()}catch{return"[invalid proxy URL]"}}var rs=E(()=>{oe();Ze()});var It,ao=E(()=>{It="2.3.2414"});var ss={};no(ss,{getFallbackPromotionStore:()=>Ee,resetFallbackPromotionStore:()=>kc});function Ee(n){return ve||(ve=new co,n&&ve.configure(n)),ve}function kc(){ve&&(ve.clearAll(),ve=null)}var _c,co,ve,Mt=E(()=>{"use strict";re();_c=600*1e3,co=class{promotions=new Map;enabled=!0;ttlMs=_c;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,i){if(!this.enabled)return;let a=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(a,{promotedModel:l,timestamp:Date.now(),ttlMs:i??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),i=this.promotions.get(s);if(!i)return null;if(Date.now()-i.timestamp>=i.ttlMs)return this.promotions.delete(s),null;let[l,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(l,u))return this.promotions.delete(s),null;let p=r.find(h=>h.name.toLowerCase()===l.toLowerCase()),m=p?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!p||!m||p.enabled===!1?(this.promotions.delete(s),null):`${p.name},${m}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},ve=null});import{existsSync as cs,mkdirSync as bc,readFileSync as Tc,writeFileSync as vc}from"fs";import{join as ls}from"path";import{HOME_DIR as xc}from"@wengine-ai/claude-code-router-shared";function wc(n){try{if(!cs(po))return;let e=JSON.parse(Tc(po,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function as(n){try{let e=n.getAllStates();if(e.length===0)return;cs(uo)||bc(uo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));vc(po,JSON.stringify(t,null,2),"utf-8")}catch{}}function fo(){if(is)return;is=!0;let n=U();wc(n),Rc=setInterval(()=>as(n),6e4),process.on("exit",()=>as(n))}function U(n){return lo||(lo=new Nt(n)),lo}var Cc,Sc,Nt,uo,po,is,Rc,lo,re=E(()=>{"use strict";Cc=120,Sc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Nt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Sc,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.successCount++,!r.rateLimitUntil&&(r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0)))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Mt(),ic(ss));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let r=this.getState(e,t);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let i=this.states.get(s);i?(i.status="open",i.lastFailureTime=Date.now(),i.lastError=r||"rate-limited",i.lastProbeTime=0):(i={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,i));let a=(o??Cc)*1e3;i.rateLimitUntil=Date.now()+a}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},uo=ls(xc,"runtime"),po=ls(uo,"provider-health.json"),is=!1,Rc=null;lo=null});import{existsSync as ms,mkdirSync as Ec,readFileSync as Pc,writeFileSync as Oc}from"fs";import{join as gs}from"path";import{HOME_DIR as Ac}from"@wengine-ai/claude-code-router-shared";function qe(n,e,t){let o=a=>{if(t instanceof Headers)return t.get(a);let l=Object.keys(t).find(c=>c.toLowerCase()===a);return l?t[l]:null},r=mo(o,Ic),s=mo(o,Mc),i=mo(o,Nc);(r||s||i)&&Pe.set(n,{provider:n,remaining:ps(r),limit:ps(s),reset:Lc(i),capturedAt:Date.now()})}function $c(n){return Pe.get(n)}function yo(){return Array.from(Pe.values())}function mo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ps(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Lc(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):t>1e9?Math.floor(t):Math.floor(Date.now()/1e3+t);let o=Date.parse(e);if(Number.isFinite(o))return Math.floor(o/1e3);let r=Dc(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Dc(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),i=r[2].toLowerCase();if(Number.isFinite(s))switch(i){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function Fc(){try{if(!ms(ho))return;let n=JSON.parse(Pc(ho,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Pe.set(t.provider,t)}}catch{}}function fs(){try{if(Pe.size===0)return;ms(go)||Ec(go,{recursive:!0}),Oc(ho,JSON.stringify(Array.from(Pe.values()),null,2),"utf-8")}catch{}}function et(){us||(us=!0,Fc(),ds=setInterval(fs,6e4),ds.unref?.(),process.on("exit",fs))}var go,ho,Pe,us,ds,Ic,Mc,Nc,Oe=E(()=>{"use strict";go=gs(Ac,"runtime"),ho=gs(go,"rate-limit.json"),Pe=new Map,us=!1,ds=null,Ic=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Mc=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Nc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Lt(){return _o||(_o=new bo),_o}function vo(){return ko||(ko=new To),ko}function Uc(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function hs(n){let e=Uc(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function ys(n,e){let t=Lt(),o=n?.[$t];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[$t]=t.acquire(e)}function xo(n){let e=n?.[$t];e&&Lt().release(e)}function _s(n,e){let t=hs(n),o=n?.[$t],r=t?vo().get(t)!==void 0:!1;!o&&!r||(t&&vo().bind(t,e),ys(n,e))}function jc(n,e,t){let o=Lt(),r=null,s=1/0;for(let i of e){if(!i||typeof i!="string")continue;let a=t(i);if(!a||a===n)continue;let l=o.count(a);l<s&&(r=a,s=l)}return r}function ks(n,e,t){let o=hs(n),r=vo(),s=Lt(),i=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,a;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(a=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(a=e)}if(!a){let l=s.count(e);if(l>=i){let c=jc(e,t.fallbackModels,t.resolve);c&&(a=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${i}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}a=a||e,o&&r.bind(o,a)}return ys(n,a),a}var bo,To,_o,ko,$t,Dt=E(()=>{"use strict";bo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},To=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},_o=null,ko=null;$t="__concurrencyLease"});async function F(n){let e=await n.text();return Hc(e,n.status)}function Hc(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function bs(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function tt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let i=0;i<8;i++){let{value:a,done:l}=await o.read();if(l||(a&&(s+=r.decode(a,{stream:!0})),tt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:tt(s)}}async function fe(n){try{let e=await n.text();if(tt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=E(()=>{"use strict"});var Ae,Co=E(()=>{"use strict";V();Ae=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let i="";typeof s=="string"?i=s:s&&typeof s=="object"&&"text"in s&&(i=s.text),t.push({role:"system",content:i})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(i=>this.normalizeRequestContent(i,r.role)).filter(i=>i!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let t=e.headers.get("Content-Type")||"";if(t.includes("application/json")){let o=await pe(e);if(o?.isSSE&&o.body){let r=new Response(o.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(r)}if(o?.body)e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(o===null){let r=await fe(e);if(r.isSSE)return this.transformResponseOut(r.response);e=r.response}}if(t.includes("application/json")){let o=await F(e);if(o.object==="response"&&o.output){let r=this.convertResponseToChat(o);return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return o.type==="message"&&Array.isArray(o.content)?new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let[o,r]=e.body.tee(),s=o.getReader(),i="";try{let{value:f,done:_}=await s.read();!_&&f&&(i=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let c=this.prependToStream(i,r),u=new TextDecoder,d=new TextEncoder,p="",m=!1,h=this,g=new ReadableStream({async start(f){let _=c.getReader(),k=-1,y="",b=T=>(T!==y&&(k++,y=T),k);try{for(;;){let{done:T,value:C}=await _.read();if(T){m||f.enqueue(d.encode(`data: [DONE]
|
|
4
|
+
`);i=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?ws(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&&ws(e,t,s,i.trim()),s++),Ps(e,t,s)}catch(i){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,i),Ps(e,t,s)}finally{r.releaseLock()}})()}var ul,dl,Ae,_o,rt=w(()=>{"use strict";ul=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),dl=/token|secret|credential|passwd|password/i,Ae={maxBodyLength:4096,maxStreamChunks:100},_o=!1});function Ms(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,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?l.dispatcher=t.dispatcher:t.httpsProxy&&(l.dispatcher=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Jt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:fl(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function fl(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 Ls=w(()=>{q();rt()});function gl(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function $s(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function To(n){if($s(n))return"pending";let e=!1,t=!1;for(let o of n.split(`
|
|
5
|
+
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(ml.some(s=>r.includes(s))){e=!0;break}hl.some(s=>r.includes(s))&&(t=!0)}}return e||gl(n)?"content":t?"empty":"pending"}async function Ns(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],i="",a=0,l=Date.now()+t,c=(u,p)=>({verdict:u,chunks:s,bytes:a,rest:p});try{for(;;){let u=l-Date.now(),p=Symbol("timeout"),d,m=o.read(),g=u<=0?p:await Promise.race([m,new Promise(h=>{d=setTimeout(()=>h(p),u)})]);if(d&&clearTimeout(d),g===p)return c(To(i)==="content"?"content":"pending",Kt(o,m));if(g.done){i+=r.decode();let h=To(i);return c(h==="empty"?"empty":"pending",null)}if(!g.value)continue;s.push(g.value),a+=g.value.byteLength,i+=r.decode(g.value,{stream:!0});let f=To(i);if(f==="content")return c("content",Kt(o));if(f==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if($s(i)||a>=e)return c("pending",Kt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Kt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:i,value:a})=>{i?t.close():(t.enqueue(a),r())}).catch(i=>t.error(i))};r()},cancel(t){return n.cancel(t)}})}function Ds(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:i})=>{s?o.close():(o.enqueue(i),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var ml,hl,Fs=w(()=>{"use strict";ml=["content_block_start","content_block_delta","content_block_stop"];hl=["message_stop","response.completed","response.incomplete","[DONE]"]});function yl(n,e){return`${n.name}|${e?.name??""}`}function vo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function Oe(n,e,t){let o=vo(n),r=yl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function xo(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(Oe(n,e,o).terminalError=t,!0)}var Us=w(()=>{"use strict"});var So=w(()=>{"use strict"});import bl from"fastify";function js(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 st,_l,Ro,Gt=w(()=>{"use strict";So();st=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,i])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(i)]})),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:[]},i="staging",a,l=u=>{try{if(this.assertOpen(),i!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw a=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>l(()=>{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=>l(()=>{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=>l(()=>{s.routes.push(u)}),registerConfigProtector:u=>l(()=>{s.protectors.push(u)}),registerUiCard:u=>l(()=>{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=>l(()=>{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(i!=="staging")throw new Error("plugin activation is no longer open");if(a)throw a;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let f of this.plugins.values()){for(let h of s.runtimes.keys())if(f.runtimes.has(h))throw new Error(`managed runtime "${h}" is already registered`);for(let h of s.transformers.keys())if(f.transformers.has(h))throw new Error(`transformer "${h}" is already registered`)}let m=[...this.transformerServices].flatMap(f=>[...s.transformers].map(([h,b])=>{if(f.hasTransformer(h))throw new Error(`transformer "${h}" is already registered`);return{service:f,name:h,value:f.preparePluginTransformer(b)}})),g=[];try{for(let f of m)g.push(f),f.service.registerTransformer(f.name,f.value);s.card=u,this.plugins.set(e.name,s),this.revision++,i="committed"}catch(f){for(let h of g)h.service.removeTransformer(h.name);throw i="aborted",f}},get cardPath(){return s.cardPath},abort:()=>{i="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:(a,l)=>{if(l==="route")return u=>(r.push(u),s);if(o.has(String(l)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:l==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(l).toUpperCase(),url:u,handler:d??p}),s);let c=Reflect.get(a,l);return typeof c=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(l)}`)}:c}}),i=bl({logger:!1});try{for(let a of e){let l=a(s);l!==s&&await l}for(let a of this.plugins.values())for(let l of a.preparedRoutes)i.route(l);for(let a of r){let l=Array.isArray(a.method)?a.method:[a.method];for(let c of l)if(t.hasRoute({method:c,url:a.url,constraints:a.constraints}))throw new Error(`plugin route ${c} ${a.url} is already registered`);i.route(a)}return await i.ready(),r}finally{await i.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")}},_l=new st,Ro=()=>_l});async function Te(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let i=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",a=s?{...s,code:i,message:`Provider plugin request failed (${i}).`}:{code:i,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e===0||e>=500};try{await n.noteUpstreamError?.(a)}catch{}let l=js(n.name,a);return l.isRateLimit=a.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}var Hs=w(()=>{"use strict";Gt()});var Vt,wo=w(()=>{Vt="2.3.2416"});var zs={};mo(zs,{getFallbackPromotionStore:()=>Ie,resetFallbackPromotionStore:()=>vl});function Ie(n){return ve||(ve=new Po,n&&ve.configure(n)),ve}function vl(){ve&&(ve.clearAll(),ve=null)}var Tl,Po,ve,Qt=w(()=>{"use strict";re();Tl=600*1e3,Po=class{promotions=new Map;enabled=!0;ttlMs=Tl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,i){if(!this.enabled)return;let a=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(a,{promotedModel:l,timestamp:Date.now(),ttlMs:i??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),i=this.promotions.get(s);if(!i)return null;if(Date.now()-i.timestamp>=i.ttlMs)return this.promotions.delete(s),null;let[l,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(l,u))return this.promotions.delete(s),null;let d=r.find(g=>g.name.toLowerCase()===l.toLowerCase()),m=d?.models?.find(g=>String(g).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}},ve=null});import{existsSync as Ws,mkdirSync as xl,readFileSync as Sl,writeFileSync as Cl}from"fs";import{join as Ks}from"path";import{HOME_DIR as Rl}from"@wengine-ai/claude-code-router-shared";function Al(n){try{if(!Ws(Oo))return;let e=JSON.parse(Sl(Oo,"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 Js(n){try{let e=n.getAllStates();if(e.length===0)return;Ws(Ao)||xl(Ao,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Cl(Oo,JSON.stringify(t,null,2),"utf-8")}catch{}}function Io(){if(Bs)return;Bs=!0;let n=U();Al(n),El=setInterval(()=>Js(n),6e4),process.on("exit",()=>Js(n))}function U(n){return Eo||(Eo=new Yt(n)),Eo}var wl,Pl,Yt,Ao,Oo,Bs,El,Eo,re=w(()=>{"use strict";wl=120,Pl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Yt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Pl,...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}=(Qt(),tl(zs));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}recordProbeAttempt(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.lastProbeTime=Date.now())}markParkedUntil(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s&&(!Number.isFinite(o)||o<=Date.now()||s.rateLimitUntil&&s.rateLimitUntil>=o||(s.rateLimitUntil=o))}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??wl)*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)}},Ao=Ks(Rl,"runtime"),Oo=Ks(Ao,"provider-health.json"),Bs=!1,El=null;Eo=null});import{existsSync as Xs,mkdirSync as Ol,readFileSync as Il,writeFileSync as Ml}from"fs";import{join as Zs}from"path";import{HOME_DIR as Ll}from"@wengine-ai/claude-code-router-shared";function it(n,e,t){let o=a=>{if(t instanceof Headers)return t.get(a);let l=Object.keys(t).find(c=>c.toLowerCase()===a);return l?t[l]:null},r=Mo(o,$l),s=Mo(o,Nl),i=Mo(o,Dl);(r||s||i)&&Me.set(n,{provider:n,remaining:Qs(r),limit:Qs(s),reset:Ul(i),capturedAt:Date.now()})}function Fl(n){return Me.get(n)}function No(){return Array.from(Me.values())}function Mo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function Qs(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Ul(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=jl(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function jl(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 Hl(){try{if(!Xs($o))return;let n=JSON.parse(Il($o,"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;Me.set(t.provider,t)}}catch{}}function Ys(){try{if(Me.size===0)return;Xs(Lo)||Ol(Lo,{recursive:!0}),Ml($o,JSON.stringify(Array.from(Me.values()),null,2),"utf-8")}catch{}}function at(){Gs||(Gs=!0,Hl(),Vs=setInterval(Ys,6e4),Vs.unref?.(),process.on("exit",Ys))}var Lo,$o,Me,Gs,Vs,$l,Nl,Dl,Le=w(()=>{"use strict";Lo=Zs(Ll,"runtime"),$o=Zs(Lo,"rate-limit.json"),Me=new Map,Gs=!1,Vs=null,$l=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Nl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Dl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Zt(){return Do||(Do=new Uo),Do}function Ho(){return Fo||(Fo=new jo),Fo}function zl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function qs(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 ei(n,e){let t=Zt(),o=n?.[Xt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[Xt]=t.acquire(e)}function zo(n){let e=n?.[Xt];e&&Zt().release(e)}function ti(n,e){let t=qs(n),o=n?.[Xt],r=t?Ho().get(t)!==void 0:!1;!o&&!r||(t&&Ho().bind(t,e),ei(n,e))}function Bl(n,e,t){let o=Zt(),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 ni(n,e,t){let o=qs(n),r=Ho(),s=Zt(),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=Bl(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 ei(n,a),a}var Uo,jo,Do,Fo,Xt,qt=w(()=>{"use strict";Uo=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()}},jo=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()}},Do=null,Fo=null;Xt="__concurrencyLease"});async function F(n){let e=await n.text();return Jl(e,n.status)}function Jl(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 oi(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function ct(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function de(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})),ct(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:ct(s)}}async function me(n){try{let e=await n.text();if(ct(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=w(()=>{"use strict"});var $e,Bo=w(()=>{"use strict";V();$e=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("text/event-stream")&&!t.includes("application/json")&&e.body){let o=await de(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 de(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 me(e);if(r.isSSE)return this.transformResponseOut(r.response);e=r.response}}if(t.includes("application/json")){let o=await F(e);if(o.object==="response"&&o.output){let r=this.convertResponseToChat(o);return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return o.type==="message"&&Array.isArray(o.content)?new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let[o,r]=e.body.tee(),s=o.getReader(),i="";try{let{value:f,done:h}=await s.read();!h&&f&&(i=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start"))return new Response(r,{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"))return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers});let c=new TextDecoder,u=new TextEncoder,p="",d=!1,m=this,g=new ReadableStream({async start(f){let h=r.getReader(),b=-1,_="",y=k=>(k!==_&&(b++,_=k),b);try{for(;;){let{done:k,value:v}=await h.read();if(k){d||f.enqueue(u.encode(`data: [DONE]
|
|
5
6
|
|
|
6
|
-
`));break}let
|
|
7
|
+
`));break}let S=c.decode(v,{stream:!0});p+=S;let T=p.split(/\r?\n/);p=T.pop()||"";for(let R of T)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]
|
|
7
8
|
|
|
8
|
-
`));continue}try{let
|
|
9
|
+
`));continue}try{let x=JSON.parse(C);if(x.type==="response.output_text.delta"){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:{content:x.delta||""},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(E)}
|
|
9
10
|
|
|
10
|
-
`))}else if(
|
|
11
|
+
`))}else if(x.type==="response.output_item.added"&&x.item?.type==="function_call"){let E={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(E)}
|
|
11
12
|
|
|
12
|
-
`))}else if(
|
|
13
|
+
`))}else if(x.type==="response.output_item.added"&&x.item?.type==="message"){let E=[];(x.item.content||[]).forEach(P=>{P.type==="output_text"&&E.push({type:"text",text:P.text||""})});let A={role:"assistant"};if(E.length===1&&E[0].type==="text"?A.content=E[0].text:E.length>0&&(A.content=E),A.content){let P={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(P)}
|
|
13
14
|
|
|
14
|
-
`))}}else if(
|
|
15
|
+
`))}}else if(x.type==="response.output_text.annotation.added"){let E={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(E)}
|
|
15
16
|
|
|
16
|
-
`))}else if(
|
|
17
|
+
`))}else if(x.type==="response.function_call_arguments.delta"){let E={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(E)}
|
|
17
18
|
|
|
18
|
-
`))}else if(
|
|
19
|
+
`))}else if(x.type==="response.completed"){let E=x.response?.output?.some(P=>P.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:E}]};f.enqueue(u.encode(`data: ${JSON.stringify(A)}
|
|
19
20
|
|
|
20
|
-
`)),
|
|
21
|
+
`)),d=!0}else if(x.type==="response.reasoning_summary_text.delta"){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:{thinking:{content:x.delta||""}},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(E)}
|
|
21
22
|
|
|
22
|
-
`))}else if(
|
|
23
|
+
`))}else if(x.type==="response.reasoning_summary_part.done"&&x.part){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:b,delta:{thinking:{signature:x.item_id}},finish_reason:null}]};f.enqueue(u.encode(`data: ${JSON.stringify(E)}
|
|
23
24
|
|
|
24
|
-
`))}}catch{f.enqueue(
|
|
25
|
-
`))}}else f.enqueue(
|
|
26
|
-
`))}catch(
|
|
27
|
-
`))}}p.trim()&&f.enqueue(
|
|
28
|
-
`)),
|
|
25
|
+
`))}}catch{f.enqueue(u.encode(R+`
|
|
26
|
+
`))}}else f.enqueue(u.encode(R+`
|
|
27
|
+
`))}catch(C){console.error("Error processing line:",R,C),f.enqueue(u.encode(R+`
|
|
28
|
+
`))}}p.trim()&&f.enqueue(u.encode(p+`
|
|
29
|
+
`)),d||f.enqueue(u.encode(`data: [DONE]
|
|
29
30
|
|
|
30
|
-
`))}catch(
|
|
31
|
-
data: ${JSON.stringify(
|
|
31
|
+
`))}catch(k){console.error("Stream error:",k),f.error(k)}finally{try{h.releaseLock()}catch(k){console.error("Error releasing reader lock:",k)}f.close()}}});return new Response(g,{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(),i=r.getReader(),a="";try{let{value:d,done:m}=await i.read();!m&&d&&(a=new TextDecoder().decode(d))}finally{i.releaseLock()}r.cancel().catch(()=>{});let l=a.includes("message_start")||a.includes("content_block_start"),c=a.includes("chat.completion.chunk");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(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(c&&!l){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 F(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",i=`resp_${Date.now()}`,a=0,l=!1,c=!1,u="",p=-1,d=[],m=(f,h)=>r.encode(`event: ${f}
|
|
32
|
+
data: ${JSON.stringify(h)}
|
|
32
33
|
|
|
33
|
-
`),
|
|
34
|
-
`);
|
|
34
|
+
`),g=(f,h=[])=>({id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:f,model:s,output:h,usage:this.buildResponsesUsage()});return new ReadableStream({async start(f){try{let h=e.getReader(),b="",_=!1,y=k=>{if(!_){_=!0;for(let v of d)if(v.type==="function_call"){let S=d.indexOf(v);f.enqueue(m("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:v.call_id||v.id,output_index:S,arguments:v.arguments||""})),v.status="completed",f.enqueue(m("response.output_item.done",{type:"response.output_item.done",output_index:S,item:v}))}for(let v of d)if(v.type==="message"){let S=d.indexOf(v);v.status="completed",f.enqueue(m("response.output_item.done",{type:"response.output_item.done",output_index:S,item:v}))}f.enqueue(m("response.completed",{type:"response.completed",response:{id:i,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:v}=await h.read();if(k)break;b+=o.decode(v,{stream:!0});let S=b.split(`
|
|
35
|
+
`);b=S.pop()||"";for(let T of S){let R=T.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]
|
|
35
36
|
|
|
36
|
-
`));continue}let
|
|
37
|
-
data: ${JSON.stringify(
|
|
37
|
+
`));continue}let x;try{x=JSON.parse(C)}catch{continue}l||(l=!0,f.enqueue(m("response.created",{type:"response.created",response:g("in_progress")})),f.enqueue(m("response.in_progress",{type:"response.in_progress",response:g("in_progress")})));let E=x.choices?.[0];if(!E)continue;let A=E.delta;if(A?.content){if(!c){c=!0;let P=a++,M={id:`${i}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(M),f.enqueue(m("response.output_item.added",{type:"response.output_item.added",output_index:P,item:M}))}f.enqueue(m("response.output_text.delta",{type:"response.output_text.delta",item_id:`${i}_msg`,output_index:a-1,content_index:0,delta:A.content}))}if(Array.isArray(A?.tool_calls))for(let P of A.tool_calls){if(P.id){u=P.id,p=a++;let M={id:P.id,type:"function_call",status:"in_progress",call_id:P.id,name:P.function?.name||"",arguments:""};d.push(M),f.enqueue(m("response.output_item.added",{type:"response.output_item.added",output_index:p,item:M}))}if(P.function?.arguments){f.enqueue(m("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:P.function.arguments}));let M=d.find(L=>L.call_id===u);M&&(M.arguments+=P.function.arguments)}}E.finish_reason&&y(x)}}_||y({}),f.close()}catch(h){f.error(h)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",i=`resp_${Date.now()}`,a="",l="",c=-1,u="",p="",d="",m=-1,g="",f="",h=-1,b=0,_=!1,y=!1,k=!1,v=!1,S=null,T=[],R=(M,L)=>r.encode(`event: ${M}
|
|
38
|
+
data: ${JSON.stringify(L)}
|
|
38
39
|
|
|
39
|
-
`),
|
|
40
|
-
`);
|
|
40
|
+
`),C=(M,L=[])=>({id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:M,model:s,output:L,usage:this.buildResponsesUsage()}),x=()=>{_||(_=!0,P.enqueue(R("response.created",{type:"response.created",response:C("in_progress")})),P.enqueue(R("response.in_progress",{type:"response.in_progress",response:C("in_progress")})))},E=(M,L)=>{P.enqueue(R("response.output_item.done",{type:"response.output_item.done",output_index:M,item:{...L,status:"completed"}}))},A=M=>{if(!v){if(v=!0,y){let L=T.find(N=>N.type==="message");L&&(L.content=[{type:"output_text",text:a}],L.status="completed")}for(let L of T)L.type==="function_call"&&(L.status="completed");return R("response.completed",{type:"response.completed",response:{id:i,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:T,usage:M?{...this.buildResponsesUsage(M)}:this.buildResponsesUsage()}})}},P;return new ReadableStream({async start(M){P=M;try{let L=e.getReader(),N="";for(;;){let{done:$,value:D}=await L.read();if($)break;N+=o.decode(D,{stream:!0});let H=N.split(`
|
|
41
|
+
`);N=H.pop()||"";for(let fe of H){let j=fe.trim();if(!j||j.startsWith("event:")||!j.startsWith("data:"))continue;let Z=j.slice(5).trim();if(Z==="[DONE]")continue;let J;try{J=JSON.parse(Z)}catch{continue}if(J.type==="message_start"&&(i=J.message?.id||i,x()),J.type==="content_block_start"){let O=J.content_block;if(S=O?.type||null,O?.type==="tool_use"){u=O.id||"",p=O.name||"",d="",m=b++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};T.push(W),P.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if(O?.type==="thinking"&&(g=O.thinking||"",!k)){k=!0,h=b++,f=`rs_${i}`;let W={id:f,type:"reasoning",status:"in_progress",summary:[]};T.push(W),P.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:h,item:W}))}if(O?.type==="text"&&(a=O?.text||"",!y)){y=!0,c=b++,l=`${i}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(W),P.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}}if(J.type==="content_block_delta"){let O=J.delta;if(O?.type==="text_delta"){if(!y){y=!0,c=b++,l=`${i}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(W),P.enqueue(R("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}a+=O.text||"",P.enqueue(R("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:O.text||""}))}O?.type==="thinking_delta"&&(g+=O.thinking||"",P.enqueue(R("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:f||`rs_${i}`,output_index:h>=0?h:0,summary_index:0,delta:O.thinking||""}))),O?.type==="input_json_delta"&&(d+=O.partial_json||"",P.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:O.partial_json||""})))}if(J.type==="content_block_stop"){if(S==="tool_use"&&u){P.enqueue(R("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:m,arguments:d}));let O=T.find(W=>W.call_id===u);O&&(O.arguments=d,O.status="completed"),O&&E(m,O)}if(S==="text"&&y){P.enqueue(R("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:c,content_index:0,text:a}));let O=T.find(W=>W.type==="message");O&&(O.content=[{type:"output_text",text:a}],E(c,O))}if(S==="thinking"&&k){let O=T.find(W=>W.type==="reasoning");O&&(O.summary=[{type:"summary_text",text:g}],E(h,O))}S=null}if(J.type==="message_delta"){let O=A(J.usage);O&&P.enqueue(O)}if(J.type==="message_stop"){let O=A();O&&P.enqueue(O),P.enqueue(r.encode(`data: [DONE]
|
|
41
42
|
|
|
42
|
-
`))}}}w();let H=O();H&&P.enqueue(H),L="",P.close()}catch($){P.error($)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(c=>c.type==="message"),o=e.output?.find(c=>c.type==="function_call"),r;t?.content?.length&&t?.content[0].annotations&&(r=t.content[0].annotations.map(c=>({type:"url_citation",url_citation:{url:c.url||"",title:c.title||"",content:"",start_index:c.start_index||0,end_index:c.end_index||0}}))),this.logger.debug({data:r,type:"url_citation"});let s=null,i=null,a=null;if(t&&t.reasoning&&(a={content:t.reasoning}),t&&t.content){let c=[],u=[];if(t.content.forEach(d=>{if(d.type==="output_text")c.push(d.text||"");else if(d.type==="output_image"){let p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&u.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&u.push(p)}}),u.length>0){let d=[];c.length>0&&d.push({type:"text",text:c.join("")}),d.push(...u),s=d}else s=c.join("")}return o&&(i=[{id:o.call_id||o.id,function:{name:o.name,arguments:o.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:a,annotations:r},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var So,X,Ft=E(()=>{"use strict";So=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},X=new So(100)});import{existsSync as Cs,mkdirSync as zc,readFileSync as Bc,writeFileSync as Jc}from"fs";import{join as Ss}from"path";import{HOME_DIR as Wc}from"@wengine-ai/claude-code-router-shared";function Eo(n,e){n&&Ie.set(n,{...e,provider:n,capturedAt:Date.now()})}function Ut(n){let e=Ie.get(n);return e?{...e}:void 0}function Po(){return Array.from(Ie.values()).map(n=>({...n}))}function Kc(){try{if(!Cs(wo))return;let n=JSON.parse(Bc(wo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;Ie.set(t.provider,t)}}catch{}}function xs(){try{if(Ie.size===0)return;Cs(Ro)||zc(Ro,{recursive:!0}),Jc(wo,JSON.stringify(Array.from(Ie.values()),null,2),"utf-8")}catch{}}function nt(){Ts||(Ts=!0,Kc(),vs=setInterval(xs,6e4),vs.unref?.(),process.on("exit",xs))}var Ro,wo,Ie,Ts,vs,Me=E(()=>{"use strict";Ro=Ss(Wc,"runtime"),wo=Ss(Ro,"quota-store.json"),Ie=new Map,Ts=!1,vs=null});function me(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Gc.test(e)))return e}function ge(n){if(!n)return;if(typeof n=="object")return me(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=me(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return me(e.slice(o+t.length))}var Gc,Ne=E(()=>{"use strict";Gc=/^[A-Za-z0-9_-]+$/});import{existsSync as Es}from"fs";import{readFile as Vc,readdir as Qc}from"fs/promises";import{homedir as Yc}from"os";import{isAbsolute as Xc,join as ot,normalize as Zc}from"path";import{openSqliteDatabase as qc}from"@wengine-ai/claude-code-router-shared";function al(){if($e.size<=Rs)return;let n=[...$e.keys()].slice(0,$e.size-Rs);for(let e of n)$e.delete(e)}function cl(){if(Le.size<=ws)return;let n=[...Le].slice(0,Le.size-ws);for(let e of n)Le.delete(e)}function ll(n){let e=n.trim();if(!e||e==="."||e===".."||/[/\\\0]/.test(e))return[];let t=e.replace(/^sess_/,"");return[...new Set([e,t,`sess_${t}`])].filter(Boolean)}function ul(n,e){let t;try{t=qc(n,{readonly:!0}).db;let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let i=o.get(r,r)?.workspace_path;if(typeof i=="string"&&i.trim())return i.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function dl(n,e){let t;try{t=await Qc(n)}catch{return null}for(let o of t)for(let r of e){let s=ot(n,o,`${r}.json`);if(Es(s))try{let i=JSON.parse(await Vc(s,"utf8")),a=i?.meta?.workspacePath??i?.workspacePath;if(typeof a=="string"&&a.trim())return a.trim()}catch{}}return null}async function Ps(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=$e.get(e);if(t)return t;let o=async()=>{let r=ll(e);if(r.length===0)return null;let s=ot(el(),tl),i=ot(s,nl);if(Es(i)){let a=ul(i,r);if(a)return a}return dl(ot(s,ol),r)};try{let r=await o();if(!r&&!Le.has(e)){Le.add(e),cl();for(let i=0;i<rl&&!r;i++)await il(sl),r=await o()}if(!r||!Xc(r))return null;let s=Zc(r);return $e.set(e,s),al(),s}catch{return null}}var el,tl,nl,ol,Rs,ws,rl,sl,$e,Le,il,Os=E(()=>{"use strict";el=()=>process.env.CCR_ZCODE_DIR||ot(Yc(),".zcode"),tl="v2",nl="tasks-index.sqlite",ol="sessions",Rs=500,ws=500,rl=3,sl=50,$e=new Map,Le=new Set,il=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as pl}from"node:crypto";import{CCR_PROJECT_HEADER as Oo}from"@wengine-ai/claude-code-router-shared";function Ms(n){return typeof n=="string"&&n.length<=fl}function ml(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Is){let{value:t}=jt(n,e);if(!Ms(t))continue;let o=me(t);if(o)return o}}function hl(n){if(typeof n=="string")return n.slice(0,1e3);if(Array.isArray(n)){let e=n.find(t=>t&&typeof t.text=="string");return e?String(e.text).slice(0,1e3):""}return""}function yl(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function jt(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function As(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function rt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Ao(n,e,t=!0){let o=ge(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function $s(n){return typeof n=="string"&&gl.includes(n)}function Rl(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function De(n){if($s(n?.clientType))return n.clientType;let e=yl(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=hl(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(jt(n,Oo).present||jt(n,"x-session-affinity").present)return"pi";if(Rl(t,o))return"zcode";let i=t["x-anthropic-billing-header"];if(typeof i=="string"&&i.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let a=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(a)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(a).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Ls(n){return Ns[n]}function wl(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||pl();return n.__ccrRequestScopeId=e,e}function xe(n,e={}){let t=De(n),o=Ls(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:wl(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,As(n,Oo),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let i of Is)As(n,i);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function El(){}var Is,fl,gl,_l,kl,bl,Tl,vl,xl,Cl,Sl,Ns,Fe=E(()=>{"use strict";Ne();Is=["x-session-affinity","x-session-id","x-litellm-session-id"],fl=256;gl=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];_l={type:"claude-code",createContext(n){return Ao(n,"claude-code")}},kl={type:"zcode",createContext(n){return Ao(n,"zcode")}},bl={type:"pi",createContext(n){let e=jt(n,Oo),t=ml(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||ge(n?.body?.metadata?.user_id),o=Ms(t)?t:void 0;return{...rt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Tl={type:"qwen-code",createContext(n){return Ao(n,"qwen-code")}},vl={type:"opencode",createContext(){return rt("opencode")}},xl={type:"codex",createContext(){return rt("codex")}},Cl={type:"api",createContext(){return rt("api")}},Sl={type:"unknown",createContext(){return rt("unknown")}},Ns={"claude-code":_l,zcode:kl,pi:bl,"qwen-code":Tl,opencode:vl,codex:xl,api:Cl,unknown:Sl}});import{get_encoding as Ol}from"tiktoken";import{readFile as Io}from"fs/promises";import{opendir as Al,stat as Il}from"fs/promises";import{join as Mo}from"path";import{CLAUDE_PROJECTS_DIR as Ds,HOME_DIR as Fs,getClaudeProjectId as Us,isZcodeProjectTakeoverActive as Ml}from"@wengine-ai/claude-code-router-shared";function Z(n,e,t,o){let r=Js(e,t);if(r.code==="model_unhealthy"){let a=K(e,t,!0);if(a)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),a}let s=n.sessionId||n.clientContext?.stableSessionId,i=Bs[r.code]||502;throw new q(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:i})}function zt(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function it(n){let e=zt(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function $l(n,e){if(!e||!n)return null;let t=zt(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=it(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let i=zt(r);if(i&&t.includes(i))return s}return null}function Ll(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function Ht(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function st(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Js(n,e){let t=Ht(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(c=>c.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let i=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!i)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!U().isAvailable(s.name,String(i)))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let l=Ut(s.name);if(l){let c=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,u=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(c||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function K(n,e,t,o,r,s,i){let a=Ht(n);if(!a)return i?null:n;let{providerName:l,routeModel:c}=a,u=st(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let p=Ee(),m=p.getPromotion(l,c,o,e);if(m){let h=Ht(m);if(h){let g=st(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let p=Ee(),m=p.getPromotion(l,c,o,e);if(m){let h=Ht(m);if(h){let g=st(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(l,c,o)}}if(!t&&!U().isAvailable(u.provider.name,u.model))return null;let d=Ut(u.provider.name);if(d){let p=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,m=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(p||m)return null}return`${u.provider.name},${u.model}`}function Q(n,e,t,o,r,s){let i=U(),a=[t?.[n],o?.[n]];for(let l of a)if(!(!Array.isArray(l)||l.length===0))for(let c of l){let u=K(c,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Dl(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function No(n){let e=zt(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function Ws(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Ll(e))}function Ks(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Fl(n,e,t,o,r,s,i,a,l,c,u,d){let p=n.clientContext,m=p?.longContextThreshold??t.longContextThreshold??l??6e4,h=Ws(e,r,p),g=n.modelFamily,f=Ks(p,t,c),_=p?.supportsExplicitExtendedContext!==!1&&s===!0;if((_||h>f)&&t.extendedContext){let b=K(t.extendedContext,o,!1,"extendedContext",a,d,u);if(b)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:b,scenarioType:"extendedContext",isFallback:!1};let T=a?Q("extendedContext",o,t.fallback,i,g,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${_}, threshold: ${f}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let C=Z(n,t.extendedContext,o,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(h>m&&(t.longContext||t.fallback?.longContext?.length||i?.longContext?.length)){let b=t.longContext?K(t.longContext,o,!1,"longContext",a,d,u):null;if(b)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:b,scenarioType:"longContext",isFallback:!1};let T=a?Q("longContext",o,t.fallback,i,g,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let C=Z(n,t.longContext,o,"longContext");if(C)return{model:C,scenarioType:"longContext",isFallback:!1}}n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(b=>b.type?.startsWith("web_search"))&&t.webSearch){let b=K(t.webSearch,o,!1,"webSearch",a,d,u);if(b)return{model:b,scenarioType:"webSearch",isFallback:!1};let T=a?Q("webSearch",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let C=Z(n,t.webSearch,o,"webSearch");if(C)return{model:C,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let b=K(t.think,o,!1,"think",a,d,u);if(b)return{model:b,scenarioType:"think",isFallback:!1};let T=a?Q("think",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let C=Z(n,t.think,o,"think");if(C)return{model:C,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let b=K(t.default,o,!1,"default",a,d,u);if(b)return{model:b,scenarioType:"default",isFallback:!1};let T=a?Q("default",o,t.fallback,i,g,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let C=Z(n,t.default,o,"default");if(C)return{model:C,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function Bl(){if(Ce.size<=js)return;let n=[...Ce.keys()].slice(0,Ce.size-js);for(let e of n)Ce.delete(e)}function Jl(){if(Ue.size<=Hs)return;let n=[...Ue].slice(0,Ue.size-Hs);for(let e of n)Ue.delete(e)}var Bs,q,le,Bt,Nl,Ul,Jt,Ce,js,Ue,Hs,jl,Hl,zl,zs,Gs,je=E(()=>{"use strict";Ft();re();Me();Mt();Dt();Ne();Os();Fe();Bs={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500,invalid_project_id:400,project_config_not_found:404},q=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Bs[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Ol("cl100k_base"),Bt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{s.type==="text"?o+=le.encode(s.text).length:s.type==="tool_use"?o+=le.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(o+=le.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},Nl=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new q(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Gs(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Ps(n.sessionId);s&&Ml(s)&&(r=Us(s))}if(r){n.projectId=r;let s=Mo(Fs,r,"config.json");if(!t&&n.sessionId){let i=Mo(Fs,r,`${n.sessionId}.json`);try{let a=JSON.parse(await Io(i,"utf8"));if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch{}}try{let i=JSON.parse(await Io(s,"utf8"));if(t&&(typeof i?.projectPath!="string"||Us(i.projectPath)!==o))throw new q(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){if(i instanceof q)throw i;if(t&&i?.code==="ENOENT")throw new q(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!i||i.code!=="ENOENT"){let a=n.sessionId||n.clientContext?.stableSessionId;throw new q(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${i.message}. Session: "${a||"unknown"}".`,{sessionId:a,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};Ul=async(n,e,t,o,r,s)=>{let i=t.get("providers")||[],a=r||t.get("Router"),l=a?.enableFallback===!0,c=l?a?.fallback:void 0,u=l&&!s?c||t.get("fallback"):c,d=!s,p=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let v=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);v&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${v[1]}</CCR-SUBAGENT-MODEL>`,""),p=v[1])}let{family:m,extended:h,isCcrAlias:g}=it(n.body.model),f=a?.families?.[m||""];if(f&&a?.enableFamilyRouting){n.log.info(`Using model family routing for: ${m}${h?" (1M)":""}`),n.modelFamily=m,n.familyFallback=f.fallback;let v=Fl(n,e,f,i,o,h,u,l,a?.longContextThreshold,a?.extendedContextThreshold,s,d);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=K(n.body.model,i,!1,"default",l,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let S=l?Q("default",i,void 0,u,void 0,s):null;if(S)return n.log.info(`Using fallback for explicit model: ${S}`),{model:S,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let _=g&&!a?.enableFamilyRouting?null:$l(n.body.model,a?.models);if(_){let v=K(_,i,!1,"modelMapping",l,d,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${_}`),{model:v,scenarioType:"modelMapping"};let S=l?Q("modelMapping",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};if(s){let x=Z(n,_,i,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${_} unavailable (fail pool), skipping`)}let k=n.clientContext,y=Ws(e,o,k),b=Ks(k,void 0,a?.extendedContextThreshold);if(y>b&&a?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${y}, estimated: ${e}, threshold: ${b}`);let v=K(a.extendedContext,i,!1,"extendedContext",l,d,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let S=l?Q("extendedContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};if(s){let x=Z(n,a.extendedContext,i,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext"}}}let T=k?.longContextThreshold??a?.longContextThreshold??6e4;if(y>T&&a?.longContext){n.log.info(`Using long context model due to token count: ${y}, estimated: ${e}, threshold: ${T}`);let v=K(a.longContext,i,!1,"longContext",l,d,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let S=l?Q("longContext",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};if(s){let x=Z(n,a.longContext,i,"longContext");if(x)return{model:x,scenarioType:"longContext"}}}if(!s&&p)return n.subagentOverrideModel=p,{model:p,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&a?.background){n.log.info(`Using background model for ${n.body.model}`);let v=K(a.background,i,!1,"background",l,d,s);if(v)return{model:v,scenarioType:"background"};let S=l?Q("background",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};if(s){let x=Z(n,a.background,i,"background");if(x)return{model:x,scenarioType:"background"}}n.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&a?.webSearch){let v=K(a.webSearch,i,!1,"webSearch",l,d,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let S=l?Q("webSearch",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};if(s){let x=Z(n,a.webSearch,i,"webSearch");if(x)return{model:x,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&a?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=K(a.think,i,!1,"think",l,d,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let S=l?Q("think",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};if(s){let x=Z(n,a.think,i,"think");if(x)return{model:x,scenarioType:"think"}}}if(a?.default){let v=K(a.default,i,!1,"default",l,d,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let S=l?Q("default",i,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};let x=K(a.default,i,!0,"default",l,d,s);if(x)return n.log.warn(`No fallback available; retrying default model ${a.default} despite fail-pool state (strict=${s})`),{model:x,scenarioType:"default"}}if(s){let v=Z(n,a?.default||n.body.model,i,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Jt=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,o.getAll());let s=await Nl(n,o),i=s||o.get("Router"),a=i?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=a,n.strictProjectRouting=c,n.fallbackConfig=c?i?.fallback:i?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??X.get(n.usageCacheKey):void 0,{messages:d,system:p=[],tools:m}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&p.length>1&&p[1]?.text?.includes("<env>")){let g=await Io(h,"utf-8");p[1].text=`${g}<env>${p[1].text.split("<env>").pop()}`}try{let[g,f]=n.body.model.split(","),_=t.tokenizerService?.getTokenizerConfigForModel(g,f),k;t.tokenizerService?k=(await t.tokenizerService.countTokens({messages:d,system:p,tools:m},_,g)).tokenCount:k=Bt(d,p,m),n.tokenCount=k;let y,b=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(b)try{y=await Xe(b)(n,o.getAll(),{event:r})}catch(S){n.log.error(`failed to load custom router: ${S.message}`)}if(y)n.scenarioType="default";else{let S=await Ul(n,k,o,u,s,!!s);y=S.model,n.scenarioType=S.scenarioType}let{family:T}=it(n.originalModel||n.body.model),C=i?.enableFamilyRouting&&T?i.families?.[T]:void 0,v=[C?.image,i?.image].filter((S,x,w)=>!!S&&w.indexOf(S)===x);if(v.length>0&&Dl(n)&&!No(y))if(v.includes(y))n.scenarioType="image";else{let S=v.map(x=>K(x,l,!1,"image",a,!c,c)).find(x=>!!x);if(S)n.log.info(`Using image model fallback for ${y}`),y=S,n.scenarioType="image";else{let x=a?Q("image",l,C?.fallback,n.fallbackConfig,T||void 0,c):null;if(x)n.log.info(`Using image fallback model: ${x}`),y=x,n.scenarioType="image";else if(c){let w=Z(n,v[0],l,"image");w&&(y=w,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${y}`),n.scenarioType="image"}}if(i?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof y=="string"&&y.trim()){let S=n.scenarioType||"default",x=[...(n.familyFallback||{})[S]||[],...(n.fallbackConfig||{})[S]||[]];y=ks(n,y,{threshold:Number(i?.concurrencyThreshold)||3,fallbackModels:x,resolve:w=>K(w,l,!1,S,a,!c,c),log:w=>n.log.info(w)})}typeof y=="string"&&y.trim()?n.body.model=y:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(g){if(g instanceof q)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),c){let f=n.sessionId||n.clientContext?.stableSessionId;throw new q(`Project routing error: router failure in project mode. ${g.message}. Session: "${f||"unknown"}".`,{sessionId:f,configuredTarget:i?.default,code:"project_router_failure",statusCode:502})}n.body.model=i?.default,n.scenarioType="default"}},Ce=new Map,js=1e3,Ue=new Set,Hs=1e3,jl=3,Hl=50,zl=n=>new Promise(e=>setTimeout(e,n));zs=async n=>{let e=await Al(Ds),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let i=Mo(Ds,s,`${n}.jsonl`);try{return(await Il(i)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Gs=async n=>{let e=me(n);if(!e)return null;if(Ce.has(e))return Ce.get(e)||null;try{let t=await zs(e);if(!t&&!Ue.has(e)){Ue.add(e),Jl();for(let o=0;o<jl&&!t;o++)await zl(Hl),t=await zs(e)}return t?(Ce.set(e,t),Bl(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function at(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
43
|
+
`))}}}x();let B=A();B&&P.enqueue(B),N="",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(p=>{if(p.type==="output_text")c.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=[];c.length>0&&p.push({type:"text",text:c.join("")}),p.push(...u),s=p}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 Jo,Q,en=w(()=>{"use strict";Jo=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},Q=new Jo(100)});import{existsSync as ai,mkdirSync as Wl,readFileSync as Kl,writeFileSync as Gl}from"fs";import{join as ci}from"path";import{HOME_DIR as Vl}from"@wengine-ai/claude-code-router-shared";function Go(n,e){n&&Ne.set(n,{...e,provider:n,capturedAt:Date.now()})}function tn(n){let e=Ne.get(n);return e?{...e}:void 0}function Vo(){return Array.from(Ne.values()).map(n=>({...n}))}function Ql(){try{if(!ai(Ko))return;let n=JSON.parse(Kl(Ko,"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;Ne.set(t.provider,t)}}catch{}}function ii(){try{if(Ne.size===0)return;ai(Wo)||Wl(Wo,{recursive:!0}),Gl(Ko,JSON.stringify(Array.from(Ne.values()),null,2),"utf-8")}catch{}}function lt(){ri||(ri=!0,Ql(),si=setInterval(ii,6e4),si.unref?.(),process.on("exit",ii))}var Wo,Ko,Ne,ri,si,De=w(()=>{"use strict";Wo=ci(Vl,"runtime"),Ko=ci(Wo,"quota-store.json"),Ne=new Map,ri=!1,si=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Yl.test(e)))return e}function he(n){if(!n)return;if(typeof n=="object")return ge(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=ge(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return ge(e.slice(o+t.length))}var Yl,Fe=w(()=>{"use strict";Yl=/^[A-Za-z0-9_-]+$/});import{existsSync as di}from"fs";import{readFile as Xl,readdir as Zl}from"fs/promises";import{homedir as ql}from"os";import{isAbsolute as eu,join as ut,normalize as tu}from"path";import{openSqliteDatabase as nu}from"@wengine-ai/claude-code-router-shared";function uu(){if(Ue.size<=li)return;let n=[...Ue.keys()].slice(0,Ue.size-li);for(let e of n)Ue.delete(e)}function du(){if(je.size<=ui)return;let n=[...je].slice(0,je.size-ui);for(let e of n)je.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=nu(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 mu(n,e){let t;try{t=await Zl(n)}catch{return null}for(let o of t)for(let r of e){let s=ut(n,o,`${r}.json`);if(di(s))try{let i=JSON.parse(await Xl(s,"utf8")),a=i?.meta?.workspacePath??i?.workspacePath;if(typeof a=="string"&&a.trim())return a.trim()}catch{}}return null}async function pi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=Ue.get(e);if(t)return t;let o=async()=>{let r=pu(e);if(r.length===0)return null;let s=ut(ou(),ru),i=ut(s,su);if(di(i)){let a=fu(i,r);if(a)return a}return mu(ut(s,iu),r)};try{let r=await o();if(!r&&!je.has(e)){je.add(e),du();for(let i=0;i<au&&!r;i++)await lu(cu),r=await o()}if(!r||!eu(r))return null;let s=tu(r);return Ue.set(e,s),uu(),s}catch{return null}}var ou,ru,su,iu,li,ui,au,cu,Ue,je,lu,fi=w(()=>{"use strict";ou=()=>process.env.CCR_ZCODE_DIR||ut(ql(),".zcode"),ru="v2",su="tasks-index.sqlite",iu="sessions",li=500,ui=500,au=3,cu=50,Ue=new Map,je=new Set,lu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as gu}from"node:crypto";import{CCR_PROJECT_HEADER as Qo}from"@wengine-ai/claude-code-router-shared";function hi(n){return typeof n=="string"&&n.length<=hu}function yu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of gi){let{value:t}=nn(n,e);if(!hi(t))continue;let o=ge(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 ku(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 nn(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 mi(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 dt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Yo(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function bi(n){return typeof n=="string"&&bu.includes(n)}function Eu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function He(n){if(bi(n?.clientType))return n.clientType;let e=ku(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(nn(n,Qo).present||nn(n,"x-session-affinity").present)return"pi";if(Eu(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 _i(n){return yi[n]}function Au(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||gu();return n.__ccrRequestScopeId=e,e}function xe(n,e={}){let t=He(n),o=_i(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Au(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,mi(n,Qo),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let i of gi)mi(n,i);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Ou(){}var gi,hu,bu,Tu,vu,xu,Su,Cu,Ru,wu,Pu,yi,ze=w(()=>{"use strict";Fe();gi=["x-session-affinity","x-session-id","x-litellm-session-id"],hu=256;bu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Tu={type:"claude-code",createContext(n){return Yo(n,"claude-code")}},vu={type:"zcode",createContext(n){return Yo(n,"zcode")}},xu={type:"pi",createContext(n){let e=nn(n,Qo),t=yu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=hi(t)?t:void 0;return{...dt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Su={type:"qwen-code",createContext(n){return Yo(n,"qwen-code")}},Cu={type:"opencode",createContext(){return dt("opencode")}},Ru={type:"codex",createContext(){return dt("codex")}},wu={type:"api",createContext(){return dt("api")}},Pu={type:"unknown",createContext(){return dt("unknown")}},yi={"claude-code":Tu,zcode:vu,pi:xu,"qwen-code":Su,opencode:Cu,codex:Ru,api:wu,unknown:Pu}});import{get_encoding as Mu}from"tiktoken";import{readFile as Xo}from"fs/promises";import{opendir as Lu,stat as $u}from"fs/promises";import{join as Zo}from"path";import{CLAUDE_PROJECTS_DIR as ki,HOME_DIR as Ti,getClaudeProjectId as vi,isZcodeProjectTakeoverActive as Nu}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=wi(e,t);if(r.code==="model_unhealthy"){let a=G(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=Ri[r.code]||502;throw new te(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:i})}function rn(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=rn(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 Fu(n,e){if(!e||!n)return null;let t=rn(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 i=rn(r);if(i&&t.includes(i))return s}return null}function Uu(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function on(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 pt(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 wi(n,e){let t=on(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(c=>c.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let i=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!i)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!U().isAvailable(s.name,String(i),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 l=tn(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 G(n,e,t,o,r,s,i){let a=on(n);if(!a)return i?null:n;let{providerName:l,routeModel:c}=a,u=pt(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Ie(),m=d.getPromotion(l,c,o,e);if(m){let g=on(m);if(g){let f=pt(e,g.providerName,g.routeModel);if(f)return`${f.provider.name},${f.model}`}d.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Ie(),m=d.getPromotion(l,c,o,e);if(m){let g=on(m);if(g){let f=pt(e,g.providerName,g.routeModel);if(f)return`${f.provider.name},${f.model}`}d.clear(l,c,o)}}if(!t&&!U().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=tn(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 X(n,e,t,o,r,s){let i=U(),a=[t?.[n],o?.[n]];for(let l of a)if(!(!Array.isArray(l)||l.length===0))for(let c of l){let u=G(c,e,!1,n,void 0,void 0,s);if(u)return u}return null}function ju(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 mt(n){let e=rn(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 Pi(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Uu(e))}function Ei(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Hu(n,e,t,o,r,s,i,a,l,c,u,p){let d=n.clientContext,m=d?.longContextThreshold??t.longContextThreshold??l??6e4,g=Pi(e,r,d),f=n.modelFamily,h=Ei(d,t,c),b=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((b||g>h)&&t.extendedContext){let k=G(t.extendedContext,o,!1,"extendedContext",a,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${b}, threshold: ${h}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let v=a?X("extendedContext",o,t.fallback,i,f,u):null;if(v)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${b}, threshold: ${h}`),{model:v,scenarioType:"extendedContext",isFallback:!0};if(u){let S=ee(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(g>m&&(t.longContext||t.fallback?.longContext?.length||i?.longContext?.length)){let k=t.longContext?G(t.longContext,o,!1,"longContext",a,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${g}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let v=a?X("longContext",o,t.fallback,i,f,u):null;if(v)return n.log.info(`Family: using long context fallback model, tokens: ${g}, estimated: ${e}`),{model:v,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let S=ee(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=G(t.webSearch,o,!1,"webSearch",a,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let v=a?X("webSearch",o,t.fallback,i,f,u):null;if(v)return n.log.info("Family: using webSearch fallback model"),{model:v,scenarioType:"webSearch",isFallback:!0};if(u){let S=ee(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=G(t.think,o,!1,"think",a,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let v=a?X("think",o,t.fallback,i,f,u):null;if(v)return n.log.info("Family: using think fallback model"),{model:v,scenarioType:"think",isFallback:!0};if(u){let S=ee(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=G(t.default,o,!1,"default",a,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let v=a?X("default",o,t.fallback,i,f,u):null;if(v)return n.log.info("Family: using default fallback model"),{model:v,scenarioType:"default",isFallback:!0};if(u){let S=ee(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 Ku(){if(Se.size<=xi)return;let n=[...Se.keys()].slice(0,Se.size-xi);for(let e of n)Se.delete(e)}function Gu(){if(Be.size<=Si)return;let n=[...Be].slice(0,Be.size-Si);for(let e of n)Be.delete(e)}var Ri,te,ce,sn,Du,zu,an,Se,xi,Be,Si,Bu,Ju,Wu,Ci,Ai,Ce=w(()=>{"use strict";en();re();De();Qt();qt();Fe();fi();ze();Ri={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},te=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Ri[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};ce=Mu("cl100k_base"),sn=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=ce.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=ce.encode(s.text).length;else if(s.type==="tool_use")o+=ce.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let i=s.content;if(Array.isArray(i))for(let a of i)a?.type!=="image"&&(o+=ce.encode(a?.type==="text"?String(a.text??""):JSON.stringify(a)).length);else o+=ce.encode(typeof i=="string"?i:JSON.stringify(i)).length}})}),typeof e=="string"?o+=ce.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=ce.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=ce.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=ce.encode(r.name+r.description).length),r.input_schema&&(o+=ce.encode(JSON.stringify(r.input_schema)).length)}),o},Du=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 te(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Ai(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await pi(n.sessionId);s&&Nu(s)&&(r=vi(s))}if(r){n.projectId=r;let s=Zo(Ti,r,"config.json");if(!t&&n.sessionId){let i=Zo(Ti,r,`${n.sessionId}.json`);try{let a=JSON.parse(await Xo(i,"utf8"));if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch{}}try{let i=JSON.parse(await Xo(s,"utf8"));if(t&&(typeof i?.projectPath!="string"||vi(i.projectPath)!==o))throw new te(`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 te)throw i;if(t&&i?.code==="ENOENT")throw new te(`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 te(`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})}}}};zu=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,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let T=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);T&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${T[1]}</CCR-SUBAGENT-MODEL>`,""),d=T[1])}let{family:m,extended:g,isCcrAlias:f}=ft(n.body.model),h=a?.families?.[m||""];if(h&&a?.enableFamilyRouting){n.log.info(`Using model family routing for: ${m}${g?" (1M)":""}`),n.modelFamily=m,n.familyFallback=h.fallback;let T=Hu(n,e,h,i,o,g,u,l,a?.longContextThreshold,a?.extendedContextThreshold,s,p);if(T)return{model:T.model,scenarioType:T.scenarioType}}if(n.body.model.includes(",")&&!s){let T=G(n.body.model,i,!1,"default",l,p,s);if(T)return{model:T,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let R=l?X("default",i,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 b=f&&!a?.enableFamilyRouting?null:Fu(n.body.model,a?.models);if(b){let T=G(b,i,!1,"modelMapping",l,p,s);if(T)return n.log.info(`Using mapped model for ${n.body.model}: ${b}`),{model:T,scenarioType:"modelMapping"};let R=l?X("modelMapping",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"modelMapping"};if(s){let C=ee(n,b,i,"modelMapping");if(C)return{model:C,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${b} unavailable (fail pool), skipping`)}let _=n.clientContext,y=Pi(e,o,_),k=Ei(_,void 0,a?.extendedContextThreshold);if(y>k&&a?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${y}, estimated: ${e}, threshold: ${k}`);let T=G(a.extendedContext,i,!1,"extendedContext",l,p,s);if(T)return{model:T,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let R=l?X("extendedContext",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"extendedContext"};if(s){let C=ee(n,a.extendedContext,i,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext"}}}let v=_?.longContextThreshold??a?.longContextThreshold??6e4;if(y>v&&a?.longContext){n.log.info(`Using long context model due to token count: ${y}, estimated: ${e}, threshold: ${v}`);let T=G(a.longContext,i,!1,"longContext",l,p,s);if(T)return{model:T,scenarioType:"longContext"};n.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let R=l?X("longContext",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"longContext"};if(s){let C=ee(n,a.longContext,i,"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")&&a?.background){n.log.info(`Using background model for ${n.body.model}`);let T=G(a.background,i,!1,"background",l,p,s);if(T)return{model:T,scenarioType:"background"};let R=l?X("background",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"background"};if(s){let C=ee(n,a.background,i,"background");if(C)return{model:C,scenarioType:"background"}}n.log.warn(`Background model ${a.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(T=>T.type?.startsWith("web_search"))&&a?.webSearch){let T=G(a.webSearch,i,!1,"webSearch",l,p,s);if(T)return{model:T,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let R=l?X("webSearch",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"webSearch"};if(s){let C=ee(n,a.webSearch,i,"webSearch");if(C)return{model:C,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&a?.think){n.log.info(`Using think model for ${n.body.thinking}`);let T=G(a.think,i,!1,"think",l,p,s);if(T)return{model:T,scenarioType:"think"};n.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let R=l?X("think",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"think"};if(s){let C=ee(n,a.think,i,"think");if(C)return{model:C,scenarioType:"think"}}}if(a?.default){let T=G(a.default,i,!1,"default",l,p,s);if(T)return{model:T,scenarioType:"default"};n.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let R=l?X("default",i,void 0,u,void 0,s):null;if(R)return{model:R,scenarioType:"default"};let C=G(a.default,i,!0,"default",l,p,s);if(C)return n.log.warn(`No fallback available; retrying default model ${a.default} despite fail-pool state (strict=${s})`),{model:C,scenarioType:"default"}}if(s){let T=ee(n,a?.default||n.body.model,i,"default");if(T)return{model:T,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},an=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,o.getAll());let s=await Du(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??Q.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:m}=n.body,g=o.get("REWRITE_SYSTEM_PROMPT");if(g&&d.length>1&&d[1]?.text?.includes("<env>")){let f=await Xo(g,"utf-8");d[1].text=`${f}<env>${d[1].text.split("<env>").pop()}`}try{let[f,h]=n.body.model.split(","),b=t.tokenizerService?.getTokenizerConfigForModel(f,h),_;t.tokenizerService?_=(await t.tokenizerService.countTokens({messages:p,system:d,tools:m},b,f)).tokenCount:_=sn(p,d,m),n.tokenCount=_;let y,k=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{y=await ot(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 zu(n,_,o,u,s,!!s);y=R.model,n.scenarioType=R.scenarioType}let{family:v}=ft(n.originalModel||n.body.model),S=i?.enableFamilyRouting&&v?i.families?.[v]:void 0,T=[S?.image,i?.image].filter((R,C,x)=>!!R&&x.indexOf(R)===C);if(T.length>0&&ju(n)&&!mt(y))if(T.includes(y))n.scenarioType="image";else{let R=T.map(C=>G(C,l,!1,"image",a,!c,c)).find(C=>!!C);if(R)n.log.info(`Using image model fallback for ${y}`),y=R,n.scenarioType="image";else{let C=a?X("image",l,S?.fallback,n.fallbackConfig,v||void 0,c):null;if(C)n.log.info(`Using image fallback model: ${C}`),y=C,n.scenarioType="image";else if(c){let x=ee(n,T[0],l,"image");x&&(y=x,n.scenarioType="image")}else n.log.warn(`Image models ${T.join(", ")} unavailable (fail pool), keeping ${y}`),n.scenarioType="image"}}if(i?.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=ni(n,y,{threshold:Number(i?.concurrencyThreshold)||3,fallbackModels:C,resolve:x=>G(x,l,!1,R,a,!c,c),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 te)throw f;if(n.log.error(`Error in router middleware: ${f.message}`),c){let h=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${f.message}. Session: "${h||"unknown"}".`,{sessionId:h,configuredTarget:i?.default,code:"project_router_failure",statusCode:502})}n.body.model=i?.default,n.scenarioType="default"}},Se=new Map,xi=1e3,Be=new Set,Si=1e3,Bu=3,Ju=50,Wu=n=>new Promise(e=>setTimeout(e,n));Ci=async n=>{let e=await Lu(ki),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let i=Zo(ki,s,`${n}.jsonl`);try{return(await $u(i)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Ai=async n=>{let e=ge(n);if(!e)return null;if(Se.has(e))return Se.get(e)||null;try{let t=await Ci(e);if(!t&&!Be.has(e)){Be.add(e),Gu();for(let o=0;o<Bu&&!t;o++)await Wu(Ju),t=await Ci(e)}return t?(Se.set(e,t),Ku(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function gt(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
43
44
|
`):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
|
|
44
|
-
${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function
|
|
45
|
-
`).some(d=>d.startsWith("data:"))))break}if(i+=r.decode(),s.length===0)throw o.releaseLock(),
|
|
46
|
-
`).filter(c=>c.startsWith("data:")&&c.trim().length>5).length===0){o.releaseLock();let c=i.length<500?i:i.slice(0,500);throw J(`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 Kl(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=U(),u=n.provider||"",d=n.body.model||"",p=new Set,m=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&Wt(r.rawBody)||r?.message&&Wt(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=st(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 O={...n,provider:v,body:R},P=C.provider,{requestBody:M,config:$,bypass:L}=await Ys(R,P,o,n.headers,{req:O}),H=await Xs(M,$,P,t,L,o,{req:O});try{P?.baseUrl&&H?.headers&&qe(v,P.baseUrl,H.headers)}catch{}let N=await Zs(M,H,P,o,L,{req:O,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1});return N=await Qs(R,N,v),n.log.info(`Fallback model ${v},${S} succeeded`),c.recordSuccess(v,S),u&&d&&!n.strictProjectRouting&&(Ee().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,_s(n,`${v},${S}`),qs(N,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 Ys(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=Gl(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 Gl(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 Vl(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 Ql(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 Xs(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||{}};Vl(l,i?.req);for(let u in l)(l[u]==="undefined"||["authorization","Authorization"].includes(u)&&l[u]?.includes("undefined"))&&delete l[u];Pt(o.configService)&&es(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:ce(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=J(`Error from provider(${t.name},${n.model}: ${c.status}): ${u}`,c.status,"provider_response_error");throw d.isRateLimit=c.status===429||Wt(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(tt(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=Wt(m),_=J(`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=J(`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&&Pt(o.configService)){let d=await c.clone().text();ts(o.log,i.req.id,{status:c.status,headers:Object.fromEntries(c.headers.entries()),body:d})}return c}async function Zs(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 Ae().transformResponseIn(i,{...s,provider:t})}catch(a){console.error("Failed to apply Responses API conversion for codex client:",a)}return i}async function qs(n,e,t,o){n.ok||e.code(n.status);let r=bs(n);if(!r){let s=await pe(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 fe(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&&Pt(o.configService)){let[s,i]=n.body.tee(),a=qr(o.configService);return ns(s,o.log,e.request.id,a),e.send(i)}return e.send(n.body)}else return F(n)}function Wt(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 Yl(n){try{return new URL(n),!0}catch{return!1}}var Wl,ei,Kt=E(()=>{"use strict";rs();wt();Ze();ao();re();Oe();Mt();Dt();Co();V();je();oe();Wl=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;ei=async n=>{n.get("/",async()=>({message:"LLMs API",version:It})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:U().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Vs(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 J("Provider name is required",400,"invalid_request");if(!s||!Yl(s))throw J("Valid base URL is required",400,"invalid_request");if(!i?.trim())throw J("API key is required",400,"invalid_request");if(!a||!Array.isArray(a)||a.length===0)throw J("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw J(`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 J("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 J("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 J("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 J("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var ue,Gt=E(()=>{"use strict";ue=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 he,Vt,ti,Xl,ni,He=E(()=>{he=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",Vt=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,ti=["low","medium","high"],Xl={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"},ni=n=>{if(typeof n=="string")return Xl[n.trim().toLowerCase()]}});var oi,ri=E(()=>{oi=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Zl(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function si(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||Vt(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:he(p);ti.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(`
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
`)
|
|
50
|
-
|
|
45
|
+
${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 Ii(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),vo(n),o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&>(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&Vu.test(r.model)&&await an(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let s=n.provider;if(!s&&r?.model){let c=r.model.split(",");c.length>1&&(s=c[0],r.model=c.slice(1).join(","))}let i=s?t.providerService.getProvider(s):void 0;if(!i&&r?.model){let c=t.providerService.resolveModelRoute(r.model);c&&(i=c.provider,r.model=c.targetModel)}if(!i&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[p,...d]=u.split(","),m=t.providerService.getProvider(p);m&&(i=m,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw z(`Provider '${s}' not found`,404,"provider_not_found");n.provider=i.name||s;let a=Zu(n),l=o.endPoint==="/v1/messages"&&a;a&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=l,n.codexDetected=a;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&>(r);let c={req:n,isCodexOnMessagesEndpoint:l,pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Li(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let h=u.messages,b=new Set,_=[],y=[];for(let k of h){if(k?.role!=="system"){y.push(k);continue}let v=JSON.stringify(k.content??"");b.has(v)||(b.add(v),_.push(k))}_.length>0&&y.length>0&&(u.messages=[..._,...y])}let m=await $i(u,p,i,t,d,o,c);try{i?.baseUrl&&m?.headers&&it(s,i.baseUrl,m.headers)}catch{}let g=await Ni(u,m,i,o,d,c);g=await Mi(r,g,i.name||s);let f=Di(g,e,r,t);try{let h=r.model||n.originalModel;s&&h&&U().recordSuccess(s,h)}catch{}return f}catch(c){if(c instanceof te)throw c;if(!xo(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Ii(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await Qu(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function Mi(n,e,t){if(!n?.stream||!e?.body)return e;let o=e.body.getReader(),r=new TextDecoder,s=[],i="";for(let u=0;u<8;u++){let p=await o.read();if(p.done||(p.value&&(s.push(p.value),i+=r.decode(p.value,{stream:!0})),i.split(`
|
|
46
|
+
`).some(d=>d.startsWith("data:"))))break}if(i+=r.decode(),s.length===0)throw o.releaseLock(),z(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(i.includes("event: error")){o.releaseLock();let u=i.length<500?i:i.slice(0,500);throw z(`Provider ${t} returned error in SSE stream: ${u}`,400,"provider_response_error")}if(i.split(`
|
|
47
|
+
`).filter(u=>u.startsWith("data:")&&u.trim().length>5).length===0){o.releaseLock();let u=i.length<500?i:i.slice(0,500);throw z(`Provider ${t} returned streaming response with no SSE data lines: ${u}`,400,"provider_response_error")}let l=new ReadableStream({start:u=>{for(let d of s)u.enqueue(d);let p=()=>{o.read().then(({done:d,value:m})=>{d?u.close():(u.enqueue(m),p())}).catch(d=>u.error(d))};p()},cancel:()=>{o.cancel()}}),c=await Ns(l);if(c.verdict==="empty")throw z(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(Ds(c.chunks,c.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function Qu(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=U(),u=n.provider||"",p=n.body.model||"",d=new Set,m=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&cn(r.rawBody)||r?.message&&cn(r.message);if(u&&p&&(m?(c.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):c.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=_=>{let[y,...k]=_.split(","),v=y?.trim(),S=k.join(",").trim();return!v||!S?null:{provider:v,model:S,key:`${v},${S}`}},h=[];if(a){let _=i?.[s];if(Array.isArray(_)&&_.length>0)h.push({name:`${a}/${s}`,models:_});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&&h.push({name:`global/${s}`,models:l[s]}),h.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(v=>v.type==="image"||v.type==="image_url"||Array.isArray(v?.content)&&v.content.some(S=>S.type==="image"||S.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`),h.push({name:"global/image (auto-detected)",models:l.image})),h.length===0)return null;let b=h.reduce((_,y)=>_+y.models.length,0);n.log.warn(`Request failed for ${s}, trying ${b} fallback models across ${h.length} fallback stage(s)`);for(let _ of h){n.log.info(`Trying ${_.name} fallback stage with ${_.models.length} models`);for(let y of _.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 v=t.providerService.getProviders(),S=pt(v,k.provider,k.model);if(!S){n.log.warn(`Fallback model ${y} is not configured or provider is disabled, skipping`);continue}let T=S.provider.name,R=S.model;if(!c.isAvailable(T,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&&Oe(n,C,{name:T}).terminalError)continue;let x;for(let E=1;E<=2;E++)try{n.log.info(`Trying fallback model: ${T},${R}${E>1?" (retry)":""}`);let A={...n.body};A.model=R;let P={...n,provider:T,body:A},M=S.provider,L={pluginRegistry:t.pluginRegistry,req:P,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1},{requestBody:N,config:B,bypass:$}=await Li(A,M,o,n.headers,L),D=await $i(N,B,M,t,$,o,L);try{M?.baseUrl&&D?.headers&&it(T,M.baseUrl,D.headers)}catch{}let H=await Ni(N,D,M,o,$,L);return H=await Mi(A,H,T),n.log.info(`Fallback model ${T},${R} succeeded`),c.recordSuccess(T,R),u&&p&&!n.strictProjectRouting&&(Ie().promote(u,p,s,T,R),n.log.info(`Promoted fallback model ${T},${R} for ${u},${p}:${s}`),m?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(c.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=T,n.body=A,ti(n,`${T},${R}`),Di(H,e,A,t)}catch(A){if(x=A,xo(n,C,A,{name:T}))break;if(E===1){n.log.warn(`Fallback model ${T},${R} failed, retrying once: ${A.message}`);continue}}c.recordFailure(T,R,x?.message),n.log.warn(`Fallback model ${T},${R} failed after retry: ${x?.message}`),t.recordUsage?.({provider:T,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 Li(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw z("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=Oe(r.req,s,e).terminalError;if(u)throw u;await s.ensureUsable?.()}let i=JSON.parse(JSON.stringify(n)),a=i?.system;if(typeof a=="string"&&a.includes("cch="))i.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let u=0;u<a.length;u++){let p=a[u],d=typeof p=="string"?p:p?.text??"";if(d.includes("cch=")){let m=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?a[u]=m:typeof p?.text=="string"&&(p.text=m)}}let l={},c=!1;if(c=Yu(e,t,n),c&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!c&&typeof t.transformRequestOut=="function"){let u=await t.transformRequestOut(i);u.body?(i=u.body,l=u.config||{}):i=u}if(!c&&e.transformer?.use?.length)for(let u of e.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let p=await u.transformRequestIn(i,e,r);p.body?(i=p.body,l={...l,...p.config}):i=p}if(!c&&e.transformer?.[n.model]?.use?.length)for(let u of e.transformer[n.model].use)!u||typeof u.transformRequestIn!="function"||(i=await u.transformRequestIn(i,e,r));return{requestBody:i,config:l,bypass:c}}function Yu(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 Xu(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 Zu(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=o.pluginRegistry.getManagedRuntimeFor(t);return a?.dispatchRequest?a.dispatchRequest({attempt:()=>Oi(n,e,t,o,r,s,i),requestBody:n,config:e,provider:t,req:i?.req}):Oi(n,e,t,o,r,s,i)}function Je(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
|
|
48
|
+
`):""}async function Oi(n,e,t,o,r,s,i){let a=o.pluginRegistry.getManagedRuntimeFor(t);a&&(await a.ensureUsable?.(),await a.lockUpstream?.(e,t));let l=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,i);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 c={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};a&&(c=await a.signRequest({headers:c,requestBody:n,provider:t,config:e})),Xu(c,i?.req);for(let d in c)(c[d]==="undefined"||["authorization","Authorization"].includes(d)&&c[d]?.includes("undefined"))&&delete c[d];!a?.suppressDebugLog&&Bt(o.configService)&&As(o.log,i.req.id,{url:String(l),headers:c,body:n});let u,p=()=>Ms(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:a?void 0:ue(o.configService,t)},i,a?void 0:o.log);try{u=await p()}catch(d){throw a?await Te(a,0,void 0,Je(n),{errorName:d?.name}):d}if(!u.ok&&a?.authRefresh&&u.status===401&&!Oe(i.req,a,t).refreshUsed){Oe(i.req,a,t).refreshUsed=!0;try{await a.authRefresh.forceRefresh(),c=await a.signRequest({headers:c,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(i.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(g){throw a?await Te(a,u.status,void 0,Je(n)):g}if(a){let g=await Te(a,u.status,d,Je(n));throw o.log.error(`[provider_response_error] Plugin(${a.name}) status=${u.status} code=${g.code}`),g}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let m=z(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw m.isRateLimit=u.status===429||cn(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 g="";try{if(g=await u.clone().text(),!g||g.trim()==="")throw new SyntaxError("Empty JSON body");if(ct(g))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let h=JSON.parse(g);if(a?.isErrorEnvelope?.(h))throw await Te(a,u.status,g,Je(n));if(h&&typeof h=="object"&&h.error&&(typeof h.error=="string"||typeof h.error=="object"&&Object.keys(h.error).length>0)){if(a)throw await Te(a,u.status,g,Je(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let _=cn(g),y=z(`Error from provider(${t.name},${n.model}: ${u.status}): ${g}`,400,"provider_response_error");throw y.isRateLimit=_,y.rawBody=g,y}}catch(f){if(a)throw f?.pluginClassified===!0?f:await Te(a,u.status,void 0,Je(n));if(f instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let h=z(`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 h.rawBody=g,h}throw f}}}if(!a?.suppressDebugLog&&!n.stream&&Bt(o.configService)){let m=await u.clone().text();Os(o.log,i.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:m})}return u}async function Ni(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 $e().transformResponseIn(i,{...s,provider:t})}catch(a){console.error("Failed to apply Responses API conversion for codex client:",a)}return i}async function Di(n,e,t,o){n.ok||e.code(n.status);let r=oi(n);if(!r){let s=await de(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 me(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&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Bt(o.configService)){let[s,i]=n.body.tee(),a=Es(o.configService);return Is(s,o.log,e.request.id,a),e.send(i)}return e.send(n.body)}else return F(n)}function cn(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 qu(n){try{return new URL(n),!0}catch{return!1}}var Vu,Fi,ln=w(()=>{"use strict";Ls();Ht();Fs();Us();Hs();rt();wo();re();Le();Qt();qt();Bo();V();Ce();q();Vu=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Fi=async n=>{n.get("/",async()=>({message:"LLMs API",version:Vt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:U().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Ii(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 z("Provider name is required",400,"invalid_request");if(!s||!qu(s))throw z("Valid base URL is required",400,"invalid_request");if(!i?.trim())throw z("API key is required",400,"invalid_request");if(!a||!Array.isArray(a)||a.length===0)throw z("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw z(`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 z("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 z("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 z("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 z("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var We,qo=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(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,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 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 ye,un,Ui,ed,ji,Ke=w(()=>{ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",un=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Ui=["low","medium","high"],ed={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"},ji=n=>{if(typeof n=="string")return ed[n.trim().toLowerCase()]}});var er,Hi=w(()=>{er=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function td(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function zi(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 g=t[m],f=g?.text??JSON.stringify(g),h=d.get(f);if(h===void 0){d.set(f,m);continue}!t[h]?.cache_control&&g?.cache_control&&(t[h]=g),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 g=m.content;try{typeof m.content=="string"&&(g=JSON.parse(m.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let f={type:"tool_result",tool_use_id:m.tool_call_id,content:g};m.cache_control&&(f.cache_control=m.cache_control);let h=s[s.length-1];h&&h.role==="user"&&Array.isArray(h.content)?h.content.push(f):s.push({role:"user",content:[f]})}else if(m.role==="user"){let g=[];typeof m.content=="string"?g.push({type:"text",text:m.content}):Array.isArray(m.content)&&m.content.forEach(h=>{h&&typeof h=="object"&&h.type==="image_url"&&h.image_url?.url?g.push({type:"image",source:{type:"base64",media_type:h.media_type||"image/jpeg",data:h.image_url.url.split(",")[1]||h.image_url.url}}):g.push(h)});let f=s[s.length-1];f&&f.role==="user"&&Array.isArray(f.content)?f.content.push(...g):s.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(m.role==="assistant"){let g=[];m.content&&(typeof m.content=="string"?g.push({type:"text",text:m.content}):Array.isArray(m.content)&&g.push(...m.content)),m.tool_calls&&m.tool_calls.length>0&&m.tool_calls.forEach(h=>{let b={};try{b=JSON.parse(h.function.arguments)}catch{b=h.function.arguments}g.push({type:"tool_use",id:h.id,name:h.function.name,input:b})}),m.thinking&&g.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(...g):s.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let i=()=>{let d=t.filter(m=>m?.cache_control).length;for(let m of s)Array.isArray(m.content)&&(d+=m.content.filter(g=>g?.cache_control).length);return d},a=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},l=()=>{for(let d=s.length-1;d>=0;d--){let m=s[d]?.content;if(!Array.isArray(m))continue;let g=m.find(f=>f?.cache_control);if(g?.cache_control)return g.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},c=(d,m)=>{if(!Array.isArray(d?.content)||d.content.some(f=>f?.cache_control))return!1;let g=d.content.find(f=>f&&typeof f=="object"&&!f.cache_control);return g?(g.cache_control=a(m),!0):!1};(()=>{let d=4-i();if(d<=0||s.length===0)return;let m=s,g=l(),f=[];for(let h=m.length-1;h>=0;h--)m[h]?.role!=="user"||!Array.isArray(m[h].content)||f.push(h);for(let h of f){if(d<=0)break;c(m[h],g)&&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||un(n.reasoning.effort||"medium"),m=Math.min(d,p.max_tokens-1024);m>=1024&&(p.thinking={type:"enabled",budget_tokens:m});let g=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Ui.includes(g)&&(p.output_config={...p.output_config||{},effort:g})}if(t.length>0){let d=t.some(m=>m?.cache_control);p.system=d?t:t.map(m=>m.text||"").join(`
|
|
49
|
+
|
|
50
|
+
`)}return n.tools&&n.tools.length>0&&(p.tools=td(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 Bi=w(()=>{Ke()});import{v4 as tr}from"uuid";function nd(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 dn,Ji=w(()=>{"use strict";Ke();Ht();V();Hi();Bi();Ce();dn=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 a=e.system.filter(l=>l.type==="text"&&l.text).map(l=>({type:"text",text:l.text,cache_control:l.cache_control}));t.push({role:"system",content:a})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(a=>{a.role==="system"&&t.push({role:"system",content:a.content})}),o?.forEach(a=>{if(a.role!=="system"&&(a.role==="user"||a.role==="assistant")){if(typeof a.content=="string"){t.push({role:a.role,content:a.content});return}if(Array.isArray(a.content)){if(a.role==="user"){let l=a.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(l.length){let u=mt(String(e.model??"")),p=[];l.forEach(d=>{let m=Array.isArray(d.content)?d.content:null,g=m?m.filter(b=>b?.type==="image"&&b?.source):[],f=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(g.length>0){let b=m.filter(_=>!(_?.type==="image"&&_?.source)).map(_=>_?.type==="text"?String(_.text??""):JSON.stringify(_)).filter(_=>_.length>0).join(`
|
|
51
|
+
`);u?(f=b||"[tool image]",p.push(...g)):(f=[b,...g.map(()=>"(tool image omitted: target model does not support image input)")].filter(_=>_.length>0).join(`
|
|
52
|
+
`),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:g.length}))}let h={role:"tool",content:f,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(h)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?er(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let c=a.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);c.length&&t.push({role:"user",content:c.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?er(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(a.role==="assistant"){let l={role:"assistant",content:""},c=a.content.filter(d=>d.type==="text"&&d.text);c.length&&(l.content=c.map(d=>d.text).join(`
|
|
53
|
+
`));let u=a.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(l.tool_calls=u.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let p=a.content.find(d=>d.type==="thinking");p&&(l.thinking={content:p.thinking,signature:p.signature}),t.push(l)}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=ji(e.output_config?.effort),i=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let a={},c=nd(e.thinking?.type)??(s!==void 0||(i??0)>0);c!==void 0&&(a.enabled=c),s!==void 0?a.effort=s:i!==void 0&&(a.effort=ye(i)),i!==void 0&&i>0&&(a.max_tokens=i),Object.keys(a).length>0&&(r.reasoning=a)}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=zi(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 de(e);if((r?.isSSE??!1)&&r?.body){let c=await this.convertOpenAIStreamToAnthropic(r.body,t);return new Response(c,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let i;if(r?.body)i=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else{let c=await me(e);if(c.isSSE){let u=await this.convertOpenAIStreamToAnthropic(c.response.body,t);return new Response(u,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}i=c.response}let a=await F(i),l=this.convertOpenAIResponseToAnthropic(a,t);return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,i=`msg_${Date.now()}`,a=null,l="unknown",c=!1,u=!1,p=!1,d=new Map,m=new Map,g=0,f=0,h=0,b=!1,_=!1,y=0,k=-1,v=()=>{let C=y;return y++,C},S=C=>{if(!b)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"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:x instanceof Error?x.message:String(x),type:"send data error"}),x}},T=()=>{if(!b)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(k>=0){let x={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
54
|
+
data: ${JSON.stringify(x)}
|
|
51
55
|
|
|
52
|
-
`)),
|
|
56
|
+
`)),k=-1}if(a)S(s.encode(`event: message_delta
|
|
53
57
|
data: ${JSON.stringify(a)}
|
|
54
58
|
|
|
55
|
-
`)),a=null;else{let
|
|
56
|
-
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:
|
|
59
|
+
`)),a=null;else{let x=t?.req?.tokenCount||0;S(s.encode(`event: message_delta
|
|
60
|
+
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}})}
|
|
57
61
|
|
|
58
|
-
`))}let
|
|
59
|
-
data: ${JSON.stringify(
|
|
62
|
+
`))}let C={type:"message_stop"};S(s.encode(`event: message_stop
|
|
63
|
+
data: ${JSON.stringify(C)}
|
|
60
64
|
|
|
61
|
-
`)),r.close(),
|
|
62
|
-
`);
|
|
63
|
-
data: ${JSON.stringify(
|
|
65
|
+
`)),r.close(),b=!0}catch(C){if(C instanceof TypeError&&C.message.includes("Controller is already closed"))b=!0;else throw C}},R=null;try{R=e.getReader();let C=new TextDecoder,x="";for(;!b;){let{done:E,value:A}=await R.read();if(E)break;x+=C.decode(A,{stream:!0});let P=x.split(`
|
|
66
|
+
`);x=P.pop()||"";for(let M of P){if(b)break;if(!M.startsWith("data:"))continue;let L=M.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:L}),L!=="[DONE]")try{let N=JSON.parse(L);if(g++,this.logger.debug({reqId:t.req.id,response:N,tppe:"Original Response"}),N.error){t?.req&&(t.req.sseError=N.error);let $={type:"error",message:{type:"api_error",message:JSON.stringify(N.error)}};S(s.encode(`event: error
|
|
67
|
+
data: ${JSON.stringify($)}
|
|
64
68
|
|
|
65
|
-
`));continue}if(l=
|
|
69
|
+
`));continue}if(l=N.model||l,!c&&!b&&!p){c=!0;let $=t?.req?.tokenCount||0,D={type:"message_start",message:{id:i,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:$,output_tokens:0}}};S(s.encode(`event: message_start
|
|
66
70
|
data: ${JSON.stringify(D)}
|
|
67
71
|
|
|
68
|
-
`))}let
|
|
72
|
+
`))}let B=N.choices?.[0];if(N.usage){let $=N.usage?.prompt_tokens_details?.cached_tokens??N.usage?.prompt_cache_hit_tokens??0,H=(N.usage?.prompt_tokens||0)-$,fe=N.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:N.usage,mappedUsage:{input_tokens:H,output_tokens:fe,cache_read_input_tokens:$},choicesLength:Array.isArray(N.choices)?N.choices.length:void 0,finishReason:B?.finish_reason});let j={input_tokens:H,output_tokens:fe,cache_read_input_tokens:$};if(!a)a={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...j}};else{let Z=a.usage||{};a.usage={input_tokens:j.input_tokens||Z.input_tokens||0,output_tokens:j.output_tokens||Z.output_tokens||0,cache_read_input_tokens:j.cache_read_input_tokens||Z.cache_read_input_tokens||0}}}if(!B)continue;if(B?.delta?.thinking&&!b&&!p&&!u){if(!_){let $=v(),D={type:"content_block_start",index:$,content_block:{type:"thinking",thinking:""}};S(s.encode(`event: content_block_start
|
|
69
73
|
data: ${JSON.stringify(D)}
|
|
70
74
|
|
|
71
|
-
`)),
|
|
72
|
-
data: ${JSON.stringify(
|
|
75
|
+
`)),k=$,_=!0}if(B.delta.thinking.signature){let $={type:"content_block_delta",index:k,delta:{type:"signature_delta",signature:B.delta.thinking.signature}};S(s.encode(`event: content_block_delta
|
|
76
|
+
data: ${JSON.stringify($)}
|
|
73
77
|
|
|
74
|
-
`));let D={type:"content_block_stop",index:
|
|
78
|
+
`));let D={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
75
79
|
data: ${JSON.stringify(D)}
|
|
76
80
|
|
|
77
|
-
`)),
|
|
78
|
-
data: ${JSON.stringify(
|
|
81
|
+
`)),k=-1}else if(B.delta.thinking.content){let $={type:"content_block_delta",index:k,delta:{type:"thinking_delta",thinking:B.delta.thinking.content||""}};S(s.encode(`event: content_block_delta
|
|
82
|
+
data: ${JSON.stringify($)}
|
|
79
83
|
|
|
80
|
-
`))}}if(
|
|
84
|
+
`))}}if(B?.delta?.content&&!b&&!p){if(f++,k>=0&&!u){let D={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
81
85
|
data: ${JSON.stringify(D)}
|
|
82
86
|
|
|
83
|
-
`)),
|
|
87
|
+
`)),k=-1}if(!u&&!p){u=!0;let $=v(),D={type:"content_block_start",index:$,content_block:{type:"text",text:""}};S(s.encode(`event: content_block_start
|
|
84
88
|
data: ${JSON.stringify(D)}
|
|
85
89
|
|
|
86
|
-
`)),
|
|
87
|
-
data: ${JSON.stringify(
|
|
90
|
+
`)),k=$}if(!b&&!p){let $={type:"content_block_delta",index:k,delta:{type:"text_delta",text:B.delta.content}};S(s.encode(`event: content_block_delta
|
|
91
|
+
data: ${JSON.stringify($)}
|
|
88
92
|
|
|
89
|
-
`))}}if(
|
|
90
|
-
data: ${JSON.stringify(
|
|
93
|
+
`))}}if(B?.delta?.annotations?.length&&!b&&!p){if(k>=0&&u){let $={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
94
|
+
data: ${JSON.stringify($)}
|
|
91
95
|
|
|
92
|
-
`)),
|
|
93
|
-
data: ${JSON.stringify(
|
|
96
|
+
`)),k=-1,u=!1}B?.delta?.annotations.forEach($=>{let D=v(),H={type:"content_block_start",index:D,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${tr()}`,content:[{type:"web_search_result",title:$.url_citation.title,url:$.url_citation.url}]}};S(s.encode(`event: content_block_start
|
|
97
|
+
data: ${JSON.stringify(H)}
|
|
94
98
|
|
|
95
|
-
`));let
|
|
96
|
-
data: ${JSON.stringify(
|
|
99
|
+
`));let fe={type:"content_block_stop",index:D};S(s.encode(`event: content_block_stop
|
|
100
|
+
data: ${JSON.stringify(fe)}
|
|
97
101
|
|
|
98
|
-
`)),
|
|
99
|
-
data: ${JSON.stringify(
|
|
102
|
+
`)),k=-1})}if(B?.delta?.tool_calls&&!b&&!p){h++;let $=new Set;for(let D of B.delta.tool_calls){if(b)break;let H=D.index??0;if($.has(H))continue;if($.add(H),!m.has(H)){if(k>=0){let Yc={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
103
|
+
data: ${JSON.stringify(Yc)}
|
|
100
104
|
|
|
101
|
-
`)),
|
|
102
|
-
data: ${JSON.stringify(
|
|
105
|
+
`)),k=-1}let j=v();m.set(H,j);let Z=D.id||`call_ccr_${H}`,J=D.function?.name||`tool_${H}`,O={type:"content_block_start",index:j,content_block:{type:"tool_use",id:Z,name:J,input:{}}};S(s.encode(`event: content_block_start
|
|
106
|
+
data: ${JSON.stringify(O)}
|
|
103
107
|
|
|
104
|
-
`)),
|
|
105
|
-
data: ${JSON.stringify(
|
|
108
|
+
`)),k=j;let W={id:Z,name:J,arguments:"",contentBlockIndex:j};d.set(H,W)}else if(D.id&&D.function?.name){let j=d.get(H);j.id.startsWith("call_")&&j.name.startsWith("tool_")&&(j.id=D.id,j.name=D.function.name)}if(D.function?.arguments&&!b&&!p){let j=m.get(H);if(j===void 0)continue;let Z=d.get(H);Z&&(Z.arguments+=D.function.arguments);try{let J={type:"content_block_delta",index:j,delta:{type:"input_json_delta",partial_json:D.function.arguments}};S(s.encode(`event: content_block_delta
|
|
109
|
+
data: ${JSON.stringify(J)}
|
|
106
110
|
|
|
107
|
-
`))}catch{try{let
|
|
108
|
-
data: ${JSON.stringify(
|
|
111
|
+
`))}catch{try{let J=D.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O={type:"content_block_delta",index:j,delta:{type:"input_json_delta",partial_json:J}};S(s.encode(`event: content_block_delta
|
|
112
|
+
data: ${JSON.stringify(O)}
|
|
109
113
|
|
|
110
|
-
`))}catch(
|
|
111
|
-
data: ${JSON.stringify(
|
|
114
|
+
`))}catch(J){console.error(J)}}}}}if(B?.finish_reason&&!b&&!p){if(f===0&&h===0&&console.error("Warning: No content in the stream response!"),k>=0){let $={type:"content_block_stop",index:k};S(s.encode(`event: content_block_stop
|
|
115
|
+
data: ${JSON.stringify($)}
|
|
112
116
|
|
|
113
|
-
`)),
|
|
114
|
-
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:c,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,i=!1,a=!1,l="",c=0,u=-1,
|
|
117
|
+
`)),k=-1}if(!b){let D={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[B.finish_reason]||"end_turn";a?a.delta={...a.delta,stop_reason:D,stop_sequence:null}:a={type:"message_delta",delta:{stop_reason:D,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(N){this.logger?.error(`parseError: ${N.name} message: ${N.message} stack: ${N.stack} data: ${L}`)}}}T()}catch(C){if(!b)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 l=`srvtoolu_${tr()}`;r.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:l,content:o.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(l=>{let c={};try{let u=l.function.arguments||"{}";typeof u=="object"?c=u:typeof u=="string"&&(c=JSON.parse(u))}catch{c={text:l.function.arguments||""}}r.push({type:"tool_use",id:l.id,name:l.function.name,input:c})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens??e.usage?.prompt_cache_hit_tokens??0,i=(e.usage?.prompt_tokens||0)-s,a={id:e.id?.startsWith("msg_")?e.id:`msg_${tr().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:i,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:a},"Conversion complete, final Anthropic response"),a}catch{throw z(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function od(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(Ge).includes(o)?o:Ge.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ge).includes(r)?r:Ge.TYPE_UNSPECIFIED})}}}function ht(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)&&od(n.type,e);for(let[i,a]of Object.entries(n))if(a!=null)if(i=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(a))continue;let l=a.toUpperCase();e.type=Object.values(Ge).includes(l)?l:Ge.TYPE_UNSPECIFIED}else if(t.includes(i))e[i]=ht(a);else if(o.includes(i)){let l=[];for(let c of a){if(c.type=="null"){e.nullable=!0;continue}l.push(ht(c))}e[i]=l}else if(r.includes(i)){let l={};for(let[c,u]of Object.entries(a))l[c]=ht(u);e[i]=l}else{if(i==="additionalProperties")continue;e[i]=a}return e}function rd(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=ht(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ht(e.response));return n}function pn(n){let e=[],t=n.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));t?.length&&e.push(rd({functionDeclarations:t})),n.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(l=>l.role==="tool");n.messages.filter(l=>l.role!=="tool").forEach(l=>{let c;l.role==="assistant"?c="model":(["user","system"].includes(l.role),c="user");let u=[];if(typeof l.content=="string"){let p={text:l.content};l.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),u.push(p)}else Array.isArray(l.content)?u.push(...l.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}}})):l.content&&typeof l.content=="object"&&(l.content.text?u.push({text:l.content.text}):u.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&u.push(...l.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 l.thinking?.signature&&(d.thoughtSignature=l.thinking.signature),d})),u.length===0&&u.push({text:""}),r.push({role:c,parts:u}),c==="model"&&l.tool_calls){let p=l.tool_calls.map(d=>{let m=s.find(g=>g.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:m?.content}}}});r.push({role:"user",parts:p})}});let i={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(i.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))i.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let l=n.model.includes("pro")?[128,32768]:[0,24576],c,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=l[0]&&u<=l[1]?c=u:u<l[0]?c=l[0]:u>l[1]&&(c=l[1]),i.thinkingConfig.thinkingBudget=c)}let a={contents:r,tools:e.length?e:void 0,generationConfig:i};if(n.tool_choice){let l={functionCallingConfig:{}};n.tool_choice==="auto"?l.functionCallingConfig.mode="auto":n.tool_choice==="none"?l.functionCallingConfig.mode="none":n.tool_choice==="required"?l.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),a.toolConfig=l}return a}function fn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,i=n.stream,a=n.tool_choice,l={messages:[],model:o,max_tokens:r,temperature:s,stream:i,tool_choice:a};return Array.isArray(e)&&e.forEach(c=>{typeof c=="string"?l.messages.push({role:"user",content:c}):typeof c.text=="string"?l.messages.push({role:"user",content:c.text||null}):c.role==="user"?l.messages.push({role:"user",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):c.role==="model"&&l.messages.push({role:"assistant",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(l.tools=[],t.forEach(c=>{Array.isArray(c.functionDeclarations)&&c.functionDeclarations.forEach(u=>{l.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),l}async function mn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",i=o.candidates[0]?.content?.parts||[],a=[];for(let p of i)p.text&&p.thought===!0?r+=p.text:a.push(p);s=i.find(p=>p.thoughtSignature)?.thoughtSignature;let l=a?.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||{})}}))||[],c=a?.filter(p=>p.text)?.map(p=>p.text)?.join(`
|
|
118
|
+
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:c,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,i=!1,a=!1,l="",c=0,u=-1,p=new ReadableStream({async start(d){let m=async(h,b)=>{if(h.startsWith("data: ")){let _=h.slice(6).trim();if(_){t?.debug({chunkStr:_},`${e} chunk:`);try{let y=JSON.parse(_);if(!y.candidates||!y.candidates[0]){t?.debug({chunkStr:_},"Invalid chunk structure");return}let k=y.candidates[0],v=k.content?.parts||[];v.filter(C=>C.text&&C.thought===!0).forEach(C=>{a||(a=!0);let x={choices:[{delta:{role:"assistant",content:null,thinking:{content:C.text}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};b.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
115
119
|
|
|
116
|
-
`))});let
|
|
120
|
+
`))});let S=v.find(C=>C.thoughtSignature)?.thoughtSignature;if(S&&!s){if(!a){let x={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};b.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
117
121
|
|
|
118
|
-
`))}let
|
|
122
|
+
`))}let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:S}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(b.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
119
123
|
|
|
120
|
-
`)),s=!0,c++,l){let
|
|
124
|
+
`)),s=!0,c++,l){let x={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};b.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
121
125
|
|
|
122
|
-
`)),l="",i||(i=!0)}}let v
|
|
123
|
-
`);if(!
|
|
126
|
+
`)),l="",i||(i=!0)}}let T=v.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=v.filter(C=>C.text&&C.thought!==!0).map(C=>C.text).join(`
|
|
127
|
+
`);if(!R&&s&&!i){let C={choices:[{delta:{role:"assistant",content:"(no content)"},index:c,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};b.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
124
128
|
|
|
125
|
-
`)),i||(i=!0)}if(a&&
|
|
129
|
+
`)),i||(i=!0)}if(a&&R&&!s)if(y.modelVersion.includes("3")){l+=R;return}else{let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:y.responseId||"",model:y.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};b.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
126
130
|
|
|
127
|
-
`)),s=!0}if(
|
|
131
|
+
`)),s=!0}if(R){l||c++;let C={choices:[{delta:{role:"assistant",content:R},finish_reason:k.finishReason?.toLowerCase()||null,index:c,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,E)=>{let A=k?.groundingMetadata?.groundingSupports?.filter(P=>P.groundingChunkIndices?.includes(E));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}}})),b.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
128
132
|
|
|
129
|
-
`)),!i&&
|
|
133
|
+
`)),!i&&R&&(i=!0)}T.length>0&&(T.forEach(C=>{c++,u++;let x={choices:[{delta:{role:"assistant",tool_calls:[{...C,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:c,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((E,A)=>{let P=k?.groundingMetadata?.groundingSupports?.filter(M=>M.groundingChunkIndices?.includes(A));return{type:"url_citation",url_citation:{url:E?.web?.uri||"",title:E?.web?.title||"",content:P?.[0]?.segment?.text||"",start_index:P?.[0]?.segment?.startIndex||0,end_index:P?.[0]?.segment?.endIndex||0}}})),b.enqueue(r.encode(`data: ${JSON.stringify(x)}
|
|
130
134
|
|
|
131
|
-
`))}),!i&&
|
|
132
|
-
`);
|
|
135
|
+
`))}),!i&&R&&(i=!0))}catch(y){t?.error(`Error parsing ${e} stream chunk`,_,y.message)}}}},g=n.body.getReader(),f="";try{for(;;){let{done:h,value:b}=await g.read();if(h){f&&await m(f,d);break}f+=o.decode(b,{stream:!0});let _=f.split(`
|
|
136
|
+
`);f=_.pop()||"";for(let y of _)await m(y,d)}}catch(h){d.error(h)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ge,nr=w(()=>{"use strict";Ge={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var gn,Wi=w(()=>{"use strict";nr();gn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:pn(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=fn;async transformResponseOut(e){return mn(e,this.name,this.logger)}}});async function sd(){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:
|
|
133
137
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
134
138
|
2. Run "gcloud auth application-default login"
|
|
135
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
136
|
-
`);for(let
|
|
137
|
-
`))},
|
|
139
|
+
3. Use Google Cloud environment with default service account`)}}var hn,Ki=w(()=>{"use strict";nr();hn=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 a=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(a);l&&l.project_id&&(o=l.project_id)}catch(i){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await sd();return{body:pn(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 fn(e)}async transformResponseOut(e){return mn(e,this.name)}}});var yn,Gi=w(()=>{"use strict";V();yn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,i=r.thinking?.signature,a="";if(typeof r.content=="string"){let c=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);c&&(a=c[1].trim(),r.content=r.content.replace(c[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,i&&(r.reasoning_content_signature=i)):a&&(r.reasoning_content=a),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 F(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,i="",a=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,m,g)=>{let f=d.split(`
|
|
140
|
+
`);for(let h of f)h.trim()&&m.enqueue(g.encode(h+`
|
|
141
|
+
`))},p=(d,m)=>{let{controller:g,encoder:f}=m;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let h=JSON.parse(d.slice(6));if(h.choices?.[0]?.delta?.reasoning_content){m.appendReasoningContent(h.choices[0].delta.reasoning_content);let b={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,thinking:{content:h.choices[0].delta.reasoning_content}}}]};delete b.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(b)}
|
|
138
142
|
|
|
139
|
-
`;
|
|
143
|
+
`;g.enqueue(f.encode(_));return}if(h.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let b="ccr_think_signature",_=h.choices[0].delta.content,y={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:b}}}]};delete y.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(y)}
|
|
140
144
|
|
|
141
|
-
`;
|
|
145
|
+
`;g.enqueue(f.encode(k));let v={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:_}}]};delete v.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(v)}
|
|
142
146
|
|
|
143
|
-
`;
|
|
147
|
+
`;g.enqueue(f.encode(S));return}if(h.choices[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){let b=`data: ${JSON.stringify(h)}
|
|
144
148
|
|
|
145
|
-
`;
|
|
146
|
-
`))}else
|
|
147
|
-
`))};try{for(;;){let{done:
|
|
148
|
-
`);i=
|
|
149
|
-
`))}}}catch(
|
|
149
|
+
`;g.enqueue(f.encode(b))}}catch{g.enqueue(f.encode(d+`
|
|
150
|
+
`))}else g.enqueue(f.encode(d+`
|
|
151
|
+
`))};try{for(;;){let{done:d,value:m}=await c.read();if(d){i.trim()&&u(i,l,o);break}let g=t.decode(m,{stream:!0});i+=g;let f=i.split(`
|
|
152
|
+
`);i=f.pop()||"";for(let h of f)if(h.trim())try{p(h,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:b=>r+=b,isReasoningComplete:()=>s,setReasoningComplete:b=>s=b})}catch(b){console.error("Error processing line:",h,b),l.enqueue(o.encode(h+`
|
|
153
|
+
`))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(a,{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 bn,Vi=w(()=>{"use strict";V();bn=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.
|
|
150
154
|
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.
|
|
151
155
|
Examples:
|
|
152
156
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
153
|
-
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 F(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="",i="",a=new ReadableStream({async start(l){let c=e.body.getReader(),u=(
|
|
154
|
-
`);for(let
|
|
155
|
-
`))},
|
|
156
|
-
|
|
157
|
-
`;
|
|
158
|
-
|
|
159
|
-
`;
|
|
160
|
-
`))}else
|
|
161
|
-
`))};try{for(;;){let{done:
|
|
162
|
-
`);i=
|
|
163
|
-
`))}}}catch(
|
|
164
|
-
`);for(let
|
|
165
|
-
`))},m=(
|
|
166
|
-
|
|
167
|
-
`));return}y.choices?.[0]?.delta?.content&&!
|
|
168
|
-
|
|
169
|
-
`;
|
|
170
|
-
|
|
171
|
-
`;
|
|
172
|
-
|
|
173
|
-
`;
|
|
174
|
-
|
|
175
|
-
`;
|
|
176
|
-
`))}}else
|
|
177
|
-
`))};try{for(;;){let{done:
|
|
178
|
-
`);l=
|
|
179
|
-
`))}continue}let
|
|
180
|
-
`);l=
|
|
181
|
-
`))}}}catch(
|
|
182
|
-
`);for(let
|
|
183
|
-
`))},
|
|
184
|
-
|
|
185
|
-
`;
|
|
186
|
-
`))}}else
|
|
187
|
-
`))};try{for(;;){let{done:m,value:
|
|
188
|
-
`);a=
|
|
189
|
-
`))}continue}let
|
|
190
|
-
`);a=
|
|
191
|
-
`))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{u.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var
|
|
192
|
-
`);for(let
|
|
193
|
-
`))},
|
|
194
|
-
|
|
195
|
-
`;
|
|
196
|
-
|
|
197
|
-
`;
|
|
198
|
-
|
|
199
|
-
`;
|
|
200
|
-
`))}}else
|
|
201
|
-
`))};try{for(;;){let{done:
|
|
202
|
-
`);c=
|
|
157
|
+
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 F(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="",i="",a=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,m,g)=>{let f=d.split(`
|
|
158
|
+
`);for(let h of f)h.trim()&&m.enqueue(g.encode(h+`
|
|
159
|
+
`))},p=(d,m)=>{let{controller:g,encoder:f,exitToolIndex:h,setExitToolIndex:b,appendExitToolResponse:_}=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"){b(k.index);return}else if(h()>-1&&k.index===h()&&k.function.arguments){_(k.function.arguments);try{let v=JSON.parse(m.exitToolResponse());y.choices=[{delta:{role:"assistant",content:v.response||""}}];let S=`data: ${JSON.stringify(y)}
|
|
160
|
+
|
|
161
|
+
`;g.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)}
|
|
162
|
+
|
|
163
|
+
`;g.enqueue(f.encode(k))}}catch{g.enqueue(f.encode(d+`
|
|
164
|
+
`))}else g.enqueue(f.encode(d+`
|
|
165
|
+
`))};try{for(;;){let{done:d,value:m}=await c.read();if(d){i.trim()&&u(i,l,o);break}let g=t.decode(m,{stream:!0});i+=g;let f=i.split(`
|
|
166
|
+
`);i=f.pop()||"";for(let h of f)if(h.trim())try{p(h,{controller:l,encoder:o,exitToolIndex:()=>r,setExitToolIndex:b=>r=b,exitToolResponse:()=>s,appendExitToolResponse:b=>s+=b})}catch(b){console.error("Error processing line:",h,b),l.enqueue(o.encode(h+`
|
|
167
|
+
`))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as id}from"uuid";var _n,Qi=w(()=>{"use strict";V();_n=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 F(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="",i=!1,a=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,f,h)=>{let b=g.split(`
|
|
168
|
+
`);for(let _ of b)_.trim()&&f.enqueue(h.encode(_+`
|
|
169
|
+
`))},m=(g,f)=>{let{controller:h,encoder:b}=f;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let _=g.slice(6);try{let y=JSON.parse(_);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:a},"usage"),y.choices[0].finish_reason=a?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"){h.enqueue(b.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
|
|
170
|
+
|
|
171
|
+
`));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)}
|
|
172
|
+
|
|
173
|
+
`;h.enqueue(b.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,E={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:C}}}]};E.choices?.[0]?.delta&&delete E.choices[0].delta.reasoning;let A=`data: ${JSON.stringify(E)}
|
|
174
|
+
|
|
175
|
+
`;h.enqueue(b.encode(A));let P={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,content:x}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content);let M=`data: ${JSON.stringify(P)}
|
|
176
|
+
|
|
177
|
+
`;h.enqueue(b.encode(M));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_${id()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!a&&(a=!0);let v=y.choices?.[0]?.delta,S=v&&Object.keys(v).length>0,T=y.choices?.[0]?.finish_reason,R=y.usage;if(S||T||R){let C=`data: ${JSON.stringify(y)}
|
|
178
|
+
|
|
179
|
+
`;h.enqueue(b.encode(C))}}catch{h.enqueue(b.encode(g+`
|
|
180
|
+
`))}}else h.enqueue(b.encode(g+`
|
|
181
|
+
`))};try{for(;;){let{done:g,value:f}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!f||f.length===0)continue;let h;try{h=t.decode(f,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(h.length===0)continue;if(l+=h,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=l.split(`
|
|
182
|
+
`);l=_.pop()||"";for(let y of _)if(y.trim())try{m(y,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>i,setReasoningComplete:k=>i=k})}catch(k){console.error("Error processing line:",y,k),u.enqueue(o.encode(y+`
|
|
183
|
+
`))}continue}let b=l.split(`
|
|
184
|
+
`);l=b.pop()||"";for(let _ of b)if(_.trim())try{m(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>i,setReasoningComplete:y=>i=y})}catch(y){console.error("Error processing line:",_,y),u.enqueue(o.encode(_+`
|
|
185
|
+
`))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var kn,Yi=w(()=>{"use strict";kn=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}}});import{v4 as ad}from"uuid";var Tn,Xi=w(()=>{"use strict";V();Tn=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 F(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="",i=!1,a="",l=new ReadableStream({async start(c){let u=e.body.getReader(),p=(m,g,f)=>{let h=m.split(`
|
|
186
|
+
`);for(let b of h)b.trim()&&g.enqueue(f.encode(b+`
|
|
187
|
+
`))},d=(m,g)=>{let{controller:f,encoder:h}=g;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let b=m.slice(6);try{let _=JSON.parse(b);if(_.error)throw new Error(JSON.stringify(_));_.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),_.choices?.[0]?.delta?.tool_calls?.length&&_.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${ad()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let y=`data: ${JSON.stringify(_)}
|
|
188
|
+
|
|
189
|
+
`;f.enqueue(h.encode(y))}catch{f.enqueue(h.encode(m+`
|
|
190
|
+
`))}}else f.enqueue(h.encode(m+`
|
|
191
|
+
`))};try{for(;;){let{done:m,value:g}=await u.read();if(m){a.trim()&&p(a,c,o);break}if(!g||g.length===0)continue;let f;try{f=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(f.length===0)continue;if(a+=f,a.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=a.split(`
|
|
192
|
+
`);a=b.pop()||"";for(let _ of b)if(_.trim())try{d(_,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>i,setReasoningComplete:y=>i=y})}catch(y){console.error("Error processing line:",_,y),c.enqueue(o.encode(_+`
|
|
193
|
+
`))}continue}let h=a.split(`
|
|
194
|
+
`);a=h.pop()||"";for(let b of h)if(b.trim())try{d(b,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>i,setReasoningComplete:_=>i=_})}catch(_){console.error("Error processing line:",b,_),c.enqueue(o.encode(b+`
|
|
195
|
+
`))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{u.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var vn,Zi=w(()=>{"use strict";vn=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}}});import cd from"json5";import{jsonrepair as ld}from"jsonrepair";function or(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=cd.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=ld(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 qi=w(()=>{});var xn,ea=w(()=>{"use strict";qi();V();xn=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await F(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=or(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,i="",a=!1,l=!1,c="",u=new ReadableStream({async start(p){let d=e.body.getReader(),m=(h,b,_)=>{let y=h.split(`
|
|
196
|
+
`);for(let k of y)k.trim()&&b.enqueue(_.encode(k+`
|
|
197
|
+
`))},g=(h,b,_)=>{let y="";try{y=or(r.arguments||"",this.logger)}catch(T){console.error(`${T.message} ${T.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"}]},v={...h,choices:[{...h.choices[0],delta:k}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let S=`data: ${JSON.stringify(v)}
|
|
198
|
+
|
|
199
|
+
`;b.enqueue(_.encode(S))},f=(h,b)=>{let{controller:_,encoder:y}=b;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let k=h.slice(6);try{let v=JSON.parse(k);if(v.choices?.[0]?.delta?.tool_calls?.length){let T=v.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:T.index,name:T.function?.name||"",id:T.id||"",arguments:T.function?.arguments||""},T.function?.arguments&&(T.function.arguments="");let R=`data: ${JSON.stringify(v)}
|
|
200
|
+
|
|
201
|
+
`;_.enqueue(y.encode(R));return}else if(r.index===T.index){T.function?.arguments&&(r.arguments+=T.function.arguments);return}else{g(v,_,y),r={index:T.index,name:T.function?.name||"",id:T.id||"",arguments:T.function?.arguments||""};return}}if(v.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){g(v,_,y),r={};return}v.choices?.[0]?.delta?.tool_calls?.length&&b.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let S=`data: ${JSON.stringify(v)}
|
|
202
|
+
|
|
203
|
+
`;_.enqueue(y.encode(S))}catch{_.enqueue(y.encode(h+`
|
|
204
|
+
`))}}else _.enqueue(y.encode(h+`
|
|
205
|
+
`))};try{for(;;){let{done:h,value:b}=await d.read();if(h){c.trim()&&m(c,p,o);break}if(!b||b.length===0)continue;let _;try{_=t.decode(b,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(_.length===0)continue;if(c+=_,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
|
|
206
|
+
`);c=k.pop()||"";for(let v of k)if(v.trim())try{f(v,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:S=>s=S,reasoningContent:()=>i,appendReasoningContent:S=>i+=S,isReasoningComplete:()=>a,setReasoningComplete:S=>a=S})}catch(S){console.error("Error processing line:",v,S),p.enqueue(o.encode(v+`
|
|
203
207
|
`))}continue}let y=c.split(`
|
|
204
|
-
`);c=y.pop()||"";for(let
|
|
205
|
-
`))}}}catch(
|
|
206
|
-
`);for(let
|
|
207
|
-
`))},
|
|
208
|
+
`);c=y.pop()||"";for(let k of y)if(k.trim())try{f(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>i,appendReasoningContent:v=>i+=v,isReasoningComplete:()=>a,setReasoningComplete:v=>a=v})}catch(v){console.error("Error processing line:",k,v),p.enqueue(o.encode(k+`
|
|
209
|
+
`))}}}catch(h){console.error("Stream error:",h),p.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}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 Sn,ta=w(()=>{"use strict";V();Ke();Sn=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??un(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 F(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,i="",a=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,m,g)=>{let f=d.split(`
|
|
210
|
+
`);for(let h of f)h.trim()&&m.enqueue(g.encode(h+`
|
|
211
|
+
`))},p=(d,m)=>{let{controller:g,encoder:f}=m;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let h=JSON.parse(d.slice(6));if(console.log(JSON.stringify(h)),h.choices?.[0]?.delta?.reasoning_content){m.appendReasoningContent(h.choices[0].delta.reasoning_content);let b={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,thinking:{content:h.choices[0].delta.reasoning_content}}}]};delete b.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(b)}
|
|
208
212
|
|
|
209
|
-
`;
|
|
213
|
+
`;g.enqueue(f.encode(_));return}if(h.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let b="ccr_think_signature",_=h.choices[0].delta.content,y={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:b}}}]};delete y.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(y)}
|
|
210
214
|
|
|
211
|
-
`;
|
|
215
|
+
`;g.enqueue(f.encode(k))}if(h.choices?.[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){m.isReasoningComplete()&&h.choices[0].index++;let b=`data: ${JSON.stringify(h)}
|
|
212
216
|
|
|
213
|
-
`;
|
|
214
|
-
`))}else
|
|
215
|
-
`))};try{for(;;){let{done:
|
|
216
|
-
`);i=
|
|
217
|
-
`))}}}catch(
|
|
217
|
+
`;g.enqueue(f.encode(b))}}catch{g.enqueue(f.encode(d+`
|
|
218
|
+
`))}else g.enqueue(f.encode(d+`
|
|
219
|
+
`))};try{for(;;){let{done:d,value:m}=await c.read();if(d){i.trim()&&u(i,l,o);break}let g=t.decode(m,{stream:!0});i+=g;let f=i.split(`
|
|
220
|
+
`);i=f.pop()||"";for(let h of f)if(h.trim())try{p(h,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:b=>r+=b,isReasoningComplete:()=>s,setReasoningComplete:b=>s=b})}catch(b){console.error("Error processing line:",h,b),l.enqueue(o.encode(h+`
|
|
221
|
+
`))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Cn,na=w(()=>{"use strict";Cn=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 Rn,oa=w(()=>{"use strict";Rn=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ra(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,i=r.role==="assistant",a=[];typeof r.content=="string"?a.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(l=>{l.type==="text"?a.push({type:"text",text:l.text||""}):l.type==="image_url"&&a.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&a.length===0&&!r.tool_calls&&!r.content)&&(s&&i&&a.length===0&&r.tool_calls&&a.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:a}))}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(i=>i.type==="text"?{type:"text",text:i.text||""}:i.type==="image"&&i.source?{type:"image_url",image_url:{url:i.source.data},media_type:i.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function ia(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:JSON.stringify(i.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(a,l)=>{if(a.startsWith("data: ")){let c=a.slice(6).trim();if(c){t?.debug({chunkStr:c},`${e} chunk:`);try{let u=JSON.parse(c);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let 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)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
218
222
|
|
|
219
|
-
`))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let
|
|
223
|
+
`))}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)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
220
224
|
|
|
221
|
-
`))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let
|
|
225
|
+
`))}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)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
222
226
|
|
|
223
|
-
`))}else if(u.type==="message_delta"){let
|
|
227
|
+
`))}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)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
224
228
|
|
|
225
229
|
`))}else if(u.type==="message_stop")l.enqueue(r.encode(`data: [DONE]
|
|
226
230
|
|
|
227
|
-
`));else{let
|
|
231
|
+
`));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)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
228
232
|
|
|
229
|
-
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,c,u.message)}}}},i=new ReadableStream({async start(a){let l=n.body.getReader(),c="";try{for(;;){let{done:u,value:
|
|
230
|
-
`);c=
|
|
233
|
+
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,c,u.message)}}}},i=new ReadableStream({async start(a){let l=n.body.getReader(),c="";try{for(;;){let{done:u,value:p}=await l.read();if(u){c&&s(c,a);break}c+=o.decode(p,{stream:!0});let d=c.split(`
|
|
234
|
+
`);c=d.pop()||"";for(let m of d)s(m,a)}}catch(u){a.error(u)}finally{a.close()}}});return new Response(i,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var aa=w(()=>{"use strict"});async function ud(){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:
|
|
231
235
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
232
236
|
2. Run "gcloud auth application-default login"
|
|
233
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
234
|
-
`);for(let
|
|
235
|
-
`))},m=(
|
|
237
|
+
3. Use Google Cloud environment with default service account`)}}var wn,ca=w(()=>{"use strict";aa();wn=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 a=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(a);l&&l.project_id&&(o=l.project_id)}catch(i){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await ud();return{body:ra(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 ia(e,this.name,this.logger)}}});var Pn,la=w(()=>{"use strict";Pn=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 En,ua=w(()=>{"use strict";En=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var An,da=w(()=>{"use strict";An=class{name="OpenAI";endPoint="/v1/chat/completions"}});var On,pa=w(()=>{"use strict";On=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}}});import{v4 as dd}from"uuid";var In,fa=w(()=>{"use strict";V();In=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 F(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="",i=!1,a=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,f,h)=>{let b=g.split(`
|
|
238
|
+
`);for(let _ of b)_.trim()&&f.enqueue(h.encode(_+`
|
|
239
|
+
`))},m=(g,f)=>{let{controller:h,encoder:b}=f;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let _=g.slice(6);try{let y=JSON.parse(_);if(y.usage&&(this.logger?.debug({usage:y.usage,hasToolCall:a},"usage"),y.choices[0].finish_reason=a?"tool_calls":"stop"),y.choices?.[0]?.finish_reason==="error"&&h.enqueue(b.encode(`data: ${JSON.stringify({error:y.choices?.[0].error})}
|
|
236
240
|
|
|
237
|
-
`)),y.choices?.[0]?.delta?.content&&!
|
|
241
|
+
`)),y.choices?.[0]?.delta?.content&&!f.hasTextContent()&&f.setHasTextContent(!0),y.choices?.[0]?.delta?.reasoning){f.appendReasoningContent(y.choices[0].delta.reasoning);let v={...y,choices:[{...y.choices?.[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let S=`data: ${JSON.stringify(v)}
|
|
238
242
|
|
|
239
|
-
`;
|
|
243
|
+
`;h.enqueue(b.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 T=`data: ${JSON.stringify(S)}
|
|
240
244
|
|
|
241
|
-
`;
|
|
245
|
+
`;h.enqueue(b.encode(T))}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(v=>{v.id=`call_${dd()}`}),y.choices?.[0]?.delta?.tool_calls?.length&&!a&&(a=!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)}
|
|
242
246
|
|
|
243
|
-
`;
|
|
244
|
-
`))}}else
|
|
245
|
-
`))};try{for(;;){let{done:
|
|
246
|
-
`);l=
|
|
247
|
-
`))}continue}let
|
|
248
|
-
`);l=
|
|
249
|
-
`))}}}catch(
|
|
247
|
+
`;h.enqueue(b.encode(k))}catch{h.enqueue(b.encode(g+`
|
|
248
|
+
`))}}else h.enqueue(b.encode(g+`
|
|
249
|
+
`))};try{for(;;){let{done:g,value:f}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!f||f.length===0)continue;let h;try{h=t.decode(f,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(h.length===0)continue;if(l+=h,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=l.split(`
|
|
250
|
+
`);l=_.pop()||"";for(let y of _)if(y.trim())try{m(y,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>i,setReasoningComplete:k=>i=k})}catch(k){console.error("Error processing line:",y,k),u.enqueue(o.encode(y+`
|
|
251
|
+
`))}continue}let b=l.split(`
|
|
252
|
+
`);l=b.pop()||"";for(let _ of b)if(_.trim())try{m(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>i,setReasoningComplete:y=>i=y})}catch(y){console.error("Error processing line:",_,y),u.enqueue(o.encode(_+`
|
|
253
|
+
`))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var rr,pd,Mn,ma=w(()=>{"use strict";V();rr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
250
254
|
|
|
251
255
|
Output format:
|
|
252
256
|
<reasoning_content>
|
|
253
257
|
Your detailed thinking process goes here
|
|
254
258
|
</reasoning_content>
|
|
255
|
-
Your final answer must follow after the closing tag above.`,
|
|
256
|
-
${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:
|
|
259
|
+
Your final answer must follow after the closing tag above.`,pd=10,Mn=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<pd)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
|
|
260
|
+
${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:rr}):o.content=[{type:"text",text:rr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:rr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await F(e);if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,i=r.choices[0]?.message.content.match(s);i&&i[1]&&(r.thinking={content:i[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,i=new TextEncoder,a=new ReadableStream({async start(l){let c=e.body.getReader(),u="",p="SEARCHING",d="",m="",g=(f,h)=>{if(typeof h!="string"){f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0&&!f.choices[0].delta.content&&(f.choices[0].index=r,l.enqueue(i.encode(`data: ${JSON.stringify(f)}
|
|
257
261
|
|
|
258
|
-
`)));return}let
|
|
262
|
+
`)));return}let b=d+h;for(d="";b.length>0;)if(p==="SEARCHING"){let _=b.indexOf(t);if(_!==-1)b=b.substring(_+t.length),p="REASONING";else{for(let y=t.length-1;y>0;y--)if(b.endsWith(t.substring(0,y))){d=b.substring(b.length-y);break}b=""}}else if(p==="REASONING"){let _=b.indexOf(o);if(_!==-1){let y=b.substring(0,_);if(y.length>0){let S={...f.choices[0].delta,thinking:{content:y}};delete S.content;let T={...f,choices:[{...f.choices[0],delta:S,index:r}]};l.enqueue(i.encode(`data: ${JSON.stringify(T)}
|
|
259
263
|
|
|
260
|
-
`))}let
|
|
264
|
+
`))}let k={...f.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let v={...f,choices:[{...f.choices[0],delta:k,index:r}]};l.enqueue(i.encode(`data: ${JSON.stringify(v)}
|
|
261
265
|
|
|
262
|
-
`)),r++,
|
|
266
|
+
`)),r++,b=b.substring(_+o.length),p="FINAL"}else{let y=b;for(let k=o.length-1;k>0;k--)if(b.endsWith(o.substring(0,k))){d=b.substring(b.length-k),y=b.substring(0,b.length-k);break}if(y.length>0){let k={...f.choices[0].delta,thinking:{content:y}};delete k.content;let v={...f,choices:[{...f.choices[0],delta:k,index:r}]};l.enqueue(i.encode(`data: ${JSON.stringify(v)}
|
|
263
267
|
|
|
264
|
-
`))}
|
|
268
|
+
`))}b=""}}else if(p==="FINAL"){if(b.length>0)if(/^\s*$/.test(b))m+=b;else{let y=m+b,k={...f.choices[0].delta,content:y};k.thinking&&delete k.thinking;let v={...f,choices:[{...f.choices[0],delta:k}]};l.enqueue(i.encode(`data: ${JSON.stringify(v)}
|
|
265
269
|
|
|
266
|
-
`)),m=""}r++,
|
|
267
|
-
`);u=
|
|
270
|
+
`)),m=""}r++,b=""}};try{for(;;){let{done:f,value:h}=await c.read();if(f)break;let b=s.decode(h,{stream:!0});u+=b;let _=u.split(`
|
|
271
|
+
`);u=_.pop()||"";for(let y of _)if(y.trim()){if(y.trim()==="data: [DONE]"){l.enqueue(i.encode(y+`
|
|
268
272
|
|
|
269
|
-
`));break}if(y.startsWith("data:"))try{let
|
|
273
|
+
`));break}if(y.startsWith("data:"))try{let k=JSON.parse(y.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{l.enqueue(i.encode(y+`
|
|
270
274
|
`))}else l.enqueue(i.encode(y+`
|
|
271
|
-
`))}}}catch(
|
|
275
|
+
`))}}}catch(f){console.error("Stream error:",f),l.error(f)}finally{try{c.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}if(p==="REASONING"){let h={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(i.encode(`data: ${JSON.stringify(h)}
|
|
272
276
|
|
|
273
|
-
`))}l.close()}}});return new Response(a,{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
|
|
274
|
-
`));break}let
|
|
275
|
-
`);i=m.pop()||"";for(let
|
|
277
|
+
`))}l.close()}}});return new Response(a,{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 Ln,ga=w(()=>{"use strict";V();Ln=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",i="",a=new ReadableStream({async start(l){let c=e.body.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u){i.trim()&&l.enqueue(r.encode(i+`
|
|
278
|
+
`));break}let d=o.decode(p,{stream:!0});i+=d;let m=i.split(`
|
|
279
|
+
`);i=m.pop()||"";for(let g of m)if(g.trim())if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let f=JSON.parse(g.slice(6));if(f.choices?.[0]?.delta?.reasoning_content){s+=f.choices[0].delta.reasoning_content;let h={...f,choices:[{...f.choices[0],delta:{thinking:{content:f.choices[0].delta.reasoning_content}}}]};delete h.choices[0].delta.reasoning_content,l.enqueue(r.encode(`data: ${JSON.stringify(h)}
|
|
276
280
|
|
|
277
|
-
`));continue}if(
|
|
281
|
+
`));continue}if(f.choices?.[0]?.delta?.content&&s&&!f.choices[0]?.delta?.reasoning_content){let h=Date.now().toString(),b={...f,choices:[{...f.choices[0],delta:{content:null,thinking:{content:s,signature:h}}}]};l.enqueue(r.encode(`data: ${JSON.stringify(b)}
|
|
278
282
|
|
|
279
|
-
`)),s=""}
|
|
283
|
+
`)),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&&l.enqueue(r.encode(`data: ${JSON.stringify(f)}
|
|
280
284
|
|
|
281
|
-
`))}catch{l.enqueue(r.encode(
|
|
282
|
-
`))}else l.enqueue(r.encode(
|
|
283
|
-
`))}}catch(u){l.error(u)}finally{try{c.releaseLock()}catch{}l.close()}}});return new Response(a,{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 F(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}}});import{v4 as
|
|
284
|
-
`);for(let
|
|
285
|
-
`))},m=(
|
|
285
|
+
`))}catch{l.enqueue(r.encode(g+`
|
|
286
|
+
`))}else l.enqueue(r.encode(g+`
|
|
287
|
+
`))}}catch(u){l.error(u)}finally{try{c.releaseLock()}catch{}l.close()}}});return new Response(a,{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 F(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}}});import{v4 as ha}from"uuid";var $n,ya=w(()=>{"use strict";V();Fe();$n=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=i=>{let a=Object.keys(r).find(c=>c.toLowerCase()===i),l=a?r[a]:void 0;return typeof l=="string"&&l.trim()?l.trim():void 0};return s("x-opencode-session")||o?.clientContext?.stableSessionId||o?.sessionId||he(e.metadata?.user_id)||s("session_id")||ha()}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(i=>{i.type==="image_url"&&(i.image_url.url.startsWith("http")||(i.image_url.url=`data:${i.media_type};base64,${i.image_url.url}`),delete i.media_type)}),s.role==="assistant"){let i=s.thinking?.content,a=s.thinking?.signature;i&&typeof i=="string"&&i.trim()?(s.reasoning_content=i,a&&(s.reasoning_content_signature=a)):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 F(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="",i=!1,a=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,f,h)=>{let b=g.split(`
|
|
288
|
+
`);for(let _ of b)_.trim()&&f.enqueue(h.encode(_+`
|
|
289
|
+
`))},m=(g,f)=>{let{controller:h,encoder:b}=f;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let _=JSON.parse(g.slice(6));if(_.usage&&(_.choices[0].finish_reason=a?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){h.enqueue(b.encode(`data: ${JSON.stringify({error:_.choices?.[0]?.error})}
|
|
286
290
|
|
|
287
|
-
`));return}
|
|
291
|
+
`));return}_.choices?.[0]?.delta?.content&&!f.hasTextContent()&&f.setHasTextContent(!0);let y=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(y){f.appendReasoningContent(y);let R={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:y}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),h.enqueue(b.encode(`data: ${JSON.stringify(R)}
|
|
288
292
|
|
|
289
|
-
`));return}if(
|
|
293
|
+
`));return}if(_.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let R="ccr_think_signature",C=_.choices[0].delta.content,x={..._,choices:[{..._.choices?.[0],delta:{..._.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),h.enqueue(b.encode(`data: ${JSON.stringify(x)}
|
|
290
294
|
|
|
291
|
-
`));let
|
|
295
|
+
`));let E={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:C}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content),h.enqueue(b.encode(`data: ${JSON.stringify(E)}
|
|
292
296
|
|
|
293
|
-
`));return}
|
|
297
|
+
`));return}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${ha()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!a&&(a=!0);let k=_.choices?.[0]?.delta,v=k&&Object.keys(k).length>0,S=_.choices?.[0]?.finish_reason,T=_.usage;(v||S||T)&&h.enqueue(b.encode(`data: ${JSON.stringify(_)}
|
|
294
298
|
|
|
295
|
-
`))}catch{
|
|
296
|
-
`))}else
|
|
297
|
-
`))};try{for(;;){let{done:
|
|
298
|
-
`);l=
|
|
299
|
-
`))}continue}let
|
|
300
|
-
`);l=
|
|
301
|
-
`))}}}catch(
|
|
299
|
+
`))}catch{h.enqueue(b.encode(g+`
|
|
300
|
+
`))}else h.enqueue(b.encode(g+`
|
|
301
|
+
`))};try{for(;;){let{done:g,value:f}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!f||f.length===0)continue;let h;try{h=t.decode(f,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(h.length===0)continue;if(l+=h,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=l.split(`
|
|
302
|
+
`);l=_.pop()||"";for(let y of _)if(y.trim())try{m(y,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>i,setReasoningComplete:k=>i=k})}catch(k){console.error("Error processing line:",y,k),u.enqueue(o.encode(y+`
|
|
303
|
+
`))}continue}let b=l.split(`
|
|
304
|
+
`);l=b.pop()||"";for(let _ of b)if(_.trim())try{m(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:y=>r=y,reasoningContent:()=>s,appendReasoningContent:y=>s+=y,isReasoningComplete:()=>i,setReasoningComplete:y=>i=y})}catch(y){console.error("Error processing line:",_,y),u.enqueue(o.encode(_+`
|
|
305
|
+
`))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function md(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 gd(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 fd,Nn,ba=w(()=>{"use strict";Ke();fd={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Nn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=md(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=gd(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 i=ye(o);r==="chat"?e.reasoning_effort=i:e.reasoning={enabled:!0,effort:i}}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=fd[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 _a(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 Dn,ka=w(()=>{"use strict";Ke();V();Dn=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"),i=!r&&!s&&o.includes("deepseek");if(e==="none")return i||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return i?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return i?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,i=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,i=i||r.effort==="none"):typeof r?.max_tokens=="number"?s=ye(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!i&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(i=!0));let a=this.resolveEffort(i?"none":s,o);return a?t.reasoning_effort=a: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 de(e);if(o){let i=new Headers(e.headers);if(o.isSSE&&i.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:i}),o.isSSE)return this.transformStream(e)}else{let i=await me(e);if(e=i.response,i.isSSE)return this.transformStream(e)}let r=await F(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)_a(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=c=>{if(!c.startsWith("data:"))return c;let u=c.slice(5).trim();if(u==="[DONE]")return c;let p;try{p=JSON.parse(u)}catch{return c}let d=!1,m=Array.isArray(p?.choices)?p.choices:[];for(let g of m)_a(g?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:c},i=(c,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,m,g="";for(;(m=p.exec(r))!==null&&!(!u&&m[0]==="\r"&&p.lastIndex===r.length);)g+=s(r.slice(d,m.index))+m[0],d=p.lastIndex;r=r.slice(d),u&&(g+=s(r),r=""),g&&c.enqueue(o.encode(g))},a=e.body.pipeThrough(new TransformStream({transform(c,u){r+=t.decode(c,{stream:!0}),i(u)},flush(c){r+=t.decode(),i(c,!0)}})),l=new Headers(e.headers);return l.delete("content-length"),new Response(a,{status:e.status,statusText:e.statusText,headers:l})}}});var Ta,va=w(()=>{Ji();Wi();Ki();Gi();Vi();Qi();Yi();Xi();Zi();ea();ta();na();oa();ca();la();ua();da();pa();fa();Bo();ma();ga();ya();ba();ka();Ta={AnthropicTransformer:dn,GeminiTransformer:gn,VertexGeminiTransformer:hn,VertexClaudeTransformer:wn,DeepseekTransformer:yn,TooluseTransformer:bn,OpenrouterTransformer:_n,OpenAITransformer:An,MaxTokenTransformer:kn,GroqTransformer:Tn,CleancacheTransformer:vn,EnhanceToolTransformer:xn,ReasoningTransformer:Sn,SamplingTransformer:Cn,MaxCompletionTokens:Rn,CerebrasTransformer:Pn,StreamOptionsTransformer:En,CustomParamsTransformer:On,VercelTransformer:In,OpenAIResponsesTransformer:$e,ForceReasoningTransformer:Mn,KimiTransformer:Ln,OpenCodeTransformer:$n,DefaultThinkingTransformer:Nn,AmdTransformer:Dn}});var Ve,sr=w(()=>{"use strict";va();Ve=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=ot(ot.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})
|
|
302
306
|
error: ${t.message}
|
|
303
307
|
stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
304
|
-
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Fi).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)}}});import{get_encoding as fu}from"tiktoken";var lt,ji=E(()=>{"use strict";lt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=fu(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)}}});import{join as xn}from"path";import{homedir as mu}from"os";import{existsSync as jo,mkdirSync as gu}from"fs";import{promises as Cn}from"fs";import{Tokenizer as hu}from"@huggingface/tokenizers";var Sn,Hi=E(()=>{"use strict";Sn=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||xn(mu(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=xn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:xn(e,"tokenizer.json"),tokenizerConfig:xn(e,"tokenizer_config.json")}}ensureDir(e){jo(e)||gu(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!jo(e.tokenizerJson)||!jo(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Cn.readFile(e.tokenizerJson,"utf-8"),Cn.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([Cn.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),Cn.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 hu(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 Rn,zi=E(()=>{"use strict";oe();Rn=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=G(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 Je,Ho=E(()=>{"use strict";ji();Hi();zi();oe();Je=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 lt("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 lt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Sn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Rn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return ce(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 Bi(n){if(!n||typeof n!="object"||xu(n))return null;for(let t of vu(n)){let o=Tu(t);if(o)return o}return null}function Tu(n){if(!n||typeof n!="object")return null;let e={},t=wn(n,yu);if(t!==void 0){let i=Ji(t);e.usedDailyBalance=i,e.limitDaily=100}let o=wn(n,_u);if(o!==void 0){let i=Ji(o);e.usedBalance=i,e.totalBalance=100}let r=wn(n,ku);if(r!==void 0){let i=Wi(r);i&&(e.resetTime=i)}let s=wn(n,bu);if(s!==void 0){let i=Wi(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 Ji(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function wn(n,e){for(let t of e){let o=I(n?.[t]);if(o!==void 0)return o}}function vu(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 xu(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 Wi(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 qo(n){let e=er(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Au:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Iu:e==="deepseek.com"||e.endsWith(".deepseek.com")?Cu:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Su:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Ru:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?wu:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Eu:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Pu:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Ou:null:null}function Mu(n){let e=er(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Nu(n,e){let t=Xo(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 Xo(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Xo(e)):Object.values(n).flatMap(e=>Xo(e))}function Zo(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function er(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function I(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 se,zo,Bo,Jo,Wo,Ko,yu,_u,ku,bu,Go,Vo,Qo,Yo,Cu,Su,Ru,wu,Eu,Pu,Ou,Au,Iu,tr=E(()=>{"use strict";oe();se=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=G(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}},zo=class extends se{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=>I(l?.total_balance)!==void 0);if(!i)return null;let a=I(i.total_balance);return a===void 0?null:{totalBalance:a,currency:typeof i.currency=="string"?i.currency:void 0}}},Bo=class extends se{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=I(s.limit),l=I(s.limit_remaining),c=I(s.usage),u=I(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}},Jo=class extends se{async queryQuota(e,t,o){let r=Mu(e.baseUrl),i=(await this.fetchJson(r,e,t,o))?.data;if(!i||typeof i!="object")return null;let a={},l=I(i.totalBalance),c=I(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}},Wo=class extends se{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=G(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=I(c.currentValue),h=I(c.usage),g=I(c.remaining),f=I(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=I(u.currentValue),h=I(u.usage),g=I(u.remaining),f=I(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=I(d.currentValue);m!==void 0&&(p.usedDailyBalance=m)}if(p.limitDaily===void 0){let m=I(d.usage),h=I(d.currentValue),g=I(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}}},Ko=class extends se{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=G(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=I(u.per5HourUsedQuota),m=I(u.per5HourTotalQuota);p!==void 0&&(d.usedDailyBalance=p),m!==void 0&&(d.limitDaily=m);let h=I(u.perWeekUsedQuota),g=I(u.perWeekTotalQuota);return h!==void 0&&(d.usedBalance=h),g!==void 0&&(d.totalBalance=g),this.hasQuotaData(d)?d:null}catch{return null}}};yu=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],_u=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],ku=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],bu=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Go=class extends se{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=Zo(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=G(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 Bi(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=G(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 Bi(c)}catch{return null}}},Vo=class extends se{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:(Zo(e.quotaToken,"atp-auth-token")||Zo(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(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=Nu(a,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},d=I(c.rp5hUsage),p=I(c.rp5hLimit);d!==void 0&&(u.usedDailyBalance=d),p!==void 0&&(u.limitDaily=p);let m=I(c.rpwUsage),h=I(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}}},Qo=class extends se{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=G(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=I(d.limit),m=I(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=I(u.limit),p=I(u.remaining),m=I(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}}},Yo=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=er(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=I(u.current_interval_total_count),m=I(u.current_interval_usage_count),h=I(u.current_interval_remaining_percent),g=I(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=I(u.current_weekly_total_count),_=I(u.current_weekly_usage_count),k=I(u.current_weekly_remaining_percent),y=I(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}}},Cu=new zo,Su=new Bo,Ru=new Jo,wu=new Wo,Eu=new Ko,Pu=new Go,Ou=new Vo,Au=new Qo,Iu=new Yo});function Ki(n){return{[$u]:n,[Lu]:It}}function Fu(n){return n===!0||n==="true"||n===1||n==="1"}function Uu(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 ju(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 Hu(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function nr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o)),s=ju(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=G(t));let a=await fetch(s,i);if(a.headers&&qe(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 zu(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",...Ki("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=G(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 Bu(n,e,t,o,r){let s=n.baseUrl,i=n.baseUrl.includes("/messages")||e.includes("claude");try{let a={"Content-Type":"application/json",...Ki("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=G(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 Gi(n,e,t,o,r){return ye||(ye=new En(n,e,t,o,r)),ye}function We(n,e,t,o,r){let s=Gi(n,e,t,o,r);return s.start(),s}function or(){ye&&ye.stop()}function Pn(){ye&&(ye.stop(),ye=null)}var $u,Lu,Du,En,ye,On=E(()=>{"use strict";re();Oe();tr();Me();ao();oe();$u="x-claude-code-router-source",Lu="x-claude-code-router-version";Du={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};En=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={...Du,...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=U();if(e.length===0)return;let o=[];for(let s of e){let i=qo(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){Eo(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`))}}})}),Hu(s.baseUrl)&&o.push({provider:s.name,models:a,type:"rate-limit-headers",promise:nr(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=U(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>nr(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=U(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[i,...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 Bu(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=Uu(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}`),zu(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?Fu(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 nr(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)U().recordSuccess(o.name,a);else for(let a of i)U().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}}},ye=null});var Vi=E(()=>{"use strict"});var rr,ut,Qi=E(()=>{"use strict";rr=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()}},ut=new rr});var ae,sr=E(()=>{"use strict";ae=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
305
|
-
`);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 Ke,ir=E(()=>{"use strict";Ke=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
308
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Ta).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)}}});import{get_encoding as hd}from"tiktoken";var yt,xa=w(()=>{"use strict";yt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=hd(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=l.content;if(Array.isArray(c))for(let u of c)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof c=="string"?c:JSON.stringify(c);o+=t.encode(u).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)}}});import{join as Fn}from"path";import{homedir as yd}from"os";import{existsSync as ir,mkdirSync as bd}from"fs";import{promises as Un}from"fs";import{Tokenizer as _d}from"@huggingface/tokenizers";var jn,Sa=w(()=>{"use strict";jn=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||Fn(yd(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Fn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Fn(e,"tokenizer.json"),tokenizerConfig:Fn(e,"tokenizer_config.json")}}ensureDir(e){ir(e)||bd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!ir(e.tokenizerJson)||!ir(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Un.readFile(e.tokenizerJson,"utf-8"),Un.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([Un.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),Un.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 _d(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)if(a.type==="text"&&a.text)t.push(a.text);else if(a.type==="tool_use"&&a.input)t.push(JSON.stringify(a.input));else if(a.type==="tool_result")if(Array.isArray(a.content))for(let l of a.content)l?.type!=="image"&&t.push(l?.type==="text"?String(l.text??""):JSON.stringify(l));else 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 Hn,Ca=w(()=>{"use strict";q();Hn=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=K(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"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
|
|
309
|
+
`):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 Qe,ar=w(()=>{"use strict";xa();Sa();Ca();q();Qe=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 yt("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 yt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new jn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Hn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return ue(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 Ra(n){if(!n||typeof n!="object"||Rd(n))return null;for(let t of Cd(n)){let o=Sd(t);if(o)return o}return null}function Sd(n){if(!n||typeof n!="object")return null;let e={},t=zn(n,kd);if(t!==void 0){let i=wa(t);e.usedDailyBalance=i,e.limitDaily=100}let o=zn(n,Td);if(o!==void 0){let i=wa(o);e.usedBalance=i,e.totalBalance=100}let r=zn(n,vd);if(r!==void 0){let i=Pa(r);i&&(e.resetTime=i)}let s=zn(n,xd);if(s!==void 0){let i=Pa(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 wa(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function zn(n,e){for(let t of e){let o=I(n?.[t]);if(o!==void 0)return o}}function Cd(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 Rd(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 Pa(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 _r(n){let e=kr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Ld:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?$d:e==="deepseek.com"||e.endsWith(".deepseek.com")?wd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Pd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Ed:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Ad:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Od:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Id:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Md:null:null}function Nd(n){let e=kr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Dd(n,e){let t=yr(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 yr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>yr(e)):Object.values(n).flatMap(e=>yr(e))}function br(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function kr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function I(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 se,cr,lr,ur,dr,pr,kd,Td,vd,xd,fr,mr,gr,hr,wd,Pd,Ed,Ad,Od,Id,Md,Ld,$d,Tr=w(()=>{"use strict";q();se=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=K(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}},cr=class extends se{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=>I(l?.total_balance)!==void 0);if(!i)return null;let a=I(i.total_balance);return a===void 0?null:{totalBalance:a,currency:typeof i.currency=="string"?i.currency:void 0}}},lr=class extends se{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=I(s.limit),l=I(s.limit_remaining),c=I(s.usage),u=I(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}},ur=class extends se{async queryQuota(e,t,o){let r=Nd(e.baseUrl),i=(await this.fetchJson(r,e,t,o))?.data;if(!i||typeof i!="object")return null;let a={},l=I(i.totalBalance),c=I(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}},dr=class extends se{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let 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,p=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"&&(p=m);let d={};if(c){let m=I(c.currentValue),g=I(c.usage),f=I(c.remaining),h=I(c.percentage);m!==void 0?d.usedDailyBalance=m:h!==void 0&&(d.usedDailyBalance=h,d.limitDaily=100),g!==void 0?d.limitDaily=g:m!==void 0&&f!==void 0&&(d.limitDaily=m+f),c.nextResetTime&&(d.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let m=I(u.currentValue),g=I(u.usage),f=I(u.remaining),h=I(u.percentage);m!==void 0?d.usedBalance=m:h!==void 0&&(d.usedBalance=h,d.totalBalance=100),g!==void 0?d.totalBalance=g: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=I(p.currentValue);m!==void 0&&(d.usedDailyBalance=m)}if(d.limitDaily===void 0){let m=I(p.usage),g=I(p.currentValue),f=I(p.remaining);m!==void 0?d.limitDaily=m:g!==void 0&&f!==void 0&&(d.limitDaily=g+f)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},pr=class extends se{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=K(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 p={},d=I(u.per5HourUsedQuota),m=I(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),m!==void 0&&(p.limitDaily=m);let g=I(u.perWeekUsedQuota),f=I(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),f!==void 0&&(p.totalBalance=f),this.hasQuotaData(p)?p:null}catch{return null}}};kd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Td=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],vd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],xd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];fr=class extends se{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=br(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=K(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,c);if(!u.ok)return null;let p=await u.json();return Ra(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"}}}),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=K(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 Ra(c)}catch{return null}}},mr=class extends se{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:(br(e.quotaToken,"atp-auth-token")||br(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(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=Dd(a,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},p=I(c.rp5hUsage),d=I(c.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let m=I(c.rpwUsage),g=I(c.rpwLimit);return m!==void 0&&(u.usedBalance=m),g!==void 0&&(u.totalBalance=g),u.remainingBalance===void 0&&g!==void 0&&m!==void 0&&(u.remainingBalance=Math.max(0,g-m)),this.hasQuotaData(u)?u:null}catch{return null}}},gr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let 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 p=c[0].detail,d=I(p.limit),m=I(p.remaining),g=p.resetTime;d!==void 0&&m!==void 0&&(l.usedDailyBalance=Math.max(0,d-m),l.limitDaily=d),g&&(l.resetTime=new Date(g).toISOString())}let u=a?.usage;if(u){let p=I(u.limit),d=I(u.remaining),m=I(u.used),g=u.resetTime;p!==void 0&&(l.totalBalance=p,m!==void 0?l.usedBalance=m:d!==void 0&&(l.usedBalance=Math.max(0,p-d),l.remainingBalance=d)),g&&(l.resetTime7d=new Date(g).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},hr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=kr(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 k of a)if(l=await this.fetchJson(k,e,t,o,r.trim()),l)break;if(!l)return null;if(l?.base_resp){let k=l.base_resp.status_code;if(k!==void 0&&k!==0)return null}let c=Array.isArray(l?.model_remains)?l.model_remains:[];if(c.length===0)return null;let u=c[0],p={},d=I(u.current_interval_total_count),m=I(u.current_interval_usage_count),g=I(u.current_interval_remaining_percent),f=I(u.end_time);d!==void 0&&m!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-m),p.limitDaily=d):g!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-g)),f&&(p.resetTime=new Date(f).toISOString());let h=I(u.current_weekly_total_count),b=I(u.current_weekly_usage_count),_=I(u.current_weekly_remaining_percent),y=I(u.weekly_end_time);return h!==void 0&&b!==void 0&&h>0?(p.usedBalance=Math.max(0,h-b),p.remainingBalance=b,p.totalBalance=h):_!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-_),p.remainingBalance=_),y&&!p.resetTime&&(p.resetTime=new Date(y).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},wd=new cr,Pd=new lr,Ed=new ur,Ad=new dr,Od=new pr,Id=new fr,Md=new mr,Ld=new gr,$d=new hr});function Ea(n){return{[Fd]:n,[Ud]:Vt}}function Re(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function Hd(n){return n===!0||n==="true"||n===1||n==="1"}function zd(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 Bd(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 Jd(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function vr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Re(n))return{success:!1,skipped:!0,error:xr,latencyMs:r()};let s=Bd(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=K(t));let a=await fetch(s,i);if(a.headers&&it(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 Wd(n,e,t,o){if(Re(n))return{success:!1,skipped:!0,error:xr};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",...Ea("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=K(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 Kd(n,e,t,o,r){if(Re(n))return{success:!1,skipped:!0,error:xr};let s=n.baseUrl,i=n.baseUrl.includes("/messages")||e.includes("claude");try{let a={"Content-Type":"application/json",...Ea("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=K(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 Aa(n,e,t,o,r,s){return be||(be=new Bn(n,e,t,o,r,s)),be}function bt(n,e,t,o,r,s){let i=Aa(n,e,t,o,r,s);return i.start(),i}function Sr(){be&&be.stop()}function Cr(){be&&(be.stop(),be=null)}var Fd,Ud,jd,xr,Bn,be,Jn=w(()=>{"use strict";re();Le();Tr();De();wo();q();Fd="x-claude-code-router-source",Ud="x-claude-code-router-version";jd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};xr="Managed provider requires its plugin's authenticated model sync";Bn=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,i){this.config={...jd,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=i}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.managedProbeTimer=setInterval(()=>this.runManagedRecoveryProbe(),this.config.quotaProbeIntervalMinutes*60*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.managedProbeTimer&&(clearInterval(this.managedProbeTimer),this.managedProbeTimer=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&&!Re(s)&&!this.config.excludeProviders.includes(s.name)),t=U();if(e.length===0)return;let o=[];for(let s of e){let i=_r(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){Go(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,p=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(u||p){let d=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,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of a){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`))}}})}),Jd(s.baseUrl)&&o.push({provider:s.name,models:a,type:"rate-limit-headers",promise:vr(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=U(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Re(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=>vr(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(l.skipped)continue;if(this.recordProbe(s.name,l,"health"),l.success){let c=0;for(let u of a){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),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 runManagedRecoveryProbe(){let e=U();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...i]=r.split(","),a=i.join(",");if(!s||!a)continue;let l=o.get(s)??[];l.push(a),o.set(s,l)}for(let[r,s]of o){let i=this.getProviders().find(d=>d?.name===r&&d.enabled!==!1);if(!i)continue;let a=this.resolveManagedRuntime(i);if(!a)continue;let l=s[0],c=e.getState(r,l);if(!c||c.status!=="open"||c.rateLimitUntil&&Date.now()<c.rateLimitUntil)continue;let u=Math.max(c.lastFailureTime??0,c.lastProbeTime??0);Date.now()-u<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,a,i,l,s,e)||await this.probeManagedLiveness(r,a,i,l,s,e)}}async probeManagedAccountState(e,t,o,r,s,i){try{if(typeof t.probeAccountState=="function"){let a=await t.probeAccountState();return a&&a.available===!1?(i.recordProbeAttempt?.(e,r),typeof a.parkedUntil=="number"&&a.parkedUntil>Date.now()&&i.markParkedUntil?.(e,r,a.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${a.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(a){return i.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${a?.code||a?.message||a}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,i){let a=this.config.probeTimeoutMs,l={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},c=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(l),signal:AbortSignal.timeout(a)})},u={TIMEOUT:a};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:c,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:c,requestBody:l,config:u,provider:o}):await c();if(p?.ok){for(let d of s)i.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else i.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){i.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=U(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[i,...a]=s.split(","),l=a.join(",");if(!i||!l)continue;let c=o.find(d=>d?.name===i);if(c&&Re(c))continue;let u=e.getState(i,l);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(i,l),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===i&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${i} not found or disabled for rate-limit probe`);continue}try{let d=await Kd(p,l,r,this.resolveProxyUrl?.(p),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 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(a=>a?.name&&a.enabled!==!1&&!Re(a)&&a.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=zd(t),i=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let a of e){let l=a.wakeupTime||i,[c,u]=l.split(":"),p=parseInt(c,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let m=o>p||o===p&&r>=d,g=(p*60+d)*6e4-(o*60+r)*6e4,f=g>0&&g<=300*1e3;(m||f)&&!this.hasWakeupFiredToday(a.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${a.name} at ${l}`),Wd(a,3e4,this.resolveProxyUrl?.(a),this.logger).then(h=>{h.success?this.logger?.info?.(`Successfully woke up provider ${a.name}`):this.logger?.error?.(`Failed to wake up provider ${a.name}: ${h.error}`)}).catch(h=>{this.logger?.error?.(`Error in wake-up task for ${a.name}: ${h}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?Hd(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 vr(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"),i=Array.isArray(o.models)?o.models:[];if(r.success)for(let a of i)U().recordSuccess(o.name,a);else for(let a of i)U().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}}},be=null});var Oa=w(()=>{"use strict"});var Rr,_t,Ia=w(()=>{"use strict";Rr=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 Rr});var ie,wr=w(()=>{"use strict";ie=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
310
|
+
`);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 Ye,Pr=w(()=>{"use strict";Ye=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
306
311
|
`),e.id&&(o+=`id: ${e.id}
|
|
307
312
|
`),e.retry&&(o+=`retry: ${e.retry}
|
|
308
313
|
`),e.data&&(e.data.type==="done"?o+=`data: [DONE]
|
|
309
314
|
`:o+=`data: ${JSON.stringify(e.data)}
|
|
310
315
|
`),o+=`
|
|
311
|
-
`,t.enqueue(o)}})}}});var
|
|
316
|
+
`,t.enqueue(o)}})}}});var Wn,Er=w(()=>{"use strict";Wn=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let i=await e(s,o);i!==void 0&&o.enqueue(i)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var Ar=w(()=>{"use strict";wr();Pr();Er()});var Ma=w(()=>{"use strict"});var kt,Or=w(()=>{"use strict";kt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:i}=t||{},a="";if(r){let l=new Date().toISOString();a+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(a+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":a+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?a+=this.toMarkdown(e):a+=String(e);break;case"text":default:typeof e=="object"?a+=JSON.stringify(e,null,2):a+=String(e);break}return i&&Object.keys(i).length>0&&(a+=`
|
|
312
317
|
`+(this.config.colors?`${this.colors.dim}`:""),a+="Metadata: "+JSON.stringify(i,null,2),this.config.colors&&(a+=this.colors.reset)),a}toMarkdown(e,t=0){let o=" ".repeat(t);return Array.isArray(e)?e.map(r=>typeof r=="object"?`${o}-
|
|
313
318
|
${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
|
|
314
319
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
|
|
315
320
|
${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
316
|
-
`):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var pt,ur=E(()=>{"use strict";pt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:i}=t||{},a={data:e};return r&&(a.timestamp=new Date().toISOString()),s&&(a.prefix=s),i&&Object.keys(i).length>0&&(a.metadata=i),a}async sendRequest(e,t,o,r,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:i.signal});if(clearTimeout(a),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(a),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,i){let a=null;for(let l=1;l<=i.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(a=c,l===i.maxAttempts)break;let u=i.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${i.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw a}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),i=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as Mn,opendir as Ju,unlink as Wu}from"node:fs/promises";import{join as Zi,resolve as fr}from"node:path";import{tmpdir as Ku}from"node:os";async function Nn(n,e){let t=fr(n),o=In.get(t),r,s=new Promise(i=>{r=i});In.set(t,s);try{return await o,await e()}finally{r(),In.get(t)===s&&In.delete(t)}}function qi(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Xi(n,e){try{let t=await Mn(n);return t.isDirectory()&&!t.isSymbolicLink()&&qi(e,t)}catch{return!1}}function Xu(){return new Promise(n=>{setTimeout(n,10).unref()})}async function ea(n,e,t,o){let r=fr(n);if(o?.aborted||dr.has(r))return 0;dr.add(r);let s=0;try{let i=await Mn(r);if(!i.isDirectory()||i.isSymbolicLink()||o?.aborted)return 0;let a=await Ju(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of a){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let d=Zi(r,u.name);try{let p=await Mn(d);if(!p.isFile()||p.isSymbolicLink()||p.mtimeMs>=e)continue;await Nn(d,async()=>{if(o?.aborted||!await Xi(r,i))return!1;let h=await Mn(d);return!h.isFile()||h.isSymbolicLink()||!qi(p,h)||h.mtimeMs!==p.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await Wu(d),!0)})&&s++}catch{}}finally{++l%64===0&&(await Xu(),c=!o?.aborted&&await Xi(r,i))}}}finally{await a.close().catch(()=>{})}}catch{}finally{dr.delete(r)}return s}function ta(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,i=t?`.${t}`:"";return ea(n,Date.now()-o,a=>Yu.test(a)?!0:!a.endsWith(".tmp")&&a.startsWith(s)&&a.endsWith(i),r)}function Zu(n,e){let t=Date.now()-Gu;return ea(n,t,o=>{let r=Qu.exec(o);return r!==null&&Number(r[1])<t},e)}function mr(n,e,t){let o=pr.get(n);if(!o){let s=new AbortController,i,a=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(a(),i=setInterval(a,Vu),i.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),i&&clearInterval(i)}},pr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),pr.delete(n)))}}function na(n=Zi(Ku(),"claude-code-router")){return mr(`legacy:${fr(n)}`,e=>Zu(n,e),1e3)}var Gu,Vu,Qu,Yu,dr,In,pr,gr=E(()=>{"use strict";Gu=3600*1e3,Vu=600*1e3,Qu=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,Yu=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,dr=new Set,In=new Map,pr=new Map});import{lstat as qu,mkdir as ed,open as td,rename as nd,unlink as od}from"node:fs/promises";import{randomUUID as rd}from"node:crypto";import{sanitizeTempFileKey as sd}from"@wengine-ai/claude-code-router-shared";import{basename as id,join as hr,resolve as ad}from"node:path";import{tmpdir as cd}from"node:os";var ft,yr=E(()=>{"use strict";gr();ft=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=ad(hr(cd(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=mr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await ed(this.baseDir,{recursive:!0});let e=await qu(this.baseDir);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Unsafe temp output directory")}getFilePath(e){let t=this.config.prefix||"session",o=this.config.extension?`.${this.config.extension}`:"",r=this.config.includeTimestamp?`-${Date.now()}`:"",s=`${t}-${sd(e)}${r}${o}`;if(id(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return hr(this.baseDir,s)}async output(e,t={}){try{let o=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 Nn(i,async()=>{await this.ensureDir();let a=hr(this.baseDir,`.ccr-tmp-${process.pid}-${rd()}.tmp`);return Nn(a,async()=>{let l=!1;try{let c=await td(a,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await nd(a,i),!0}finally{l&&await od(a).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return ta(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var _r,Ge,oa=E(()=>{"use strict";lr();ur();yr();_r=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new dt(e.config);case"webhook":return new pt(e.config);case"temp-file":return new ft(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([i,a])=>{try{await a.output(e,o)?r.success.push(i):r.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),r.failed.push(i)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},i=e.map(async a=>{let l=this.handlers.get(a);if(!l){console.warn(`[OutputManager] Handler ${a} not found`),s.failed.push(a);return}try{await l.output(t,r)?s.success.push(a):s.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),s.failed.push(a)}});return await Promise.all(i),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,i])=>i.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},Ge=new _r});var kr=E(()=>{"use strict";Yi();lr();ur();yr();oa()});import ld from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as ud}from"@wengine-ai/claude-code-router-shared";function $n(){return{subdirectory:ud,extension:"json",includeTimestamp:!1,prefix:"session"}}function ra(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,dd);return Math.round(n/o)}function gt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function sa(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},i={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let a of e)try{await Ge.outputToType(a,s,i)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${a}:`,l)}}var mt,br,dd,Ln,ia=E(()=>{"use strict";cr();kr();Ne();mt=new Map,br=new Map,dd=1,Ln={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:ld(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)Ge.registerHandlers(t.outputHandlers);else{let i=[];for(let a of o)a==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?i.push({type:"temp-file",enabled:!0,config:$n()}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&Ge.registerHandlers(i)}t.outputOptions&&Ge.setDefaultOptions(t.outputOptions);let r=async i=>{let a=n.tokenizerService;if(!a)return n.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let l=i.provider,c=i.model,u=`${l}:${c}`;if(br.has(u))return br.get(u);let d=a.getTokenizerConfigForModel(l,c);if(!d)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let p=await a.getTokenizer(d,l);return br.set(u,p),n.log?.info(`Created tokenizer for ${l}:${c} - ${p.name}`),p}catch(p){return n.log?.warn(`Failed to create tokenizer for ${l}:${c}: ${p.message}`),null}},s=i=>{let a=new URL(`http://127.0.0.1${i}`).pathname;return a.endsWith("/v1/messages")||a.endsWith("/v1/responses")};n.addHook("onRequest",async i=>{s(i.url)&&(i.requestStartTime=performance.now())}),n.addHook("onSend",async(i,a,l)=>{let c=i.requestStartTime;if(!c)return;let u=i.id||Date.now().toString(),d=i.usageSessionId||u,p=i.sessionId;if(!p)try{p=ge(i.body?.metadata?.user_id)||d}catch{p=d}let m=await r(i);if(l instanceof ReadableStream){mt.set(u,{requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[_,k]=l.tee(),y=async()=>{let b=null,T=async C=>{let v=mt.get(u);if(!v)return;let S=v.firstTokenTime?v.firstTokenTime-v.startTime:0,w=(C?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=ra(v.tokenCount,w,S),await sa(v,o,t.outputOptions,C).catch(R=>{n.log?.warn(`Failed to output streaming stats: ${R.message}`)})};try{let v=k.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();for(b=setInterval(async()=>{mt.get(u)&&await T(!1)},1e3);;){let{done:S,value:x}=await v.read();if(S)break;let w=x,R=mt.get(u);if(!R)continue;let O=performance.now(),P=w.event||w.data?.type,M=w.event==="content_block_start"||w.event==="content_block_delta"||w.event==="text_block"||w.event==="content_block"||P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta";!R.firstTokenTime&&M&&(R.firstTokenTime=O,R.timeToFirstToken=Math.round(O-R.startTime));let $="";if(w.event==="content_block_delta"&&w.data?.delta){let L=w.data.delta.type;L==="text_delta"?$=w.data.delta.text||"":L==="input_json_delta"?$=w.data.delta.partial_json||"":L==="thinking_delta"&&($=w.data.delta.thinking||"")}if((P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta")&&($=typeof w.data?.delta=="string"?w.data.delta:""),$){let L=m&&m.encodeText?m.encodeText($).length:gt($);R.tokenCount+=L,R.lastTokenTime=O}(w.event==="message_stop"||P==="response.completed"||P==="response.failed")&&(b&&(clearInterval(b),b=null),await T(!0),mt.delete(u))}}catch(C){b&&clearInterval(b),C.name!=="AbortError"&&C.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${C.message}`)}};return i.tokenSpeedCapturePromise=y().catch(b=>{console.log(b),n.log?.warn(`Background stats processing failed: ${b.message}`)}),_}let h=performance.now(),g=0,f=!1;if(l&&typeof l=="string")try{let _=JSON.parse(l);if(typeof _.usage?.output_tokens=="number")g=_.usage.output_tokens,f=!0;else{let k=_.content??_.message?.content;if(k!==void 0)if(f=!0,m)Array.isArray(k)?g=k.reduce((y,b)=>{if(b.type==="text"){let T=b.text||"";return y+(m.encodeText?m.encodeText(T).length:gt(T))}return y},0):typeof k=="string"&&(g=m.encodeText?m.encodeText(k).length:gt(k));else{let y=Array.isArray(k)?k.map(b=>b.text).join(""):typeof k=="string"?k:"";g=gt(y)}}}catch{}if(f){let _=h-c,k={requestId:u,sessionId:p,statsKey:d,startTime:c,lastTokenTime:h,tokenCount:g,tokensPerSecond:ra(g,_),stream:!1};await sa(k,o,t.outputOptions,!0)}return l})})}});var Tr=E(()=>{"use strict";Vi();Qi();ia();kr()});import ee from"node:fs/promises";import aa from"json5";import Se from"node:path";import{CONFIG_FILE as te,HOME_DIR as Dn,PLUGINS_DIR as pd}from"@wengine-ai/claude-code-router-shared";function ca(){if(process.env.VITEST||process.env.CI)throw new Error("Config write attempted during test/CI. Set CCR_CONFIG_DIR to a temp dir to isolate.")}var vr,ht,Fn,xr,ne,Un,_e,fd,Cr,jn=E(()=>{"use strict";vr=n=>{if(typeof n=="string")return n.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,t,o)=>{let r=t||o;return process.env[r]||e});if(Array.isArray(n))return n.map(vr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=vr(o);return e}return n},ht=async n=>{try{await ee.access(n)}catch{await ee.mkdir(n,{recursive:!0})}},Fn=async()=>{await ht(Dn),await ht(pd),await ht(Se.join(Dn,"logs"))},xr=async()=>{let n=await ee.readFile(te,"utf-8");return aa.parse(n)},ne=async()=>{try{let n=await ee.readFile(te,"utf-8");try{let e=aa.parse(n);return vr(e)}catch(e){console.error(`Failed to parse config file at ${te}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await Fn();let e=await Un();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await _e(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${te}`),console.error("Error details:",n.message),process.exit(1)}};Un=async()=>{ca();try{if(await ee.access(te).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${te}.${n}.bak`;await ee.copyFile(te,e);try{let t=Se.dirname(te),o=Se.basename(te),s=(await ee.readdir(t)).filter(i=>i.startsWith(o)&&i.endsWith(".bak")).sort().reverse();if(s.length>3)for(let i=3;i<s.length;i++){let a=Se.join(t,s[i]);await ee.unlink(a)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},_e=async n=>{ca(),await ht(Dn),await fd();let e=`${JSON.stringify(n,null,2)}`;await ee.writeFile(te,e)},fd=async()=>{if(!await ee.access(te).then(()=>!0).catch(()=>!1))return;let e=Se.join(Dn,"config-history");await ht(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Se.join(e,`config-${t}.json`);await ee.copyFile(te,o);try{let s=(await ee.readdir(e)).filter(i=>i.startsWith("config-")&&i.endsWith(".json")).sort().reverse();if(s.length>50)for(let i of s.slice(50))await ee.unlink(Se.join(e,i))}catch(r){console.warn("Failed to prune config-history:",r)}},Cr=async()=>{let n=await ne();return Object.assign(process.env,n),n}});function md(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function gd(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Ve(n){if(!(!n||typeof n!="object"))return{...n,input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:md(n),cache_creation_input_tokens:gd(n)}}function Hn(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var Sr=E(()=>{"use strict"});function zn(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(Rr(r,s))}return}if(Array.isArray(n)){for(let o of n)zn(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))zn(o,e,t)}}function la(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let i=Array.isArray(r?.models)?r.models:[];for(let a of i)a&&o.add(Rr(s,a))}return zn(n?.Router,t,o),zn(n?.fallback,t,o),o}function yt(n,e){try{let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=la(n),r=0;for(let s of t.getAllStates()||[]){let i=s?.provider,a=s?.model;!i||!a||o.has(Rr(i,a))||(t.recover(i,a),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function Bn(n,e){try{if(!n)return 0;let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var hd,Rr,Jn=E(()=>{"use strict";re();hd="\0",Rr=(n,e)=>`${n}${hd}${e}`});function yd(n){return/\[1m\]/i.test(n)?1e6:2e5}function _d(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function kd(n,e=n){let t=yd(n),o=_d(n);return{type:"model",id:n,display_name:e,created_at:"2024-01-01T00:00:00Z",context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o,capabilities:{context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o}}}function Wn(n){let e=new Map,t=(o,r=o)=>{!o||e.has(o)||e.set(o,kd(o,r))};t("ccr-opus","CCR Opus"),t("ccr-sonnet","CCR Sonnet"),t("ccr-haiku","CCR Haiku"),t("ccr-opus[1m]","CCR Opus 1M"),t("ccr-sonnet[1m]","CCR Sonnet 1M"),t("ccr-haiku[1m]","CCR Haiku 1M");for(let o of n.Providers||n.providers||[])if(!(!o?.name||!Array.isArray(o.models)))for(let r of o.models)typeof r!="string"||!r||(t(r,r),t(`${o.name},${r}`,`${o.name}/${r}`));return Array.from(e.values())}var wr=E(()=>{"use strict"});function bd(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var Kn,Er=E(()=>{"use strict";Kn=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||bd(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let i=n.APIKEY;if(!i){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let a=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(a)?a[0]:a||"";if(!l){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let c="";if(l.startsWith("Bearer")?c=l.split(" ")[1]:c=l,c!==i){t.log.warn({url:e.url,gotPrefix:c.slice(0,10),gotSuffix:c.slice(-6),gotLen:c.length,expectedPrefix:i.slice(0,6),expectedSuffix:i.slice(-6),expectedLen:i.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var ka={};no(ka,{append:()=>vt,clear:()=>Ir,close:()=>zd,getOldestRecordTimestamp:()=>Bd,query:()=>Ar,querySummary:()=>xt,readTokenSpeedStats:()=>Mr});import{existsSync as pa,mkdirSync as Td,readFileSync as fa}from"fs";import{join as Qn}from"path";import{tmpdir as vd}from"os";import{openSqliteDatabase as xd}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Cd,sanitizeTempFileKey as Sd,TOKEN_SPEED_TEMP_SUBDIRECTORY as Rd}from"@wengine-ai/claude-code-router-shared";function Ad(){pa(Vn)||Td(Vn,{recursive:!0})}function Tt(){if(be)return be;Ad();let n=xd(wd),e=n.db;n.driver==="node:sqlite"&&console.error(`[usage] better-sqlite3 unavailable, using built-in node:sqlite fallback. Reason: ${n.fallbackReason}`),e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("busy_timeout = 5000");let t=e.pragma("user_version",{simple:!0})||0;return t<1&&(Id(e),e.pragma("user_version = 1")),t<2&&(e.prepare("PRAGMA table_info(usage_records)").all().some(r=>r.name==="upstream_model")||e.exec("ALTER TABLE usage_records ADD COLUMN upstream_model TEXT"),e.pragma("user_version = 2")),Nd(e),ha(e,!0),Or=e.prepare(`
|
|
321
|
+
`):`${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 Tt,Ir=w(()=>{"use strict";Tt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:i}=t||{},a={data:e};return r&&(a.timestamp=new Date().toISOString()),s&&(a.prefix=s),i&&Object.keys(i).length>0&&(a.metadata=i),a}async sendRequest(e,t,o,r,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:i.signal});if(clearTimeout(a),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(a),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,i){let a=null;for(let l=1;l<=i.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(a=c,l===i.maxAttempts)break;let u=i.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${i.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw a}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),i=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as Gn,opendir as Vd,unlink as Qd}from"node:fs/promises";import{join as $a,resolve as $r}from"node:path";import{tmpdir as Yd}from"node:os";async function Vn(n,e){let t=$r(n),o=Kn.get(t),r,s=new Promise(i=>{r=i});Kn.set(t,s);try{return await o,await e()}finally{r(),Kn.get(t)===s&&Kn.delete(t)}}function Na(n,e){return n.dev===e.dev&&n.ino===e.ino}async function La(n,e){try{let t=await Gn(n);return t.isDirectory()&&!t.isSymbolicLink()&&Na(e,t)}catch{return!1}}function tp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Da(n,e,t,o){let r=$r(n);if(o?.aborted||Mr.has(r))return 0;Mr.add(r);let s=0;try{let i=await Gn(r);if(!i.isDirectory()||i.isSymbolicLink()||o?.aborted)return 0;let a=await Vd(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 p=$a(r,u.name);try{let d=await Gn(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await Vn(p,async()=>{if(o?.aborted||!await La(r,i))return!1;let g=await Gn(p);return!g.isFile()||g.isSymbolicLink()||!Na(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await Qd(p),!0)})&&s++}catch{}}finally{++l%64===0&&(await tp(),c=!o?.aborted&&await La(r,i))}}}finally{await a.close().catch(()=>{})}}catch{}finally{Mr.delete(r)}return s}function Fa(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,i=t?`.${t}`:"";return Da(n,Date.now()-o,a=>ep.test(a)?!0:!a.endsWith(".tmp")&&a.startsWith(s)&&a.endsWith(i),r)}function np(n,e){let t=Date.now()-Xd;return Da(n,t,o=>{let r=qd.exec(o);return r!==null&&Number(r[1])<t},e)}function Nr(n,e,t){let o=Lr.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,Zd),i.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),i&&clearInterval(i)}},Lr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Lr.delete(n)))}}function Ua(n=$a(Yd(),"claude-code-router")){return Nr(`legacy:${$r(n)}`,e=>np(n,e),1e3)}var Xd,Zd,qd,ep,Mr,Kn,Lr,Dr=w(()=>{"use strict";Xd=3600*1e3,Zd=600*1e3,qd=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,ep=/^\.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$/,Mr=new Set,Kn=new Map,Lr=new Map});import{lstat as op,mkdir as rp,open as sp,rename as ip,unlink as ap}from"node:fs/promises";import{randomUUID as cp}from"node:crypto";import{sanitizeTempFileKey as lp}from"@wengine-ai/claude-code-router-shared";import{basename as up,join as Fr,resolve as dp}from"node:path";import{tmpdir as pp}from"node:os";var vt,Ur=w(()=>{"use strict";Dr();vt=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=dp(Fr(pp(),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=Nr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await rp(this.baseDir,{recursive:!0});let e=await op(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}-${lp(e)}${r}${o}`;if(up(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Fr(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 Vn(i,async()=>{await this.ensureDir();let a=Fr(this.baseDir,`.ccr-tmp-${process.pid}-${cp()}.tmp`);return Vn(a,async()=>{let l=!1;try{let c=await sp(a,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await ip(a,i),!0}finally{l&&await ap(a).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return Fa(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var jr,Xe,ja=w(()=>{"use strict";Or();Ir();Ur();jr=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 kt(e.config);case"webhook":return new Tt(e.config);case"temp-file":return new vt(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)}},Xe=new jr});var Hr=w(()=>{"use strict";Ma();Or();Ir();Ur();ja()});import fp from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as mp}from"@wengine-ai/claude-code-router-shared";function Qn(){return{subdirectory:mp,extension:"json",includeTimestamp:!1,prefix:"session"}}function Ha(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,gp);return Math.round(n/o)}function St(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function za(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 Xe.outputToType(a,s,i)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${a}:`,l)}}var xt,zr,gp,Yn,Ba=w(()=>{"use strict";Ar();Hr();Fe();xt=new Map,zr=new Map,gp=1,Yn={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:fp(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)Xe.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:Qn()}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&Xe.registerHandlers(i)}t.outputOptions&&Xe.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(zr.has(u))return zr.get(u);let p=a.getTokenizerConfigForModel(l,c);if(!p)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let d=await a.getTokenizer(p,l);return zr.set(u,d),n.log?.info(`Created tokenizer for ${l}:${c} - ${d.name}`),d}catch(d){return n.log?.warn(`Failed to create tokenizer for ${l}:${c}: ${d.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(),p=i.usageSessionId||u,d=i.sessionId;if(!d)try{d=he(i.body?.metadata?.user_id)||p}catch{d=p}let m=await r(i);if(l instanceof ReadableStream){xt.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[b,_]=l.tee(),y=async()=>{let k=null,v=async S=>{let T=xt.get(u);if(!T)return;let R=T.firstTokenTime?T.firstTokenTime-T.startTime:0,x=(S?T.lastTokenTime:performance.now())-T.startTime;T.tokensPerSecond=Ha(T.tokenCount,x,R),await za(T,o,t.outputOptions,S).catch(E=>{n.log?.warn(`Failed to output streaming stats: ${E.message}`)})};try{let T=_.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();for(k=setInterval(async()=>{xt.get(u)&&await v(!1)},1e3);;){let{done:R,value:C}=await T.read();if(R)break;let x=C,E=xt.get(u);if(!E)continue;let A=performance.now(),P=x.event||x.data?.type,M=x.event==="content_block_start"||x.event==="content_block_delta"||x.event==="text_block"||x.event==="content_block"||P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta";!E.firstTokenTime&&M&&(E.firstTokenTime=A,E.timeToFirstToken=Math.round(A-E.startTime));let L="";if(x.event==="content_block_delta"&&x.data?.delta){let N=x.data.delta.type;N==="text_delta"?L=x.data.delta.text||"":N==="input_json_delta"?L=x.data.delta.partial_json||"":N==="thinking_delta"&&(L=x.data.delta.thinking||"")}if((P==="response.output_text.delta"||P==="response.function_call_arguments.delta"||P==="response.reasoning_summary_text.delta")&&(L=typeof x.data?.delta=="string"?x.data.delta:""),L){let N=m&&m.encodeText?m.encodeText(L).length:St(L);E.tokenCount+=N,E.lastTokenTime=A}(x.event==="message_stop"||P==="response.completed"||P==="response.failed")&&(k&&(clearInterval(k),k=null),await v(!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 i.tokenSpeedCapturePromise=y().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),b}let g=performance.now(),f=0,h=!1;if(l&&typeof l=="string")try{let b=JSON.parse(l);if(typeof b.usage?.output_tokens=="number")f=b.usage.output_tokens,h=!0;else{let _=b.content??b.message?.content;if(_!==void 0)if(h=!0,m)Array.isArray(_)?f=_.reduce((y,k)=>{if(k.type==="text"){let v=k.text||"";return y+(m.encodeText?m.encodeText(v).length:St(v))}return y},0):typeof _=="string"&&(f=m.encodeText?m.encodeText(_).length:St(_));else{let y=Array.isArray(_)?_.map(k=>k.text).join(""):typeof _=="string"?_:"";f=St(y)}}}catch{}if(h){let b=g-c,_={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:g,tokenCount:f,tokensPerSecond:Ha(f,b),stream:!1};await za(_,o,t.outputOptions,!0)}return l})})}});var Br=w(()=>{"use strict";Oa();Ia();Ba();Hr()});import ne from"node:fs/promises";import Ja from"json5";import we from"node:path";import{CONFIG_FILE as oe,HOME_DIR as Xn,PLUGINS_DIR as hp}from"@wengine-ai/claude-code-router-shared";function Wa(){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 Jr,Ct,Zn,Rt,Y,qn,le,yp,Wr,wt=w(()=>{"use strict";Jr=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(Jr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Jr(o);return e}return n},Ct=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},Zn=async()=>{await Ct(Xn),await Ct(hp),await Ct(we.join(Xn,"logs"))},Rt=async()=>{let n=await ne.readFile(oe,"utf-8");return Ja.parse(n)},Y=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=Ja.parse(n);return Jr(e)}catch(e){console.error(`Failed to parse config file at ${oe}`),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 Zn();let e=await qn();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await le(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 ${oe}`),console.error("Error details:",n.message),process.exit(1)}};qn=async()=>{Wa();try{if(await ne.access(oe).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${oe}.${n}.bak`;await ne.copyFile(oe,e);try{let t=we.dirname(oe),o=we.basename(oe),s=(await ne.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=we.join(t,s[i]);await ne.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},le=async n=>{Wa(),await Ct(Xn),await yp();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},yp=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=we.join(Xn,"config-history");await Ct(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=we.join(e,`config-${t}.json`);await ne.copyFile(oe,o);try{let s=(await ne.readdir(e)).filter(i=>i.startsWith("config-")&&i.endsWith(".json")).sort().reverse();if(s.length>50)for(let i of s.slice(50))await ne.unlink(we.join(e,i))}catch(r){console.warn("Failed to prune config-history:",r)}},Wr=async()=>{let n=await Y();return Object.assign(process.env,n),n}});function bp(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function _p(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 Pe(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:bp(n),cache_creation_input_tokens:_p(n)}}function Pt(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 Kr=w(()=>{"use strict"});function eo(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(Gr(r,s))}return}if(Array.isArray(n)){for(let o of n)eo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))eo(o,e,t)}}function Ka(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(Gr(s,a))}return eo(n?.Router,t,o),eo(n?.fallback,t,o),o}function Et(n,e){try{let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=Ka(n),r=0;for(let s of t.getAllStates()||[]){let i=s?.provider,a=s?.model;!i||!a||o.has(Gr(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 to(n,e){try{if(!n)return 0;let t=U();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var kp,Gr,At=w(()=>{"use strict";re();kp="\0",Gr=(n,e)=>`${n}${kp}${e}`});function Tp(n){return/\[1m\]/i.test(n)?1e6:2e5}function vp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function xp(n,e=n){let t=Tp(n),o=vp(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 Sp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Vr(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,xp(r,s))};o("ccr-opus","CCR Opus"),o("ccr-sonnet","CCR Sonnet"),o("ccr-haiku","CCR Haiku"),o("ccr-opus[1m]","CCR Opus 1M"),o("ccr-sonnet[1m]","CCR Sonnet 1M"),o("ccr-haiku[1m]","CCR Haiku 1M");for(let r of n.Providers||n.providers||[])if(!(!r?.name||!Array.isArray(r.models)))for(let s of r.models){if(typeof s!="string"||!s)continue;let i=Sp(e,r.name,s);i||o(s,s),i||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var Qr=w(()=>{"use strict"});function Cp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var no,Yr=w(()=>{"use strict";no=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Cp(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 nc={};mo(nc,{append:()=>$t,clear:()=>es,close:()=>Gp,getOldestRecordTimestamp:()=>Vp,query:()=>qr,querySummary:()=>Nt,readTokenSpeedStats:()=>ts});import{existsSync as Qa,mkdirSync as Rp,readFileSync as Ya}from"fs";import{join as so}from"path";import{tmpdir as wp}from"os";import{openSqliteDatabase as Pp}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Ep,sanitizeTempFileKey as Ap,TOKEN_SPEED_TEMP_SUBDIRECTORY as Op}from"@wengine-ai/claude-code-router-shared";function Np(){Qa(ro)||Rp(ro,{recursive:!0})}function Lt(){if(ke)return ke;Np();let n=Pp(Ip),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&&(Dp(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")),Up(e),qa(e,!0),Zr=e.prepare(`
|
|
317
322
|
INSERT INTO usage_records (
|
|
318
323
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
319
324
|
scenario_type, client_type,
|
|
@@ -327,7 +332,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
327
332
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
328
333
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
329
334
|
)
|
|
330
|
-
`),
|
|
335
|
+
`),ke=e,ke}function Dp(n){n.exec(`
|
|
331
336
|
CREATE TABLE IF NOT EXISTS usage_records (
|
|
332
337
|
id TEXT PRIMARY KEY,
|
|
333
338
|
timestamp TEXT NOT NULL,
|
|
@@ -364,12 +369,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
364
369
|
CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
|
|
365
370
|
CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
|
|
366
371
|
CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
|
|
367
|
-
`)}function
|
|
372
|
+
`)}function Fp(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
|
|
368
373
|
INSERT INTO usage_meta (key, value)
|
|
369
374
|
VALUES (?, ?)
|
|
370
375
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
371
|
-
`).run(e,t)}function
|
|
372
|
-
`)){let l=a.trim();if(l)try{let c=JSON.parse(l);if(
|
|
376
|
+
`).run(e,t)}function Up(n){if(Fp(n,Ga)||!Qa(Xr))return;let e=Hp(n,"INSERT OR IGNORE"),t=Ya(Xr,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let a of t.split(`
|
|
377
|
+
`)){let l=a.trim();if(l)try{let c=JSON.parse(l);if(!jp(c)){r++;continue}e.run(Za(io(c))).changes>0?o++:s++}catch{r++}}Ot(n,Ga,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",Xr),Ot(n,"legacy_usage_jsonl_imported_count",String(o)),Ot(n,"legacy_usage_jsonl_skipped_count",String(r)),Ot(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function jp(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 Hp(n,e="INSERT"){return n.prepare(`
|
|
373
378
|
${e} INTO usage_records (
|
|
374
379
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
375
380
|
scenario_type, client_type,
|
|
@@ -383,11 +388,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
383
388
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
384
389
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
385
390
|
)
|
|
386
|
-
`)}function
|
|
387
|
-
SELECT ${t} AS key, ${
|
|
391
|
+
`)}function zp(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,Mp);return Math.round(n/r)}function io(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Mt(n.ttft):null;return{...n,ttft:r,tokensPerSecond:zp(e,o,r)}}function _e(n){return typeof n=="string"?n:n==null?"":String(n)}function oo(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function It(n){let e=Number(n);return Number.isFinite(e)?e:0}function Xa(n){return n==="success"?"success":"error"}function Za(n){let e=io(n);return{id:_e(e.id),timestamp:_e(e.timestamp),session_id:_e(e.sessionId),provider:_e(e.provider),original_model:_e(e.originalModel),model:_e(e.model),upstream_model:oo(e.upstreamModel)??null,model_family:_e(e.modelFamily),scenario_type:_e(e.scenarioType),client_type:oo(e.clientType)??null,stream:e.stream?1:0,input_tokens:Math.trunc(It(e.inputTokens)),output_tokens:Math.trunc(It(e.outputTokens)),cache_read_input_tokens:Math.trunc(It(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(It(e.cacheCreationInputTokens)),ttft:Mt(e.ttft),tokens_per_second:Mt(e.tokensPerSecond),duration_ms:Math.trunc(It(e.durationMs)),status:Xa(e.status),error_message:oo(e.errorMessage)??null,response_body:oo(e.responseBody)??null}}function Bp(n){return io({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:Xa(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function Jp(){return new Date(Date.now()-Lp*24*60*60*1e3).toISOString()}function qa(n,e=!1){let t=Date.now();!e&&t-Va<$p||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(Jp()),Va=t)}function ec(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 Ze(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
|
|
392
|
+
SELECT ${t} AS key, ${Wp}
|
|
388
393
|
FROM usage_records ${r}
|
|
389
394
|
GROUP BY key
|
|
390
|
-
`).all(...e.params),i={};for(let a of s)a.key!=null&&(i[String(a.key)]={count:a.count,inputTokens:a.inputTokens,outputTokens:a.outputTokens,cacheReadInputTokens:a.cacheReadInputTokens,cacheCreationInputTokens:a.cacheCreationInputTokens});return i}function
|
|
395
|
+
`).all(...e.params),i={};for(let a of s)a.key!=null&&(i[String(a.key)]={count:a.count,inputTokens:a.inputTokens,outputTokens:a.outputTokens,cacheReadInputTokens:a.cacheReadInputTokens,cacheCreationInputTokens:a.cacheCreationInputTokens});return i}function tc(n,e){let t=ec(e),o=n.prepare(`
|
|
391
396
|
SELECT
|
|
392
397
|
COUNT(*) AS totalRequests,
|
|
393
398
|
COALESCE(SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END), 0) AS successCount,
|
|
@@ -398,14 +403,14 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
398
403
|
AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
|
|
399
404
|
AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
|
|
400
405
|
FROM usage_records ${t.sql}
|
|
401
|
-
`).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:
|
|
406
|
+
`).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:Ze(n,t,"model"),byProvider:Ze(n,t,"provider"),byScenario:Ze(n,t,"scenario_type"),byFamily:Ze(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:Ze(n,t,"date(timestamp, 'localtime')"),byClient:Ze(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function $t(n){let e=Lt(),t=io(n);Zr.run(Za(t)),qa(e)}function qr(n){let e=Lt(),t=ec(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),Kp):50,s=(o-1)*r,i=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),a=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),l=tc(e,n);return{records:a.map(Bp),summary:l,total:i.count,page:o,pageSize:r}}function Nt(n,e,t){let o=Lt();return tc(o,{startTime:n,endTime:e,status:t})}function es(n){let e=Lt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Gp(){ke&&(ke.pragma("wal_checkpoint(TRUNCATE)"),ke.close(),ke=null,Zr=null)}function Mt(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function ts(n){let e=so(wp(),Op,`session-${Ap(n)}.json`);try{let t=JSON.parse(Ya(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function Vp(n,e,t){return Lt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var ro,Ip,Xr,Mp,Lp,$p,Ga,ke,Zr,Va,Wp,Kp,Dt=w(()=>{"use strict";ro=so(Ep,"data"),Ip=so(ro,"usage.sqlite"),Xr=so(ro,"usage.jsonl"),Mp=1,Lp=180,$p=3600*1e3,Ga="legacy_usage_jsonl_migrated_at",ke=null,Zr=null,Va=0;Wp=`
|
|
402
407
|
COUNT(*) AS count,
|
|
403
408
|
COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
|
|
404
409
|
COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
|
|
405
410
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
|
|
406
411
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
|
|
407
|
-
`;Hd=200});import{existsSync as Jd}from"fs";import{homedir as Wd}from"os";import{join as Kd}from"path";import{writeFile as Gd}from"fs/promises";async function ba(){let n=Wd(),e=Kd(n,".claude.json");if(!Jd(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 Gd(e,JSON.stringify(o,null,2))}}var Ta=E(()=>{"use strict"});import{existsSync as Vd,readdirSync as Qd,statSync as Yd,unlinkSync as Xd}from"fs";import{join as va}from"path";import{HOME_DIR as Zd}from"@wengine-ai/claude-code-router-shared";function Ca(n=va(Zd,"logs")){try{if(!Vd(n))return;let e=Date.now()-ep;for(let t of Qd(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=va(n,t),r=Yd(o);r.isFile()&&r.mtime.getTime()<e&&Xd(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function Sa(){xa||(xa=!0,Ca(),setInterval(Ca,tp).unref())}var qd,ep,tp,xa,Ra=E(()=>{"use strict";qd=7,ep=qd*24*60*60*1e3,tp=1440*60*1e3,xa=!1});async function wa(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":ut.registerPlugin(Ln,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:$n()}],...i});break;default:console.warn(`Unknown plugin: ${r}`);break}}await ut.enablePlugins(n)}var Ea=E(()=>{"use strict";Tr()});import{ensureCcrSelfProvider as np}from"@wengine-ai/claude-code-router-shared";import{join as ie,isAbsolute as op,normalize as rp,dirname as sp}from"path";import{fileURLToPath as ip}from"url";import ap from"@fastify/static";import{readdirSync as Pa,statSync as cp,readFileSync as Oa,writeFileSync as lp,existsSync as de,unlinkSync as Aa,rmSync as up}from"fs";import{homedir as Nr}from"os";import{getPresetDir as Xn,readManifestFromDir as $r,manifestToPresetFile as Ia,saveManifest as Ma,isPresetInstalled as Na,extractPreset as dp,HOME_DIR as pp,loadConfigFromManifest as fp,downloadPresetToTemp as mp,findMarketPresetByName as gp,getMarketPresets as hp,applyClientSelection as yp,disableClient as _p,enableClient as kp,isClientId as bp,listClientStatuses as $a,restoreClient as Tp,listProjectConfigs as vp,readProjectConfigById as Lr,readProjectConfig as xp,writeProjectConfig as La,deleteProjectConfig as Cp,getClaudeProjectId as Sp,getProjectConfigPath as Rp,refreshCcrProjectTakeover as wp,refreshPiProjectTakeover as Ep,refreshProjectTakeovers as Pp,syncGlobalProjectTakeovers as Dr,getProjectTakeoverClients as Fr,setProjectTakeover as Ur,isProjectTakeoverClient as Op}from"@wengine-ai/claude-code-router-shared";import Ap from"@fastify/multipart";import Ip from"adm-zip";function Da(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 Mp(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=xt(t,e),s=xt(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 Fa(n,e){let t=n.app;et(),nt(),t.register(Ap,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let a=Wn(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=Wn(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:Bt(c,d,u)}}),t.get("/api/config",async(a,l)=>await xr()),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=Kr(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 Un();d&&console.log(`Backed up existing configuration file to ${d}`);let p=null;try{p=await ne()}catch{}let m=np(c,p);await _e(c);let h;try{h=await Dr(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),ue&&g.transformerService&&(g.providerService=new ue(g.configService,g.transformerService,t.log)),yt(c,t.log),We&&Pn){try{Pn()}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=We(()=>g.providerService.getProviders(),_,k=>ce(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 ne();return{clients:$a(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 ne(),p=yp(d,u);await _e(p.config);let m=await Dr(p.config),h=Da(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(!bp(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let d=await ne(),p=c==="enable"?kp(d,u):c==="restore"?Tp(d,u):_p(d,u);await _e(d);let m=await Dr(d),h=Da(t,m,`clients/${u}/${c}`);return{success:p.success&&h,result:p,results:[p],clients:$a(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 vp();return{projects:await Promise.all(c.map(async d=>{let p=await Fr(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"||!op(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=rp(c).replace(/[\\/]+$/,"")||c;if(await xp(u)){l.status(409).send({error:"Project is already configured"});return}await La(u,{Router:{}});try{let m=await ne();await Ur(u,["claudeCode"],m)}catch(m){console.error("Failed to auto-enable ccr takeover for new project:",m)}let p=await Fr(u);return{id:Sp(u),path:u,configPath:Rp(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 Lr(c);if(!d){l.status(404).send({error:"Project config not found"});return}await La(d.path,{Router:u});let p=await ne();Object.keys(u).length===0?await Pp(d.path,p):(await wp(d.path,p,u),await Ep(d.path,p,u));let m=await Fr(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(Op);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 Lr(c);if(!p){l.status(404).send({error:"Project config not found"});return}let m=await ne(),h=await Ur(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 Lr(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let d=await ne();await Ur(u.path,[],d)}catch(d){console.error("Failed to remove ccr takeover while deleting project:",d)}return await Cp(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:sp(ip(import.meta.url)),s=de(ie(r,"index.html"))?r:de(ie(r,"..","index.html"))?ie(r,".."):ie(r,"..","dist");t.register(ap,{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=ie(Nr(),".claude-code-router","logs"),u=[];if(de(c)){let d=Pa(c);for(let p of d)if(p.endsWith(".log")){let m=ie(c,p),h=cp(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=ie(Nr(),".claude-code-router","logs","app.log"),de(u)?Oa(u,"utf8").split(`
|
|
408
|
-
`).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=ie(Nr(),".claude-code-router","logs","app.log"),de(u)&&lp(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:Et()})),t.put("/api/debug-log",async a=>{let{enabled:l}=a.body;return io(l),{enabled:Et()}}),t.get("/api/usage",async(a,l)=>{try{let c=a.query;return Ar({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 xt(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 Ir(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=U().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&&Bn(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&&Bn(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 ne()).Providers||[],d=Mp(u),p=new Map(d.map(g=>[g.provider,g])),m=yo();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=Po();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=ie(pp,"presets");if(!de(c))return{presets:[]};let d=Pa(c,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).map(m=>m.name),p=[];for(let m of d){let h=ie(c,m);try{let g=ie(h,"manifest.json"),f=Oa(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:O,...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=Xn(c);if(!de(u)){l.status(404).send({error:"Preset not found"});return}let d=await $r(u);return{...Ia(d),config:fp(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=Xn(c);if(!de(d)){l.status(404).send({error:"Preset not found"});return}let m={...await $r(d)};return u&&Object.keys(u).length>0&&(m.userValues={...m.userValues,...u}),await Ma(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=Xn(c);if(!de(u)){l.status(404).send({error:"Preset not found"});return}return up(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 hp()}}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 gp(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 Na(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 mp(g),_=await i(f);if(await Na(h)){Aa(f),l.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let k=Xn(h);await dp(f,k);let y=await $r(k);return y.repository=u.repo,u.url&&(y.source=u.url),await Ma(h,y),Aa(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 Ip(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 Ia(u)}return n}var Ua=E(()=>{"use strict";je();Oe();Me();Gt();On();oe();Ze();re();Jn();jn();Ct();wr()});function Np(n,e){let t=n?.Router,{family:o}=it(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function ja(n){return n?.Router?.image}function $p(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 Lp(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 jr,Zn,Hr,Ha,za=E(()=>{"use strict";je();jr=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}},Zn=new jr;Hr=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Np(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!$p(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&No(e.body.model)?!1:(Lp(e.body.messages),s&&!!ja(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=Zn.getImage(`${t.req.id}_Image#${a}`);l&&o.push({type:"image",source:l})});else{let a=Zn.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:ja(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
412
|
+
`;Kp=200});import{existsSync as Qp}from"fs";import{homedir as Yp}from"os";import{join as Xp}from"path";import{writeFile as Zp}from"fs/promises";async function oc(){let n=Yp(),e=Xp(n,".claude.json");if(!Qp(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 Zp(e,JSON.stringify(o,null,2))}}var rc=w(()=>{"use strict"});import{existsSync as qp,readdirSync as ef,statSync as tf,unlinkSync as nf}from"fs";import{join as sc}from"path";import{HOME_DIR as of}from"@wengine-ai/claude-code-router-shared";function ac(n=sc(of,"logs")){try{if(!qp(n))return;let e=Date.now()-sf;for(let t of ef(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=sc(n,t),r=tf(o);r.isFile()&&r.mtime.getTime()<e&&nf(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function cc(){ic||(ic=!0,ac(),setInterval(ac,af).unref())}var rf,sf,af,ic,lc=w(()=>{"use strict";rf=7,sf=rf*24*60*60*1e3,af=1440*60*1e3,ic=!1});async function uc(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":_t.registerPlugin(Yn,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:Qn()}],...i});break;default:console.warn(`Unknown plugin: ${r}`);break}}await _t.enablePlugins(n)}var dc=w(()=>{"use strict";Br()});function qe(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()),Et(e,t),Cr();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=bt(()=>n.providerService.getProviders(),o,r=>ue(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var ao=w(()=>{"use strict";At();Jn();q()});import{constants as ns,lstatSync as et,realpathSync as Ft,openSync as cf,closeSync as lf,fstatSync as uf,readFileSync as pc}from"node:fs";import{dirname as L_,join as tt,sep as df}from"node:path";import{pathToFileURL as pf}from"node:url";function mc(n){try{let e=JSON.parse(pc(tt(ff(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function rs(n,e){if(!fc(e))return null;try{let t=Ft(n),o=tt(t,"plugins"),r=tt(o,e);return et(o).isSymbolicLink()||!et(o).isDirectory()||et(r).isSymbolicLink()||!et(r).isDirectory()||Ft(o)!==o||Ft(r)!==r||!r.startsWith(o+df)?null:r}catch{return null}}function os(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=rs(n,e);if(!o)throw new Error("unsafe plugin directory");let r=tt(o,t),s=et(r);if(s.isSymbolicLink()||!s.isFile()||Ft(r)!==r)throw new Error("unsafe plugin file");let i=cf(r,ns.O_RDONLY|ns.O_NOFOLLOW|ns.O_NONBLOCK);try{let a=uf(i),l=et(r);if(!a.isFile()||l.isSymbolicLink()||a.dev!==s.dev||a.ino!==s.ino||a.dev!==l.dev||a.ino!==l.ino||rs(n,e)!==o||Ft(r)!==r)throw new Error("plugin file changed while opening");return pc(i)}finally{lf(i)}}function mf(n){let e=n?.configService,t=e?Ts(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return vs(t)}async function gc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Ro(),r={configDir:e,readConfig:()=>Y(),readRawConfig:()=>Rt(),writeConfig:a=>le(a),reloadRuntime:async a=>qe(n.getServer(),a??await Y(),t),getDirectDispatcher:ho,getSubscriptionDispatcher:()=>mf(n.getServer())},s={loaded:[],failed:[],skipped:[]},i=new Set;for(let a of mc(e)){let l;try{if(!fc(a.name))throw new Error("invalid plugin install name");if(i.has(a.name))throw new Error(`duplicate plugin install record "${a.name}"`);if(i.add(a.name),a.enabled===!1){s.skipped.push({name:a.name,reason:"disabled"});continue}let c=rs(e,a.name);if(!c){s.skipped.push({name:a.name,reason:"directory missing or unsafe"});continue}let u;try{let f=JSON.parse(os(e,a.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!==a.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,c);l=p,os(e,a.name,"plugin.js");let d=await import(pf(tt(c,"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 g=p.cardPath?os(e,a.name,p.cardPath):void 0;await p.commit(g,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(c){l?.abort(),s.failed.push({name:a.name,error:c?.message??String(c)}),t.warn(`plugin ${a.name} failed to load: ${c?.message??String(c)}`)}}return s}function hc(n,e=Ro()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return mc(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 fc,ff,ss=w(()=>{"use strict";So();Gt();ao();wt();q();fc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),ff=n=>tt(n,"plugins")});import{existsSync as gf,readFileSync as hf}from"node:fs";import{join as yc}from"node:path";import{NPM_SPEC_PATTERN as yf,PluginInstallError as bf,installPluginFromNpm as _f,readPluginRecords as kf}from"@wengine-ai/claude-code-router-shared";async function vf(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 xf(n,e={}){let t=(e.registryBase??Tf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(bc.map(d=>vf(t,d,o))),s=new Map,i=!1;for(let d of r)if(d.status==="fulfilled"){i=!0;for(let m of d.value){let g=m?.package,f=typeof g?.name=="string"?g.name:"";if(!f||!yf.test(f)||!(Array.isArray(g?.keywords)?g.keywords.filter(_=>typeof _=="string"):[]).some(_=>bc.includes(_)))continue;let b=typeof g?.version=="string"?g.version:"";s.has(f)||s.set(f,{name:f,version:b,description:typeof g?.description=="string"?g.description:""})}}if(!i)return{ok:!0,plugins:[],warning:"registry_unavailable"};let a=kf(n),l=new Map(a.map(d=>[d.name,d])),c=new Map(a.filter(d=>typeof d.source=="string"&&d.source!=="").map(d=>[d.source,d])),u=d=>{try{let m=JSON.parse(hf(yc(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=l.get(d.name)??c.get(d.name),g=m!==void 0||gf(yc(n,"plugins",d.name));return{...d,installed:g,installedVersion:g?u(m?m.name:d.name):null}})}}function Sf(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 _c(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?.(),i=typeof s?.port=="number"&&s.port>0?s.port:t,a=new Set([`127.0.0.1:${i}`,`localhost:${i}`,`[::1]:${i}`]),l=n.headers?.host;if(typeof l=="string"&&!a.has(l))return!1;let c=n.headers?.origin;if(c!==void 0&&c!==""){if(typeof c!="string")return!1;let u="";try{let p=new URL(c);if(!["http:","https:"].includes(p.protocol))return!1;u=p.host}catch{return!1}if(!a.has(u))return!1}return!0}function kc(n,e){let t=e.configuredPort??3456,o=(r,s,i)=>r.status(s).send({ok:!1,error:i});n.get("/api/plugins/catalog",async(r,s)=>{if(!_c(r,n,t))return o(s,403,"local_only");try{return await xf(e.configDir,{registryBase:e.catalogRegistryBase??e.registry,timeoutMs:e.catalogTimeoutMs})}catch(i){return n.log?.warn?.(`plugin catalog failed: ${i?.code??i?.name??"error"}`),{ok:!0,plugins:[],warning:"registry_unavailable"}}}),n.post("/api/plugins/install",async(r,s)=>{if(!_c(r,n,t))return o(s,403,"local_only");let i=r.body??{},a=i.name??i.spec,l=i.force===!0;try{let c=await _f({spec:a,configDir:e.configDir,force:l,registry:e.registry,timeoutMs:e.npmTimeoutMs});return n.log?.info?.(`provider plugin installed via API: ${c.manifest.name}@${c.manifest.version} (restart to activate)`),{ok:!0,name:c.manifest.name,version:c.manifest.version,restartRequired:!0}}catch(c){if(c instanceof bf){let u=Sf(c.code);return u===502?n.log?.warn?.(`plugin install failed: ${c.code}`):n.log?.warn?.(`plugin install rejected: ${c.code}: ${c.message}`),o(s,u,c.code)}return n.log?.error?.(`plugin install crashed: ${c?.message??c}`),o(s,500,"install_failed")}})}var bc,Tf,Tc=w(()=>{"use strict";bc=["ccr-provider-plugin","claude-code-router-plugin"],Tf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Cf}from"@wengine-ai/claude-code-router-shared";import{join as ae,isAbsolute as Rf,normalize as wf,dirname as Pf}from"path";import{fileURLToPath as Ef}from"url";import Af from"@fastify/static";import{readdirSync as vc,statSync as Of,readFileSync as xc,writeFileSync as If,existsSync as pe,unlinkSync as Sc,rmSync as Mf}from"fs";import{homedir as is}from"os";import{getPresetDir as co,readManifestFromDir as as,manifestToPresetFile as Cc,saveManifest as Rc,isPresetInstalled as wc,extractPreset as Lf,HOME_DIR as cs,loadConfigFromManifest as $f,downloadPresetToTemp as Nf,findMarketPresetByName as Df,getMarketPresets as Ff,applyClientSelection as Uf,disableClient as jf,enableClient as Hf,isClientId as zf,listClientStatuses as Pc,restoreClient as Bf,listProjectConfigs as Jf,readProjectConfigById as ls,readProjectConfig as Wf,writeProjectConfig as Ec,deleteProjectConfig as Kf,getClaudeProjectId as Gf,getProjectConfigPath as Vf,refreshCcrProjectTakeover as Qf,refreshPiProjectTakeover as Yf,refreshProjectTakeovers as Xf,syncGlobalProjectTakeovers as us,getProjectTakeoverClients as ds,setProjectTakeover as ps,isProjectTakeoverClient as Zf}from"@wengine-ai/claude-code-router-shared";import qf from"@fastify/multipart";import em from"adm-zip";function Ac(n){let e=U();return Vr(n,(t,o)=>e.isAvailable(t,o))}function Oc(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 tm(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=Nt(t,e),s=Nt(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},p=(c.inputTokens||0)+(c.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),m,g,f=(n||[]).find(h=>h&&h.name===l);f&&f.quota&&(m=f.quota.limit5h,g=f.quota.limit7d),i.push({provider:l,used5h:p,used7d:d,limit5h:m,limit7d:g})}return i}async function Ic(n,e){let t=n.app;at(),lt(),t.register(qf,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let a=Ac(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=Ac(e).find(p=>p.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:p,model:d}=a.body,m=t._server.tokenizerService;if(d&&d.includes(",")&&m)try{let[f,h]=d.split(",");a.log?.info(`Looking up tokenizer for provider: ${f}, model: ${h}`);let b=m.getTokenizerConfigForModel(f,h);b?a.log?.info(`Using tokenizer config: ${JSON.stringify(b)}`):a.log?.warn(`No tokenizer config found for ${f},${h}, using default tiktoken`);let _=await m.countTokens({messages:c,system:p,tools:u},b,f);return{input_tokens:_.tokenCount,tokenizer:_.tokenizerUsed}}catch(f){a.log?.error(`Error using configured tokenizer: ${f.message}`),a.log?.error(f.stack)}else d?d.includes(",")?m||a.log?.warn("TokenizerService not available, using default tiktoken"):a.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):a.log?.info("No model specified, using default tiktoken");return{input_tokens:sn(c,p,u)}}),t.get("/api/config",async(a,l)=>await Rt()),t.get("/api/transformers",async(a,l)=>{let c=t._server.transformerService.getAllTransformers();return{transformers:Array.from(c.entries()).map(([p,d])=>({name:p,endpoint:d.endPoint||null}))}}),t.post("/api/config",async(a,l)=>{let c=a.body,u=ks(c||{});if(u.length>0)return l.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(f=>`${f.key}: ${f.error}`).join("; "),proxyErrors:u};let p=await qn();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await Y()}catch{}let m=Cf(c,d);n.pluginRegistry.applyConfigProtectors(c,d),await le(c);let g;try{g=await us(c),g.failed.length>0&&t.log?.warn?.({projectTakeoverSync:g},"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 qe(n,c,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:g}}),t.get("/api/clients",async(a,l)=>{try{let c=await Y();return{clients:Pc(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:[],p=await Y(),d=Uf(p,u);await le(d.config);let m=await us(d.config),g=Oc(t,m,"clients/apply");return{...d,success:d.success&&g,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(!zf(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let p=await Y(),d=c==="enable"?Hf(p,u):c==="restore"?Bf(p,u):jf(p,u);await le(p);let m=await us(p),g=Oc(t,m,`clients/${u}/${c}`);return{success:d.success&&g,result:d,results:[d],clients:Pc(p),config:p,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 Jf();return{projects:await Promise.all(c.map(async p=>{let d=await ds(p.path);return{...p,ccrTakeoverClients:d,ccrTakeover:d.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"||!Rf(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=wf(c).replace(/[\\/]+$/,"")||c;if(await Wf(u)){l.status(409).send({error:"Project is already configured"});return}await Ec(u,{Router:{}});try{let m=await Y();await ps(u,["claudeCode"],m)}catch(m){console.error("Failed to auto-enable ccr takeover for new project:",m)}let d=await ds(u);return{id:Gf(u),path:u,configPath:Vf(u),Router:{},ccrTakeoverClients:d,ccrTakeover:d.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 p=await ls(c);if(!p){l.status(404).send({error:"Project config not found"});return}await Ec(p.path,{Router:u});let d=await Y();Object.keys(u).length===0?await Xf(p.path,d):(await Qf(p.path,d,u),await Yf(p.path,d,u));let m=await ds(p.path);return{id:c,path:p.path,configPath:p.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||{},p;if(Array.isArray(u.clients))p=u.clients.filter(Zf);else if(typeof u.enabled=="boolean")p=u.enabled?["claudeCode"]:[];else{l.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let d=await ls(c);if(!d){l.status(404).send({error:"Project config not found"});return}let m=await Y(),g=await ps(d.path,p,m);return{id:c,path:d.path,ccrTakeoverClients:g,ccrTakeover:g.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 ls(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let p=await Y();await ps(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await Kf(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:Pf(Ef(import.meta.url)),s=pe(ae(r,"index.html"))?r:pe(ae(r,"..","index.html"))?ae(r,".."):ae(r,"..","dist");t.register(Af,{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=ae(is(),".claude-code-router","logs"),u=[];if(pe(c)){let p=vc(c);for(let d of p)if(d.endsWith(".log")){let m=ae(c,d),g=Of(m);u.push({name:d,path:m,size:g.size,lastModified:g.mtime.toISOString()})}u.sort((d,m)=>new Date(m.lastModified).getTime()-new Date(d.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=ae(is(),".claude-code-router","logs","app.log"),pe(u)?xc(u,"utf8").split(`
|
|
413
|
+
`).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=ae(is(),".claude-code-router","logs","app.log"),pe(u)&&If(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:zt()})),t.put("/api/debug-log",async a=>{let{enabled:l}=a.body;return ko(l),{enabled:zt()}}),t.get("/api/usage",async(a,l)=>{try{let c=a.query;return qr({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 Nt(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 es(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=U().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(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 p=t._server?.activeProbeService;if(!p?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let d=await p.probeProviderManually(c);return d.success&&to(c,a.log),{provider:c,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.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 p=(c?.providerService?.getProviders?.()||[]).filter(m=>m?.name&&m.enabled!==!1),d=await Promise.all(p.map(async m=>{let g=await u.probeProviderManually(m.name);return g.success&&to(m.name,a?.log),{provider:m.name,success:g.success,latencyMs:g.latencyMs,status:g.status,isSlow:g.isSlow,errorKind:g.errorKind??null,error:g.error}}));return{results:d,successCount:d.filter(m=>m.success).length,total:d.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 Y()).Providers||[],p=tm(u),d=new Map(p.map(f=>[f.provider,f])),m=No();for(let f of p){let h=m.find(b=>b.provider===f.provider);h&&h.limit!=null&&(f.limit5h=h.limit,f.used5h=h.limit-(h.remaining??0),h.reset&&(f.reset5h=new Date(h.reset*1e3).toISOString()))}let g=Vo();for(let f of g){let h=d.get(f.provider);h||(h={provider:f.provider,used5h:0,used7d:0},p.push(h),d.set(f.provider,h)),typeof f.totalBalance=="number"?(h.limit7d=f.totalBalance,h.type7d=f.currency?"balance":"rateLimit",f.currency&&(h.currency=f.currency),typeof f.usedBalance=="number"?h.used7d=f.usedBalance:typeof f.remainingBalance=="number"?h.used7d=Math.max(0,f.totalBalance-f.remainingBalance):(h.used7d=0,h.limit7d=f.totalBalance)):typeof f.usedBalance=="number"&&(h.used7d=f.usedBalance),typeof f.usedDailyBalance=="number"&&(h.used5h=f.usedDailyBalance,h.type5h="rateLimit"),typeof f.limitDaily=="number"&&(h.limit5h=f.limitDaily,h.type5h="rateLimit"),typeof f.resetTime=="string"&&(f.limitDaily!==void 0?h.reset5h=f.resetTime:h.reset7d=f.resetTime),typeof f.resetTime7d=="string"&&(h.reset7d=f.resetTime7d)}return{quotas:p,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=ae(cs,"presets");if(!pe(c))return{presets:[]};let p=vc(c,{withFileTypes:!0}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).map(m=>m.name),d=[];for(let m of p){let g=ae(c,m);try{let f=ae(g,"manifest.json"),h=xc(f,"utf-8"),b=JSON.parse(h),{Providers:_,Router:y,PORT:k,HOST:v,API_TIMEOUT_MS:S,PROXY_URL:T,PROXY_GLOBAL_ENABLED:R,LOG:C,LOG_LEVEL:x,StatusLine:E,NON_INTERACTIVE_MODE:A,...P}=b;d.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(f){console.error(`Failed to read preset ${m}:`,f)}}return{presets:d}}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=co(c);if(!pe(u)){l.status(404).send({error:"Preset not found"});return}let p=await as(u);return{...Cc(p),config:$f(p,u),userValues:p.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,p=co(c);if(!pe(p)){l.status(404).send({error:"Preset not found"});return}let m={...await as(p)};return u&&Object.keys(u).length>0&&(m.userValues={...m.userValues,...u}),await Rc(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=co(c);if(!pe(u)){l.status(404).send({error:"Preset not found"});return}return Mf(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 Ff()}}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 Df(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 p=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!p){l.status(400).send({error:"Invalid GitHub repository URL"});return}let[,d,m]=p,g=u.name||c;if(await wc(g)){l.status(409).send({error:"Preset already installed",message:`Preset '${g}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:g});return}let f=`https://github.com/${d}/${m}/archive/refs/heads/main.zip`,h=await Nf(f),b=await i(h);if(await wc(g)){Sc(h),l.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let _=co(g);await Lf(h,_);let y=await as(_);return y.repository=u.repo,u.url&&(y.source=u.url),await Rc(g,y),Sc(h),{success:!0,presetName:g,preset:{...b.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 em(a),c=l.getEntry("manifest.json");if(c||(c=l.getEntries().find(d=>d.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 Cc(u)}return t.get("/api/plugins",async()=>({plugins:hc(cs,n.pluginRegistry)})),kc(t,{configDir:cs,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(a,l)=>{let{name:c,file:u}=a.params,p=n.pluginRegistry.getPublicCard(c,u);return p?(l.header("Content-Type","application/javascript; charset=utf-8"),l.header("X-Content-Type-Options","nosniff"),l.header("Cache-Control","no-store"),l.send(p)):l.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var Mc=w(()=>{"use strict";Ce();Le();De();q();rt();re();At();ao();ss();Tc();wt();Dt();Qr()});function nm(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 Lc(n){return n?.Router?.image}function om(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 rm(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 fs,lo,ms,$c,Nc=w(()=>{"use strict";Ce();fs=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}},lo=new fs;ms=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=nm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!om(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&mt(e.body.model)?!1:(rm(e.body.messages),s&&!!Lc(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=lo.getImage(`${t.req.id}_Image#${a}`);l&&o.push({type:"image",source:l})});else{let a=lo.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:Lc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
409
414
|
When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
|
|
410
415
|
Do not ignore or deviate from the task.
|
|
411
416
|
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(a=>a.json()).catch(a=>null);return!i||!i.content?"analyzeImage Error":i.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
|
|
@@ -418,5 +423,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
|
|
|
418
423
|
|
|
419
424
|
Do not attempt to describe or analyze the image directly yourself.
|
|
420
425
|
Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
|
|
421
|
-
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")Zn.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:(Zn.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}})})}},Ha=new Hr});var zr,Ba,qn,Ja=E(()=>{"use strict";za();zr=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}},Ba=new zr;Ba.registerAgent(Ha);qn=Ba});import{EventEmitter as Dp}from"node:events";import{performance as Wa}from"node:perf_hooks";import Fp from"json5";function Up(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 Ga(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,e)}function Br(n){return n.usageSessionId||n.id}function eo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Br(n)}`}function Ye(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 jp(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?Ve(e.usage):e.response?.usage?Ve(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Hp(n,e,t){if(await new Promise((r,s)=>{let i=a=>a?s(a):r();Kn(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")){Ga(n,t);let r=eo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=X.get(r))}}async function zp(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of qn.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 Va(n){return{authClient:(e,t)=>Hp(e,t,n),agent:(e,t)=>zp(e,t,n)}}function Qa(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=Wa.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();Kn(e)(t,o,a).then(()=>s(),i)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Ka.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){Ga(t,e);let l=Br(t),c=eo(t);if(r instanceof ReadableStream){if(i&&t.agents){let h=new AbortController,g=r.pipeThrough(new ae),f,_=-1,k="",y="",b="",T=[],C=[];return s(null,An(g,async(v,S)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let x=t.agents.find(w=>qn.getAgent(w)?.tools.get(v.data.content_block.name));if(x){f=qn.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=Fp.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 ae).getReader();for(;;)try{let{value:O,done:P}=await R.read();if(P)break;let M=O;if(["message_start","message_stop"].includes(M.event))continue;if(!S.desiredSize)break;S.enqueue(M)}catch(O){if(O.name==="AbortError"||O.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw O}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 Ke))}let[d,p]=r.tee(),m=async h=>{let f=h.pipeThrough(new TextDecoderStream).pipeThrough(new ae).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=X.get(c)||{},C=Ve(b.usage),v=Hn(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:Ye(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}),X.put(c,v)}if(b?.response?.usage){let T=Ve(b.response.usage),C=X.get(c)||{},v=Hn(C,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:y,provider:t.provider,model:Ye(t),usageSessionId:l,capturedUsage:T,mergedUsage:v}),X.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=jp(r);if(u?.usage&&X.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(Ka.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=>{xo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),xo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{t.usageCapturePromise&&await t.usageCapturePromise,t.tokenSpeedCapturePromise&&await t.tokenSpeedCapturePromise;let r=Br(t),s=r,i=t.sessionId||r,a=o.statusCode>=400,l=a?void 0:X.get(eo(t)),c=Mr(s),u=U(),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=Ye(t);Up(o.statusCode,d)?u.markRateLimited(t.provider||"",T,120,d):u.recordFailure(t.provider||"",T,d)}else{let T=Ye(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:Ye(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."}),vt({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:Ye(t),upstreamModel:t.upstreamModel,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||De(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(Wa.now()-t.requestStartTime):0,status:f?"error":"success",errorMessage:d,responseBody:p}),t.clientContext?.usageScope!=="session"&&X.delete(eo(t))}catch(r){console.error("Usage tracking error:",r)}})}var Ka,Ya=E(()=>{"use strict";Fe();Ft();Dt();re();sr();ir();ar();Ct();Sr();Ja();Er();Kt();Ka=new Dp});var Xa={};no(Xa,{createCcrServer:()=>Yp});import{homedir as Bp}from"os";import{join as Jp}from"path";import{createStream as Wp}from"rotating-file-stream";import{CONFIG_FILE as Kp,HOME_DIR as Gp,listPresets as Vp,ensureCcrSelfProvider as Qp}from"@wengine-ai/claude-code-router-shared";async function Yp(n={}){await ba(),await Fn();let e=await Cr();Qp(e).changed&&(await _e(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;na();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:(Sa(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:Wp(c,{path:Gp,interval:"1d",size:"50M",compress:!1})}):u=!1);let d=await Vp(),p=new qa({jsonPath:Kp,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:a,LOG_FILE:Jp(Bp(),".claude-code-router","claude-code-router.log")},logger:u});await p.ready(),await Fa(p,e),p.recordUsage=f=>{try{let _=f.req?f.req.clientType||De(f.req):"unknown";vt({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:",_)}},Qa(p,e),p.ccrPreHandlerCallbacks=Va(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 wa(p,e),yt(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 Za=E(()=>{"use strict";ec();Ta();jn();Ra();gr();Ea();Ua();Ya();Jn();Ct();Fe()});import Xp from"fastify";import Zp from"@fastify/cors";function qp(n={}){let e=Xp({bodyLimit:52428800,...n});return e.setErrorHandler(Yr),e.register(Zp),e}async function ef(n={}){return(await Promise.resolve().then(()=>(Za(),Xa))).createCcrServer(n)}var Jr,qa,Vk,ec=E(()=>{ro();wt();Kt();Gt();Uo();Ho();je();Ft();On();re();Oe();Me();oe();Fe();Kt();Ne();Fe();je();ro();Gt();Uo();Ho();Tr();cr();re();Oe();tr();Me();re();On();Ze();oe();jn();Sr();Jn();wr();Er();Ct();Jr=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=qp({...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 Re(c),this.transformerService=new Be(this.configService,this.app.log),this.tokenizerService=new Je(this.configService,this.app.log),this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.providerService=new ue(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 Re({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Be(o,this.app.log),i=new Je(o,this.app.log),await Promise.all([r.initialize(),i.initialize()]),s=new ue(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&&at(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),xe(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 Jt(c,u,{configService:o,tokenizerService:i}),c.usageCacheKey&&X.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 ei(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{or()}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 oo()})}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{et()}catch{}try{nt()}catch{}try{fo()}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=We(()=>this.providerService.getProviders(),t,o=>ce(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)}}},qa=Jr;Vk=ef});ec();export{En as ActiveProbeService,Re as ConfigService,q as ProjectRoutingError,Nt as ProviderHealthStore,ue as ProviderService,ae as SSEParserTransform,Ke as SSESerializerTransform,Je as TokenizerService,Be as TransformerService,Kn as apiKeyAuth,xe as applyClientAdapter,Un as backupConfigFile,Ns as builtinClientAdapterRegistry,Bt as calculateTokenCount,El as clearClientAdapterCaches,Bn as clearProviderHealth,oo as closeProxyDispatchers,la as collectReachableModelKeys,ef as createCcrServer,qa as default,De as detectClientType,Js as diagnoseResolutionFailure,ge as extractSessionIdFromUserId,Gi as getActiveProbeService,Po as getAllQuotaResults,yo as getAllRateLimitInfo,Ls as getClientAdapter,Rt as getConfiguredProxyUrl,U as getHealthStore,G as getProxyDispatcher,qo as getQuotaAdapter,Ut as getQuotaResult,$c as getRateLimitInfo,Et as getRuntimeDebugLog,Vk as getServer,Cr as initConfig,Fn as initDir,fo as initProviderHealthPersistence,nt as initQuotaStorePersistence,et as initRateLimitPersistence,$s as isClientType,Gr as isGlobalProxyEnabled,Wn as listAnthropicCompatibleModels,Hn as mergeUsageCapture,me as normalizeSessionId,Ve as normalizeUsagePayload,ut as pluginManager,ne as readConfigFile,xr as readConfigFileRaw,yt as reconcileHealthStore,Pn as resetActiveProbeService,ce as resolveProviderProxyUrl,An as rewriteStream,Jt as router,Gs as searchProjectBySession,X as sessionUsageCache,io as setRuntimeDebugLog,We as startActiveProbe,or as stopActiveProbe,Eo as storeQuotaResult,Ln as tokenSpeedPlugin,ka as usageStore,_e as writeConfigFile};
|
|
426
|
+
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")lo.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:(lo.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}})})}},$c=new ms});var gs,Dc,uo,Fc=w(()=>{"use strict";Nc();gs=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}},Dc=new gs;Dc.registerAgent($c);uo=Dc});import{EventEmitter as sm}from"node:events";import{performance as Uc}from"node:perf_hooks";import im from"json5";function cm(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 Hc(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,e)}function hs(n){return n.usageSessionId||n.id}function po(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${hs(n)}`}function nt(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 lm(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?Pe(e.usage):e.response?.usage?Pe(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function um(n,e,t){if(await new Promise((r,s)=>{let i=a=>a?s(a):r();no(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")){Hc(n,t);let r=po(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Q.get(r))}}async function dm(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of uo.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 zc(n){return{authClient:(e,t)=>um(e,t,n),agent:(e,t)=>dm(e,t,n)}}function Bc(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=Uc.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();no(e)(t,o,a).then(()=>s(),i)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",jc.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){Hc(t,e);let l=hs(t),c=po(t);if(r instanceof ReadableStream){if(i&&t.agents){let g=new AbortController,f=r.pipeThrough(new ie),h,b=-1,_="",y="",k="",v=[],S=[];return s(null,Wn(f,async(T,R)=>{try{if(T.event==="content_block_start"&&T?.data?.content_block?.name){let C=t.agents.find(x=>uo.getAgent(x)?.tools.get(T.data.content_block.name));if(C){h=uo.getAgent(C),b=T.data.index,_=T.data.content_block.name,k=T.data.content_block.id;return}}if(b>-1&&T.data.index===b&&T.data?.delta?.type==="input_json_delta"){y+=T.data?.delta?.partial_json;return}if(b>-1&&T.data.index===b&&T.data?.type==="content_block_stop"){try{let C=im.parse(y);S.push({type:"tool_use",id:k,name:_,input:C});let x=await h?.tools.get(_)?.handler(C,{req:t,config:e});v.push({tool_use_id:k,type:"tool_result",content:x}),h=void 0,b=-1,_="",y="",k=""}catch(C){console.log(C)}return}if(T.event==="message_delta"&&v.length){t.body.messages.push({role:"assistant",content:S}),t.body.messages.push({role:"user",content:v});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 E=C.body.pipeThrough(new ie).getReader();for(;;)try{let{value:A,done:P}=await E.read();if(P)break;let M=A;if(["message_start","message_stop"].includes(M.event))continue;if(!R.desiredSize)break;R.enqueue(M)}catch(A){if(A.name==="AbortError"||A.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw A}return}return T}catch(C){if(console.error("Unexpected error in stream processing:",C),C.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw C}}).pipeThrough(new Ye))}let[p,d]=r.tee(),m=async g=>{let h=g.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:b,value:_}=await h.read();if(b)break;let y=_.event,k=_.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 v=Q.get(c)||{},S=Pe(k.usage),T=Pt(v,S,y==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:y,provider:t.provider,model:nt(t),usageSessionId:l,capturedUsage:S,mergedUsage:T}),(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}),Q.put(c,T)}if(k?.response?.usage){let v=Pe(k.response.usage),S=Q.get(c)||{},T=Pt(S,v,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:y,provider:t.provider,model:nt(t),usageSessionId:l,capturedUsage:v,mergedUsage:T}),Q.put(c,T)}}}catch(b){b.name==="AbortError"||b.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",b)}finally{h.releaseLock()}};return t.usageCapturePromise=m(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let m=d.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:g,value:f}=await m.read();if(g)break;let h=f.event,b=f.data;h==="message_start"&&b?.message?.model&&(t.upstreamModel=b.message.model),h==="response.completed"&&b?.response?.model&&(t.upstreamModel=b.response.model);let _=b?.usage??b?.response?.usage;if(_){let y=Pe(_),k=Q.get(c)||{},v=Pt(k,y,h==="message_start");Q.put(c,v)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{m.releaseLock()}})(),s(null,p)}let u=lm(r);if(u?.usage&&Q.put(c,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(jc.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{let r=async S=>{if(!S)return;let T;try{await Promise.race([S,new Promise(R=>{T=setTimeout(R,am)})])}finally{T&&clearTimeout(T)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=hs(t),i=s,a=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:Q.get(po(t)),u=ts(i),p=U(),d,m,g=t.sseError,f=g&&(g.type||g.code||g.message),h=c?.output_tokens&&c.output_tokens>0,b=l||f&&!h;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,f&&(d=d||JSON.stringify(g),m=JSON.stringify(g)),m=m||t.errorResponseBody;let S=nt(t);cm(o.statusCode,d)?p.markRateLimited(t.provider||"",S,120,d):p.recordFailure(t.provider||"",S,d)}else{let S=nt(t);p.recordSuccess(t.provider||"",S)}let _=c?.cache_read_input_tokens??0,k=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 v=b?0:c?.output_tokens||0;!b&&t.body?.stream&&k===0&&v===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:nt(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."}),$t({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:nt(t),upstreamModel:t.upstreamModel,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||He(t),stream:t.body?.stream??!1,inputTokens:k,outputTokens:v,cacheReadInputTokens:_,cacheCreationInputTokens:c?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Uc.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:m}),t.clientContext?.usageScope!=="session"&&Q.delete(po(t))}catch(r){console.error("Usage tracking error:",r)}})}var am,jc,Jc=w(()=>{"use strict";ze();en();qt();re();wr();Pr();Er();Dt();Kr();Fc();Yr();ln();am=1500;jc=new sm});var Kc={};mo(Kc,{createCcrServer:()=>bm});import{homedir as pm}from"os";import{join as fm}from"path";import{createStream as mm}from"rotating-file-stream";import{CONFIG_FILE as gm,HOME_DIR as Wc,listPresets as hm,ensureCcrSelfProvider as ym}from"@wengine-ai/claude-code-router-shared";async function bm(n={}){await oc(),await Zn();let e=await Wr();ym(e).changed&&(await le(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;Ua();let l=m=>(m>9?"":"0")+m,c=(m,g)=>{let f;m?typeof m=="number"?f=new Date(m):f=m:f=new Date;let h=f.getFullYear()+""+l(f.getMonth()+1),b=l(f.getDate()),_=l(f.getHours()),y=l(f.getMinutes());return`./logs/ccr-${h}${b}${_}${y}${l(f.getSeconds())}${g?`_${g}`:""}.log`},u;n.logger!==void 0?u=n.logger:(cc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:mm(c,{path:Wc,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await hm(),d=new Vc({jsonPath:gm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:a,LOG_FILE:fm(pm(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let m=await gc({configDir:Wc,registry:d.pluginRegistry,getServer:()=>d,log:{info:b=>d.app?.log?.info?.(b),warn:b=>d.app?.log?.warn?.(b),error:b=>d.app?.log?.error?.(b)}});m.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${m.failed.map(b=>`${b.name} (${b.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(b=>`${b.name}@${b.version}`).join(", ")}`),m.loaded.length&&qe(d,e,d.app.log),await Ic(d,e),d.recordUsage=b=>{try{let _=b.req?b.req.clientType||He(b.req):"unknown";$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:b.sessionId||"",provider:b.provider||"",originalModel:b.originalModel||"",model:b.model||"",modelFamily:b.modelFamily||"",scenarioType:b.scenarioType||"default",clientType:_,stream:b.stream??!1,inputTokens:b.inputTokens||0,outputTokens:0,cacheReadInputTokens:b.cacheReadInputTokens||0,cacheCreationInputTokens:b.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:b.errorMessage,responseBody:void 0})}catch(_){console.error("Fallback usage tracking error:",_)}},Bc(d,e),d.ccrPreHandlerCallbacks=zc(e),(await Promise.allSettled(p.map(async b=>await d.registerNamespace(`/preset/${b.name}`,b.config)))).forEach((b,_)=>{if(b.status==="rejected"){let y=p[_],k=b.reason instanceof Error?b.reason.message:String(b.reason);d.app?.log?.error?.(`Failed to register preset "${y?.name}": ${k}`)}}),await uc(d,e),Et(e,d.app?.log);let f=b=>{d.app.log.error({err:b},"Uncaught exception")},h=(b,_)=>{d.app.log.error({reason:b,promise:_},"Unhandled rejection")};return process.on("uncaughtException",f),process.on("unhandledRejection",h),d.app.addHook("onClose",async()=>{process.off("uncaughtException",f),process.off("unhandledRejection",h)}),d}catch(m){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),m}}var Gc=w(()=>{"use strict";Qc();rc();wt();lc();Dr();dc();Mc();ss();ao();Jc();At();Dt();ze()});import _m from"fastify";import km from"@fastify/cors";function Tm(n={}){let e=_m({bodyLimit:52428800,...n});return e.setErrorHandler(Rs),e.register(km),e}async function vm(n={}){return(await Promise.resolve().then(()=>(Gc(),Kc))).createCcrServer(n)}var ys,Vc,QT,Qc=w(()=>{bo();Ht();ln();qo();sr();ar();Ce();en();Jn();re();Le();De();q();ze();ln();Gt();Fe();ze();Ce();bo();qo();sr();ar();Br();Ar();re();Le();Tr();De();re();Jn();rt();q();wt();Kr();At();Qr();Yr();Dt();ys=class{app;pluginRegistry=new st;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:i,useEnvironmentVariables:a,...l}=e;this.app=Tm({...l,logger:l.logger??!0}),this.app._server=this,this.app.addHook("onClose",async()=>{this.pluginRegistry.dispose(),this.tokenizerService?.dispose()});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 Ee(c),this.transformerService=new Ve(this.configService,this.app.log),this.tokenizerService=new Qe(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,i=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Ee({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ve(o,this.app.log),i=new Qe(o,this.app.log),await Promise.all([r.initialize(),i.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new We(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let a=async l=>{l.decorate("pluginRegistry",this.pluginRegistry),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 p=new URL(`http://127.0.0.1${c.url}`);c.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),m=p.pathname.endsWith("/v1/responses");if(!d&&!m||!c.body||typeof c.body!="object")return;let g=c.ccrHookOrder||=[];if(g.push("request-normalize"),m&&c.body.input&&!c.body.messages&>(c.body),c.body.stream===void 0&&(c.body.stream=!1),c.log.info({data:c.body,type:"request body"}),g.push("adapter"),!c.originalModel&&c.body.model&&(c.originalModel=c.body.model),xe(c,o.getAll()),g.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(c,u),u.sent))&&(g.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(c,u),u.sent)))){g.push("router"),c.body?.model&&await an(c,u,{configService:o,tokenizerService:i}),c.usageCacheKey&&Q.put(c.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),g.push("provider-model-normalize");try{let f=c.body;if(!f||!f.model)return u.code(400).send({error:"Missing model in request body"});let h=f.model.split(","),b=f.model;if(h.length>1){let[_,...y]=h;b=y.join(","),f.model=b,c.provider=_}c.model=b}catch(f){return c.log.error({error:f},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Fi(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{Sr()}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 yo()})}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{at()}catch{}try{lt()}catch{}try{Io()}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=bt(()=>this.providerService.getProviders(),t,o=>ue(this.configService,o),this.app.log,o=>this.configService.get(o),o=>this.pluginRegistry?.getManagedRuntimeFor(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)}}},Vc=ys;QT=vm});Qc();export{Bn as ActiveProbeService,Ee as ConfigService,te as ProjectRoutingError,Yt as ProviderHealthStore,We as ProviderService,ie as SSEParserTransform,Ye as SSESerializerTransform,Qe as TokenizerService,Ve as TransformerService,no as apiKeyAuth,xe as applyClientAdapter,qn as backupConfigFile,yi as builtinClientAdapterRegistry,sn as calculateTokenCount,Ou as clearClientAdapterCaches,to as clearProviderHealth,yo as closeProxyDispatchers,Ka as collectReachableModelKeys,vm as createCcrServer,Vc as default,He as detectClientType,wi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Aa as getActiveProbeService,Vo as getAllQuotaResults,No as getAllRateLimitInfo,_i as getClientAdapter,jt as getConfiguredProxyUrl,U as getHealthStore,K as getProxyDispatcher,_r as getQuotaAdapter,tn as getQuotaResult,Fl as getRateLimitInfo,zt as getRuntimeDebugLog,QT as getServer,Wr as initConfig,Zn as initDir,Io as initProviderHealthPersistence,lt as initQuotaStorePersistence,at as initRateLimitPersistence,bi as isClientType,xs as isGlobalProxyEnabled,Vr as listAnthropicCompatibleModels,Pt as mergeUsageCapture,ge as normalizeSessionId,Pe as normalizeUsagePayload,_t as pluginManager,Y as readConfigFile,Rt as readConfigFileRaw,Et as reconcileHealthStore,Cr as resetActiveProbeService,ue as resolveProviderProxyUrl,Wn as rewriteStream,an as router,Ai as searchProjectBySession,Q as sessionUsageCache,ko as setRuntimeDebugLog,bt as startActiveProbe,Sr as stopActiveProbe,Go as storeQuotaResult,Yn as tokenSpeedPlugin,nc as usageStore,le as writeConfigFile};
|
|
422
427
|
//# sourceMappingURL=server.mjs.map
|