@wengine-ai/llms 2.3.2431 → 2.3.2433

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,38 @@
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 ko=Object.defineProperty;var gl=Object.getOwnPropertyDescriptor;var hl=Object.getOwnPropertyNames;var yl=Object.prototype.hasOwnProperty;var vo=(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 To=(n,e)=>{for(var t in e)ko(n,t,{get:e[t],enumerable:!0})},_l=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hl(e))!yl.call(n,r)&&r!==t&&ko(n,r,{get:()=>e[r],enumerable:!(o=gl(e,r))||o.enumerable});return n};var bl=n=>_l(ko({},"__esModule",{value:!0}),n);import{Agent as kl,ProxyAgent as vl}from"undici";function xl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Tl.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 Os(n){let e=[];for(let t of[...Es,As]){let o=n[t];if(o==null)continue;let r=xl(o);r.ok||e.push({key:t,error:r.error})}return e}function So(){return xo||(xo=new kl({connect:{timeout:15e3}})),xo}function Is(n){let e=n.get(As);return(typeof e=="string"?e.trim():"")||void 0}function Ms(n){return n?G(n):So()}function Ht(n){for(let e of Es){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Ls(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=Ht(n);if(t)return Ls(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=Sl(n),t=jt.get(e);if(t)return t;let o=new vl(e);return jt.set(e,o),o}async function Co(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function Sl(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 Es,As,Tl,jt,xo,q=w(()=>{"use strict";Es=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],As="SUBSCRIPTION_PROXY_URL",Tl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as Cl,existsSync as $s}from"fs";import{join as Ns}from"path";import{config as Rl}from"dotenv";import wl from"json5";var Me,Ro=w(()=>{"use strict";q();Me=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:Ns(process.cwd(),this.options.jsonPath);if($s(e))try{let t=Cl(e,"utf-8"),o=wl.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:Ns(process.cwd(),this.options.envPath);if($s(e))try{let t=Rl({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 Ht(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 K(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 Us(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 zt=w(()=>{"use strict"});function Po(n){wo=n}function Bt(){return wo}function Jt(n){return wo||n.get("DEBUG_LOG")===!0}function js(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();Pl.has(r)||El.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Kt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Hs(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:Wt(t.headers),body:Kt(o,Le.maxBodyLength)})}function zs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Wt(t.headers),...t.body!==void 0?{body:Kt(t.body,Le.maxBodyLength)}:{}})}function Ds(n,e,t,o){let r=Al(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Le.maxBodyLength)})}function Al(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:Kt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Fs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Bs(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:l}=await r.read();if(i)break;a+=l;let c=a.split(`
2
+ var vo=Object.defineProperty;var kl=Object.getOwnPropertyDescriptor;var vl=Object.getOwnPropertyNames;var Tl=Object.prototype.hasOwnProperty;var To=(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 P=(n,e)=>()=>(n&&(e=n(n=0)),e);var So=(n,e)=>{for(var t in e)vo(n,t,{get:e[t],enumerable:!0})},Sl=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vl(e))!Tl.call(n,r)&&r!==t&&vo(n,r,{get:()=>e[r],enumerable:!(o=kl(e,r))||o.enumerable});return n};var xl=n=>Sl(vo({},"__esModule",{value:!0}),n);import{Agent as Cl,ProxyAgent as Rl}from"undici";function Pl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(wl.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 Ls(n){let e=[];for(let t of[...Is,Ms]){let o=n[t];if(o==null)continue;let r=Pl(o);r.ok||e.push({key:t,error:r.error})}return e}function Co(){return xo||(xo=new Cl({connect:{timeout:15e3}})),xo}function $s(n){let e=n.get(Ms);return(typeof e=="string"?e.trim():"")||void 0}function Ns(n){return n?G(n):Co()}function zt(n){for(let e of Is){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Us(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 pe(n,e){let t=zt(n);if(t)return Us(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=El(n),t=Ht.get(e);if(t)return t;let o=new Rl(e);return Ht.set(e,o),o}async function Ro(){let n=Array.from(Ht.values());Ht.clear(),await Promise.allSettled(n.map(e=>e.close()))}function El(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 Is,Ms,wl,Ht,xo,ee=P(()=>{"use strict";Is=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Ms="SUBSCRIPTION_PROXY_URL",wl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Ht=new Map});import{readFileSync as Al,existsSync as Ds}from"fs";import{join as Fs}from"path";import{config as Ol}from"dotenv";import Il from"json5";var Me,wo=P(()=>{"use strict";ee();Me=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:Fs(process.cwd(),this.options.jsonPath);if(Ds(e))try{let t=Al(e,"utf-8"),o=Il.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:Fs(process.cwd(),this.options.envPath);if(Ds(e))try{let t=Ol({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 zt(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 K(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 js(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 Bt=P(()=>{"use strict"});function Eo(n){Po=n}function Jt(){return Po}function Wt(n){return Po||n.get("DEBUG_LOG")===!0}function Bs(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function Kt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();Ml.has(r)||Ll.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Gt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Js(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:Kt(t.headers),body:Gt(o,Le.maxBodyLength)})}function Ws(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Kt(t.headers),...t.body!==void 0?{body:Gt(t.body,Le.maxBodyLength)}:{}})}function Hs(n,e,t,o){let r=$l(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Gt(o,Le.maxBodyLength)})}function $l(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Gt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function zs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Ks(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:l}=await r.read();if(i)break;a+=l;let c=a.split(`
3
3
 
4
- `);a=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Ds(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Ds(e,t,s,a.trim()),s++),Fs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Fs(e,t,s)}finally{r.releaseLock()}})()}var Pl,El,Le,wo,rt=w(()=>{"use strict";Pl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),El=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},wo=!1});function Js(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 a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=c.signal}else a=i;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?l.dispatcher=t.dispatcher:t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Ol(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function Ol(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 Ws=w(()=>{q();rt()});function Ml(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Ks(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Eo(n){if(Ks(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(Il.some(s=>r.includes(s))){e=!0;break}Ll.some(s=>r.includes(s))&&(t=!0)}}return e||Ml(n)?"content":t?"empty":"pending"}async function Gs(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,l=Date.now()+t,c=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=l-Date.now(),p=Symbol("timeout"),d,f=o.read(),g=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),g===p)return c(Eo(a)==="content"?"content":"pending",Gt(o,f));if(g.done){a+=r.decode();let m=Eo(a);return c(m==="empty"?"empty":"pending",null)}if(!g.value)continue;s.push(g.value),i+=g.value.byteLength,a+=r.decode(g.value,{stream:!0});let h=Eo(a);if(h==="content")return c("content",Gt(o));if(h==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if(Ks(a)||i>=e)return c("pending",Gt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Gt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Qs(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:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var Il,Ll,Vs=w(()=>{"use strict";Il=["content_block_start","content_block_delta","content_block_stop"];Ll=["message_stop","response.completed","response.incomplete","[DONE]"]});function $l(n,e){return`${n.name}|${e?.name??""}`}function Ao(n){return n.__ccrPluginRequestState??={budgets:new Map}}function $e(n,e,t){let o=Ao(n),r=$l(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Oo(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:($e(n,e,o).terminalError=t,!0)}var Ys=w(()=>{"use strict"});var Io=w(()=>{"use strict"});import Nl from"fastify";function Xs(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,Ul,Lo,Qt=w(()=>{"use strict";Io();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,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,l=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>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(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let h of this.plugins.values()){for(let m of s.runtimes.keys())if(h.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(h.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(h=>[...s.transformers].map(([m,y])=>{if(h.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:h,name:m,value:h.preparePluginTransformer(y)}})),g=[];try{for(let h of f)g.push(h),h.service.registerTransformer(h.name,h.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(h){for(let m of g)m.service.removeTransformer(m.name);throw a="aborted",h}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,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(i,l);return typeof c=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(l)}`)}:c}}),a=Nl({logger:!1});try{for(let i of e){let l=i(s);l!==s&&await l}for(let i of this.plugins.values())for(let l of i.preparedRoutes)a.route(l);for(let i of r){let l=Array.isArray(i.method)?i.method:[i.method];for(let c of l)if(t.hasRoute({method:c,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${c} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},Ul=new st,Lo=()=>Ul});function Zs(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function Te(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?Dl(r):{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(i)}catch{}let l=Xs(n.name,i);return l.isRateLimit=i.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function Dl(n){let e=[n?.causeCode,n?.causeDetail].filter(Boolean).join(" ");return{code:"plugin_network_error",message:e?`Provider plugin network failure (${e}).`:n?.errorName?`Provider plugin network failure (${n.errorName}).`:"Provider plugin network failure.",httpStatus:502,retryable:!0}}var qs=w(()=>{"use strict";Qt()});var Vt,$o=w(()=>{Vt="2.3.2431"});var ei={};To(ei,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>Hl});function Ne(n){return xe||(xe=new No,n&&xe.configure(n)),xe}function Hl(){xe&&(xe.clearAll(),xe=null)}var jl,No,xe,Yt=w(()=>{"use strict";re();jl=600*1e3,No=class{promotions=new Map;enabled=!0;ttlMs=jl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(i,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...c]=a.promotedModel.split(","),u=c.join(",");if(!H().isAvailable(l,u))return this.promotions.delete(s),null;let d=r.find(g=>g.name.toLowerCase()===l.toLowerCase()),f=d?.models?.find(g=>String(g).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});import{existsSync as oi,mkdirSync as zl,readFileSync as Bl,writeFileSync as Jl}from"fs";import{join as ri}from"path";import{HOME_DIR as Wl}from"@wengine-ai/claude-code-router-shared";function Vl(n){try{if(!oi(Fo))return;let e=JSON.parse(Bl(Fo,"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,lastSuccessTime:o.lastSuccessTime,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function ni(n){try{let e=n.getAllStates();if(e.length===0)return;oi(Do)||zl(Do,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Jl(Fo,JSON.stringify(t,null,2),"utf-8")}catch{}}function jo(){if(ti)return;ti=!0;let n=H();Vl(n),Ql=setInterval(()=>ni(n),6e4),process.on("exit",()=>ni(n))}function H(n){return Uo||(Uo=new Xt(n)),Uo}var Kl,Gl,Xt,Do,Fo,ti,Ql,Uo,re=w(()=>{"use strict";Kl=120,Gl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Gl,...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.lastSuccessTime=Date.now(),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}=(Yt(),bl(ei));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 a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??Kl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Do=ri(Wl,"runtime"),Fo=ri(Do,"provider-health.json"),ti=!1,Ql=null;Uo=null});import{existsSync as li,mkdirSync as Yl,readFileSync as Xl,writeFileSync as Zl}from"fs";import{join as ui}from"path";import{HOME_DIR as ql}from"@wengine-ai/claude-code-router-shared";function it(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let l=Object.keys(t).find(c=>c.toLowerCase()===i);return l?t[l]:null},r=Ho(o,eu),s=Ho(o,tu),a=Ho(o,nu);(r||s||a)&&Ue.set(n,{provider:n,remaining:ai(r),limit:ai(s),reset:ru(a),capturedAt:Date.now()})}function ou(n){return Ue.get(n)}function Jo(){return Array.from(Ue.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Ho(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ai(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function ru(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=su(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function su(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function iu(){try{if(!li(Bo))return;let n=JSON.parse(Xl(Bo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Ue.set(t.provider,t)}}catch{}}function ci(){try{if(Ue.size===0)return;li(zo)||Yl(zo,{recursive:!0}),Zl(Bo,JSON.stringify(Array.from(Ue.values()),null,2),"utf-8")}catch{}}function at(){si||(si=!0,iu(),ii=setInterval(ci,6e4),ii.unref?.(),process.on("exit",ci))}var zo,Bo,Ue,si,ii,eu,tu,nu,Se=w(()=>{"use strict";zo=ui(ql,"runtime"),Bo=ui(zo,"rate-limit.json"),Ue=new Map,si=!1,ii=null,eu=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],tu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],nu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return Wo||(Wo=new Go),Wo}function Vo(){return Ko||(Ko=new Qo),Ko}function au(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function di(n){let e=au(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 pi(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Yo(n){let e=n?.[qt];e&&en().release(e)}function fi(n,e){let t=di(n),o=n?.[qt],r=t?Vo().get(t)!==void 0:!1;!o&&!r||(t&&Vo().bind(t,e),pi(n,e))}function cu(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let l=o.count(i);l<s&&(r=i,s=l)}return r}function mi(n,e,t){let o=di(n),r=Vo(),s=en(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(i=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(i=e)}if(!i){let l=s.count(e);if(l>=a){let c=cu(e,t.fallbackModels,t.resolve);c&&(i=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}i=i||e,o&&r.bind(o,i)}return pi(n,i),i}var Go,Qo,Wo,Ko,qt,tn=w(()=>{"use strict";Go=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()}},Qo=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()}},Wo=null,Ko=null;qt="__concurrencyLease"});async function j(n){let e=await n.text();return lu(e,n.status)}function lu(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 gi(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 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 a=0;a<8;a++){let{value:i,done:l}=await o.read();if(l||(i&&(s+=r.decode(i,{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"});function uu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function nn(n){for(let e of uu(n))if(e.startsWith("response."))return!0;return!1}var De,Xo=w(()=>{"use strict";V();De=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role==="system")return;if(Array.isArray(r.content)){let i=r.content.map(l=>this.normalizeRequestContent(l,r.role)).filter(l=>l!==null);i.length>0?r.content=i:delete r.content}if(r.role==="tool"){let i={...r};i.type="function_call_output",i.call_id=r.tool_call_id,i.output=r.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}let{thinking:s,...a}=r;r.role==="assistant"&&a.content===void 0||t.push(a)}),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,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await j(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",l=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=l.decode(p,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}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}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",l,c,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(v){let x=(S,I=null)=>{v.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[{index:0,delta:S,finish_reason:I}]})}
4
+ `);a=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Hs(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Hs(e,t,s,a.trim()),s++),zs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),zs(e,t,s)}finally{r.releaseLock()}})()}var Ml,Ll,Le,Po,ot=P(()=>{"use strict";Ml=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Ll=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},Po=!1});function Gs(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 a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=c.signal}else a=i;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?l.dispatcher=t.dispatcher:t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Kt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Nl(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function Nl(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 Qs=P(()=>{ee();ot()});function Dl(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Vs(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Ao(n){if(Vs(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(Ul.some(s=>r.includes(s))){e=!0;break}Fl.some(s=>r.includes(s))&&(t=!0)}}return e||Dl(n)?"content":t?"empty":"pending"}async function Ys(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,l=Date.now()+t,c=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=l-Date.now(),p=Symbol("timeout"),d,f=o.read(),h=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),h===p)return c(Ao(a)==="content"?"content":"pending",Qt(o,f));if(h.done){a+=r.decode();let m=Ao(a);return c(m==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let g=Ao(a);if(g==="content")return c("content",Qt(o));if(g==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if(Vs(a)||i>=e)return c("pending",Qt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Qt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Xs(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:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var Ul,Fl,Zs=P(()=>{"use strict";Ul=["content_block_start","content_block_delta","content_block_stop"];Fl=["message_stop","response.completed","response.incomplete","[DONE]"]});function jl(n,e){return`${n.name}|${e?.name??""}`}function Oo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function rt(n,e,t){let o=Oo(n),r=jl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Io(n,e,t,o,r){if(!e||t?.nonRetryable!==!0)return!1;let s=rt(n,e,o);return e.modelScopedRecovery&&t?.statusCode===429&&r?(s.modelErrors??=new Map).set(r,t):s.terminalError=t,!0}function Mo(n,e,t,o){let r=rt(n,e,t);return r.terminalError??(o?r.modelErrors?.get(o):void 0)}var qs=P(()=>{"use strict"});var Lo=P(()=>{"use strict"});import Hl from"fastify";function ei(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,zl,No,Vt=P(()=>{"use strict";Lo();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,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,l=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>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(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let g of this.plugins.values()){for(let m of s.runtimes.keys())if(g.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(g.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([m,y])=>{if(g.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:g,name:m,value:g.preparePluginTransformer(y)}})),h=[];try{for(let g of f)h.push(g),g.service.registerTransformer(g.name,g.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(g){for(let m of h)m.service.removeTransformer(m.name);throw a="aborted",g}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,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(i,l);return typeof c=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(l)}`)}:c}}),a=Hl({logger:!1});try{for(let i of e){let l=i(s);l!==s&&await l}for(let i of this.plugins.values())for(let l of i.preparedRoutes)a.route(l);for(let i of r){let l=Array.isArray(i.method)?i.method:[i.method];for(let c of l)if(t.hasRoute({method:c,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${c} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},zl=new st,No=()=>zl});function ti(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function Te(n,e,t,o,r,s){let a;try{a=n.classifyError?.(e,t,o)}catch{}let i=a&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(a.code)?a.code:"plugin_upstream_error",l=a?{...a,code:i,message:`Provider plugin request failed (${i}).`}:e===0?Bl(r):{code:i,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(l,s)}catch{}let c=ei(n.name,l);return c.isRateLimit=l.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function Bl(n){let e=[n?.causeCode,n?.causeDetail].filter(Boolean).join(" ");return{code:"plugin_network_error",message:e?`Provider plugin network failure (${e}).`:n?.errorName?`Provider plugin network failure (${n.errorName}).`:"Provider plugin network failure.",httpStatus:502,retryable:!0}}var ni=P(()=>{"use strict";Vt()});var Yt,Uo=P(()=>{Yt="2.3.2433"});var oi={};So(oi,{getFallbackPromotionStore:()=>$e,resetFallbackPromotionStore:()=>Kl});function $e(n){return Se||(Se=new Do,n&&Se.configure(n)),Se}function Kl(){Se&&(Se.clearAll(),Se=null)}var Wl,Do,Se,Xt=P(()=>{"use strict";ie();Wl=600*1e3,Do=class{promotions=new Map;enabled=!0;ttlMs=Wl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(i,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...c]=a.promotedModel.split(","),u=c.join(",");if(!H().isAvailable(l,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===l.toLowerCase()),f=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}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}},Se=null});import{existsSync as ii,mkdirSync as Gl,readFileSync as Ql,writeFileSync as Vl}from"fs";import{join as ai}from"path";import{HOME_DIR as Yl}from"@wengine-ai/claude-code-router-shared";function eu(n){try{if(!ii(Ho))return;let e=JSON.parse(Ql(Ho,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastSuccessTime:o.lastSuccessTime,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function si(n){try{let e=n.getAllStates();if(e.length===0)return;ii(jo)||Gl(jo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Vl(Ho,JSON.stringify(t,null,2),"utf-8")}catch{}}function zo(){if(ri)return;ri=!0;let n=H();eu(n),ql=setInterval(()=>si(n),6e4),process.on("exit",()=>si(n))}function H(n){return Fo||(Fo=new Zt(n)),Fo}var Xl,Zl,Zt,jo,Ho,ri,ql,Fo,ie=P(()=>{"use strict";Xl=120,Zl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Zt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Zl,...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.lastSuccessTime=Date.now(),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}=(Xt(),xl(oi));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 a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??Xl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},jo=ai(Yl,"runtime"),Ho=ai(jo,"provider-health.json"),ri=!1,ql=null;Fo=null});import{existsSync as pi,mkdirSync as tu,readFileSync as nu,writeFileSync as ou}from"fs";import{join as fi}from"path";import{HOME_DIR as ru}from"@wengine-ai/claude-code-router-shared";function it(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let l=Object.keys(t).find(c=>c.toLowerCase()===i);return l?t[l]:null},r=Bo(o,su),s=Bo(o,iu),a=Bo(o,au);(r||s||a)&&Ne.set(n,{provider:n,remaining:ui(r),limit:ui(s),reset:lu(a),capturedAt:Date.now()})}function cu(n){return Ne.get(n)}function Ko(){return Array.from(Ne.values())}function qt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Bo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ui(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function lu(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=uu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function uu(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function du(){try{if(!pi(Wo))return;let n=JSON.parse(nu(Wo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Ne.set(t.provider,t)}}catch{}}function di(){try{if(Ne.size===0)return;pi(Jo)||tu(Jo,{recursive:!0}),ou(Wo,JSON.stringify(Array.from(Ne.values()),null,2),"utf-8")}catch{}}function at(){ci||(ci=!0,du(),li=setInterval(di,6e4),li.unref?.(),process.on("exit",di))}var Jo,Wo,Ne,ci,li,su,iu,au,xe=P(()=>{"use strict";Jo=fi(ru,"runtime"),Wo=fi(Jo,"rate-limit.json"),Ne=new Map,ci=!1,li=null,su=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],iu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],au=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function tn(){return Go||(Go=new Vo),Go}function Xo(){return Qo||(Qo=new Yo),Qo}function pu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function mi(n){let e=pu(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 gi(n,e){let t=tn(),o=n?.[en];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[en]=t.acquire(e)}function Zo(n){let e=n?.[en];e&&tn().release(e)}function hi(n,e){let t=mi(n),o=n?.[en],r=t?Xo().get(t)!==void 0:!1;!o&&!r||(t&&Xo().bind(t,e),gi(n,e))}function fu(n,e,t){let o=tn(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let l=o.count(i);l<s&&(r=i,s=l)}return r}function yi(n,e,t){let o=mi(n),r=Xo(),s=tn(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(i=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(i=e)}if(!i){let l=s.count(e);if(l>=a){let c=fu(e,t.fallbackModels,t.resolve);c&&(i=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}i=i||e,o&&r.bind(o,i)}return gi(n,i),i}var Vo,Yo,Go,Qo,en,nn=P(()=>{"use strict";Vo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},Yo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},Go=null,Qo=null;en="__concurrencyLease"});async function j(n){let e=await n.text();return mu(e,n.status)}function mu(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 _i(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 fe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:l}=await o.read();if(l||(i&&(s+=r.decode(i,{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=P(()=>{"use strict"});function gu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function on(n){for(let e of gu(n))if(e.startsWith("response."))return!0;return!1}var Ue,qo=P(()=>{"use strict";V();Ue=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role==="system")return;if(Array.isArray(r.content)){let i=r.content.map(l=>this.normalizeRequestContent(l,r.role)).filter(l=>l!==null);i.length>0?r.content=i:delete r.content}if(r.role==="tool"){let i={...r};i.type="function_call_output",i.call_id=r.tool_call_id,i.output=r.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}let{thinking:s,...a}=r;r.role==="assistant"&&a.content===void 0||t.push(a)}),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,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await fe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await fe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await j(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",l=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=l.decode(p,{stream:!0})),on(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):on(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}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}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",l,c,u,p,d="",f=new Map,h=new Map,g=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(v){let S=(x,I=null)=>{v.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[{index:0,delta:x,finish_reason:I}]})}
6
6
 
7
- `))},T=S=>{if(!S)return;let I=_.getCacheReadInputTokens(S),M=typeof S.input_tokens=="number"?S.input_tokens:void 0,N=_.getCacheCreationInputTokens(S);v.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[],usage:{prompt_tokens:M,completion_tokens:typeof S.output_tokens=="number"?S.output_tokens:void 0,total_tokens:S.total_tokens,prompt_tokens_details:{cached_tokens:I,cache_creation_tokens:N},cache_read_input_tokens:I,cache_creation_input_tokens:N}})}
7
+ `))},T=x=>{if(!x)return;let I=_.getCacheReadInputTokens(x),M=typeof x.input_tokens=="number"?x.input_tokens:void 0,N=_.getCacheCreationInputTokens(x);v.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[],usage:{prompt_tokens:M,completion_tokens:typeof x.output_tokens=="number"?x.output_tokens:void 0,total_tokens:x.total_tokens,prompt_tokens_details:{cached_tokens:I,cache_creation_tokens:N},cache_read_input_tokens:I,cache_creation_input_tokens:N}})}
8
8
 
9
- `))},P=S=>{m||(m=!0,v.enqueue(r.encode(`data: ${JSON.stringify({error:{message:S,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
9
+ `))},w=x=>{m||(m=!0,v.enqueue(r.encode(`data: ${JSON.stringify({error:{message:x,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
10
10
 
11
- `)))},E=S=>{y||(y=!0,T(u),x({},S))},R=()=>{b||(b=!0,v.enqueue(r.encode(`data: [DONE]
11
+ `)))},E=x=>{y||(y=!0,T(u),S({},x))},R=()=>{b||(b=!0,v.enqueue(r.encode(`data: [DONE]
12
12
 
13
- `)))},A=(S,I)=>{let M=S?.call_id||S?.id||(I!==void 0?`idx_${I}`:void 0);if(!M)return h++;let N=f.get(M);if(N!==void 0)return N;let L=h++;return f.set(M,L),S?.call_id&&S?.id?(f.set(S.id,L),I!==void 0&&f.set(`idx_${I}`,L)):S?.id&&I!==void 0&&f.set(`idx_${I}`,L),L},D=S=>{let I=!1;for(let M of Array.isArray(S)?S:[])if(M?.type==="function_call"){d="tool";let N=A(M,void 0),L=M.call_id||M.id;L&&g.set(N,L),x({role:"assistant",tool_calls:[{index:N,id:L,type:"function",function:{name:M.name||"",arguments:typeof M.arguments=="string"?M.arguments:""}}]}),I=!0}else if(M?.type==="message")for(let N of Array.isArray(M.content)?M.content:[])N?.type==="output_text"&&typeof N.text=="string"&&N.text.trim().length>0&&(d="text",x({role:"assistant",content:N.text}),I=!0);return I},C=S=>{switch(S?.response?.model&&(l=S.response.model),S?.response?.id&&(c=S.response.id),S?.type){case"response.output_item.added":{let I=S.item;if(I?.type!=="function_call")return;d="tool";let M=A(I,S.output_index),N=I.call_id||I.id;N&&g.set(M,N),x({role:"assistant",tool_calls:[{index:M,id:N,type:"function",function:{name:I.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let I=A({id:S.item_id},S.output_index);d="tool";let M=g.get(I);x({tool_calls:[{index:I,...M?{id:M,type:"function"}:{},function:{arguments:typeof S.delta=="string"?S.delta:""}}]});return}case"response.output_text.annotation.added":{let I=S.annotation;if(!I)return;d="annotation",x({annotations:[{type:"url_citation",url_citation:{url:I.url||"",title:I.title||"",content:"",start_index:I.start_index||0,end_index:I.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;d="thinking",x({thinking:{content:S.delta}});return}case"response.output_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;d="text";let I=p!==S.item_id;p=S.item_id;let M={content:S.delta};I&&(M.role="assistant"),x(M);return}case"response.completed":{u=S.response?.usage;let I=Array.isArray(S.response?.output)?S.response.output:[],M=I.some(N=>N?.type==="function_call");if(d===""&&D(I),!M&&d===""){let N=String(S.response?.incomplete_details?.reason??"");P(I.length===0&&!N?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${N||"empty"})`);return}E(d==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=S.response?.usage;let I=String(S.response?.incomplete_details?.reason??"");d===""&&D(Array.isArray(S.response?.output)?S.response.output:[]);let M=I==="max_output_tokens"||I==="max_tokens";if(d===""){P(`Upstream Responses stream produced no content (${I||"incomplete"})`);return}E(M?"length":I==="content_filter"?"content_filter":"stop");return}case"response.failed":{let I=S.response?.error||S.error||void 0;P(I?.message||"Upstream Responses stream failed before completing");return}case"error":{P(S.error?.message||S.message||"Upstream Responses stream error");return}default:return}},O=e.getReader();(async()=>{try{for(;;){let{done:S,value:I}=await O.read();if(S)break;i+=o.decode(I,{stream:!0});let M=i.split(/\r?\n/);i=M.pop()||"";for(let N of M){let L=N.trim();if(!L||L.startsWith(":")||L.startsWith("event:")||!L.startsWith("data:"))continue;let F=L.slice(5).trim();if(!F)continue;if(F==="[DONE]"){R();continue}let J;try{J=JSON.parse(F)}catch{continue}C(J)}}if(i+=o.decode(),i.trim().startsWith("data:")){let S=i.trim().slice(5).trim();if(S&&S!=="[DONE]")try{C(JSON.parse(S))}catch{}}!m&&!y&&(d===""?P("Upstream Responses stream ended before any output"):E(d==="tool"?"tool_calls":"stop")),m||R()}catch(S){console.error("Responses\u2192Chat stream error:",S);try{v.error(S)}catch{}return}finally{try{O.releaseLock()}catch{}}try{v.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:g}=await a.read();if(g||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}i+=new TextDecoder().decode()}finally{a.releaseLock()}r.cancel().catch(()=>{});let l=i.includes("message_start")||i.includes("content_block_start"),c=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")||nn(i))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 j(e);return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i=0,l=!1,c=!1,u="",p=-1,d=[],f=(h,m)=>r.encode(`event: ${h}
13
+ `)))},A=(x,I)=>{let M=x?.call_id||x?.id||(I!==void 0?`idx_${I}`:void 0);if(!M)return g++;let N=f.get(M);if(N!==void 0)return N;let L=g++;return f.set(M,L),x?.call_id&&x?.id?(f.set(x.id,L),I!==void 0&&f.set(`idx_${I}`,L)):x?.id&&I!==void 0&&f.set(`idx_${I}`,L),L},D=x=>{let I=!1;for(let M of Array.isArray(x)?x:[])if(M?.type==="function_call"){d="tool";let N=A(M,void 0),L=M.call_id||M.id;L&&h.set(N,L),S({role:"assistant",tool_calls:[{index:N,id:L,type:"function",function:{name:M.name||"",arguments:typeof M.arguments=="string"?M.arguments:""}}]}),I=!0}else if(M?.type==="message")for(let N of Array.isArray(M.content)?M.content:[])N?.type==="output_text"&&typeof N.text=="string"&&N.text.trim().length>0&&(d="text",S({role:"assistant",content:N.text}),I=!0);return I},C=x=>{switch(x?.response?.model&&(l=x.response.model),x?.response?.id&&(c=x.response.id),x?.type){case"response.output_item.added":{let I=x.item;if(I?.type!=="function_call")return;d="tool";let M=A(I,x.output_index),N=I.call_id||I.id;N&&h.set(M,N),S({role:"assistant",tool_calls:[{index:M,id:N,type:"function",function:{name:I.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let I=A({id:x.item_id},x.output_index);d="tool";let M=h.get(I);S({tool_calls:[{index:I,...M?{id:M,type:"function"}:{},function:{arguments:typeof x.delta=="string"?x.delta:""}}]});return}case"response.output_text.annotation.added":{let I=x.annotation;if(!I)return;d="annotation",S({annotations:[{type:"url_citation",url_citation:{url:I.url||"",title:I.title||"",content:"",start_index:I.start_index||0,end_index:I.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof x.delta!="string"||x.delta.length===0)return;d="thinking",S({thinking:{content:x.delta}});return}case"response.output_text.delta":{if(typeof x.delta!="string"||x.delta.length===0)return;d="text";let I=p!==x.item_id;p=x.item_id;let M={content:x.delta};I&&(M.role="assistant"),S(M);return}case"response.completed":{u=x.response?.usage;let I=Array.isArray(x.response?.output)?x.response.output:[],M=I.some(N=>N?.type==="function_call");if(d===""&&D(I),!M&&d===""){let N=String(x.response?.incomplete_details?.reason??"");w(I.length===0&&!N?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${N||"empty"})`);return}E(d==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=x.response?.usage;let I=String(x.response?.incomplete_details?.reason??"");d===""&&D(Array.isArray(x.response?.output)?x.response.output:[]);let M=I==="max_output_tokens"||I==="max_tokens";if(d===""){w(`Upstream Responses stream produced no content (${I||"incomplete"})`);return}E(M?"length":I==="content_filter"?"content_filter":"stop");return}case"response.failed":{let I=x.response?.error||x.error||void 0;w(I?.message||"Upstream Responses stream failed before completing");return}case"error":{w(x.error?.message||x.message||"Upstream Responses stream error");return}default:return}},O=e.getReader();(async()=>{try{for(;;){let{done:x,value:I}=await O.read();if(x)break;i+=o.decode(I,{stream:!0});let M=i.split(/\r?\n/);i=M.pop()||"";for(let N of M){let L=N.trim();if(!L||L.startsWith(":")||L.startsWith("event:")||!L.startsWith("data:"))continue;let F=L.slice(5).trim();if(!F)continue;if(F==="[DONE]"){R();continue}let J;try{J=JSON.parse(F)}catch{continue}C(J)}}if(i+=o.decode(),i.trim().startsWith("data:")){let x=i.trim().slice(5).trim();if(x&&x!=="[DONE]")try{C(JSON.parse(x))}catch{}}!m&&!y&&(d===""?w("Upstream Responses stream ended before any output"):E(d==="tool"?"tool_calls":"stop")),m||R()}catch(x){console.error("Responses\u2192Chat stream error:",x);try{v.error(x)}catch{}return}finally{try{O.releaseLock()}catch{}}try{v.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:h}=await a.read();if(h||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),on(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}i+=new TextDecoder().decode()}finally{a.releaseLock()}r.cancel().catch(()=>{});let l=i.includes("message_start")||i.includes("content_block_start"),c=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")||on(i))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 j(e);return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i=0,l=!1,c=!1,u="",p=-1,d=[],f=(g,m)=>r.encode(`event: ${g}
14
14
  data: ${JSON.stringify(m)}
15
15
 
16
- `),g=(h,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:h,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(h){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let v of d)if(v.type==="function_call"){let x=d.indexOf(v);h.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:v.call_id||v.id,output_index:x,arguments:v.arguments||""})),v.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:v}))}for(let v of d)if(v.type==="message"){let x=d.indexOf(v);v.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:v}))}h.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:v}=await m.read();if(k)break;y+=o.decode(v,{stream:!0});let x=y.split(`
17
- `);y=x.pop()||"";for(let T of x){let P=T.trim();if(!P||P.startsWith("event:")||!P.startsWith("data:"))continue;let E=P.slice(5).trim();if(E==="[DONE]"){_({}),h.enqueue(r.encode(`data: [DONE]
16
+ `),h=(g,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:g,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(g){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let v of d)if(v.type==="function_call"){let S=d.indexOf(v);g.enqueue(f("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",g.enqueue(f("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",g.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:S,item:v}))}g.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:v}=await m.read();if(k)break;y+=o.decode(v,{stream:!0});let S=y.split(`
17
+ `);y=S.pop()||"";for(let T of S){let w=T.trim();if(!w||w.startsWith("event:")||!w.startsWith("data:"))continue;let E=w.slice(5).trim();if(E==="[DONE]"){_({}),g.enqueue(r.encode(`data: [DONE]
18
18
 
19
- `));continue}let R;try{R=JSON.parse(E)}catch{continue}l||(l=!0,h.enqueue(f("response.created",{type:"response.created",response:g("in_progress")})),h.enqueue(f("response.in_progress",{type:"response.in_progress",response:g("in_progress")})));let A=R.choices?.[0];if(!A)continue;let D=A.delta;if(D?.content){if(!c){c=!0;let C=i++,O={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(O),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:C,item:O}))}h.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:D.content}))}if(Array.isArray(D?.tool_calls))for(let C of D.tool_calls){if(C.id){u=C.id,p=i++;let O={id:C.id,type:"function_call",status:"in_progress",call_id:C.id,name:C.function?.name||"",arguments:""};d.push(O),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:O}))}if(C.function?.arguments){h.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:C.function.arguments}));let O=d.find(S=>S.call_id===u);O&&(O.arguments+=C.function.arguments)}}A.finish_reason&&_(R)}}b||_({}),h.close()}catch(m){h.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",l="",c=-1,u="",p="",d="",f=-1,g="",h="",m=-1,y=0,b=!1,_=!1,k=!1,v=!1,x=null,T=[],P=(O,S)=>r.encode(`event: ${O}
20
- data: ${JSON.stringify(S)}
19
+ `));continue}let R;try{R=JSON.parse(E)}catch{continue}l||(l=!0,g.enqueue(f("response.created",{type:"response.created",response:h("in_progress")})),g.enqueue(f("response.in_progress",{type:"response.in_progress",response:h("in_progress")})));let A=R.choices?.[0];if(!A)continue;let D=A.delta;if(D?.content){if(!c){c=!0;let C=i++,O={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(O),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:C,item:O}))}g.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:D.content}))}if(Array.isArray(D?.tool_calls))for(let C of D.tool_calls){if(C.id){u=C.id,p=i++;let O={id:C.id,type:"function_call",status:"in_progress",call_id:C.id,name:C.function?.name||"",arguments:""};d.push(O),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:O}))}if(C.function?.arguments){g.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:C.function.arguments}));let O=d.find(x=>x.call_id===u);O&&(O.arguments+=C.function.arguments)}}A.finish_reason&&_(R)}}b||_({}),g.close()}catch(m){g.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",l="",c=-1,u="",p="",d="",f=-1,h="",g="",m=-1,y=0,b=!1,_=!1,k=!1,v=!1,S=null,T=[],w=(O,x)=>r.encode(`event: ${O}
20
+ data: ${JSON.stringify(x)}
21
21
 
22
- `),E=(O,S=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:O,model:s,output:S,usage:this.buildResponsesUsage()}),R=()=>{b||(b=!0,C.enqueue(P("response.created",{type:"response.created",response:E("in_progress")})),C.enqueue(P("response.in_progress",{type:"response.in_progress",response:E("in_progress")})))},A=(O,S)=>{C.enqueue(P("response.output_item.done",{type:"response.output_item.done",output_index:O,item:{...S,status:"completed"}}))},D=O=>{if(!v){if(v=!0,_){let S=T.find(I=>I.type==="message");S&&(S.content=[{type:"output_text",text:i}],S.status="completed")}for(let S of T)S.type==="function_call"&&(S.status="completed");return P("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:T,usage:O?{...this.buildResponsesUsage(O)}:this.buildResponsesUsage()}})}},C;return new ReadableStream({async start(O){C=O;try{let S=e.getReader(),I="";for(;;){let{done:N,value:L}=await S.read();if(N)break;I+=o.decode(L,{stream:!0});let F=I.split(`
23
- `);I=F.pop()||"";for(let J of F){let ce=J.trim();if(!ce||ce.startsWith("event:")||!ce.startsWith("data:"))continue;let B=ce.slice(5).trim();if(B==="[DONE]")continue;let z;try{z=JSON.parse(B)}catch{continue}if(z.type==="message_start"&&(a=z.message?.id||a,R()),z.type==="content_block_start"){let $=z.content_block;if(x=$?.type||null,$?.type==="tool_use"){u=$.id||"",p=$.name||"",d="",f=y++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};T.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if($?.type==="thinking"&&(g=$.thinking||"",!k)){k=!0,m=y++,h=`rs_${a}`;let W={id:h,type:"reasoning",status:"in_progress",summary:[]};T.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if($?.type==="text"&&(i=$?.text||"",!_)){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}}if(z.type==="content_block_delta"){let $=z.delta;if($?.type==="text_delta"){if(!_){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}i+=$.text||"",C.enqueue(P("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(g+=$.thinking||"",C.enqueue(P("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:h||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(d+=$.partial_json||"",C.enqueue(P("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:f>=0?f:0,delta:$.partial_json||""})))}if(z.type==="content_block_stop"){if(x==="tool_use"&&u){C.enqueue(P("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:d}));let $=T.find(W=>W.call_id===u);$&&($.arguments=d,$.status="completed"),$&&A(f,$)}if(x==="text"&&_){C.enqueue(P("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:c,content_index:0,text:i}));let $=T.find(W=>W.type==="message");$&&($.content=[{type:"output_text",text:i}],A(c,$))}if(x==="thinking"&&k){let $=T.find(W=>W.type==="reasoning");$&&($.summary=[{type:"summary_text",text:g}],A(m,$))}x=null}if(z.type==="message_delta"){let $=D(z.usage);$&&C.enqueue($)}if(z.type==="message_stop"){let $=D();$&&C.enqueue($),C.enqueue(r.encode(`data: [DONE]
22
+ `),E=(O,x=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:O,model:s,output:x,usage:this.buildResponsesUsage()}),R=()=>{b||(b=!0,C.enqueue(w("response.created",{type:"response.created",response:E("in_progress")})),C.enqueue(w("response.in_progress",{type:"response.in_progress",response:E("in_progress")})))},A=(O,x)=>{C.enqueue(w("response.output_item.done",{type:"response.output_item.done",output_index:O,item:{...x,status:"completed"}}))},D=O=>{if(!v){if(v=!0,_){let x=T.find(I=>I.type==="message");x&&(x.content=[{type:"output_text",text:i}],x.status="completed")}for(let x of T)x.type==="function_call"&&(x.status="completed");return w("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:T,usage:O?{...this.buildResponsesUsage(O)}:this.buildResponsesUsage()}})}},C;return new ReadableStream({async start(O){C=O;try{let x=e.getReader(),I="";for(;;){let{done:N,value:L}=await x.read();if(N)break;I+=o.decode(L,{stream:!0});let F=I.split(`
23
+ `);I=F.pop()||"";for(let J of F){let le=J.trim();if(!le||le.startsWith("event:")||!le.startsWith("data:"))continue;let B=le.slice(5).trim();if(B==="[DONE]")continue;let z;try{z=JSON.parse(B)}catch{continue}if(z.type==="message_start"&&(a=z.message?.id||a,R()),z.type==="content_block_start"){let $=z.content_block;if(S=$?.type||null,$?.type==="tool_use"){u=$.id||"",p=$.name||"",d="",f=y++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};T.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if($?.type==="thinking"&&(h=$.thinking||"",!k)){k=!0,m=y++,g=`rs_${a}`;let W={id:g,type:"reasoning",status:"in_progress",summary:[]};T.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if($?.type==="text"&&(i=$?.text||"",!_)){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}}if(z.type==="content_block_delta"){let $=z.delta;if($?.type==="text_delta"){if(!_){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}i+=$.text||"",C.enqueue(w("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(h+=$.thinking||"",C.enqueue(w("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:g||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(d+=$.partial_json||"",C.enqueue(w("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:f>=0?f:0,delta:$.partial_json||""})))}if(z.type==="content_block_stop"){if(S==="tool_use"&&u){C.enqueue(w("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:d}));let $=T.find(W=>W.call_id===u);$&&($.arguments=d,$.status="completed"),$&&A(f,$)}if(S==="text"&&_){C.enqueue(w("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:c,content_index:0,text:i}));let $=T.find(W=>W.type==="message");$&&($.content=[{type:"output_text",text:i}],A(c,$))}if(S==="thinking"&&k){let $=T.find(W=>W.type==="reasoning");$&&($.summary=[{type:"summary_text",text:h}],A(m,$))}S=null}if(z.type==="message_delta"){let $=D(z.usage);$&&C.enqueue($)}if(z.type==="message_stop"){let $=D();$&&C.enqueue($),C.enqueue(r.encode(`data: [DONE]
24
24
 
25
- `))}}}R();let M=D();M&&C.enqueue(M),I="",C.close()}catch(S){C.error(S)}}})}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;t?.content?.length&&t?.content[0].annotations&&(o=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:o,type:"url_citation"});let r=null,s=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),r=p}else r=c.join("")}let i=(e.output??[]).filter(c=>c.type==="function_call");return i.length>0&&(s=i.map(c=>({id:c.call_id||c.id,type:"function",function:{name:c.name,arguments:c.arguments}}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:r||null,tool_calls:s,thinking:a,annotations:o},logprobs:null,finish_reason:s?"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 Zo,Y,on=w(()=>{"use strict";Zo=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)}},Y=new Zo(100)});import{existsSync as bi,mkdirSync as du,readFileSync as pu,writeFileSync as fu}from"fs";import{join as ki}from"path";import{HOME_DIR as mu}from"@wengine-ai/claude-code-router-shared";function lt(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function rn(n){let e=Fe.get(n);return e?{...e}:void 0}function tr(){return Array.from(Fe.values()).map(n=>({...n}))}function gu(){try{if(!bi(er))return;let n=JSON.parse(pu(er,"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;Fe.set(t.provider,t)}}catch{}}function _i(){try{if(Fe.size===0)return;bi(qo)||du(qo,{recursive:!0}),fu(er,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function ut(){hi||(hi=!0,gu(),yi=setInterval(_i,6e4),yi.unref?.(),process.on("exit",_i))}var qo,er,Fe,hi,yi,Ce=w(()=>{"use strict";qo=ki(mu,"runtime"),er=ki(qo,"quota-store.json"),Fe=new Map,hi=!1,yi=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!hu.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 hu,je=w(()=>{"use strict";hu=/^[A-Za-z0-9_-]+$/});import{existsSync as xi}from"fs";import{readFile as yu,readdir as _u}from"fs/promises";import{homedir as bu}from"os";import{isAbsolute as ku,join as dt,normalize as vu}from"path";import{openSqliteDatabase as Tu}from"@wengine-ai/claude-code-router-shared";function Au(){if(He.size<=vi)return;let n=[...He.keys()].slice(0,He.size-vi);for(let e of n)He.delete(e)}function Ou(){if(ze.size<=Ti)return;let n=[...ze].slice(0,ze.size-Ti);for(let e of n)ze.delete(e)}function Iu(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 Mu(n,e){let t;try{t=Tu(n,{readonly:!0}).db;let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let a=o.get(r,r)?.workspace_path;if(typeof a=="string"&&a.trim())return a.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function Lu(n,e){let t;try{t=await _u(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(xi(s))try{let a=JSON.parse(await yu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Si(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=He.get(e);if(t)return t;let o=async()=>{let r=Iu(e);if(r.length===0)return null;let s=dt(xu(),Su),a=dt(s,Cu);if(xi(a)){let i=Mu(a,r);if(i)return i}return Lu(dt(s,Ru),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),Ou();for(let a=0;a<wu&&!r;a++)await Eu(Pu),r=await o()}if(!r||!ku(r))return null;let s=vu(r);return He.set(e,s),Au(),s}catch{return null}}var xu,Su,Cu,Ru,vi,Ti,wu,Pu,He,ze,Eu,Ci=w(()=>{"use strict";xu=()=>process.env.CCR_ZCODE_DIR||dt(bu(),".zcode"),Su="v2",Cu="tasks-index.sqlite",Ru="sessions",vi=500,Ti=500,wu=3,Pu=50,He=new Map,ze=new Set,Eu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as $u}from"node:crypto";import{CCR_PROJECT_HEADER as nr}from"@wengine-ai/claude-code-router-shared";function Pi(n){return typeof n=="string"&&n.length<=Nu}function Uu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of wi){let{value:t}=sn(n,e);if(!Pi(t))continue;let o=ge(t);if(o)return o}}function Fu(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 ju(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 sn(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 Ri(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 pt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function or(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Ai(n){return typeof n=="string"&&Du.includes(n)}function Vu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(Ai(n?.clientType))return n.clientType;let e=ju(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Fu(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(sn(n,nr).present||sn(n,"x-session-affinity").present)return"pi";if(Vu(t,o))return"zcode";let a=t["x-anthropic-billing-header"];if(typeof a=="string"&&a.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let i=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(i)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(i).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Oi(n){return Ei[n]}function Yu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||$u();return n.__ccrRequestScopeId=e,e}function Re(n,e={}){let t=Be(n),o=Oi(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Yu(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,Ri(n,nr),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of wi)Ri(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Xu(){}var wi,Nu,Du,Hu,zu,Bu,Ju,Wu,Ku,Gu,Qu,Ei,Je=w(()=>{"use strict";je();wi=["x-session-affinity","x-session-id","x-litellm-session-id"],Nu=256;Du=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Hu={type:"claude-code",createContext(n){return or(n,"claude-code")}},zu={type:"zcode",createContext(n){return or(n,"zcode")}},Bu={type:"pi",createContext(n){let e=sn(n,nr),t=Uu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=Pi(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Ju={type:"qwen-code",createContext(n){return or(n,"qwen-code")}},Wu={type:"opencode",createContext(){return pt("opencode")}},Ku={type:"codex",createContext(){return pt("codex")}},Gu={type:"api",createContext(){return pt("api")}},Qu={type:"unknown",createContext(){return pt("unknown")}},Ei={"claude-code":Hu,zcode:zu,pi:Bu,"qwen-code":Ju,opencode:Wu,codex:Ku,api:Gu,unknown:Qu}});import{get_encoding as qu}from"tiktoken";import{readFile as rr}from"fs/promises";import{opendir as ed,stat as td}from"fs/promises";import{isAbsolute as nd,join as sr}from"path";import{CLAUDE_PROJECTS_DIR as Ii,HOME_DIR as Mi,getClaudeProjectId as Li,isZcodeProjectTakeoverActive as od}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Fi(e,t);if(r.code==="model_unhealthy"){let i=Q(e,t,!0);if(i)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),i}let s=n.sessionId||n.clientContext?.stableSessionId,a=Di[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:a})}function cn(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 mt(n){let e=cn(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 sd(n,e){if(!e||!n)return null;let t=cn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=cn(r);if(a&&t.includes(a))return s}return null}function id(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function an(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 ft(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 Fi(n,e){let t=an(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 a=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!H().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let l=rn(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 Q(n,e,t,o,r,s,a){let i=an(n);if(!i)return a?null:n;let{providerName:l,routeModel:c}=i,u=ft(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(l,c,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(l,c,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(l,c,o)}}if(!t&&!H().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=rn(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,f=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||f)return null}return`${u.provider.name},${u.model}`}function Z(n,e,t,o,r,s){let a=[t?.[n],o?.[n]];for(let i of a)if(!(!Array.isArray(i)||i.length===0))for(let l of i){let c=Q(l,e,!1,n,void 0,void 0,s);if(c)return c}return null}function ad(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 gt(n){let e=cn(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 ji(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,id(e))}function Hi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function cd(n,e,t,o,r,s,a,i,l,c,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??l??6e4,g=ji(e,r,d),h=n.modelFamily,m=Hi(d,t,c),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||g>m)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let v=i?Z("extendedContext",o,t.fallback,a,h,u):null;if(v)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:v,scenarioType:"extendedContext",isFallback:!0};if(u){let x=ee(n,t.extendedContext,o,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(g>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?Q(t.longContext,o,!1,"longContext",i,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=i?Z("longContext",o,t.fallback,a,h,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 x=ee(n,t.longContext,o,"longContext");if(x)return{model:x,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=Q(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let v=i?Z("webSearch",o,t.fallback,a,h,u):null;if(v)return n.log.info("Family: using webSearch fallback model"),{model:v,scenarioType:"webSearch",isFallback:!0};if(u){let x=ee(n,t.webSearch,o,"webSearch");if(x)return{model:x,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let k=Q(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let v=i?Z("think",o,t.fallback,a,h,u):null;if(v)return n.log.info("Family: using think fallback model"),{model:v,scenarioType:"think",isFallback:!0};if(u){let x=ee(n,t.think,o,"think");if(x)return{model:x,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let k=Q(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let v=i?Z("default",o,t.fallback,a,h,u):null;if(v)return n.log.info("Family: using default fallback model"),{model:v,scenarioType:"default",isFallback:!0};if(u){let x=ee(n,t.default,o,"default");if(x)return{model:x,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function fd(){if(we.size<=$i)return;let n=[...we.keys()].slice(0,we.size-$i);for(let e of n)we.delete(e)}function md(){if(We.size<=Ni)return;let n=[...We].slice(0,We.size-Ni);for(let e of n)We.delete(e)}var Di,te,le,ln,rd,ld,un,we,$i,We,Ni,ud,dd,pd,Ui,zi,Pe=w(()=>{"use strict";on();re();Ce();Yt();tn();je();Ci();Je();Di={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||Di[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=qu("cl100k_base"),ln=(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=>{if(s.type==="text")o+=le.encode(s.text).length;else if(s.type==="tool_use")o+=le.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=le.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=le.encode(typeof a=="string"?a:JSON.stringify(a)).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},rd=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 zi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Si(n.sessionId);s&&od(s)&&(r=Li(s))}if(r){n.projectId=r;let s=sr(Mi,r,"config.json");if(!t&&n.sessionId){let a=sr(Mi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await rr(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await rr(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Li(a.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(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch(a){if(a instanceof te)throw a;if(t&&a?.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(!a||a.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${a.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};ld=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),l=i?.enableFallback===!0,c=l?i?.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 C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),d=C[1])}let f=typeof n.body?.model=="string"?n.body.model:"",g=f.indexOf(",")>0,m=(g?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),y,b;if(!s&&m)for(let C of a){if(C?.enabled===!1||!Array.isArray(C?.models))continue;let O=C.models.find(S=>typeof S=="string"&&S.toLowerCase()===m);if(O){y=C,b=O;break}}let{family:_,extended:k,isCcrAlias:v}=mt(n.body.model),x=i?.families?.[_||""];if(x&&i?.enableFamilyRouting&&!y){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=x.fallback;let C=cd(n,e,x,a,o,k,u,l,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(C)return{model:C.model,scenarioType:C.scenarioType}}if(g&&y&&b){let C=`${y.name},${b}`;n.body.model!==C&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${C}`),n.body.model=C)}if(n.body.model.includes(",")&&!s){let C=Q(n.body.model,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=l?Z("default",a,void 0,u,void 0,s):null;if(O)return n.log.info(`Using fallback for explicit model: ${O}`),{model:O,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let T=v&&!i?.enableFamilyRouting?null:sd(n.body.model,i?.models);if(T){let C=Q(T,a,!1,"modelMapping",l,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${T}`),{model:C,scenarioType:"modelMapping"};let O=l?Z("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let S=ee(n,T,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${T} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let P=n.clientContext,E=ji(e,o,P),R=Hi(P,void 0,i?.extendedContextThreshold);if(E>R&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${E}, estimated: ${e}, threshold: ${R}`);let C=Q(i.extendedContext,a,!1,"extendedContext",l,p,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=l?Z("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let S=ee(n,i.extendedContext,a,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext"}}}let A=P?.longContextThreshold??i?.longContextThreshold??6e4;if(E>A&&i?.longContext){n.log.info(`Using long context model due to token count: ${E}, estimated: ${e}, threshold: ${A}`);let C=Q(i.longContext,a,!1,"longContext",l,p,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=l?Z("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let S=ee(n,i.longContext,a,"longContext");if(S)return{model:S,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let C=Q(i.background,a,!1,"background",l,p,s);if(C)return{model:C,scenarioType:"background"};let O=l?Z("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let S=ee(n,i.background,a,"background");if(S)return{model:S,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&i?.webSearch){let C=Q(i.webSearch,a,!1,"webSearch",l,p,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=l?Z("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let S=ee(n,i.webSearch,a,"webSearch");if(S)return{model:S,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=Q(i.think,a,!1,"think",l,p,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=l?Z("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let S=ee(n,i.think,a,"think");if(S)return{model:S,scenarioType:"think"}}}if(i?.default){let C=Q(i.default,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=l?Z("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let S=Q(i.default,a,!0,"default",l,p,s);if(S)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:S,scenarioType:"default"}}if(s){let C=ee(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},un=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,o.getAll());let s=await rd(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=i,n.strictProjectRouting=c,n.fallbackConfig=c?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Y.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:f}=n.body,g=o.get("REWRITE_SYSTEM_PROMPT");if(g&&d.length>1&&d[1]?.text?.includes("<env>")){let h=await rr(g,"utf-8");d[1].text=`${h}<env>${d[1].text.split("<env>").pop()}`}try{let[h,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(h,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,h)).tokenCount:b=ln(p,d,f),n.tokenCount=b;let _,k=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!nd(k)||!/\.(c|m)?js$/i.test(k))throw new Error(`CUSTOM_ROUTER_PATH must be an absolute .js/.cjs/.mjs path, got: ${String(k).slice(0,120)}`);let P=await import(k),E=typeof P=="function"?P:P?.default;if(typeof E!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await E(n,o.getAll(),{event:r})}catch(P){n.log.error(`failed to load custom router: ${P.message}`)}if(_)n.scenarioType="default";else{let P=await ld(n,b,o,u,s,!!s);_=P.model,n.scenarioType=P.scenarioType}let{family:v}=mt(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&v?a.families?.[v]:void 0,T=[x?.image,a?.image].filter((P,E,R)=>!!P&&R.indexOf(P)===E);if(T.length>0&&ad(n)&&!gt(_))if(T.includes(_))n.scenarioType="image";else{let P=T.map(E=>Q(E,l,!1,"image",i,!c,c)).find(E=>!!E);if(P)n.log.info(`Using image model fallback for ${_}`),_=P,n.scenarioType="image";else{let E=i?Z("image",l,x?.fallback,n.fallbackConfig,v||void 0,c):null;if(E)n.log.info(`Using image fallback model: ${E}`),_=E,n.scenarioType="image";else if(c){let R=ee(n,T[0],l,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${T.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let P=n.scenarioType||"default",E=[...(n.familyFallback||{})[P]||[],...(n.fallbackConfig||{})[P]||[]];_=mi(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:E,resolve:R=>Q(R,l,!1,P,i,!c,c),log:R=>n.log.info(R)})}typeof _=="string"&&_.trim()?n.body.model=_:(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(h){if(h instanceof te)throw h;if(n.log.error(`Error in router middleware: ${h.message}`),c){let m=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${h.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},we=new Map,$i=1e3,We=new Set,Ni=1e3,ud=3,dd=50,pd=n=>new Promise(e=>setTimeout(e,n));Ui=async n=>{let e=await ed(Ii),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=sr(Ii,s,`${n}.jsonl`);try{return(await td(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},zi=async n=>{let e=ge(n);if(!e)return null;if(we.has(e))return we.get(e)||null;try{let t=await Ui(e);if(!t&&!We.has(e)){We.add(e),md();for(let o=0;o<ud&&!t;o++)await pd(dd),t=await Ui(e)}return t?(we.set(e,t),fd(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
25
+ `))}}}R();let M=D();M&&C.enqueue(M),I="",C.close()}catch(x){C.error(x)}}})}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;t?.content?.length&&t?.content[0].annotations&&(o=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:o,type:"url_citation"});let r=null,s=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),r=p}else r=c.join("")}let i=(e.output??[]).filter(c=>c.type==="function_call");return i.length>0&&(s=i.map(c=>({id:c.call_id||c.id,type:"function",function:{name:c.name,arguments:c.arguments}}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:r||null,tool_calls:s,thinking:a,annotations:o},logprobs:null,finish_reason:s?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var er,Y,rn=P(()=>{"use strict";er=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},Y=new er(100)});import{existsSync as Ti,mkdirSync as hu,readFileSync as yu,writeFileSync as _u}from"fs";import{join as Si}from"path";import{HOME_DIR as bu}from"@wengine-ai/claude-code-router-shared";function lt(n,e){n&&De.set(n,{...e,provider:n,capturedAt:Date.now()})}function sn(n){let e=De.get(n);return e?{...e}:void 0}function or(){return Array.from(De.values()).map(n=>({...n}))}function ku(){try{if(!Ti(nr))return;let n=JSON.parse(yu(nr,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;De.set(t.provider,t)}}catch{}}function vi(){try{if(De.size===0)return;Ti(tr)||hu(tr,{recursive:!0}),_u(nr,JSON.stringify(Array.from(De.values()),null,2),"utf-8")}catch{}}function ut(){bi||(bi=!0,ku(),ki=setInterval(vi,6e4),ki.unref?.(),process.on("exit",vi))}var tr,nr,De,bi,ki,Ce=P(()=>{"use strict";tr=Si(bu,"runtime"),nr=Si(tr,"quota-store.json"),De=new Map,bi=!1,ki=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!vu.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 vu,Fe=P(()=>{"use strict";vu=/^[A-Za-z0-9_-]+$/});import{existsSync as Ri}from"fs";import{readFile as Tu,readdir as Su}from"fs/promises";import{homedir as xu}from"os";import{isAbsolute as Cu,join as dt,normalize as Ru}from"path";import{openSqliteDatabase as wu}from"@wengine-ai/claude-code-router-shared";function $u(){if(je.size<=xi)return;let n=[...je.keys()].slice(0,je.size-xi);for(let e of n)je.delete(e)}function Nu(){if(He.size<=Ci)return;let n=[...He].slice(0,He.size-Ci);for(let e of n)He.delete(e)}function Uu(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 Du(n,e){let t;try{t=wu(n,{readonly:!0}).db;let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let a=o.get(r,r)?.workspace_path;if(typeof a=="string"&&a.trim())return a.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function Fu(n,e){let t;try{t=await Su(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(Ri(s))try{let a=JSON.parse(await Tu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function wi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=je.get(e);if(t)return t;let o=async()=>{let r=Uu(e);if(r.length===0)return null;let s=dt(Pu(),Eu),a=dt(s,Au);if(Ri(a)){let i=Du(a,r);if(i)return i}return Fu(dt(s,Ou),r)};try{let r=await o();if(!r&&!He.has(e)){He.add(e),Nu();for(let a=0;a<Iu&&!r;a++)await Lu(Mu),r=await o()}if(!r||!Cu(r))return null;let s=Ru(r);return je.set(e,s),$u(),s}catch{return null}}var Pu,Eu,Au,Ou,xi,Ci,Iu,Mu,je,He,Lu,Pi=P(()=>{"use strict";Pu=()=>process.env.CCR_ZCODE_DIR||dt(xu(),".zcode"),Eu="v2",Au="tasks-index.sqlite",Ou="sessions",xi=500,Ci=500,Iu=3,Mu=50,je=new Map,He=new Set,Lu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as ju}from"node:crypto";import{CCR_PROJECT_HEADER as rr}from"@wengine-ai/claude-code-router-shared";function Oi(n){return typeof n=="string"&&n.length<=Hu}function zu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Ai){let{value:t}=an(n,e);if(!Oi(t))continue;let o=ge(t);if(o)return o}}function Ju(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 Wu(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 an(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 Ei(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 pt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function sr(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Mi(n){return typeof n=="string"&&Bu.includes(n)}function ed(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function ze(n){if(Mi(n?.clientType))return n.clientType;let e=Wu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Ju(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(an(n,rr).present||an(n,"x-session-affinity").present)return"pi";if(ed(t,o))return"zcode";let a=t["x-anthropic-billing-header"];if(typeof a=="string"&&a.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let i=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(i)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(i).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Li(n){return Ii[n]}function td(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||ju();return n.__ccrRequestScopeId=e,e}function Re(n,e={}){let t=ze(n),o=Li(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:td(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,Ei(n,rr),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Ai)Ei(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function nd(){}var Ai,Hu,Bu,Ku,Gu,Qu,Vu,Yu,Xu,Zu,qu,Ii,Be=P(()=>{"use strict";Fe();Ai=["x-session-affinity","x-session-id","x-litellm-session-id"],Hu=256;Bu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Ku={type:"claude-code",createContext(n){return sr(n,"claude-code")}},Gu={type:"zcode",createContext(n){return sr(n,"zcode")}},Qu={type:"pi",createContext(n){let e=an(n,rr),t=zu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=Oi(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Vu={type:"qwen-code",createContext(n){return sr(n,"qwen-code")}},Yu={type:"opencode",createContext(){return pt("opencode")}},Xu={type:"codex",createContext(){return pt("codex")}},Zu={type:"api",createContext(){return pt("api")}},qu={type:"unknown",createContext(){return pt("unknown")}},Ii={"claude-code":Ku,zcode:Gu,pi:Qu,"qwen-code":Vu,opencode:Yu,codex:Xu,api:Zu,unknown:qu}});import{get_encoding as rd}from"tiktoken";import{readFile as ir}from"fs/promises";import{opendir as sd,stat as id}from"fs/promises";import{isAbsolute as ad,join as ar}from"path";import{CLAUDE_PROJECTS_DIR as $i,HOME_DIR as Ni,getClaudeProjectId as Ui,isZcodeProjectTakeoverActive as cd}from"@wengine-ai/claude-code-router-shared";function te(n,e,t,o){let r=zi(e,t);if(r.code==="model_unhealthy"){let i=Q(e,t,!0);if(i)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),i}let s=n.sessionId||n.clientContext?.stableSessionId,a=Hi[r.code]||502;throw new ne(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function ln(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 mt(n){let e=ln(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 ud(n,e){if(!e||!n)return null;let t=ln(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=ln(r);if(a&&t.includes(a))return s}return null}function dd(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function cn(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function ft(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 zi(n,e){let t=cn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(c=>c.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!H().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let l=sn(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 Q(n,e,t,o,r,s,a){let i=cn(n);if(!i)return a?null:n;let{providerName:l,routeModel:c}=i,u=ft(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=$e(),f=d.getPromotion(l,c,o,e);if(f){let h=cn(f);if(h){let g=ft(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=$e(),f=d.getPromotion(l,c,o,e);if(f){let h=cn(f);if(h){let g=ft(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(l,c,o)}}if(!t&&!H().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=sn(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,f=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||f)return null}return`${u.provider.name},${u.model}`}function q(n,e,t,o,r,s){let a=[t?.[n],o?.[n]];for(let i of a)if(!(!Array.isArray(i)||i.length===0))for(let l of i){let c=Q(l,e,!1,n,void 0,void 0,s);if(c)return c}return null}function pd(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 gt(n){let e=ln(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 Bi(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,dd(e))}function Ji(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function fd(n,e,t,o,r,s,a,i,l,c,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??l??6e4,h=Bi(e,r,d),g=n.modelFamily,m=Ji(d,t,c),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||h>m)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let v=i?q("extendedContext",o,t.fallback,a,g,u):null;if(v)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:v,scenarioType:"extendedContext",isFallback:!0};if(u){let S=te(n,t.extendedContext,o,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(h>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?Q(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let v=i?q("longContext",o,t.fallback,a,g,u):null;if(v)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:v,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let S=te(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=Q(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let v=i?q("webSearch",o,t.fallback,a,g,u):null;if(v)return n.log.info("Family: using webSearch fallback model"),{model:v,scenarioType:"webSearch",isFallback:!0};if(u){let S=te(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=Q(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let v=i?q("think",o,t.fallback,a,g,u):null;if(v)return n.log.info("Family: using think fallback model"),{model:v,scenarioType:"think",isFallback:!0};if(u){let S=te(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=Q(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let v=i?q("default",o,t.fallback,a,g,u):null;if(v)return n.log.info("Family: using default fallback model"),{model:v,scenarioType:"default",isFallback:!0};if(u){let S=te(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 _d(){if(we.size<=Di)return;let n=[...we.keys()].slice(0,we.size-Di);for(let e of n)we.delete(e)}function bd(){if(Je.size<=Fi)return;let n=[...Je].slice(0,Je.size-Fi);for(let e of n)Je.delete(e)}var Hi,ne,ue,un,ld,md,dn,we,Di,Je,Fi,gd,hd,yd,ji,Wi,Pe=P(()=>{"use strict";rn();ie();Ce();Xt();nn();Fe();Pi();Be();Hi={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500,invalid_project_id:400,project_config_not_found:404},ne=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Hi[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};ue=rd("cl100k_base"),un=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=ue.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=ue.encode(s.text).length;else if(s.type==="tool_use")o+=ue.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=ue.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=ue.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=ue.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=ue.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=ue.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=ue.encode(r.name+r.description).length),r.input_schema&&(o+=ue.encode(JSON.stringify(r.input_schema)).length)}),o},ld=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new ne(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Wi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await wi(n.sessionId);s&&cd(s)&&(r=Ui(s))}if(r){n.projectId=r;let s=ar(Ni,r,"config.json");if(!t&&n.sessionId){let a=ar(Ni,r,`${n.sessionId}.json`);try{let i=JSON.parse(await ir(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await ir(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Ui(a.projectPath)!==o))throw new ne(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch(a){if(a instanceof ne)throw a;if(t&&a?.code==="ENOENT")throw new ne(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!a||a.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new ne(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${a.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};md=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),l=i?.enableFallback===!0,c=l?i?.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 C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),d=C[1])}let f=typeof n.body?.model=="string"?n.body.model:"",h=f.indexOf(",")>0,m=(h?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),y,b;if(!s&&m)for(let C of a){if(C?.enabled===!1||!Array.isArray(C?.models))continue;let O=C.models.find(x=>typeof x=="string"&&x.toLowerCase()===m);if(O){y=C,b=O;break}}let{family:_,extended:k,isCcrAlias:v}=mt(n.body.model),S=i?.families?.[_||""];if(S&&i?.enableFamilyRouting&&!y){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=S.fallback;let C=fd(n,e,S,a,o,k,u,l,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(C)return{model:C.model,scenarioType:C.scenarioType}}if(h&&y&&b){let C=`${y.name},${b}`;n.body.model!==C&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${C}`),n.body.model=C)}if(n.body.model.includes(",")&&!s){let C=Q(n.body.model,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=l?q("default",a,void 0,u,void 0,s):null;if(O)return n.log.info(`Using fallback for explicit model: ${O}`),{model:O,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let T=v&&!i?.enableFamilyRouting?null:ud(n.body.model,i?.models);if(T){let C=Q(T,a,!1,"modelMapping",l,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${T}`),{model:C,scenarioType:"modelMapping"};let O=l?q("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let x=te(n,T,a,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${T} unavailable (fail pool), skipping`)}if(y&&!h){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let w=n.clientContext,E=Bi(e,o,w),R=Ji(w,void 0,i?.extendedContextThreshold);if(E>R&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${E}, estimated: ${e}, threshold: ${R}`);let C=Q(i.extendedContext,a,!1,"extendedContext",l,p,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=l?q("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let x=te(n,i.extendedContext,a,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext"}}}let A=w?.longContextThreshold??i?.longContextThreshold??6e4;if(E>A&&i?.longContext){n.log.info(`Using long context model due to token count: ${E}, estimated: ${e}, threshold: ${A}`);let C=Q(i.longContext,a,!1,"longContext",l,p,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=l?q("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let x=te(n,i.longContext,a,"longContext");if(x)return{model:x,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let C=Q(i.background,a,!1,"background",l,p,s);if(C)return{model:C,scenarioType:"background"};let O=l?q("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let x=te(n,i.background,a,"background");if(x)return{model:x,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&i?.webSearch){let C=Q(i.webSearch,a,!1,"webSearch",l,p,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=l?q("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let x=te(n,i.webSearch,a,"webSearch");if(x)return{model:x,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=Q(i.think,a,!1,"think",l,p,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=l?q("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let x=te(n,i.think,a,"think");if(x)return{model:x,scenarioType:"think"}}}if(i?.default){let C=Q(i.default,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=l?q("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let x=Q(i.default,a,!0,"default",l,p,s);if(x)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:x,scenarioType:"default"}}if(s){let C=te(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},dn=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,o.getAll());let s=await ld(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=i,n.strictProjectRouting=c,n.fallbackConfig=c?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Y.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:f}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&d.length>1&&d[1]?.text?.includes("<env>")){let g=await ir(h,"utf-8");d[1].text=`${g}<env>${d[1].text.split("<env>").pop()}`}try{let[g,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(g,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,g)).tokenCount:b=un(p,d,f),n.tokenCount=b;let _,k=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!ad(k)||!/\.(c|m)?js$/i.test(k))throw new Error(`CUSTOM_ROUTER_PATH must be an absolute .js/.cjs/.mjs path, got: ${String(k).slice(0,120)}`);let w=await import(k),E=typeof w=="function"?w:w?.default;if(typeof E!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await E(n,o.getAll(),{event:r})}catch(w){n.log.error(`failed to load custom router: ${w.message}`)}if(_)n.scenarioType="default";else{let w=await md(n,b,o,u,s,!!s);_=w.model,n.scenarioType=w.scenarioType}let{family:v}=mt(n.originalModel||n.body.model),S=a?.enableFamilyRouting&&v?a.families?.[v]:void 0,T=[S?.image,a?.image].filter((w,E,R)=>!!w&&R.indexOf(w)===E);if(T.length>0&&pd(n)&&!gt(_))if(T.includes(_))n.scenarioType="image";else{let w=T.map(E=>Q(E,l,!1,"image",i,!c,c)).find(E=>!!E);if(w)n.log.info(`Using image model fallback for ${_}`),_=w,n.scenarioType="image";else{let E=i?q("image",l,S?.fallback,n.fallbackConfig,v||void 0,c):null;if(E)n.log.info(`Using image fallback model: ${E}`),_=E,n.scenarioType="image";else if(c){let R=te(n,T[0],l,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${T.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let w=n.scenarioType||"default",E=[...(n.familyFallback||{})[w]||[],...(n.fallbackConfig||{})[w]||[]];_=yi(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:E,resolve:R=>Q(R,l,!1,w,i,!c,c),log:R=>n.log.info(R)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(g){if(g instanceof ne)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),c){let m=n.sessionId||n.clientContext?.stableSessionId;throw new ne(`Project routing error: router failure in project mode. ${g.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},we=new Map,Di=1e3,Je=new Set,Fi=1e3,gd=3,hd=50,yd=n=>new Promise(e=>setTimeout(e,n));ji=async n=>{let e=await sd($i),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=ar($i,s,`${n}.jsonl`);try{return(await id(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Wi=async n=>{let e=ge(n);if(!e)return null;if(we.has(e))return we.get(e)||null;try{let t=await ji(e);if(!t&&!Je.has(e)){Je.add(e),bd();for(let o=0;o<gd&&!t;o++)await yd(hd),t=await ji(e)}return t?(we.set(e,t),_d(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
26
26
  `):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
27
- ${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 Ji(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Ao(n);let s=bd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&gd.test(r.model)&&await un(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let a=n.provider;if(!a&&r?.model){let c=r.model.split(",");c.length>1&&(a=c[0],r.model=c.slice(1).join(","))}let i=a?t.providerService.getProvider(a):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(","),f=t.providerService.getProvider(p);f&&(i=f,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw K(`Provider '${a}' not found`,404,"provider_not_found");n.provider=i.name||a;let l=o.endPoint==="/v1/messages"&&s;s&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=l;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&ht(r);let c={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:Gi(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Ki(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let v=JSON.stringify(k.content??"");y.has(v)||(y.add(v),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await Qi(u,p,i,t,d,o,c);try{i?.baseUrl&&f?.headers&&it(a,i.baseUrl,f.headers)}catch{}let g=await Vi(u,f,i,o,d,c);g=await Wi(r,g,i.name||a);let h=Yi(g,e,r,t);try{let m=r.model||n.originalModel;a&&m&&H().recordSuccess(a,m)}catch{}return h}catch(c){if(c instanceof te)throw c;if(!Oo(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Ji(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await hd(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function Wi(n,e,t){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let s=e.body.getReader(),a=new TextDecoder,i=[],l="";for(let d=0;d<8;d++){let f=await s.read();if(f.done||(f.value&&(i.push(f.value),l+=a.decode(f.value,{stream:!0})),l.split(`
28
- `).some(g=>g.startsWith("data:"))))break}if(l+=a.decode(),i.length===0)throw s.releaseLock(),K(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(l.includes("event: error")){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned error in SSE stream: ${d}`,400,"provider_response_error")}if(l.split(`
29
- `).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let g of i)d.enqueue(g);let f=()=>{s.read().then(({done:g,value:h})=>{g?d.close():(d.enqueue(h),f())}).catch(g=>d.error(g))};f()},cancel:()=>{s.cancel()}}),p=await Gs(u);if(p.verdict==="empty")throw K(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(Qs(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function hd(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),c=H(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&dn(r.rawBody)||r?.message&&dn(r.message);if(u&&p&&(f?(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 h=b=>{let[_,...k]=b.split(","),v=_?.trim(),x=k.join(",").trim();return!v||!x?null:{provider:v,model:x,key:`${v},${x}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.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(x=>x.type==="image"||x.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`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=h(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let v=t.providerService.getProviders(),x=ft(v,k.provider,k.model);if(!x){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let T=x.provider.name,P=x.model;if(!c.isAvailable(T,P,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let E=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(E&&$e(n,E,{name:T}).terminalError)continue;let R;for(let A=1;A<=2;A++)try{n.log.info(`Trying fallback model: ${T},${P}${A>1?" (retry)":""}`);let D={...n.body};D.model=P;let C={...n,provider:T,body:D},O=x.provider,S={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Gi(C,o,C.codexDetected===!0)},{requestBody:I,config:M,bypass:N}=await Ki(D,O,o,n.headers,S),L=await Qi(I,M,O,t,N,o,S);try{O?.baseUrl&&L?.headers&&it(T,O.baseUrl,L.headers)}catch{}let F=await Vi(I,L,O,o,N,S);return F=await Wi(D,F,T),n.log.info(`Fallback model ${T},${P} succeeded`),c.recordSuccess(T,P),u&&p&&!n.strictProjectRouting&&(Ne().promote(u,p,s,T,P),n.log.info(`Promoted fallback model ${T},${P} for ${u},${p}:${s}`),f?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=D,fi(n,`${T},${P}`),Yi(F,e,D,t)}catch(D){if(R=D,Oo(n,E,D,{name:T}))break;if(A===1){n.log.warn(`Fallback model ${T},${P} failed, retrying once: ${D.message}`);continue}}c.recordFailure(T,P,R?.message),n.log.warn(`Fallback model ${T},${P} failed after retry: ${R?.message}`),t.recordUsage?.({provider:T,model:P,originalModel:n.originalModel||p||n.body.model,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})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Ki(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw K("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=$e(r.req,s,e).terminalError;if(u)throw u;await s.ensureUsable?.()}let a=JSON.parse(JSON.stringify(n)),i=a?.system;if(typeof i=="string"&&i.includes("cch="))a.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let u=0;u<i.length;u++){let p=i[u],d=typeof p=="string"?p:p?.text??"";if(d.includes("cch=")){let f=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?i[u]=f:typeof p?.text=="string"&&(p.text=f)}}let l={},c=!1;if(c=yd(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(a);u.body?(a=u.body,l=u.config||{}):a=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(a,e,r);p.body?(a=p.body,l={...l,...p.config}):a=p}if(!c&&e.transformer?.[n.model]?.use?.length)for(let u of e.transformer[n.model].use)!u||typeof u.transformRequestIn!="function"||(a=await u.transformRequestIn(a,e,r));return{requestBody:a,config:l,bypass:c}}function yd(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 _d(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 Gi(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function bd(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 Qi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>Bi(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):Bi(n,e,t,o,r,s,a)}function Ke(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
30
- `):""}async function Bi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);i&&(await i.ensureUsable?.(),await i.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,a);if(d.body){n=d.body;let f=e.headers||{};d.config?.headers&&(f={...f,...d.config.headers},delete f.host,delete d.config.headers),e={...e,...d.config,headers:f}}else n=d}let c={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(c=await i.signRequest({headers:c,requestBody:n,provider:t,config:e})),_d(c,a?.req);for(let d in c)(c[d]==="undefined"||["authorization","Authorization"].includes(d)&&c[d]?.includes("undefined"))&&delete c[d];!i?.suppressDebugLog&&Jt(o.configService)&&Hs(o.log,a.req.id,{url:String(l),headers:c,body:n});let u,p=()=>Js(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:i?void 0:de(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await Te(i,0,void 0,Ke(n),Zs(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!$e(a.req,i,t).refreshUsed){$e(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),c=await i.signRequest({headers:c,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(g){throw i?await Te(i,u.status,void 0,Ke(n)):g}if(i){let g=await Te(i,u.status,d,Ke(n));throw o.log.error(`[provider_response_error] Plugin(${i.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 f=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||dn(d),f.rawBody=d,f}if(u.ok){let d=u.headers.get("content-type")||"",f=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${f} contentType=${d} ok=${u.ok} status=${u.status} hasBody=${!!u.body}`),!f||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 m=JSON.parse(g);if(i?.isErrorEnvelope?.(m))throw await Te(i,u.status,g,Ke(n));if(m&&typeof m=="object"&&m.error&&(typeof m.error=="string"||typeof m.error=="object"&&Object.keys(m.error).length>0)){if(i)throw await Te(i,u.status,g,Ke(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let b=dn(g),_=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${g}`,400,"provider_response_error");throw _.isRateLimit=b,_.rawBody=g,_}}catch(h){if(i)throw h?.pluginClassified===!0?h:await Te(i,u.status,void 0,Ke(n));if(h instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let m=K(`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 m.rawBody=g,m}throw h}}}if(!i?.suppressDebugLog&&!n.stream&&Jt(o.configService)){let f=await u.clone().text();zs(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Vi(n,e,t,o,r,s){let a=e;if(!r&&t.transformer?.use?.length)for(let i of Array.from(t.transformer.use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let i of Array.from(t.transformer[n.model].use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),a=await o.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new De().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function Yi(n,e,t,o){n.ok||e.code(n.status);let r=gi(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 a=await me(n);n=a.response,a.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Jt(o.configService)){let[s,a]=n.body.tee(),i=js(o.configService);return Bs(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function dn(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 kd(n){try{return new URL(n),!0}catch{return!1}}var gd,Xi,pn=w(()=>{"use strict";Ws();zt();Vs();Ys();qs();rt();$o();re();Se();Yt();tn();Xo();V();Pe();q();gd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Xi=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:H().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)=>Ji(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw K("Provider name is required",400,"invalid_request");if(!s||!kd(s))throw K("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw K("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw K("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw K(`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 K("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 K("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 K("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 K("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ge,ir=w(()=>{"use strict";Ge=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var ye,fn,Zi,vd,qi,Qe=w(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",fn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Zi=["low","medium","high"],vd={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"},qi=n=>{if(typeof n=="string")return vd[n.trim().toLowerCase()]}});var ar,ea=w(()=>{ar=(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 ta(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let g=t[f],h=g?.text??JSON.stringify(g),m=d.get(h);if(m===void 0){d.set(h,f);continue}!t[m]?.cache_control&&g?.cache_control&&(t[m]=g),t.splice(f,1),f--}};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 f=e[d];if(f.role==="tool"){let g=f.content;try{typeof f.content=="string"&&(g=JSON.parse(f.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let h={type:"tool_result",tool_use_id:f.tool_call_id,content:g};f.cache_control&&(h.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(h):s.push({role:"user",content:[h]})}else if(f.role==="user"){let g=[];typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?g.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):g.push(m)});let h=s[s.length-1];h&&h.role==="user"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let g=[];f.content&&(typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&g.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}g.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&g.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let h=s[s.length-1];h&&h.role==="assistant"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(g=>g?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},l=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let g=f.find(h=>h?.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,f)=>{if(!Array.isArray(d?.content)||d.content.some(h=>h?.cache_control))return!1;let g=d.content.find(h=>h&&typeof h=="object"&&!h.cache_control);return g?(g.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,g=l(),h=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||h.push(m);for(let m of h){if(d<=0)break;c(f[m],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||fn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let g=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Zi.includes(g)&&(p.output_config={...p.output_config||{},effort:g})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
31
-
32
- `)}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 na=w(()=>{Qe()});function xd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function mn(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 Ee(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:xd(n),cache_creation_input_tokens:mn(n)}}function Ae(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,...r.usage_estimated===!0||o.usage_estimated===!0?{usage_estimated:!0}:{},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 gn=w(()=>{"use strict"});import{v4 as cr}from"uuid";function Sd(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}function lr(n){if(!n||typeof n!="object")return!1;let e=n;return e.usage_source==="kiro"||e.usage_estimated===!0||e.kiro_estimated===!0}var hn,oa=w(()=>{"use strict";Qe();zt();V();ea();na();Pe();gn();hn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(l=>l.type==="text"&&l.text).map(l=>({type:"text",text:l.text,cache_control:l.cache_control}));t.push({role:"system",content:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let l=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(l.length){let u=gt(String(e.model??"")),p=[];l.forEach(d=>{let f=Array.isArray(d.content)?d.content:null,g=f?f.filter(y=>y?.type==="image"&&y?.source):[],h=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(g.length>0){let y=f.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
33
- `);u?(h=y||"[tool image]",p.push(...g)):(h=[y,...g.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
34
- `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:g.length}))}let m={role:"tool",content:h,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?ar(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let c=i.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"?ar(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let l={role:"assistant",content:""},c=i.content.filter(d=>d.type==="text"&&d.text);c.length&&(l.content=c.map(d=>d.text).join(`
35
- `));let u=i.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=i.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=qi(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},c=Sd(e.thinking?.type)??(s!==void 0||(a??0)>0);c!==void 0&&(i.enabled=c),s!==void 0?i.effort=s:a!==void 0&&(i.effort=ye(a)),a!==void 0&&a>0&&(i.max_tokens=a),Object.keys(i).length>0&&(r.reasoning=i)}return e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=ta(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 pe(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 a;if(r?.body)a=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"}})}a=c.response}let i=await j(a),l=this.convertOpenAIResponseToAnthropic(i,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,a=`msg_${Date.now()}`,i=null,l=String(t?.req?.body?.model??"unknown"),c=!1,u=!1,p=!1;t?.req&&(t.req.contentDelivered=!1);let d=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,g=new Map,h=0,m=0,y=0,b=!1,_=!1,k=0,v=-1,x=()=>{let R=k;return k++,R},T=R=>{if(!b)try{r.enqueue(R);let A=new TextDecoder().decode(R);this.logger.debug({reqId:t.req.id,data:A,type:"send data"})}catch(A){if(A instanceof TypeError&&A.message.includes("Controller is already closed"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:A instanceof Error?A.message:String(A),type:"send data error"}),A}},P=()=>{if(!b)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(v>=0){let A={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
27
+ ${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 Gi(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Oo(n);let s=xd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&kd.test(r.model)&&await dn(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let a=n.provider;if(!a&&r?.model){let c=r.model.split(",");c.length>1&&(a=c[0],r.model=c.slice(1).join(","))}let i=a?t.providerService.getProvider(a):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(","),f=t.providerService.getProvider(p);f&&(i=f,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw K(`Provider '${a}' not found`,404,"provider_not_found");n.provider=i.name||a;let l=o.endPoint==="/v1/messages"&&s;s&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=l;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&ht(r);let c={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:Yi(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Vi(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let v=JSON.stringify(k.content??"");y.has(v)||(y.add(v),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await Xi(u,p,i,t,d,o,c);try{i?.baseUrl&&f?.headers&&it(a,i.baseUrl,f.headers)}catch{}let h=await Zi(u,f,i,o,d,c);h=await Qi(r,h,i.name||a);let g=qi(h,e,r,t);try{let m=r.model||n.originalModel;a&&m&&H().recordSuccess(a,m)}catch{}return g}catch(c){if(c instanceof ne)throw c;if(!Io(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i,r.model)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Gi(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await vd(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function Qi(n,e,t){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let s=e.body.getReader(),a=new TextDecoder,i=[],l="";for(let d=0;d<8;d++){let f=await s.read();if(f.done||(f.value&&(i.push(f.value),l+=a.decode(f.value,{stream:!0})),l.split(`
28
+ `).some(h=>h.startsWith("data:"))))break}if(l+=a.decode(),i.length===0)throw s.releaseLock(),K(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(l.includes("event: error")){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned error in SSE stream: ${d}`,400,"provider_response_error")}if(l.split(`
29
+ `).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let h of i)d.enqueue(h);let f=()=>{s.read().then(({done:h,value:g})=>{h?d.close():(d.enqueue(g),f())}).catch(h=>d.error(h))};f()},cancel:()=>{s.cancel()}}),p=await Ys(u);if(p.verdict==="empty")throw K(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(Xs(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function vd(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),c=H(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&pn(r.rawBody)||r?.message&&pn(r.message);if(u&&p&&(f?(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 g=b=>{let[_,...k]=b.split(","),v=_?.trim(),S=k.join(",").trim();return!v||!S?null:{provider:v,model:S,key:`${v},${S}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.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`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=g(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let v=t.providerService.getProviders(),S=ft(v,k.provider,k.model);if(!S){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let T=S.provider.name,w=S.model;if(!c.isAvailable(T,w,S.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let E=t.pluginRegistry.getManagedRuntimeFor(S.provider);if(E&&Mo(n,E,{name:T},w))continue;let R;for(let A=1;A<=2;A++)try{n.log.info(`Trying fallback model: ${T},${w}${A>1?" (retry)":""}`);let D={...n.body};D.model=w;let C={...n,provider:T,body:D},O=S.provider,x={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Yi(C,o,C.codexDetected===!0)},{requestBody:I,config:M,bypass:N}=await Vi(D,O,o,n.headers,x),L=await Xi(I,M,O,t,N,o,x);try{O?.baseUrl&&L?.headers&&it(T,O.baseUrl,L.headers)}catch{}let F=await Zi(I,L,O,o,N,x);return F=await Qi(D,F,T),n.log.info(`Fallback model ${T},${w} succeeded`),c.recordSuccess(T,w),u&&p&&!n.strictProjectRouting&&($e().promote(u,p,s,T,w),n.log.info(`Promoted fallback model ${T},${w} for ${u},${p}:${s}`),f?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=D,hi(n,`${T},${w}`),qi(F,e,D,t)}catch(D){if(R=D,Io(n,E,D,{name:T},w))break;if(A===1){n.log.warn(`Fallback model ${T},${w} failed, retrying once: ${D.message}`);continue}}c.recordFailure(T,w,R?.message),n.log.warn(`Fallback model ${T},${w} failed after retry: ${R?.message}`),t.recordUsage?.({provider:T,model:w,originalModel:n.originalModel||p||n.body.model,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})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Vi(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw K("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s={model:n.model,provider:e,requestState:{}},a=r.pluginRegistry.getManagedRuntimeFor(e);if(a){let p=Mo(r.req,a,e,n.model);if(p)throw p;await a.ensureUsable?.(s)}let i=JSON.parse(JSON.stringify(n)),l=i?.system;if(typeof l=="string"&&l.includes("cch="))i.system=l.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(l))for(let p=0;p<l.length;p++){let d=l[p],f=typeof d=="string"?d:d?.text??"";if(f.includes("cch=")){let h=f.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof d=="string"?l[p]=h:typeof d?.text=="string"&&(d.text=h)}}let c={__ccrManagedRequest:s},u=!1;if(u=Td(e,t,n),u&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],c.headers=o),!u&&typeof t.transformRequestOut=="function"){let p=await t.transformRequestOut(i);p.body?(i=p.body,c={...c,...p.config}):i=p}if(!u&&e.transformer?.use?.length)for(let p of e.transformer.use){if(!p||typeof p.transformRequestIn!="function")continue;let d=await p.transformRequestIn(i,e,r);d.body?(i=d.body,c={...c,...d.config}):i=d}if(!u&&e.transformer?.[n.model]?.use?.length)for(let p of e.transformer[n.model].use)!p||typeof p.transformRequestIn!="function"||(i=await p.transformRequestIn(i,e,r));return{requestBody:i,config:c,bypass:u}}function Td(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 Sd(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 Yi(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function xd(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Xi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>Ki(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):Ki(n,e,t,o,r,s,a)}function We(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
30
+ `):""}async function Ki(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);i&&(await i.ensureUsable?.(e.__ccrManagedRequest??={model:n?.model,provider:t,requestState:{}}),await i.lockUpstream?.(e,t));let l=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let f=o.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(r&&typeof s.auth=="function"){let f=await s.auth(n,t,a);if(f.body){n=f.body;let h=e.headers||{};f.config?.headers&&(h={...h,...f.config.headers},delete h.host,delete f.config.headers),e={...e,...f.config,headers:h}}else n=f}let c={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(c=await i.signRequest({headers:c,requestBody:n,provider:t,config:e})),Sd(c,a?.req);for(let f in c)(c[f]==="undefined"||["authorization","Authorization"].includes(f)&&c[f]?.includes("undefined"))&&delete c[f];!i?.suppressDebugLog&&Wt(o.configService)&&Js(o.log,a.req.id,{url:String(l),headers:c,body:n});let u=e.__ccrManagedRequest,p,d=()=>Gs(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:i?void 0:pe(o.configService,t)},a,i?void 0:o.log);try{p=await d()}catch(f){throw i?await Te(i,0,void 0,We(n),ti(f),u):f}if(!p.ok&&i?.authRefresh&&p.status===401&&!rt(a.req,i,t).refreshUsed){rt(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),c=await i.signRequest({headers:c,requestBody:n,provider:t}),p=await d()}catch{}p.status===401&&(a.req.__retryAttempted=!0)}if(!p.ok){let f;try{f=await p.text()}catch(g){throw i?await Te(i,p.status,void 0,We(n),void 0,u):g}if(i){let g=await Te(i,p.status,f,We(n),void 0,u);throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${p.status} code=${g.code}`),g}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${p.status}): ${f}`);let h=K(`Error from provider(${t.name},${n.model}: ${p.status}): ${f}`,p.status,"provider_response_error");throw h.isRateLimit=p.status===429||pn(f),h.rawBody=f,h}if(p.ok){let f=p.headers.get("content-type")||"",h=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${h} contentType=${f} ok=${p.ok} status=${p.status} hasBody=${!!p.body}`),!h||f.includes("application/json")){let g="";try{if(g=await p.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 ${f}, skipping JSON validation`),p;let y=JSON.parse(g);if(i?.isErrorEnvelope?.(y))throw await Te(i,p.status,g,We(n),void 0,u);if(y&&typeof y=="object"&&y.error&&(typeof y.error=="string"||typeof y.error=="object"&&Object.keys(y.error).length>0)){if(i)throw await Te(i,p.status,g,We(n),void 0,u);o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${p.status}): ${g}`);let _=pn(g),k=K(`Error from provider(${t.name},${n.model}: ${p.status}): ${g}`,400,"provider_response_error");throw k.isRateLimit=_,k.rawBody=g,k}}catch(m){if(i)throw m?.pluginClassified===!0?m:await Te(i,p.status,void 0,We(n),void 0,u);if(m instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let y=K(`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 y.rawBody=g,y}throw m}}}if(!i?.suppressDebugLog&&!n.stream&&Wt(o.configService)){let h=await p.clone().text();Ws(o.log,a.req.id,{status:p.status,headers:Object.fromEntries(Array.from(p.headers)),body:h})}return p}async function Zi(n,e,t,o,r,s){let a=e;if(!r&&t.transformer?.use?.length)for(let i of Array.from(t.transformer.use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let i of Array.from(t.transformer[n.model].use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),a=await o.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Ue().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function qi(n,e,t,o){n.ok||e.code(n.status);let r=_i(n);if(!r){let s=await fe(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let a=await me(n);n=a.response,a.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Wt(o.configService)){let[s,a]=n.body.tee(),i=Bs(o.configService);return Ks(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function pn(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 Cd(n){try{return new URL(n),!0}catch{return!1}}var kd,ea,fn=P(()=>{"use strict";Qs();Bt();Zs();qs();ni();ot();Uo();ie();xe();Xt();nn();qo();V();Pe();ee();kd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;ea=async n=>{n.get("/",async()=>({message:"LLMs API",version:Yt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:H().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Gi(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw K("Provider name is required",400,"invalid_request");if(!s||!Cd(s))throw K("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw K("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw K("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw K(`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 K("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 K("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 K("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 K("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ke,cr=P(()=>{"use strict";Ke=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var ye,mn,ta,Rd,na,Ge=P(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",mn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,ta=["low","medium","high"],Rd={none:"none",off:"none",disabled:"none",min:"low",minimal:"low",light:"low",low:"low",medium:"medium",mid:"medium",high:"high",xhigh:"max",max:"max",maximum:"max",ultra:"max",ultracode:"max"},na=n=>{if(typeof n=="string")return Rd[n.trim().toLowerCase()]}});var lr,oa=P(()=>{lr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function wd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ra(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let h=t[f],g=h?.text??JSON.stringify(h),m=d.get(g);if(m===void 0){d.set(g,f);continue}!t[m]?.cache_control&&h?.cache_control&&(t[m]=h),t.splice(f,1),f--}};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 f=e[d];if(f.role==="tool"){let h=f.content;try{typeof f.content=="string"&&(h=JSON.parse(f.content))}catch{}h!=null&&typeof h!="object"&&typeof h!="string"&&(h=String(h));let g={type:"tool_result",tool_use_id:f.tool_call_id,content:h};f.cache_control&&(g.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(g):s.push({role:"user",content:[g]})}else if(f.role==="user"){let h=[];typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?h.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):h.push(m)});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(f.role==="assistant"){let h=[];f.content&&(typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&h.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}h.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&h.unshift({type:"thinking",thinking:f.thinking.content,signature:f.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 a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(h=>h?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},l=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let h=f.find(g=>g?.cache_control);if(h?.cache_control)return h.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},c=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(g=>g?.cache_control))return!1;let h=d.content.find(g=>g&&typeof g=="object"&&!g.cache_control);return h?(h.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,h=l(),g=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||g.push(m);for(let m of g){if(d<=0)break;c(f[m],h)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||mn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let h=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);ta.includes(h)&&(p.output_config={...p.output_config||{},effort:h})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
31
+
32
+ `)}return n.tools&&n.tools.length>0&&(p.tools=wd(n.tools),n.tool_choice&&(n.tool_choice==="auto"?p.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?p.tool_choice={type:"any"}:typeof n.tool_choice=="string"?p.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:n.tool_choice.function.name}))),p}var sa=P(()=>{Ge()});function Pd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function gn(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 Ee(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:Pd(n),cache_creation_input_tokens:gn(n)}}function Ae(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,...r.usage_estimated===!0||o.usage_estimated===!0?{usage_estimated:!0}:{},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 hn=P(()=>{"use strict"});import{v4 as ur}from"uuid";function Ed(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}function dr(n){if(!n||typeof n!="object")return!1;let e=n;return e.usage_source==="kiro"||e.usage_estimated===!0||e.kiro_estimated===!0}var yn,ia=P(()=>{"use strict";Ge();Bt();V();oa();sa();Pe();hn();yn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=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:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let l=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(l.length){let u=gt(String(e.model??"")),p=[];l.forEach(d=>{let f=Array.isArray(d.content)?d.content:null,h=f?f.filter(y=>y?.type==="image"&&y?.source):[],g=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(h.length>0){let y=f.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
33
+ `);u?(g=y||"[tool image]",p.push(...h)):(g=[y,...h.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
34
+ `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:h.length}))}let m={role:"tool",content:g,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?lr(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let c=i.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"?lr(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let l={role:"assistant",content:""},c=i.content.filter(d=>d.type==="text"&&d.text);c.length&&(l.content=c.map(d=>d.text).join(`
35
+ `));let u=i.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=i.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=na(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},c=Ed(e.thinking?.type)??(s!==void 0||(a??0)>0);c!==void 0&&(i.enabled=c),s!==void 0?i.effort=s:a!==void 0&&(i.effort=ye(a)),a!==void 0&&a>0&&(i.max_tokens=a),Object.keys(i).length>0&&(r.reasoning=i)}return e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=ra(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let r=await this.convertOpenAIStreamToAnthropic(e.body,t);return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let r=await fe(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 a;if(r?.body)a=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"}})}a=c.response}let i=await j(a),l=this.convertOpenAIResponseToAnthropic(i,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,a=`msg_${Date.now()}`,i=null,l=String(t?.req?.body?.model??"unknown"),c=!1,u=!1,p=!1;t?.req&&(t.req.contentDelivered=!1);let d=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,h=new Map,g=0,m=0,y=0,b=!1,_=!1,k=0,v=-1,S=()=>{let R=k;return k++,R},T=R=>{if(!b)try{r.enqueue(R);let A=new TextDecoder().decode(R);this.logger.debug({reqId:t.req.id,data:A,type:"send data"})}catch(A){if(A instanceof TypeError&&A.message.includes("Controller is already closed"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:A instanceof Error?A.message:String(A),type:"send data error"}),A}},w=()=>{if(!b)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(v>=0){let A={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
36
36
  data: ${JSON.stringify(A)}
37
37
 
38
38
  `)),v=-1}if(i)T(s.encode(`event: message_delta
@@ -45,13 +45,13 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
45
45
  data: ${JSON.stringify(R)}
46
46
 
47
47
  `)),r.close(),b=!0}catch(R){if(R instanceof TypeError&&R.message.includes("Controller is already closed"))b=!0;else throw R}},E=null;try{E=e.getReader();let R=new TextDecoder,A="";for(;!b;){let{done:D,value:C}=await E.read();if(D)break;A+=R.decode(C,{stream:!0});let O=A.split(`
48
- `);A=O.pop()||"";for(let S of O){if(b)break;if(!S.startsWith("data:"))continue;let I=S.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:I}),I!=="[DONE]")try{let M=JSON.parse(I);if(h++,this.logger.debug({reqId:t.req.id,response:M,tppe:"Original Response"}),M.error){t?.req&&(t.req.sseError=M.error);let L={type:"error",message:{type:"api_error",message:JSON.stringify(M.error)}};T(s.encode(`event: error
48
+ `);A=O.pop()||"";for(let x of O){if(b)break;if(!x.startsWith("data:"))continue;let I=x.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:I}),I!=="[DONE]")try{let M=JSON.parse(I);if(g++,this.logger.debug({reqId:t.req.id,response:M,tppe:"Original Response"}),M.error){t?.req&&(t.req.sseError=M.error);let L={type:"error",message:{type:"api_error",message:JSON.stringify(M.error)}};T(s.encode(`event: error
49
49
  data: ${JSON.stringify(L)}
50
50
 
51
51
  `));continue}if(l=M.model&&M.model!=="unknown"?M.model:l,!c&&!b&&!p){c=!0;let L=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};T(s.encode(`event: message_start
52
52
  data: ${JSON.stringify(F)}
53
53
 
54
- `))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,J=(M.usage?.prompt_tokens||0)-L,ce=M.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:M.usage,mappedUsage:{input_tokens:J,output_tokens:ce,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let B={input_tokens:J,output_tokens:ce,cache_read_input_tokens:L,...lr(M.usage)?{cache_creation_input_tokens:mn(M.usage)}:{},...M.usage.kiro_estimated===!0||M.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...B}};else{let z=i.usage||{};lr(M.usage)||"cache_creation_input_tokens"in z?i.usage=Ae(z,B,!1):i.usage={input_tokens:B.input_tokens||z.input_tokens||0,output_tokens:B.output_tokens||z.output_tokens||0,cache_read_input_tokens:B.cache_read_input_tokens||z.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!b&&!p&&!u){if(!_){let L=x();d();let F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};T(s.encode(`event: content_block_start
54
+ `))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,J=(M.usage?.prompt_tokens||0)-L,le=M.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:M.usage,mappedUsage:{input_tokens:J,output_tokens:le,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let B={input_tokens:J,output_tokens:le,cache_read_input_tokens:L,...dr(M.usage)?{cache_creation_input_tokens:gn(M.usage)}:{},...M.usage.kiro_estimated===!0||M.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...B}};else{let z=i.usage||{};dr(M.usage)||"cache_creation_input_tokens"in z?i.usage=Ae(z,B,!1):i.usage={input_tokens:B.input_tokens||z.input_tokens||0,output_tokens:B.output_tokens||z.output_tokens||0,cache_read_input_tokens:B.cache_read_input_tokens||z.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!b&&!p&&!u){if(!_){let L=S();d();let F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};T(s.encode(`event: content_block_start
55
55
  data: ${JSON.stringify(F)}
56
56
 
57
57
  `)),v=L,_=!0}if(N.delta.thinking.signature){let L={type:"content_block_delta",index:v,delta:{type:"signature_delta",signature:N.delta.thinking.signature}};T(s.encode(`event: content_block_delta
@@ -66,7 +66,7 @@ data: ${JSON.stringify(L)}
66
66
  `))}}if(N?.delta?.content&&!b&&!p){if(m++,v>=0&&!u){let F={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
67
67
  data: ${JSON.stringify(F)}
68
68
 
69
- `)),v=-1}if(!u&&!p){u=!0;let L=x();d();let F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};T(s.encode(`event: content_block_start
69
+ `)),v=-1}if(!u&&!p){u=!0;let L=S();d();let F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};T(s.encode(`event: content_block_start
70
70
  data: ${JSON.stringify(F)}
71
71
 
72
72
  `)),v=L}if(!b&&!p){let L={type:"content_block_delta",index:v,delta:{type:"text_delta",text:N.delta.content}};T(s.encode(`event: content_block_delta
@@ -75,19 +75,19 @@ data: ${JSON.stringify(L)}
75
75
  `))}}if(N?.delta?.annotations?.length&&!b&&!p){if(v>=0&&u){let L={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
76
76
  data: ${JSON.stringify(L)}
77
77
 
78
- `)),v=-1,u=!1}N?.delta?.annotations.forEach(L=>{let F=x();d();let J={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${cr()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};T(s.encode(`event: content_block_start
78
+ `)),v=-1,u=!1}N?.delta?.annotations.forEach(L=>{let F=S();d();let J={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${ur()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};T(s.encode(`event: content_block_start
79
79
  data: ${JSON.stringify(J)}
80
80
 
81
- `));let ce={type:"content_block_stop",index:F};T(s.encode(`event: content_block_stop
82
- data: ${JSON.stringify(ce)}
81
+ `));let le={type:"content_block_stop",index:F};T(s.encode(`event: content_block_stop
82
+ data: ${JSON.stringify(le)}
83
83
 
84
- `)),v=-1})}if(N?.delta?.tool_calls&&!b&&!p){y++;let L=new Set;for(let F of N.delta.tool_calls){if(b)break;let J=F.index??0;if(L.has(J))continue;if(L.add(J),!g.has(J)){if(v>=0){let ml={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
85
- data: ${JSON.stringify(ml)}
84
+ `)),v=-1})}if(N?.delta?.tool_calls&&!b&&!p){y++;let L=new Set;for(let F of N.delta.tool_calls){if(b)break;let J=F.index??0;if(L.has(J))continue;if(L.add(J),!h.has(J)){if(v>=0){let bl={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
85
+ data: ${JSON.stringify(bl)}
86
86
 
87
- `)),v=-1}let B=x();g.set(J,B);let z=F.id||`call_ccr_${J}`,$=F.function?.name||`tool_${J}`;d();let W={type:"content_block_start",index:B,content_block:{type:"tool_use",id:z,name:$,input:{}}};T(s.encode(`event: content_block_start
87
+ `)),v=-1}let B=S();h.set(J,B);let z=F.id||`call_ccr_${J}`,$=F.function?.name||`tool_${J}`;d();let W={type:"content_block_start",index:B,content_block:{type:"tool_use",id:z,name:$,input:{}}};T(s.encode(`event: content_block_start
88
88
  data: ${JSON.stringify(W)}
89
89
 
90
- `)),v=B;let fl={id:z,name:$,arguments:"",contentBlockIndex:B};f.set(J,fl)}else if(F.id&&F.function?.name){let B=f.get(J);B.id.startsWith("call_")&&B.name.startsWith("tool_")&&(B.id=F.id,B.name=F.function.name)}if(F.function?.arguments&&!b&&!p){let B=g.get(J);if(B===void 0)continue;let z=f.get(J);z&&(z.arguments+=F.function.arguments);try{let $={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:F.function.arguments}};T(s.encode(`event: content_block_delta
90
+ `)),v=B;let _l={id:z,name:$,arguments:"",contentBlockIndex:B};f.set(J,_l)}else if(F.id&&F.function?.name){let B=f.get(J);B.id.startsWith("call_")&&B.name.startsWith("tool_")&&(B.id=F.id,B.name=F.function.name)}if(F.function?.arguments&&!b&&!p){let B=h.get(J);if(B===void 0)continue;let z=f.get(J);z&&(z.arguments+=F.function.arguments);try{let $={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:F.function.arguments}};T(s.encode(`event: content_block_delta
91
91
  data: ${JSON.stringify($)}
92
92
 
93
93
  `))}catch{try{let $=F.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),W={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:$}};T(s.encode(`event: content_block_delta
@@ -96,117 +96,117 @@ data: ${JSON.stringify(W)}
96
96
  `))}catch($){console.error($)}}}}}if(N?.finish_reason&&!b&&!p){if(m===0&&y===0&&console.error("Warning: No content in the stream response!"),v>=0){let L={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
97
97
  data: ${JSON.stringify(L)}
98
98
 
99
- `)),v=-1}if(!b){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[N.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:F,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(M){this.logger?.error(`parseError: ${M.name} message: ${M.message} stack: ${M.stack} data: ${I}`)}}}P()}catch(R){if(!b)try{r.error(R)}catch(A){console.error(A)}}finally{if(E)try{E.releaseLock()}catch(R){console.error(R)}}},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_${cr()}`;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,a=(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${cr().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:lr(e.usage)?mn(e.usage):0,...e.usage?.kiro_estimated===!0||e.usage?.usage_estimated===!0?{usage_estimated:!0}:{},cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw K(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Cd(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(Ve).includes(o)?o:Ve.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ve).includes(r)?r:Ve.TYPE_UNSPECIFIED})}}}function yt(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)&&Cd(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let l=i.toUpperCase();e.type=Object.values(Ve).includes(l)?l:Ve.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=yt(i);else if(o.includes(a)){let l=[];for(let c of i){if(c.type=="null"){e.nullable=!0;continue}l.push(yt(c))}e[a]=l}else if(r.includes(a)){let l={};for(let[c,u]of Object.entries(i))l[c]=yt(u);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=i}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=yt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=yt(e.response));return n}function _n(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 f=s.find(g=>g.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let 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]),a.thinkingConfig.thinkingBudget=c)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};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]),i.toolConfig=l}return i}function bn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,l={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};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}function yn(n){return{completion_tokens:n?.candidatesTokenCount||0,prompt_tokens:n?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n?.cachedContentTokenCount||0},total_tokens:n?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n?.thoughtsTokenCount||0}}}function dr(n){if(n?.groundingMetadata?.groundingChunks?.length)return n.groundingMetadata.groundingChunks.map((e,t)=>{let o=n?.groundingMetadata?.groundingSupports?.filter(r=>r.groundingChunkIndices?.includes(t));return{type:"url_citation",url_citation:{url:e?.web?.uri||"",title:e?.web?.title||"",content:o?.[0]?.segment?.text||"",start_index:o?.[0]?.segment?.startIndex||0,end_index:o?.[0]?.segment?.endIndex||0}}})}function ur(n,e,t){let o=e?dr(e):void 0,r=e?.finishReason?.toLowerCase()||null;return{choices:r||o?[{delta:o?{role:"assistant",annotations:o}:{},finish_reason:r,index:t,logprobs:null}]:[],created:parseInt(new Date().getTime()/1e3+"",10),id:n.responseId||"",model:n.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...n.usageMetadata?{usage:yn(n.usageMetadata)}:{}}}async function kn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],i=[];for(let p of a)p.text&&p.thought===!0?r+=p.text:i.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=i?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],c=i?.filter(p=>p.text)?.map(p=>p.text)?.join(`
100
- `)||"",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:yn(o.usageMetadata)};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,l="",c=0,u=-1,p=new ReadableStream({async start(d){let f=async(m,y)=>{if(m.startsWith("data: ")){let b=m.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){if(_.usageMetadata){y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,void 0,c))}
99
+ `)),v=-1}if(!b){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[N.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:F,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(M){this.logger?.error(`parseError: ${M.name} message: ${M.message} stack: ${M.stack} data: ${I}`)}}}w()}catch(R){if(!b)try{r.error(R)}catch(A){console.error(A)}}finally{if(E)try{E.releaseLock()}catch(R){console.error(R)}}},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_${ur()}`;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,a=(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${ur().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:dr(e.usage)?gn(e.usage):0,...e.usage?.kiro_estimated===!0||e.usage?.usage_estimated===!0?{usage_estimated:!0}:{},cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw K(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Ad(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(Qe).includes(o)?o:Qe.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Qe).includes(r)?r:Qe.TYPE_UNSPECIFIED})}}}function yt(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)&&Ad(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let l=i.toUpperCase();e.type=Object.values(Qe).includes(l)?l:Qe.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=yt(i);else if(o.includes(a)){let l=[];for(let c of i){if(c.type=="null"){e.nullable=!0;continue}l.push(yt(c))}e[a]=l}else if(r.includes(a)){let l={};for(let[c,u]of Object.entries(i))l[c]=yt(u);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=i}return e}function Od(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=yt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=yt(e.response));return n}function bn(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(Od({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 f=s.find(h=>h.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let 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]),a.thinkingConfig.thinkingBudget=c)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};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]),i.toolConfig=l}return i}function kn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,l={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};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}function _n(n){return{completion_tokens:n?.candidatesTokenCount||0,prompt_tokens:n?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n?.cachedContentTokenCount||0},total_tokens:n?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n?.thoughtsTokenCount||0}}}function fr(n){if(n?.groundingMetadata?.groundingChunks?.length)return n.groundingMetadata.groundingChunks.map((e,t)=>{let o=n?.groundingMetadata?.groundingSupports?.filter(r=>r.groundingChunkIndices?.includes(t));return{type:"url_citation",url_citation:{url:e?.web?.uri||"",title:e?.web?.title||"",content:o?.[0]?.segment?.text||"",start_index:o?.[0]?.segment?.startIndex||0,end_index:o?.[0]?.segment?.endIndex||0}}})}function pr(n,e,t){let o=e?fr(e):void 0,r=e?.finishReason?.toLowerCase()||null;return{choices:r||o?[{delta:o?{role:"assistant",annotations:o}:{},finish_reason:r,index:t,logprobs:null}]:[],created:parseInt(new Date().getTime()/1e3+"",10),id:n.responseId||"",model:n.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...n.usageMetadata?{usage:_n(n.usageMetadata)}:{}}}async function vn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],i=[];for(let p of a)p.text&&p.thought===!0?r+=p.text:i.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=i?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],c=i?.filter(p=>p.text)?.map(p=>p.text)?.join(`
100
+ `)||"",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:_n(o.usageMetadata)};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,l="",c=0,u=-1,p=new ReadableStream({async start(d){let f=async(m,y)=>{if(m.startsWith("data: ")){let b=m.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){if(_.usageMetadata){y.enqueue(r.encode(`data: ${JSON.stringify(pr(_,void 0,c))}
101
101
 
102
- `));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],v=!1,x=k.content?.parts||[];x.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:R.text}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
102
+ `));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],v=!1,S=k.content?.parts||[];S.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:R.text}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
103
103
 
104
- `))});let T=x.find(R=>R.thoughtSignature)?.thoughtSignature;if(T&&!s){if(!i){let A={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:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
104
+ `))});let T=S.find(R=>R.thoughtSignature)?.thoughtSignature;if(T&&!s){if(!i){let A={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:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
105
105
 
106
106
  `))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:T}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(R)}
107
107
 
108
108
  `)),s=!0,c++,l){let A={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
109
109
 
110
- `)),l="",a||(a=!0)}}let P=x.filter(R=>R.functionCall).map(R=>({id:R.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:R.functionCall?.name,arguments:JSON.stringify(R.functionCall?.args||{})}})),E=x.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
110
+ `)),l="",a||(a=!0)}}let w=S.filter(R=>R.functionCall).map(R=>({id:R.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:R.functionCall?.name,arguments:JSON.stringify(R.functionCall?.args||{})}})),E=S.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
111
111
  `);if(!E&&s&&!a){let R={choices:[{delta:{role:"assistant",content:"(no content)"},index:c,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
112
112
 
113
- `)),a||(a=!0)}if(i&&E&&!s)if(_.modelVersion?.includes("3")){l+=E,_.usageMetadata&&y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,k,c))}
113
+ `)),a||(a=!0)}if(i&&E&&!s)if(_.modelVersion?.includes("3")){l+=E,_.usageMetadata&&y.enqueue(r.encode(`data: ${JSON.stringify(pr(_,k,c))}
114
114
 
115
115
  `));return}else{let R={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:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
116
116
 
117
- `)),s=!0}if(E){l||c++;let R={choices:[{delta:{role:"assistant",content:E},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:yn(_.usageMetadata)},A=dr(k);A&&(R.choices[0].delta.annotations=A),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
117
+ `)),s=!0}if(E){l||c++;let R={choices:[{delta:{role:"assistant",content:E},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:_n(_.usageMetadata)},A=fr(k);A&&(R.choices[0].delta.annotations=A),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
118
118
 
119
- `)),v=!0,!a&&E&&(a=!0)}P.length>0&&(P.forEach(R=>{c++,u++;let A={choices:[{delta:{role:"assistant",tool_calls:[{...R,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:yn(_.usageMetadata)},D=dr(k);D&&(A.choices[0].delta.annotations=D),y.enqueue(r.encode(`data: ${JSON.stringify(A)}
119
+ `)),v=!0,!a&&E&&(a=!0)}w.length>0&&(w.forEach(R=>{c++,u++;let A={choices:[{delta:{role:"assistant",tool_calls:[{...R,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:_n(_.usageMetadata)},D=fr(k);D&&(A.choices[0].delta.annotations=D),y.enqueue(r.encode(`data: ${JSON.stringify(A)}
120
120
 
121
- `)),v=!0}),!a&&E&&(a=!0)),!v&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,k,c))}
121
+ `)),v=!0}),!a&&E&&(a=!0)),!v&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&y.enqueue(r.encode(`data: ${JSON.stringify(pr(_,k,c))}
122
122
 
123
- `))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},g=n.body.getReader(),h="";try{for(;;){let{done:m,value:y}=await g.read();if(m){h&&await f(h,d);break}h+=o.decode(y,{stream:!0});let b=h.split(`
124
- `);h=b.pop()||"";for(let _ of b)await f(_,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ve,pr=w(()=>{"use strict";Ve={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var vn,ra=w(()=>{"use strict";pr();vn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:_n(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=bn;async transformResponseOut(e){return kn(e,this.name,this.logger)}}});async function wd(){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:
123
+ `))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},h=n.body.getReader(),g="";try{for(;;){let{done:m,value:y}=await h.read();if(m){g&&await f(g,d);break}g+=o.decode(y,{stream:!0});let b=g.split(`
124
+ `);g=b.pop()||"";for(let _ of b)await f(_,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Qe,mr=P(()=>{"use strict";Qe={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var Tn,aa=P(()=>{"use strict";mr();Tn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:bn(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=kn;async transformResponseOut(e){return vn(e,this.name,this.logger)}}});async function Id(){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:
125
125
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
126
126
  2. Run "gcloud auth application-default login"
127
- 3. Use Google Cloud environment with default service account`)}}var Tn,sa=w(()=>{"use strict";pr();Tn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await wd();return{body:_n(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return bn(e)}async transformResponseOut(e){return kn(e,this.name)}}});var xn,ia=w(()=>{"use strict";V();xn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,i="";if(typeof r.content=="string"){let c=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);c&&(i=c[1].trim(),r.content=r.content.replace(c[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
128
- `);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
129
- `))},p=(d,f)=>{let{controller:g,encoder:h}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
127
+ 3. Use Google Cloud environment with default service account`)}}var Sn,ca=P(()=>{"use strict";mr();Sn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Id();return{body:bn(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return kn(e)}async transformResponseOut(e){return vn(e,this.name)}}});var xn,la=P(()=>{"use strict";V();xn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,i="";if(typeof r.content=="string"){let c=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);c&&(i=c[1].trim(),r.content=r.content.replace(c[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,h)=>{let g=d.split(`
128
+ `);for(let m of g)m.trim()&&f.enqueue(h.encode(m+`
129
+ `))},p=(d,f)=>{let{controller:h,encoder:g}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
130
130
 
131
- `;g.enqueue(h.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
131
+ `;h.enqueue(g.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
132
132
 
133
- `;g.enqueue(h.encode(k));let v={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete v.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(v)}
133
+ `;h.enqueue(g.encode(k));let v={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete v.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(v)}
134
134
 
135
- `;g.enqueue(h.encode(x));return}if(m.choices[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){let y=`data: ${JSON.stringify(m)}
135
+ `;h.enqueue(g.encode(S));return}if(m.choices[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){let y=`data: ${JSON.stringify(m)}
136
136
 
137
- `;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
138
- `))}else g.enqueue(h.encode(d+`
139
- `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
140
- `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
141
- `))}}}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(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Sn,aa=w(()=>{"use strict";V();Sn=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.
137
+ `;h.enqueue(g.encode(y))}}catch{h.enqueue(g.encode(d+`
138
+ `))}else h.enqueue(g.encode(d+`
139
+ `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
140
+ `);a=g.pop()||"";for(let m of g)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
141
+ `))}}}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(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Cn,ua=P(()=>{"use strict";V();Cn=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.
142
142
  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.
143
143
  Examples:
144
144
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
145
- 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 j(e);if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
146
- `);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
147
- `))},p=(d,f)=>{let{controller:g,encoder:h,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let v=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:v.response||""}}];let x=`data: ${JSON.stringify(_)}
145
+ 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 j(e);if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,h)=>{let g=d.split(`
146
+ `);for(let m of g)m.trim()&&f.enqueue(h.encode(m+`
147
+ `))},p=(d,f)=>{let{controller:h,encoder:g,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let v=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:v.response||""}}];let S=`data: ${JSON.stringify(_)}
148
148
 
149
- `;g.enqueue(h.encode(x))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
149
+ `;h.enqueue(g.encode(S))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
150
150
 
151
- `;g.enqueue(h.encode(k))}}catch{g.enqueue(h.encode(d+`
152
- `))}else g.enqueue(h.encode(d+`
153
- `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
154
- `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,exitToolIndex:()=>r,setExitToolIndex:y=>r=y,exitToolResponse:()=>s,appendExitToolResponse:y=>s+=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
155
- `))}}}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(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as Pd}from"uuid";var Cn,ca=w(()=>{"use strict";V();Cn=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 j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
156
- `);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
157
- `))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
151
+ `;h.enqueue(g.encode(k))}}catch{h.enqueue(g.encode(d+`
152
+ `))}else h.enqueue(g.encode(d+`
153
+ `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
154
+ `);a=g.pop()||"";for(let m of g)if(m.trim())try{p(m,{controller:l,encoder:o,exitToolIndex:()=>r,setExitToolIndex:y=>r=y,exitToolResponse:()=>s,appendExitToolResponse:y=>s+=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
155
+ `))}}}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(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as Md}from"uuid";var Rn,da=P(()=>{"use strict";V();Rn=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 j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
156
+ `);for(let b of y)b.trim()&&g.enqueue(m.encode(b+`
157
+ `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let b=h.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
158
158
 
159
- `));return}_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let k=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(k){h.appendReasoningContent(k);let E={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let R=`data: ${JSON.stringify(E)}
159
+ `));return}_.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0);let k=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(k){g.appendReasoningContent(k);let E={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let R=`data: ${JSON.stringify(E)}
160
160
 
161
- `;m.enqueue(y.encode(R));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let E="ccr_think_signature",R=_.choices[0].delta.content,A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:E}}}]};A.choices?.[0]?.delta&&delete A.choices[0].delta.reasoning;let D=`data: ${JSON.stringify(A)}
161
+ `;m.enqueue(y.encode(R));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let E="ccr_think_signature",R=_.choices[0].delta.content,A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:E}}}]};A.choices?.[0]?.delta&&delete A.choices[0].delta.reasoning;let D=`data: ${JSON.stringify(A)}
162
162
 
163
163
  `;m.enqueue(y.encode(D));let C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:R}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let O=`data: ${JSON.stringify(C)}
164
164
 
165
- `;m.enqueue(y.encode(O));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(E=>{E.id=`call_${Pd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let v=_.choices?.[0]?.delta,x=v&&Object.keys(v).length>0,T=_.choices?.[0]?.finish_reason,P=_.usage;if(x||T||P){let E=`data: ${JSON.stringify(_)}
165
+ `;m.enqueue(y.encode(O));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(E=>{E.id=`call_${Md()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let v=_.choices?.[0]?.delta,S=v&&Object.keys(v).length>0,T=_.choices?.[0]?.finish_reason,w=_.usage;if(S||T||w){let E=`data: ${JSON.stringify(_)}
166
166
 
167
- `;m.enqueue(y.encode(E))}}catch{m.enqueue(y.encode(g+`
168
- `))}}else m.enqueue(y.encode(g+`
169
- `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
167
+ `;m.enqueue(y.encode(E))}}catch{m.enqueue(y.encode(h+`
168
+ `))}}else m.enqueue(y.encode(h+`
169
+ `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){l.trim()&&d(l,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
170
170
  `);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
171
171
  `))}continue}let y=l.split(`
172
172
  `);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
173
- `))}}}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 Rn,la=w(()=>{"use strict";Rn=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});import{v4 as Ed}from"uuid";var wn,ua=w(()=>{"use strict";V();wn=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i="",l=new ReadableStream({async start(c){let u=e.body.getReader(),p=(f,g,h)=>{let m=f.split(`
174
- `);for(let y of m)y.trim()&&g.enqueue(h.encode(y+`
175
- `))},d=(f,g)=>{let{controller:h,encoder:m}=g;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let b=JSON.parse(y);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${Ed()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let _=`data: ${JSON.stringify(b)}
173
+ `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var wn,pa=P(()=>{"use strict";wn=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 Ld}from"uuid";var Pn,fa=P(()=>{"use strict";V();Pn=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 j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i="",l=new ReadableStream({async start(c){let u=e.body.getReader(),p=(f,h,g)=>{let m=f.split(`
174
+ `);for(let y of m)y.trim()&&h.enqueue(g.encode(y+`
175
+ `))},d=(f,h)=>{let{controller:g,encoder:m}=h;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let b=JSON.parse(y);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${Ld()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let _=`data: ${JSON.stringify(b)}
176
176
 
177
- `;h.enqueue(m.encode(_))}catch{h.enqueue(m.encode(f+`
178
- `))}}else h.enqueue(m.encode(f+`
179
- `))};try{for(;;){let{done:f,value:g}=await u.read();if(f){i.trim()&&p(i,c,o);break}if(!g||g.length===0)continue;let h;try{h=t.decode(g,{stream:!0})}catch(y){console.warn("Failed to decode chunk",y);continue}if(h.length===0)continue;if(i+=h,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let y=i.split(`
177
+ `;g.enqueue(m.encode(_))}catch{g.enqueue(m.encode(f+`
178
+ `))}}else g.enqueue(m.encode(f+`
179
+ `))};try{for(;;){let{done:f,value:h}=await u.read();if(f){i.trim()&&p(i,c,o);break}if(!h||h.length===0)continue;let g;try{g=t.decode(h,{stream:!0})}catch(y){console.warn("Failed to decode chunk",y);continue}if(g.length===0)continue;if(i+=g,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let y=i.split(`
180
180
  `);i=y.pop()||"";for(let b of y)if(b.trim())try{d(b,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),c.enqueue(o.encode(b+`
181
181
  `))}continue}let m=i.split(`
182
182
  `);i=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",y,b),c.enqueue(o.encode(y+`
183
- `))}}}catch(f){console.error("Stream error:",f),c.error(f)}finally{try{u.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}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 Pn,da=w(()=>{"use strict";Pn=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),e}}});import Ad from"json5";import{jsonrepair as Od}from"jsonrepair";function fr(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=Ad.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=Od(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 pa=w(()=>{});var En,fa=w(()=>{"use strict";pa();V();En=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(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=fr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,l=!1,c="",u=new ReadableStream({async start(p){let d=e.body.getReader(),f=(m,y,b)=>{let _=m.split(`
183
+ `))}}}catch(f){console.error("Stream error:",f),c.error(f)}finally{try{u.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}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 En,ma=P(()=>{"use strict";En=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 $d from"json5";import{jsonrepair as Nd}from"jsonrepair";function gr(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=$d.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=Nd(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 ga=P(()=>{});var An,ha=P(()=>{"use strict";ga();V();An=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(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=gr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,l=!1,c="",u=new ReadableStream({async start(p){let d=e.body.getReader(),f=(m,y,b)=>{let _=m.split(`
184
184
  `);for(let k of _)k.trim()&&y.enqueue(b.encode(k+`
185
- `))},g=(m,y,b)=>{let _="";try{_=fr(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)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},v={...m,choices:[{...m.choices[0],delta:k}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let x=`data: ${JSON.stringify(v)}
185
+ `))},h=(m,y,b)=>{let _="";try{_=gr(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)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},v={...m,choices:[{...m.choices[0],delta:k}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let S=`data: ${JSON.stringify(v)}
186
186
 
187
- `;y.enqueue(b.encode(x))},h=(m,y)=>{let{controller:b,encoder:_}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.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 P=`data: ${JSON.stringify(v)}
187
+ `;y.enqueue(b.encode(S))},g=(m,y)=>{let{controller:b,encoder:_}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.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 w=`data: ${JSON.stringify(v)}
188
188
 
189
- `;b.enqueue(_.encode(P));return}else if(r.index===T.index){T.function?.arguments&&(r.arguments+=T.function.arguments);return}else{g(v,b,_),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,b,_),r={};return}v.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let x=`data: ${JSON.stringify(v)}
189
+ `;b.enqueue(_.encode(w));return}else if(r.index===T.index){T.function?.arguments&&(r.arguments+=T.function.arguments);return}else{h(v,b,_),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){h(v,b,_),r={};return}v.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let S=`data: ${JSON.stringify(v)}
190
190
 
191
- `;b.enqueue(_.encode(x))}catch{b.enqueue(_.encode(m+`
191
+ `;b.enqueue(_.encode(S))}catch{b.enqueue(_.encode(m+`
192
192
  `))}}else b.enqueue(_.encode(m+`
193
193
  `))};try{for(;;){let{done:m,value:y}=await d.read();if(m){c.trim()&&f(c,p,o);break}if(!y||y.length===0)continue;let b;try{b=t.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(b.length===0)continue;if(c+=b,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
194
- `);c=k.pop()||"";for(let v of k)if(v.trim())try{h(v,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>i,setReasoningComplete:x=>i=x})}catch(x){console.error("Error processing line:",v,x),p.enqueue(o.encode(v+`
194
+ `);c=k.pop()||"";for(let v of k)if(v.trim())try{g(v,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:S=>s=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>i,setReasoningComplete:S=>i=S})}catch(S){console.error("Error processing line:",v,S),p.enqueue(o.encode(v+`
195
195
  `))}continue}let _=c.split(`
196
- `);c=_.pop()||"";for(let k of _)if(k.trim())try{h(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>a,appendReasoningContent:v=>a+=v,isReasoningComplete:()=>i,setReasoningComplete:v=>i=v})}catch(v){console.error("Error processing line:",k,v),p.enqueue(o.encode(k+`
197
- `))}}}catch(m){console.error("Stream error:",m),p.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}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 An,ma=w(()=>{"use strict";V();Qe();An=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??fn(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 j(e);return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
198
- `);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
199
- `))},p=(d,f)=>{let{controller:g,encoder:h}=f;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(console.log(JSON.stringify(m)),m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
196
+ `);c=_.pop()||"";for(let k of _)if(k.trim())try{g(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>a,appendReasoningContent:v=>a+=v,isReasoningComplete:()=>i,setReasoningComplete:v=>i=v})}catch(v){console.error("Error processing line:",k,v),p.enqueue(o.encode(k+`
197
+ `))}}}catch(m){console.error("Stream error:",m),p.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}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 On,ya=P(()=>{"use strict";V();Ge();On=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens??mn(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 j(e);return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,h)=>{let g=d.split(`
198
+ `);for(let m of g)m.trim()&&f.enqueue(h.encode(m+`
199
+ `))},p=(d,f)=>{let{controller:h,encoder:g}=f;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(console.log(JSON.stringify(m)),m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
200
200
 
201
- `;g.enqueue(h.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
201
+ `;h.enqueue(g.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
202
202
 
203
- `;g.enqueue(h.encode(k))}if(m.choices?.[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){f.isReasoningComplete()&&m.choices[0].index++;let y=`data: ${JSON.stringify(m)}
203
+ `;h.enqueue(g.encode(k))}if(m.choices?.[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){f.isReasoningComplete()&&m.choices[0].index++;let y=`data: ${JSON.stringify(m)}
204
204
 
205
- `;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
206
- `))}else g.enqueue(h.encode(d+`
207
- `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
208
- `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
209
- `))}}}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(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var On,ga=w(()=>{"use strict";On=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var In,ha=w(()=>{"use strict";In=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ya(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(l=>{l.type==="text"?i.push({type:"text",text:l.text||""}):l.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function _a(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function ba(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,l)=>{if(i.startsWith("data: ")){let c=i.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)}
205
+ `;h.enqueue(g.encode(y))}}catch{h.enqueue(g.encode(d+`
206
+ `))}else h.enqueue(g.encode(d+`
207
+ `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
208
+ `);a=g.pop()||"";for(let m of g)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
209
+ `))}}}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(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var In,_a=P(()=>{"use strict";In=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 Mn,ba=P(()=>{"use strict";Mn=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ka(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(l=>{l.type==="text"?i.push({type:"text",text:l.text||""}):l.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function va(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function Ta(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,l)=>{if(i.startsWith("data: ")){let c=i.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)}
210
210
 
211
211
  `))}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)}
212
212
 
@@ -219,94 +219,100 @@ Examples:
219
219
  `));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)}
220
220
 
221
221
  `))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,c,u.message)}}}},a=new ReadableStream({async start(i){let l=n.body.getReader(),c="";try{for(;;){let{done:u,value:p}=await l.read();if(u){c&&s(c,i);break}c+=o.decode(p,{stream:!0});let d=c.split(`
222
- `);c=d.pop()||"";for(let f of d)s(f,i)}}catch(u){i.error(u)}finally{i.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var ka=w(()=>{"use strict"});async function Id(){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:
222
+ `);c=d.pop()||"";for(let f of d)s(f,i)}}catch(u){i.error(u)}finally{i.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var Sa=P(()=>{"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:
223
223
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
224
224
  2. Run "gcloud auth application-default login"
225
- 3. Use Google Cloud environment with default service account`)}}var Mn,va=w(()=>{"use strict";ka();Mn=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Id();return{body:ya(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 _a(e)}async transformResponseOut(e){return ba(e,this.name,this.logger)}}});var Ln,Ta=w(()=>{"use strict";Ln=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 $n,xa=w(()=>{"use strict";$n=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Nn,Sa=w(()=>{"use strict";Nn=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Un,Ca=w(()=>{"use strict";Un=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 Md}from"uuid";var Dn,Ra=w(()=>{"use strict";V();Dn=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 j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
226
- `);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
227
- `))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"&&m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
225
+ 3. Use Google Cloud environment with default service account`)}}var Ln,xa=P(()=>{"use strict";Sa();Ln=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Ud();return{body:ka(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 va(e)}async transformResponseOut(e){return Ta(e,this.name,this.logger)}}});var $n,Ca=P(()=>{"use strict";$n=class{name="cerebras";async transformRequestIn(e,t){let o=JSON.parse(JSON.stringify(e));return o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}}});var Nn,Ra=P(()=>{"use strict";Nn=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Un,wa=P(()=>{"use strict";Un=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Dn,Pa=P(()=>{"use strict";Dn=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let t={...e},o=Object.entries(this.options);for(let[r,s]of o)if(r in t)if(typeof t[r]=="object"&&typeof s=="object"&&!Array.isArray(t[r])&&!Array.isArray(s)&&t[r]!==null&&s!==null)t[r]=this.deepMergeObjects(t[r],s);else continue;else t[r]=this.cloneValue(s);return t}async transformResponseOut(e){return e}deepMergeObjects(e,t){let o={...e};for(let[r,s]of Object.entries(t))r in o&&typeof o[r]=="object"&&typeof s=="object"&&!Array.isArray(o[r])&&!Array.isArray(s)&&o[r]!==null&&s!==null?o[r]=this.deepMergeObjects(o[r],s):o[r]=this.cloneValue(s);return o}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>this.cloneValue(o));let t={};for(let[o,r]of Object.entries(e))t[o]=this.cloneValue(r);return t}}});import{v4 as Dd}from"uuid";var Fn,Ea=P(()=>{"use strict";V();Fn=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
226
+ `);for(let b of y)b.trim()&&g.enqueue(m.encode(b+`
227
+ `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let b=h.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"&&m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
228
228
 
229
- `)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let v={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(v)}
229
+ `)),_.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){g.appendReasoningContent(_.choices[0].delta.reasoning);let v={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let S=`data: ${JSON.stringify(v)}
230
230
 
231
- `;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let x={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let T=`data: ${JSON.stringify(x)}
231
+ `;m.enqueue(y.encode(S));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let S={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:"ccr_think_signature"}}}]};S.choices?.[0]?.delta&&delete S.choices[0].delta.reasoning;let T=`data: ${JSON.stringify(S)}
232
232
 
233
- `;m.enqueue(y.encode(T))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(v=>{v.id=`call_${Md()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),_.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let k=`data: ${JSON.stringify(_)}
233
+ `;m.enqueue(y.encode(T))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(v=>{v.id=`call_${Dd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),_.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let k=`data: ${JSON.stringify(_)}
234
234
 
235
- `;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(g+`
236
- `))}}else m.enqueue(y.encode(g+`
237
- `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
235
+ `;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(h+`
236
+ `))}}else m.enqueue(y.encode(h+`
237
+ `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){l.trim()&&d(l,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
238
238
  `);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
239
239
  `))}continue}let y=l.split(`
240
240
  `);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
241
- `))}}}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 mr,Ld,Fn,wa=w(()=>{"use strict";V();mr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
241
+ `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var hr,Fd,jn,Aa=P(()=>{"use strict";V();hr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
242
242
 
243
243
  Output format:
244
244
  <reasoning_content>
245
245
  Your detailed thinking process goes here
246
246
  </reasoning_content>
247
- Your final answer must follow after the closing tag above.`,Ld=10,Fn=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<Ld)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
248
- ${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:mr}):o.content=[{type:"text",text:mr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:mr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await j(e);if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=r.choices[0]?.message.content.match(s);a&&a[1]&&(r.thinking={content:a[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,a=new TextEncoder,i=new ReadableStream({async start(l){let c=e.body.getReader(),u="",p="SEARCHING",d="",f="",g=(h,m)=>{if(typeof m!="string"){h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&!h.choices[0].delta.content&&(h.choices[0].index=r,l.enqueue(a.encode(`data: ${JSON.stringify(h)}
247
+ Your final answer must follow after the closing tag above.`,Fd=10,jn=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<Fd)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
248
+ ${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:hr}):o.content=[{type:"text",text:hr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:hr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await j(e);if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=r.choices[0]?.message.content.match(s);a&&a[1]&&(r.thinking={content:a[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,a=new TextEncoder,i=new ReadableStream({async start(l){let c=e.body.getReader(),u="",p="SEARCHING",d="",f="",h=(g,m)=>{if(typeof m!="string"){g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0&&!g.choices[0].delta.content&&(g.choices[0].index=r,l.enqueue(a.encode(`data: ${JSON.stringify(g)}
249
249
 
250
- `)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let x={...h.choices[0].delta,thinking:{content:_}};delete x.content;let T={...h,choices:[{...h.choices[0],delta:x,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
250
+ `)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let S={...g.choices[0].delta,thinking:{content:_}};delete S.content;let T={...g,choices:[{...g.choices[0],delta:S,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
251
251
 
252
- `))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let v={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
252
+ `))}let k={...g.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let v={...g,choices:[{...g.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
253
253
 
254
- `)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...h.choices[0].delta,thinking:{content:_}};delete k.content;let v={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
254
+ `)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...g.choices[0].delta,thinking:{content:_}};delete k.content;let v={...g,choices:[{...g.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
255
255
 
256
- `))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...h.choices[0].delta,content:_};k.thinking&&delete k.thinking;let v={...h,choices:[{...h.choices[0],delta:k}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
256
+ `))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...g.choices[0].delta,content:_};k.thinking&&delete k.thinking;let v={...g,choices:[{...g.choices[0],delta:k}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
257
257
 
258
- `)),f=""}r++,y=""}};try{for(;;){let{done:h,value:m}=await c.read();if(h)break;let y=s.decode(m,{stream:!0});u+=y;let b=u.split(`
258
+ `)),f=""}r++,y=""}};try{for(;;){let{done:g,value:m}=await c.read();if(g)break;let y=s.decode(m,{stream:!0});u+=y;let b=u.split(`
259
259
  `);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){l.enqueue(a.encode(_+`
260
260
 
261
- `));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(_+`
261
+ `));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));h(k,k.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(_+`
262
262
  `))}else l.enqueue(a.encode(_+`
263
- `))}}}catch(h){console.error("Stream error:",h),l.error(h)}finally{try{c.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}if(p==="REASONING"){let m={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(m)}
263
+ `))}}}catch(g){console.error("Stream error:",g),l.error(g)}finally{try{c.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}if(p==="REASONING"){let m={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(m)}
264
264
 
265
- `))}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var jn,Pa=w(()=>{"use strict";V();jn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u){a.trim()&&l.enqueue(r.encode(a+`
265
+ `))}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Hn,Oa=P(()=>{"use strict";V();Hn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u){a.trim()&&l.enqueue(r.encode(a+`
266
266
  `));break}let d=o.decode(p,{stream:!0});a+=d;let f=a.split(`
267
- `);a=f.pop()||"";for(let g of f)if(g.trim())if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let h=JSON.parse(g.slice(6));if(h.choices?.[0]?.delta?.reasoning_content){s+=h.choices[0].delta.reasoning_content;let m={...h,choices:[{...h.choices[0],delta:{thinking:{content:h.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content,l.enqueue(r.encode(`data: ${JSON.stringify(m)}
267
+ `);a=f.pop()||"";for(let h of f)if(h.trim())if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let g=JSON.parse(h.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){s+=g.choices[0].delta.reasoning_content;let m={...g,choices:[{...g.choices[0],delta:{thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content,l.enqueue(r.encode(`data: ${JSON.stringify(m)}
268
268
 
269
- `));continue}if(h.choices?.[0]?.delta?.content&&s&&!h.choices[0]?.delta?.reasoning_content){let m=Date.now().toString(),y={...h,choices:[{...h.choices[0],delta:{content:null,thinking:{content:s,signature:m}}}]};l.enqueue(r.encode(`data: ${JSON.stringify(y)}
269
+ `));continue}if(g.choices?.[0]?.delta?.content&&s&&!g.choices[0]?.delta?.reasoning_content){let m=Date.now().toString(),y={...g,choices:[{...g.choices[0],delta:{content:null,thinking:{content:s,signature:m}}}]};l.enqueue(r.encode(`data: ${JSON.stringify(y)}
270
270
 
271
- `)),s=""}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&&l.enqueue(r.encode(`data: ${JSON.stringify(h)}
271
+ `)),s=""}g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0&&l.enqueue(r.encode(`data: ${JSON.stringify(g)}
272
272
 
273
- `))}catch{l.enqueue(r.encode(g+`
274
- `))}else l.enqueue(r.encode(g+`
275
- `))}}catch(u){l.error(u)}finally{try{c.releaseLock()}catch{}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await j(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 Ea}from"uuid";var Hn,Aa=w(()=>{"use strict";V();je();Hn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(c=>c.toLowerCase()===a),l=i?r[i]: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")||Ea()}async transformRequestIn(e,t,o){let r=e.reasoning?.enabled||e.messages.some(s=>s.thinking?.content);return e.messages.forEach(s=>{if(Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)}),s.role==="assistant"){let a=s.thinking?.content,i=s.thinking?.signature;a&&typeof a=="string"&&a.trim()?(s.reasoning_content=a,i&&(s.reasoning_content_signature=i)):r&&s.tool_calls?.length&&!s.reasoning_content&&(s.reasoning_content=" "),s.thinking&&delete s.thinking}}),Object.assign(e,this.options||{}),{body:e,config:{headers:{"x-opencode-session":this.resolveSessionId(e,o)}}}}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
276
- `);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
277
- `))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let b=JSON.parse(g.slice(6));if(b.usage&&(b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
273
+ `))}catch{l.enqueue(r.encode(h+`
274
+ `))}else l.enqueue(r.encode(h+`
275
+ `))}}catch(u){l.error(u)}finally{try{c.releaseLock()}catch{}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await j(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 Ia}from"uuid";var zn,Ma=P(()=>{"use strict";V();Fe();zn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(c=>c.toLowerCase()===a),l=i?r[i]: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")||Ia()}async transformRequestIn(e,t,o){let r=e.reasoning?.enabled||e.messages.some(s=>s.thinking?.content);return e.messages.forEach(s=>{if(Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)}),s.role==="assistant"){let a=s.thinking?.content,i=s.thinking?.signature;a&&typeof a=="string"&&a.trim()?(s.reasoning_content=a,i&&(s.reasoning_content_signature=i)):r&&s.tool_calls?.length&&!s.reasoning_content&&(s.reasoning_content=" "),s.thinking&&delete s.thinking}}),Object.assign(e,this.options||{}),{body:e,config:{headers:{"x-opencode-session":this.resolveSessionId(e,o)}}}}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
276
+ `);for(let b of y)b.trim()&&g.enqueue(m.encode(b+`
277
+ `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let b=JSON.parse(h.slice(6));if(b.usage&&(b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
278
278
 
279
- `));return}b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let _=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(_){h.appendReasoningContent(_);let P={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:_}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(P)}
279
+ `));return}b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0);let _=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(_){g.appendReasoningContent(_);let w={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:_}}}]};w.choices?.[0]?.delta&&(delete w.choices[0].delta.reasoning,delete w.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(w)}
280
280
 
281
- `));return}if(b.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let P="ccr_think_signature",E=b.choices[0].delta.content,R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:P}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(R)}
281
+ `));return}if(b.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let w="ccr_think_signature",E=b.choices[0].delta.content,R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:w}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(R)}
282
282
 
283
283
  `));let A={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:E}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(A)}
284
284
 
285
- `));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(P=>{P.id=`call_${Ea()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,v=k&&Object.keys(k).length>0,x=b.choices?.[0]?.finish_reason,T=b.usage;(v||x||T)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
285
+ `));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(w=>{w.id=`call_${Ia()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,v=k&&Object.keys(k).length>0,S=b.choices?.[0]?.finish_reason,T=b.usage;(v||S||T)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
286
286
 
287
- `))}catch{m.enqueue(y.encode(g+`
288
- `))}else m.enqueue(y.encode(g+`
289
- `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
287
+ `))}catch{m.enqueue(y.encode(h+`
288
+ `))}else m.enqueue(y.encode(h+`
289
+ `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){l.trim()&&d(l,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
290
290
  `);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
291
291
  `))}continue}let y=l.split(`
292
292
  `);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
293
- `))}}}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 Nd(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 Ud(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 $d,zn,Oa=w(()=>{"use strict";Qe();$d={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};zn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=Nd(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Ud(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=ye(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=$d[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 Ia(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 Bn,Ma=w(()=>{"use strict";Qe();V();Bn=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),a=!r&&!s&&o.includes("deepseek");if(e==="none")return a||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return a?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return a?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,a=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,a=a||r.effort==="none"):typeof r?.max_tokens=="number"?s=ye(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!a&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(a=!0));let i=this.resolveEffort(a?"none":s,o);return i?t.reasoning_effort=i:delete t.reasoning_effort,delete t.reasoning,delete t.thinking,delete t.enable_thinking,t}async transformResponseOut(e){let t=e.headers.get("Content-Type")??"";if(t.includes("application/json")){if(!e.body)return e;let o=await pe(e);if(o){let a=new Headers(e.headers);if(o.isSSE&&a.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:a}),o.isSSE)return this.transformStream(e)}else{let a=await me(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await j(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)Ia(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,f=Array.isArray(p?.choices)?p.choices:[];for(let g of f)Ia(g?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:c},a=(c,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,g="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)g+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(g+=s(r),r=""),g&&c.enqueue(o.encode(g))},i=e.body.pipeThrough(new TransformStream({transform(c,u){r+=t.decode(c,{stream:!0}),a(u)},flush(c){r+=t.decode(),a(c,!0)}})),l=new Headers(e.headers);return l.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:l})}}});var La,$a=w(()=>{oa();ra();sa();ia();aa();ca();la();ua();da();fa();ma();ga();ha();va();Ta();xa();Sa();Ca();Ra();Xo();wa();Pa();Aa();Oa();Ma();La={AnthropicTransformer:hn,GeminiTransformer:vn,VertexGeminiTransformer:Tn,VertexClaudeTransformer:Mn,DeepseekTransformer:xn,TooluseTransformer:Sn,OpenrouterTransformer:Cn,OpenAITransformer:Nn,MaxTokenTransformer:Rn,GroqTransformer:wn,CleancacheTransformer:Pn,EnhanceToolTransformer:En,ReasoningTransformer:An,SamplingTransformer:On,MaxCompletionTokens:In,CerebrasTransformer:Ln,StreamOptionsTransformer:$n,CustomParamsTransformer:Un,VercelTransformer:Dn,OpenAIResponsesTransformer:De,ForceReasoningTransformer:Fn,KimiTransformer:jn,OpenCodeTransformer:Hn,DefaultThinkingTransformer:zn,AmdTransformer:Bn}});var Ye,gr=w(()=>{"use strict";$a();Ye=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=vo(vo.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})
293
+ `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function Hd(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 zd(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 jd,Bn,La=P(()=>{"use strict";Ge();jd={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Bn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=Hd(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=zd(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=ye(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=jd[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 Jn,Na=P(()=>{"use strict";Ge();V();Jn=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),a=!r&&!s&&o.includes("deepseek");if(e==="none")return a||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return a?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return a?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,a=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,a=a||r.effort==="none"):typeof r?.max_tokens=="number"?s=ye(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!a&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(a=!0));let i=this.resolveEffort(a?"none":s,o);return i?t.reasoning_effort=i:delete t.reasoning_effort,delete t.reasoning,delete t.thinking,delete t.enable_thinking,t}async transformResponseOut(e){let t=e.headers.get("Content-Type")??"";if(t.includes("application/json")){if(!e.body)return e;let o=await fe(e);if(o){let a=new Headers(e.headers);if(o.isSSE&&a.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:a}),o.isSSE)return this.transformStream(e)}else{let a=await me(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await j(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,f=Array.isArray(p?.choices)?p.choices:[];for(let h of f)$a(h?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:c},a=(c,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,h="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)h+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(h+=s(r),r=""),h&&c.enqueue(o.encode(h))},i=e.body.pipeThrough(new TransformStream({transform(c,u){r+=t.decode(c,{stream:!0}),a(u)},flush(c){r+=t.decode(),a(c,!0)}})),l=new Headers(e.headers);return l.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:l})}}});var Ua,Da=P(()=>{ia();aa();ca();la();ua();da();pa();fa();ma();ha();ya();_a();ba();xa();Ca();Ra();wa();Pa();Ea();qo();Aa();Oa();Ma();La();Na();Ua={AnthropicTransformer:yn,GeminiTransformer:Tn,VertexGeminiTransformer:Sn,VertexClaudeTransformer:Ln,DeepseekTransformer:xn,TooluseTransformer:Cn,OpenrouterTransformer:Rn,OpenAITransformer:Un,MaxTokenTransformer:wn,GroqTransformer:Pn,CleancacheTransformer:En,EnhanceToolTransformer:An,ReasoningTransformer:On,SamplingTransformer:In,MaxCompletionTokens:Mn,CerebrasTransformer:$n,StreamOptionsTransformer:Nn,CustomParamsTransformer:Dn,VercelTransformer:Fn,OpenAIResponsesTransformer:Ue,ForceReasoningTransformer:jn,KimiTransformer:Hn,OpenCodeTransformer:zn,DefaultThinkingTransformer:Bn,AmdTransformer:Jn}});var Ve,yr=P(()=>{"use strict";Da();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=To(To.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})
294
294
  error: ${t.message}
295
295
  stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
296
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(La).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});import{get_encoding as Dd}from"tiktoken";var _t,Na=w(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Dd(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(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(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(l=>{o+=t.encode(l||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Jn}from"path";import{homedir as Fd}from"os";import{existsSync as hr,mkdirSync as jd}from"fs";import{promises as Wn}from"fs";import{Tokenizer as Hd}from"@huggingface/tokenizers";var Kn,Ua=w(()=>{"use strict";Kn=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||Jn(Fd(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Jn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Jn(e,"tokenizer.json"),tokenizerConfig:Jn(e,"tokenizer_config.json")}}ensureDir(e){hr(e)||jd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!hr(e.tokenizerJson)||!hr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Wn.readFile(e.tokenizerJson,"utf-8"),Wn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Wn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Wn.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:i,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 Hd(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let l of i.content)l?.type!=="image"&&t.push(l?.type==="text"?String(l.text??""):JSON.stringify(l));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Gn,Da=w(()=>{"use strict";q();Gn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},i=this.options.resolveProxyUrl?.();i&&(a.dispatcher=G(i));let l=await fetch(this.config.url,a);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(`
297
- `):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 Xe,yr=w(()=>{"use strict";Na();Ua();Da();q();Xe=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 _t("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 _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Kn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Gn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function Fa(n){if(!n||typeof n!="object"||Qd(n))return null;for(let t of Gd(n)){let o=Kd(t);if(o)return o}return null}function Kd(n){if(!n||typeof n!="object")return null;let e={},t=Qn(n,zd);if(t!==void 0){let a=ja(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Qn(n,Bd);if(o!==void 0){let a=ja(o);e.usedBalance=a,e.totalBalance=100}let r=Qn(n,Jd);if(r!==void 0){let a=Ha(r);a&&(e.resetTime=a)}let s=Qn(n,Wd);if(s!==void 0){let a=Ha(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function ja(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Qn(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function Gd(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function Qd(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 Ha(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 Er(n){let e=Ar(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?np:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?op:e==="deepseek.com"||e.endsWith(".deepseek.com")?Vd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Yd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Xd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Zd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?qd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?ep:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?tp:null:null}function rp(n){let e=Ar(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function sp(n,e){let t=wr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(l=>l.includes(i)||i.includes(l))})||t[0]}function wr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>wr(e)):Object.values(n).flatMap(e=>wr(e))}function Pr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Ar(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function U(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,_r,br,kr,vr,Tr,zd,Bd,Jd,Wd,xr,Sr,Cr,Rr,Vd,Yd,Xd,Zd,qd,ep,tp,np,op,Or=w(()=>{"use strict";q();se=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=G(r));let l=await fetch(e,i);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},_r=class extends se{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(l=>U(l?.total_balance)!==void 0);if(!a)return null;let i=U(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},br=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 a={},i=U(s.limit),l=U(s.limit_remaining),c=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),l!==void 0&&(a.remainingBalance=l),c!==void 0&&(a.usedBalance=c),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},kr=class extends se{async queryQuota(e,t,o){let r=rp(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},l=U(a.totalBalance),c=U(a.balance);return l!==void 0&&(i.totalBalance=l),c!==void 0&&(i.remainingBalance=c),l!==void 0&&c!==void 0&&(i.usedBalance=Math.max(0,l-c)),this.hasQuotaData(i)?i:null}},vr=class extends se{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),l=Array.isArray(i?.data?.limits)?i.data.limits:[],c=null,u=null,p=null;for(let f of l)f.type==="TOKENS_LIMIT"?f.unit===3?c=f:f.unit===6?u=f:c||(c=f):f.type==="TIME_LIMIT"&&(p=f);let d={};if(c){let f=U(c.currentValue),g=U(c.usage),h=U(c.remaining),m=U(c.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),g!==void 0?d.limitDaily=g:f!==void 0&&h!==void 0&&(d.limitDaily=f+h),c.nextResetTime&&(d.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),g=U(u.usage),h=U(u.remaining),m=U(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),g!==void 0?d.totalBalance=g:f!==void 0&&h!==void 0&&(d.totalBalance=f+h),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=U(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=U(p.usage),g=U(p.currentValue),h=U(p.remaining);f!==void 0?d.limitDaily=f:g!==void 0&&h!==void 0&&(d.limitDaily=g+h)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},Tr=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","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=G(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let c=(await i.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=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let g=U(u.perWeekUsedQuota),h=U(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),h!==void 0&&(p.totalBalance=h),this.hasQuotaData(p)?p:null}catch{return null}}};zd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Bd=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Jd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Wd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];xr=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 a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Pr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),l=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),c={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",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 p=await u.json();return Fa(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=G(o));let l=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!l.ok)return null;let c=await l.json();return Fa(c)}catch{return null}}},Sr=class extends se{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity","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:(Pr(e.quotaToken,"atp-auth-token")||Pr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let l=sp(i,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},p=U(c.rp5hUsage),d=U(c.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=U(c.rpwUsage),g=U(c.rpwLimit);return f!==void 0&&(u.usedBalance=f),g!==void 0&&(u.totalBalance=g),u.remainingBalance===void 0&&g!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,g-f)),this.hasQuotaData(u)?u:null}catch{return null}}},Cr=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","Accept-Encoding":"identity",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),l={},c=Array.isArray(i?.limits)?i.limits:[];if(c.length>0&&c[0]?.detail){let p=c[0].detail,d=U(p.limit),f=U(p.remaining),g=p.resetTime;d!==void 0&&f!==void 0&&(l.usedDailyBalance=Math.max(0,d-f),l.limitDaily=d),g&&(l.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let p=U(u.limit),d=U(u.remaining),f=U(u.used),g=u.resetTime;p!==void 0&&(l.totalBalance=p,f!==void 0?l.usedBalance=f: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}}},Rr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Ar(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let k of i)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=U(u.current_interval_total_count),f=U(u.current_interval_usage_count),g=U(u.current_interval_remaining_percent),h=U(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):g!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-g)),h&&(p.resetTime=new Date(h).toISOString());let m=U(u.current_weekly_total_count),y=U(u.current_weekly_usage_count),b=U(u.current_weekly_remaining_percent),_=U(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Vd=new _r,Yd=new br,Xd=new kr,Zd=new vr,qd=new Tr,ep=new xr,tp=new Sr,np=new Cr,op=new Rr});async function Vn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=za.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<ip)return;let r=o??{fetchedAt:0};return r.pending=(async()=>{try{let s=await t.fetchQuota(e);s&&lt(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),za.set(n,r),r.pending}var ip,Ba,za,Ir=w(()=>{"use strict";Ce();ip=6e4,Ba=2500,za=new Map});function Ja(n){return{[ap]:n,[cp]:Vt}}function _e(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function up(n){return n===!0||n==="true"||n===1||n==="1"}function dp(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 pp(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 fp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Mr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(_e(n))return{success:!1,skipped:!0,error:Lr,latencyMs:r()};let s=pp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=G(t));let i=await fetch(s,a);if(i.headers&&it(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let l=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${l.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",l=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:l?"timeout":"network"}}}async function mp(n,e,t,o){if(_e(n))return{success:!1,skipped:!0,error:Lr};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Ja("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(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(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function gp(n,e,t,o,r){if(_e(n))return{success:!1,skipped:!0,error:Lr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Ja("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(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(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function Wa(n,e,t,o,r,s){return be||(be=new Yn(n,e,t,o,r,s)),be}function bt(n,e,t,o,r,s){let a=Wa(n,e,t,o,r,s);return a.start(),a}function $r(){be&&be.stop()}function Nr(){be&&(be.stop(),be=null)}var ap,cp,lp,Lr,Yn,be,Xn=w(()=>{"use strict";re();Se();Or();Ce();Ir();$o();q();ap="x-claude-code-router-source",cp="x-claude-code-router-version";lp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Lr="Managed provider requires its plugin's authenticated model sync";Yn=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,a){this.config={...lp,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),l={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,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&&!_e(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Er(s.baseUrl),i=Array.isArray(s.models)?s.models:[],l=this.resolveProxyUrl?.(s);if(!a){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")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,l).then(c=>{if(c){lt(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 f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),fp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Mr(s,this.config.probeTimeoutMs,l).then(c=>{this.recordProbe(s.name,c,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&_e(a)&&!this.config.excludeProviders.includes(a.name));for(let a of s){let i=this.resolveManagedRuntime(a);i&&typeof i.fetchQuota=="function"&&o.push({provider:a.name,models:Array.isArray(a.models)?a.models:[],type:"managed-plugin-quota",promise:Vn(a.name,a,i)})}}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=H(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!_e(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=>Mr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let l=a.value;if(l.skipped)continue;if(this.recordProbe(s.name,l,"health"),l.success){let c=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=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(f||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 i)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:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let l of i)e.recordFailure(s.name,l,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=H();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let l=o.get(s)??[];l.push(i),o.set(s,l)}for(let[r,s]of o){let a=this.getProviders().find(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let l=s[0],c=e.getState(r,l);!c||c.status!=="open"||c.rateLimitUntil&&Date.now()<c.rateLimitUntil||Date.now()-(c.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,l,s,e)||await this.probeManagedLiveness(r,i,a,l,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=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(i)})},u={TIMEOUT:i};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)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=H(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),l=i.join(",");if(!a||!l)continue;let c=o.find(d=>d?.name===a);if(c&&_e(c))continue;let u=e.getState(a,l);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,l),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await gp(p,l,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,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 f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!_e(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=dp(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let l=i.wakeupTime||a,[c,u]=l.split(":"),p=parseInt(c,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,g=(p*60+d)*6e4-(o*60+r)*6e4,h=g>0&&g<=300*1e3;(f||h)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${l}`),mp(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?up(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Mr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)H().recordSuccess(o.name,i);else for(let i of a)H().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},be=null});var Ka=w(()=>{"use strict"});var Ur,kt,Ga=w(()=>{"use strict";Ur=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()}},kt=new Ur});var ie,Dr=w(()=>{"use strict";ie=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
298
- `);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 Ze,Fr=w(()=>{"use strict";Ze=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
296
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Ua).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 Bd}from"tiktoken";var _t,Fa=P(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Bd(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(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(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(l=>{o+=t.encode(l||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Wn}from"path";import{homedir as Jd}from"os";import{existsSync as _r,mkdirSync as Wd}from"fs";import{promises as Kn}from"fs";import{Tokenizer as Kd}from"@huggingface/tokenizers";var Gn,ja=P(()=>{"use strict";Gn=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||Wn(Jd(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Wn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Wn(e,"tokenizer.json"),tokenizerConfig:Wn(e,"tokenizer_config.json")}}ensureDir(e){_r(e)||Wd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!_r(e.tokenizerJson)||!_r(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Kn.readFile(e.tokenizerJson,"utf-8"),Kn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Kn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Kn.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:i,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 Kd(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let l of i.content)l?.type!=="image"&&t.push(l?.type==="text"?String(l.text??""):JSON.stringify(l));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Qn,Ha=P(()=>{"use strict";ee();Qn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},i=this.options.resolveProxyUrl?.();i&&(a.dispatcher=G(i));let l=await fetch(this.config.url,a);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(`
297
+ `):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 Ye,br=P(()=>{"use strict";Fa();ja();Ha();ee();Ye=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 _t("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 _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Gn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Qn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return pe(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});import{createHash as Gd,createHmac as Qd}from"node:crypto";function za(n){if(!n||typeof n!="object"||tp(n))return null;for(let t of ep(n)){let o=qd(t);if(o)return o}return null}function qd(n){if(!n||typeof n!="object")return null;let e={},t=Vn(n,Vd);if(t!==void 0){let a=Ba(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Vn(n,Yd);if(o!==void 0){let a=Ba(o);e.usedBalance=a,e.totalBalance=100}let r=Vn(n,Xd);if(r!==void 0){let a=Ja(r);a&&(e.resetTime=a)}let s=Vn(n,Zd);if(s!==void 0){let a=Ja(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function Ba(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Vn(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function ep(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function tp(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 Ja(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 np(n){let{accessKey:e,secretKey:t,method:o,url:r,body:s,region:a,service:i,xDate:l}=n,c=l.slice(0,8),u="application/json",p=Wa(s),d="host;x-date;x-content-sha256;content-type",f=`host:${r.host}
298
+ x-date:${l}
299
+ x-content-sha256:${p}
300
+ content-type:${u}
301
+ `,h=[...r.searchParams.entries()].sort(([T,w],[E,R])=>T<E?-1:T>E?1:w<R?-1:w>R?1:0).map(([T,w])=>`${Ka(T)}=${Ka(w)}`).join("&"),g=[o.toUpperCase(),r.pathname,h,f,d,p].join(`
302
+ `),m=`${c}/${a}/${i}/request`,y=["HMAC-SHA256",l,m,Wa(g)].join(`
303
+ `),b=bt(t,c),_=bt(b,a),k=bt(_,i),v=bt(k,"request"),S=bt(v,y).toString("hex");return{"Content-Type":u,"X-Date":l,"X-Content-Sha256":p,Authorization:`HMAC-SHA256 Credential=${e}/${m}, SignedHeaders=${d}, Signature=${S}`}}function Wa(n){return Gd("sha256").update(n,"utf8").digest("hex")}function bt(n,e){return Qd("sha256",n).update(e,"utf8").digest()}function Ka(n){return encodeURIComponent(n).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function op(n){if(!n||typeof n!="object"||n.ResponseMetadata?.Error)return null;let e=n.Result?.QuotaUsage;if(!Array.isArray(e))return null;let t={};for(let o of e){let r=o?.Level;if(r!=="session"&&r!=="weekly")continue;let s=U(o?.Percent);if(s===void 0)continue;let a=U(o?.ResetTimestamp);if(a!==void 0&&a<=0)continue;let i;if(a!==void 0){let l=new Date(a*1e3);i=isNaN(l.getTime())?void 0:l.toISOString()}r==="session"?(t.limitDaily=100,t.usedDailyBalance=s,i&&(t.resetTime=i)):(t.totalBalance=100,t.usedBalance=s,i&&(t.resetTime7d=i))}return t.usedDailyBalance!==void 0||t.usedBalance!==void 0?t:null}function Ir(n){let e=Mr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?dp:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?pp:e==="deepseek.com"||e.endsWith(".deepseek.com")?rp:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?sp:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?ip:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?ap:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?cp:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?lp:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?up:e==="ark.cn-beijing.volces.com"&&hp(n)?.includes("/api/coding/")?fp:null:null}function mp(n){let e=Mr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function gp(n,e){let t=Ar(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(l=>l.includes(i)||i.includes(l))})||t[0]}function Ar(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Ar(e)):Object.values(n).flatMap(e=>Ar(e))}function Or(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Mr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function hp(n){try{return new URL(n).pathname}catch{return null}}function U(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 re,kr,vr,Tr,Sr,xr,Vd,Yd,Xd,Zd,Cr,Rr,wr,Pr,Er,rp,sp,ip,ap,cp,lp,up,dp,pp,fp,Lr=P(()=>{"use strict";ee();re=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=G(r));let l=await fetch(e,i);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}},kr=class extends re{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(l=>U(l?.total_balance)!==void 0);if(!a)return null;let i=U(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},vr=class extends re{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=U(s.limit),l=U(s.limit_remaining),c=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),l!==void 0&&(a.remainingBalance=l),c!==void 0&&(a.usedBalance=c),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},Tr=class extends re{async queryQuota(e,t,o){let r=mp(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},l=U(a.totalBalance),c=U(a.balance);return l!==void 0&&(i.totalBalance=l),c!==void 0&&(i.remainingBalance=c),l!==void 0&&c!==void 0&&(i.usedBalance=Math.max(0,l-c)),this.hasQuotaData(i)?i:null}},Sr=class extends re{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),l=Array.isArray(i?.data?.limits)?i.data.limits:[],c=null,u=null,p=null;for(let f of l)f.type==="TOKENS_LIMIT"?f.unit===3?c=f:f.unit===6?u=f:c||(c=f):f.type==="TIME_LIMIT"&&(p=f);let d={};if(c){let f=U(c.currentValue),h=U(c.usage),g=U(c.remaining),m=U(c.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),h!==void 0?d.limitDaily=h:f!==void 0&&g!==void 0&&(d.limitDaily=f+g),c.nextResetTime&&(d.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),h=U(u.usage),g=U(u.remaining),m=U(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),h!==void 0?d.totalBalance=h:f!==void 0&&g!==void 0&&(d.totalBalance=f+g),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=U(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=U(p.usage),h=U(p.currentValue),g=U(p.remaining);f!==void 0?d.limitDaily=f:h!==void 0&&g!==void 0&&(d.limitDaily=h+g)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},xr=class extends re{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=G(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let c=(await i.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=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let h=U(u.perWeekUsedQuota),g=U(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),g!==void 0&&(p.totalBalance=g),this.hasQuotaData(p)?p:null}catch{return null}}};Vd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Yd=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Xd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Zd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Cr=class extends re{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Or(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),l=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),c={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",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 p=await u.json();return za(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=G(o));let l=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!l.ok)return null;let c=await l.json();return za(c)}catch{return null}}},Rr=class extends re{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity","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:(Or(e.quotaToken,"atp-auth-token")||Or(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let l=gp(i,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},p=U(c.rp5hUsage),d=U(c.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=U(c.rpwUsage),h=U(c.rpwLimit);return f!==void 0&&(u.usedBalance=f),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,h-f)),this.hasQuotaData(u)?u:null}catch{return null}}},wr=class extends re{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),l={},c=Array.isArray(i?.limits)?i.limits:[];if(c.length>0&&c[0]?.detail){let p=c[0].detail,d=U(p.limit),f=U(p.remaining),h=U(p.used),g=p.resetTime;d!==void 0&&(l.limitDaily=d,h!==void 0?l.usedDailyBalance=h:f!==void 0&&(l.usedDailyBalance=Math.max(0,d-f))),g&&(l.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let p=U(u.limit),d=U(u.remaining),f=U(u.used),h=u.resetTime;p!==void 0&&(l.totalBalance=p,f!==void 0?l.usedBalance=f:d!==void 0&&(l.usedBalance=Math.max(0,p-d),l.remainingBalance=d)),h&&(l.resetTime7d=new Date(h).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Pr=class extends re{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Mr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let k of i)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=U(u.current_interval_total_count),f=U(u.current_interval_usage_count),h=U(u.current_interval_remaining_percent),g=U(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),g&&(p.resetTime=new Date(g).toISOString());let m=U(u.current_weekly_total_count),y=U(u.current_weekly_usage_count),b=U(u.current_weekly_remaining_percent),_=U(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}};Er=class extends re{async queryQuota(e,t,o){let r=e.quotaAccessKey?.trim(),s=e.quotaSecretKey?.trim();if(!r||!s)return null;let a="{}",i=new URL("https://open.volcengineapi.com/?Action=GetCodingPlanUsage&Version=2024-01-01"),l=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),u={method:"POST",headers:{Accept:"application/json","Accept-Encoding":"identity",...np({accessKey:r,secretKey:s,method:"POST",url:i,body:a,region:"cn-beijing",service:"ark",xDate:l})},body:a,signal:AbortSignal.timeout(t)};try{o&&(u.dispatcher=G(o));let p=await fetch(i.toString(),u);if(!p.ok)return null;let d=await p.json();return op(d)}catch{return null}}},rp=new kr,sp=new vr,ip=new Tr,ap=new Sr,cp=new xr,lp=new Cr,up=new Rr,dp=new wr,pp=new Pr,fp=new Er});async function Yn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=Ga.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<yp)return;let r=o??{fetchedAt:0};return r.pending=(async()=>{try{let s=await t.fetchQuota(e);s&&lt(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),Ga.set(n,r),r.pending}var yp,Qa,Ga,$r=P(()=>{"use strict";Ce();yp=6e4,Qa=2500,Ga=new Map});function Va(n){return{[_p]:n,[bp]:Yt}}function _e(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function vp(n){return n===!0||n==="true"||n===1||n==="1"}function Tp(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 Sp(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 xp(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));if(_e(n))return{success:!1,skipped:!0,error:Ur,latencyMs:r()};let s=Sp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=G(t));let i=await fetch(s,a);if(i.headers&&it(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let l=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${l.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",l=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:l?"timeout":"network"}}}async function Cp(n,e,t,o){if(_e(n))return{success:!1,skipped:!0,error:Ur};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Va("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(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(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function Rp(n,e,t,o,r){if(_e(n))return{success:!1,skipped:!0,error:Ur};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Va("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(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(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function Ya(n,e,t,o,r,s){return be||(be=new Xn(n,e,t,o,r,s)),be}function kt(n,e,t,o,r,s){let a=Ya(n,e,t,o,r,s);return a.start(),a}function Dr(){be&&be.stop()}function Fr(){be&&(be.stop(),be=null)}var _p,bp,kp,Ur,Xn,be,Zn=P(()=>{"use strict";ie();xe();Lr();Ce();$r();Uo();ee();_p="x-claude-code-router-source",bp="x-claude-code-router-version";kp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Ur="Managed provider requires its plugin's authenticated model sync";Xn=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,a){this.config={...kp,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),l={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,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&&!_e(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Ir(s.baseUrl),i=Array.isArray(s.models)?s.models:[],l=this.resolveProxyUrl?.(s);if(!a){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")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,l).then(c=>{if(c){lt(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 f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),xp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Nr(s,this.config.probeTimeoutMs,l).then(c=>{this.recordProbe(s.name,c,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&_e(a)&&!this.config.excludeProviders.includes(a.name));for(let a of s){let i=this.resolveManagedRuntime(a);i&&typeof i.fetchQuota=="function"&&o.push({provider:a.name,models:Array.isArray(a.models)?a.models:[],type:"managed-plugin-quota",promise:Yn(a.name,a,i)})}}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=H(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!_e(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=>Nr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let l=a.value;if(l.skipped)continue;if(this.recordProbe(s.name,l,"health"),l.success){let c=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=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(f||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 i)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:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let l of i)e.recordFailure(s.name,l,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=H();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let l=o.get(s)??[];l.push(i),o.set(s,l)}for(let[r,s]of o){let a=this.getProviders().find(c=>c?.name===r&&c.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let l=i.modelScopedRecovery?s.map(c=>[c]):[s];for(let c of l){let u=c[0],p=e.getState(r,u);!p||p.status!=="open"||p.rateLimitUntil&&Date.now()<p.rateLimitUntil||Date.now()-(p.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,u,c,e)||await this.probeManagedLiveness(r,i,a,u,c,e)}}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState({model:r,provider:o});return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable({model:r,provider:o}),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=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(i)})},u={TIMEOUT:i};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)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=H(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),l=i.join(",");if(!a||!l)continue;let c=o.find(d=>d?.name===a);if(c&&_e(c))continue;let u=e.getState(a,l);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,l),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await Rp(p,l,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,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 f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!_e(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=Tp(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let l=i.wakeupTime||a,[c,u]=l.split(":"),p=parseInt(c,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,h=(p*60+d)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(f||g)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${l}`),Cp(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?vp(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Nr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)H().recordSuccess(o.name,i);else for(let i of a)H().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},be=null});var Xa=P(()=>{"use strict"});var jr,vt,Za=P(()=>{"use strict";jr=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()}},vt=new jr});var ae,Hr=P(()=>{"use strict";ae=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
304
+ `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Xe,zr=P(()=>{"use strict";Xe=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
299
305
  `),e.id&&(o+=`id: ${e.id}
300
306
  `),e.retry&&(o+=`retry: ${e.retry}
301
307
  `),e.data&&(e.data.type==="done"?o+=`data: [DONE]
302
308
  `:o+=`data: ${JSON.stringify(e.data)}
303
309
  `),o+=`
304
- `,t.enqueue(o)}})}}});var Zn,jr=w(()=>{"use strict";Zn=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var Hr=w(()=>{"use strict";Dr();Fr();jr()});var Qa=w(()=>{"use strict"});var vt,zr=w(()=>{"use strict";vt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let l=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
310
+ `,t.enqueue(o)}})}}});var qn,Br=P(()=>{"use strict";qn=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var Jr=P(()=>{"use strict";Hr();zr();Br()});var qa=P(()=>{"use strict"});var Tt,Wr=P(()=>{"use strict";Tt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let l=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
305
311
  `+(this.config.colors?`${this.colors.dim}`:""),i+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(i+=this.colors.reset)),i}toMarkdown(e,t=0){let o=" ".repeat(t);return Array.isArray(e)?e.map(r=>typeof r=="object"?`${o}-
306
312
  ${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
307
313
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
308
314
  ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
309
- `):`${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,Br=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:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(i),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(i=c,l===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as eo,opendir as yp,unlink as _p}from"node:fs/promises";import{join as Ya,resolve as Kr}from"node:path";import{tmpdir as bp}from"node:os";async function to(n,e){let t=Kr(n),o=qn.get(t),r,s=new Promise(a=>{r=a});qn.set(t,s);try{return await o,await e()}finally{r(),qn.get(t)===s&&qn.delete(t)}}function Xa(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Va(n,e){try{let t=await eo(n);return t.isDirectory()&&!t.isSymbolicLink()&&Xa(e,t)}catch{return!1}}function Sp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Za(n,e,t,o){let r=Kr(n);if(o?.aborted||Jr.has(r))return 0;Jr.add(r);let s=0;try{let a=await eo(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await yp(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of i){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let p=Ya(r,u.name);try{let d=await eo(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await to(p,async()=>{if(o?.aborted||!await Va(r,a))return!1;let g=await eo(p);return!g.isFile()||g.isSymbolicLink()||!Xa(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await _p(p),!0)})&&s++}catch{}}finally{++l%64===0&&(await Sp(),c=!o?.aborted&&await Va(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Jr.delete(r)}return s}function qa(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Za(n,Date.now()-o,i=>xp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function Cp(n,e){let t=Date.now()-kp;return Za(n,t,o=>{let r=Tp.exec(o);return r!==null&&Number(r[1])<t},e)}function Gr(n,e,t){let o=Wr.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,vp),a.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),a&&clearInterval(a)}},Wr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Wr.delete(n)))}}function ec(n=Ya(bp(),"claude-code-router")){return Gr(`legacy:${Kr(n)}`,e=>Cp(n,e),1e3)}var kp,vp,Tp,xp,Jr,qn,Wr,Qr=w(()=>{"use strict";kp=3600*1e3,vp=600*1e3,Tp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,xp=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,Jr=new Set,qn=new Map,Wr=new Map});import{lstat as Rp,mkdir as wp,open as Pp,rename as Ep,unlink as Ap}from"node:fs/promises";import{randomUUID as Op}from"node:crypto";import{sanitizeTempFileKey as Ip}from"@wengine-ai/claude-code-router-shared";import{basename as Mp,join as Vr,resolve as Lp}from"node:path";import{tmpdir as $p}from"node:os";var xt,Yr=w(()=>{"use strict";Qr();xt=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=Lp(Vr($p(),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=Gr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await wp(this.baseDir,{recursive:!0});let e=await Rp(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}-${Ip(e)}${r}${o}`;if(Mp(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Vr(this.baseDir,s)}async output(e,t={}){try{let o=typeof t.metadata?.statsKey=="string"&&t.metadata.statsKey?t.metadata.statsKey:t.metadata?.sessionId;if(!o)return!1;let r=t.metadata?.sessionId??o,s=JSON.stringify({...e,timestamp:Date.now(),sessionId:r},null,2),a=this.getFilePath(o);return await to(a,async()=>{await this.ensureDir();let i=Vr(this.baseDir,`.ccr-tmp-${process.pid}-${Op()}.tmp`);return to(i,async()=>{let l=!1;try{let c=await Pp(i,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await Ep(i,a),!0}finally{l&&await Ap(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return qa(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Xr,qe,tc=w(()=>{"use strict";zr();Br();Yr();Xr=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new vt(e.config);case"webhook":return new Tt(e.config);case"temp-file":return new xt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let l=this.handlers.get(i);if(!l){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await l.output(t,r)?s.success.push(i):s.failed.push(i)}catch(c){console.error(`[OutputManager] Handler ${i} failed:`,c),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},qe=new Xr});var Zr=w(()=>{"use strict";Qa();zr();Br();Yr();tc()});import Np from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Up}from"@wengine-ai/claude-code-router-shared";function no(){return{subdirectory:Up,extension:"json",includeTimestamp:!1,prefix:"session"}}function nc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Dp);return Math.round(n/o)}function Ct(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function oc(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await qe.outputToType(i,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,l)}}var St,qr,Dp,oo,rc=w(()=>{"use strict";Hr();Zr();je();St=new Map,qr=new Map,Dp=1,oo={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:Np(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)qe.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:no()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&qe.registerHandlers(a)}t.outputOptions&&qe.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,c=a.model,u=`${l}:${c}`;if(qr.has(u))return qr.get(u);let p=i.getTokenizerConfigForModel(l,c);if(!p)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let d=await i.getTokenizer(p,l);return qr.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=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,l)=>{let c=a.requestStartTime;if(!c)return;let u=a.id||Date.now().toString(),p=a.usageSessionId||u,d=a.sessionId;if(!d)try{d=he(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(l instanceof ReadableStream){St.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=l.tee(),_=async()=>{let k=null,v=async x=>{let T=St.get(u);if(!T)return;let P=T.firstTokenTime?T.firstTokenTime-T.startTime:0,R=(x?T.lastTokenTime:performance.now())-T.startTime;T.tokensPerSecond=nc(T.tokenCount,R,P),await oc(T,o,t.outputOptions,x).catch(A=>{n.log?.warn(`Failed to output streaming stats: ${A.message}`)})};try{let T=b.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();for(k=setInterval(async()=>{St.get(u)&&await v(!1)},1e3);;){let{done:P,value:E}=await T.read();if(P)break;let R=E,A=St.get(u);if(!A)continue;let D=performance.now(),C=R.event||R.data?.type,O=R.event==="content_block_start"||R.event==="content_block_delta"||R.event==="text_block"||R.event==="content_block"||C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta";!A.firstTokenTime&&O&&(A.firstTokenTime=D,A.timeToFirstToken=Math.round(D-A.startTime));let S="";if(R.event==="content_block_delta"&&R.data?.delta){let I=R.data.delta.type;I==="text_delta"?S=R.data.delta.text||"":I==="input_json_delta"?S=R.data.delta.partial_json||"":I==="thinking_delta"&&(S=R.data.delta.thinking||"")}if((C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta")&&(S=typeof R.data?.delta=="string"?R.data.delta:""),S){let I=f&&f.encodeText?f.encodeText(S).length:Ct(S);A.tokenCount+=I,A.lastTokenTime=D}(R.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await v(!0),St.delete(u))}}catch(x){k&&clearInterval(k),x.name!=="AbortError"&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${x.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let g=performance.now(),h=0,m=!1;if(l&&typeof l=="string")try{let y=JSON.parse(l);if(typeof y.usage?.output_tokens=="number")h=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?h=b.reduce((_,k)=>{if(k.type==="text"){let v=k.text||"";return _+(f.encodeText?f.encodeText(v).length:Ct(v))}return _},0):typeof b=="string"&&(h=f.encodeText?f.encodeText(b).length:Ct(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";h=Ct(_)}}}catch{}if(m){let y=g-c,b={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:g,tokenCount:h,tokensPerSecond:nc(h,y),stream:!1};await oc(b,o,t.outputOptions,!0)}return l})})}});var es=w(()=>{"use strict";Ka();Ga();rc();Zr()});import ne from"node:fs/promises";import sc from"json5";import Oe from"node:path";import{CONFIG_FILE as oe,HOME_DIR as ro,PLUGINS_DIR as Fp}from"@wengine-ai/claude-code-router-shared";function ic(){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 ts,Rt,so,wt,X,io,ue,jp,ns,Pt=w(()=>{"use strict";ts=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(ts);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=ts(o);return e}return n},Rt=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},so=async()=>{await Rt(ro),await Rt(Fp),await Rt(Oe.join(ro,"logs"))},wt=async()=>{let n=await ne.readFile(oe,"utf-8");return sc.parse(n)},X=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=sc.parse(n);return ts(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 so();let e=await io();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await ue(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)}};io=async()=>{ic();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=Oe.dirname(oe),o=Oe.basename(oe),s=(await ne.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=Oe.join(t,s[a]);await ne.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},ue=async n=>{ic(),await Rt(ro),await jp();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},jp=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=Oe.join(ro,"config-history");await Rt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Oe.join(e,`config-${t}.json`);await ne.copyFile(oe,o);try{let s=(await ne.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ne.unlink(Oe.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},ns=async()=>{let n=await X();return Object.assign(process.env,n),n}});function ao(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(os(r,s))}return}if(Array.isArray(n)){for(let o of n)ao(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))ao(o,e,t)}}function ac(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let i of a)i&&o.add(os(s,i))}return ao(n?.Router,t,o),ao(n?.fallback,t,o),o}function Et(n,e){try{let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=ac(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(os(a,i))||(t.recover(a,i),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function co(n,e){try{if(!n)return 0;let t=H();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 Hp,os,At=w(()=>{"use strict";re();Hp="\0",os=(n,e)=>`${n}${Hp}${e}`});function zp(n){return/\[1m\]/i.test(n)?1e6:2e5}function Bp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Jp(n,e=n){let t=zp(n),o=Bp(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 Wp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function rs(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Jp(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 a=Wp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var ss=w(()=>{"use strict"});function Kp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var lo,is=w(()=>{"use strict";lo=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Kp(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(i)?i[0]:i||"";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!==a){t.log.warn({url:e.url,gotPrefix:c.slice(0,10),gotSuffix:c.slice(-6),gotLen:c.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var yc={};To(yc,{append:()=>$t,clear:()=>us,close:()=>gf,getOldestRecordTimestamp:()=>hf,query:()=>ls,querySummary:()=>Nt,readTokenSpeedStats:()=>ds});import{existsSync as uc,mkdirSync as Gp,readFileSync as dc}from"fs";import{join as fo}from"path";import{tmpdir as Qp}from"os";import{openSqliteDatabase as Vp}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Yp,sanitizeTempFileKey as Xp,TOKEN_SPEED_TEMP_SUBDIRECTORY as Zp}from"@wengine-ai/claude-code-router-shared";function of(){uc(po)||Gp(po,{recursive:!0})}function Lt(){if(ve)return ve;of();let n=Vp(qp),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&&(rf(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")),t<3&&(e.exec("ALTER TABLE usage_records ADD COLUMN usage_estimated INTEGER NOT NULL DEFAULT 0"),e.pragma("user_version = 3")),af(e),mc(e,!0),cs=e.prepare(`
315
+ `):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var St,Kr=P(()=>{"use strict";St=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(i),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(i=c,l===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as to,opendir as Pp,unlink as Ep}from"node:fs/promises";import{join as tc,resolve as Vr}from"node:path";import{tmpdir as Ap}from"node:os";async function no(n,e){let t=Vr(n),o=eo.get(t),r,s=new Promise(a=>{r=a});eo.set(t,s);try{return await o,await e()}finally{r(),eo.get(t)===s&&eo.delete(t)}}function nc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function ec(n,e){try{let t=await to(n);return t.isDirectory()&&!t.isSymbolicLink()&&nc(e,t)}catch{return!1}}function $p(){return new Promise(n=>{setTimeout(n,10).unref()})}async function oc(n,e,t,o){let r=Vr(n);if(o?.aborted||Gr.has(r))return 0;Gr.add(r);let s=0;try{let a=await to(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await Pp(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of i){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let p=tc(r,u.name);try{let d=await to(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await no(p,async()=>{if(o?.aborted||!await ec(r,a))return!1;let h=await to(p);return!h.isFile()||h.isSymbolicLink()||!nc(d,h)||h.mtimeMs!==d.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await Ep(p),!0)})&&s++}catch{}}finally{++l%64===0&&(await $p(),c=!o?.aborted&&await ec(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Gr.delete(r)}return s}function rc(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return oc(n,Date.now()-o,i=>Lp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function Np(n,e){let t=Date.now()-Op;return oc(n,t,o=>{let r=Mp.exec(o);return r!==null&&Number(r[1])<t},e)}function Yr(n,e,t){let o=Qr.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,Ip),a.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),a&&clearInterval(a)}},Qr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Qr.delete(n)))}}function sc(n=tc(Ap(),"claude-code-router")){return Yr(`legacy:${Vr(n)}`,e=>Np(n,e),1e3)}var Op,Ip,Mp,Lp,Gr,eo,Qr,Xr=P(()=>{"use strict";Op=3600*1e3,Ip=600*1e3,Mp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,Lp=/^\.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$/,Gr=new Set,eo=new Map,Qr=new Map});import{lstat as Up,mkdir as Dp,open as Fp,rename as jp,unlink as Hp}from"node:fs/promises";import{randomUUID as zp}from"node:crypto";import{sanitizeTempFileKey as Bp}from"@wengine-ai/claude-code-router-shared";import{basename as Jp,join as Zr,resolve as Wp}from"node:path";import{tmpdir as Kp}from"node:os";var xt,qr=P(()=>{"use strict";Xr();xt=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=Wp(Zr(Kp(),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=Yr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await Dp(this.baseDir,{recursive:!0});let e=await Up(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}-${Bp(e)}${r}${o}`;if(Jp(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Zr(this.baseDir,s)}async output(e,t={}){try{let o=typeof t.metadata?.statsKey=="string"&&t.metadata.statsKey?t.metadata.statsKey:t.metadata?.sessionId;if(!o)return!1;let r=t.metadata?.sessionId??o,s=JSON.stringify({...e,timestamp:Date.now(),sessionId:r},null,2),a=this.getFilePath(o);return await no(a,async()=>{await this.ensureDir();let i=Zr(this.baseDir,`.ccr-tmp-${process.pid}-${zp()}.tmp`);return no(i,async()=>{let l=!1;try{let c=await Fp(i,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await jp(i,a),!0}finally{l&&await Hp(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return rc(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var es,Ze,ic=P(()=>{"use strict";Wr();Kr();qr();es=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 Tt(e.config);case"webhook":return new St(e.config);case"temp-file":return new xt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let l=this.handlers.get(i);if(!l){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await l.output(t,r)?s.success.push(i):s.failed.push(i)}catch(c){console.error(`[OutputManager] Handler ${i} failed:`,c),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},Ze=new es});var ts=P(()=>{"use strict";qa();Wr();Kr();qr();ic()});import Gp from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Qp}from"@wengine-ai/claude-code-router-shared";function oo(){return{subdirectory:Qp,extension:"json",includeTimestamp:!1,prefix:"session"}}function ac(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Vp);return Math.round(n/o)}function Rt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function cc(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await Ze.outputToType(i,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,l)}}var Ct,ns,Vp,ro,lc=P(()=>{"use strict";Jr();ts();Fe();Ct=new Map,ns=new Map,Vp=1,ro={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:Gp(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)Ze.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:oo()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&Ze.registerHandlers(a)}t.outputOptions&&Ze.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,c=a.model,u=`${l}:${c}`;if(ns.has(u))return ns.get(u);let p=i.getTokenizerConfigForModel(l,c);if(!p)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let d=await i.getTokenizer(p,l);return ns.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=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,l)=>{let c=a.requestStartTime;if(!c)return;let u=a.id||Date.now().toString(),p=a.usageSessionId||u,d=a.sessionId;if(!d)try{d=he(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(l instanceof ReadableStream){Ct.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=l.tee(),_=async()=>{let k=null,v=async S=>{let T=Ct.get(u);if(!T)return;let w=T.firstTokenTime?T.firstTokenTime-T.startTime:0,R=(S?T.lastTokenTime:performance.now())-T.startTime;T.tokensPerSecond=ac(T.tokenCount,R,w),await cc(T,o,t.outputOptions,S).catch(A=>{n.log?.warn(`Failed to output streaming stats: ${A.message}`)})};try{let T=b.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();for(k=setInterval(async()=>{Ct.get(u)&&await v(!1)},1e3);;){let{done:w,value:E}=await T.read();if(w)break;let R=E,A=Ct.get(u);if(!A)continue;let D=performance.now(),C=R.event||R.data?.type,O=R.event==="content_block_start"||R.event==="content_block_delta"||R.event==="text_block"||R.event==="content_block"||C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta";!A.firstTokenTime&&O&&(A.firstTokenTime=D,A.timeToFirstToken=Math.round(D-A.startTime));let x="";if(R.event==="content_block_delta"&&R.data?.delta){let I=R.data.delta.type;I==="text_delta"?x=R.data.delta.text||"":I==="input_json_delta"?x=R.data.delta.partial_json||"":I==="thinking_delta"&&(x=R.data.delta.thinking||"")}if((C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta")&&(x=typeof R.data?.delta=="string"?R.data.delta:""),x){let I=f&&f.encodeText?f.encodeText(x).length:Rt(x);A.tokenCount+=I,A.lastTokenTime=D}(R.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await v(!0),Ct.delete(u))}}catch(S){k&&clearInterval(k),S.name!=="AbortError"&&S.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${S.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let h=performance.now(),g=0,m=!1;if(l&&typeof l=="string")try{let y=JSON.parse(l);if(typeof y.usage?.output_tokens=="number")g=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?g=b.reduce((_,k)=>{if(k.type==="text"){let v=k.text||"";return _+(f.encodeText?f.encodeText(v).length:Rt(v))}return _},0):typeof b=="string"&&(g=f.encodeText?f.encodeText(b).length:Rt(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";g=Rt(_)}}}catch{}if(m){let y=h-c,b={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:h,tokenCount:g,tokensPerSecond:ac(g,y),stream:!1};await cc(b,o,t.outputOptions,!0)}return l})})}});var os=P(()=>{"use strict";Xa();Za();lc();ts()});import oe from"node:fs/promises";import uc from"json5";import Oe from"node:path";import{CONFIG_FILE as se,HOME_DIR as so,PLUGINS_DIR as Yp}from"@wengine-ai/claude-code-router-shared";function dc(){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 rs,wt,io,Pt,X,ao,de,Xp,ss,Et=P(()=>{"use strict";rs=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(rs);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=rs(o);return e}return n},wt=async n=>{try{await oe.access(n)}catch{await oe.mkdir(n,{recursive:!0})}},io=async()=>{await wt(so),await wt(Yp),await wt(Oe.join(so,"logs"))},Pt=async()=>{let n=await oe.readFile(se,"utf-8");return uc.parse(n)},X=async()=>{try{let n=await oe.readFile(se,"utf-8");try{let e=uc.parse(n);return rs(e)}catch(e){console.error(`Failed to parse config file at ${se}`),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 io();let e=await ao();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await de(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 ${se}`),console.error("Error details:",n.message),process.exit(1)}};ao=async()=>{dc();try{if(await oe.access(se).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${se}.${n}.bak`;await oe.copyFile(se,e);try{let t=Oe.dirname(se),o=Oe.basename(se),s=(await oe.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=Oe.join(t,s[a]);await oe.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},de=async n=>{dc(),await wt(so),await Xp();let e=`${JSON.stringify(n,null,2)}`;await oe.writeFile(se,e)},Xp=async()=>{if(!await oe.access(se).then(()=>!0).catch(()=>!1))return;let e=Oe.join(so,"config-history");await wt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Oe.join(e,`config-${t}.json`);await oe.copyFile(se,o);try{let s=(await oe.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await oe.unlink(Oe.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},ss=async()=>{let n=await X();return Object.assign(process.env,n),n}});function co(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(is(r,s))}return}if(Array.isArray(n)){for(let o of n)co(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))co(o,e,t)}}function pc(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let i of a)i&&o.add(is(s,i))}return co(n?.Router,t,o),co(n?.fallback,t,o),o}function At(n,e){try{let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=pc(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(is(a,i))||(t.recover(a,i),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function lo(n,e){try{if(!n)return 0;let t=H();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 Zp,is,Ot=P(()=>{"use strict";ie();Zp="\0",is=(n,e)=>`${n}${Zp}${e}`});function qp(n){return/\[1m\]/i.test(n)?1e6:2e5}function ef(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function tf(n,e=n){let t=qp(n),o=ef(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 nf(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function as(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,tf(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 a=nf(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var cs=P(()=>{"use strict"});function of(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var uo,ls=P(()=>{"use strict";uo=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||of(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(i)?i[0]:i||"";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!==a){t.log.warn({url:e.url,gotPrefix:c.slice(0,10),gotSuffix:c.slice(-6),gotLen:c.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var Tc={};So(Tc,{append:()=>Nt,clear:()=>fs,close:()=>Rf,getOldestRecordTimestamp:()=>wf,query:()=>ps,querySummary:()=>Ut,readTokenSpeedStats:()=>ms});import{existsSync as gc,mkdirSync as rf,readFileSync as hc}from"fs";import{join as mo}from"path";import{tmpdir as sf}from"os";import{openSqliteDatabase as af}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as cf,sanitizeTempFileKey as lf,TOKEN_SPEED_TEMP_SUBDIRECTORY as uf}from"@wengine-ai/claude-code-router-shared";function gf(){gc(fo)||rf(fo,{recursive:!0})}function $t(){if(ve)return ve;gf();let n=af(df),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&&(hf(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")),t<3&&(e.exec("ALTER TABLE usage_records ADD COLUMN usage_estimated INTEGER NOT NULL DEFAULT 0"),e.pragma("user_version = 3")),_f(e),bc(e,!0),ds=e.prepare(`
310
316
  INSERT INTO usage_records (
311
317
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
312
318
  scenario_type, client_type,
@@ -320,7 +326,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
320
326
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
321
327
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
322
328
  )
323
- `),ve=e,ve}function rf(n){n.exec(`
329
+ `),ve=e,ve}function hf(n){n.exec(`
324
330
  CREATE TABLE IF NOT EXISTS usage_records (
325
331
  id TEXT PRIMARY KEY,
326
332
  timestamp TEXT NOT NULL,
@@ -357,12 +363,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
357
363
  CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
358
364
  CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
359
365
  CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
360
- `)}function sf(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
366
+ `)}function yf(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function It(n,e,t){n.prepare(`
361
367
  INSERT INTO usage_meta (key, value)
362
368
  VALUES (?, ?)
363
369
  ON CONFLICT(key) DO UPDATE SET value = excluded.value
364
- `).run(e,t)}function af(n){if(sf(n,cc)||!uc(as))return;let e=lf(n,"INSERT OR IGNORE"),t=dc(as,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
365
- `)){let l=i.trim();if(l)try{let c=JSON.parse(l);if(!cf(c)){r++;continue}e.run(fc(mo(c))).changes>0?o++:s++}catch{r++}}Ot(n,cc,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",as),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 cf(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 lf(n,e="INSERT"){return n.prepare(`
370
+ `).run(e,t)}function _f(n){if(yf(n,fc)||!gc(us))return;let e=kf(n,"INSERT OR IGNORE"),t=hc(us,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
371
+ `)){let l=i.trim();if(l)try{let c=JSON.parse(l);if(!bf(c)){r++;continue}e.run(_c(go(c))).changes>0?o++:s++}catch{r++}}It(n,fc,new Date().toISOString()),It(n,"legacy_usage_jsonl_migrated_path",us),It(n,"legacy_usage_jsonl_imported_count",String(o)),It(n,"legacy_usage_jsonl_skipped_count",String(r)),It(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function bf(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 kf(n,e="INSERT"){return n.prepare(`
366
372
  ${e} INTO usage_records (
367
373
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
368
374
  scenario_type, client_type,
@@ -376,11 +382,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
376
382
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
377
383
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
378
384
  )
379
- `)}function uf(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,ef);return Math.round(n/r)}function mo(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:uf(e,o,r)}}function ke(n){return typeof n=="string"?n:n==null?"":String(n)}function uo(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 pc(n){return n==="success"?"success":"error"}function fc(n){let e=mo(n);return{id:ke(e.id),timestamp:ke(e.timestamp),session_id:ke(e.sessionId),provider:ke(e.provider),original_model:ke(e.originalModel),model:ke(e.model),upstream_model:uo(e.upstreamModel)??null,model_family:ke(e.modelFamily),scenario_type:ke(e.scenarioType),client_type:uo(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?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:pc(e.status),error_message:uo(e.errorMessage)??null,response_body:uo(e.responseBody)??null}}function df(n){return mo({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,...n.usage_estimated===1?{usageEstimated:!0}:{},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:pc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function pf(){return new Date(Date.now()-tf*24*60*60*1e3).toISOString()}function mc(n,e=!1){let t=Date.now();!e&&t-lc<nf||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(pf()),lc=t)}function gc(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 et(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
380
- SELECT ${t} AS key, ${ff}
385
+ `)}function vf(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,pf);return Math.round(n/r)}function go(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Lt(n.ttft):null;return{...n,ttft:r,tokensPerSecond:vf(e,o,r)}}function ke(n){return typeof n=="string"?n:n==null?"":String(n)}function po(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function Mt(n){let e=Number(n);return Number.isFinite(e)?e:0}function yc(n){return n==="success"?"success":"error"}function _c(n){let e=go(n);return{id:ke(e.id),timestamp:ke(e.timestamp),session_id:ke(e.sessionId),provider:ke(e.provider),original_model:ke(e.originalModel),model:ke(e.model),upstream_model:po(e.upstreamModel)??null,model_family:ke(e.modelFamily),scenario_type:ke(e.scenarioType),client_type:po(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(Mt(e.inputTokens)),output_tokens:Math.trunc(Mt(e.outputTokens)),cache_read_input_tokens:Math.trunc(Mt(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(Mt(e.cacheCreationInputTokens)),ttft:Lt(e.ttft),tokens_per_second:Lt(e.tokensPerSecond),duration_ms:Math.trunc(Mt(e.durationMs)),status:yc(e.status),error_message:po(e.errorMessage)??null,response_body:po(e.responseBody)??null}}function Tf(n){return go({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,...n.usage_estimated===1?{usageEstimated:!0}:{},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:yc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function Sf(){return new Date(Date.now()-ff*24*60*60*1e3).toISOString()}function bc(n,e=!1){let t=Date.now();!e&&t-mc<mf||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(Sf()),mc=t)}function kc(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 qe(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
386
+ SELECT ${t} AS key, ${xf}
381
387
  FROM usage_records ${r}
382
388
  GROUP BY key
383
- `).all(...e.params),a={};for(let i of s)i.key!=null&&(a[String(i.key)]={count:i.count,inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadInputTokens:i.cacheReadInputTokens,cacheCreationInputTokens:i.cacheCreationInputTokens});return a}function hc(n,e){let t=gc(e),o=n.prepare(`
389
+ `).all(...e.params),a={};for(let i of s)i.key!=null&&(a[String(i.key)]={count:i.count,inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadInputTokens:i.cacheReadInputTokens,cacheCreationInputTokens:i.cacheCreationInputTokens});return a}function vc(n,e){let t=kc(e),o=n.prepare(`
384
390
  SELECT
385
391
  COUNT(*) AS totalRequests,
386
392
  COALESCE(SUM(usage_estimated), 0) AS estimatedCount,
@@ -392,14 +398,14 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
392
398
  AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
393
399
  AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
394
400
  FROM usage_records ${t.sql}
395
- `).get(...t.params);return{estimatedCount:o.estimatedCount,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:et(n,t,"model"),byProvider:et(n,t,"provider"),byScenario:et(n,t,"scenario_type"),byFamily:et(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:et(n,t,"date(timestamp, 'localtime')"),byClient:et(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function $t(n){let e=Lt(),t=mo(n);cs.run(fc(t)),mc(e)}function ls(n){let e=Lt(),t=gc(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),mf):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),l=hc(e,n);return{records:i.map(df),summary:l,total:a.count,page:o,pageSize:r}}function Nt(n,e,t){let o=Lt();return hc(o,{startTime:n,endTime:e,status:t})}function us(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 gf(){ve&&(ve.pragma("wal_checkpoint(TRUNCATE)"),ve.close(),ve=null,cs=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 ds(n){let e=fo(Qp(),Zp,`session-${Xp(n)}.json`);try{let t=JSON.parse(dc(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function hf(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 po,qp,as,ef,tf,nf,cc,ve,cs,lc,ff,mf,Ut=w(()=>{"use strict";po=fo(Yp,"data"),qp=fo(po,"usage.sqlite"),as=fo(po,"usage.jsonl"),ef=1,tf=180,nf=3600*1e3,cc="legacy_usage_jsonl_migrated_at",ve=null,cs=null,lc=0;ff=`
401
+ `).get(...t.params);return{estimatedCount:o.estimatedCount,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:qe(n,t,"model"),byProvider:qe(n,t,"provider"),byScenario:qe(n,t,"scenario_type"),byFamily:qe(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:qe(n,t,"date(timestamp, 'localtime')"),byClient:qe(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function Nt(n){let e=$t(),t=go(n);ds.run(_c(t)),bc(e)}function ps(n){let e=$t(),t=kc(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),Cf):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),l=vc(e,n);return{records:i.map(Tf),summary:l,total:a.count,page:o,pageSize:r}}function Ut(n,e,t){let o=$t();return vc(o,{startTime:n,endTime:e,status:t})}function fs(n){let e=$t();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Rf(){ve&&(ve.pragma("wal_checkpoint(TRUNCATE)"),ve.close(),ve=null,ds=null)}function Lt(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function ms(n){let e=mo(sf(),uf,`session-${lf(n)}.json`);try{let t=JSON.parse(hc(e,"utf-8"));return{ttft:Lt(t.timeToFirstToken),tokensPerSecond:Lt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function wf(n,e,t){return $t().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var fo,df,us,pf,ff,mf,fc,ve,ds,mc,xf,Cf,Dt=P(()=>{"use strict";fo=mo(cf,"data"),df=mo(fo,"usage.sqlite"),us=mo(fo,"usage.jsonl"),pf=1,ff=180,mf=3600*1e3,fc="legacy_usage_jsonl_migrated_at",ve=null,ds=null,mc=0;xf=`
396
402
  COUNT(*) AS count,
397
403
  COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
398
404
  COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
399
405
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
400
406
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
401
- `;mf=200});import{existsSync as yf}from"fs";import{homedir as _f}from"os";import{join as bf}from"path";import{writeFile as kf}from"fs/promises";async function _c(){let n=_f(),e=bf(n,".claude.json");if(!yf(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 kf(e,JSON.stringify(o,null,2))}}var bc=w(()=>{"use strict"});import{existsSync as vf,readdirSync as Tf,statSync as xf,unlinkSync as Sf}from"fs";import{join as kc}from"path";import{HOME_DIR as Cf}from"@wengine-ai/claude-code-router-shared";function Tc(n=kc(Cf,"logs")){try{if(!vf(n))return;let e=Date.now()-wf;for(let t of Tf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=kc(n,t),r=xf(o);r.isFile()&&r.mtime.getTime()<e&&Sf(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function xc(){vc||(vc=!0,Tc(),setInterval(Tc,Pf).unref())}var Rf,wf,Pf,vc,Sc=w(()=>{"use strict";Rf=7,wf=Rf*24*60*60*1e3,Pf=1440*60*1e3,vc=!1});async function Cc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":kt.registerPlugin(oo,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:no()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var Rc=w(()=>{"use strict";es()});function tt(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),Nr();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=>de(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var go=w(()=>{"use strict";At();Xn();q()});import{constants as ps,lstatSync as nt,realpathSync as Dt,openSync as Ef,closeSync as Af,fstatSync as Of,readFileSync as wc}from"node:fs";import{dirname as rk,join as ot,sep as If}from"node:path";import{pathToFileURL as Mf}from"node:url";function Ec(n){try{let e=JSON.parse(wc(ot(Lf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function ms(n,e){if(!Pc(e))return null;try{let t=Dt(n),o=ot(t,"plugins"),r=ot(o,e);return nt(o).isSymbolicLink()||!nt(o).isDirectory()||nt(r).isSymbolicLink()||!nt(r).isDirectory()||Dt(o)!==o||Dt(r)!==r||!r.startsWith(o+If)?null:r}catch{return null}}function fs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=ms(n,e);if(!o)throw new Error("unsafe plugin directory");let r=ot(o,t),s=nt(r);if(s.isSymbolicLink()||!s.isFile()||Dt(r)!==r)throw new Error("unsafe plugin file");let a=Ef(r,ps.O_RDONLY|ps.O_NOFOLLOW|ps.O_NONBLOCK);try{let i=Of(a),l=nt(r);if(!i.isFile()||l.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==l.dev||i.ino!==l.ino||ms(n,e)!==o||Dt(r)!==r)throw new Error("plugin file changed while opening");return wc(a)}finally{Af(a)}}function $f(n){let e=n?.configService,t=e?Is(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Ms(t)}async function Ac(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Lo(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>wt(),writeConfig:i=>ue(i),reloadRuntime:async i=>tt(n.getServer(),i??await X(),t),getDirectDispatcher:So,getSubscriptionDispatcher:()=>$f(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Ec(e)){let l;try{if(!Pc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let c=ms(e,i.name);if(!c){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(fs(e,i.name,"plugin.json").toString("utf8"));if(!h||typeof h.name!="string"||typeof h.version!="string")throw new Error;u={name:h.name,version:h.version,coreApi:String(h.coreApi??"1"),description:h.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:h=>t.info(`[plugin:${u.name}] ${h}`),warn:h=>t.warn(`[plugin:${u.name}] ${h}`),error:h=>t.error(`[plugin:${u.name}] ${h}`)},r,c);l=p,fs(e,i.name,"plugin.js");let d=await import(Mf(ot(c,"plugin.js")).href),f=d?.activate??d?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(p.context);let g=p.cardPath?fs(e,i.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:i.name,error:c?.message??String(c)}),t.warn(`plugin ${i.name} failed to load: ${c?.message??String(c)}`)}}return s}function Oc(n,e=Lo()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Ec(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 Pc,Lf,gs=w(()=>{"use strict";Io();Qt();go();Pt();q();Pc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Lf=n=>ot(n,"plugins")});import{gt as Nf,valid as Ic}from"semver";import{existsSync as Mc,readFileSync as Uf}from"node:fs";import{join as hs}from"node:path";import{NPM_SPEC_PATTERN as Df,PLUGIN_NAME_PATTERN as Lc,PluginInstallError as Ff,installPluginFromNpm as jf,readPluginRecords as Hf}from"@wengine-ai/claude-code-router-shared";async function Bf(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 Jf(n,e={}){let t=(e.registryBase??zf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled($c.map(m=>Bf(t,m,o))),s=new Map,a=!1;for(let m of r)if(m.status==="fulfilled"){a=!0;for(let y of m.value){let b=y?.package,_=typeof b?.name=="string"?b.name:"";if(!_||!Df.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>$c.includes(x)))continue;let v=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:v,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=Hf(n),l=new Map(i.map(m=>[m.name,m])),c=m=>{let y=m.indexOf("@",m.startsWith("@")?1:0);return y>0?m.slice(0,y):m},u=new Map(i.filter(m=>typeof m.source=="string"&&m.source!=="").map(m=>[c(m.source),m])),p=m=>{if(!Lc.test(m))return null;try{let y=JSON.parse(Uf(hs(n,"plugins",m,"plugin.json"),"utf8"));return typeof y?.version=="string"?y.version:null}catch{return null}},d=[...s.values()].sort((m,y)=>m.name.localeCompare(y.name)).map(m=>{let y=l.get(m.name)??u.get(m.name),b=y!==void 0||Mc(hs(n,"plugins",m.name)),_=b?p(y?y.name:m.name):null;return{...m,installed:b,installedVersion:_,...b&&_!==null&&Ic(_)&&Ic(m.version)&&Nf(m.version,_)?{updateAvailable:!0}:{}}}),f=new Set(d.map(m=>m.name)),g=new Set,h=new Map;for(let[m,y]of u)g.add(y.name),!f.has(m)&&h.set(m,y.name);for(let m of i)f.has(m.name)||g.has(m.name)||h.set(m.name,m.name);for(let[m,y]of h){if(!Lc.test(y)||!Mc(hs(n,"plugins",y)))continue;let b=p(y);b!==null&&d.push({name:m,description:"",version:b,installed:!0,installedVersion:b,localOnly:!0})}return d.sort((m,y)=>m.name.localeCompare(y.name)),{ok:!0,plugins:d}}function Wf(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 Nc(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),l=n.headers?.host;if(typeof l=="string"&&!i.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(!i.has(u))return!1}return!0}function Uc(n,e){let t=e.configuredPort??3456,o=(r,s,a)=>r.status(s).send({ok:!1,error:a});n.get("/api/plugins/catalog",async(r,s)=>{if(!Nc(r,n,t))return o(s,403,"local_only");try{return await Jf(e.configDir,{registryBase:e.catalogRegistryBase??e.registry,timeoutMs:e.catalogTimeoutMs})}catch(a){return n.log?.warn?.(`plugin catalog failed: ${a?.code??a?.name??"error"}`),{ok:!0,plugins:[],warning:"registry_unavailable"}}}),n.post("/api/plugins/install",async(r,s)=>{if(!Nc(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,l=a.force===!0;try{let c=await jf({spec:i,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 Ff){let u=Wf(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 $c,zf,Dc=w(()=>{"use strict";$c=["ccr-provider-plugin","claude-code-router-plugin"],zf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Kf}from"@wengine-ai/claude-code-router-shared";import{join as ae,isAbsolute as Gf,normalize as Qf,dirname as Vf}from"path";import{fileURLToPath as Yf}from"url";import Xf from"@fastify/static";import{readdirSync as Fc,statSync as Zf,readFileSync as jc,writeFileSync as qf,existsSync as fe,unlinkSync as Hc,rmSync as em}from"fs";import{homedir as ys}from"os";import{getPresetDir as ho,readManifestFromDir as _s,manifestToPresetFile as zc,saveManifest as Bc,isPresetInstalled as Jc,extractPreset as tm,HOME_DIR as bs,loadConfigFromManifest as nm,downloadPresetToTemp as om,findMarketPresetByName as rm,getMarketPresets as sm,applyClientSelection as im,disableClient as am,enableClient as cm,isClientId as lm,listClientStatuses as Wc,restoreClient as um,listProjectConfigs as dm,readProjectConfigById as ks,readProjectConfig as pm,writeProjectConfig as Kc,deleteProjectConfig as fm,getClaudeProjectId as mm,getProjectConfigPath as gm,refreshCcrProjectTakeover as hm,refreshPiProjectTakeover as ym,refreshProjectTakeovers as _m,syncGlobalProjectTakeovers as vs,getProjectTakeoverClients as Ts,setProjectTakeover as xs,isProjectTakeoverClient as bm}from"@wengine-ai/claude-code-router-shared";import km from"@fastify/multipart";import vm from"adm-zip";function Gc(n){let e=H();return rs(n,(t,o)=>e.isAvailable(t,o))}function Qc(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function 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),a=[],i=new Set;for(let l of n||[])l&&l.name&&i.add(l.name);for(let l of Object.keys(r.byProvider||{}))i.add(l);for(let l of Object.keys(s.byProvider||{}))i.add(l);for(let l of i){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),f,g,h=(n||[]).find(m=>m&&m.name===l);h&&h.quota&&(f=h.quota.limit5h,g=h.quota.limit7d),a.push({provider:l,used5h:p,used7d:d,limit5h:f,limit7d:g})}return a}async function Vc(n,e){let t=n.app;at(),ut(),t.register(km,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Gc(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,l)=>{let c=decodeURIComponent(i.params.modelId),u=Gc(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(i,l)=>{let{messages:c,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[h,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${h}, model: ${m}`);let y=f.getTokenizerConfigForModel(h,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${h},${m}, using default tiktoken`);let b=await f.countTokens({messages:c,system:p,tools:u},y,h);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(h){i.log?.error(`Error using configured tokenizer: ${h.message}`),i.log?.error(h.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:ln(c,p,u)}}),t.get("/api/config",async(i,l)=>await wt()),t.get("/api/transformers",async(i,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(i,l)=>{let c=i.body,u=Os(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 p=await io();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}Kf(c,d),n.pluginRegistry.applyConfigProtectors(c,d),await ue(c);let f;try{f=await vs(c),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"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}`)}return tt(n,c,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,l)=>{try{let c=await X();return{clients:Wc(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(i,l)=>{try{let c=i.body,u=Array.isArray(c?.enabled)?c.enabled:[],p=await X(),d=im(p,u);await ue(d.config);let f=await vs(d.config),g=Qc(t,f,"clients/apply");return{...d,success:d.success&&g,projectTakeoverSync:f}}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(i,l,c){try{let{id:u}=i.params;if(!lm(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=c==="enable"?cm(p,u):c==="restore"?um(p,u):am(p,u);await ue(p);let f=await vs(p),g=Qc(t,f,`clients/${u}/${c}`);return{success:d.success&&g,result:d,results:[d],clients:Wc(p),config:p,projectTakeoverSync:f}}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(i,l)=>o(i,l,"enable")),t.post("/api/clients/:id/disable",async(i,l)=>o(i,l,"disable")),t.post("/api/clients/:id/restore",async(i,l)=>o(i,l,"restore")),t.get("/api/projects",async(i,l)=>{try{let c=await dm();return{projects:await Promise.all(c.map(async p=>{let d=await Ts(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(i,l)=>{try{let{path:c}=i.body||{};if(!c||typeof c!="string"||!Gf(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=Qf(c).replace(/[\\/]+$/,"")||c;if(await pm(u)){l.status(409).send({error:"Project is already configured"});return}await Kc(u,{Router:{}});try{let f=await X();await xs(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await Ts(u);return{id:mm(u),path:u,configPath:gm(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(i,l)=>{try{let{id:c}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){l.status(400).send({error:"Router must be an object"});return}let p=await ks(c);if(!p){l.status(404).send({error:"Project config not found"});return}await Kc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await _m(p.path,d):(await hm(p.path,d,u),await ym(p.path,d,u));let f=await Ts(p.path);return{id:c,path:p.path,configPath:p.configPath,Router:u,ccrTakeoverClients:f,ccrTakeover:f.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(i,l)=>{try{let{id:c}=i.params,u=i.body||{},p;if(Array.isArray(u.clients))p=u.clients.filter(bm);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 ks(c);if(!d){l.status(404).send({error:"Project config not found"});return}let f=await X(),g=await xs(d.path,p,f);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(i,l)=>{try{let{id:c}=i.params,u=await ks(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let p=await X();await xs(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await fm(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:Vf(Yf(import.meta.url)),s=fe(ae(r,"index.html"))?r:fe(ae(r,"..","index.html"))?ae(r,".."):ae(r,"..","dist");t.register(Xf,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(i,l)=>l.redirect("/ui/")),t.get("/api/logs/files",async(i,l)=>{try{let c=ae(ys(),".claude-code-router","logs"),u=[];if(fe(c)){let p=Fc(c);for(let d of p)if(d.endsWith(".log")){let f=ae(c,d),g=Zf(f);u.push({name:d,path:f,size:g.size,lastModified:g.mtime.toISOString()})}u.sort((d,f)=>new Date(f.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(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=ae(ys(),".claude-code-router","logs","app.log"),fe(u)?jc(u,"utf8").split(`
402
- `).filter(f=>f.trim()):[]}catch(c){console.error("Failed to get logs:",c),l.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=ae(ys(),".claude-code-router","logs","app.log"),fe(u)&&qf(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:Bt()})),t.put("/api/debug-log",async i=>{let{enabled:l}=i.body;return Po(l),{enabled:Bt()}}),t.get("/api/usage",async(i,l)=>{try{let c=i.query;return ls({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(i,l)=>{try{let c=i.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(i,l)=>{try{let c=i.query;return us(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(i,l)=>{try{let u=H().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,lastSuccessTime:f.lastSuccessTime??null,lastError:f.lastError,rateLimitUntil:f.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(i,l)=>{try{let{providerName:c}=i.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&&co(c,i.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(i,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(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let g=await u.probeProviderManually(f.name);return g.success&&co(f.name,i?.log),{provider:f.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(f=>f.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(i,l)=>{try{let u=(await X()).Providers||[],p=t._server?.pluginRegistry,d=t._server?.providerService;if(p&&d?.getProviders){let b=d.getProviders().filter(_=>_?.name&&_.enabled!==!1).map(_=>{let k=p.getManagedRuntimeFor(_);if(!(!k||typeof k.fetchQuota!="function"))return Vn(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,Ba).unref?.()});await Promise.race([Promise.all(b),_])}}let f=Tm(u),g=new Map(f.map(y=>[y.provider,y])),h=Jo();for(let y of f){let b=h.find(_=>_.provider===y.provider);b&&b.limit!=null&&!Zt(b.reset)&&(y.limit5h=b.limit,y.used5h=b.limit-(b.remaining??0),b.reset&&(y.reset5h=new Date(b.reset*1e3).toISOString()))}let m=tr();for(let y of m){let b=g.get(y.provider);b||(b={provider:y.provider,used5h:0,used7d:0},f.push(b),g.set(y.provider,b)),typeof y.totalBalance=="number"?(b.limit7d=y.totalBalance,b.type7d=y.currency?"balance":"rateLimit",y.currency&&(b.currency=y.currency),typeof y.usedBalance=="number"?b.used7d=y.usedBalance:typeof y.remainingBalance=="number"?b.used7d=Math.max(0,y.totalBalance-y.remainingBalance):(b.used7d=0,b.limit7d=y.totalBalance)):typeof y.usedBalance=="number"&&(b.used7d=y.usedBalance);let _=Zt(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=Zt(typeof y.resetTime7d=="string"?Date.parse(y.resetTime7d)/1e3:void 0);typeof y.usedDailyBalance=="number"&&!_&&(b.used5h=y.usedDailyBalance,b.type5h="rateLimit"),typeof y.limitDaily=="number"&&!_&&(b.limit5h=y.limitDaily,b.type5h="rateLimit"),typeof y.resetTime=="string"&&!_&&(y.limitDaily!==void 0?b.reset5h=y.resetTime:b.reset7d=y.resetTime),typeof y.resetTime7d=="string"&&!k&&(b.reset7d=y.resetTime7d)}return{quotas:f,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(i,l)=>{try{let c=ae(bs,"presets");if(!fe(c))return{presets:[]};let p=Fc(c,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let g=ae(c,f);try{let h=ae(g,"manifest.json"),m=jc(h,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:v,API_TIMEOUT_MS:x,PROXY_URL:T,PROXY_GLOBAL_ENABLED:P,LOG:E,LOG_LEVEL:R,StatusLine:A,NON_INTERACTIVE_MODE:D,...C}=y;d.push({id:f,name:C.name||f,version:C.version||"1.0.0",description:C.description,author:C.author,homepage:C.homepage,repository:C.repository,license:C.license,keywords:C.keywords,ccrVersion:C.ccrVersion,source:C.source,sourceType:C.sourceType,checksum:C.checksum,installed:!0})}catch(h){console.error(`Failed to read preset ${f}:`,h)}}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(i,l)=>{try{let{name:c}=i.params,u=ho(c);if(!fe(u)){l.status(404).send({error:"Preset not found"});return}let p=await _s(u);return{...zc(p),config:nm(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(i,l)=>{try{let{name:c}=i.params,{secrets:u}=i.body,p=ho(c);if(!fe(p)){l.status(404).send({error:"Preset not found"});return}let f={...await _s(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await Bc(c,f),{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(i,l)=>{try{let{name:c}=i.params,u=ho(c);if(!fe(u)){l.status(404).send({error:"Preset not found"});return}return em(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(i,l)=>{try{return{presets:await sm()}}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(i,l)=>{try{let{presetName:c}=i.body;if(!c){l.status(400).send({error:"Preset name is required"});return}let u=await rm(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,f]=p,g=u.name||c;if(await Jc(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 h=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await om(h),y=await a(m);if(await Jc(g)){Hc(m),l.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let b=ho(g);await tm(m,b);let _=await _s(b);return _.repository=u.repo,u.url&&(_.source=u.url),await Bc(g,_),Hc(m),{success:!0,presetName:g,preset:{...y.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 a(i){let l=new vm(i),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 zc(u)}return t.get("/api/plugins",async()=>({plugins:Oc(bs,n.pluginRegistry)})),Uc(t,{configDir:bs,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,l)=>{let{name:c,file:u}=i.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 Yc=w(()=>{"use strict";Pe();Se();Ce();Ir();Se();q();rt();re();At();go();gs();Dc();Pt();Ut();ss()});function xm(n,e){let t=n?.Router,{family:o}=mt(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function Xc(n){return n?.Router?.image}function Sm(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 Cm(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 Ss,yo,Cs,Zc,qc=w(()=>{"use strict";Pe();Ss=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}},yo=new Ss;Cs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=xm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Sm(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&gt(e.body.model)?!1:(Cm(e.body.messages),s&&!!Xc(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let l=yo.getImage(`${t.req.id}_Image#${i}`);l&&o.push({type:"image",source:l})});else{let i=yo.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(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(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:Xc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
407
+ `;Cf=200});import{existsSync as Pf}from"fs";import{homedir as Ef}from"os";import{join as Af}from"path";import{writeFile as Of}from"fs/promises";async function Sc(){let n=Ef(),e=Af(n,".claude.json");if(!Pf(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 Of(e,JSON.stringify(o,null,2))}}var xc=P(()=>{"use strict"});import{existsSync as If,readdirSync as Mf,statSync as Lf,unlinkSync as $f}from"fs";import{join as Cc}from"path";import{HOME_DIR as Nf}from"@wengine-ai/claude-code-router-shared";function wc(n=Cc(Nf,"logs")){try{if(!If(n))return;let e=Date.now()-Df;for(let t of Mf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=Cc(n,t),r=Lf(o);r.isFile()&&r.mtime.getTime()<e&&$f(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function Pc(){Rc||(Rc=!0,wc(),setInterval(wc,Ff).unref())}var Uf,Df,Ff,Rc,Ec=P(()=>{"use strict";Uf=7,Df=Uf*24*60*60*1e3,Ff=1440*60*1e3,Rc=!1});async function Ac(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":vt.registerPlugin(ro,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:oo()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await vt.enablePlugins(n)}var Oc=P(()=>{"use strict";os()});function et(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()),At(e,t),Fr();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=kt(()=>n.providerService.getProviders(),o,r=>pe(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var ho=P(()=>{"use strict";Ot();Zn();ee()});import{constants as gs,lstatSync as tt,realpathSync as Ft,openSync as jf,closeSync as Hf,fstatSync as zf,readFileSync as Ic}from"node:fs";import{dirname as hk,join as nt,sep as Bf}from"node:path";import{pathToFileURL as Jf}from"node:url";function Lc(n){try{let e=JSON.parse(Ic(nt(Wf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function ys(n,e){if(!Mc(e))return null;try{let t=Ft(n),o=nt(t,"plugins"),r=nt(o,e);return tt(o).isSymbolicLink()||!tt(o).isDirectory()||tt(r).isSymbolicLink()||!tt(r).isDirectory()||Ft(o)!==o||Ft(r)!==r||!r.startsWith(o+Bf)?null:r}catch{return null}}function hs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=ys(n,e);if(!o)throw new Error("unsafe plugin directory");let r=nt(o,t),s=tt(r);if(s.isSymbolicLink()||!s.isFile()||Ft(r)!==r)throw new Error("unsafe plugin file");let a=jf(r,gs.O_RDONLY|gs.O_NOFOLLOW|gs.O_NONBLOCK);try{let i=zf(a),l=tt(r);if(!i.isFile()||l.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==l.dev||i.ino!==l.ino||ys(n,e)!==o||Ft(r)!==r)throw new Error("plugin file changed while opening");return Ic(a)}finally{Hf(a)}}function Kf(n){let e=n?.configService,t=e?$s(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Ns(t)}async function $c(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??No(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>Pt(),writeConfig:i=>de(i),reloadRuntime:async i=>et(n.getServer(),i??await X(),t),getDirectDispatcher:Co,getSubscriptionDispatcher:()=>Kf(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Lc(e)){let l;try{if(!Mc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let c=ys(e,i.name);if(!c){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let g=JSON.parse(hs(e,i.name,"plugin.json").toString("utf8"));if(!g||typeof g.name!="string"||typeof g.version!="string")throw new Error;u={name:g.name,version:g.version,coreApi:String(g.coreApi??"1"),description:g.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:g=>t.info(`[plugin:${u.name}] ${g}`),warn:g=>t.warn(`[plugin:${u.name}] ${g}`),error:g=>t.error(`[plugin:${u.name}] ${g}`)},r,c);l=p,hs(e,i.name,"plugin.js");let d=await import(Jf(nt(c,"plugin.js")).href),f=d?.activate??d?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(p.context);let h=p.cardPath?hs(e,i.name,p.cardPath):void 0;await p.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(c){l?.abort(),s.failed.push({name:i.name,error:c?.message??String(c)}),t.warn(`plugin ${i.name} failed to load: ${c?.message??String(c)}`)}}return s}function Nc(n,e=No()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Lc(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 Mc,Wf,_s=P(()=>{"use strict";Lo();Vt();ho();Et();ee();Mc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Wf=n=>nt(n,"plugins")});import{gt as Gf,valid as Uc}from"semver";import{existsSync as Dc,readFileSync as Qf}from"node:fs";import{join as bs}from"node:path";import{NPM_SPEC_PATTERN as Vf,PLUGIN_NAME_PATTERN as Fc,PluginInstallError as Yf,installPluginFromNpm as Xf,readPluginRecords as Zf}from"@wengine-ai/claude-code-router-shared";async function em(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 tm(n,e={}){let t=(e.registryBase??qf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(jc.map(m=>em(t,m,o))),s=new Map,a=!1;for(let m of r)if(m.status==="fulfilled"){a=!0;for(let y of m.value){let b=y?.package,_=typeof b?.name=="string"?b.name:"";if(!_||!Vf.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(S=>typeof S=="string"):[]).some(S=>jc.includes(S)))continue;let v=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:v,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=Zf(n),l=new Map(i.map(m=>[m.name,m])),c=m=>{let y=m.indexOf("@",m.startsWith("@")?1:0);return y>0?m.slice(0,y):m},u=new Map(i.filter(m=>typeof m.source=="string"&&m.source!=="").map(m=>[c(m.source),m])),p=m=>{if(!Fc.test(m))return null;try{let y=JSON.parse(Qf(bs(n,"plugins",m,"plugin.json"),"utf8"));return typeof y?.version=="string"?y.version:null}catch{return null}},d=[...s.values()].sort((m,y)=>m.name.localeCompare(y.name)).map(m=>{let y=l.get(m.name)??u.get(m.name),b=y!==void 0||Dc(bs(n,"plugins",m.name)),_=b?p(y?y.name:m.name):null;return{...m,installed:b,installedVersion:_,...b&&_!==null&&Uc(_)&&Uc(m.version)&&Gf(m.version,_)?{updateAvailable:!0}:{}}}),f=new Set(d.map(m=>m.name)),h=new Set,g=new Map;for(let[m,y]of u)h.add(y.name),!f.has(m)&&g.set(m,y.name);for(let m of i)f.has(m.name)||h.has(m.name)||g.set(m.name,m.name);for(let[m,y]of g){if(!Fc.test(y)||!Dc(bs(n,"plugins",y)))continue;let b=p(y);b!==null&&d.push({name:m,description:"",version:b,installed:!0,installedVersion:b,localOnly:!0})}return d.sort((m,y)=>m.name.localeCompare(y.name)),{ok:!0,plugins:d}}function nm(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 Hc(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),l=n.headers?.host;if(typeof l=="string"&&!i.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(!i.has(u))return!1}return!0}function zc(n,e){let t=e.configuredPort??3456,o=(r,s,a)=>r.status(s).send({ok:!1,error:a});n.get("/api/plugins/catalog",async(r,s)=>{if(!Hc(r,n,t))return o(s,403,"local_only");try{return await tm(e.configDir,{registryBase:e.catalogRegistryBase??e.registry,timeoutMs:e.catalogTimeoutMs})}catch(a){return n.log?.warn?.(`plugin catalog failed: ${a?.code??a?.name??"error"}`),{ok:!0,plugins:[],warning:"registry_unavailable"}}}),n.post("/api/plugins/install",async(r,s)=>{if(!Hc(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,l=a.force===!0;try{let c=await Xf({spec:i,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 Yf){let u=nm(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 jc,qf,Bc=P(()=>{"use strict";jc=["ccr-provider-plugin","claude-code-router-plugin"],qf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as om}from"@wengine-ai/claude-code-router-shared";import{join as Z,isAbsolute as rm,normalize as sm,dirname as im}from"path";import{fileURLToPath as am}from"url";import cm from"@fastify/static";import{readdirSync as Jc,statSync as lm,readFileSync as Wc,writeFileSync as um,existsSync as ce,unlinkSync as Kc,rmSync as dm}from"fs";import{homedir as ks}from"os";import{getPresetDir as yo,readManifestFromDir as vs,manifestToPresetFile as Gc,saveManifest as Qc,isPresetInstalled as Vc,extractPreset as pm,HOME_DIR as Ts,loadConfigFromManifest as fm,downloadPresetToTemp as mm,findMarketPresetByName as gm,getMarketPresets as hm,applyClientSelection as ym,disableClient as _m,enableClient as bm,isClientId as km,listClientStatuses as Yc,restoreClient as vm,listProjectConfigs as Tm,readProjectConfigById as Ss,readProjectConfig as Sm,writeProjectConfig as Xc,deleteProjectConfig as xm,getClaudeProjectId as Cm,getProjectConfigPath as Rm,refreshCcrProjectTakeover as wm,refreshPiProjectTakeover as Pm,refreshProjectTakeovers as Em,syncGlobalProjectTakeovers as xs,getProjectTakeoverClients as Cs,setProjectTakeover as Rs,isProjectTakeoverClient as Am}from"@wengine-ai/claude-code-router-shared";import Om from"@fastify/multipart";import Im from"adm-zip";function Zc(n){let e=H();return as(n,(t,o)=>e.isAvailable(t,o))}function qc(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function Mm(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=Ut(t,e),s=Ut(o,e),a=[],i=new Set;for(let l of n||[])l&&l.name&&i.add(l.name);for(let l of Object.keys(r.byProvider||{}))i.add(l);for(let l of Object.keys(s.byProvider||{}))i.add(l);for(let l of i){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),f,h,g=(n||[]).find(m=>m&&m.name===l);g&&g.quota&&(f=g.quota.limit5h,h=g.quota.limit7d),a.push({provider:l,used5h:p,used7d:d,limit5h:f,limit7d:h})}return a}async function el(n,e){let t=n.app;at(),ut(),t.register(Om,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Zc(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,l)=>{let c=decodeURIComponent(i.params.modelId),u=Zc(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(i,l)=>{let{messages:c,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[g,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${g}, model: ${m}`);let y=f.getTokenizerConfigForModel(g,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${g},${m}, using default tiktoken`);let b=await f.countTokens({messages:c,system:p,tools:u},y,g);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(g){i.log?.error(`Error using configured tokenizer: ${g.message}`),i.log?.error(g.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:un(c,p,u)}}),t.get("/api/config",async(i,l)=>await Pt()),t.get("/api/transformers",async(i,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(i,l)=>{let c=i.body,u=Ls(c||{});if(u.length>0)return l.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(h=>`${h.key}: ${h.error}`).join("; "),proxyErrors:u};let p=await ao();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}om(c,d),n.pluginRegistry.applyConfigProtectors(c,d),await de(c);let f;try{f=await xs(c),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"Config saved but some global project takeovers failed to sync")}catch(h){t.log?.warn?.(`Config saved but global project takeover sync failed: ${h?.message||h}`)}return et(n,c,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,l)=>{try{let c=await X();return{clients:Yc(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(i,l)=>{try{let c=i.body,u=Array.isArray(c?.enabled)?c.enabled:[],p=await X(),d=ym(p,u);await de(d.config);let f=await xs(d.config),h=qc(t,f,"clients/apply");return{...d,success:d.success&&h,projectTakeoverSync:f}}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(i,l,c){try{let{id:u}=i.params;if(!km(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=c==="enable"?bm(p,u):c==="restore"?vm(p,u):_m(p,u);await de(p);let f=await xs(p),h=qc(t,f,`clients/${u}/${c}`);return{success:d.success&&h,result:d,results:[d],clients:Yc(p),config:p,projectTakeoverSync:f}}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(i,l)=>o(i,l,"enable")),t.post("/api/clients/:id/disable",async(i,l)=>o(i,l,"disable")),t.post("/api/clients/:id/restore",async(i,l)=>o(i,l,"restore")),t.get("/api/projects",async(i,l)=>{try{let c=await Tm();return{projects:await Promise.all(c.map(async p=>{let d=await Cs(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(i,l)=>{try{let{path:c}=i.body||{};if(!c||typeof c!="string"||!rm(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=sm(c).replace(/[\\/]+$/,"")||c;if(await Sm(u)){l.status(409).send({error:"Project is already configured"});return}await Xc(u,{Router:{}});try{let f=await X();await Rs(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await Cs(u);return{id:Cm(u),path:u,configPath:Rm(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(i,l)=>{try{let{id:c}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){l.status(400).send({error:"Router must be an object"});return}let p=await Ss(c);if(!p){l.status(404).send({error:"Project config not found"});return}await Xc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await Em(p.path,d):(await wm(p.path,d,u),await Pm(p.path,d,u));let f=await Cs(p.path);return{id:c,path:p.path,configPath:p.configPath,Router:u,ccrTakeoverClients:f,ccrTakeover:f.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(i,l)=>{try{let{id:c}=i.params,u=i.body||{},p;if(Array.isArray(u.clients))p=u.clients.filter(Am);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 Ss(c);if(!d){l.status(404).send({error:"Project config not found"});return}let f=await X(),h=await Rs(d.path,p,f);return{id:c,path:d.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(i,l)=>{try{let{id:c}=i.params,u=await Ss(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let p=await X();await Rs(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await xm(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:im(am(import.meta.url)),s=ce(Z(r,"index.html"))?r:ce(Z(r,"..","index.html"))?Z(r,".."):ce(Z(r,"..","dist","index.html"))?Z(r,"..","dist"):ce(Z(r,"..","..","dist","index.html"))?Z(r,"..","..","dist"):Z(r,"..","dist");t.register(cm,{root:s,prefix:"/ui/",cacheControl:!1,setHeaders:(i,l)=>{i.setHeader("Cache-Control","no-cache")}}),t.get("/ui",async(i,l)=>l.redirect("/ui/")),t.get("/api/logs/files",async(i,l)=>{try{let c=Z(ks(),".claude-code-router","logs"),u=[];if(ce(c)){let p=Jc(c);for(let d of p)if(d.endsWith(".log")){let f=Z(c,d),h=lm(f);u.push({name:d,path:f,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((d,f)=>new Date(f.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(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=Z(ks(),".claude-code-router","logs","app.log"),ce(u)?Wc(u,"utf8").split(`
408
+ `).filter(f=>f.trim()):[]}catch(c){console.error("Failed to get logs:",c),l.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=Z(ks(),".claude-code-router","logs","app.log"),ce(u)&&um(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:Jt()})),t.put("/api/debug-log",async i=>{let{enabled:l}=i.body;return Eo(l),{enabled:Jt()}}),t.get("/api/usage",async(i,l)=>{try{let c=i.query;return ps({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(i,l)=>{try{let c=i.query;return Ut(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(i,l)=>{try{let c=i.query;return fs(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(i,l)=>{try{let u=H().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,lastSuccessTime:f.lastSuccessTime??null,lastError:f.lastError,rateLimitUntil:f.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(i,l)=>{try{let{providerName:c}=i.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&&lo(c,i.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(i,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(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let h=await u.probeProviderManually(f.name);return h.success&&lo(f.name,i?.log),{provider:f.name,success:h.success,latencyMs:h.latencyMs,status:h.status,isSlow:h.isSlow,errorKind:h.errorKind??null,error:h.error}}));return{results:d,successCount:d.filter(f=>f.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(i,l)=>{try{let u=(await X()).Providers||[],p=t._server?.pluginRegistry,d=t._server?.providerService;if(p&&d?.getProviders){let b=d.getProviders().filter(_=>_?.name&&_.enabled!==!1).map(_=>{let k=p.getManagedRuntimeFor(_);if(!(!k||typeof k.fetchQuota!="function"))return Yn(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,Qa).unref?.()});await Promise.race([Promise.all(b),_])}}let f=Mm(u),h=new Map(f.map(y=>[y.provider,y])),g=Ko();for(let y of f){let b=g.find(_=>_.provider===y.provider);b&&b.limit!=null&&!qt(b.reset)&&(y.limit5h=b.limit,y.used5h=b.limit-(b.remaining??0),b.reset&&(y.reset5h=new Date(b.reset*1e3).toISOString()))}let m=or();for(let y of m){let b=h.get(y.provider);b||(b={provider:y.provider,used5h:0,used7d:0},f.push(b),h.set(y.provider,b)),typeof y.totalBalance=="number"?(b.limit7d=y.totalBalance,b.type7d=y.currency?"balance":"rateLimit",y.currency&&(b.currency=y.currency),typeof y.usedBalance=="number"?b.used7d=y.usedBalance:typeof y.remainingBalance=="number"?b.used7d=Math.max(0,y.totalBalance-y.remainingBalance):(b.used7d=0,b.limit7d=y.totalBalance)):typeof y.usedBalance=="number"&&(b.used7d=y.usedBalance);let _=qt(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=qt(typeof y.resetTime7d=="string"?Date.parse(y.resetTime7d)/1e3:void 0);typeof y.usedDailyBalance=="number"&&!_&&(b.used5h=y.usedDailyBalance,b.type5h="rateLimit"),typeof y.limitDaily=="number"&&!_&&(b.limit5h=y.limitDaily,b.type5h="rateLimit"),typeof y.resetTime=="string"&&!_&&(y.limitDaily!==void 0?b.reset5h=y.resetTime:b.reset7d=y.resetTime),typeof y.resetTime7d=="string"&&!k&&(b.reset7d=y.resetTime7d)}return{quotas:f,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(i,l)=>{try{let c=Z(Ts,"presets");if(!ce(c))return{presets:[]};let p=Jc(c,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let h=Z(c,f);try{let g=Z(h,"manifest.json"),m=Wc(g,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:v,API_TIMEOUT_MS:S,PROXY_URL:T,PROXY_GLOBAL_ENABLED:w,LOG:E,LOG_LEVEL:R,StatusLine:A,NON_INTERACTIVE_MODE:D,...C}=y;d.push({id:f,name:C.name||f,version:C.version||"1.0.0",description:C.description,author:C.author,homepage:C.homepage,repository:C.repository,license:C.license,keywords:C.keywords,ccrVersion:C.ccrVersion,source:C.source,sourceType:C.sourceType,checksum:C.checksum,installed:!0})}catch(g){console.error(`Failed to read preset ${f}:`,g)}}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(i,l)=>{try{let{name:c}=i.params,u=yo(c);if(!ce(u)){l.status(404).send({error:"Preset not found"});return}let p=await vs(u);return{...Gc(p),config:fm(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(i,l)=>{try{let{name:c}=i.params,{secrets:u}=i.body,p=yo(c);if(!ce(p)){l.status(404).send({error:"Preset not found"});return}let f={...await vs(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await Qc(c,f),{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(i,l)=>{try{let{name:c}=i.params,u=yo(c);if(!ce(u)){l.status(404).send({error:"Preset not found"});return}return dm(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(i,l)=>{try{return{presets:await hm()}}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(i,l)=>{try{let{presetName:c}=i.body;if(!c){l.status(400).send({error:"Preset name is required"});return}let u=await gm(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,f]=p,h=u.name||c;if(await Vc(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/${d}/${f}/archive/refs/heads/main.zip`,m=await mm(g),y=await a(m);if(await Vc(h)){Kc(m),l.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let b=yo(h);await pm(m,b);let _=await vs(b);return _.repository=u.repo,u.url&&(_.source=u.url),await Qc(h,_),Kc(m),{success:!0,presetName:h,preset:{...y.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 a(i){let l=new Im(i),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 Gc(u)}return t.get("/api/plugins",async()=>({plugins:Nc(Ts,n.pluginRegistry)})),zc(t,{configDir:Ts,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,l)=>{let{name:c,file:u}=i.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 tl=P(()=>{"use strict";Pe();xe();Ce();$r();xe();ee();ot();ie();Ot();ho();_s();Bc();Et();Dt();cs()});function Lm(n,e){let t=n?.Router,{family:o}=mt(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function nl(n){return n?.Router?.image}function $m(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 Nm(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 ws,_o,Ps,ol,rl=P(()=>{"use strict";Pe();ws=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}},_o=new ws;Ps=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Lm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!$m(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&gt(e.body.model)?!1:(Nm(e.body.messages),s&&!!nl(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let l=_o.getImage(`${t.req.id}_Image#${i}`);l&&o.push({type:"image",source:l})});else{let i=_o.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(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(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:nl(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
403
409
  When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
404
410
  Do not ignore or deviate from the task.
405
411
  Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(i=>i.json()).catch(i=>null);return!a||!a.content?"analyzeImage Error":a.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
@@ -412,5 +418,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
412
418
 
413
419
  Do not attempt to describe or analyze the image directly yourself.
414
420
  Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
415
- Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")yo.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],l=a.content.filter(u=>u.type!=="image"?!0:(yo.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),c=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=l.length>0?[{type:"text",text:c},...l]:c}})})}},Zc=new Cs});var Rs,el,_o,tl=w(()=>{"use strict";qc();Rs=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}},el=new Rs;el.registerAgent(Zc);_o=el});import{EventEmitter as Rm}from"node:events";import{performance as nl}from"node:perf_hooks";import wm from"json5";function Em(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 rl(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,e)}function ws(n){return n.usageSessionId||n.id}function bo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${ws(n)}`}function Ft(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ie(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 Am(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?Ee(e.usage):e.response?.usage?Ee(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Om(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();lo(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o;try{o=new URL(`http://127.0.0.1${n.url}`)}catch{return}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")){rl(n,t);let r=bo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function Im(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of _o.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 sl(n){return{authClient:(e,t)=>Om(e,t,n),agent:(e,t)=>Im(e,t,n)}}function il(n,e){n.addHook("onRequest",async t=>{let o;try{o=new URL(`http://127.0.0.1${t.url}`)}catch{return}t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=nl.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname;if(!r)try{r=new URL(`http://127.0.0.1${t.url}`).pathname}catch{r=""}r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=l=>l?a(l):s();lo(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",ol.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){rl(t,e);let l=ws(t),c=bo(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new ie),m,y=-1,b="",_="",k="",v=[],x=[];return s(null,Zn(h,async(T,P)=>{try{if(T.event==="content_block_start"&&T?.data?.content_block?.name){let E=t.agents.find(R=>_o.getAgent(R)?.tools.get(T.data.content_block.name));if(E){m=_o.getAgent(E),y=T.data.index,b=T.data.content_block.name,k=T.data.content_block.id;return}}if(y>-1&&T.data.index===y&&T.data?.delta?.type==="input_json_delta"){_+=T.data?.delta?.partial_json;return}if(y>-1&&T.data.index===y&&T.data?.type==="content_block_stop"){try{let E=wm.parse(_);x.push({type:"tool_use",id:k,name:b,input:E});let R=await m?.tools.get(b)?.handler(E,{req:t,config:e});v.push({tool_use_id:k,type:"tool_result",content:R}),m=void 0,y=-1,b="",_="",k=""}catch(E){console.log(E)}return}if(T.event==="message_delta"&&v.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:v});let E=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(!E.ok)return;let A=E.body.pipeThrough(new ie).getReader();for(;;)try{let{value:D,done:C}=await A.read();if(C)break;let O=D;if(["message_start","message_stop"].includes(O.event))continue;if(!P.desiredSize)break;P.enqueue(O)}catch(D){if(D.name==="AbortError"||D.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw D}return}return T}catch(E){if(console.error("Unexpected error in stream processing:",E),E.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw E}}).pipeThrough(new Ze))}let[p,d]=r.tee(),f=async g=>{let m=g.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&Ft(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let v=Y.get(c)||{},x=Ee(k.usage),T=Ae(v,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:x,mergedUsage:T}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),Y.put(c,T)}if(k?.response?.usage){let v=Ee(k.response.usage),x=Y.get(c)||{},T=Ae(x,v,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:v,mergedUsage:T}),Y.put(c,T)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:g,value:h}=await f.read();if(g)break;let m=h.event,y=h.data;m==="message_start"&&y?.message?.model&&Ft(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&Ft(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ee(b),k=Y.get(c)||{},v=Ae(k,_,m==="message_start");Y.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{f.releaseLock()}})(),s(null,p)}let u=Am(r);if(u?.usage&&Y.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(ol.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=>{Yo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Yo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async T=>{if(!T)return;let P;try{await Promise.race([T,new Promise(E=>{P=setTimeout(E,Pm)})])}finally{P&&clearTimeout(P)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=ws(t),a=s,i=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:Y.get(bo(t)),u=ds(a),p=H(),d,f,g=t.sseError,h=g&&(g.type||g.code||g.message),m=c?.output_tokens&&c.output_tokens>0,y=t.contentDelivered===!0,b=l||h&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(g),f=JSON.stringify(g)),f=f||t.errorResponseBody;let T=Ie(t);Em(o.statusCode,d)?p.markRateLimited(t.provider||"",T,120,d):p.recordFailure(t.provider||"",T,d)}else{let T=Ie(t);p.recordSuccess(t.provider||"",T)}let _=c?.cache_read_input_tokens??0,v=c?.input_tokens||0||t.tokenCount||0;!c?.usage_estimated&&!_&&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 x=b?0:c?.output_tokens||0;!b&&t.body?.stream&&v===0&&x===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ie(t),usageSessionId:i,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:i,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:Ie(t),upstreamModel:t.upstreamModel||Ie(t)||void 0,...c?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Be(t),stream:t.body?.stream??!1,inputTokens:v,outputTokens:x,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(nl.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(bo(t))}catch(r){console.error("Usage tracking error:",r)}})}var Pm,ol,al=w(()=>{"use strict";Je();on();tn();re();Dr();Fr();jr();Ut();gn();tl();is();pn();Pm=1500;ol=new Rm});var ll={};To(ll,{createCcrServer:()=>Fm});import{homedir as Mm}from"os";import{join as Lm}from"path";import{createStream as $m}from"rotating-file-stream";import{CONFIG_FILE as Nm,HOME_DIR as cl,listPresets as Um,ensureCcrSelfProvider as Dm}from"@wengine-ai/claude-code-router-shared";async function Fm(n={}){await _c(),await so();let e=await ns();Dm(e).changed&&(await ue(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;ec();let l=f=>(f>9?"":"0")+f,c=(f,g)=>{let h;f?typeof f=="number"?h=new Date(f):h=f:h=new Date;let m=h.getFullYear()+""+l(h.getMonth()+1),y=l(h.getDate()),b=l(h.getHours()),_=l(h.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${l(h.getSeconds())}${g?`_${g}`:""}.log`},u;n.logger!==void 0?u=n.logger:(xc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:$m(c,{path:cl,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await Um(),d=new dl({jsonPath:Nm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:Lm(Mm(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await Ac({configDir:cl,registry:d.pluginRegistry,getServer:()=>d,log:{info:y=>d.app?.log?.info?.(y),warn:y=>d.app?.log?.warn?.(y),error:y=>d.app?.log?.error?.(y)}});f.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(y=>`${y.name} (${y.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(y=>`${y.name}@${y.version}`).join(", ")}`),f.loaded.length&&tt(d,e,d.app.log),await Vc(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Be(y.req):"unknown";$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:y.sessionId||"",provider:y.provider||"",originalModel:y.originalModel||"",model:y.model||"",modelFamily:y.modelFamily||"",scenarioType:y.scenarioType||"default",clientType:b,stream:y.stream??!1,inputTokens:y.inputTokens||0,outputTokens:0,cacheReadInputTokens:y.cacheReadInputTokens||0,cacheCreationInputTokens:y.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:y.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},il(d,e),d.ccrPreHandlerCallbacks=sl(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,b)=>{if(y.status==="rejected"){let _=p[b],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await Cc(d,e),Et(e,d.app?.log);let h=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",h),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",h),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var ul=w(()=>{"use strict";pl();bc();Pt();Sc();Qr();Rc();Yc();gs();go();al();At();Ut();Je()});import jm from"fastify";import Hm from"@fastify/cors";function zm(n={}){let e=jm({bodyLimit:52428800,...n});return e.setErrorHandler(Us),e.register(Hm),e}async function Bm(n={}){return(await Promise.resolve().then(()=>(ul(),ll))).createCcrServer(n)}var Ps,dl,TT,pl=w(()=>{Ro();zt();pn();ir();gr();yr();Pe();on();Xn();re();Se();Ce();q();Je();pn();Qt();je();Je();Pe();Ro();ir();gr();yr();es();Hr();re();Se();Or();Ce();re();Xn();rt();q();Pt();gn();At();ss();is();Ut();Ps=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:a,useEnvironmentVariables:i,...l}=e;this.app=zm({...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),a!==void 0&&(c.useJsonFile=a),i!==void 0&&(c.useEnvironmentVariables=i),this.configService=new Me(c),this.transformerService=new Ye(this.configService,this.app.log),this.tokenizerService=new Xe(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 Ge(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Me({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ye(o,this.app.log),a=new Xe(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ge(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async l=>{l.decorate("pluginRegistry",this.pluginRegistry),l.decorate("configService",o),l.decorate("transformerService",r),l.decorate("providerService",s),l.decorate("tokenizerService",a),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"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!c.body||typeof c.body!="object")return;let g=c.ccrHookOrder||=[];if(g.push("request-normalize"),f&&c.body.input&&!c.body.messages&&ht(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),Re(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 un(c,u,{configService:o,tokenizerService:a}),c.usageCacheKey&&Y.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 h=c.body;if(!h||!h.model)return u.code(400).send({error:"Missing model in request body"});let m=h.model.split(","),y=h.model;if(m.length>1){let[b,..._]=m;y=_.join(","),h.model=y,c.provider=b}c.model=y}catch(h){return c.log.error({error:h},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Xi(l)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{$r()}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 Co()})}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{ut()}catch{}try{jo()}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=>de(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)}}},dl=Ps;TT=Bm});pl();export{Yn as ActiveProbeService,Me as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ge as ProviderService,ie as SSEParserTransform,Ze as SSESerializerTransform,Xe as TokenizerService,Ye as TransformerService,lo as apiKeyAuth,Re as applyClientAdapter,io as backupConfigFile,Ei as builtinClientAdapterRegistry,ln as calculateTokenCount,Xu as clearClientAdapterCaches,co as clearProviderHealth,Co as closeProxyDispatchers,ac as collectReachableModelKeys,Bm as createCcrServer,dl as default,Be as detectClientType,Fi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Wa as getActiveProbeService,tr as getAllQuotaResults,Jo as getAllRateLimitInfo,Oi as getClientAdapter,Ht as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Er as getQuotaAdapter,rn as getQuotaResult,ou as getRateLimitInfo,Bt as getRuntimeDebugLog,TT as getServer,ns as initConfig,so as initDir,jo as initProviderHealthPersistence,ut as initQuotaStorePersistence,at as initRateLimitPersistence,Ai as isClientType,Ls as isGlobalProxyEnabled,rs as listAnthropicCompatibleModels,Ae as mergeUsageCapture,ge as normalizeSessionId,Ee as normalizeUsagePayload,kt as pluginManager,X as readConfigFile,wt as readConfigFileRaw,Et as reconcileHealthStore,Nr as resetActiveProbeService,de as resolveProviderProxyUrl,Zn as rewriteStream,un as router,zi as searchProjectBySession,Y as sessionUsageCache,Po as setRuntimeDebugLog,bt as startActiveProbe,$r as stopActiveProbe,lt as storeQuotaResult,oo as tokenSpeedPlugin,yc as usageStore,ue as writeConfigFile};
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(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")_o.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],l=a.content.filter(u=>u.type!=="image"?!0:(_o.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),c=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=l.length>0?[{type:"text",text:c},...l]:c}})})}},ol=new Ps});var Es,sl,bo,il=P(()=>{"use strict";rl();Es=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}},sl=new Es;sl.registerAgent(ol);bo=sl});import{EventEmitter as Um}from"node:events";import{performance as al}from"node:perf_hooks";import Dm from"json5";function jm(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 ll(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,e)}function As(n){return n.usageSessionId||n.id}function ko(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${As(n)}`}function jt(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ie(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 Hm(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?Ee(e.usage):e.response?.usage?Ee(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function zm(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();uo(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o;try{o=new URL(`http://127.0.0.1${n.url}`)}catch{return}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")){ll(n,t);let r=ko(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function Bm(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of bo.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 ul(n){return{authClient:(e,t)=>zm(e,t,n),agent:(e,t)=>Bm(e,t,n)}}function dl(n,e){n.addHook("onRequest",async t=>{let o;try{o=new URL(`http://127.0.0.1${t.url}`)}catch{return}t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=al.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname;if(!r)try{r=new URL(`http://127.0.0.1${t.url}`).pathname}catch{r=""}r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=l=>l?a(l):s();uo(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",cl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){ll(t,e);let l=As(t),c=ko(t);if(r instanceof ReadableStream){if(a&&t.agents){let h=new AbortController,g=r.pipeThrough(new ae),m,y=-1,b="",_="",k="",v=[],S=[];return s(null,qn(g,async(T,w)=>{try{if(T.event==="content_block_start"&&T?.data?.content_block?.name){let E=t.agents.find(R=>bo.getAgent(R)?.tools.get(T.data.content_block.name));if(E){m=bo.getAgent(E),y=T.data.index,b=T.data.content_block.name,k=T.data.content_block.id;return}}if(y>-1&&T.data.index===y&&T.data?.delta?.type==="input_json_delta"){_+=T.data?.delta?.partial_json;return}if(y>-1&&T.data.index===y&&T.data?.type==="content_block_stop"){try{let E=Dm.parse(_);S.push({type:"tool_use",id:k,name:b,input:E});let R=await m?.tools.get(b)?.handler(E,{req:t,config:e});v.push({tool_use_id:k,type:"tool_result",content:R}),m=void 0,y=-1,b="",_="",k=""}catch(E){console.log(E)}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 E=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(!E.ok)return;let A=E.body.pipeThrough(new ae).getReader();for(;;)try{let{value:D,done:C}=await A.read();if(C)break;let O=D;if(["message_start","message_stop"].includes(O.event))continue;if(!w.desiredSize)break;w.enqueue(O)}catch(D){if(D.name==="AbortError"||D.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw D}return}return T}catch(E){if(console.error("Unexpected error in stream processing:",E),E.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();return}throw E}}).pipeThrough(new Xe))}let[p,d]=r.tee(),f=async h=>{let m=h.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&jt(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&jt(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&jt(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let v=Y.get(c)||{},S=Ee(k.usage),T=Ae(v,S,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Ie(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}),Y.put(c,T)}if(k?.response?.usage){let v=Ee(k.response.usage),S=Y.get(c)||{},T=Ae(S,v,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:v,mergedUsage:T}),Y.put(c,T)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();try{for(;;){let{done:h,value:g}=await f.read();if(h)break;let m=g.event,y=g.data;m==="message_start"&&y?.message?.model&&jt(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&jt(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ee(b),k=Y.get(c)||{},v=Ae(k,_,m==="message_start");Y.put(c,v)}}}catch(h){h?.name!=="AbortError"&&h?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(h)})}finally{f.releaseLock()}})(),s(null,p)}let u=Hm(r);if(u?.usage&&Y.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(cl.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{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 T=>{if(!T)return;let w;try{await Promise.race([T,new Promise(E=>{w=setTimeout(E,Fm)})])}finally{w&&clearTimeout(w)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=As(t),a=s,i=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:Y.get(ko(t)),u=ms(a),p=H(),d,f,h=t.sseError,g=h&&(h.type||h.code||h.message),m=c?.output_tokens&&c.output_tokens>0,y=t.contentDelivered===!0,b=l||g&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,g&&(d=d||JSON.stringify(h),f=JSON.stringify(h)),f=f||t.errorResponseBody;let T=Ie(t);jm(o.statusCode,d)?p.markRateLimited(t.provider||"",T,120,d):p.recordFailure(t.provider||"",T,d)}else{let T=Ie(t);p.recordSuccess(t.provider||"",T)}let _=c?.cache_read_input_tokens??0,v=c?.input_tokens||0||t.tokenCount||0;!c?.usage_estimated&&!_&&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 S=b?0:c?.output_tokens||0;!b&&t.body?.stream&&v===0&&S===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ie(t),usageSessionId:i,tokenCount:t.tokenCount,cachedUsage:c,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),Nt({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:Ie(t),upstreamModel:t.upstreamModel||Ie(t)||void 0,...c?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||ze(t),stream:t.body?.stream??!1,inputTokens:v,outputTokens:S,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(al.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(ko(t))}catch(r){console.error("Usage tracking error:",r)}})}var Fm,cl,pl=P(()=>{"use strict";Be();rn();nn();ie();Hr();zr();Br();Dt();hn();il();ls();fn();Fm=1500;cl=new Um});var ml={};So(ml,{createCcrServer:()=>Ym});import{homedir as Jm}from"os";import{join as Wm}from"path";import{createStream as Km}from"rotating-file-stream";import{CONFIG_FILE as Gm,HOME_DIR as fl,listPresets as Qm,ensureCcrSelfProvider as Vm}from"@wengine-ai/claude-code-router-shared";async function Ym(n={}){await Sc(),await io();let e=await ss();Vm(e).changed&&(await de(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;sc();let l=f=>(f>9?"":"0")+f,c=(f,h)=>{let g;f?typeof f=="number"?g=new Date(f):g=f:g=new Date;let m=g.getFullYear()+""+l(g.getMonth()+1),y=l(g.getDate()),b=l(g.getHours()),_=l(g.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${l(g.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(Pc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:Km(c,{path:fl,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await Qm(),d=new hl({jsonPath:Gm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:Wm(Jm(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await $c({configDir:fl,registry:d.pluginRegistry,getServer:()=>d,log:{info:y=>d.app?.log?.info?.(y),warn:y=>d.app?.log?.warn?.(y),error:y=>d.app?.log?.error?.(y)}});f.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(y=>`${y.name} (${y.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(y=>`${y.name}@${y.version}`).join(", ")}`),f.loaded.length&&et(d,e,d.app.log),await el(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||ze(y.req):"unknown";Nt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:y.sessionId||"",provider:y.provider||"",originalModel:y.originalModel||"",model:y.model||"",modelFamily:y.modelFamily||"",scenarioType:y.scenarioType||"default",clientType:b,stream:y.stream??!1,inputTokens:y.inputTokens||0,outputTokens:0,cacheReadInputTokens:y.cacheReadInputTokens||0,cacheCreationInputTokens:y.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:y.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},dl(d,e),d.ccrPreHandlerCallbacks=ul(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,b)=>{if(y.status==="rejected"){let _=p[b],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await Ac(d,e),At(e,d.app?.log);let g=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",g),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",g),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var gl=P(()=>{"use strict";yl();xc();Et();Ec();Xr();Oc();tl();_s();ho();pl();Ot();Dt();Be()});import Xm from"fastify";import Zm from"@fastify/cors";function qm(n={}){let e=Xm({bodyLimit:52428800,...n});return e.setErrorHandler(js),e.register(Zm),e}async function eg(n={}){return(await Promise.resolve().then(()=>(gl(),ml))).createCcrServer(n)}var Os,hl,LT,yl=P(()=>{wo();Bt();fn();cr();yr();br();Pe();rn();Zn();ie();xe();Ce();ee();Be();fn();Vt();Fe();Be();Pe();wo();cr();yr();br();os();Jr();ie();xe();Lr();Ce();ie();Zn();ot();ee();Et();hn();Ot();cs();ls();Dt();Os=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:a,useEnvironmentVariables:i,...l}=e;this.app=qm({...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),a!==void 0&&(c.useJsonFile=a),i!==void 0&&(c.useEnvironmentVariables=i),this.configService=new Me(c),this.transformerService=new Ve(this.configService,this.app.log),this.tokenizerService=new Ye(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 Ke(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Me({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ve(o,this.app.log),a=new Ye(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ke(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async l=>{l.decorate("pluginRegistry",this.pluginRegistry),l.decorate("configService",o),l.decorate("transformerService",r),l.decorate("providerService",s),l.decorate("tokenizerService",a),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"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!c.body||typeof c.body!="object")return;let h=c.ccrHookOrder||=[];if(h.push("request-normalize"),f&&c.body.input&&!c.body.messages&&ht(c.body),c.body.stream===void 0&&(c.body.stream=!1),c.log.info({data:c.body,type:"request body"}),h.push("adapter"),!c.originalModel&&c.body.model&&(c.originalModel=c.body.model),Re(c,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(c,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(c,u),u.sent)))){h.push("router"),c.body?.model&&await dn(c,u,{configService:o,tokenizerService:a}),c.usageCacheKey&&Y.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 m=g.model.split(","),y=g.model;if(m.length>1){let[b,..._]=m;y=_.join(","),g.model=y,c.provider=b}c.model=y}catch(g){return c.log.error({error:g},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await ea(l)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{Dr()}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 Ro()})}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{ut()}catch{}try{zo()}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=kt(()=>this.providerService.getProviders(),t,o=>pe(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)}}},hl=Os;LT=eg});yl();export{Xn as ActiveProbeService,Me as ConfigService,ne as ProjectRoutingError,Zt as ProviderHealthStore,Ke as ProviderService,ae as SSEParserTransform,Xe as SSESerializerTransform,Ye as TokenizerService,Ve as TransformerService,uo as apiKeyAuth,Re as applyClientAdapter,ao as backupConfigFile,Ii as builtinClientAdapterRegistry,un as calculateTokenCount,nd as clearClientAdapterCaches,lo as clearProviderHealth,Ro as closeProxyDispatchers,pc as collectReachableModelKeys,eg as createCcrServer,hl as default,ze as detectClientType,zi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Ya as getActiveProbeService,or as getAllQuotaResults,Ko as getAllRateLimitInfo,Li as getClientAdapter,zt as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Ir as getQuotaAdapter,sn as getQuotaResult,cu as getRateLimitInfo,Jt as getRuntimeDebugLog,LT as getServer,ss as initConfig,io as initDir,zo as initProviderHealthPersistence,ut as initQuotaStorePersistence,at as initRateLimitPersistence,Mi as isClientType,Us as isGlobalProxyEnabled,as as listAnthropicCompatibleModels,Ae as mergeUsageCapture,ge as normalizeSessionId,Ee as normalizeUsagePayload,vt as pluginManager,X as readConfigFile,Pt as readConfigFileRaw,At as reconcileHealthStore,Fr as resetActiveProbeService,pe as resolveProviderProxyUrl,qn as rewriteStream,dn as router,Wi as searchProjectBySession,Y as sessionUsageCache,Eo as setRuntimeDebugLog,kt as startActiveProbe,Dr as stopActiveProbe,lt as storeQuotaResult,ro as tokenSpeedPlugin,Tc as usageStore,de as writeConfigFile};
416
422
  //# sourceMappingURL=server.mjs.map