@wengine-ai/llms 2.3.2435 → 2.3.2436

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,218 +1,218 @@
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 So=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ul=Object.getOwnPropertyNames;var Dl=Object.prototype.hasOwnProperty;var xo=(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 Ro=(n,e)=>{for(var t in e)So(n,t,{get:e[t],enumerable:!0})},Fl=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ul(e))!Dl.call(n,r)&&r!==t&&So(n,r,{get:()=>e[r],enumerable:!(o=Nl(e,r))||o.enumerable});return n};var jl=n=>Fl(So({},"__esModule",{value:!0}),n);import{Agent as Hl,ProxyAgent as zl}from"undici";function Jl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Bl.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 js(n){let e=[];for(let t of[...Ds,Fs]){let o=n[t];if(o==null)continue;let r=Jl(o);r.ok||e.push({key:t,error:r.error})}return e}function Po(){return wo||(wo=new Hl({connect:{timeout:15e3}})),wo}function Hs(n){let e=n.get(Fs);return(typeof e=="string"?e.trim():"")||void 0}function zs(n){return n?G(n):Po()}function Kt(n){for(let e of Ds){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Bs(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function me(n,e){let t=Kt(n);if(t)return Bs(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=Wl(n),t=Wt.get(e);if(t)return t;let o=new zl(e);return Wt.set(e,o),o}async function Eo(){let n=Array.from(Wt.values());Wt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function Wl(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 Ds,Fs,Bl,Wt,wo,te=P(()=>{"use strict";Ds=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Fs="SUBSCRIPTION_PROXY_URL",Bl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Wt=new Map});import{readFileSync as Kl,existsSync as Js}from"fs";import{join as Ws}from"path";import{config as Gl}from"dotenv";import Ql from"json5";var Me,Ao=P(()=>{"use strict";te();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:Ws(process.cwd(),this.options.jsonPath);if(Js(e))try{let t=Kl(e,"utf-8"),o=Ql.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:Ws(process.cwd(),this.options.envPath);if(Js(e))try{let t=Gl({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 Kt(this)}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}}});function J(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Ks(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 Gt=P(()=>{"use strict"});function Io(n){Oo=n}function Qt(){return Oo}function Vt(n){return Oo||n.get("DEBUG_LOG")===!0}function Vs(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 Yt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();Vl.has(r)||Yl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Xt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Ys(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:Yt(t.headers),body:Xt(o,Le.maxBodyLength)})}function Xs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Yt(t.headers),...t.body!==void 0?{body:Xt(t.body,Le.maxBodyLength)}:{}})}function Gs(n,e,t,o){let r=Xl(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Xt(o,Le.maxBodyLength)})}function Xl(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:Xt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Qs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Zs(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:c}=await r.read();if(i)break;a+=c;let l=a.split(`
2
+ var xo=Object.defineProperty;var Fl=Object.getOwnPropertyDescriptor;var jl=Object.getOwnPropertyNames;var Hl=Object.prototype.hasOwnProperty;var Ro=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var E=(n,e)=>()=>(n&&(e=n(n=0)),e);var wo=(n,e)=>{for(var t in e)xo(n,t,{get:e[t],enumerable:!0})},zl=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jl(e))!Hl.call(n,r)&&r!==t&&xo(n,r,{get:()=>e[r],enumerable:!(o=Fl(e,r))||o.enumerable});return n};var Bl=n=>zl(xo({},"__esModule",{value:!0}),n);import{Agent as Jl,ProxyAgent as Wl}from"undici";function Gl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Kl.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 Hs(n){let e=[];for(let t of[...Fs,js]){let o=n[t];if(o==null)continue;let r=Gl(o);r.ok||e.push({key:t,error:r.error})}return e}function Eo(){return Po||(Po=new Jl({connect:{timeout:15e3}})),Po}function zs(n){let e=n.get(js);return(typeof e=="string"?e.trim():"")||void 0}function Bs(n){return n?G(n):Eo()}function Qt(n){for(let e of Fs){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Js(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function me(n,e){let t=Qt(n);if(t)return Js(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=Ql(n),t=Gt.get(e);if(t)return t;let o=new Wl(e);return Gt.set(e,o),o}async function Ao(){let n=Array.from(Gt.values());Gt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function Ql(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 Fs,js,Kl,Gt,Po,te=E(()=>{"use strict";Fs=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],js="SUBSCRIPTION_PROXY_URL",Kl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Gt=new Map});import{readFileSync as Vl,existsSync as Ws}from"fs";import{join as Ks}from"path";import{config as Yl}from"dotenv";import Xl from"json5";var Me,Oo=E(()=>{"use strict";te();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:Ks(process.cwd(),this.options.jsonPath);if(Ws(e))try{let t=Vl(e,"utf-8"),o=Xl.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:Ks(process.cwd(),this.options.envPath);if(Ws(e))try{let t=Yl({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 Qt(this)}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}}});function J(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Gs(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var Vt=E(()=>{"use strict"});function Mo(n){Io=n}function Yt(){return Io}function Xt(n){return Io||n.get("DEBUG_LOG")===!0}function Ys(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 Zt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();Zl.has(r)||ql.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function qt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Xs(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:Zt(t.headers),body:qt(o,Le.maxBodyLength)})}function Zs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Zt(t.headers),...t.body!==void 0?{body:qt(t.body,Le.maxBodyLength)}:{}})}function Qs(n,e,t,o){let r=eu(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:qt(o,Le.maxBodyLength)})}function eu(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:qt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Vs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function qs(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:c}=await r.read();if(i)break;a+=c;let l=a.split(`
3
3
 
4
- `);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?Gs(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&&Gs(e,t,s,a.trim()),s++),Qs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Qs(e,t,s)}finally{r.releaseLock()}})()}var Vl,Yl,Le,Oo,it=P(()=>{"use strict";Vl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Yl=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},Oo=!1});function qs(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([l,u])=>{u&&s.set(l,u)});let a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let l=new AbortController,u=()=>l.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=l.signal}else a=i;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?c.dispatcher=t.dispatcher:t.httpsProxy&&(c.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Yt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Zl(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function Zl(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 ei=P(()=>{te();it()});function eu(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function ti(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Mo(n){if(ti(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(ql.some(s=>r.includes(s))){e=!0;break}tu.some(s=>r.includes(s))&&(t=!0)}}return e||eu(n)?"content":t?"empty":"pending"}async function ni(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,d)=>({verdict:u,chunks:s,bytes:i,rest:d});try{for(;;){let u=c-Date.now(),d=Symbol("timeout"),p,f=o.read(),h=u<=0?d:await Promise.race([f,new Promise(y=>{p=setTimeout(()=>y(d),u)})]);if(p&&clearTimeout(p),h===d)return l(Mo(a)==="content"?"content":"pending",Zt(o,f));if(h.done){a+=r.decode();let y=Mo(a);return l(y==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let m=Mo(a);if(m==="content")return l("content",Zt(o));if(m==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(ti(a)||i>=e)return l("pending",Zt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Zt(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 oi(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 ql,tu,ri=P(()=>{"use strict";ql=["content_block_start","content_block_delta","content_block_stop"];tu=["message_stop","response.completed","response.incomplete","[DONE]"]});var Lo=P(()=>{"use strict"});import nu from"fastify";function si(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}function ii(n){return n?.pluginClassified===!0}var at,ou,No,ct=P(()=>{"use strict";Lo();at=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(d){throw i=d,d}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let d=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof d!="string"||!d)throw new Error("plugin transformer has no name");if(s.transformers.has(d))throw new Error(`transformer "${d}" is already registered`);s.transformers.set(d,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,d)=>{this.assertOpen();let p=this.revision;if(s.routes.length){if(!d)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,d)}if(this.assertOpen(),this.revision!==p)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 m of this.plugins.values()){for(let y of s.runtimes.keys())if(m.runtimes.has(y))throw new Error(`managed runtime "${y}" is already registered`);for(let y of s.transformers.keys())if(m.transformers.has(y))throw new Error(`transformer "${y}" is already registered`)}let f=[...this.transformerServices].flatMap(m=>[...s.transformers].map(([y,g])=>{if(m.hasTransformer(y))throw new Error(`transformer "${y}" is already registered`);return{service:m,name:y,value:m.preparePluginTransformer(g)}})),h=[];try{for(let m of f)h.push(m),m.service.registerTransformer(m.name,m.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(m){for(let y of h)y.service.removeTransformer(y.name);throw a="aborted",m}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,d,p)=>(r.push({...typeof d=="function"?{}:d,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:p??d}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=nu({logger:!1});try{for(let i of e){let c=i(s);c!==s&&await c}for(let i of this.plugins.values())for(let c of i.preparedRoutes)a.route(c);for(let i of r){let c=Array.isArray(i.method)?i.method:[i.method];for(let l of c)if(t.hasRoute({method:l,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${l} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},ou=new at,No=()=>ou});function ru(n,e){return`${n.name}|${e?.name??""}`}function Uo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function lt(n,e,t){let o=Uo(n),r=ru(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Do(n,e,t,o,r){if(!e||t?.nonRetryable!==!0)return!1;let s=lt(n,e,o);return e.modelScopedRecovery&&t?.statusCode===429&&r?(s.modelErrors??=new Map).set(r,t):s.terminalError=t,!0}function Fo(n,e,t,o){let r=lt(n,e,t);return r.terminalError??(o?r.modelErrors?.get(o):void 0)}var ai=P(()=>{"use strict"});function ci(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 xe(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",c=a?{...a,code:i,message:`Provider plugin request failed (${i}).`}:e===0?su(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?.(c,s)}catch{}let l=si(n.name,c);return l.isRateLimit=c.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function su(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 li=P(()=>{"use strict";ct()});var qt,jo=P(()=>{qt="2.3.2435"});var ui={};Ro(ui,{getFallbackPromotionStore:()=>$e,resetFallbackPromotionStore:()=>cu});function $e(n){return Re||(Re=new Ho,n&&Re.configure(n)),Re}function cu(){Re&&(Re.clearAll(),Re=null)}var au,Ho,Re,en=P(()=>{"use strict";ae();au=600*1e3,Ho=class{promotions=new Map;enabled=!0;ttlMs=au;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!H().isAvailable(c,u))return this.promotions.delete(s),null;let p=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=p?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!p||!f||p.enabled===!1?(this.promotions.delete(s),null):`${p.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}},Re=null});import{existsSync as fi,mkdirSync as lu,readFileSync as uu,writeFileSync as du}from"fs";import{join as mi}from"path";import{HOME_DIR as pu}from"@wengine-ai/claude-code-router-shared";function hu(n){try{if(!fi(Jo))return;let e=JSON.parse(uu(Jo,"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 pi(n){try{let e=n.getAllStates();if(e.length===0)return;fi(Bo)||lu(Bo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));du(Jo,JSON.stringify(t,null,2),"utf-8")}catch{}}function Wo(){if(di)return;di=!0;let n=H();hu(n),gu=setInterval(()=>pi(n),6e4),process.on("exit",()=>pi(n))}function H(n){return zo||(zo=new tn(n)),zo}var fu,mu,tn,Bo,Jo,di,gu,zo,ae=P(()=>{"use strict";fu=120,mu={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},tn=class{states=new Map;config;probeTimer;constructor(e){this.config={...mu,...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}=(en(),jl(ui));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t,o=!1){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let s=this.getState(e,t);return s?s.status==="open"&&s.rateLimitUntil?!(Date.now()<s.rateLimitUntil):s.status==="open"&&o&&Date.now()-Math.max(s.lastFailureTime,s.lastProbeTime)>=this.config.probeIntervalMinutes*6e4?(s.status="half-open",s.successCount=0,s.lastProbeTime=Date.now(),!0):s.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}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??fu)*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)}},Bo=mi(pu,"runtime"),Jo=mi(Bo,"provider-health.json"),di=!1,gu=null;zo=null});import{existsSync as bi,mkdirSync as yu,readFileSync as _u,writeFileSync as bu}from"fs";import{join as ki}from"path";import{HOME_DIR as ku}from"@wengine-ai/claude-code-router-shared";function we(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 ut(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let c=Object.keys(t).find(l=>l.toLowerCase()===i);return c?t[c]:null},r=Ko(o,vu),s=Ko(o,Tu),a=Ko(o,Cu);(r||s||a)&&Ne.set(n,{provider:n,remaining:yi(r),limit:yi(s),reset:xu(a),capturedAt:Date.now()})}function Su(n){return Ne.get(n)}function Vo(){return Array.from(Ne.values())}function nn(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Ko(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function yi(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function xu(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=Ru(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Ru(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 wu(){try{if(!bi(Qo))return;let n=JSON.parse(_u(Qo,"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 _i(){try{if(Ne.size===0)return;bi(Go)||yu(Go,{recursive:!0}),bu(Qo,JSON.stringify(Array.from(Ne.values()),null,2),"utf-8")}catch{}}function dt(){gi||(gi=!0,wu(),hi=setInterval(_i,6e4),hi.unref?.(),process.on("exit",_i))}var Go,Qo,Ne,gi,hi,vu,Tu,Cu,ge=P(()=>{"use strict";Go=ki(ku,"runtime"),Qo=ki(Go,"rate-limit.json"),Ne=new Map,gi=!1,hi=null,vu=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Tu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Cu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function rn(){return Yo||(Yo=new Zo),Yo}function er(){return Xo||(Xo=new qo),Xo}function Pu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function vi(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 Ti(n,e){let t=rn(),o=n?.[on];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[on]=t.acquire(e)}function tr(n){let e=n?.[on];e&&rn().release(e)}function Ci(n,e){let t=vi(n),o=n?.[on],r=t?er().get(t)!==void 0:!1;!o&&!r||(t&&er().bind(t,e),Ti(n,e))}function Eu(n,e,t){let o=rn(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function Si(n,e,t){let o=vi(n),r=er(),s=rn(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let c=r.get(o);if(c&&c!==e){let l=t.resolve(c);l?(i=l,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${l}`)):r.unbind(o)}else c&&(i=e)}if(!i){let c=s.count(e);if(c>=a){let l=Eu(e,t.fallbackModels,t.resolve);l&&(i=l,t.log?.(`Concurrency priority: model ${e} has ${c} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${l}`))}i=i||e,o&&r.bind(o,i)}return Ti(n,i),i}var Zo,qo,Yo,Xo,on,sn=P(()=>{"use strict";Zo=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()}},Yo=null,Xo=null;on="__concurrencyLease"});async function j(n){let e=await n.text();return Au(e,n.status)}function Au(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 pt(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function Ue(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function ce(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:c}=await o.read();if(c||(i&&(s+=r.decode(i,{stream:!0})),Ue(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:Ue(s)}}async function ye(n){try{let e=await n.text();if(Ue(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 Ou(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 an(n){for(let e of Ou(n))if(e.startsWith("response."))return!0;return!1}var De,nr=P(()=>{"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){e={...e};let t=e.stream_options;if(t&&Object.hasOwn(t,"include_usage")){let{include_usage:s,...a}=t;Object.keys(a).length?e.stream_options=a:delete e.stream_options}delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let o=[],r=e.messages.filter(s=>s.role==="system");if(r.length>0){let s=r[0];Array.isArray(s.content)?s.content.forEach(a=>{let i="";typeof a=="string"?i=a:a&&typeof a=="object"&&"text"in a&&(i=a.text),o.push({role:"system",content:i})}):e.instructions=s.content}if(e.messages.forEach(s=>{if(s.role==="system")return;if(Array.isArray(s.content)){let c=s.content.map(l=>this.normalizeRequestContent(l,s.role)).filter(l=>l!==null);c.length>0?s.content=c:delete s.content}if(s.role==="tool"){let c={...s};c.type="function_call_output",c.call_id=s.tool_call_id,c.output=s.content,delete c.cache_control,delete c.role,delete c.tool_call_id,delete c.content,o.push(c);return}if(s.role==="assistant"&&Array.isArray(s.tool_calls)){s.tool_calls.forEach(c=>{o.push({type:"function_call",arguments:c.function.arguments,name:c.function.name,call_id:c.id})});return}let{thinking:a,...i}=s;s.role==="assistant"&&i.content===void 0||o.push(i)}),e.input=o,delete e.messages,Array.isArray(e.tools)){let s=e.tools.find(a=>a.function.name==="web_search");e.tools=e.tools.filter(a=>a.function.name!=="web_search").map(a=>(a.function.name==="WebSearch"&&delete a.function.parameters.properties.allowed_domains,a.function.name==="Edit"?{type:a.type,name:a.function.name,description:a.function.description,parameters:{...a.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:a.type,name:a.function.name,description:a.function.description,parameters:a.function.parameters})),s&&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 ce(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 ce(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 ye(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="",c=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:d,done:p}=await a.read();if(p||(d&&(i+=c.decode(d,{stream:!0})),an(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}):an(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="",c,l,u,d,p="",f=new Map,h=new Map,m=0,y=!1,g=!1,_=!1,b=this,k=new ReadableStream({start(v){let T=(S,I=null)=>{v.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[{index:0,delta:S,finish_reason:I}]})}
4
+ `);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?Qs(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&&Qs(e,t,s,a.trim()),s++),Vs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Vs(e,t,s)}finally{r.releaseLock()}})()}var Zl,ql,Le,Io,it=E(()=>{"use strict";Zl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),ql=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},Io=!1});function ei(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([l,u])=>{u&&s.set(l,u)});let a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let l=new AbortController,u=()=>l.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=l.signal}else a=i;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?c.dispatcher=t.dispatcher:t.httpsProxy&&(c.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Zt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:tu(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function tu(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 ti=E(()=>{te();it()});function ou(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function ni(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Lo(n){if(ni(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(nu.some(s=>r.includes(s))){e=!0;break}ru.some(s=>r.includes(s))&&(t=!0)}}return e||ou(n)?"content":t?"empty":"pending"}async function oi(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,d)=>({verdict:u,chunks:s,bytes:i,rest:d});try{for(;;){let u=c-Date.now(),d=Symbol("timeout"),p,f=o.read(),h=u<=0?d:await Promise.race([f,new Promise(y=>{p=setTimeout(()=>y(d),u)})]);if(p&&clearTimeout(p),h===d)return l(Lo(a)==="content"?"content":"pending",en(o,f));if(h.done){a+=r.decode();let y=Lo(a);return l(y==="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=Lo(a);if(g==="content")return l("content",en(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(ni(a)||i>=e)return l("pending",en(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function en(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 ri(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 nu,ru,si=E(()=>{"use strict";nu=["content_block_start","content_block_delta","content_block_stop"];ru=["message_stop","response.completed","response.incomplete","[DONE]"]});var $o=E(()=>{"use strict"});import su from"fastify";function ii(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}function ai(n){return n?.pluginClassified===!0}var at,iu,Uo,ct=E(()=>{"use strict";$o();at=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(d){throw i=d,d}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let d=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof d!="string"||!d)throw new Error("plugin transformer has no name");if(s.transformers.has(d))throw new Error(`transformer "${d}" is already registered`);s.transformers.set(d,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,d)=>{this.assertOpen();let p=this.revision;if(s.routes.length){if(!d)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,d)}if(this.assertOpen(),this.revision!==p)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 y of s.runtimes.keys())if(g.runtimes.has(y))throw new Error(`managed runtime "${y}" is already registered`);for(let y of s.transformers.keys())if(g.transformers.has(y))throw new Error(`transformer "${y}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([y,m])=>{if(g.hasTransformer(y))throw new Error(`transformer "${y}" is already registered`);return{service:g,name:y,value:g.preparePluginTransformer(m)}})),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 y of h)y.service.removeTransformer(y.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,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,d,p)=>(r.push({...typeof d=="function"?{}:d,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:p??d}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=su({logger:!1});try{for(let i of e){let c=i(s);c!==s&&await c}for(let i of this.plugins.values())for(let c of i.preparedRoutes)a.route(c);for(let i of r){let c=Array.isArray(i.method)?i.method:[i.method];for(let l of c)if(t.hasRoute({method:l,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${l} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},iu=new at,Uo=()=>iu});function au(n,e){return`${n.name}|${e?.name??""}`}function Do(n){return n.__ccrPluginRequestState??={budgets:new Map}}function lt(n,e,t){let o=Do(n),r=au(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Fo(n,e,t,o,r){if(!e||t?.nonRetryable!==!0)return!1;let s=lt(n,e,o);return e.modelScopedRecovery&&t?.statusCode===429&&r?(s.modelErrors??=new Map).set(r,t):s.terminalError=t,!0}function jo(n,e,t,o){let r=lt(n,e,t);return r.terminalError??(o?r.modelErrors?.get(o):void 0)}var ci=E(()=>{"use strict"});function li(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 xe(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",c=a?{...a,code:i,message:`Provider plugin request failed (${i}).`}:e===0?cu(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?.(c,s)}catch{}let l=ii(n.name,c);return l.isRateLimit=c.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function cu(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 ui=E(()=>{"use strict";ct()});var tn,Ho=E(()=>{tn="2.3.2436"});var di={};wo(di,{getFallbackPromotionStore:()=>$e,resetFallbackPromotionStore:()=>du});function $e(n){return Re||(Re=new zo,n&&Re.configure(n)),Re}function du(){Re&&(Re.clearAll(),Re=null)}var uu,zo,Re,nn=E(()=>{"use strict";ce();uu=600*1e3,zo=class{promotions=new Map;enabled=!0;ttlMs=uu;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!H().isAvailable(c,u))return this.promotions.delete(s),null;let p=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=p?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!p||!f||p.enabled===!1?(this.promotions.delete(s),null):`${p.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}},Re=null});import{existsSync as mi,mkdirSync as pu,readFileSync as fu,writeFileSync as mu}from"fs";import{join as gi}from"path";import{HOME_DIR as gu}from"@wengine-ai/claude-code-router-shared";function bu(n){try{if(!mi(Wo))return;let e=JSON.parse(fu(Wo,"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 fi(n){try{let e=n.getAllStates();if(e.length===0)return;mi(Jo)||pu(Jo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));mu(Wo,JSON.stringify(t,null,2),"utf-8")}catch{}}function Ko(){if(pi)return;pi=!0;let n=H();bu(n),_u=setInterval(()=>fi(n),6e4),process.on("exit",()=>fi(n))}function H(n){return Bo||(Bo=new on(n)),Bo}var hu,yu,on,Jo,Wo,pi,_u,Bo,ce=E(()=>{"use strict";hu=120,yu={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},on=class{states=new Map;config;probeTimer;constructor(e){this.config={...yu,...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}=(nn(),Bl(di));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??hu)*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=gi(gu,"runtime"),Wo=gi(Jo,"provider-health.json"),pi=!1,_u=null;Bo=null});import{existsSync as ki,mkdirSync as ku,readFileSync as vu,writeFileSync as Tu}from"fs";import{join as vi}from"path";import{HOME_DIR as Cu}from"@wengine-ai/claude-code-router-shared";function we(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 ut(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let c=Object.keys(t).find(l=>l.toLowerCase()===i);return c?t[c]:null},r=Go(o,Su),s=Go(o,xu),a=Go(o,Ru);(r||s||a)&&Ne.set(n,{provider:n,remaining:_i(r),limit:_i(s),reset:Pu(a),capturedAt:Date.now()})}function wu(n){return Ne.get(n)}function Yo(){return Array.from(Ne.values())}function rn(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Go(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function _i(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Pu(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=Eu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Eu(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 Au(){try{if(!ki(Vo))return;let n=JSON.parse(vu(Vo,"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 bi(){try{if(Ne.size===0)return;ki(Qo)||ku(Qo,{recursive:!0}),Tu(Vo,JSON.stringify(Array.from(Ne.values()),null,2),"utf-8")}catch{}}function dt(){hi||(hi=!0,Au(),yi=setInterval(bi,6e4),yi.unref?.(),process.on("exit",bi))}var Qo,Vo,Ne,hi,yi,Su,xu,Ru,ge=E(()=>{"use strict";Qo=vi(Cu,"runtime"),Vo=vi(Qo,"rate-limit.json"),Ne=new Map,hi=!1,yi=null,Su=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],xu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Ru=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function an(){return Xo||(Xo=new qo),Xo}function tr(){return Zo||(Zo=new er),Zo}function Ou(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function Ti(n){let e=Ou(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 Ci(n,e){let t=an(),o=n?.[sn];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[sn]=t.acquire(e)}function nr(n){let e=n?.[sn];e&&an().release(e)}function Si(n,e){let t=Ti(n),o=n?.[sn],r=t?tr().get(t)!==void 0:!1;!o&&!r||(t&&tr().bind(t,e),Ci(n,e))}function Iu(n,e,t){let o=an(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function xi(n,e,t){let o=Ti(n),r=tr(),s=an(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let c=r.get(o);if(c&&c!==e){let l=t.resolve(c);l?(i=l,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${l}`)):r.unbind(o)}else c&&(i=e)}if(!i){let c=s.count(e);if(c>=a){let l=Iu(e,t.fallbackModels,t.resolve);l&&(i=l,t.log?.(`Concurrency priority: model ${e} has ${c} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${l}`))}i=i||e,o&&r.bind(o,i)}return Ci(n,i),i}var qo,er,Xo,Zo,sn,cn=E(()=>{"use strict";qo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},er=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()}},Xo=null,Zo=null;sn="__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 pt(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function Ue(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function le(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:c}=await o.read();if(c||(i&&(s+=r.decode(i,{stream:!0})),Ue(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:Ue(s)}}async function ye(n){try{let e=await n.text();if(Ue(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=E(()=>{"use strict"});function Lu(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 ln(n){for(let e of Lu(n))if(e.startsWith("response."))return!0;return!1}var De,or=E(()=>{"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){e={...e};let t=e.stream_options;if(t&&Object.hasOwn(t,"include_usage")){let{include_usage:s,...a}=t;Object.keys(a).length?e.stream_options=a:delete e.stream_options}delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let o=[],r=e.messages.filter(s=>s.role==="system");if(r.length>0){let s=r[0];Array.isArray(s.content)?s.content.forEach(a=>{let i="";typeof a=="string"?i=a:a&&typeof a=="object"&&"text"in a&&(i=a.text),o.push({role:"system",content:i})}):e.instructions=s.content}if(e.messages.forEach(s=>{if(s.role==="system")return;if(Array.isArray(s.content)){let c=s.content.map(l=>this.normalizeRequestContent(l,s.role)).filter(l=>l!==null);c.length>0?s.content=c:delete s.content}if(s.role==="tool"){let c={...s};c.type="function_call_output",c.call_id=s.tool_call_id,c.output=s.content,delete c.cache_control,delete c.role,delete c.tool_call_id,delete c.content,o.push(c);return}if(s.role==="assistant"&&Array.isArray(s.tool_calls)){s.tool_calls.forEach(c=>{o.push({type:"function_call",arguments:c.function.arguments,name:c.function.name,call_id:c.id})});return}let{thinking:a,...i}=s;s.role==="assistant"&&i.content===void 0||o.push(i)}),e.input=o,delete e.messages,Array.isArray(e.tools)){let s=e.tools.find(a=>a.function.name==="web_search");e.tools=e.tools.filter(a=>a.function.name!=="web_search").map(a=>(a.function.name==="WebSearch"&&delete a.function.parameters.properties.allowed_domains,a.function.name==="Edit"?{type:a.type,name:a.function.name,description:a.function.description,parameters:{...a.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:a.type,name:a.function.name,description:a.function.description,parameters:a.function.parameters})),s&&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 le(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 le(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 ye(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="",c=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:d,done:p}=await a.read();if(p||(d&&(i+=c.decode(d,{stream:!0})),ln(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}):ln(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="",c,l,u,d,p="",f=new Map,h=new Map,g=0,y=!1,m=!1,b=!1,_=this,k=new ReadableStream({start(v){let T=(C,I=null)=>{v.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[{index:0,delta:C,finish_reason:I}]})}
6
6
 
7
- `))},x=S=>{if(!S)return;let I=b.getCacheReadInputTokens(S),M=typeof S.input_tokens=="number"?S.input_tokens:void 0,N=b.getCacheCreationInputTokens(S);v.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||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
+ `))},S=C=>{if(!C)return;let I=_.getCacheReadInputTokens(C),M=typeof C.input_tokens=="number"?C.input_tokens:void 0,N=_.getCacheCreationInputTokens(C);v.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[],usage:{prompt_tokens:M,completion_tokens:typeof C.output_tokens=="number"?C.output_tokens:void 0,total_tokens:C.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
- `))},w=S=>{y||(y=!0,v.enqueue(r.encode(`data: ${JSON.stringify({error:{message:S,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
9
+ `))},w=C=>{y||(y=!0,v.enqueue(r.encode(`data: ${JSON.stringify({error:{message:C,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
10
10
 
11
- `)))},E=S=>{g||(g=!0,x(u),T({},S))},C=()=>{_||(_=!0,v.enqueue(r.encode(`data: [DONE]
11
+ `)))},P=C=>{m||(m=!0,S(u),T({},C))},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 m++;let N=f.get(M);if(N!==void 0)return N;let L=m++;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},F=S=>{let I=!1;for(let M of Array.isArray(S)?S:[])if(M?.type==="function_call"){p="tool";let N=A(M,void 0),L=M.call_id||M.id;L&&h.set(N,L),T({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&&(p="text",T({role:"assistant",content:N.text}),I=!0);return I},R=S=>{switch(S?.response?.model&&(c=S.response.model),S?.response?.id&&(l=S.response.id),S?.type){case"response.output_item.added":{let I=S.item;if(I?.type!=="function_call")return;p="tool";let M=A(I,S.output_index),N=I.call_id||I.id;N&&h.set(M,N),T({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);p="tool";let M=h.get(I);T({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;p="annotation",T({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;p="thinking",T({thinking:{content:S.delta}});return}case"response.output_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;p="text";let I=d!==S.item_id;d=S.item_id;let M={content:S.delta};I&&(M.role="assistant"),T(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(p===""&&F(I),!M&&p===""){let N=String(S.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(p==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=S.response?.usage;let I=String(S.response?.incomplete_details?.reason??"");p===""&&F(Array.isArray(S.response?.output)?S.response.output:[]);let M=I==="max_output_tokens"||I==="max_tokens";if(p===""){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=S.response?.error||S.error||void 0;w(I?.message||"Upstream Responses stream failed before completing");return}case"error":{w(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 D=L.slice(5).trim();if(!D)continue;if(D==="[DONE]"){C();continue}let z;try{z=JSON.parse(D)}catch{continue}R(z)}}if(i+=o.decode(),i.trim().startsWith("data:")){let S=i.trim().slice(5).trim();if(S&&S!=="[DONE]")try{R(JSON.parse(S))}catch{}}!y&&!g&&(p===""?w("Upstream Responses stream ended before any output"):E(p==="tool"?"tool_calls":"stop")),y||C()}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 p=0;p<8&&i.length<65536;p++){let{value:f,done:h}=await a.read();if(h||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),an(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 c=i.includes("message_start")||i.includes("content_block_start"),l=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")||an(i))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(l&&!c){let p=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let d=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await 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,c=!1,l=!1,u="",d=-1,p=[],f=(m,y)=>r.encode(`event: ${m}
13
+ `)))},A=(C,I)=>{let M=C?.call_id||C?.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),C?.call_id&&C?.id?(f.set(C.id,L),I!==void 0&&f.set(`idx_${I}`,L)):C?.id&&I!==void 0&&f.set(`idx_${I}`,L),L},D=C=>{let I=!1;for(let M of Array.isArray(C)?C:[])if(M?.type==="function_call"){p="tool";let N=A(M,void 0),L=M.call_id||M.id;L&&h.set(N,L),T({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&&(p="text",T({role:"assistant",content:N.text}),I=!0);return I},x=C=>{switch(C?.response?.model&&(c=C.response.model),C?.response?.id&&(l=C.response.id),C?.type){case"response.output_item.added":{let I=C.item;if(I?.type!=="function_call")return;p="tool";let M=A(I,C.output_index),N=I.call_id||I.id;N&&h.set(M,N),T({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:C.item_id},C.output_index);p="tool";let M=h.get(I);T({tool_calls:[{index:I,...M?{id:M,type:"function"}:{},function:{arguments:typeof C.delta=="string"?C.delta:""}}]});return}case"response.output_text.annotation.added":{let I=C.annotation;if(!I)return;p="annotation",T({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 C.delta!="string"||C.delta.length===0)return;p="thinking",T({thinking:{content:C.delta}});return}case"response.output_text.delta":{if(typeof C.delta!="string"||C.delta.length===0)return;p="text";let I=d!==C.item_id;d=C.item_id;let M={content:C.delta};I&&(M.role="assistant"),T(M);return}case"response.completed":{u=C.response?.usage;let I=Array.isArray(C.response?.output)?C.response.output:[],M=I.some(N=>N?.type==="function_call");if(p===""&&D(I),!M&&p===""){let N=String(C.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}P(p==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=C.response?.usage;let I=String(C.response?.incomplete_details?.reason??"");p===""&&D(Array.isArray(C.response?.output)?C.response.output:[]);let M=I==="max_output_tokens"||I==="max_tokens";if(p===""){w(`Upstream Responses stream produced no content (${I||"incomplete"})`);return}P(M?"length":I==="content_filter"?"content_filter":"stop");return}case"response.failed":{let I=C.response?.error||C.error||void 0;w(I?.message||"Upstream Responses stream failed before completing");return}case"error":{w(C.error?.message||C.message||"Upstream Responses stream error");return}default:return}},O=e.getReader();(async()=>{try{for(;;){let{done:C,value:I}=await O.read();if(C)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 z;try{z=JSON.parse(F)}catch{continue}x(z)}}if(i+=o.decode(),i.trim().startsWith("data:")){let C=i.trim().slice(5).trim();if(C&&C!=="[DONE]")try{x(JSON.parse(C))}catch{}}!y&&!m&&(p===""?w("Upstream Responses stream ended before any output"):P(p==="tool"?"tool_calls":"stop")),y||R()}catch(C){console.error("Responses\u2192Chat stream error:",C);try{v.error(C)}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 p=0;p<8&&i.length<65536;p++){let{value:f,done:h}=await a.read();if(h||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),ln(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 c=i.includes("message_start")||i.includes("content_block_start"),l=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")||ln(i))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(l&&!c){let p=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let d=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await 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,c=!1,l=!1,u="",d=-1,p=[],f=(g,y)=>r.encode(`event: ${g}
14
14
  data: ${JSON.stringify(y)}
15
15
 
16
- `),h=(m,y=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:m,model:s,output:y,usage:this.buildResponsesUsage()});return new ReadableStream({async start(m){try{let y=e.getReader(),g="",_=!1,b=k=>{if(!_){_=!0;for(let v of p)if(v.type==="function_call"){let T=p.indexOf(v);m.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:v.call_id||v.id,output_index:T,arguments:v.arguments||""})),v.status="completed",m.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:T,item:v}))}for(let v of p)if(v.type==="message"){let T=p.indexOf(v);v.status="completed",m.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:T,item:v}))}m.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:p.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:v}=await y.read();if(k)break;g+=o.decode(v,{stream:!0});let T=g.split(`
17
- `);g=T.pop()||"";for(let x of T){let w=x.trim();if(!w||w.startsWith("event:")||!w.startsWith("data:"))continue;let E=w.slice(5).trim();if(E==="[DONE]"){b({}),m.enqueue(r.encode(`data: [DONE]
16
+ `),h=(g,y=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:g,model:s,output:y,usage:this.buildResponsesUsage()});return new ReadableStream({async start(g){try{let y=e.getReader(),m="",b=!1,_=k=>{if(!b){b=!0;for(let v of p)if(v.type==="function_call"){let T=p.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:T,arguments:v.arguments||""})),v.status="completed",g.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:T,item:v}))}for(let v of p)if(v.type==="message"){let T=p.indexOf(v);v.status="completed",g.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:T,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:p.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:v}=await y.read();if(k)break;m+=o.decode(v,{stream:!0});let T=m.split(`
17
+ `);m=T.pop()||"";for(let S of T){let w=S.trim();if(!w||w.startsWith("event:")||!w.startsWith("data:"))continue;let P=w.slice(5).trim();if(P==="[DONE]"){_({}),g.enqueue(r.encode(`data: [DONE]
18
18
 
19
- `));continue}let C;try{C=JSON.parse(E)}catch{continue}c||(c=!0,m.enqueue(f("response.created",{type:"response.created",response:h("in_progress")})),m.enqueue(f("response.in_progress",{type:"response.in_progress",response:h("in_progress")})));let A=C.choices?.[0];if(!A)continue;let F=A.delta;if(F?.content){if(!l){l=!0;let R=i++,O={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};p.push(O),m.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:R,item:O}))}m.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:F.content}))}if(Array.isArray(F?.tool_calls))for(let R of F.tool_calls){if(R.id){u=R.id,d=i++;let O={id:R.id,type:"function_call",status:"in_progress",call_id:R.id,name:R.function?.name||"",arguments:""};p.push(O),m.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:d,item:O}))}if(R.function?.arguments){m.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:d,delta:R.function.arguments}));let O=p.find(S=>S.call_id===u);O&&(O.arguments+=R.function.arguments)}}A.finish_reason&&b(C)}}_||b({}),m.close()}catch(y){m.error(y)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",c="",l=-1,u="",d="",p="",f=-1,h="",m="",y=-1,g=0,_=!1,b=!1,k=!1,v=!1,T=null,x=[],w=(O,S)=>r.encode(`event: ${O}
20
- data: ${JSON.stringify(S)}
19
+ `));continue}let R;try{R=JSON.parse(P)}catch{continue}c||(c=!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(!l){l=!0;let x=i++,O={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};p.push(O),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:x,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 x of D.tool_calls){if(x.id){u=x.id,d=i++;let O={id:x.id,type:"function_call",status:"in_progress",call_id:x.id,name:x.function?.name||"",arguments:""};p.push(O),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:d,item:O}))}if(x.function?.arguments){g.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:d,delta:x.function.arguments}));let O=p.find(C=>C.call_id===u);O&&(O.arguments+=x.function.arguments)}}A.finish_reason&&_(R)}}b||_({}),g.close()}catch(y){g.error(y)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",c="",l=-1,u="",d="",p="",f=-1,h="",g="",y=-1,m=0,b=!1,_=!1,k=!1,v=!1,T=null,S=[],w=(O,C)=>r.encode(`event: ${O}
20
+ data: ${JSON.stringify(C)}
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()}),C=()=>{_||(_=!0,R.enqueue(w("response.created",{type:"response.created",response:E("in_progress")})),R.enqueue(w("response.in_progress",{type:"response.in_progress",response:E("in_progress")})))},A=(O,S)=>{R.enqueue(w("response.output_item.done",{type:"response.output_item.done",output_index:O,item:{...S,status:"completed"}}))},F=O=>{if(!v){if(v=!0,b){let S=x.find(I=>I.type==="message");S&&(S.content=[{type:"output_text",text:i}],S.status="completed")}for(let S of x)S.type==="function_call"&&(S.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:x,usage:O?{...this.buildResponsesUsage(O)}:this.buildResponsesUsage()}})}},R;return new ReadableStream({async start(O){R=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 D=I.split(`
23
- `);I=D.pop()||"";for(let z of D){let q=z.trim();if(!q||q.startsWith("event:")||!q.startsWith("data:"))continue;let W=q.slice(5).trim();if(W==="[DONE]")continue;let B;try{B=JSON.parse(W)}catch{continue}if(B.type==="message_start"&&(a=B.message?.id||a,C()),B.type==="content_block_start"){let $=B.content_block;if(T=$?.type||null,$?.type==="tool_use"){u=$.id||"",d=$.name||"",p="",f=g++;let K={id:u,type:"function_call",status:"in_progress",call_id:u,name:d,arguments:""};x.push(K),R.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:f,item:K}))}if($?.type==="thinking"&&(h=$.thinking||"",!k)){k=!0,y=g++,m=`rs_${a}`;let K={id:m,type:"reasoning",status:"in_progress",summary:[]};x.push(K),R.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:y,item:K}))}if($?.type==="text"&&(i=$?.text||"",!b)){b=!0,l=g++,c=`${a}_msg`;let K={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};x.push(K),R.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:l,item:K}))}}if(B.type==="content_block_delta"){let $=B.delta;if($?.type==="text_delta"){if(!b){b=!0,l=g++,c=`${a}_msg`;let K={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};x.push(K),R.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:l,item:K}))}i+=$.text||"",R.enqueue(w("response.output_text.delta",{type:"response.output_text.delta",item_id:c,output_index:l,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(h+=$.thinking||"",R.enqueue(w("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:m||`rs_${a}`,output_index:y>=0?y:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(p+=$.partial_json||"",R.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(B.type==="content_block_stop"){if(T==="tool_use"&&u){R.enqueue(w("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:p}));let $=x.find(K=>K.call_id===u);$&&($.arguments=p,$.status="completed"),$&&A(f,$)}if(T==="text"&&b){R.enqueue(w("response.output_text.done",{type:"response.output_text.done",item_id:c,output_index:l,content_index:0,text:i}));let $=x.find(K=>K.type==="message");$&&($.content=[{type:"output_text",text:i}],A(l,$))}if(T==="thinking"&&k){let $=x.find(K=>K.type==="reasoning");$&&($.summary=[{type:"summary_text",text:h}],A(y,$))}T=null}if(B.type==="message_delta"){let $=F(B.usage);$&&R.enqueue($)}if(B.type==="message_stop"){let $=F();$&&R.enqueue($),R.enqueue(r.encode(`data: [DONE]
22
+ `),P=(O,C=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:O,model:s,output:C,usage:this.buildResponsesUsage()}),R=()=>{b||(b=!0,x.enqueue(w("response.created",{type:"response.created",response:P("in_progress")})),x.enqueue(w("response.in_progress",{type:"response.in_progress",response:P("in_progress")})))},A=(O,C)=>{x.enqueue(w("response.output_item.done",{type:"response.output_item.done",output_index:O,item:{...C,status:"completed"}}))},D=O=>{if(!v){if(v=!0,_){let C=S.find(I=>I.type==="message");C&&(C.content=[{type:"output_text",text:i}],C.status="completed")}for(let C of S)C.type==="function_call"&&(C.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:S,usage:O?{...this.buildResponsesUsage(O)}:this.buildResponsesUsage()}})}},x;return new ReadableStream({async start(O){x=O;try{let C=e.getReader(),I="";for(;;){let{done:N,value:L}=await C.read();if(N)break;I+=o.decode(L,{stream:!0});let F=I.split(`
23
+ `);I=F.pop()||"";for(let z of F){let q=z.trim();if(!q||q.startsWith("event:")||!q.startsWith("data:"))continue;let W=q.slice(5).trim();if(W==="[DONE]")continue;let B;try{B=JSON.parse(W)}catch{continue}if(B.type==="message_start"&&(a=B.message?.id||a,R()),B.type==="content_block_start"){let $=B.content_block;if(T=$?.type||null,$?.type==="tool_use"){u=$.id||"",d=$.name||"",p="",f=m++;let K={id:u,type:"function_call",status:"in_progress",call_id:u,name:d,arguments:""};S.push(K),x.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:f,item:K}))}if($?.type==="thinking"&&(h=$.thinking||"",!k)){k=!0,y=m++,g=`rs_${a}`;let K={id:g,type:"reasoning",status:"in_progress",summary:[]};S.push(K),x.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:y,item:K}))}if($?.type==="text"&&(i=$?.text||"",!_)){_=!0,l=m++,c=`${a}_msg`;let K={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};S.push(K),x.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:l,item:K}))}}if(B.type==="content_block_delta"){let $=B.delta;if($?.type==="text_delta"){if(!_){_=!0,l=m++,c=`${a}_msg`;let K={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};S.push(K),x.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:l,item:K}))}i+=$.text||"",x.enqueue(w("response.output_text.delta",{type:"response.output_text.delta",item_id:c,output_index:l,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(h+=$.thinking||"",x.enqueue(w("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:g||`rs_${a}`,output_index:y>=0?y:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(p+=$.partial_json||"",x.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(B.type==="content_block_stop"){if(T==="tool_use"&&u){x.enqueue(w("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:p}));let $=S.find(K=>K.call_id===u);$&&($.arguments=p,$.status="completed"),$&&A(f,$)}if(T==="text"&&_){x.enqueue(w("response.output_text.done",{type:"response.output_text.done",item_id:c,output_index:l,content_index:0,text:i}));let $=S.find(K=>K.type==="message");$&&($.content=[{type:"output_text",text:i}],A(l,$))}if(T==="thinking"&&k){let $=S.find(K=>K.type==="reasoning");$&&($.summary=[{type:"summary_text",text:h}],A(y,$))}T=null}if(B.type==="message_delta"){let $=D(B.usage);$&&x.enqueue($)}if(B.type==="message_stop"){let $=D();$&&x.enqueue($),x.enqueue(r.encode(`data: [DONE]
24
24
 
25
- `))}}}C();let M=F();M&&R.enqueue(M),I="",R.close()}catch(S){R.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(l=>l.type==="message"),o;t?.content?.length&&t?.content[0].annotations&&(o=t.content[0].annotations.map(l=>({type:"url_citation",url_citation:{url:l.url||"",title:l.title||"",content:"",start_index:l.start_index||0,end_index:l.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let r=null,s=null,a=null;if(t&&t.reasoning&&(a={content:t.reasoning}),t&&t.content){let l=[],u=[];if(t.content.forEach(d=>{if(d.type==="output_text")l.push(d.text||"");else if(d.type==="output_image"){let p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&u.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&u.push(p)}}),u.length>0){let d=[];l.length>0&&d.push({type:"text",text:l.join("")}),d.push(...u),r=d}else r=l.join("")}let i=(e.output??[]).filter(l=>l.type==="function_call");return i.length>0&&(s=i.map(l=>({id:l.call_id||l.id,type:"function",function:{name:l.name,arguments:l.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 or,Y,cn=P(()=>{"use strict";or=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 or(100)});import{existsSync as Pi,mkdirSync as Iu,readFileSync as Mu,writeFileSync as Lu}from"fs";import{join as Ei}from"path";import{HOME_DIR as $u}from"@wengine-ai/claude-code-router-shared";function ft(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function ln(n){let e=Fe.get(n);return e?{...e}:void 0}function ir(){return Array.from(Fe.values()).map(n=>({...n}))}function Nu(){try{if(!Pi(sr))return;let n=JSON.parse(Mu(sr,"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 wi(){try{if(Fe.size===0)return;Pi(rr)||Iu(rr,{recursive:!0}),Lu(sr,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function mt(){xi||(xi=!0,Nu(),Ri=setInterval(wi,6e4),Ri.unref?.(),process.on("exit",wi))}var rr,sr,Fe,xi,Ri,Pe=P(()=>{"use strict";rr=Ei($u,"runtime"),sr=Ei(rr,"quota-store.json"),Fe=new Map,xi=!1,Ri=null});function _e(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Uu.test(e)))return e}function be(n){if(!n)return;if(typeof n=="object")return _e(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=_e(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return _e(e.slice(o+t.length))}var Uu,je=P(()=>{"use strict";Uu=/^[A-Za-z0-9_-]+$/});import{existsSync as Ii}from"fs";import{readFile as Du,readdir as Fu}from"fs/promises";import{homedir as ju}from"os";import{isAbsolute as Hu,join as gt,normalize as zu}from"path";import{openSqliteDatabase as Bu}from"@wengine-ai/claude-code-router-shared";function Xu(){if(He.size<=Ai)return;let n=[...He.keys()].slice(0,He.size-Ai);for(let e of n)He.delete(e)}function Zu(){if(ze.size<=Oi)return;let n=[...ze].slice(0,ze.size-Oi);for(let e of n)ze.delete(e)}function qu(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 ed(n,e){let t;try{t=Bu(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 td(n,e){let t;try{t=await Fu(n)}catch{return null}for(let o of t)for(let r of e){let s=gt(n,o,`${r}.json`);if(Ii(s))try{let a=JSON.parse(await Du(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Mi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=He.get(e);if(t)return t;let o=async()=>{let r=qu(e);if(r.length===0)return null;let s=gt(Ju(),Wu),a=gt(s,Ku);if(Ii(a)){let i=ed(a,r);if(i)return i}return td(gt(s,Gu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),Zu();for(let a=0;a<Qu&&!r;a++)await Yu(Vu),r=await o()}if(!r||!Hu(r))return null;let s=zu(r);return He.set(e,s),Xu(),s}catch{return null}}var Ju,Wu,Ku,Gu,Ai,Oi,Qu,Vu,He,ze,Yu,Li=P(()=>{"use strict";Ju=()=>process.env.CCR_ZCODE_DIR||gt(ju(),".zcode"),Wu="v2",Ku="tasks-index.sqlite",Gu="sessions",Ai=500,Oi=500,Qu=3,Vu=50,He=new Map,ze=new Set,Yu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as nd}from"node:crypto";import{CCR_PROJECT_HEADER as ar}from"@wengine-ai/claude-code-router-shared";function Ui(n){return typeof n=="string"&&n.length<=od}function rd(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Ni){let{value:t}=un(n,e);if(!Ui(t))continue;let o=_e(t);if(o)return o}}function id(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 ad(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 un(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function $i(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function ht(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function cr(n,e,t=!0){let o=be(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Fi(n){return typeof n=="string"&&sd.includes(n)}function hd(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(Fi(n?.clientType))return n.clientType;let e=ad(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=id(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(un(n,ar).present||un(n,"x-session-affinity").present)return"pi";if(hd(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 ji(n){return Di[n]}function yd(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||nd();return n.__ccrRequestScopeId=e,e}function Ee(n,e={}){let t=Be(n),o=ji(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:yd(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,$i(n,ar),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Ni)$i(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function _d(){}var Ni,od,sd,cd,ld,ud,dd,pd,fd,md,gd,Di,Je=P(()=>{"use strict";je();Ni=["x-session-affinity","x-session-id","x-litellm-session-id"],od=256;sd=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];cd={type:"claude-code",createContext(n){return cr(n,"claude-code")}},ld={type:"zcode",createContext(n){return cr(n,"zcode")}},ud={type:"pi",createContext(n){let e=un(n,ar),t=rd(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||be(n?.body?.metadata?.user_id),o=Ui(t)?t:void 0;return{...ht("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},dd={type:"qwen-code",createContext(n){return cr(n,"qwen-code")}},pd={type:"opencode",createContext(){return ht("opencode")}},fd={type:"codex",createContext(){return ht("codex")}},md={type:"api",createContext(){return ht("api")}},gd={type:"unknown",createContext(){return ht("unknown")}},Di={"claude-code":cd,zcode:ld,pi:ud,"qwen-code":dd,opencode:pd,codex:fd,api:md,unknown:gd}});import{get_encoding as kd}from"tiktoken";import{readFile as lr}from"fs/promises";import{opendir as vd,stat as Td}from"fs/promises";import{isAbsolute as Cd,join as ur}from"path";import{CLAUDE_PROJECTS_DIR as Hi,HOME_DIR as zi,getClaudeProjectId as Bi,isCcrSelfProvider as Sd,isZcodeProjectTakeoverActive as xd}from"@wengine-ai/claude-code-router-shared";function ne(n,e,t,o){let r=Qi(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=Gi[r.code]||502;throw new oe(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function pn(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 _t(n){let e=pn(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 wd(n,e){if(!e||!n)return null;let t=pn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=_t(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=pn(r);if(a&&t.includes(a))return s}return null}function Pd(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function dn(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function yt(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Qi(n,e){let t=dn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!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 c=ln(s.name);if(c){let l=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,u=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(l||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function Q(n,e,t,o,r,s,a){let i=dn(n);if(!i)return a?null:n;let{providerName:c,routeModel:l}=i,u=yt(e,c,l);if(!u){if(r===!0&&o&&!t&&s!==!1){let p=$e(),f=p.getPromotion(c,l,o,e);if(f){let h=dn(f);if(h){let m=yt(e,h.providerName,h.routeModel);if(m)return`${m.provider.name},${m.model}`}p.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let p=$e(),f=p.getPromotion(c,l,o,e);if(f){let h=dn(f);if(h){let m=yt(e,h.providerName,h.routeModel);if(m)return`${m.provider.name},${m.model}`}p.clear(c,l,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 d=ln(u.provider.name);if(d){let p=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,f=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(p||f)return null}return`${u.provider.name},${u.model}`}function ee(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 c of i){let l=Q(c,e,!1,n,void 0,void 0,s);if(l)return l}return null}function Ed(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 bt(n){let e=pn(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 Vi(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Pd(e))}function Yi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Ad(n,e,t,o,r,s,a,i,c,l,u,d){let p=n.clientContext,f=p?.longContextThreshold??t.longContextThreshold??c??6e4,h=Vi(e,r,p),m=n.modelFamily,y=Yi(p,t,l),g=p?.supportsExplicitExtendedContext!==!1&&s===!0;if((g||h>y)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,d,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${g}, threshold: ${y}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let v=i?ee("extendedContext",o,t.fallback,a,m,u):null;if(v)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${g}, threshold: ${y}`),{model:v,scenarioType:"extendedContext",isFallback:!0};if(u){let T=ne(n,t.extendedContext,o,"extendedContext");if(T)return{model:T,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,d,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?ee("longContext",o,t.fallback,a,m,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 T=ne(n,t.longContext,o,"longContext");if(T)return{model:T,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,d,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let v=i?ee("webSearch",o,t.fallback,a,m,u):null;if(v)return n.log.info("Family: using webSearch fallback model"),{model:v,scenarioType:"webSearch",isFallback:!0};if(u){let T=ne(n,t.webSearch,o,"webSearch");if(T)return{model:T,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,d,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let v=i?ee("think",o,t.fallback,a,m,u):null;if(v)return n.log.info("Family: using think fallback model"),{model:v,scenarioType:"think",isFallback:!0};if(u){let T=ne(n,t.think,o,"think");if(T)return{model:T,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default||i&&t.fallback?.default?.length){let k=t.default?Q(t.default,o,!1,"default",i,d,u):null;if(k)return{model:k,scenarioType:"default",isFallback:!1};let v=i?ee("default",o,t.fallback,a,m,u):null;if(v)return n.log.info("Family: using default fallback model"),{model:v,scenarioType:"default",isFallback:!0};if(u&&t.default){let T=ne(n,t.default,o,"default");if(T)return{model:T,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function $d(){if(Ae.size<=Ji)return;let n=[...Ae.keys()].slice(0,Ae.size-Ji);for(let e of n)Ae.delete(e)}function Nd(){if(We.size<=Wi)return;let n=[...We].slice(0,We.size-Wi);for(let e of n)We.delete(e)}var Gi,oe,pe,fn,Rd,Od,mn,Ae,Ji,We,Wi,Id,Md,Ld,Ki,Xi,Oe=P(()=>{"use strict";cn();ae();Pe();en();sn();je();Li();Je();Gi={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},oe=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Gi[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};pe=kd("cl100k_base"),fn=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=pe.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=pe.encode(s.text).length;else if(s.type==="tool_use")o+=pe.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+=pe.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=pe.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=pe.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=pe.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=pe.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=pe.encode(r.name+r.description).length),r.input_schema&&(o+=pe.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 oe(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Xi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Mi(n.sessionId);s&&xd(s)&&(r=Bi(s))}if(r){n.projectId=r;let s=ur(zi,r,"config.json");if(!t&&n.sessionId){let a=ur(zi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await lr(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await lr(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Bi(a.projectPath)!==o))throw new oe(`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 oe)throw a;if(t&&a?.code==="ENOENT")throw new oe(`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 oe(`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})}}}};Od=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,d=!s,p=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let R=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);R&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${R[1]}</CCR-SUBAGENT-MODEL>`,""),p=R[1])}let f=typeof n.body?.model=="string"?n.body.model:"",h=f.indexOf(",")>0,y=(h?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),g,_;if(!s&&y)for(let R of a){if(R?.enabled===!1||!Array.isArray(R?.models)||n.pathname?.endsWith("/v1/chat/completions")&&Sd(R))continue;let O=R.models.find(S=>typeof S=="string"&&S.toLowerCase()===y);if(O){g=R,_=O;break}}let{family:b,extended:k,isCcrAlias:v}=_t(n.body.model),T=i?.families?.[b||""];if(T&&i?.enableFamilyRouting&&!g){n.log.info(`Using model family routing for: ${b}${k?" (1M)":""}`),n.modelFamily=b,n.familyFallback=T.fallback;let R=Ad(n,e,T,a,o,k,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,d);if(R)return{model:R.model,scenarioType:R.scenarioType}}if(h&&g&&_){let R=`${g.name},${_}`;n.body.model!==R&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${R}`),n.body.model=R)}if(n.body.model.includes(",")&&!s){let R=Q(n.body.model,a,!1,"default",c,d,s);if(R)return{model:R,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=c?ee("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 x=v&&!i?.enableFamilyRouting?null:wd(n.body.model,i?.models);if(x){let R=Q(x,a,!1,"modelMapping",c,d,s);if(R)return n.log.info(`Using mapped model for ${n.body.model}: ${x}`),{model:R,scenarioType:"modelMapping"};let O=c?ee("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let S=ne(n,x,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${x} unavailable (fail pool), skipping`)}if(g&&!h){let R=`${g.name},${_}`;return n.log.info(`Exact provider model ${f} routes to ${R}`),{model:R,scenarioType:"default"}}let w=n.clientContext,E=Vi(e,o,w),C=Yi(w,void 0,i?.extendedContextThreshold);if(E>C&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${E}, estimated: ${e}, threshold: ${C}`);let R=Q(i.extendedContext,a,!1,"extendedContext",c,d,s);if(R)return{model:R,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=c?ee("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let S=ne(n,i.extendedContext,a,"extendedContext");if(S)return{model:S,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 R=Q(i.longContext,a,!1,"longContext",c,d,s);if(R)return{model:R,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=c?ee("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let S=ne(n,i.longContext,a,"longContext");if(S)return{model:S,scenarioType:"longContext"}}}if(!s&&p)return n.subagentOverrideModel=p,{model:p,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 R=Q(i.background,a,!1,"background",c,d,s);if(R)return{model:R,scenarioType:"background"};let O=c?ee("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let S=ne(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(R=>R.type?.startsWith("web_search"))&&i?.webSearch){let R=Q(i.webSearch,a,!1,"webSearch",c,d,s);if(R)return{model:R,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=c?ee("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let S=ne(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 R=Q(i.think,a,!1,"think",c,d,s);if(R)return{model:R,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=c?ee("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let S=ne(n,i.think,a,"think");if(S)return{model:S,scenarioType:"think"}}}if(i?.default){let R=Q(i.default,a,!1,"default",c,d,s);if(R)return{model:R,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=c?ee("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let S=Q(i.default,a,!0,"default",c,d,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 R=ne(n,i?.default||n.body.model,a,"default");if(R)return{model:R,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},mn=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ee(n,o.getAll());let s=await Rd(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,c=o.get("providers")||[],l=!!s;n.enableFallback=i,n.strictProjectRouting=l,n.fallbackConfig=l?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Y.get(n.usageCacheKey):void 0,{messages:d,system:p=[],tools:f}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&p.length>1&&p[1]?.text?.includes("<env>")){let m=await lr(h,"utf-8");p[1].text=`${m}<env>${p[1].text.split("<env>").pop()}`}try{let[m,y]=n.body.model.split(","),g=t.tokenizerService?.getTokenizerConfigForModel(m,y),_;t.tokenizerService?_=(await t.tokenizerService.countTokens({messages:d,system:p,tools:f},g,m)).tokenCount:_=fn(d,p,f),n.tokenCount=_;let b,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!Cd(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}`);b=await E(n,o.getAll(),{event:r})}catch(w){n.log.error(`failed to load custom router: ${w.message}`)}if(b)n.scenarioType="default";else{let w=await Od(n,_,o,u,s,!!s);b=w.model,n.scenarioType=w.scenarioType}let{family:v}=_t(n.originalModel||n.body.model),T=a?.enableFamilyRouting&&v?a.families?.[v]:void 0,x=[T?.image,a?.image].filter((w,E,C)=>!!w&&C.indexOf(w)===E);if(x.length>0&&Ed(n)&&!bt(b))if(x.includes(b))n.scenarioType="image";else{let w=x.map(E=>Q(E,c,!1,"image",i,!l,l)).find(E=>!!E);if(w)n.log.info(`Using image model fallback for ${b}`),b=w,n.scenarioType="image";else{let E=i?ee("image",c,T?.fallback,n.fallbackConfig,v||void 0,l):null;if(E)n.log.info(`Using image fallback model: ${E}`),b=E,n.scenarioType="image";else if(l){let C=ne(n,x[0],c,"image");C&&(b=C,n.scenarioType="image")}else n.log.warn(`Image models ${x.join(", ")} unavailable (fail pool), keeping ${b}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof b=="string"&&b.trim()){let w=n.scenarioType||"default",E=[...(n.familyFallback||{})[w]||[],...(n.fallbackConfig||{})[w]||[]];b=Si(n,b,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:E,resolve:C=>Q(C,c,!1,w,i,!l,l),log:C=>n.log.info(C)})}typeof b=="string"&&b.trim()?n.body.model=b:(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(m){if(m instanceof oe)throw m;if(n.log.error(`Error in router middleware: ${m.message}`),l){let y=n.sessionId||n.clientContext?.stableSessionId;throw new oe(`Project routing error: router failure in project mode. ${m.message}. Session: "${y||"unknown"}".`,{sessionId:y,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Ae=new Map,Ji=1e3,We=new Set,Wi=1e3,Id=3,Md=50,Ld=n=>new Promise(e=>setTimeout(e,n));Ki=async n=>{let e=await vd(Hi),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=ur(Hi,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},Xi=async n=>{let e=_e(n);if(!e)return null;if(Ae.has(e))return Ae.get(e)||null;try{let t=await Ki(e);if(!t&&!We.has(e)){We.add(e),Nd();for(let o=0;o<Id&&!t;o++)await Ld(Md),t=await Ki(e)}return t?(Ae.set(e,t),$d(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});import{CCR_SELF_PROVIDER_NAME as Ud}from"@wengine-ai/claude-code-router-shared";function kt(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&&x.enqueue(M),I="",x.close()}catch(C){x.error(C)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(l=>l.type==="message"),o;t?.content?.length&&t?.content[0].annotations&&(o=t.content[0].annotations.map(l=>({type:"url_citation",url_citation:{url:l.url||"",title:l.title||"",content:"",start_index:l.start_index||0,end_index:l.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let r=null,s=null,a=null;if(t&&t.reasoning&&(a={content:t.reasoning}),t&&t.content){let l=[],u=[];if(t.content.forEach(d=>{if(d.type==="output_text")l.push(d.text||"");else if(d.type==="output_image"){let p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&u.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&u.push(p)}}),u.length>0){let d=[];l.length>0&&d.push({type:"text",text:l.join("")}),d.push(...u),r=d}else r=l.join("")}let i=(e.output??[]).filter(l=>l.type==="function_call");return i.length>0&&(s=i.map(l=>({id:l.call_id||l.id,type:"function",function:{name:l.name,arguments:l.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 rr,Y,un=E(()=>{"use strict";rr=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 rr(100)});import{existsSync as Ei,mkdirSync as $u,readFileSync as Nu,writeFileSync as Uu}from"fs";import{join as Ai}from"path";import{HOME_DIR as Du}from"@wengine-ai/claude-code-router-shared";function ft(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function dn(n){let e=Fe.get(n);return e?{...e}:void 0}function ar(){return Array.from(Fe.values()).map(n=>({...n}))}function Fu(){try{if(!Ei(ir))return;let n=JSON.parse(Nu(ir,"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 Pi(){try{if(Fe.size===0)return;Ei(sr)||$u(sr,{recursive:!0}),Uu(ir,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function mt(){Ri||(Ri=!0,Fu(),wi=setInterval(Pi,6e4),wi.unref?.(),process.on("exit",Pi))}var sr,ir,Fe,Ri,wi,Pe=E(()=>{"use strict";sr=Ai(Du,"runtime"),ir=Ai(sr,"quota-store.json"),Fe=new Map,Ri=!1,wi=null});function _e(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!ju.test(e)))return e}function be(n){if(!n)return;if(typeof n=="object")return _e(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=_e(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return _e(e.slice(o+t.length))}var ju,je=E(()=>{"use strict";ju=/^[A-Za-z0-9_-]+$/});import{existsSync as Mi}from"fs";import{readFile as Hu,readdir as zu}from"fs/promises";import{homedir as Bu}from"os";import{isAbsolute as Ju,join as gt,normalize as Wu}from"path";import{openSqliteDatabase as Ku}from"@wengine-ai/claude-code-router-shared";function ed(){if(He.size<=Oi)return;let n=[...He.keys()].slice(0,He.size-Oi);for(let e of n)He.delete(e)}function td(){if(ze.size<=Ii)return;let n=[...ze].slice(0,ze.size-Ii);for(let e of n)ze.delete(e)}function nd(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 od(n,e){let t;try{t=Ku(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 rd(n,e){let t;try{t=await zu(n)}catch{return null}for(let o of t)for(let r of e){let s=gt(n,o,`${r}.json`);if(Mi(s))try{let a=JSON.parse(await Hu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Li(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=nd(e);if(r.length===0)return null;let s=gt(Gu(),Qu),a=gt(s,Vu);if(Mi(a)){let i=od(a,r);if(i)return i}return rd(gt(s,Yu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),td();for(let a=0;a<Xu&&!r;a++)await qu(Zu),r=await o()}if(!r||!Ju(r))return null;let s=Wu(r);return He.set(e,s),ed(),s}catch{return null}}var Gu,Qu,Vu,Yu,Oi,Ii,Xu,Zu,He,ze,qu,$i=E(()=>{"use strict";Gu=()=>process.env.CCR_ZCODE_DIR||gt(Bu(),".zcode"),Qu="v2",Vu="tasks-index.sqlite",Yu="sessions",Oi=500,Ii=500,Xu=3,Zu=50,He=new Map,ze=new Set,qu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as sd}from"node:crypto";import{CCR_PROJECT_HEADER as cr}from"@wengine-ai/claude-code-router-shared";function Di(n){return typeof n=="string"&&n.length<=id}function ad(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Ui){let{value:t}=pn(n,e);if(!Di(t))continue;let o=_e(t);if(o)return o}}function ld(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 ud(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 pn(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 Ni(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 ht(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function lr(n,e,t=!0){let o=be(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function ji(n){return typeof n=="string"&&cd.includes(n)}function bd(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(ji(n?.clientType))return n.clientType;let e=ud(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=ld(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(pn(n,cr).present||pn(n,"x-session-affinity").present)return"pi";if(bd(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 Hi(n){return Fi[n]}function kd(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||sd();return n.__ccrRequestScopeId=e,e}function Ee(n,e={}){let t=Be(n),o=Hi(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:kd(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,Ni(n,cr),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Ui)Ni(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function vd(){}var Ui,id,cd,dd,pd,fd,md,gd,hd,yd,_d,Fi,Je=E(()=>{"use strict";je();Ui=["x-session-affinity","x-session-id","x-litellm-session-id"],id=256;cd=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];dd={type:"claude-code",createContext(n){return lr(n,"claude-code")}},pd={type:"zcode",createContext(n){return lr(n,"zcode")}},fd={type:"pi",createContext(n){let e=pn(n,cr),t=ad(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||be(n?.body?.metadata?.user_id),o=Di(t)?t:void 0;return{...ht("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},md={type:"qwen-code",createContext(n){return lr(n,"qwen-code")}},gd={type:"opencode",createContext(){return ht("opencode")}},hd={type:"codex",createContext(){return ht("codex")}},yd={type:"api",createContext(){return ht("api")}},_d={type:"unknown",createContext(){return ht("unknown")}},Fi={"claude-code":dd,zcode:pd,pi:fd,"qwen-code":md,opencode:gd,codex:hd,api:yd,unknown:_d}});import{get_encoding as Cd}from"tiktoken";import{readFile as ur}from"fs/promises";import{opendir as Sd,stat as xd}from"fs/promises";import{isAbsolute as Rd,join as dr}from"path";import{CLAUDE_PROJECTS_DIR as zi,HOME_DIR as Bi,getClaudeProjectId as Ji,isCcrSelfProvider as wd,isZcodeProjectTakeoverActive as Pd}from"@wengine-ai/claude-code-router-shared";function ne(n,e,t,o){let r=Vi(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=Qi[r.code]||502;throw new oe(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function mn(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 _t(n){let e=mn(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 Ad(n,e){if(!e||!n)return null;let t=mn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=_t(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=mn(r);if(a&&t.includes(a))return s}return null}function Od(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function fn(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function yt(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Vi(n,e){let t=fn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!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 c=dn(s.name);if(c){let l=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,u=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(l||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function Q(n,e,t,o,r,s,a){let i=fn(n);if(!i)return a?null:n;let{providerName:c,routeModel:l}=i,u=yt(e,c,l);if(!u){if(r===!0&&o&&!t&&s!==!1){let p=$e(),f=p.getPromotion(c,l,o,e);if(f){let h=fn(f);if(h){let g=yt(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let p=$e(),f=p.getPromotion(c,l,o,e);if(f){let h=fn(f);if(h){let g=yt(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}p.clear(c,l,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 d=dn(u.provider.name);if(d){let p=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,f=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(p||f)return null}return`${u.provider.name},${u.model}`}function ee(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 c of i){let l=Q(c,e,!1,n,void 0,void 0,s);if(l)return l}return null}function Id(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 bt(n){let e=mn(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 Yi(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Od(e))}function Xi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Md(n,e,t,o,r,s,a,i,c,l,u,d){let p=n.clientContext,f=p?.longContextThreshold??t.longContextThreshold??c??6e4,h=Yi(e,r,p),g=n.modelFamily,y=Xi(p,t,l),m=p?.supportsExplicitExtendedContext!==!1&&s===!0;if((m||h>y)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,d,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${m}, threshold: ${y}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let v=i?ee("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: ${m}, threshold: ${y}`),{model:v,scenarioType:"extendedContext",isFallback:!0};if(u){let T=ne(n,t.extendedContext,o,"extendedContext");if(T)return{model:T,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,d,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?ee("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 T=ne(n,t.longContext,o,"longContext");if(T)return{model:T,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,d,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let v=i?ee("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 T=ne(n,t.webSearch,o,"webSearch");if(T)return{model:T,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,d,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let v=i?ee("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 T=ne(n,t.think,o,"think");if(T)return{model:T,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default||i&&t.fallback?.default?.length){let k=t.default?Q(t.default,o,!1,"default",i,d,u):null;if(k)return{model:k,scenarioType:"default",isFallback:!1};let v=i?ee("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&&t.default){let T=ne(n,t.default,o,"default");if(T)return{model:T,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function Dd(){if(Ae.size<=Wi)return;let n=[...Ae.keys()].slice(0,Ae.size-Wi);for(let e of n)Ae.delete(e)}function Fd(){if(We.size<=Ki)return;let n=[...We].slice(0,We.size-Ki);for(let e of n)We.delete(e)}var Qi,oe,pe,gn,Ed,Ld,hn,Ae,Wi,We,Ki,$d,Nd,Ud,Gi,Zi,Oe=E(()=>{"use strict";un();ce();Pe();nn();cn();je();$i();Je();Qi={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},oe=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Qi[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};pe=Cd("cl100k_base"),gn=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=pe.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=pe.encode(s.text).length;else if(s.type==="tool_use")o+=pe.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+=pe.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=pe.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=pe.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=pe.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=pe.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=pe.encode(r.name+r.description).length),r.input_schema&&(o+=pe.encode(JSON.stringify(r.input_schema)).length)}),o},Ed=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 oe(`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 Li(n.sessionId);s&&Pd(s)&&(r=Ji(s))}if(r){n.projectId=r;let s=dr(Bi,r,"config.json");if(!t&&n.sessionId){let a=dr(Bi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await ur(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await ur(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Ji(a.projectPath)!==o))throw new oe(`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 oe)throw a;if(t&&a?.code==="ENOENT")throw new oe(`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 oe(`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"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,d=!s,p=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let x=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);x&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${x[1]}</CCR-SUBAGENT-MODEL>`,""),p=x[1])}let f=typeof n.body?.model=="string"?n.body.model:"",h=f.indexOf(",")>0,y=(h?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),m,b;if(!s&&y)for(let x of a){if(x?.enabled===!1||!Array.isArray(x?.models)||n.pathname?.endsWith("/v1/chat/completions")&&wd(x))continue;let O=x.models.find(C=>typeof C=="string"&&C.toLowerCase()===y);if(O){m=x,b=O;break}}let{family:_,extended:k,isCcrAlias:v}=_t(n.body.model),T=i?.families?.[_||""];if(T&&i?.enableFamilyRouting&&!m){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=T.fallback;let x=Md(n,e,T,a,o,k,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,d);if(x)return{model:x.model,scenarioType:x.scenarioType}}if(h&&m&&b){let x=`${m.name},${b}`;n.body.model!==x&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${x}`),n.body.model=x)}if(n.body.model.includes(",")&&!s){let x=Q(n.body.model,a,!1,"default",c,d,s);if(x)return{model:x,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=c?ee("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 S=v&&!i?.enableFamilyRouting?null:Ad(n.body.model,i?.models);if(S){let x=Q(S,a,!1,"modelMapping",c,d,s);if(x)return n.log.info(`Using mapped model for ${n.body.model}: ${S}`),{model:x,scenarioType:"modelMapping"};let O=c?ee("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let C=ne(n,S,a,"modelMapping");if(C)return{model:C,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${S} unavailable (fail pool), skipping`)}if(m&&!h){let x=`${m.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${x}`),{model:x,scenarioType:"default"}}let w=n.clientContext,P=Yi(e,o,w),R=Xi(w,void 0,i?.extendedContextThreshold);if(P>R&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${P}, estimated: ${e}, threshold: ${R}`);let x=Q(i.extendedContext,a,!1,"extendedContext",c,d,s);if(x)return{model:x,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=c?ee("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let C=ne(n,i.extendedContext,a,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext"}}}let A=w?.longContextThreshold??i?.longContextThreshold??6e4;if(P>A&&i?.longContext){n.log.info(`Using long context model due to token count: ${P}, estimated: ${e}, threshold: ${A}`);let x=Q(i.longContext,a,!1,"longContext",c,d,s);if(x)return{model:x,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=c?ee("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let C=ne(n,i.longContext,a,"longContext");if(C)return{model:C,scenarioType:"longContext"}}}if(!s&&p)return n.subagentOverrideModel=p,{model:p,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 x=Q(i.background,a,!1,"background",c,d,s);if(x)return{model:x,scenarioType:"background"};let O=c?ee("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let C=ne(n,i.background,a,"background");if(C)return{model:C,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(x=>x.type?.startsWith("web_search"))&&i?.webSearch){let x=Q(i.webSearch,a,!1,"webSearch",c,d,s);if(x)return{model:x,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=c?ee("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let C=ne(n,i.webSearch,a,"webSearch");if(C)return{model:C,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let x=Q(i.think,a,!1,"think",c,d,s);if(x)return{model:x,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=c?ee("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let C=ne(n,i.think,a,"think");if(C)return{model:C,scenarioType:"think"}}}if(i?.default){let x=Q(i.default,a,!1,"default",c,d,s);if(x)return{model:x,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=c?ee("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let C=Q(i.default,a,!0,"default",c,d,s);if(C)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:C,scenarioType:"default"}}if(s){let x=ne(n,i?.default||n.body.model,a,"default");if(x)return{model:x,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},hn=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ee(n,o.getAll());let s=await Ed(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,c=o.get("providers")||[],l=!!s;n.enableFallback=i,n.strictProjectRouting=l,n.fallbackConfig=l?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Y.get(n.usageCacheKey):void 0,{messages:d,system:p=[],tools:f}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&p.length>1&&p[1]?.text?.includes("<env>")){let g=await ur(h,"utf-8");p[1].text=`${g}<env>${p[1].text.split("<env>").pop()}`}try{let[g,y]=n.body.model.split(","),m=t.tokenizerService?.getTokenizerConfigForModel(g,y),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:d,system:p,tools:f},m,g)).tokenCount:b=gn(d,p,f),n.tokenCount=b;let _,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!Rd(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),P=typeof w=="function"?w:w?.default;if(typeof P!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await P(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 Ld(n,b,o,u,s,!!s);_=w.model,n.scenarioType=w.scenarioType}let{family:v}=_t(n.originalModel||n.body.model),T=a?.enableFamilyRouting&&v?a.families?.[v]:void 0,S=[T?.image,a?.image].filter((w,P,R)=>!!w&&R.indexOf(w)===P);if(S.length>0&&Id(n)&&!bt(_))if(S.includes(_))n.scenarioType="image";else{let w=S.map(P=>Q(P,c,!1,"image",i,!l,l)).find(P=>!!P);if(w)n.log.info(`Using image model fallback for ${_}`),_=w,n.scenarioType="image";else{let P=i?ee("image",c,T?.fallback,n.fallbackConfig,v||void 0,l):null;if(P)n.log.info(`Using image fallback model: ${P}`),_=P,n.scenarioType="image";else if(l){let R=ne(n,S[0],c,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${S.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",P=[...(n.familyFallback||{})[w]||[],...(n.fallbackConfig||{})[w]||[]];_=xi(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:P,resolve:R=>Q(R,c,!1,w,i,!l,l),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 oe)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),l){let y=n.sessionId||n.clientContext?.stableSessionId;throw new oe(`Project routing error: router failure in project mode. ${g.message}. Session: "${y||"unknown"}".`,{sessionId:y,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Ae=new Map,Wi=1e3,We=new Set,Ki=1e3,$d=3,Nd=50,Ud=n=>new Promise(e=>setTimeout(e,n));Gi=async n=>{let e=await Sd(zi),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=dr(zi,s,`${n}.jsonl`);try{return(await xd(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=_e(n);if(!e)return null;if(Ae.has(e))return Ae.get(e)||null;try{let t=await Gi(e);if(!t&&!We.has(e)){We.add(e),Fd();for(let o=0;o<$d&&!t;o++)await Ud(Nd),t=await Gi(e)}return t?(Ae.set(e,t),Dd(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});import{CCR_SELF_PROVIDER_NAME as jd}from"@wengine-ai/claude-code-router-shared";function kt(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 ta(n,e,t,o){let r=n.body;n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt,(n.ccrHookOrder||=[]).push("handler"),Uo(n);let s=jd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&kt(r);let a=o.endPoint==="/v1/chat/completions";if(a&&(n.originalModel??=r?.model),(a||o.endPoint==="/v1/responses")&&!n.provider&&typeof r?.model=="string"&&dr.test(r.model)&&await mn(n,e,{configService:t.configService,tokenizerService:t.tokenizerService}),a&&!n.provider&&typeof r?.model=="string"&&dr.test(r.model))throw J("No upstream route configured for this model family",404,"provider_not_found");a&&!n.strictProjectRouting&&(n.fallbackConfig??=t.configService.get("Router")?.fallback);let i=n.provider;if(!i&&r?.model){let d=r.model.split(",");d.length>1&&(i=d[0],r.model=d.slice(1).join(","))}let c=i?t.providerService.getProvider(i):void 0;if(!c&&r?.model){let d=t.providerService.resolveModelRoute(r.model);d&&(c=d.provider,r.model=d.targetModel)}if(!c&&r?.model){let p=t.configService.get("Router")?.default;if(p&&p.includes(",")){let[f,...h]=p.split(","),m=t.providerService.getProvider(f);m&&(c=m,r.model=h.join(","))}}if(n.originalModel||(n.originalModel=r?.model),a&&c&&ua(c))throw J("The managed CCR preset cannot be a Chat upstream",400,"invalid_route");if(!c)throw J(`Provider '${i}' not found`,404,"provider_not_found");n.provider=c.name||i;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;let u=a&&dr.test(n.originalModel)&&Hd(r);if(u&&la(c,r.model,t.pluginRegistry)){let d=await Zi(n,e,t,o,void 0,u);if(d)return d;throw J("No configured Chat route supports this tool request",400,"agy_unsupported_request")}try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&kt(r);let d={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:ra(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:p,config:f,bypass:h}=await oa(r,c,o,n.headers,d);if(p?.messages&&!h&&!n.isTargetAnthropic){let _=p.messages,b=new Set,k=[],v=[];for(let T of _){if(T?.role!=="system"){v.push(T);continue}let x=JSON.stringify(T.content??"");b.has(x)||(b.add(x),k.push(T))}k.length>0&&v.length>0&&(p.messages=[...k,...v])}let m=await sa(p,f,c,t,h,o,d);try{c?.baseUrl&&m?.headers&&ut(i,c.baseUrl,m.headers)}catch{}let y=await ia(p,m,c,o,h,d);y=await na(r,y,c.name||i,n.chatCompletionCapture);let g=aa(y,e,r,t);try{let _=r.model||n.originalModel;!n.chatCompletionCapture&&i&&_&&H().recordSuccess(i,_)}catch{}return g}catch(d){if(d instanceof oe||a&&pr(d))throw d;let p=Do(n,t.pluginRegistry.getManagedRuntimeFor(c),d,c,r.model);if(a&&p&&d.statusCode===401)throw n.__fallbackExhausted=!0,d;if(!p&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await ta(n,e,t,o)}catch(h){if(n.__fallbackExhausted||a&&pr(h))throw h;d=h}}let f=await Zi(n,e,t,o,d,u);if(f)return f;throw n.__fallbackExhausted=!0,d}}async function na(n,e,t,o){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let a=e.body.getReader(),i=new TextDecoder,c=[],l="";for(let f=0;f<8;f++){let h=await a.read();if(h.done||(h.value&&(c.push(h.value),l+=i.decode(h.value,{stream:!0})),l.split(`
28
- `).some(m=>m.startsWith("data:"))))break}if(l+=i.decode(),c.length===0)throw a.releaseLock(),J(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(l.includes("event: error")){a.releaseLock(),o&&(o.streamError=!0,o.rateLimited=we(200,l));let f=l.length<500?l:l.slice(0,500);throw J(`Provider ${t} returned error in SSE stream: ${f}`,400,"provider_response_error")}if(l.split(`
29
- `).filter(f=>f.startsWith("data:")&&f.trim().length>5).length===0){a.releaseLock();let f=l.length<500?l:l.slice(0,500);throw J(`Provider ${t} returned streaming response with no SSE data lines: ${f}`,400,"provider_response_error")}let d=new ReadableStream({start:f=>{for(let m of c)f.enqueue(m);let h=()=>{a.read().then(({done:m,value:y})=>{m?f.close():(f.enqueue(y),h())}).catch(m=>f.error(m))};h()},cancel:()=>{a.cancel()}}),p=await ni(d);if(p.verdict==="empty")throw J(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(oi(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function Zi(n,e,t,o,r,s){let a=n.scenarioType||"default",i=n.familyFallback,c=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),u=H(),d=n.provider||"",p=n.body.model||"",f=new Set,h=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&vt(r.rawBody)||r?.message&&vt(r.message);if(d&&p&&f.add(`${d},${p}`),r&&d&&p&&(h?(u.markRateLimited(d,p,120,r?.message),n.log.warn(`Primary model ${d},${p} rate-limited, will try fallbacks`)):u.recordFailure(d,p,r?.message),n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt,t.recordUsage?.({provider:d,model:p,originalModel:n.originalModel||p,scenarioType:a,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.chatCompletionCapture?0: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 y=k=>{let[v,...T]=k.split(","),x=v?.trim(),w=T.join(",").trim();return!x||!w?null:{provider:x,model:w,key:`${x},${w}`}},g=[];if(c){let k=i?.[a];if(Array.isArray(k)&&k.length>0)g.push({name:`${c}/${a}`,models:k});else{let v=n.strictProjectRouting;n.log.warn(`No ${c} fallback configured for ${a}; ${v?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[a])&&l[a].length>0&&g.push({name:`global/${a}`,models:l[a]}),g.length===0&&a!=="image"&&n.body?.messages?.some(T=>T.role==="user"&&Array.isArray(T.content)&&T.content.some(x=>x.type==="image"||x.type==="image_url"||Array.isArray(x?.content)&&x.content.some(w=>w.type==="image"||w.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${a}', but request has images \u2014 trying fallback.image`),g.push({name:"global/image (auto-detected)",models:l.image})),g.length===0)return null;let _=g.reduce((k,v)=>k+v.models.length,0);n.log.warn(`Request failed for ${a}, trying ${_} fallback models across ${g.length} fallback stage(s)`);let b;for(let k of g){n.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let v of k.models){let T=y(v);if(!T){n.log.warn(`Fallback model '${v}' is invalid, skipping`);continue}if(f.has(T.key))continue;f.add(T.key);let x=t.providerService.getProviders(),w=yt(x,T.provider,T.model);if(!w||o.endPoint==="/v1/chat/completions"&&ua(w.provider)){n.log.warn(`Fallback model ${v} is not configured or provider is disabled, skipping`);continue}let E=w.provider.name,C=w.model;if(s&&la(w.provider,C,t.pluginRegistry))continue;if(!u.isAvailable(E,C,w.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${v} unavailable (fail pool), skipping`);continue}let A=t.pluginRegistry.getManagedRuntimeFor(w.provider);if(A&&Fo(n,A,{name:E},C))continue;let F;for(let R=1;R<=2;R++){n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt;try{n.log.info(`Trying fallback model: ${E},${C}${R>1?" (retry)":""}`);let O={...n.body};O.model=C;let S={...n,provider:E,body:O},I=w.provider,M={pluginRegistry:t.pluginRegistry,req:S,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:ra(S,o,S.codexDetected===!0)},{requestBody:N,config:L,bypass:D}=await oa(O,I,o,n.headers,M),z=await sa(N,L,I,t,D,o,M);try{I?.baseUrl&&z?.headers&&ut(E,I.baseUrl,z.headers)}catch{}let q=await ia(N,z,I,o,D,M);return q=await na(O,q,E,n.chatCompletionCapture),n.log.info(`Fallback model ${E},${C} succeeded`),n.chatCompletionCapture||u.recordSuccess(E,C),r&&d&&p&&!n.strictProjectRouting&&($e().promote(d,p,a,E,C),n.log.info(`Promoted fallback model ${E},${C} for ${d},${p}:${a}`),h?n.log.info(`Rate-limited original model ${d},${p} already marked unavailable with cooldown`):(u.forceOpen(d,p,r?.message),n.log.info(`Marked original model ${d},${p} as unavailable`))),n.provider=E,n.body=O,r&&Ci(n,`${E},${C}`),aa(q,e,O,t)}catch(O){if(o.endPoint==="/v1/chat/completions"&&pr(O))throw O;if(F=O,Do(n,A,O,{name:E},C))break;if(R===1){n.log.warn(`Fallback model ${E},${C} failed, retrying once: ${O.message}`);continue}}}b=F,u.recordFailure(E,C,F?.message),n.log.warn(`Fallback model ${E},${C} failed after retry: ${F?.message}`),n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt,t.recordUsage?.({provider:E,model:C,originalModel:n.originalModel||p||n.body.model,scenarioType:a,modelFamily:n.modelFamily,errorMessage:F?.message||String(F),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.chatCompletionCapture?0:n.tokenCount||0,req:n})}}if(n.log.error(`All fallback models failed for ${a}`),!r&&b)throw b;return null}async function oa(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw J("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");r.clientEndpoint=t.endPoint;let s={model:n.model,provider:e,requestState:{}},a=r.pluginRegistry.getManagedRuntimeFor(e);if(a){let d=Fo(r.req,a,e,n.model);if(d)throw d;await a.ensureUsable?.(s)}let i=JSON.parse(JSON.stringify(n)),c=i?.system;if(typeof c=="string"&&c.includes("cch="))i.system=c.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(c))for(let d=0;d<c.length;d++){let p=c[d],f=typeof p=="string"?p:p?.text??"";if(f.includes("cch=")){let h=f.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?c[d]=h:typeof p?.text=="string"&&(p.text=h)}}let l={__ccrManagedRequest:s},u=!1;if(u=Dd(e,t,n),u&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!u&&typeof t.transformRequestOut=="function"){let d=await t.transformRequestOut(i);d.body?(i=d.body,l={...l,...d.config}):i=d}if(!u&&e.transformer?.use?.length)for(let d of e.transformer.use){if(!d||typeof d.transformRequestIn!="function")continue;let p=await d.transformRequestIn(i,e,r);p.body?(i=p.body,l={...l,...p.config}):i=p}if(!u&&e.transformer?.[n.model]?.use?.length)for(let d of e.transformer[n.model].use){if(!d||typeof d.transformRequestIn!="function")continue;let p=await d.transformRequestIn(i,e,r);r.anthropicChat&&p.body?(i=p.body,l={...l,...p.config}):i=p}return{requestBody:i,config:l,bypass:u}}function Dd(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 Fd(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 ra(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function jd(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 sa(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>qi(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):qi(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 qi(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 c=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 l={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(l=await i.signRequest({headers:l,requestBody:n,provider:t,config:e})),Fd(l,a?.req);for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];!i?.suppressDebugLog&&Vt(o.configService)&&Ys(o.log,a.req.id,{url:String(c),headers:l,body:n});let u=e.__ccrManagedRequest,d,p=()=>qs(c,n,{...e,headers:JSON.parse(JSON.stringify(l)),httpsProxy:i?void 0:me(o.configService,t)},a,i?void 0:o.log);try{d=await p();let f=a.req.chatCompletionCapture;f&&(f.unbookedAttempt={provider:a.req.provider,model:a.req.body.model})}catch(f){throw i?await xe(i,0,void 0,Ke(n),ci(f),u):f}if(!d.ok&&i?.authRefresh&&d.status===401&&!lt(a.req,i,t).refreshUsed){lt(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),d=await p()}catch{}d.status===401&&(a.req.__retryAttempted=!0)}if(!d.ok){let f;try{f=await d.text()}catch(y){throw i?await xe(i,d.status,void 0,Ke(n),void 0,u):y}if(i){let y=await xe(i,d.status,f,Ke(n),void 0,u);throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${d.status} code=${y.code}`),y}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${d.status}): ${f}`);let h=a.req.chatCompletionCapture&&(pt(d)||Ue(f))?"Upstream SSE error":f,m=J(`Error from provider(${t.name},${n.model}: ${d.status}): ${h}`,d.status,"provider_response_error");throw m.isRateLimit=d.status===429||vt(f),m.rawBody=f,m}if(d.ok){let f=d.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=${d.ok} status=${d.status} hasBody=${!!d.body}`),!h||f.includes("application/json")){let m="";try{if(m=await d.clone().text(),!m||m.trim()==="")throw new SyntaxError("Empty JSON body");if(Ue(m))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${f}, skipping JSON validation`),d;let g=JSON.parse(m);if(i?.isErrorEnvelope?.(g))throw await xe(i,d.status,m,Ke(n),void 0,u);if(g&&typeof g=="object"&&g.error&&(typeof g.error=="string"||typeof g.error=="object"&&Object.keys(g.error).length>0)){if(i)throw await xe(i,d.status,m,Ke(n),void 0,u);o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${d.status}): ${m}`);let b=vt(m),k=J(`Error from provider(${t.name},${n.model}: ${d.status}): ${m}`,400,"provider_response_error");throw k.isRateLimit=b,k.rawBody=m,k}}catch(y){if(i)throw y?.pluginClassified===!0?y:await xe(i,d.status,void 0,Ke(n),void 0,u);if(y instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${m}"`);let g=J(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw g.rawBody=m,g}throw y}}}if(!i?.suppressDebugLog&&!n.stream&&Vt(o.configService)){let h=await d.clone().text();Xs(o.log,a.req.id,{status:d.status,headers:Object.fromEntries(Array.from(d.headers)),body:h})}return d}async function ia(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 aa(n,e,t,o){n.ok||e.code(n.status);let r=pt(n);if(!r){let s=await ce(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let a=await ye(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&&Vt(o.configService)){let[s,a]=n.body.tee(),i=Vs(o.configService);return Zs(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function vt(n,e=!0){let t=n.toLowerCase();return t.includes("rate limit")||t.includes("rate_limit")||t.includes("rate_limit_error")||t.includes("too many requests")||e&&t.includes("too many")||t.includes("quota exhausted")||t.includes("qps_limit")||t.includes("token_limit")||t.includes("\u9650\u6D41")||t.includes("\u9891\u7387\u9650\u5236")}function pr(n){if(ii(n))return!1;let e=n?.statusCode,t=n?.isRateLimit&&(typeof n.rawBody!="string"||vt(n.rawBody,!1));return e>=400&&e<500&&e!==408&&e!==429&&!t}function la(n,e,t){let o=r=>r?.some(s=>s.name===ea);return t.getManagedRuntimeFor(n)?.name===ea||!!o(n.transformer?.use)||!!o(n.transformer?.[e]?.use)}function Hd(n){let e=i=>typeof i=="string"&&i.trim().length>0,t=i=>(i?.type==="function"||i?.type==="custom")&&e(i[i.type]?.name),o=n.tools;if(o!==void 0&&!(Array.isArray(o)&&o.every(t)))return!1;let r=n.functions;if(r!==void 0&&!(Array.isArray(r)&&r.every(i=>e(i?.name))))return!1;let s=n.function_call;if(s!=null&&!["auto","none"].includes(s)&&!e(s.name))return!1;let a=n.tool_choice;if(a!=null){if(["auto","none","required"].includes(a)||t(a))return!0;let i=a.allowed_tools;return a.type==="allowed_tools"&&["auto","required"].includes(i?.mode)&&Array.isArray(i.tools)&&i.tools.length>0&&i.tools.every(t)}return o?.length||r?.length||s!=null?!0:Array.isArray(n.messages)&&n.messages.some(i=>i?.role==="tool"?e(i.tool_call_id)&&i.content!=null:i?.role==="function"?e(i.name)&&i.content!=null:i?.role!=="assistant"?!1:e(i.function_call?.name)&&typeof i.function_call.arguments=="string"?!0:Array.isArray(i.tool_calls)&&i.tool_calls.length>0&&i.tool_calls.every(c=>t(c)&&e(c.id)&&(c.type==="function"?typeof c.function.arguments=="string":typeof c.custom.input=="string")))}function ua(n){return n.name===Ud&&n.pluginManaged===!0}function zd(n){try{return new URL(n),!0}catch{return!1}}var dr,ca,ea,gn=P(()=>{"use strict";ei();Gt();ri();ct();ai();li();it();jo();ae();ge();en();sn();nr();V();Oe();te();dr=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;ca=async n=>{n.get("/",async()=>({message:"LLMs API",version:qt})),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)=>ta(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 J("Provider name is required",400,"invalid_request");if(!s||!zd(s))throw J("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw J("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw J("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw J(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw J("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw J("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw J("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw J("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})};ea="gemini-agy-acp"});var Ge,fr=P(()=>{"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 ke,hn,da,Bd,pa,Qe=P(()=>{"use strict";ke=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",hn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,da=["low","medium","high"],Bd={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"},pa=n=>{if(typeof n=="string")return Bd[n.trim().toLowerCase()]}});function Jd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function yn(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 he(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:Jd(n),cache_creation_input_tokens:yn(n)}}function le(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 Ve=P(()=>{"use strict"});function fa(n,e){let t=n.cache_read_input_tokens??0,o=n.cache_creation_input_tokens??0,r=(n.input_tokens??0)+(e==="inclusive"?0:t+o),s=n.output_tokens??0;return{prompt_tokens:r,completion_tokens:s,total_tokens:r+s,prompt_tokens_details:{cached_tokens:t,cache_creation_tokens:o}}}function ma(n){switch(n){case"tool_use":return"tool_calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"refusal":return"content_filter";case"end_turn":case"pause_turn":case"stop_sequence":return"stop";default:throw new Error("Anthropic response has no recognized stop reason")}}function Wd(n,e){if(n?.type!=="message"||!Array.isArray(n.content))throw new Error("Expected an Anthropic Messages response");let t="",o="",r=[];for(let s of n.content)s.type==="text"&&(t+=s.text),s.type==="thinking"&&(o+=s.thinking),s.type==="tool_use"&&r.push({id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.input)}});return{id:n.id,model:n.model,created:Math.floor(Date.now()/1e3),object:"chat.completion",choices:[{index:0,finish_reason:ma(n.stop_reason),message:{role:"assistant",content:t||(r.length?null:""),...o&&{reasoning_content:o},...r.length&&{tool_calls:r}}}],...n.usage&&{usage:fa(n.usage,e)}}}function Kd(n,e,t){let o=new TextEncoder,r={created:Math.floor(Date.now()/1e3),object:"chat.completion.chunk"},s,a,i=null,c=0,l=new Map,u="",d=!1,p="",f=[];function h(g,_){g.enqueue(o.encode(`data: ${JSON.stringify(_)}
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 na(n,e,t,o){let r=n.body;n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt,(n.ccrHookOrder||=[]).push("handler"),Do(n);let s=Bd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&kt(r);let a=o.endPoint==="/v1/chat/completions";if(a&&(n.originalModel??=r?.model),(a||o.endPoint==="/v1/responses")&&!n.provider&&typeof r?.model=="string"&&pr.test(r.model)&&await hn(n,e,{configService:t.configService,tokenizerService:t.tokenizerService}),a&&!n.provider&&typeof r?.model=="string"&&pr.test(r.model))throw J("No upstream route configured for this model family",404,"provider_not_found");a&&!n.strictProjectRouting&&(n.fallbackConfig??=t.configService.get("Router")?.fallback);let i=n.provider;if(!i&&r?.model){let d=r.model.split(",");d.length>1&&(i=d[0],r.model=d.slice(1).join(","))}let c=i?t.providerService.getProvider(i):void 0;if(!c&&r?.model){let d=t.providerService.resolveModelRoute(r.model);d&&(c=d.provider,r.model=d.targetModel)}if(!c&&r?.model){let p=t.configService.get("Router")?.default;if(p&&p.includes(",")){let[f,...h]=p.split(","),g=t.providerService.getProvider(f);g&&(c=g,r.model=h.join(","))}}if(n.originalModel||(n.originalModel=r?.model),a&&c&&da(c))throw J("The managed CCR preset cannot be a Chat upstream",400,"invalid_route");if(!c)throw J(`Provider '${i}' not found`,404,"provider_not_found");n.provider=c.name||i;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;let u=a&&pr.test(n.originalModel)&&Jd(r);if(u&&ua(c,r.model,t.pluginRegistry)){let d=await qi(n,e,t,o,void 0,u);if(d)return d;throw J("No configured Chat route supports this tool request",400,"agy_unsupported_request")}try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&kt(r);let d={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:sa(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:p,config:f,bypass:h}=await ra(r,c,o,n.headers,d);if(p?.messages&&!h&&!n.isTargetAnthropic){let b=p.messages,_=new Set,k=[],v=[];for(let T of b){if(T?.role!=="system"){v.push(T);continue}let S=JSON.stringify(T.content??"");_.has(S)||(_.add(S),k.push(T))}k.length>0&&v.length>0&&(p.messages=[...k,...v])}let g=await ia(p,f,c,t,h,o,d);try{c?.baseUrl&&g?.headers&&ut(i,c.baseUrl,g.headers)}catch{}let y=await aa(p,g,c,o,h,d);y=await oa(r,y,c.name||i,n.chatCompletionCapture);let m=ca(y,e,r,t);try{let b=r.model||n.originalModel;!n.chatCompletionCapture&&i&&b&&H().recordSuccess(i,b)}catch{}return m}catch(d){if(d instanceof oe||a&&fr(d))throw d;let p=Fo(n,t.pluginRegistry.getManagedRuntimeFor(c),d,c,r.model);if(a&&p&&d.statusCode===401)throw n.__fallbackExhausted=!0,d;if(!p&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await na(n,e,t,o)}catch(h){if(n.__fallbackExhausted||a&&fr(h))throw h;d=h}}let f=await qi(n,e,t,o,d,u);if(f)return f;throw n.__fallbackExhausted=!0,d}}async function oa(n,e,t,o){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let a=e.body.getReader(),i=new TextDecoder,c=[],l="";for(let f=0;f<8;f++){let h=await a.read();if(h.done||(h.value&&(c.push(h.value),l+=i.decode(h.value,{stream:!0})),l.split(`
28
+ `).some(g=>g.startsWith("data:"))))break}if(l+=i.decode(),c.length===0)throw a.releaseLock(),J(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(l.includes("event: error")){a.releaseLock(),o&&(o.streamError=!0,o.rateLimited=we(200,l));let f=l.length<500?l:l.slice(0,500);throw J(`Provider ${t} returned error in SSE stream: ${f}`,400,"provider_response_error")}if(l.split(`
29
+ `).filter(f=>f.startsWith("data:")&&f.trim().length>5).length===0){a.releaseLock();let f=l.length<500?l:l.slice(0,500);throw J(`Provider ${t} returned streaming response with no SSE data lines: ${f}`,400,"provider_response_error")}let d=new ReadableStream({start:f=>{for(let g of c)f.enqueue(g);let h=()=>{a.read().then(({done:g,value:y})=>{g?f.close():(f.enqueue(y),h())}).catch(g=>f.error(g))};h()},cancel:()=>{a.cancel()}}),p=await oi(d);if(p.verdict==="empty")throw J(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(ri(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function qi(n,e,t,o,r,s){let a=n.scenarioType||"default",i=n.familyFallback,c=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),u=H(),d=n.provider||"",p=n.body.model||"",f=new Set,h=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&vt(r.rawBody)||r?.message&&vt(r.message);if(d&&p&&f.add(`${d},${p}`),r&&d&&p&&(h?(u.markRateLimited(d,p,120,r?.message),n.log.warn(`Primary model ${d},${p} rate-limited, will try fallbacks`)):u.recordFailure(d,p,r?.message),n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt,t.recordUsage?.({provider:d,model:p,originalModel:n.originalModel||p,scenarioType:a,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.chatCompletionCapture?0: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 y=k=>{let[v,...T]=k.split(","),S=v?.trim(),w=T.join(",").trim();return!S||!w?null:{provider:S,model:w,key:`${S},${w}`}},m=[];if(c){let k=i?.[a];if(Array.isArray(k)&&k.length>0)m.push({name:`${c}/${a}`,models:k});else{let v=n.strictProjectRouting;n.log.warn(`No ${c} fallback configured for ${a}; ${v?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[a])&&l[a].length>0&&m.push({name:`global/${a}`,models:l[a]}),m.length===0&&a!=="image"&&n.body?.messages?.some(T=>T.role==="user"&&Array.isArray(T.content)&&T.content.some(S=>S.type==="image"||S.type==="image_url"||Array.isArray(S?.content)&&S.content.some(w=>w.type==="image"||w.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${a}', but request has images \u2014 trying fallback.image`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let b=m.reduce((k,v)=>k+v.models.length,0);n.log.warn(`Request failed for ${a}, trying ${b} fallback models across ${m.length} fallback stage(s)`);let _;for(let k of m){n.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let v of k.models){let T=y(v);if(!T){n.log.warn(`Fallback model '${v}' is invalid, skipping`);continue}if(f.has(T.key))continue;f.add(T.key);let S=t.providerService.getProviders(),w=yt(S,T.provider,T.model);if(!w||o.endPoint==="/v1/chat/completions"&&da(w.provider)){n.log.warn(`Fallback model ${v} is not configured or provider is disabled, skipping`);continue}let P=w.provider.name,R=w.model;if(s&&ua(w.provider,R,t.pluginRegistry))continue;if(!u.isAvailable(P,R,w.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${v} unavailable (fail pool), skipping`);continue}let A=t.pluginRegistry.getManagedRuntimeFor(w.provider);if(A&&jo(n,A,{name:P},R))continue;let D;for(let x=1;x<=2;x++){n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt;try{n.log.info(`Trying fallback model: ${P},${R}${x>1?" (retry)":""}`);let O={...n.body};O.model=R;let C={...n,provider:P,body:O},I=w.provider,M={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:sa(C,o,C.codexDetected===!0)},{requestBody:N,config:L,bypass:F}=await ra(O,I,o,n.headers,M),z=await ia(N,L,I,t,F,o,M);try{I?.baseUrl&&z?.headers&&ut(P,I.baseUrl,z.headers)}catch{}let q=await aa(N,z,I,o,F,M);return q=await oa(O,q,P,n.chatCompletionCapture),n.log.info(`Fallback model ${P},${R} succeeded`),n.chatCompletionCapture||u.recordSuccess(P,R),r&&d&&p&&!n.strictProjectRouting&&($e().promote(d,p,a,P,R),n.log.info(`Promoted fallback model ${P},${R} for ${d},${p}:${a}`),h?n.log.info(`Rate-limited original model ${d},${p} already marked unavailable with cooldown`):(u.forceOpen(d,p,r?.message),n.log.info(`Marked original model ${d},${p} as unavailable`))),n.provider=P,n.body=O,r&&Si(n,`${P},${R}`),ca(q,e,O,t)}catch(O){if(o.endPoint==="/v1/chat/completions"&&fr(O))throw O;if(D=O,Fo(n,A,O,{name:P},R))break;if(x===1){n.log.warn(`Fallback model ${P},${R} failed, retrying once: ${O.message}`);continue}}}_=D,u.recordFailure(P,R,D?.message),n.log.warn(`Fallback model ${P},${R} failed after retry: ${D?.message}`),n.chatCompletionCapture&&delete n.chatCompletionCapture.unbookedAttempt,t.recordUsage?.({provider:P,model:R,originalModel:n.originalModel||p||n.body.model,scenarioType:a,modelFamily:n.modelFamily,errorMessage:D?.message||String(D),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.chatCompletionCapture?0:n.tokenCount||0,req:n})}}if(n.log.error(`All fallback models failed for ${a}`),!r&&_)throw _;return null}async function ra(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw J("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");r.clientEndpoint=t.endPoint;let s={model:n.model,provider:e,requestState:{}},a=r.pluginRegistry.getManagedRuntimeFor(e);if(a){let d=jo(r.req,a,e,n.model);if(d)throw d;await a.ensureUsable?.(s)}let i=JSON.parse(JSON.stringify(n)),c=i?.system;if(typeof c=="string"&&c.includes("cch="))i.system=c.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(c))for(let d=0;d<c.length;d++){let p=c[d],f=typeof p=="string"?p:p?.text??"";if(f.includes("cch=")){let h=f.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?c[d]=h:typeof p?.text=="string"&&(p.text=h)}}let l={__ccrManagedRequest:s},u=!1;if(u=Hd(e,t,n),u&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!u&&typeof t.transformRequestOut=="function"){let d=await t.transformRequestOut(i);d.body?(i=d.body,l={...l,...d.config}):i=d}if(!u&&e.transformer?.use?.length)for(let d of e.transformer.use){if(!d||typeof d.transformRequestIn!="function")continue;let p=await d.transformRequestIn(i,e,r);p.body?(i=p.body,l={...l,...p.config}):i=p}if(!u&&e.transformer?.[n.model]?.use?.length)for(let d of e.transformer[n.model].use){if(!d||typeof d.transformRequestIn!="function")continue;let p=await d.transformRequestIn(i,e,r);r.anthropicChat&&p.body?(i=p.body,l={...l,...p.config}):i=p}return{requestBody:i,config:l,bypass:u}}function Hd(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 zd(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 sa(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 ia(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>ea(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):ea(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 ea(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 c=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 l={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(l=await i.signRequest({headers:l,requestBody:n,provider:t,config:e})),zd(l,a?.req);for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];!i?.suppressDebugLog&&Xt(o.configService)&&Xs(o.log,a.req.id,{url:String(c),headers:l,body:n});let u=e.__ccrManagedRequest,d,p=()=>ei(c,n,{...e,headers:JSON.parse(JSON.stringify(l)),httpsProxy:i?void 0:me(o.configService,t)},a,i?void 0:o.log);try{d=await p();let f=a.req.chatCompletionCapture;f&&(f.unbookedAttempt={provider:a.req.provider,model:a.req.body.model})}catch(f){throw i?await xe(i,0,void 0,Ke(n),li(f),u):f}if(!d.ok&&i?.authRefresh&&d.status===401&&!lt(a.req,i,t).refreshUsed){lt(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),d=await p()}catch{}d.status===401&&(a.req.__retryAttempted=!0)}if(!d.ok){let f;try{f=await d.text()}catch(y){throw i?await xe(i,d.status,void 0,Ke(n),void 0,u):y}if(i){let y=await xe(i,d.status,f,Ke(n),void 0,u);throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${d.status} code=${y.code}`),y}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${d.status}): ${f}`);let h=a.req.chatCompletionCapture&&(pt(d)||Ue(f))?"Upstream SSE error":f,g=J(`Error from provider(${t.name},${n.model}: ${d.status}): ${h}`,d.status,"provider_response_error");throw g.isRateLimit=d.status===429||vt(f),g.rawBody=f,g}if(d.ok){let f=d.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=${d.ok} status=${d.status} hasBody=${!!d.body}`),!h||f.includes("application/json")){let g="";try{if(g=await d.clone().text(),!g||g.trim()==="")throw new SyntaxError("Empty JSON body");if(Ue(g))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${f}, skipping JSON validation`),d;let m=JSON.parse(g);if(i?.isErrorEnvelope?.(m))throw await xe(i,d.status,g,Ke(n),void 0,u);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 xe(i,d.status,g,Ke(n),void 0,u);o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${d.status}): ${g}`);let _=vt(g),k=J(`Error from provider(${t.name},${n.model}: ${d.status}): ${g}`,400,"provider_response_error");throw k.isRateLimit=_,k.rawBody=g,k}}catch(y){if(i)throw y?.pluginClassified===!0?y:await xe(i,d.status,void 0,Ke(n),void 0,u);if(y instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let m=J(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw m.rawBody=g,m}throw y}}}if(!i?.suppressDebugLog&&!n.stream&&Xt(o.configService)){let h=await d.clone().text();Zs(o.log,a.req.id,{status:d.status,headers:Object.fromEntries(Array.from(d.headers)),body:h})}return d}async function aa(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 ca(n,e,t,o){n.ok||e.code(n.status);let r=pt(n);if(!r){let s=await le(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 ye(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&&Xt(o.configService)){let[s,a]=n.body.tee(),i=Ys(o.configService);return qs(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function vt(n,e=!0){let t=n.toLowerCase();return t.includes("rate limit")||t.includes("rate_limit")||t.includes("rate_limit_error")||t.includes("too many requests")||e&&t.includes("too many")||t.includes("quota exhausted")||t.includes("qps_limit")||t.includes("token_limit")||t.includes("\u9650\u6D41")||t.includes("\u9891\u7387\u9650\u5236")}function fr(n){if(ai(n))return!1;let e=n?.statusCode,t=n?.isRateLimit&&(typeof n.rawBody!="string"||vt(n.rawBody,!1));return e>=400&&e<500&&e!==408&&e!==429&&!t}function ua(n,e,t){let o=r=>r?.some(s=>s.name===ta);return t.getManagedRuntimeFor(n)?.name===ta||!!o(n.transformer?.use)||!!o(n.transformer?.[e]?.use)}function Jd(n){let e=i=>typeof i=="string"&&i.trim().length>0,t=i=>(i?.type==="function"||i?.type==="custom")&&e(i[i.type]?.name),o=n.tools;if(o!==void 0&&!(Array.isArray(o)&&o.every(t)))return!1;let r=n.functions;if(r!==void 0&&!(Array.isArray(r)&&r.every(i=>e(i?.name))))return!1;let s=n.function_call;if(s!=null&&!["auto","none"].includes(s)&&!e(s.name))return!1;let a=n.tool_choice;if(a!=null){if(["auto","none","required"].includes(a)||t(a))return!0;let i=a.allowed_tools;return a.type==="allowed_tools"&&["auto","required"].includes(i?.mode)&&Array.isArray(i.tools)&&i.tools.length>0&&i.tools.every(t)}return o?.length||r?.length||s!=null?!0:Array.isArray(n.messages)&&n.messages.some(i=>i?.role==="tool"?e(i.tool_call_id)&&i.content!=null:i?.role==="function"?e(i.name)&&i.content!=null:i?.role!=="assistant"?!1:e(i.function_call?.name)&&typeof i.function_call.arguments=="string"?!0:Array.isArray(i.tool_calls)&&i.tool_calls.length>0&&i.tool_calls.every(c=>t(c)&&e(c.id)&&(c.type==="function"?typeof c.function.arguments=="string":typeof c.custom.input=="string")))}function da(n){return n.name===jd&&n.pluginManaged===!0}function Wd(n){try{return new URL(n),!0}catch{return!1}}var pr,la,ta,yn=E(()=>{"use strict";ti();Vt();si();ct();ci();ui();it();Ho();ce();ge();nn();cn();or();V();Oe();te();pr=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;la=async n=>{n.get("/",async()=>({message:"LLMs API",version:tn})),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)=>na(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 J("Provider name is required",400,"invalid_request");if(!s||!Wd(s))throw J("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw J("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw J("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw J(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw J("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw J("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw J("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw J("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})};ta="gemini-agy-acp"});var Ge,mr=E(()=>{"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 ke,_n,pa,Kd,fa,Qe=E(()=>{"use strict";ke=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",_n=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,pa=["low","medium","high"],Kd={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"},fa=n=>{if(typeof n=="string")return Kd[n.trim().toLowerCase()]}});function ma(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function Tt(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 Ct(n){if(!(n?.usage_source!=="gemini-agy-acp"||typeof n.prompt_tokens!="number"))return n.prompt_tokens-ma(n)-Tt(n)}function he(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??Ct(n)??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:ma(n),cache_creation_input_tokens:Tt(n)}}function se(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 Ve=E(()=>{"use strict"});function ga(n,e){let t=n.cache_read_input_tokens??0,o=n.cache_creation_input_tokens??0,r=(n.input_tokens??0)+(e==="inclusive"?0:t+o),s=n.output_tokens??0;return{prompt_tokens:r,completion_tokens:s,total_tokens:r+s,prompt_tokens_details:{cached_tokens:t,cache_creation_tokens:o}}}function ha(n){switch(n){case"tool_use":return"tool_calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"refusal":return"content_filter";case"end_turn":case"pause_turn":case"stop_sequence":return"stop";default:throw new Error("Anthropic response has no recognized stop reason")}}function Gd(n,e){if(n?.type!=="message"||!Array.isArray(n.content))throw new Error("Expected an Anthropic Messages response");let t="",o="",r=[];for(let s of n.content)s.type==="text"&&(t+=s.text),s.type==="thinking"&&(o+=s.thinking),s.type==="tool_use"&&r.push({id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.input)}});return{id:n.id,model:n.model,created:Math.floor(Date.now()/1e3),object:"chat.completion",choices:[{index:0,finish_reason:ha(n.stop_reason),message:{role:"assistant",content:t||(r.length?null:""),...o&&{reasoning_content:o},...r.length&&{tool_calls:r}}}],...n.usage&&{usage:ga(n.usage,e)}}}function Qd(n,e,t){let o=new TextEncoder,r={created:Math.floor(Date.now()/1e3),object:"chat.completion.chunk"},s,a,i=null,c=0,l=new Map,u="",d=!1,p="",f=[];function h(m,b){m.enqueue(o.encode(`data: ${JSON.stringify(b)}
31
31
 
32
- `))}function m(g,_,b=null){if(!s)throw new Error("Expected Anthropic message_start before a Chat chunk");h(g,{...s,...r,...t&&{usage:null},choices:[{index:0,delta:_,finish_reason:b}]})}function y(g,_){switch(g.type){case"message_start":s={id:g.message.id,model:g.message.model},a=g.message.usage,m(_,{role:"assistant"});break;case"content_block_start":{let b=g.content_block;if(b.type==="text"&&b.text&&m(_,{content:b.text}),b.type==="thinking"&&b.thinking&&m(_,{reasoning_content:b.thinking}),b.type==="tool_use"){let k=c++,v=b.input&&Object.keys(b.input).length?JSON.stringify(b.input):"";l.set(g.index,{index:k,hasArguments:!!v}),m(_,{tool_calls:[{index:k,id:b.id,type:"function",function:{name:b.name,arguments:v}}]})}break}case"content_block_delta":{let b=g.delta;if(b.type==="text_delta"&&m(_,{content:b.text}),b.type==="thinking_delta"&&m(_,{reasoning_content:b.thinking}),b.type==="input_json_delta"){let k=l.get(g.index);k&&b.partial_json&&(k.hasArguments=!0,m(_,{tool_calls:[{index:k.index,function:{arguments:b.partial_json}}]}))}break}case"content_block_stop":{let b=l.get(g.index);b&&!b.hasArguments&&m(_,{tool_calls:[{index:b.index,function:{arguments:"{}"}}]}),l.delete(g.index);break}case"message_delta":i=g.delta.stop_reason??i,g.usage&&(a=le(a,g.usage,!1));break;case"message_stop":return m(_,{},ma(i)),t&&a&&h(_,{...s,...r,choices:[],usage:fa(a,e)}),_.enqueue(o.encode(`data: [DONE]
32
+ `))}function g(m,b,_=null){if(!s)throw new Error("Expected Anthropic message_start before a Chat chunk");h(m,{...s,...r,...t&&{usage:null},choices:[{index:0,delta:b,finish_reason:_}]})}function y(m,b){switch(m.type){case"message_start":s={id:m.message.id,model:m.message.model},a=m.message.usage,g(b,{role:"assistant"});break;case"content_block_start":{let _=m.content_block;if(_.type==="text"&&_.text&&g(b,{content:_.text}),_.type==="thinking"&&_.thinking&&g(b,{reasoning_content:_.thinking}),_.type==="tool_use"){let k=c++,v=_.input&&Object.keys(_.input).length?JSON.stringify(_.input):"";l.set(m.index,{index:k,hasArguments:!!v}),g(b,{tool_calls:[{index:k,id:_.id,type:"function",function:{name:_.name,arguments:v}}]})}break}case"content_block_delta":{let _=m.delta;if(_.type==="text_delta"&&g(b,{content:_.text}),_.type==="thinking_delta"&&g(b,{reasoning_content:_.thinking}),_.type==="input_json_delta"){let k=l.get(m.index);k&&_.partial_json&&(k.hasArguments=!0,g(b,{tool_calls:[{index:k.index,function:{arguments:_.partial_json}}]}))}break}case"content_block_stop":{let _=l.get(m.index);_&&!_.hasArguments&&g(b,{tool_calls:[{index:_.index,function:{arguments:"{}"}}]}),l.delete(m.index);break}case"message_delta":i=m.delta.stop_reason??i,m.usage&&(a=se(a,m.usage,!1));break;case"message_stop":return g(b,{},ha(i)),t&&a&&h(b,{...s,...r,choices:[],usage:ga(a,e)}),b.enqueue(o.encode(`data: [DONE]
33
33
 
34
- `)),_.terminate(),!0}return!1}return n.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(g,_){if(!g)return;d&&g.startsWith(`
35
- `)&&(g=g.slice(1)),d=g.endsWith("\r");let b=(u+g).split(/\r\n|[\r\n]/);u=b.pop();for(let k of b)if(k.startsWith("event:")&&(p=k.slice(6).trim()),k.startsWith("data:")&&f.push(k.slice(5).replace(/^ /,"")),k===""){if(f.length){let v=JSON.parse(f.join(`
36
- `));if(p==="error"||v.type==="error"||v.error){h(_,{error:v.error??{type:"upstream_error",message:"Anthropic stream failed"}}),_.terminate();return}if(y(v,_))return}f=[],p=""}}}))}async function ga(n,e,t){let o=pt(n),r=o?null:await ce(n);if(o||r?.isSSE){let a=r?.body??n.body;if(!a)throw new Error("Anthropic stream has no response body");return new Response(Kd(a,e,t),{status:n.status,headers:{"content-type":"text/event-stream"}})}let s=await j(r?new Response(r.body,{status:n.status}):n);return Response.json(Wd(s,e),{status:n.status})}var ha=P(()=>{"use strict";Ve();V()});var mr,ya=P(()=>{mr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Gd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function _a(n,e=!1){let t=[],o=[],r=f=>{if(typeof f=="string"){o.push({type:"text",text:f});return}Array.isArray(f)&&f.forEach(h=>{if(typeof h=="string"){o.push({type:"text",text:h});return}h&&typeof h=="object"&&h.type==="text"&&h.text&&o.push({...h})})},s=()=>{let f=new Map;for(let h=0;h<o.length;h++){let m=o[h],y=m?.text??JSON.stringify(m),g=f.get(y);if(g===void 0){f.set(y,h);continue}!o[g]?.cache_control&&m?.cache_control&&(o[g]=m),o.splice(h,1),h--}};n.messages.forEach(f=>{f.role==="system"?r(f.content):t.push(f)}),s();let a=[];for(let f=0;f<t.length;f++){let h=t[f];if(h.role==="tool"){let m=h.content;try{!e&&typeof h.content=="string"&&(m=JSON.parse(h.content))}catch{}m!=null&&typeof m!="object"&&typeof m!="string"&&(m=String(m));let y={type:"tool_result",tool_use_id:h.tool_call_id,content:m};h.cache_control&&(y.cache_control=h.cache_control);let g=a[a.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(y):a.push({role:"user",content:[y]})}else if(h.role==="user"){let m=[];typeof h.content=="string"?m.push({type:"text",text:h.content}):Array.isArray(h.content)&&h.content.forEach(g=>{g&&typeof g=="object"&&g.type==="image_url"&&g.image_url?.url?m.push({type:"image",source:{type:"base64",media_type:g.media_type||"image/jpeg",data:g.image_url.url.split(",")[1]||g.image_url.url}}):m.push(g)});let y=a[a.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(...m):a.push({role:"user",content:m.length>0?m:[{type:"text",text:" "}]})}else if(h.role==="assistant"){let m=[];h.content&&(typeof h.content=="string"?m.push({type:"text",text:h.content}):Array.isArray(h.content)&&m.push(...h.content)),h.tool_calls&&h.tool_calls.length>0&&h.tool_calls.forEach(g=>{let _={};try{_=JSON.parse(g.function.arguments)}catch{_=g.function.arguments}m.push({type:"tool_use",id:g.id,name:g.function.name,input:_})}),h.thinking&&m.unshift({type:"thinking",thinking:h.thinking.content,signature:h.thinking.signature});let y=a[a.length-1];y&&y.role==="assistant"&&Array.isArray(y.content)?y.content.push(...m):a.push({role:"assistant",content:m.length>0?m:[{type:"text",text:" "}]})}}let i=()=>{let f=o.filter(h=>h?.cache_control).length;for(let h of a)Array.isArray(h.content)&&(f+=h.content.filter(m=>m?.cache_control).length);return f},c=f=>f&&typeof f=="object"?{...f}:{type:"ephemeral"},l=()=>{for(let f=a.length-1;f>=0;f--){let h=a[f]?.content;if(!Array.isArray(h))continue;let m=h.find(y=>y?.cache_control);if(m?.cache_control)return m.cache_control}for(let f=o.length-1;f>=0;f--)if(o[f]?.cache_control)return o[f].cache_control;return{type:"ephemeral"}},u=(f,h)=>{if(!Array.isArray(f?.content)||f.content.some(y=>y?.cache_control))return!1;let m=f.content.find(y=>y&&typeof y=="object"&&!y.cache_control);return m?(m.cache_control=c(h),!0):!1};(()=>{let f=4-i();if(f<=0||a.length===0)return;let h=a,m=l(),y=[];for(let g=h.length-1;g>=0;g--)h[g]?.role!=="user"||!Array.isArray(h[g].content)||y.push(g);for(let g of y){if(f<=0)break;u(h[g],m)&&f--}})();let p={messages:a,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let f=n.reasoning.max_tokens||hn(n.reasoning.effort||"medium"),h=Math.min(f,p.max_tokens-1024);h>=1024&&(p.thinking={type:"enabled",budget_tokens:h});let m=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ke(f);da.includes(m)&&(p.output_config={...p.output_config||{},effort:m})}if(o.length>0){let f=o.some(h=>h?.cache_control);p.system=f?o:o.map(h=>h.text||"").join(`
34
+ `)),b.terminate(),!0}return!1}return n.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(m,b){if(!m)return;d&&m.startsWith(`
35
+ `)&&(m=m.slice(1)),d=m.endsWith("\r");let _=(u+m).split(/\r\n|[\r\n]/);u=_.pop();for(let k of _)if(k.startsWith("event:")&&(p=k.slice(6).trim()),k.startsWith("data:")&&f.push(k.slice(5).replace(/^ /,"")),k===""){if(f.length){let v=JSON.parse(f.join(`
36
+ `));if(p==="error"||v.type==="error"||v.error){h(b,{error:v.error??{type:"upstream_error",message:"Anthropic stream failed"}}),b.terminate();return}if(y(v,b))return}f=[],p=""}}}))}async function ya(n,e,t){let o=pt(n),r=o?null:await le(n);if(o||r?.isSSE){let a=r?.body??n.body;if(!a)throw new Error("Anthropic stream has no response body");return new Response(Qd(a,e,t),{status:n.status,headers:{"content-type":"text/event-stream"}})}let s=await j(r?new Response(r.body,{status:n.status}):n);return Response.json(Gd(s,e),{status:n.status})}var _a=E(()=>{"use strict";Ve();V()});var gr,ba=E(()=>{gr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Vd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ka(n,e=!1){let t=[],o=[],r=f=>{if(typeof f=="string"){o.push({type:"text",text:f});return}Array.isArray(f)&&f.forEach(h=>{if(typeof h=="string"){o.push({type:"text",text:h});return}h&&typeof h=="object"&&h.type==="text"&&h.text&&o.push({...h})})},s=()=>{let f=new Map;for(let h=0;h<o.length;h++){let g=o[h],y=g?.text??JSON.stringify(g),m=f.get(y);if(m===void 0){f.set(y,h);continue}!o[m]?.cache_control&&g?.cache_control&&(o[m]=g),o.splice(h,1),h--}};n.messages.forEach(f=>{f.role==="system"?r(f.content):t.push(f)}),s();let a=[];for(let f=0;f<t.length;f++){let h=t[f];if(h.role==="tool"){let g=h.content;try{!e&&typeof h.content=="string"&&(g=JSON.parse(h.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let y={type:"tool_result",tool_use_id:h.tool_call_id,content:g};h.cache_control&&(y.cache_control=h.cache_control);let m=a[a.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(y):a.push({role:"user",content:[y]})}else if(h.role==="user"){let g=[];typeof h.content=="string"?g.push({type:"text",text:h.content}):Array.isArray(h.content)&&h.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 y=a[a.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(...g):a.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(h.role==="assistant"){let g=[];h.content&&(typeof h.content=="string"?g.push({type:"text",text:h.content}):Array.isArray(h.content)&&g.push(...h.content)),h.tool_calls&&h.tool_calls.length>0&&h.tool_calls.forEach(m=>{let b={};try{b=JSON.parse(m.function.arguments)}catch{b=m.function.arguments}g.push({type:"tool_use",id:m.id,name:m.function.name,input:b})}),h.thinking&&g.unshift({type:"thinking",thinking:h.thinking.content,signature:h.thinking.signature});let y=a[a.length-1];y&&y.role==="assistant"&&Array.isArray(y.content)?y.content.push(...g):a.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let i=()=>{let f=o.filter(h=>h?.cache_control).length;for(let h of a)Array.isArray(h.content)&&(f+=h.content.filter(g=>g?.cache_control).length);return f},c=f=>f&&typeof f=="object"?{...f}:{type:"ephemeral"},l=()=>{for(let f=a.length-1;f>=0;f--){let h=a[f]?.content;if(!Array.isArray(h))continue;let g=h.find(y=>y?.cache_control);if(g?.cache_control)return g.cache_control}for(let f=o.length-1;f>=0;f--)if(o[f]?.cache_control)return o[f].cache_control;return{type:"ephemeral"}},u=(f,h)=>{if(!Array.isArray(f?.content)||f.content.some(y=>y?.cache_control))return!1;let g=f.content.find(y=>y&&typeof y=="object"&&!y.cache_control);return g?(g.cache_control=c(h),!0):!1};(()=>{let f=4-i();if(f<=0||a.length===0)return;let h=a,g=l(),y=[];for(let m=h.length-1;m>=0;m--)h[m]?.role!=="user"||!Array.isArray(h[m].content)||y.push(m);for(let m of y){if(f<=0)break;u(h[m],g)&&f--}})();let p={messages:a,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let f=n.reasoning.max_tokens||_n(n.reasoning.effort||"medium"),h=Math.min(f,p.max_tokens-1024);h>=1024&&(p.thinking={type:"enabled",budget_tokens:h});let g=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ke(f);pa.includes(g)&&(p.output_config={...p.output_config||{},effort:g})}if(o.length>0){let f=o.some(h=>h?.cache_control);p.system=f?o:o.map(h=>h.text||"").join(`
37
37
 
38
- `)}if(n.tools&&n.tools.length>0){if(p.tools=Gd(n.tools),e)for(let f of p.tools)f.input_schema??={type:"object",properties:{}};n.tool_choice&&(n.tool_choice==="auto"||e&&n.tool_choice==="none"?p.tool_choice={type:n.tool_choice}: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}))}return p}var ba=P(()=>{Qe()});import{v4 as gr}from"uuid";function Qd(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 hr(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 _n,ka=P(()=>{"use strict";Qe();Gt();V();ha();ya();ba();Oe();Ve();_n=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(c=>c.type==="text"&&c.text).map(c=>({type:"text",text:c.text,cache_control:c.cache_control}));t.push({role:"system",content:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let c=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(c.length){let u=bt(String(e.model??"")),d=[];c.forEach(p=>{let f=Array.isArray(p.content)?p.content:null,h=f?f.filter(g=>g?.type==="image"&&g?.source):[],m=typeof p.content=="string"?p.content:JSON.stringify(p.content);if(h.length>0){let g=f.filter(_=>!(_?.type==="image"&&_?.source)).map(_=>_?.type==="text"?String(_.text??""):JSON.stringify(_)).filter(_=>_.length>0).join(`
39
- `);u?(m=g||"[tool image]",d.push(...h)):(m=[g,...h.map(()=>"(tool image omitted: target model does not support image input)")].filter(_=>_.length>0).join(`
40
- `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:h.length}))}let y={role:"tool",content:m,tool_call_id:p.tool_use_id,cache_control:p.cache_control};t.push(y)}),d.length>0&&t.push({role:"user",content:d.map(p=>({type:"image_url",image_url:{url:p.source?.type==="base64"?mr(p.source.data,p.source.media_type):p.source.url},media_type:p.source.media_type}))})}let l=i.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);l.length&&t.push({role:"user",content:l.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?mr(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let c={role:"assistant",content:""},l=i.content.filter(p=>p.type==="text"&&p.text);l.length&&(c.content=l.map(p=>p.text).join(`
41
- `));let u=i.content.filter(p=>p.type==="tool_use"&&p.id);u.length&&(c.tool_calls=u.map(p=>({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.input||{})}})));let d=i.content.find(p=>p.type==="thinking");d&&(c.thinking={content:d.thinking,signature:d.signature}),t.push(c)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice},s=pa(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},l=Qd(e.thinking?.type)??(s!==void 0||(a??0)>0);l!==void 0&&(i.enabled=l),s!==void 0?i.effort=s:a!==void 0&&(i.effort=ke(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=o?.clientEndpoint==="/v1/chat/completions";r&&(o.anthropicChat={cacheMode:t.cacheMode,includeUsage:o.req?.body?.stream_options?.include_usage===!0});let s=_a(e,r),a={};return this.useBearer?(a.authorization=`Bearer ${t.apiKey}`,a["x-api-key"]=void 0):(a["x-api-key"]=t.apiKey,a.authorization=void 0),a["anthropic-version"]="2023-06-01",a["content-type"]="application/json",{body:s,config:{headers:a}}}async transformResponseOut(e,t){if(!t?.anthropicChat)return e;let{cacheMode:o,includeUsage:r}=t.anthropicChat;return ga(e,o,r)}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 ce(e);if((r?.isSSE??!1)&&r?.body){let l=await this.convertOpenAIStreamToAnthropic(r.body,t);return new Response(l,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let a;if(r?.body)a=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else{let l=await ye(e);if(l.isSSE){let u=await this.convertOpenAIStreamToAnthropic(l.response.body,t);return new Response(u,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}a=l.response}let i=await j(a),c=this.convertOpenAIResponseToAnthropic(i,t);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,a=`msg_${Date.now()}`,i=null,c=String(t?.req?.body?.model??"unknown"),l=!1,u=!1,d=!1;t?.req&&(t.req.contentDelivered=!1);let p=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,h=new Map,m=0,y=0,g=0,_=!1,b=!1,k=0,v=-1,T=()=>{let C=k;return k++,C},x=C=>{if(!_)try{r.enqueue(C);let A=new TextDecoder().decode(C);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"))_=!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(!_)try{if(!l){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),_=!0;return}if(v>=0){let A={type:"content_block_stop",index:v};x(s.encode(`event: content_block_stop
38
+ `)}if(n.tools&&n.tools.length>0){if(p.tools=Vd(n.tools),e)for(let f of p.tools)f.input_schema??={type:"object",properties:{}};n.tool_choice&&(n.tool_choice==="auto"||e&&n.tool_choice==="none"?p.tool_choice={type:n.tool_choice}: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}))}return p}var va=E(()=>{Qe()});import{v4 as hr}from"uuid";function Yd(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 yr(n){if(!n||typeof n!="object")return!1;let e=n;return e.usage_source==="kiro"||Ct(n)!==void 0||e.usage_estimated===!0||e.kiro_estimated===!0}var bn,Ta=E(()=>{"use strict";Qe();Vt();V();_a();ba();va();Oe();Ve();bn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(c=>c.type==="text"&&c.text).map(c=>({type:"text",text:c.text,cache_control:c.cache_control}));t.push({role:"system",content:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let c=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(c.length){let u=bt(String(e.model??"")),d=[];c.forEach(p=>{let f=Array.isArray(p.content)?p.content:null,h=f?f.filter(m=>m?.type==="image"&&m?.source):[],g=typeof p.content=="string"?p.content:JSON.stringify(p.content);if(h.length>0){let m=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(`
39
+ `);u?(g=m||"[tool image]",d.push(...h)):(g=[m,...h.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
40
+ `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:h.length}))}let y={role:"tool",content:g,tool_call_id:p.tool_use_id,cache_control:p.cache_control};t.push(y)}),d.length>0&&t.push({role:"user",content:d.map(p=>({type:"image_url",image_url:{url:p.source?.type==="base64"?gr(p.source.data,p.source.media_type):p.source.url},media_type:p.source.media_type}))})}let l=i.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);l.length&&t.push({role:"user",content:l.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?gr(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let c={role:"assistant",content:""},l=i.content.filter(p=>p.type==="text"&&p.text);l.length&&(c.content=l.map(p=>p.text).join(`
41
+ `));let u=i.content.filter(p=>p.type==="tool_use"&&p.id);u.length&&(c.tool_calls=u.map(p=>({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.input||{})}})));let d=i.content.find(p=>p.type==="thinking");d&&(c.thinking={content:d.thinking,signature:d.signature}),t.push(c)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice},s=fa(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},l=Yd(e.thinking?.type)??(s!==void 0||(a??0)>0);l!==void 0&&(i.enabled=l),s!==void 0?i.effort=s:a!==void 0&&(i.effort=ke(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=o?.clientEndpoint==="/v1/chat/completions";r&&(o.anthropicChat={cacheMode:t.cacheMode,includeUsage:o.req?.body?.stream_options?.include_usage===!0});let s=ka(e,r),a={};return this.useBearer?(a.authorization=`Bearer ${t.apiKey}`,a["x-api-key"]=void 0):(a["x-api-key"]=t.apiKey,a.authorization=void 0),a["anthropic-version"]="2023-06-01",a["content-type"]="application/json",{body:s,config:{headers:a}}}async transformResponseOut(e,t){if(!t?.anthropicChat)return e;let{cacheMode:o,includeUsage:r}=t.anthropicChat;return ya(e,o,r)}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 le(e);if((r?.isSSE??!1)&&r?.body){let l=await this.convertOpenAIStreamToAnthropic(r.body,t);return new Response(l,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let a;if(r?.body)a=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else{let l=await ye(e);if(l.isSSE){let u=await this.convertOpenAIStreamToAnthropic(l.response.body,t);return new Response(u,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}a=l.response}let i=await j(a),c=this.convertOpenAIResponseToAnthropic(i,t);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,a=`msg_${Date.now()}`,i=null,c=String(t?.req?.body?.model??"unknown"),l=!1,u=!1,d=!1;t?.req&&(t.req.contentDelivered=!1);let p=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,h=new Map,g=0,y=0,m=0,b=!1,_=!1,k=0,v=-1,T=()=>{let R=k;return k++,R},S=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(!l){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};S(s.encode(`event: content_block_stop
42
42
  data: ${JSON.stringify(A)}
43
43
 
44
- `)),v=-1}if(i)x(s.encode(`event: message_delta
44
+ `)),v=-1}if(i)S(s.encode(`event: message_delta
45
45
  data: ${JSON.stringify(i)}
46
46
 
47
- `)),i=null;else{let A=t?.req?.tokenCount||0;x(s.encode(`event: message_delta
47
+ `)),i=null;else{let A=t?.req?.tokenCount||0;S(s.encode(`event: message_delta
48
48
  data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:A,output_tokens:0,cache_read_input_tokens:0}})}
49
49
 
50
- `))}let C={type:"message_stop"};x(s.encode(`event: message_stop
51
- data: ${JSON.stringify(C)}
50
+ `))}let R={type:"message_stop"};S(s.encode(`event: message_stop
51
+ data: ${JSON.stringify(R)}
52
52
 
53
- `)),r.close(),_=!0}catch(C){if(C instanceof TypeError&&C.message.includes("Controller is already closed"))_=!0;else throw C}},E=null;try{E=e.getReader();let C=new TextDecoder,A="";for(;!_;){let{done:F,value:R}=await E.read();if(F)break;A+=C.decode(R,{stream:!0});let O=A.split(`
54
- `);A=O.pop()||"";for(let S of O){if(_)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(m++,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)}};x(s.encode(`event: error
53
+ `)),r.close(),b=!0}catch(R){if(R instanceof TypeError&&R.message.includes("Controller is already closed"))b=!0;else throw R}},P=null;try{P=e.getReader();let R=new TextDecoder,A="";for(;!b;){let{done:D,value:x}=await P.read();if(D)break;A+=R.decode(x,{stream:!0});let O=A.split(`
54
+ `);A=O.pop()||"";for(let C of O){if(b)break;if(!C.startsWith("data:"))continue;let I=C.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)}};S(s.encode(`event: error
55
55
  data: ${JSON.stringify(L)}
56
56
 
57
- `));continue}if(c=M.model&&M.model!=="unknown"?M.model:c,!l&&!_&&!d){l=!0;let L=t?.req?.tokenCount||0,D={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:c,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};x(s.encode(`event: message_start
58
- data: ${JSON.stringify(D)}
57
+ `));continue}if(c=M.model&&M.model!=="unknown"?M.model:c,!l&&!b&&!d){l=!0;let L=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:c,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};S(s.encode(`event: message_start
58
+ data: ${JSON.stringify(F)}
59
59
 
60
- `))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,z=(M.usage?.prompt_tokens||0)-L,q=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:z,output_tokens:q,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let W={input_tokens:z,output_tokens:q,cache_read_input_tokens:L,...hr(M.usage)?{cache_creation_input_tokens:yn(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:{...W}};else{let B=i.usage||{};hr(M.usage)||"cache_creation_input_tokens"in B?i.usage=le(B,W,!1):i.usage={input_tokens:W.input_tokens||B.input_tokens||0,output_tokens:W.output_tokens||B.output_tokens||0,cache_read_input_tokens:W.cache_read_input_tokens||B.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!_&&!d&&!u){if(!b){let L=T();p();let D={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};x(s.encode(`event: content_block_start
61
- data: ${JSON.stringify(D)}
60
+ `))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,F=M.usage?.prompt_tokens||0,z=Ct(M.usage)??F-L,q=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:z,output_tokens:q,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let W={input_tokens:z,output_tokens:q,cache_read_input_tokens:L,...yr(M.usage)?{cache_creation_input_tokens:Tt(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:{...W}};else{let B=i.usage||{};yr(M.usage)||"cache_creation_input_tokens"in B?i.usage=se(B,W,!1):i.usage={input_tokens:W.input_tokens||B.input_tokens||0,output_tokens:W.output_tokens||B.output_tokens||0,cache_read_input_tokens:W.cache_read_input_tokens||B.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!b&&!d&&!u){if(!_){let L=T();p();let F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};S(s.encode(`event: content_block_start
61
+ data: ${JSON.stringify(F)}
62
62
 
63
- `)),v=L,b=!0}if(N.delta.thinking.signature){let L={type:"content_block_delta",index:v,delta:{type:"signature_delta",signature:N.delta.thinking.signature}};x(s.encode(`event: content_block_delta
63
+ `)),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}};S(s.encode(`event: content_block_delta
64
64
  data: ${JSON.stringify(L)}
65
65
 
66
- `));let D={type:"content_block_stop",index:v};x(s.encode(`event: content_block_stop
67
- data: ${JSON.stringify(D)}
66
+ `));let F={type:"content_block_stop",index:v};S(s.encode(`event: content_block_stop
67
+ data: ${JSON.stringify(F)}
68
68
 
69
- `)),v=-1}else if(N.delta.thinking.content){let L={type:"content_block_delta",index:v,delta:{type:"thinking_delta",thinking:N.delta.thinking.content||""}};x(s.encode(`event: content_block_delta
69
+ `)),v=-1}else if(N.delta.thinking.content){let L={type:"content_block_delta",index:v,delta:{type:"thinking_delta",thinking:N.delta.thinking.content||""}};S(s.encode(`event: content_block_delta
70
70
  data: ${JSON.stringify(L)}
71
71
 
72
- `))}}if(N?.delta?.content&&!_&&!d){if(y++,v>=0&&!u){let D={type:"content_block_stop",index:v};x(s.encode(`event: content_block_stop
73
- data: ${JSON.stringify(D)}
72
+ `))}}if(N?.delta?.content&&!b&&!d){if(y++,v>=0&&!u){let F={type:"content_block_stop",index:v};S(s.encode(`event: content_block_stop
73
+ data: ${JSON.stringify(F)}
74
74
 
75
- `)),v=-1}if(!u&&!d){u=!0;let L=T();p();let D={type:"content_block_start",index:L,content_block:{type:"text",text:""}};x(s.encode(`event: content_block_start
76
- data: ${JSON.stringify(D)}
75
+ `)),v=-1}if(!u&&!d){u=!0;let L=T();p();let F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};S(s.encode(`event: content_block_start
76
+ data: ${JSON.stringify(F)}
77
77
 
78
- `)),v=L}if(!_&&!d){let L={type:"content_block_delta",index:v,delta:{type:"text_delta",text:N.delta.content}};x(s.encode(`event: content_block_delta
78
+ `)),v=L}if(!b&&!d){let L={type:"content_block_delta",index:v,delta:{type:"text_delta",text:N.delta.content}};S(s.encode(`event: content_block_delta
79
79
  data: ${JSON.stringify(L)}
80
80
 
81
- `))}}if(N?.delta?.annotations?.length&&!_&&!d){if(v>=0&&u){let L={type:"content_block_stop",index:v};x(s.encode(`event: content_block_stop
81
+ `))}}if(N?.delta?.annotations?.length&&!b&&!d){if(v>=0&&u){let L={type:"content_block_stop",index:v};S(s.encode(`event: content_block_stop
82
82
  data: ${JSON.stringify(L)}
83
83
 
84
- `)),v=-1,u=!1}N?.delta?.annotations.forEach(L=>{let D=T();p();let z={type:"content_block_start",index:D,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${gr()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};x(s.encode(`event: content_block_start
84
+ `)),v=-1,u=!1}N?.delta?.annotations.forEach(L=>{let F=T();p();let z={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${hr()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};S(s.encode(`event: content_block_start
85
85
  data: ${JSON.stringify(z)}
86
86
 
87
- `));let q={type:"content_block_stop",index:D};x(s.encode(`event: content_block_stop
87
+ `));let q={type:"content_block_stop",index:F};S(s.encode(`event: content_block_stop
88
88
  data: ${JSON.stringify(q)}
89
89
 
90
- `)),v=-1})}if(N?.delta?.tool_calls&&!_&&!d){g++;let L=new Set;for(let D of N.delta.tool_calls){if(_)break;let z=D.index??0;if(L.has(z))continue;if(L.add(z),!h.has(z)){if(v>=0){let $l={type:"content_block_stop",index:v};x(s.encode(`event: content_block_stop
91
- data: ${JSON.stringify($l)}
90
+ `)),v=-1})}if(N?.delta?.tool_calls&&!b&&!d){m++;let L=new Set;for(let F of N.delta.tool_calls){if(b)break;let z=F.index??0;if(L.has(z))continue;if(L.add(z),!h.has(z)){if(v>=0){let Dl={type:"content_block_stop",index:v};S(s.encode(`event: content_block_stop
91
+ data: ${JSON.stringify(Dl)}
92
92
 
93
- `)),v=-1}let W=T();h.set(z,W);let B=D.id||`call_ccr_${z}`,$=D.function?.name||`tool_${z}`;p();let K={type:"content_block_start",index:W,content_block:{type:"tool_use",id:B,name:$,input:{}}};x(s.encode(`event: content_block_start
93
+ `)),v=-1}let W=T();h.set(z,W);let B=F.id||`call_ccr_${z}`,$=F.function?.name||`tool_${z}`;p();let K={type:"content_block_start",index:W,content_block:{type:"tool_use",id:B,name:$,input:{}}};S(s.encode(`event: content_block_start
94
94
  data: ${JSON.stringify(K)}
95
95
 
96
- `)),v=W;let Ll={id:B,name:$,arguments:"",contentBlockIndex:W};f.set(z,Ll)}else if(D.id&&D.function?.name){let W=f.get(z);W.id.startsWith("call_")&&W.name.startsWith("tool_")&&(W.id=D.id,W.name=D.function.name)}if(D.function?.arguments&&!_&&!d){let W=h.get(z);if(W===void 0)continue;let B=f.get(z);B&&(B.arguments+=D.function.arguments);try{let $={type:"content_block_delta",index:W,delta:{type:"input_json_delta",partial_json:D.function.arguments}};x(s.encode(`event: content_block_delta
96
+ `)),v=W;let Ul={id:B,name:$,arguments:"",contentBlockIndex:W};f.set(z,Ul)}else if(F.id&&F.function?.name){let W=f.get(z);W.id.startsWith("call_")&&W.name.startsWith("tool_")&&(W.id=F.id,W.name=F.function.name)}if(F.function?.arguments&&!b&&!d){let W=h.get(z);if(W===void 0)continue;let B=f.get(z);B&&(B.arguments+=F.function.arguments);try{let $={type:"content_block_delta",index:W,delta:{type:"input_json_delta",partial_json:F.function.arguments}};S(s.encode(`event: content_block_delta
97
97
  data: ${JSON.stringify($)}
98
98
 
99
- `))}catch{try{let $=D.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),K={type:"content_block_delta",index:W,delta:{type:"input_json_delta",partial_json:$}};x(s.encode(`event: content_block_delta
99
+ `))}catch{try{let $=F.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),K={type:"content_block_delta",index:W,delta:{type:"input_json_delta",partial_json:$}};S(s.encode(`event: content_block_delta
100
100
  data: ${JSON.stringify(K)}
101
101
 
102
- `))}catch($){console.error($)}}}}}if(N?.finish_reason&&!_&&!d){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),v>=0){let L={type:"content_block_stop",index:v};x(s.encode(`event: content_block_stop
102
+ `))}catch($){console.error($)}}}}}if(N?.finish_reason&&!b&&!d){if(y===0&&m===0&&console.error("Warning: No content in the stream response!"),v>=0){let L={type:"content_block_stop",index:v};S(s.encode(`event: content_block_stop
103
103
  data: ${JSON.stringify(L)}
104
104
 
105
- `)),v=-1}if(!_){let D={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:D,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:D,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}d=!0}}catch(M){this.logger?.error(`parseError: ${M.name} message: ${M.message} stack: ${M.stack} data: ${I}`)}}}w()}catch(C){if(!_)try{r.error(C)}catch(A){console.error(A)}}finally{if(E)try{E.releaseLock()}catch(C){console.error(C)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let c=`srvtoolu_${gr()}`;r.push({type:"server_tool_use",id:c,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:c,content:o.message.annotations.map(l=>({type:"web_search_result",url:l.url_citation.url,title:l.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(c=>{let l={};try{let u=c.function.arguments||"{}";typeof u=="object"?l=u:typeof u=="string"&&(l=JSON.parse(u))}catch{l={text:c.function.arguments||""}}r.push({type:"tool_use",id:c.id,name:c.function.name,input:l})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens??e.usage?.prompt_cache_hit_tokens??0,a=(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${gr().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:hr(e.usage)?yn(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 J(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Vd(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ye).includes(o)?o:Ye.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ye).includes(r)?r:Ye.TYPE_UNSPECIFIED})}}}function Tt(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)&&Vd(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let c=i.toUpperCase();e.type=Object.values(Ye).includes(c)?c:Ye.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=Tt(i);else if(o.includes(a)){let c=[];for(let l of i){if(l.type=="null"){e.nullable=!0;continue}c.push(Tt(l))}e[a]=c}else if(r.includes(a)){let c={};for(let[l,u]of Object.entries(i))c[l]=Tt(u);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=i}return e}function Yd(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=Tt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Tt(e.response));return n}function kn(n){let e=[],t=n.tools?.filter(c=>c.function.name!=="web_search")?.map(c=>({name:c.function.name,description:c.function.description,parametersJsonSchema:c.function.parameters}));t?.length&&e.push(Yd({functionDeclarations:t})),n.tools?.find(c=>c.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(c=>c.role==="tool");n.messages.filter(c=>c.role!=="tool").forEach(c=>{let l;c.role==="assistant"?l="model":(["user","system"].includes(c.role),l="user");let u=[];if(typeof c.content=="string"){let d={text:c.content};c.thinking?.signature&&(d.thoughtSignature=c.thinking.signature),u.push(d)}else Array.isArray(c.content)?u.push(...c.content.map(d=>{if(d.type==="text")return{text:d.text||""};if(d.type==="image_url")return d.image_url.url.startsWith("http")?{file_data:{mime_type:d.media_type,file_uri:d.image_url.url}}:{inlineData:{mime_type:d.media_type,data:d.image_url.url?.split(",")?.pop()||d.image_url.url}}})):c.content&&typeof c.content=="object"&&(c.content.text?u.push({text:c.content.text}):u.push({text:JSON.stringify(c.content)}));if(Array.isArray(c.tool_calls)&&u.push(...c.tool_calls.map(d=>{let p={functionCall:{id:d.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:d.function.name,args:JSON.parse(d.function.arguments||"{}")}};return c.thinking?.signature&&(p.thoughtSignature=c.thinking.signature),p})),u.length===0&&u.push({text:""}),r.push({role:l,parts:u}),l==="model"&&c.tool_calls){let d=c.tool_calls.map(p=>{let f=s.find(h=>h.tool_call_id===p.id);return{functionResponse:{name:p?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:d})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let c=n.model.includes("pro")?[128,32768]:[0,24576],l,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=c[0]&&u<=c[1]?l=u:u<c[0]?l=c[0]:u>c[1]&&(l=c[1]),a.thinkingConfig.thinkingBudget=l)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};if(n.tool_choice){let c={functionCallingConfig:{}};n.tool_choice==="auto"?c.functionCallingConfig.mode="auto":n.tool_choice==="none"?c.functionCallingConfig.mode="none":n.tool_choice==="required"?c.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(c.functionCallingConfig.mode="any",c.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),i.toolConfig=c}return i}function vn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,c={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};return Array.isArray(e)&&e.forEach(l=>{typeof l=="string"?c.messages.push({role:"user",content:l}):typeof l.text=="string"?c.messages.push({role:"user",content:l.text||null}):l.role==="user"?c.messages.push({role:"user",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):l.role==="model"&&c.messages.push({role:"assistant",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(c.tools=[],t.forEach(l=>{Array.isArray(l.functionDeclarations)&&l.functionDeclarations.forEach(u=>{c.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),c}function bn(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 _r(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 yr(n,e,t){let o=e?_r(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:bn(n.usageMetadata)}:{}}}async function Tn(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 d of a)d.text&&d.thought===!0?r+=d.text:i.push(d);s=a.find(d=>d.thoughtSignature)?.thoughtSignature;let c=i?.filter(d=>d.functionCall)?.map(d=>({id:d.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:d.functionCall?.name,arguments:JSON.stringify(d.functionCall?.args||{})}}))||[],l=i?.filter(d=>d.text)?.map(d=>d.text)?.join(`
106
- `)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:l,role:"assistant",tool_calls:c.length>0?c:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:bn(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,c="",l=0,u=-1,d=new ReadableStream({async start(p){let f=async(y,g)=>{if(y.startsWith("data: ")){let _=y.slice(6).trim();if(_){t?.debug({chunkStr:_},`${e} chunk:`);try{let b=JSON.parse(_);if(!b.candidates||!b.candidates[0]){if(b.usageMetadata){g.enqueue(r.encode(`data: ${JSON.stringify(yr(b,void 0,l))}
105
+ `)),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}}}d=!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(P)try{P.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 c=`srvtoolu_${hr()}`;r.push({type:"server_tool_use",id:c,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:c,content:o.message.annotations.map(l=>({type:"web_search_result",url:l.url_citation.url,title:l.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(c=>{let l={};try{let u=c.function.arguments||"{}";typeof u=="object"?l=u:typeof u=="string"&&(l=JSON.parse(u))}catch{l={text:c.function.arguments||""}}r.push({type:"tool_use",id:c.id,name:c.function.name,input:l})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens??e.usage?.prompt_cache_hit_tokens??0,a=Ct(e.usage)??(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${hr().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:yr(e.usage)?Tt(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 J(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Xd(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ye).includes(o)?o:Ye.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ye).includes(r)?r:Ye.TYPE_UNSPECIFIED})}}}function St(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)&&Xd(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let c=i.toUpperCase();e.type=Object.values(Ye).includes(c)?c:Ye.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=St(i);else if(o.includes(a)){let c=[];for(let l of i){if(l.type=="null"){e.nullable=!0;continue}c.push(St(l))}e[a]=c}else if(r.includes(a)){let c={};for(let[l,u]of Object.entries(i))c[l]=St(u);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=i}return e}function Zd(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=St(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=St(e.response));return n}function vn(n){let e=[],t=n.tools?.filter(c=>c.function.name!=="web_search")?.map(c=>({name:c.function.name,description:c.function.description,parametersJsonSchema:c.function.parameters}));t?.length&&e.push(Zd({functionDeclarations:t})),n.tools?.find(c=>c.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(c=>c.role==="tool");n.messages.filter(c=>c.role!=="tool").forEach(c=>{let l;c.role==="assistant"?l="model":(["user","system"].includes(c.role),l="user");let u=[];if(typeof c.content=="string"){let d={text:c.content};c.thinking?.signature&&(d.thoughtSignature=c.thinking.signature),u.push(d)}else Array.isArray(c.content)?u.push(...c.content.map(d=>{if(d.type==="text")return{text:d.text||""};if(d.type==="image_url")return d.image_url.url.startsWith("http")?{file_data:{mime_type:d.media_type,file_uri:d.image_url.url}}:{inlineData:{mime_type:d.media_type,data:d.image_url.url?.split(",")?.pop()||d.image_url.url}}})):c.content&&typeof c.content=="object"&&(c.content.text?u.push({text:c.content.text}):u.push({text:JSON.stringify(c.content)}));if(Array.isArray(c.tool_calls)&&u.push(...c.tool_calls.map(d=>{let p={functionCall:{id:d.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:d.function.name,args:JSON.parse(d.function.arguments||"{}")}};return c.thinking?.signature&&(p.thoughtSignature=c.thinking.signature),p})),u.length===0&&u.push({text:""}),r.push({role:l,parts:u}),l==="model"&&c.tool_calls){let d=c.tool_calls.map(p=>{let f=s.find(h=>h.tool_call_id===p.id);return{functionResponse:{name:p?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:d})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let c=n.model.includes("pro")?[128,32768]:[0,24576],l,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=c[0]&&u<=c[1]?l=u:u<c[0]?l=c[0]:u>c[1]&&(l=c[1]),a.thinkingConfig.thinkingBudget=l)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};if(n.tool_choice){let c={functionCallingConfig:{}};n.tool_choice==="auto"?c.functionCallingConfig.mode="auto":n.tool_choice==="none"?c.functionCallingConfig.mode="none":n.tool_choice==="required"?c.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(c.functionCallingConfig.mode="any",c.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),i.toolConfig=c}return i}function Tn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,c={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};return Array.isArray(e)&&e.forEach(l=>{typeof l=="string"?c.messages.push({role:"user",content:l}):typeof l.text=="string"?c.messages.push({role:"user",content:l.text||null}):l.role==="user"?c.messages.push({role:"user",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):l.role==="model"&&c.messages.push({role:"assistant",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(c.tools=[],t.forEach(l=>{Array.isArray(l.functionDeclarations)&&l.functionDeclarations.forEach(u=>{c.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),c}function kn(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 br(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 _r(n,e,t){let o=e?br(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:kn(n.usageMetadata)}:{}}}async function Cn(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 d of a)d.text&&d.thought===!0?r+=d.text:i.push(d);s=a.find(d=>d.thoughtSignature)?.thoughtSignature;let c=i?.filter(d=>d.functionCall)?.map(d=>({id:d.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:d.functionCall?.name,arguments:JSON.stringify(d.functionCall?.args||{})}}))||[],l=i?.filter(d=>d.text)?.map(d=>d.text)?.join(`
106
+ `)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:l,role:"assistant",tool_calls:c.length>0?c:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:kn(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,c="",l=0,u=-1,d=new ReadableStream({async start(p){let f=async(y,m)=>{if(y.startsWith("data: ")){let b=y.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){if(_.usageMetadata){m.enqueue(r.encode(`data: ${JSON.stringify(_r(_,void 0,l))}
107
107
 
108
- `));return}t?.debug({chunkStr:_},"Invalid chunk structure");return}let k=b.candidates[0],v=!1,T=k.content?.parts||[];T.filter(C=>C.text&&C.thought===!0).forEach(C=>{i||(i=!0);let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:C.text}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(r.encode(`data: ${JSON.stringify(A)}
108
+ `));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],v=!1,T=k.content?.parts||[];T.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:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(r.encode(`data: ${JSON.stringify(A)}
109
109
 
110
- `))});let x=T.find(C=>C.thoughtSignature)?.thoughtSignature;if(x&&!s){if(!i){let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(r.encode(`data: ${JSON.stringify(A)}
110
+ `))});let S=T.find(R=>R.thoughtSignature)?.thoughtSignature;if(S&&!s){if(!i){let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(r.encode(`data: ${JSON.stringify(A)}
111
111
 
112
- `))}let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:x}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(g.enqueue(r.encode(`data: ${JSON.stringify(C)}
112
+ `))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:S}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(r.encode(`data: ${JSON.stringify(R)}
113
113
 
114
- `)),s=!0,l++,c){let A={choices:[{delta:{role:"assistant",content:c},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(r.encode(`data: ${JSON.stringify(A)}
114
+ `)),s=!0,l++,c){let A={choices:[{delta:{role:"assistant",content:c},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(r.encode(`data: ${JSON.stringify(A)}
115
115
 
116
- `)),c="",a||(a=!0)}}let w=T.filter(C=>C.functionCall).map(C=>({id:C.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})}})),E=T.filter(C=>C.text&&C.thought!==!0).map(C=>C.text).join(`
117
- `);if(!E&&s&&!a){let C={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(r.encode(`data: ${JSON.stringify(C)}
116
+ `)),c="",a||(a=!0)}}let w=T.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||{})}})),P=T.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
117
+ `);if(!P&&s&&!a){let R={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(r.encode(`data: ${JSON.stringify(R)}
118
118
 
119
- `)),a||(a=!0)}if(i&&E&&!s)if(b.modelVersion?.includes("3")){c+=E,b.usageMetadata&&g.enqueue(r.encode(`data: ${JSON.stringify(yr(b,k,l))}
119
+ `)),a||(a=!0)}if(i&&P&&!s)if(_.modelVersion?.includes("3")){c+=P,_.usageMetadata&&m.enqueue(r.encode(`data: ${JSON.stringify(_r(_,k,l))}
120
120
 
121
- `));return}else{let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(r.encode(`data: ${JSON.stringify(C)}
121
+ `));return}else{let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(r.encode(`data: ${JSON.stringify(R)}
122
122
 
123
- `)),s=!0}if(E){c||l++;let C={choices:[{delta:{role:"assistant",content:E},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:bn(b.usageMetadata)},A=_r(k);A&&(C.choices[0].delta.annotations=A),g.enqueue(r.encode(`data: ${JSON.stringify(C)}
123
+ `)),s=!0}if(P){c||l++;let R={choices:[{delta:{role:"assistant",content:P},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:kn(_.usageMetadata)},A=br(k);A&&(R.choices[0].delta.annotations=A),m.enqueue(r.encode(`data: ${JSON.stringify(R)}
124
124
 
125
- `)),v=!0,!a&&E&&(a=!0)}w.length>0&&(w.forEach(C=>{l++,u++;let A={choices:[{delta:{role:"assistant",tool_calls:[{...C,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:bn(b.usageMetadata)},F=_r(k);F&&(A.choices[0].delta.annotations=F),g.enqueue(r.encode(`data: ${JSON.stringify(A)}
125
+ `)),v=!0,!a&&P&&(a=!0)}w.length>0&&(w.forEach(R=>{l++,u++;let A={choices:[{delta:{role:"assistant",tool_calls:[{...R,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:kn(_.usageMetadata)},D=br(k);D&&(A.choices[0].delta.annotations=D),m.enqueue(r.encode(`data: ${JSON.stringify(A)}
126
126
 
127
- `)),v=!0}),!a&&E&&(a=!0)),!v&&(k.finishReason||b.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&g.enqueue(r.encode(`data: ${JSON.stringify(yr(b,k,l))}
127
+ `)),v=!0}),!a&&P&&(a=!0)),!v&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&m.enqueue(r.encode(`data: ${JSON.stringify(_r(_,k,l))}
128
128
 
129
- `))}catch(b){t?.error(`Error parsing ${e} stream chunk`,_,b.message)}}}},h=n.body.getReader(),m="";try{for(;;){let{done:y,value:g}=await h.read();if(y){m&&await f(m,p);break}m+=o.decode(g,{stream:!0});let _=m.split(`
130
- `);m=_.pop()||"";for(let b of _)await f(b,p)}}catch(y){p.error(y)}finally{p.close()}}});return new Response(d,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ye,br=P(()=>{"use strict";Ye={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var Cn,va=P(()=>{"use strict";br();Cn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:kn(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=vn;async transformResponseOut(e){return Tn(e,this.name,this.logger)}}});async function Xd(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
129
+ `))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},h=n.body.getReader(),g="";try{for(;;){let{done:y,value:m}=await h.read();if(y){g&&await f(g,p);break}g+=o.decode(m,{stream:!0});let b=g.split(`
130
+ `);g=b.pop()||"";for(let _ of b)await f(_,p)}}catch(y){p.error(y)}finally{p.close()}}});return new Response(d,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ye,kr=E(()=>{"use strict";Ye={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var Sn,Ca=E(()=>{"use strict";kr();Sn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:vn(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=Tn;async transformResponseOut(e){return Cn(e,this.name,this.logger)}}});async function qd(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
131
131
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
132
132
  2. Run "gcloud auth application-default login"
133
- 3. Use Google Cloud environment with default service account`)}}var Sn,Ta=P(()=>{"use strict";br();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"),c=JSON.parse(i);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Xd();return{body:kn(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return vn(e)}async transformResponseOut(e){return Tn(e,this.name)}}});var xn,Ca=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 l=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);l&&(i=l[1].trim(),r.content=r.content.replace(l[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await 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(c){let l=e.body.getReader(),u=(p,f,h)=>{let m=p.split(`
134
- `);for(let y of m)y.trim()&&f.enqueue(h.encode(y+`
135
- `))},d=(p,f)=>{let{controller:h,encoder:m}=f;if(p.startsWith("data: ")&&p.trim()!=="data: [DONE]")try{let y=JSON.parse(p.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(y.choices[0].delta.reasoning_content);let g={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(g)}
133
+ 3. Use Google Cloud environment with default service account`)}}var xn,Sa=E(()=>{"use strict";kr();xn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(i);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await qd();return{body:vn(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 Tn(e)}async transformResponseOut(e){return Cn(e,this.name)}}});var Rn,xa=E(()=>{"use strict";V();Rn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,i="";if(typeof r.content=="string"){let l=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);l&&(i=l[1].trim(),r.content=r.content.replace(l[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await 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(c){let l=e.body.getReader(),u=(p,f,h)=>{let g=p.split(`
134
+ `);for(let y of g)y.trim()&&f.enqueue(h.encode(y+`
135
+ `))},d=(p,f)=>{let{controller:h,encoder:g}=f;if(p.startsWith("data: ")&&p.trim()!=="data: [DONE]")try{let y=JSON.parse(p.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(y.choices[0].delta.reasoning_content);let m={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(m)}
136
136
 
137
- `;h.enqueue(m.encode(_));return}if(y.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let g="ccr_think_signature",_=y.choices[0].delta.content,b={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:g}}}]};delete b.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(b)}
137
+ `;h.enqueue(g.encode(b));return}if(y.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let m="ccr_think_signature",b=y.choices[0].delta.content,_={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:m}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
138
138
 
139
- `;h.enqueue(m.encode(k));let v={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:_}}]};delete v.choices[0].delta.reasoning_content;let T=`data: ${JSON.stringify(v)}
139
+ `;h.enqueue(g.encode(k));let v={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:b}}]};delete v.choices[0].delta.reasoning_content;let T=`data: ${JSON.stringify(v)}
140
140
 
141
- `;h.enqueue(m.encode(T));return}if(y.choices[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let g=`data: ${JSON.stringify(y)}
141
+ `;h.enqueue(g.encode(T));return}if(y.choices[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let m=`data: ${JSON.stringify(y)}
142
142
 
143
- `;h.enqueue(m.encode(g))}}catch{h.enqueue(m.encode(p+`
144
- `))}else h.enqueue(m.encode(p+`
145
- `))};try{for(;;){let{done:p,value:f}=await l.read();if(p){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let m=a.split(`
146
- `);a=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:g=>r+=g,isReasoningComplete:()=>s,setReasoningComplete:g=>s=g})}catch(g){console.error("Error processing line:",y,g),c.enqueue(o.encode(y+`
147
- `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{l.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Rn,Sa=P(()=>{"use strict";V();Rn=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
143
+ `;h.enqueue(g.encode(m))}}catch{h.enqueue(g.encode(p+`
144
+ `))}else h.enqueue(g.encode(p+`
145
+ `))};try{for(;;){let{done:p,value:f}=await l.read();if(p){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
146
+ `);a=g.pop()||"";for(let y of g)if(y.trim())try{d(y,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:m=>r+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",y,m),c.enqueue(o.encode(y+`
147
+ `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{l.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var wn,Ra=E(()=>{"use strict";V();wn=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
148
148
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
149
149
  Examples:
150
150
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
151
- 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await 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(c){let l=e.body.getReader(),u=(p,f,h)=>{let m=p.split(`
152
- `);for(let y of m)y.trim()&&f.enqueue(h.encode(y+`
153
- `))},d=(p,f)=>{let{controller:h,encoder:m,exitToolIndex:y,setExitToolIndex:g,appendExitToolResponse:_}=f;if(p.startsWith("data: ")&&p.trim()!=="data: [DONE]")try{let b=JSON.parse(p.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let k=b.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){g(k.index);return}else if(y()>-1&&k.index===y()&&k.function.arguments){_(k.function.arguments);try{let v=JSON.parse(f.exitToolResponse());b.choices=[{delta:{role:"assistant",content:v.response||""}}];let T=`data: ${JSON.stringify(b)}
154
-
155
- `;h.enqueue(m.encode(T))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let k=`data: ${JSON.stringify(b)}
156
-
157
- `;h.enqueue(m.encode(k))}}catch{h.enqueue(m.encode(p+`
158
- `))}else h.enqueue(m.encode(p+`
159
- `))};try{for(;;){let{done:p,value:f}=await l.read();if(p){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let m=a.split(`
160
- `);a=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:c,encoder:o,exitToolIndex:()=>r,setExitToolIndex:g=>r=g,exitToolResponse:()=>s,appendExitToolResponse:g=>s+=g})}catch(g){console.error("Error processing line:",y,g),c.enqueue(o.encode(y+`
161
- `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{l.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as Zd}from"uuid";var wn,xa=P(()=>{"use strict";V();wn=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,c="",l=new ReadableStream({async start(u){let d=e.body.getReader(),p=(h,m,y)=>{let g=h.split(`
162
- `);for(let _ of g)_.trim()&&m.enqueue(y.encode(_+`
163
- `))},f=(h,m)=>{let{controller:y,encoder:g}=m;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let _=h.slice(6);try{let b=JSON.parse(_);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:i},"usage"),b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){y.enqueue(g.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
164
-
165
- `));return}b.choices?.[0]?.delta?.content&&!m.hasTextContent()&&m.setHasTextContent(!0);let k=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(k){m.appendReasoningContent(k);let E={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:k}}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let C=`data: ${JSON.stringify(E)}
166
-
167
- `;y.enqueue(g.encode(C));return}if(b.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let E="ccr_think_signature",C=b.choices[0].delta.content,A={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:E}}}]};A.choices?.[0]?.delta&&delete A.choices[0].delta.reasoning;let F=`data: ${JSON.stringify(A)}
168
-
169
- `;y.enqueue(g.encode(F));let R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:C}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content);let O=`data: ${JSON.stringify(R)}
170
-
171
- `;y.enqueue(g.encode(O));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(E=>{E.id=`call_${Zd()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let v=b.choices?.[0]?.delta,T=v&&Object.keys(v).length>0,x=b.choices?.[0]?.finish_reason,w=b.usage;if(T||x||w){let E=`data: ${JSON.stringify(b)}
172
-
173
- `;y.enqueue(g.encode(E))}}catch{y.enqueue(g.encode(h+`
174
- `))}}else y.enqueue(g.encode(h+`
175
- `))};try{for(;;){let{done:h,value:m}=await d.read();if(h){c.trim()&&p(c,u,o);break}if(!m||m.length===0)continue;let y;try{y=t.decode(m,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=c.split(`
176
- `);c=_.pop()||"";for(let b of _)if(b.trim())try{f(b,{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:",b,k),u.enqueue(o.encode(b+`
177
- `))}continue}let g=c.split(`
178
- `);c=g.pop()||"";for(let _ of g)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),u.enqueue(o.encode(_+`
179
- `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Pn,Ra=P(()=>{"use strict";Pn=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 qd}from"uuid";var En,wa=P(()=>{"use strict";V();En=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="",c=new ReadableStream({async start(l){let u=e.body.getReader(),d=(f,h,m)=>{let y=f.split(`
180
- `);for(let g of y)g.trim()&&h.enqueue(m.encode(g+`
181
- `))},p=(f,h)=>{let{controller:m,encoder:y}=h;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let g=f.slice(6);try{let _=JSON.parse(g);if(_.error)throw new Error(JSON.stringify(_));_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.tool_calls?.length&&_.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${qd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let b=`data: ${JSON.stringify(_)}
182
-
183
- `;m.enqueue(y.encode(b))}catch{m.enqueue(y.encode(f+`
184
- `))}}else m.enqueue(y.encode(f+`
185
- `))};try{for(;;){let{done:f,value:h}=await u.read();if(f){i.trim()&&d(i,l,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(g){console.warn("Failed to decode chunk",g);continue}if(m.length===0)continue;if(i+=m,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let g=i.split(`
186
- `);i=g.pop()||"";for(let _ of g)if(_.trim())try{p(_,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),l.enqueue(o.encode(_+`
151
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await 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(c){let l=e.body.getReader(),u=(p,f,h)=>{let g=p.split(`
152
+ `);for(let y of g)y.trim()&&f.enqueue(h.encode(y+`
153
+ `))},d=(p,f)=>{let{controller:h,encoder:g,exitToolIndex:y,setExitToolIndex:m,appendExitToolResponse:b}=f;if(p.startsWith("data: ")&&p.trim()!=="data: [DONE]")try{let _=JSON.parse(p.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){m(k.index);return}else if(y()>-1&&k.index===y()&&k.function.arguments){b(k.function.arguments);try{let v=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:v.response||""}}];let T=`data: ${JSON.stringify(_)}
154
+
155
+ `;h.enqueue(g.encode(T))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
156
+
157
+ `;h.enqueue(g.encode(k))}}catch{h.enqueue(g.encode(p+`
158
+ `))}else h.enqueue(g.encode(p+`
159
+ `))};try{for(;;){let{done:p,value:f}=await l.read();if(p){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
160
+ `);a=g.pop()||"";for(let y of g)if(y.trim())try{d(y,{controller:c,encoder:o,exitToolIndex:()=>r,setExitToolIndex:m=>r=m,exitToolResponse:()=>s,appendExitToolResponse:m=>s+=m})}catch(m){console.error("Error processing line:",y,m),c.enqueue(o.encode(y+`
161
+ `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{l.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as ep}from"uuid";var Pn,wa=E(()=>{"use strict";V();Pn=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,c="",l=new ReadableStream({async start(u){let d=e.body.getReader(),p=(h,g,y)=>{let m=h.split(`
162
+ `);for(let b of m)b.trim()&&g.enqueue(y.encode(b+`
163
+ `))},f=(h,g)=>{let{controller:y,encoder:m}=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"){y.enqueue(m.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
164
+
165
+ `));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 P={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content);let R=`data: ${JSON.stringify(P)}
166
+
167
+ `;y.enqueue(m.encode(R));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let P="ccr_think_signature",R=_.choices[0].delta.content,A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:P}}}]};A.choices?.[0]?.delta&&delete A.choices[0].delta.reasoning;let D=`data: ${JSON.stringify(A)}
168
+
169
+ `;y.enqueue(m.encode(D));let x={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:R}}]};x.choices?.[0]?.delta&&(delete x.choices[0].delta.reasoning,delete x.choices[0].delta.reasoning_content);let O=`data: ${JSON.stringify(x)}
170
+
171
+ `;y.enqueue(m.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(P=>{P.id=`call_${ep()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let v=_.choices?.[0]?.delta,T=v&&Object.keys(v).length>0,S=_.choices?.[0]?.finish_reason,w=_.usage;if(T||S||w){let P=`data: ${JSON.stringify(_)}
172
+
173
+ `;y.enqueue(m.encode(P))}}catch{y.enqueue(m.encode(h+`
174
+ `))}}else y.enqueue(m.encode(h+`
175
+ `))};try{for(;;){let{done:h,value:g}=await d.read();if(h){c.trim()&&p(c,u,o);break}if(!g||g.length===0)continue;let y;try{y=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
176
+ `);c=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(_+`
177
+ `))}continue}let m=c.split(`
178
+ `);c=m.pop()||"";for(let b of m)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+`
179
+ `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var En,Pa=E(()=>{"use strict";En=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});import{v4 as tp}from"uuid";var An,Ea=E(()=>{"use strict";V();An=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="",c=new ReadableStream({async start(l){let u=e.body.getReader(),d=(f,h,g)=>{let y=f.split(`
180
+ `);for(let m of y)m.trim()&&h.enqueue(g.encode(m+`
181
+ `))},p=(f,h)=>{let{controller:g,encoder:y}=h;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let m=f.slice(6);try{let b=JSON.parse(m);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_${tp()}`}),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)}
182
+
183
+ `;g.enqueue(y.encode(_))}catch{g.enqueue(y.encode(f+`
184
+ `))}}else g.enqueue(y.encode(f+`
185
+ `))};try{for(;;){let{done:f,value:h}=await u.read();if(f){i.trim()&&d(i,l,o);break}if(!h||h.length===0)continue;let g;try{g=t.decode(h,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(g.length===0)continue;if(i+=g,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=i.split(`
186
+ `);i=m.pop()||"";for(let b of m)if(b.trim())try{p(b,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),l.enqueue(o.encode(b+`
187
187
  `))}continue}let y=i.split(`
188
- `);i=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",g,_),l.enqueue(o.encode(g+`
189
- `))}}}catch(f){console.error("Stream error:",f),l.error(f)}finally{try{u.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var An,Pa=P(()=>{"use strict";An=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 ep from"json5";import{jsonrepair as tp}from"jsonrepair";function kr(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=ep.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=tp(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 Ea=P(()=>{});var On,Aa=P(()=>{"use strict";Ea();V();On=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=kr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,c=!1,l="",u=new ReadableStream({async start(d){let p=e.body.getReader(),f=(y,g,_)=>{let b=y.split(`
190
- `);for(let k of b)k.trim()&&g.enqueue(_.encode(k+`
191
- `))},h=(y,g,_)=>{let b="";try{b=kr(r.arguments||"",this.logger)}catch(x){console.error(`${x.message} ${x.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),b=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:b},id:r.id,index:r.index,type:"function"}]},v={...y,choices:[{...y.choices[0],delta:k}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let T=`data: ${JSON.stringify(v)}
188
+ `);i=y.pop()||"";for(let m of y)if(m.trim())try{p(m,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",m,b),l.enqueue(o.encode(m+`
189
+ `))}}}catch(f){console.error("Stream error:",f),l.error(f)}finally{try{u.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var On,Aa=E(()=>{"use strict";On=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 np from"json5";import{jsonrepair as op}from"jsonrepair";function vr(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=np.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=op(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 Oa=E(()=>{});var In,Ia=E(()=>{"use strict";Oa();V();In=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=vr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,c=!1,l="",u=new ReadableStream({async start(d){let p=e.body.getReader(),f=(y,m,b)=>{let _=y.split(`
190
+ `);for(let k of _)k.trim()&&m.enqueue(b.encode(k+`
191
+ `))},h=(y,m,b)=>{let _="";try{_=vr(r.arguments||"",this.logger)}catch(S){console.error(`${S.message} ${S.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={...y,choices:[{...y.choices[0],delta:k}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let T=`data: ${JSON.stringify(v)}
192
192
 
193
- `;g.enqueue(_.encode(T))},m=(y,g)=>{let{controller:_,encoder:b}=g;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let k=y.slice(6);try{let v=JSON.parse(k);if(v.choices?.[0]?.delta?.tool_calls?.length){let x=v.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:x.index,name:x.function?.name||"",id:x.id||"",arguments:x.function?.arguments||""},x.function?.arguments&&(x.function.arguments="");let w=`data: ${JSON.stringify(v)}
193
+ `;m.enqueue(b.encode(T))},g=(y,m)=>{let{controller:b,encoder:_}=m;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let k=y.slice(6);try{let v=JSON.parse(k);if(v.choices?.[0]?.delta?.tool_calls?.length){let S=v.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:S.index,name:S.function?.name||"",id:S.id||"",arguments:S.function?.arguments||""},S.function?.arguments&&(S.function.arguments="");let w=`data: ${JSON.stringify(v)}
194
194
 
195
- `;_.enqueue(b.encode(w));return}else if(r.index===x.index){x.function?.arguments&&(r.arguments+=x.function.arguments);return}else{h(v,_,b),r={index:x.index,name:x.function?.name||"",id:x.id||"",arguments:x.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&&g.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let T=`data: ${JSON.stringify(v)}
195
+ `;b.enqueue(_.encode(w));return}else if(r.index===S.index){S.function?.arguments&&(r.arguments+=S.function.arguments);return}else{h(v,b,_),r={index:S.index,name:S.function?.name||"",id:S.id||"",arguments:S.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&&m.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let T=`data: ${JSON.stringify(v)}
196
196
 
197
- `;_.enqueue(b.encode(T))}catch{_.enqueue(b.encode(y+`
198
- `))}}else _.enqueue(b.encode(y+`
199
- `))};try{for(;;){let{done:y,value:g}=await p.read();if(y){l.trim()&&f(l,d,o);break}if(!g||g.length===0)continue;let _;try{_=t.decode(g,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(_.length===0)continue;if(l+=_,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
200
- `);l=k.pop()||"";for(let v of k)if(v.trim())try{m(v,{controller:d,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",v,T),d.enqueue(o.encode(v+`
201
- `))}continue}let b=l.split(`
202
- `);l=b.pop()||"";for(let k of b)if(k.trim())try{m(k,{controller:d,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),d.enqueue(o.encode(k+`
203
- `))}}}catch(y){console.error("Stream error:",y),d.error(y)}finally{try{p.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}d.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var In,Oa=P(()=>{"use strict";V();Qe();In=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??hn(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(c){let l=e.body.getReader(),u=(p,f,h)=>{let m=p.split(`
204
- `);for(let y of m)y.trim()&&f.enqueue(h.encode(y+`
205
- `))},d=(p,f)=>{let{controller:h,encoder:m}=f;if(this.logger?.debug({line:p},"Processing reason line"),p.startsWith("data: ")&&p.trim()!=="data: [DONE]")try{let y=JSON.parse(p.slice(6));if(console.log(JSON.stringify(y)),y.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(y.choices[0].delta.reasoning_content);let g={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(g)}
197
+ `;b.enqueue(_.encode(T))}catch{b.enqueue(_.encode(y+`
198
+ `))}}else b.enqueue(_.encode(y+`
199
+ `))};try{for(;;){let{done:y,value:m}=await p.read();if(y){l.trim()&&f(l,d,o);break}if(!m||m.length===0)continue;let b;try{b=t.decode(m,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(b.length===0)continue;if(l+=b,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
200
+ `);l=k.pop()||"";for(let v of k)if(v.trim())try{g(v,{controller:d,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",v,T),d.enqueue(o.encode(v+`
201
+ `))}continue}let _=l.split(`
202
+ `);l=_.pop()||"";for(let k of _)if(k.trim())try{g(k,{controller:d,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),d.enqueue(o.encode(k+`
203
+ `))}}}catch(y){console.error("Stream error:",y),d.error(y)}finally{try{p.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}d.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Mn,Ma=E(()=>{"use strict";V();Qe();Mn=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??_n(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(c){let l=e.body.getReader(),u=(p,f,h)=>{let g=p.split(`
204
+ `);for(let y of g)y.trim()&&f.enqueue(h.encode(y+`
205
+ `))},d=(p,f)=>{let{controller:h,encoder:g}=f;if(this.logger?.debug({line:p},"Processing reason line"),p.startsWith("data: ")&&p.trim()!=="data: [DONE]")try{let y=JSON.parse(p.slice(6));if(console.log(JSON.stringify(y)),y.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(y.choices[0].delta.reasoning_content);let m={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(m)}
206
206
 
207
- `;h.enqueue(m.encode(_));return}if(y.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let g="ccr_think_signature",_=y.choices[0].delta.content,b={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:g}}}]};delete b.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(b)}
207
+ `;h.enqueue(g.encode(b));return}if(y.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let m="ccr_think_signature",b=y.choices[0].delta.content,_={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:m}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
208
208
 
209
- `;h.enqueue(m.encode(k))}if(y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){f.isReasoningComplete()&&y.choices[0].index++;let g=`data: ${JSON.stringify(y)}
209
+ `;h.enqueue(g.encode(k))}if(y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){f.isReasoningComplete()&&y.choices[0].index++;let m=`data: ${JSON.stringify(y)}
210
210
 
211
- `;h.enqueue(m.encode(g))}}catch{h.enqueue(m.encode(p+`
212
- `))}else h.enqueue(m.encode(p+`
213
- `))};try{for(;;){let{done:p,value:f}=await l.read();if(p){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let m=a.split(`
214
- `);a=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:g=>r+=g,isReasoningComplete:()=>s,setReasoningComplete:g=>s=g})}catch(g){console.error("Error processing line:",y,g),c.enqueue(o.encode(y+`
215
- `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{l.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Mn,Ia=P(()=>{"use strict";Mn=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 Ln,Ma=P(()=>{"use strict";Ln=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function La(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(c=>{c.type==="text"?i.push({type:"text",text:c.text||""}):c.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:c.media_type||"image/jpeg",data:c.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function $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 Na(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,c)=>{if(i.startsWith("data: ")){let l=i.slice(6).trim();if(l){t?.debug({chunkStr:l},`${e} chunk:`);try{let u=JSON.parse(l);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let d={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
211
+ `;h.enqueue(g.encode(m))}}catch{h.enqueue(g.encode(p+`
212
+ `))}else h.enqueue(g.encode(p+`
213
+ `))};try{for(;;){let{done:p,value:f}=await l.read();if(p){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
214
+ `);a=g.pop()||"";for(let y of g)if(y.trim())try{d(y,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:m=>r+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",y,m),c.enqueue(o.encode(y+`
215
+ `))}}}catch(p){console.error("Stream error:",p),c.error(p)}finally{try{l.releaseLock()}catch(p){console.error("Error releasing reader lock:",p)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Ln,La=E(()=>{"use strict";Ln=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var $n,$a=E(()=>{"use strict";$n=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function Na(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(c=>{c.type==="text"?i.push({type:"text",text:c.text||""}):c.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:c.media_type||"image/jpeg",data:c.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function Ua(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 Da(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,c)=>{if(i.startsWith("data: ")){let l=i.slice(6).trim();if(l){t?.debug({chunkStr:l},`${e} chunk:`);try{let u=JSON.parse(l);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let d={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
216
216
 
217
217
  `))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let d={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
218
218
 
@@ -225,100 +225,100 @@ Examples:
225
225
  `));else{let d={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(d)}
226
226
 
227
227
  `))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,l,u.message)}}}},a=new ReadableStream({async start(i){let c=n.body.getReader(),l="";try{for(;;){let{done:u,value:d}=await c.read();if(u){l&&s(l,i);break}l+=o.decode(d,{stream:!0});let p=l.split(`
228
- `);l=p.pop()||"";for(let f of p)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 Ua=P(()=>{"use strict"});async function np(){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:
228
+ `);l=p.pop()||"";for(let f of p)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 Fa=E(()=>{"use strict"});async function rp(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
229
229
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
230
230
  2. Run "gcloud auth application-default login"
231
- 3. Use Google Cloud environment with default service account`)}}var $n,Da=P(()=>{"use strict";Ua();$n=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(i);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await np();return{body:La(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 Na(e,this.name,this.logger)}}});var Nn,Fa=P(()=>{"use strict";Nn=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 Un,ja=P(()=>{"use strict";Un=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Dn,Ha=P(()=>{"use strict";Dn=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Fn,za=P(()=>{"use strict";Fn=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 op}from"uuid";var jn,Ba=P(()=>{"use strict";V();jn=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await 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,c="",l=new ReadableStream({async start(u){let d=e.body.getReader(),p=(h,m,y)=>{let g=h.split(`
232
- `);for(let _ of g)_.trim()&&m.enqueue(y.encode(_+`
233
- `))},f=(h,m)=>{let{controller:y,encoder:g}=m;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let _=h.slice(6);try{let b=JSON.parse(_);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:i},"usage"),b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&y.enqueue(g.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
231
+ 3. Use Google Cloud environment with default service account`)}}var Nn,ja=E(()=>{"use strict";Fa();Nn=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),c=JSON.parse(i);c&&c.project_id&&(o=c.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await rp();return{body:Na(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 Ua(e)}async transformResponseOut(e){return Da(e,this.name,this.logger)}}});var Un,Ha=E(()=>{"use strict";Un=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 Dn,za=E(()=>{"use strict";Dn=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Fn,Ba=E(()=>{"use strict";Fn=class{name="OpenAI";endPoint="/v1/chat/completions"}});var jn,Ja=E(()=>{"use strict";jn=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 sp}from"uuid";var Hn,Wa=E(()=>{"use strict";V();Hn=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,c="",l=new ReadableStream({async start(u){let d=e.body.getReader(),p=(h,g,y)=>{let m=h.split(`
232
+ `);for(let b of m)b.trim()&&g.enqueue(y.encode(b+`
233
+ `))},f=(h,g)=>{let{controller:y,encoder:m}=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"&&y.enqueue(m.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
234
234
 
235
- `)),b.choices?.[0]?.delta?.content&&!m.hasTextContent()&&m.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){m.appendReasoningContent(b.choices[0].delta.reasoning);let v={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let T=`data: ${JSON.stringify(v)}
235
+ `)),_.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 T=`data: ${JSON.stringify(v)}
236
236
 
237
- `;y.enqueue(g.encode(T));return}if(b.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let T={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:"ccr_think_signature"}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(T)}
237
+ `;y.enqueue(m.encode(T));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let T={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:"ccr_think_signature"}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let S=`data: ${JSON.stringify(T)}
238
238
 
239
- `;y.enqueue(g.encode(x))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,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(v=>{v.id=`call_${op()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),b.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let k=`data: ${JSON.stringify(b)}
239
+ `;y.enqueue(m.encode(S))}_.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_${sp()}`}),_.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(_)}
240
240
 
241
- `;y.enqueue(g.encode(k))}catch{y.enqueue(g.encode(h+`
242
- `))}}else y.enqueue(g.encode(h+`
243
- `))};try{for(;;){let{done:h,value:m}=await d.read();if(h){c.trim()&&p(c,u,o);break}if(!m||m.length===0)continue;let y;try{y=t.decode(m,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=c.split(`
244
- `);c=_.pop()||"";for(let b of _)if(b.trim())try{f(b,{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:",b,k),u.enqueue(o.encode(b+`
245
- `))}continue}let g=c.split(`
246
- `);c=g.pop()||"";for(let _ of g)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),u.enqueue(o.encode(_+`
247
- `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var vr,rp,Hn,Ja=P(()=>{"use strict";V();vr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
241
+ `;y.enqueue(m.encode(k))}catch{y.enqueue(m.encode(h+`
242
+ `))}}else y.enqueue(m.encode(h+`
243
+ `))};try{for(;;){let{done:h,value:g}=await d.read();if(h){c.trim()&&p(c,u,o);break}if(!g||g.length===0)continue;let y;try{y=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
244
+ `);c=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(_+`
245
+ `))}continue}let m=c.split(`
246
+ `);c=m.pop()||"";for(let b of m)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+`
247
+ `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Tr,ip,zn,Ka=E(()=>{"use strict";V();Tr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
248
248
 
249
249
  Output format:
250
250
  <reasoning_content>
251
251
  Your detailed thinking process goes here
252
252
  </reasoning_content>
253
- Your final answer must follow after the closing tag above.`,rp=10,Hn=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<rp)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
254
- ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:vr}):o.content=[{type:"text",text:vr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:vr}]}),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(c){let l=e.body.getReader(),u="",d="SEARCHING",p="",f="",h=(m,y)=>{if(typeof y!="string"){m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0&&!m.choices[0].delta.content&&(m.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(m)}
253
+ Your final answer must follow after the closing tag above.`,ip=10,zn=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<ip)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
254
+ ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:Tr}):o.content=[{type:"text",text:Tr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Tr}]}),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(c){let l=e.body.getReader(),u="",d="SEARCHING",p="",f="",h=(g,y)=>{if(typeof y!="string"){g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0&&!g.choices[0].delta.content&&(g.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(g)}
255
255
 
256
- `)));return}let g=p+y;for(p="";g.length>0;)if(d==="SEARCHING"){let _=g.indexOf(t);if(_!==-1)g=g.substring(_+t.length),d="REASONING";else{for(let b=t.length-1;b>0;b--)if(g.endsWith(t.substring(0,b))){p=g.substring(g.length-b);break}g=""}}else if(d==="REASONING"){let _=g.indexOf(o);if(_!==-1){let b=g.substring(0,_);if(b.length>0){let T={...m.choices[0].delta,thinking:{content:b}};delete T.content;let x={...m,choices:[{...m.choices[0],delta:T,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(x)}
256
+ `)));return}let m=p+y;for(p="";m.length>0;)if(d==="SEARCHING"){let b=m.indexOf(t);if(b!==-1)m=m.substring(b+t.length),d="REASONING";else{for(let _=t.length-1;_>0;_--)if(m.endsWith(t.substring(0,_))){p=m.substring(m.length-_);break}m=""}}else if(d==="REASONING"){let b=m.indexOf(o);if(b!==-1){let _=m.substring(0,b);if(_.length>0){let T={...g.choices[0].delta,thinking:{content:_}};delete T.content;let S={...g,choices:[{...g.choices[0],delta:T,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(S)}
257
257
 
258
- `))}let k={...m.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let v={...m,choices:[{...m.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
258
+ `))}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}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
259
259
 
260
- `)),r++,g=g.substring(_+o.length),d="FINAL"}else{let b=g;for(let k=o.length-1;k>0;k--)if(g.endsWith(o.substring(0,k))){p=g.substring(g.length-k),b=g.substring(0,g.length-k);break}if(b.length>0){let k={...m.choices[0].delta,thinking:{content:b}};delete k.content;let v={...m,choices:[{...m.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
260
+ `)),r++,m=m.substring(b+o.length),d="FINAL"}else{let _=m;for(let k=o.length-1;k>0;k--)if(m.endsWith(o.substring(0,k))){p=m.substring(m.length-k),_=m.substring(0,m.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}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
261
261
 
262
- `))}g=""}}else if(d==="FINAL"){if(g.length>0)if(/^\s*$/.test(g))f+=g;else{let b=f+g,k={...m.choices[0].delta,content:b};k.thinking&&delete k.thinking;let v={...m,choices:[{...m.choices[0],delta:k}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
262
+ `))}m=""}}else if(d==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))f+=m;else{let _=f+m,k={...g.choices[0].delta,content:_};k.thinking&&delete k.thinking;let v={...g,choices:[{...g.choices[0],delta:k}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
263
263
 
264
- `)),f=""}r++,g=""}};try{for(;;){let{done:m,value:y}=await l.read();if(m)break;let g=s.decode(y,{stream:!0});u+=g;let _=u.split(`
265
- `);u=_.pop()||"";for(let b of _)if(b.trim()){if(b.trim()==="data: [DONE]"){c.enqueue(a.encode(b+`
264
+ `)),f=""}r++,m=""}};try{for(;;){let{done:g,value:y}=await l.read();if(g)break;let m=s.decode(y,{stream:!0});u+=m;let b=u.split(`
265
+ `);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){c.enqueue(a.encode(_+`
266
266
 
267
- `));break}if(b.startsWith("data:"))try{let k=JSON.parse(b.slice(5));h(k,k.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(b+`
268
- `))}else c.enqueue(a.encode(b+`
269
- `))}}}catch(m){console.error("Stream error:",m),c.error(m)}finally{try{l.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}if(d==="REASONING"){let y={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};c.enqueue(a.encode(`data: ${JSON.stringify(y)}
267
+ `));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));h(k,k.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(_+`
268
+ `))}else c.enqueue(a.encode(_+`
269
+ `))}}}catch(g){console.error("Stream error:",g),c.error(g)}finally{try{l.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}if(d==="REASONING"){let y={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};c.enqueue(a.encode(`data: ${JSON.stringify(y)}
270
270
 
271
- `))}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var zn,Wa=P(()=>{"use strict";V();zn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(c){let l=e.body.getReader();try{for(;;){let{done:u,value:d}=await l.read();if(u){a.trim()&&c.enqueue(r.encode(a+`
271
+ `))}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Bn,Ga=E(()=>{"use strict";V();Bn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(c){let l=e.body.getReader();try{for(;;){let{done:u,value:d}=await l.read();if(u){a.trim()&&c.enqueue(r.encode(a+`
272
272
  `));break}let p=o.decode(d,{stream:!0});a+=p;let f=a.split(`
273
- `);a=f.pop()||"";for(let h of f)if(h.trim())if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let m=JSON.parse(h.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){s+=m.choices[0].delta.reasoning_content;let y={...m,choices:[{...m.choices[0],delta:{thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content,c.enqueue(r.encode(`data: ${JSON.stringify(y)}
273
+ `);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 y={...g,choices:[{...g.choices[0],delta:{thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content,c.enqueue(r.encode(`data: ${JSON.stringify(y)}
274
274
 
275
- `));continue}if(m.choices?.[0]?.delta?.content&&s&&!m.choices[0]?.delta?.reasoning_content){let y=Date.now().toString(),g={...m,choices:[{...m.choices[0],delta:{content:null,thinking:{content:s,signature:y}}}]};c.enqueue(r.encode(`data: ${JSON.stringify(g)}
275
+ `));continue}if(g.choices?.[0]?.delta?.content&&s&&!g.choices[0]?.delta?.reasoning_content){let y=Date.now().toString(),m={...g,choices:[{...g.choices[0],delta:{content:null,thinking:{content:s,signature:y}}}]};c.enqueue(r.encode(`data: ${JSON.stringify(m)}
276
276
 
277
- `)),s=""}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&&c.enqueue(r.encode(`data: ${JSON.stringify(m)}
277
+ `)),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&&c.enqueue(r.encode(`data: ${JSON.stringify(g)}
278
278
 
279
279
  `))}catch{c.enqueue(r.encode(h+`
280
280
  `))}else c.enqueue(r.encode(h+`
281
- `))}}catch(u){c.error(u)}finally{try{l.releaseLock()}catch{}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await 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 Ka}from"uuid";var Bn,Ga=P(()=>{"use strict";V();je();Bn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(l=>l.toLowerCase()===a),c=i?r[i]:void 0;return typeof c=="string"&&c.trim()?c.trim():void 0};return s("x-opencode-session")||o?.clientContext?.stableSessionId||o?.sessionId||be(e.metadata?.user_id)||s("session_id")||Ka()}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,c="",l=new ReadableStream({async start(u){let d=e.body.getReader(),p=(h,m,y)=>{let g=h.split(`
282
- `);for(let _ of g)_.trim()&&m.enqueue(y.encode(_+`
283
- `))},f=(h,m)=>{let{controller:y,encoder:g}=m;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let _=JSON.parse(h.slice(6));if(_.usage&&(_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){y.enqueue(g.encode(`data: ${JSON.stringify({error:_.choices?.[0]?.error})}
281
+ `))}}catch(u){c.error(u)}finally{try{l.releaseLock()}catch{}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await 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 Qa}from"uuid";var Jn,Va=E(()=>{"use strict";V();je();Jn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(l=>l.toLowerCase()===a),c=i?r[i]:void 0;return typeof c=="string"&&c.trim()?c.trim():void 0};return s("x-opencode-session")||o?.clientContext?.stableSessionId||o?.sessionId||be(e.metadata?.user_id)||s("session_id")||Qa()}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,c="",l=new ReadableStream({async start(u){let d=e.body.getReader(),p=(h,g,y)=>{let m=h.split(`
282
+ `);for(let b of m)b.trim()&&g.enqueue(y.encode(b+`
283
+ `))},f=(h,g)=>{let{controller:y,encoder:m}=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"){y.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
284
284
 
285
- `));return}_.choices?.[0]?.delta?.content&&!m.hasTextContent()&&m.setHasTextContent(!0);let b=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(b){m.appendReasoningContent(b);let w={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:b}}}]};w.choices?.[0]?.delta&&(delete w.choices[0].delta.reasoning,delete w.choices[0].delta.reasoning_content),y.enqueue(g.encode(`data: ${JSON.stringify(w)}
285
+ `));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),y.enqueue(m.encode(`data: ${JSON.stringify(w)}
286
286
 
287
- `));return}if(_.choices?.[0]?.delta?.content&&m.reasoningContent()&&!m.isReasoningComplete()){m.setReasoningComplete(!0);let w="ccr_think_signature",E=_.choices[0].delta.content,C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:m.reasoningContent(),signature:w}}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content),y.enqueue(g.encode(`data: ${JSON.stringify(C)}
287
+ `));return}if(b.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let w="ccr_think_signature",P=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),y.enqueue(m.encode(`data: ${JSON.stringify(R)}
288
288
 
289
- `));let A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:E}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content),y.enqueue(g.encode(`data: ${JSON.stringify(A)}
289
+ `));let A={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:P}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content),y.enqueue(m.encode(`data: ${JSON.stringify(A)}
290
290
 
291
- `));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(w=>{w.id=`call_${Ka()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=_.choices?.[0]?.delta,v=k&&Object.keys(k).length>0,T=_.choices?.[0]?.finish_reason,x=_.usage;(v||T||x)&&y.enqueue(g.encode(`data: ${JSON.stringify(_)}
291
+ `));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_${Qa()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,v=k&&Object.keys(k).length>0,T=b.choices?.[0]?.finish_reason,S=b.usage;(v||T||S)&&y.enqueue(m.encode(`data: ${JSON.stringify(b)}
292
292
 
293
- `))}catch{y.enqueue(g.encode(h+`
294
- `))}else y.enqueue(g.encode(h+`
295
- `))};try{for(;;){let{done:h,value:m}=await d.read();if(h){c.trim()&&p(c,u,o);break}if(!m||m.length===0)continue;let y;try{y=t.decode(m,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=c.split(`
296
- `);c=_.pop()||"";for(let b of _)if(b.trim())try{f(b,{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:",b,k),u.enqueue(o.encode(b+`
297
- `))}continue}let g=c.split(`
298
- `);c=g.pop()||"";for(let _ of g)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),u.enqueue(o.encode(_+`
299
- `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function ip(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 ap(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 sp,Jn,Qa=P(()=>{"use strict";Qe();sp={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Jn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=ip(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=ap(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=ke(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=sp[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 Va(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 Wn,Ya=P(()=>{"use strict";Qe();V();Wn=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=ke(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 ce(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 ye(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)Va(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=l=>{if(!l.startsWith("data:"))return l;let u=l.slice(5).trim();if(u==="[DONE]")return l;let d;try{d=JSON.parse(u)}catch{return l}let p=!1,f=Array.isArray(d?.choices)?d.choices:[];for(let h of f)Va(h?.delta,!0)&&(p=!0);return p?`data: ${JSON.stringify(d)}`:l},a=(l,u=!1)=>{let d=/\r\n|\r|\n/g,p=0,f,h="";for(;(f=d.exec(r))!==null&&!(!u&&f[0]==="\r"&&d.lastIndex===r.length);)h+=s(r.slice(p,f.index))+f[0],p=d.lastIndex;r=r.slice(p),u&&(h+=s(r),r=""),h&&l.enqueue(o.encode(h))},i=e.body.pipeThrough(new TransformStream({transform(l,u){r+=t.decode(l,{stream:!0}),a(u)},flush(l){r+=t.decode(),a(l,!0)}})),c=new Headers(e.headers);return c.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:c})}}});var Xa,Za=P(()=>{ka();va();Ta();Ca();Sa();xa();Ra();wa();Pa();Aa();Oa();Ia();Ma();Da();Fa();ja();Ha();za();Ba();nr();Ja();Wa();Ga();Qa();Ya();Xa={AnthropicTransformer:_n,GeminiTransformer:Cn,VertexGeminiTransformer:Sn,VertexClaudeTransformer:$n,DeepseekTransformer:xn,TooluseTransformer:Rn,OpenrouterTransformer:wn,OpenAITransformer:Dn,MaxTokenTransformer:Pn,GroqTransformer:En,CleancacheTransformer:An,EnhanceToolTransformer:On,ReasoningTransformer:In,SamplingTransformer:Mn,MaxCompletionTokens:Ln,CerebrasTransformer:Nn,StreamOptionsTransformer:Un,CustomParamsTransformer:Fn,VercelTransformer:jn,OpenAIResponsesTransformer:De,ForceReasoningTransformer:Hn,KimiTransformer:zn,OpenCodeTransformer:Bn,DefaultThinkingTransformer:Jn,AmdTransformer:Wn}});var Xe,Tr=P(()=>{"use strict";Za();Xe=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=xo(xo.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{y.enqueue(m.encode(h+`
294
+ `))}else y.enqueue(m.encode(h+`
295
+ `))};try{for(;;){let{done:h,value:g}=await d.read();if(h){c.trim()&&p(c,u,o);break}if(!g||g.length===0)continue;let y;try{y=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
296
+ `);c=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(_+`
297
+ `))}continue}let m=c.split(`
298
+ `);c=m.pop()||"";for(let b of m)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+`
299
+ `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{d.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function cp(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 lp(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 ap,Wn,Ya=E(()=>{"use strict";Qe();ap={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Wn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=cp(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=lp(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=ke(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=ap[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 Xa(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 Kn,Za=E(()=>{"use strict";Qe();V();Kn=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=ke(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 le(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 ye(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)Xa(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=l=>{if(!l.startsWith("data:"))return l;let u=l.slice(5).trim();if(u==="[DONE]")return l;let d;try{d=JSON.parse(u)}catch{return l}let p=!1,f=Array.isArray(d?.choices)?d.choices:[];for(let h of f)Xa(h?.delta,!0)&&(p=!0);return p?`data: ${JSON.stringify(d)}`:l},a=(l,u=!1)=>{let d=/\r\n|\r|\n/g,p=0,f,h="";for(;(f=d.exec(r))!==null&&!(!u&&f[0]==="\r"&&d.lastIndex===r.length);)h+=s(r.slice(p,f.index))+f[0],p=d.lastIndex;r=r.slice(p),u&&(h+=s(r),r=""),h&&l.enqueue(o.encode(h))},i=e.body.pipeThrough(new TransformStream({transform(l,u){r+=t.decode(l,{stream:!0}),a(u)},flush(l){r+=t.decode(),a(l,!0)}})),c=new Headers(e.headers);return c.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:c})}}});var qa,ec=E(()=>{Ta();Ca();Sa();xa();Ra();wa();Pa();Ea();Aa();Ia();Ma();La();$a();ja();Ha();za();Ba();Ja();Wa();or();Ka();Ga();Va();Ya();Za();qa={AnthropicTransformer:bn,GeminiTransformer:Sn,VertexGeminiTransformer:xn,VertexClaudeTransformer:Nn,DeepseekTransformer:Rn,TooluseTransformer:wn,OpenrouterTransformer:Pn,OpenAITransformer:Fn,MaxTokenTransformer:En,GroqTransformer:An,CleancacheTransformer:On,EnhanceToolTransformer:In,ReasoningTransformer:Mn,SamplingTransformer:Ln,MaxCompletionTokens:$n,CerebrasTransformer:Un,StreamOptionsTransformer:Dn,CustomParamsTransformer:jn,VercelTransformer:Hn,OpenAIResponsesTransformer:De,ForceReasoningTransformer:zn,KimiTransformer:Bn,OpenCodeTransformer:Jn,DefaultThinkingTransformer:Wn,AmdTransformer:Kn}});var Xe,Cr=E(()=>{"use strict";ec();Xe=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=Ro(Ro.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
300
300
  error: ${t.message}
301
301
  stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
302
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Xa).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 cp}from"tiktoken";var Ct,qa=P(()=>{"use strict";Ct=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=cp(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(c=>{if(c.type==="text")o+=t.encode(c.text).length;else if(c.type==="tool_use")o+=t.encode(JSON.stringify(c.input)).length;else if(c.type==="tool_result"){let l=c.content;if(Array.isArray(l))for(let u of l)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof l=="string"?l:JSON.stringify(l);o+=t.encode(u).length}}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(c=>{o+=t.encode(c||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Kn}from"path";import{homedir as lp}from"os";import{existsSync as Cr,mkdirSync as up}from"fs";import{promises as Gn}from"fs";import{Tokenizer as dp}from"@huggingface/tokenizers";var Qn,ec=P(()=>{"use strict";Qn=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||Kn(lp(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Kn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Kn(e,"tokenizer.json"),tokenizerConfig:Kn(e,"tokenizer_config.json")}}ensureDir(e){Cr(e)||up(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Cr(e.tokenizerJson)||!Cr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Gn.readFile(e.tokenizerJson,"utf-8"),Gn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,c]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Gn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Gn.writeFile(e.tokenizerConfig,JSON.stringify(c,null,2))]),{tokenizerJson:i,tokenizerConfig:c}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new dp(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let c of i.content)c?.type!=="image"&&t.push(c?.type==="text"?String(c.text??""):JSON.stringify(c));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Vn,tc=P(()=>{"use strict";te();Vn=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 c=await fetch(this.config.url,a);if(clearTimeout(s),!c.ok)throw new Error(`API tokenizer request failed: ${c.status} ${c.statusText}`);let l=await c.json();return this.extractTokenCount(l)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
303
- `):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ze,Sr=P(()=>{"use strict";qa();ec();tc();te();Ze=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new Ct("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 Ct(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Qn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Vn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return me(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});import{createHash as pp,createHmac as fp}from"node:crypto";function nc(n){if(!n||typeof n!="object"||kp(n))return null;for(let t of bp(n)){let o=_p(t);if(o)return o}return null}function _p(n){if(!n||typeof n!="object")return null;let e={},t=Yn(n,mp);if(t!==void 0){let a=oc(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Yn(n,gp);if(o!==void 0){let a=oc(o);e.usedBalance=a,e.totalBalance=100}let r=Yn(n,hp);if(r!==void 0){let a=rc(r);a&&(e.resetTime=a)}let s=Yn(n,yp);if(s!==void 0){let a=rc(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 oc(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Yn(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function bp(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 kp(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 rc(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 vp(n){let{accessKey:e,secretKey:t,method:o,url:r,body:s,region:a,service:i,xDate:c}=n,l=c.slice(0,8),u="application/json",d=sc(s),p="host;x-date;x-content-sha256;content-type",f=`host:${r.host}
302
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(qa).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 up}from"tiktoken";var xt,tc=E(()=>{"use strict";xt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=up(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(c=>{if(c.type==="text")o+=t.encode(c.text).length;else if(c.type==="tool_use")o+=t.encode(JSON.stringify(c.input)).length;else if(c.type==="tool_result"){let l=c.content;if(Array.isArray(l))for(let u of l)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof l=="string"?l:JSON.stringify(l);o+=t.encode(u).length}}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(c=>{o+=t.encode(c||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Gn}from"path";import{homedir as dp}from"os";import{existsSync as Sr,mkdirSync as pp}from"fs";import{promises as Qn}from"fs";import{Tokenizer as fp}from"@huggingface/tokenizers";var Vn,nc=E(()=>{"use strict";Vn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||Gn(dp(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Gn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Gn(e,"tokenizer.json"),tokenizerConfig:Gn(e,"tokenizer_config.json")}}ensureDir(e){Sr(e)||pp(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Sr(e.tokenizerJson)||!Sr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Qn.readFile(e.tokenizerJson,"utf-8"),Qn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,c]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Qn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Qn.writeFile(e.tokenizerConfig,JSON.stringify(c,null,2))]),{tokenizerJson:i,tokenizerConfig:c}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new fp(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let c of i.content)c?.type!=="image"&&t.push(c?.type==="text"?String(c.text??""):JSON.stringify(c));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Yn,oc=E(()=>{"use strict";te();Yn=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 c=await fetch(this.config.url,a);if(clearTimeout(s),!c.ok)throw new Error(`API tokenizer request failed: ${c.status} ${c.statusText}`);let l=await c.json();return this.extractTokenCount(l)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
303
+ `):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ze,xr=E(()=>{"use strict";tc();nc();oc();te();Ze=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new xt("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 xt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Vn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Yn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return me(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});import{createHash as mp,createHmac as gp}from"node:crypto";function rc(n){if(!n||typeof n!="object"||Tp(n))return null;for(let t of vp(n)){let o=kp(t);if(o)return o}return null}function kp(n){if(!n||typeof n!="object")return null;let e={},t=Xn(n,hp);if(t!==void 0){let a=sc(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Xn(n,yp);if(o!==void 0){let a=sc(o);e.usedBalance=a,e.totalBalance=100}let r=Xn(n,_p);if(r!==void 0){let a=ic(r);a&&(e.resetTime=a)}let s=Xn(n,bp);if(s!==void 0){let a=ic(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 sc(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Xn(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function vp(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 ic(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 Cp(n){let{accessKey:e,secretKey:t,method:o,url:r,body:s,region:a,service:i,xDate:c}=n,l=c.slice(0,8),u="application/json",d=ac(s),p="host;x-date;x-content-sha256;content-type",f=`host:${r.host}
304
304
  x-date:${c}
305
305
  x-content-sha256:${d}
306
306
  content-type:${u}
307
- `,h=[...r.searchParams.entries()].sort(([x,w],[E,C])=>x<E?-1:x>E?1:w<C?-1:w>C?1:0).map(([x,w])=>`${ic(x)}=${ic(w)}`).join("&"),m=[o.toUpperCase(),r.pathname,h,f,p,d].join(`
308
- `),y=`${l}/${a}/${i}/request`,g=["HMAC-SHA256",c,y,sc(m)].join(`
309
- `),_=St(t,l),b=St(_,a),k=St(b,i),v=St(k,"request"),T=St(v,g).toString("hex");return{"Content-Type":u,"X-Date":c,"X-Content-Sha256":d,Authorization:`HMAC-SHA256 Credential=${e}/${y}, SignedHeaders=${p}, Signature=${T}`}}function sc(n){return pp("sha256").update(n,"utf8").digest("hex")}function St(n,e){return fp("sha256",n).update(e,"utf8").digest()}function ic(n){return encodeURIComponent(n).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Tp(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 c=new Date(a*1e3);i=isNaN(c.getTime())?void 0:c.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 Ur(n){let e=Dr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Ap:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Op:e==="deepseek.com"||e.endsWith(".deepseek.com")?Cp:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Sp:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?xp:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Rp:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?wp:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Pp:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Ep:e==="ark.cn-beijing.volces.com"&&$p(n)?.includes("/api/coding/")?Ip:null:null}function Mp(n){let e=Dr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Lp(n,e){let t=$r(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function $r(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>$r(e)):Object.values(n).flatMap(e=>$r(e))}function Nr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Dr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function $p(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 se,xr,Rr,wr,Pr,Er,mp,gp,hp,yp,Ar,Or,Ir,Mr,Lr,Cp,Sp,xp,Rp,wp,Pp,Ep,Ap,Op,Ip,Fr=P(()=>{"use strict";te();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 c=await fetch(e,i);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},xr=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(c=>U(c?.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}}},Rr=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),c=U(s.limit_remaining),l=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},wr=class extends se{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={},c=U(a.totalBalance),l=U(a.balance);return c!==void 0&&(i.totalBalance=c),l!==void 0&&(i.remainingBalance=l),c!==void 0&&l!==void 0&&(i.usedBalance=Math.max(0,c-l)),this.hasQuotaData(i)?i:null}},Pr=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(),c=Array.isArray(i?.data?.limits)?i.data.limits:[],l=null,u=null,d=null;for(let f of c)f.type==="TOKENS_LIMIT"?f.unit===3?l=f:f.unit===6?u=f:l||(l=f):f.type==="TIME_LIMIT"&&(d=f);let p={};if(l){let f=U(l.currentValue),h=U(l.usage),m=U(l.remaining),y=U(l.percentage);f!==void 0?p.usedDailyBalance=f:y!==void 0&&(p.usedDailyBalance=y,p.limitDaily=100),h!==void 0?p.limitDaily=h:f!==void 0&&m!==void 0&&(p.limitDaily=f+m),l.nextResetTime&&(p.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),h=U(u.usage),m=U(u.remaining),y=U(u.percentage);f!==void 0?p.usedBalance=f:y!==void 0&&(p.usedBalance=y,p.totalBalance=100),h!==void 0?p.totalBalance=h:f!==void 0&&m!==void 0&&(p.totalBalance=f+m),u.nextResetTime&&!p.resetTime&&(p.resetTime=new Date(u.nextResetTime).toISOString())}if(d){if(p.usedDailyBalance===void 0){let f=U(d.currentValue);f!==void 0&&(p.usedDailyBalance=f)}if(p.limitDaily===void 0){let f=U(d.usage),h=U(d.currentValue),m=U(d.remaining);f!==void 0?p.limitDaily=f:h!==void 0&&m!==void 0&&(p.limitDaily=h+m)}d.nextResetTime&&!p.resetTime&&(p.resetTime=new Date(d.nextResetTime).toISOString())}return this.hasQuotaData(p)?p:null}catch{return null}}},Er=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 l=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(l)||l.length===0)return null;let u=l[0]?.codingPlanQuotaInfo;if(!u)return null;let d={},p=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);p!==void 0&&(d.usedDailyBalance=p),f!==void 0&&(d.limitDaily=f);let h=U(u.perWeekUsedQuota),m=U(u.perWeekTotalQuota);return h!==void 0&&(d.usedBalance=h),m!==void 0&&(d.totalBalance=m),this.hasQuotaData(d)?d:null}catch{return null}}};mp=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],gp=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],hp=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],yp=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Ar=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=Nr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","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:c,signal:AbortSignal.timeout(o)};try{r&&(l.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`,l);if(!u.ok)return null;let d=await u.json();return nc(d)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),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 c=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!c.ok)return null;let l=await c.json();return nc(l)}catch{return null}}},Or=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:(Nr(e.quotaToken,"atp-auth-token")||Nr(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 c=Lp(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},d=U(l.rp5hUsage),p=U(l.rp5hLimit);d!==void 0&&(u.usedDailyBalance=d),p!==void 0&&(u.limitDaily=p);let f=U(l.rpwUsage),h=U(l.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}}},Ir=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(),c={},l=Array.isArray(i?.limits)?i.limits:[];if(l.length>0&&l[0]?.detail){let d=l[0].detail,p=U(d.limit),f=U(d.remaining),h=U(d.used),m=d.resetTime;p!==void 0&&(c.limitDaily=p,h!==void 0?c.usedDailyBalance=h:f!==void 0&&(c.usedDailyBalance=Math.max(0,p-f))),m&&(c.resetTime=new Date(m).toISOString())}let u=i?.usage;if(u){let d=U(u.limit),p=U(u.remaining),f=U(u.used),h=u.resetTime;d!==void 0&&(c.totalBalance=d,f!==void 0?c.usedBalance=f:p!==void 0&&(c.usedBalance=Math.max(0,d-p),c.remainingBalance=p)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},Mr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Dr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let k of i)if(c=await this.fetchJson(k,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let k=c.base_resp.status_code;if(k!==void 0&&k!==0)return null}let l=Array.isArray(c?.model_remains)?c.model_remains:[];if(l.length===0)return null;let u=l[0],d={},p=U(u.current_interval_total_count),f=U(u.current_interval_usage_count),h=U(u.current_interval_remaining_percent),m=U(u.end_time);p!==void 0&&f!==void 0&&p>0?(d.usedDailyBalance=Math.max(0,p-f),d.limitDaily=p):h!==void 0&&(d.limitDaily=100,d.usedDailyBalance=Math.max(0,100-h)),m&&(d.resetTime=new Date(m).toISOString());let y=U(u.current_weekly_total_count),g=U(u.current_weekly_usage_count),_=U(u.current_weekly_remaining_percent),b=U(u.weekly_end_time);return y!==void 0&&g!==void 0&&y>0?(d.usedBalance=Math.max(0,y-g),d.remainingBalance=g,d.totalBalance=y):_!==void 0&&(d.totalBalance=100,d.usedBalance=Math.max(0,100-_),d.remainingBalance=_),b&&!d.resetTime&&(d.resetTime=new Date(b).toISOString()),this.hasQuotaData(d)?d:null}catch{return null}}};Lr=class extends se{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"),c=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),u={method:"POST",headers:{Accept:"application/json","Accept-Encoding":"identity",...vp({accessKey:r,secretKey:s,method:"POST",url:i,body:a,region:"cn-beijing",service:"ark",xDate:c})},body:a,signal:AbortSignal.timeout(t)};try{o&&(u.dispatcher=G(o));let d=await fetch(i.toString(),u);if(!d.ok)return null;let p=await d.json();return Tp(p)}catch{return null}}},Cp=new xr,Sp=new Rr,xp=new wr,Rp=new Pr,wp=new Er,Pp=new Ar,Ep=new Or,Ap=new Ir,Op=new Mr,Ip=new Lr});async function Xn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=ac.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<Np)return;let r=o??{fetchedAt:0};return r.pending=(async()=>{try{let s=await t.fetchQuota(e);s&&ft(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),ac.set(n,r),r.pending}var Np,cc,ac,jr=P(()=>{"use strict";Pe();Np=6e4,cc=2500,ac=new Map});function lc(n){return{[Up]:n,[Dp]:qt}}function ve(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function jp(n){return n===!0||n==="true"||n===1||n==="1"}function Hp(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 zp(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 Bp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Hr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(ve(n))return{success:!1,skipped:!0,error:zr,latencyMs:r()};let s=zp(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&&ut(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let c=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${c.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",c=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:c?"timeout":"network"}}}async function Jp(n,e,t,o){if(ve(n))return{success:!1,skipped:!0,error:zr};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",...lc("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=G(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function Wp(n,e,t,o,r){if(ve(n))return{success:!1,skipped:!0,error:zr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...lc("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=G(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function uc(n,e,t,o,r,s){return Te||(Te=new Zn(n,e,t,o,r,s)),Te}function xt(n,e,t,o,r,s){let a=uc(n,e,t,o,r,s);return a.start(),a}function Br(){Te&&Te.stop()}function Jr(){Te&&(Te.stop(),Te=null)}var Up,Dp,Fp,zr,Zn,Te,qn=P(()=>{"use strict";ae();ge();Fr();Pe();jr();jo();te();Up="x-claude-code-router-source",Dp="x-claude-code-router-version";Fp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};zr="Managed provider requires its plugin's authenticated model sync";Zn=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={...Fp,...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),c={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,c),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),c}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.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&&!ve(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Ur(s.baseUrl),i=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let l;try{l=new URL(s.baseUrl).hostname}catch{l=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(l?` (host: ${l})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(l=>{if(l){ft(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,d=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||d){let p=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.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,p)}this.logger?.warn?.(`${p} for ${s.name}, marked as unhealthy`)}else for(let p of i){let f=t.getState(s.name,p);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,p),this.logger?.info?.(`Quota recovered for ${s.name} (${p}), marked as healthy`))}}})}),Bp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Hr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&ve(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:Xn(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&&!ve(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Hr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let d=e.getState(s.name,u);if(d&&d.status==="open"){let p=d.lastError?.includes("Quota exhausted"),f=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(p){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let l of i)e.recordFailure(s.name,l,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let c of i)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async 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 c=o.get(s)??[];c.push(i),o.set(s,c)}for(let[r,s]of o){let a=this.getProviders().find(l=>l?.name===r&&l.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let c=i.modelScopedRecovery?s.map(l=>[l]):[s];for(let l of c){let u=l[0],d=e.getState(r,u);!d||d.status!=="open"||d.rateLimitUntil&&Date.now()<d.rateLimitUntil||Date.now()-(d.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,u,l,e)||await this.probeManagedLiveness(r,i,a,u,l,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,c={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},l=async()=>{let d=o.baseUrl||o.api_base_url;return await fetch(d,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(c),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let d=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:l,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:l,requestBody:c,config:u,provider:o}):await l();if(d?.ok){for(let p of s)a.recover(e,p);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 ${d?.status}`)}catch(d){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${d?.message||d}`)}}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(","),c=i.join(",");if(!a||!c)continue;let l=o.find(p=>p?.name===a);if(l&&ve(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let d=o.find(p=>p?.name===a&&p.enabled!==!1);if(!d){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let p=await Wp(d,c,r,this.resolveProxyUrl?.(d),this.logger);if(p.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(p.error&&(p.error.includes("429")||p.error.toLowerCase().includes("rate limit")||p.error.toLowerCase().includes("rate_limit")||p.error.toLowerCase().includes("too many requests")||p.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: ${p.error?.slice(0,100)}`)}catch(p){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${p?.message||p}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!ve(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=Hp(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),d=parseInt(l,10),p=parseInt(u,10);if(isNaN(d)||isNaN(p))continue;let f=o>d||o===d&&r>=p,h=(d*60+p)*6e4-(o*60+r)*6e4,m=h>0&&h<=300*1e3;(f||m)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),Jp(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(y=>{y.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${y.error}`)}).catch(y=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${y}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?jp(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 Hr(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}}},Te=null});var dc=P(()=>{"use strict"});var Wr,Rt,pc=P(()=>{"use strict";Wr=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()}},Rt=new Wr});var ue,Kr=P(()=>{"use strict";ue=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
310
- `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var qe,Gr=P(()=>{"use strict";qe=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
307
+ `,h=[...r.searchParams.entries()].sort(([S,w],[P,R])=>S<P?-1:S>P?1:w<R?-1:w>R?1:0).map(([S,w])=>`${cc(S)}=${cc(w)}`).join("&"),g=[o.toUpperCase(),r.pathname,h,f,p,d].join(`
308
+ `),y=`${l}/${a}/${i}/request`,m=["HMAC-SHA256",c,y,ac(g)].join(`
309
+ `),b=Rt(t,l),_=Rt(b,a),k=Rt(_,i),v=Rt(k,"request"),T=Rt(v,m).toString("hex");return{"Content-Type":u,"X-Date":c,"X-Content-Sha256":d,Authorization:`HMAC-SHA256 Credential=${e}/${y}, SignedHeaders=${p}, Signature=${T}`}}function ac(n){return mp("sha256").update(n,"utf8").digest("hex")}function Rt(n,e){return gp("sha256",n).update(e,"utf8").digest()}function cc(n){return encodeURIComponent(n).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Sp(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 c=new Date(a*1e3);i=isNaN(c.getTime())?void 0:c.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 Dr(n){let e=Fr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Ip:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Mp:e==="deepseek.com"||e.endsWith(".deepseek.com")?xp:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Rp:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?wp:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Pp:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Ep:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Ap:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Op:e==="ark.cn-beijing.volces.com"&&Up(n)?.includes("/api/coding/")?Lp:null:null}function $p(n){let e=Fr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Np(n,e){let t=Nr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function Nr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Nr(e)):Object.values(n).flatMap(e=>Nr(e))}function Ur(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Fr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function Up(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 ie,Rr,wr,Pr,Er,Ar,hp,yp,_p,bp,Or,Ir,Mr,Lr,$r,xp,Rp,wp,Pp,Ep,Ap,Op,Ip,Mp,Lp,jr=E(()=>{"use strict";te();ie=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 c=await fetch(e,i);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},Rr=class extends ie{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>U(c?.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}}},wr=class extends ie{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),c=U(s.limit_remaining),l=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},Pr=class extends ie{async queryQuota(e,t,o){let r=$p(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=U(a.totalBalance),l=U(a.balance);return c!==void 0&&(i.totalBalance=c),l!==void 0&&(i.remainingBalance=l),c!==void 0&&l!==void 0&&(i.usedBalance=Math.max(0,c-l)),this.hasQuotaData(i)?i:null}},Er=class extends ie{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(),c=Array.isArray(i?.data?.limits)?i.data.limits:[],l=null,u=null,d=null;for(let f of c)f.type==="TOKENS_LIMIT"?f.unit===3?l=f:f.unit===6?u=f:l||(l=f):f.type==="TIME_LIMIT"&&(d=f);let p={};if(l){let f=U(l.currentValue),h=U(l.usage),g=U(l.remaining),y=U(l.percentage);f!==void 0?p.usedDailyBalance=f:y!==void 0&&(p.usedDailyBalance=y,p.limitDaily=100),h!==void 0?p.limitDaily=h:f!==void 0&&g!==void 0&&(p.limitDaily=f+g),l.nextResetTime&&(p.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),h=U(u.usage),g=U(u.remaining),y=U(u.percentage);f!==void 0?p.usedBalance=f:y!==void 0&&(p.usedBalance=y,p.totalBalance=100),h!==void 0?p.totalBalance=h:f!==void 0&&g!==void 0&&(p.totalBalance=f+g),u.nextResetTime&&!p.resetTime&&(p.resetTime=new Date(u.nextResetTime).toISOString())}if(d){if(p.usedDailyBalance===void 0){let f=U(d.currentValue);f!==void 0&&(p.usedDailyBalance=f)}if(p.limitDaily===void 0){let f=U(d.usage),h=U(d.currentValue),g=U(d.remaining);f!==void 0?p.limitDaily=f:h!==void 0&&g!==void 0&&(p.limitDaily=h+g)}d.nextResetTime&&!p.resetTime&&(p.resetTime=new Date(d.nextResetTime).toISOString())}return this.hasQuotaData(p)?p:null}catch{return null}}},Ar=class extends ie{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 l=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(l)||l.length===0)return null;let u=l[0]?.codingPlanQuotaInfo;if(!u)return null;let d={},p=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);p!==void 0&&(d.usedDailyBalance=p),f!==void 0&&(d.limitDaily=f);let h=U(u.perWeekUsedQuota),g=U(u.perWeekTotalQuota);return h!==void 0&&(d.usedBalance=h),g!==void 0&&(d.totalBalance=g),this.hasQuotaData(d)?d:null}catch{return null}}};hp=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],yp=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],_p=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],bp=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];Or=class extends ie{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=Ur(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","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:c,signal:AbortSignal.timeout(o)};try{r&&(l.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`,l);if(!u.ok)return null;let d=await u.json();return rc(d)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),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 c=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!c.ok)return null;let l=await c.json();return rc(l)}catch{return null}}},Ir=class extends ie{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:(Ur(e.quotaToken,"atp-auth-token")||Ur(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 c=Np(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},d=U(l.rp5hUsage),p=U(l.rp5hLimit);d!==void 0&&(u.usedDailyBalance=d),p!==void 0&&(u.limitDaily=p);let f=U(l.rpwUsage),h=U(l.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}}},Mr=class extends ie{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(),c={},l=Array.isArray(i?.limits)?i.limits:[];if(l.length>0&&l[0]?.detail){let d=l[0].detail,p=U(d.limit),f=U(d.remaining),h=U(d.used),g=d.resetTime;p!==void 0&&(c.limitDaily=p,h!==void 0?c.usedDailyBalance=h:f!==void 0&&(c.usedDailyBalance=Math.max(0,p-f))),g&&(c.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let d=U(u.limit),p=U(u.remaining),f=U(u.used),h=u.resetTime;d!==void 0&&(c.totalBalance=d,f!==void 0?c.usedBalance=f:p!==void 0&&(c.usedBalance=Math.max(0,d-p),c.remainingBalance=p)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},Lr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Fr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let k of i)if(c=await this.fetchJson(k,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let k=c.base_resp.status_code;if(k!==void 0&&k!==0)return null}let l=Array.isArray(c?.model_remains)?c.model_remains:[];if(l.length===0)return null;let u=l[0],d={},p=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);p!==void 0&&f!==void 0&&p>0?(d.usedDailyBalance=Math.max(0,p-f),d.limitDaily=p):h!==void 0&&(d.limitDaily=100,d.usedDailyBalance=Math.max(0,100-h)),g&&(d.resetTime=new Date(g).toISOString());let y=U(u.current_weekly_total_count),m=U(u.current_weekly_usage_count),b=U(u.current_weekly_remaining_percent),_=U(u.weekly_end_time);return y!==void 0&&m!==void 0&&y>0?(d.usedBalance=Math.max(0,y-m),d.remainingBalance=m,d.totalBalance=y):b!==void 0&&(d.totalBalance=100,d.usedBalance=Math.max(0,100-b),d.remainingBalance=b),_&&!d.resetTime&&(d.resetTime=new Date(_).toISOString()),this.hasQuotaData(d)?d:null}catch{return null}}};$r=class extends ie{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"),c=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),u={method:"POST",headers:{Accept:"application/json","Accept-Encoding":"identity",...Cp({accessKey:r,secretKey:s,method:"POST",url:i,body:a,region:"cn-beijing",service:"ark",xDate:c})},body:a,signal:AbortSignal.timeout(t)};try{o&&(u.dispatcher=G(o));let d=await fetch(i.toString(),u);if(!d.ok)return null;let p=await d.json();return Sp(p)}catch{return null}}},xp=new Rr,Rp=new wr,wp=new Pr,Pp=new Er,Ep=new Ar,Ap=new Or,Op=new Ir,Ip=new Mr,Mp=new Lr,Lp=new $r});async function Zn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=lc.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<Dp)return;let r=o??{fetchedAt:0};return r.pending=(async()=>{try{let s=await t.fetchQuota(e);s&&ft(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),lc.set(n,r),r.pending}var Dp,uc,lc,Hr=E(()=>{"use strict";Pe();Dp=6e4,uc=2500,lc=new Map});function dc(n){return{[Fp]:n,[jp]:tn}}function ve(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function zp(n){return n===!0||n==="true"||n===1||n==="1"}function Bp(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 Jp(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 Wp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function zr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(ve(n))return{success:!1,skipped:!0,error:Br,latencyMs:r()};let s=Jp(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&&ut(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let c=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${c.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",c=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:c?"timeout":"network"}}}async function Kp(n,e,t,o){if(ve(n))return{success:!1,skipped:!0,error:Br};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",...dc("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=G(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function Gp(n,e,t,o,r){if(ve(n))return{success:!1,skipped:!0,error:Br};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...dc("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=G(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function pc(n,e,t,o,r,s){return Te||(Te=new qn(n,e,t,o,r,s)),Te}function wt(n,e,t,o,r,s){let a=pc(n,e,t,o,r,s);return a.start(),a}function Jr(){Te&&Te.stop()}function Wr(){Te&&(Te.stop(),Te=null)}var Fp,jp,Hp,Br,qn,Te,eo=E(()=>{"use strict";ce();ge();jr();Pe();Hr();Ho();te();Fp="x-claude-code-router-source",jp="x-claude-code-router-version";Hp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Br="Managed provider requires its plugin's authenticated model sync";qn=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={...Hp,...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),c={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,c),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),c}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.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&&!ve(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Dr(s.baseUrl),i=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let l;try{l=new URL(s.baseUrl).hostname}catch{l=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(l?` (host: ${l})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(l=>{if(l){ft(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,d=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||d){let p=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.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,p)}this.logger?.warn?.(`${p} for ${s.name}, marked as unhealthy`)}else for(let p of i){let f=t.getState(s.name,p);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,p),this.logger?.info?.(`Quota recovered for ${s.name} (${p}), marked as healthy`))}}})}),Wp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:zr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&ve(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:Zn(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&&!ve(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>zr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let d=e.getState(s.name,u);if(d&&d.status==="open"){let p=d.lastError?.includes("Quota exhausted"),f=d.rateLimitUntil||d.lastError&&(d.lastError.includes("429")||d.lastError.toLowerCase().includes("rate limit")||d.lastError.toLowerCase().includes("rate_limit")||d.lastError.toLowerCase().includes("too many requests")||d.lastError.toLowerCase().includes("\u9650\u6D41"));if(p){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||d.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let l of i)e.recordFailure(s.name,l,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let c of i)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async 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 c=o.get(s)??[];c.push(i),o.set(s,c)}for(let[r,s]of o){let a=this.getProviders().find(l=>l?.name===r&&l.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let c=i.modelScopedRecovery?s.map(l=>[l]):[s];for(let l of c){let u=l[0],d=e.getState(r,u);!d||d.status!=="open"||d.rateLimitUntil&&Date.now()<d.rateLimitUntil||Date.now()-(d.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,u,l,e)||await this.probeManagedLiveness(r,i,a,u,l,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,c={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},l=async()=>{let d=o.baseUrl||o.api_base_url;return await fetch(d,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(c),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let d=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:l,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:l,requestBody:c,config:u,provider:o}):await l();if(d?.ok){for(let p of s)a.recover(e,p);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 ${d?.status}`)}catch(d){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${d?.message||d}`)}}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(","),c=i.join(",");if(!a||!c)continue;let l=o.find(p=>p?.name===a);if(l&&ve(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let d=o.find(p=>p?.name===a&&p.enabled!==!1);if(!d){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let p=await Gp(d,c,r,this.resolveProxyUrl?.(d),this.logger);if(p.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(p.error&&(p.error.includes("429")||p.error.toLowerCase().includes("rate limit")||p.error.toLowerCase().includes("rate_limit")||p.error.toLowerCase().includes("too many requests")||p.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: ${p.error?.slice(0,100)}`)}catch(p){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${p?.message||p}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!ve(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=Bp(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),d=parseInt(l,10),p=parseInt(u,10);if(isNaN(d)||isNaN(p))continue;let f=o>d||o===d&&r>=p,h=(d*60+p)*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 ${c}`),Kp(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(y=>{y.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${y.error}`)}).catch(y=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${y}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?zp(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await zr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)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}}},Te=null});var fc=E(()=>{"use strict"});var Kr,Pt,mc=E(()=>{"use strict";Kr=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()}},Pt=new Kr});var ue,Gr=E(()=>{"use strict";ue=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
310
+ `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var qe,Qr=E(()=>{"use strict";qe=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
311
311
  `),e.id&&(o+=`id: ${e.id}
312
312
  `),e.retry&&(o+=`retry: ${e.retry}
313
313
  `),e.data&&(e.data.type==="done"?o+=`data: [DONE]
314
314
  `:o+=`data: ${JSON.stringify(e.data)}
315
315
  `),o+=`
316
- `,t.enqueue(o)}})}}});var eo,Qr=P(()=>{"use strict";eo=(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 Vr=P(()=>{"use strict";Kr();Gr();Qr()});var fc=P(()=>{"use strict"});var wt,Yr=P(()=>{"use strict";wt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let c=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${c}]${this.colors.reset} `:`[${c}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
316
+ `,t.enqueue(o)}})}}});var to,Vr=E(()=>{"use strict";to=(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 Yr=E(()=>{"use strict";Gr();Qr();Vr()});var gc=E(()=>{"use strict"});var Et,Xr=E(()=>{"use strict";Et=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let c=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${c}]${this.colors.reset} `:`[${c}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
317
317
  `+(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}-
318
318
  ${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
319
319
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
320
320
  ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
321
- `):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var Pt,Xr=P(()=>{"use strict";Pt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let c=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);return c}catch(c){throw clearTimeout(i),c}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let c=1;c<=a.maxAttempts;c++)try{return await this.sendRequest(e,t,o,r,s)}catch(l){if(i=l,c===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,c-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${c}/${a.maxAttempts}), retrying in ${u}ms...`,l.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as no,opendir as Gp,unlink as Qp}from"node:fs/promises";import{join as gc,resolve as es}from"node:path";import{tmpdir as Vp}from"node:os";async function oo(n,e){let t=es(n),o=to.get(t),r,s=new Promise(a=>{r=a});to.set(t,s);try{return await o,await e()}finally{r(),to.get(t)===s&&to.delete(t)}}function hc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function mc(n,e){try{let t=await no(n);return t.isDirectory()&&!t.isSymbolicLink()&&hc(e,t)}catch{return!1}}function ef(){return new Promise(n=>{setTimeout(n,10).unref()})}async function yc(n,e,t,o){let r=es(n);if(o?.aborted||Zr.has(r))return 0;Zr.add(r);let s=0;try{let a=await no(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await Gp(r,{bufferSize:32});try{let c=0,l=!0;for await(let u of i){if(o?.aborted||!l)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let d=gc(r,u.name);try{let p=await no(d);if(!p.isFile()||p.isSymbolicLink()||p.mtimeMs>=e)continue;await oo(d,async()=>{if(o?.aborted||!await mc(r,a))return!1;let h=await no(d);return!h.isFile()||h.isSymbolicLink()||!hc(p,h)||h.mtimeMs!==p.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await Qp(d),!0)})&&s++}catch{}}finally{++c%64===0&&(await ef(),l=!o?.aborted&&await mc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Zr.delete(r)}return s}function _c(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return yc(n,Date.now()-o,i=>qp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function tf(n,e){let t=Date.now()-Yp;return yc(n,t,o=>{let r=Zp.exec(o);return r!==null&&Number(r[1])<t},e)}function ts(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(()=>{})},c=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,Xp),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),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 bc(n=gc(Vp(),"claude-code-router")){return ts(`legacy:${es(n)}`,e=>tf(n,e),1e3)}var Yp,Xp,Zp,qp,Zr,to,qr,ns=P(()=>{"use strict";Yp=3600*1e3,Xp=600*1e3,Zp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,qp=/^\.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$/,Zr=new Set,to=new Map,qr=new Map});import{lstat as nf,mkdir as of,open as rf,rename as sf,unlink as af}from"node:fs/promises";import{randomUUID as cf}from"node:crypto";import{sanitizeTempFileKey as lf}from"@wengine-ai/claude-code-router-shared";import{basename as uf,join as os,resolve as df}from"node:path";import{tmpdir as pf}from"node:os";var Et,rs=P(()=>{"use strict";ns();Et=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=df(os(pf(),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=ts(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await of(this.baseDir,{recursive:!0});let e=await nf(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}-${lf(e)}${r}${o}`;if(uf(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return os(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 oo(a,async()=>{await this.ensureDir();let i=os(this.baseDir,`.ccr-tmp-${process.pid}-${cf()}.tmp`);return oo(i,async()=>{let c=!1;try{let l=await rf(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await sf(i,a),!0}finally{c&&await af(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return _c(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var ss,et,kc=P(()=>{"use strict";Yr();Xr();rs();ss=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 wt(e.config);case"webhook":return new Pt(e.config);case"temp-file":return new Et(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let c=this.handlers.get(i);if(!c){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await c.output(t,r)?s.success.push(i):s.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},et=new ss});var is=P(()=>{"use strict";fc();Yr();Xr();rs();kc()});import ff from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as mf}from"@wengine-ai/claude-code-router-shared";function ro(){return{subdirectory:mf,extension:"json",includeTimestamp:!1,prefix:"session"}}function vc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,gf);return Math.round(n/o)}function Ot(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Tc(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 et.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var At,as,gf,so,Cc=P(()=>{"use strict";Vr();is();je();At=new Map,as=new Map,gf=1,so={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:ff(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)et.registerHandlers(t.outputHandlers);else{let 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:ro()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&et.registerHandlers(a)}t.outputOptions&&et.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,l=a.model,u=`${c}:${l}`;if(as.has(u))return as.get(u);let d=i.getTokenizerConfigForModel(c,l);if(!d)return n.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await i.getTokenizer(d,c);return as.set(u,p),n.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return n.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}},s=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,c)=>{let l=a.requestStartTime;if(!l||a.chatCompletionCapture)return;let u=a.id||Date.now().toString(),d=a.usageSessionId||u,p=a.sessionId;if(!p)try{p=be(a.body?.metadata?.user_id)||d}catch{p=d}let f=await r(a);if(c instanceof ReadableStream){At.set(u,{requestId:u,sessionId:p,statsKey:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[g,_]=c.tee(),b=async()=>{let k=null,v=async T=>{let x=At.get(u);if(!x)return;let w=x.firstTokenTime?x.firstTokenTime-x.startTime:0,C=(T?x.lastTokenTime:performance.now())-x.startTime;x.tokensPerSecond=vc(x.tokenCount,C,w),await Tc(x,o,t.outputOptions,T).catch(A=>{n.log?.warn(`Failed to output streaming stats: ${A.message}`)})};try{let x=_.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();for(k=setInterval(async()=>{At.get(u)&&await v(!1)},1e3);;){let{done:w,value:E}=await x.read();if(w)break;let C=E,A=At.get(u);if(!A)continue;let F=performance.now(),R=C.event||C.data?.type,O=C.event==="content_block_start"||C.event==="content_block_delta"||C.event==="text_block"||C.event==="content_block"||R==="response.output_text.delta"||R==="response.function_call_arguments.delta"||R==="response.reasoning_summary_text.delta";!A.firstTokenTime&&O&&(A.firstTokenTime=F,A.timeToFirstToken=Math.round(F-A.startTime));let S="";if(C.event==="content_block_delta"&&C.data?.delta){let I=C.data.delta.type;I==="text_delta"?S=C.data.delta.text||"":I==="input_json_delta"?S=C.data.delta.partial_json||"":I==="thinking_delta"&&(S=C.data.delta.thinking||"")}if((R==="response.output_text.delta"||R==="response.function_call_arguments.delta"||R==="response.reasoning_summary_text.delta")&&(S=typeof C.data?.delta=="string"?C.data.delta:""),S){let I=f&&f.encodeText?f.encodeText(S).length:Ot(S);A.tokenCount+=I,A.lastTokenTime=F}(C.event==="message_stop"||R==="response.completed"||R==="response.failed")&&(k&&(clearInterval(k),k=null),await v(!0),At.delete(u))}}catch(T){k&&clearInterval(k),T.name!=="AbortError"&&T.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${T.message}`)}};return a.tokenSpeedCapturePromise=b().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),g}let h=performance.now(),m=0,y=!1;if(c&&typeof c=="string")try{let g=JSON.parse(c);if(typeof g.usage?.output_tokens=="number")m=g.usage.output_tokens,y=!0;else{let _=g.content??g.message?.content;if(_!==void 0)if(y=!0,f)Array.isArray(_)?m=_.reduce((b,k)=>{if(k.type==="text"){let v=k.text||"";return b+(f.encodeText?f.encodeText(v).length:Ot(v))}return b},0):typeof _=="string"&&(m=f.encodeText?f.encodeText(_).length:Ot(_));else{let b=Array.isArray(_)?_.map(k=>k.text).join(""):typeof _=="string"?_:"";m=Ot(b)}}}catch{}if(y){let g=h-l,_={requestId:u,sessionId:p,statsKey:d,startTime:l,lastTokenTime:h,tokenCount:m,tokensPerSecond:vc(m,g),stream:!1};await Tc(_,o,t.outputOptions,!0)}return c})})}});var cs=P(()=>{"use strict";dc();pc();Cc();is()});import re from"node:fs/promises";import Sc from"json5";import Ie from"node:path";import{CONFIG_FILE as ie,HOME_DIR as io,PLUGINS_DIR as hf}from"@wengine-ai/claude-code-router-shared";function xc(){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 ls,It,ao,Mt,X,co,fe,yf,us,Lt=P(()=>{"use strict";ls=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(ls);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=ls(o);return e}return n},It=async n=>{try{await re.access(n)}catch{await re.mkdir(n,{recursive:!0})}},ao=async()=>{await It(io),await It(hf),await It(Ie.join(io,"logs"))},Mt=async()=>{let n=await re.readFile(ie,"utf-8");return Sc.parse(n)},X=async()=>{try{let n=await re.readFile(ie,"utf-8");try{let e=Sc.parse(n);return ls(e)}catch(e){console.error(`Failed to parse config file at ${ie}`),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 ao();let e=await co();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await fe(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${ie}`),console.error("Error details:",n.message),process.exit(1)}};co=async()=>{xc();try{if(await re.access(ie).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${ie}.${n}.bak`;await re.copyFile(ie,e);try{let t=Ie.dirname(ie),o=Ie.basename(ie),s=(await re.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=Ie.join(t,s[a]);await re.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},fe=async n=>{xc(),await It(io),await yf();let e=`${JSON.stringify(n,null,2)}`;await re.writeFile(ie,e)},yf=async()=>{if(!await re.access(ie).then(()=>!0).catch(()=>!1))return;let e=Ie.join(io,"config-history");await It(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ie.join(e,`config-${t}.json`);await re.copyFile(ie,o);try{let s=(await re.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await re.unlink(Ie.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},us=async()=>{let n=await X();return Object.assign(process.env,n),n}});function lo(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(ds(r,s))}return}if(Array.isArray(n)){for(let o of n)lo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))lo(o,e,t)}}function Rc(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(ds(s,i))}return lo(n?.Router,t,o),lo(n?.fallback,t,o),o}function $t(n,e){try{let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=Rc(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(ds(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 uo(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 _f,ds,Nt=P(()=>{"use strict";ae();_f="\0",ds=(n,e)=>`${n}${_f}${e}`});function bf(n){return/\[1m\]/i.test(n)?1e6:2e5}function kf(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function vf(n,e=n){let t=bf(n),o=kf(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 Tf(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function ps(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,vf(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=Tf(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var fs=P(()=>{"use strict"});function Cf(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var po,ms=P(()=>{"use strict";po=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Cf(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],c=Array.isArray(i)?i[0]:i||"";if(!c){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let l="";if(c.startsWith("Bearer")?l=c.split(" ")[1]:l=c,l!==a){t.log.warn({url:e.url,gotPrefix:l.slice(0,10),gotSuffix:l.slice(-6),gotLen:l.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var Nc={};Ro(Nc,{append:()=>Ht,clear:()=>_s,close:()=>Wf,getOldestRecordTimestamp:()=>Kf,query:()=>ys,querySummary:()=>zt,readTokenSpeedStats:()=>bs});import{existsSync as Ec,mkdirSync as Sf,readFileSync as Ac}from"fs";import{join as go}from"path";import{tmpdir as xf}from"os";import{openSqliteDatabase as Rf}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as wf,sanitizeTempFileKey as Pf,TOKEN_SPEED_TEMP_SUBDIRECTORY as Ef}from"@wengine-ai/claude-code-router-shared";function Lf(){Ec(mo)||Sf(mo,{recursive:!0})}function jt(){if(Se)return Se;Lf();let n=Rf(Af),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&&($f(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")),Uf(e),Mc(e,!0),hs=e.prepare(`
321
+ `):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var At,Zr=E(()=>{"use strict";At=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let c=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);return c}catch(c){throw clearTimeout(i),c}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let c=1;c<=a.maxAttempts;c++)try{return await this.sendRequest(e,t,o,r,s)}catch(l){if(i=l,c===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,c-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${c}/${a.maxAttempts}), retrying in ${u}ms...`,l.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as oo,opendir as Vp,unlink as Yp}from"node:fs/promises";import{join as yc,resolve as ts}from"node:path";import{tmpdir as Xp}from"node:os";async function ro(n,e){let t=ts(n),o=no.get(t),r,s=new Promise(a=>{r=a});no.set(t,s);try{return await o,await e()}finally{r(),no.get(t)===s&&no.delete(t)}}function _c(n,e){return n.dev===e.dev&&n.ino===e.ino}async function hc(n,e){try{let t=await oo(n);return t.isDirectory()&&!t.isSymbolicLink()&&_c(e,t)}catch{return!1}}function nf(){return new Promise(n=>{setTimeout(n,10).unref()})}async function bc(n,e,t,o){let r=ts(n);if(o?.aborted||qr.has(r))return 0;qr.add(r);let s=0;try{let a=await oo(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await Vp(r,{bufferSize:32});try{let c=0,l=!0;for await(let u of i){if(o?.aborted||!l)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let d=yc(r,u.name);try{let p=await oo(d);if(!p.isFile()||p.isSymbolicLink()||p.mtimeMs>=e)continue;await ro(d,async()=>{if(o?.aborted||!await hc(r,a))return!1;let h=await oo(d);return!h.isFile()||h.isSymbolicLink()||!_c(p,h)||h.mtimeMs!==p.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await Yp(d),!0)})&&s++}catch{}}finally{++c%64===0&&(await nf(),l=!o?.aborted&&await hc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{qr.delete(r)}return s}function kc(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return bc(n,Date.now()-o,i=>tf.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function of(n,e){let t=Date.now()-Zp;return bc(n,t,o=>{let r=ef.exec(o);return r!==null&&Number(r[1])<t},e)}function ns(n,e,t){let o=es.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},c=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,qp),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},es.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),es.delete(n)))}}function vc(n=yc(Xp(),"claude-code-router")){return ns(`legacy:${ts(n)}`,e=>of(n,e),1e3)}var Zp,qp,ef,tf,qr,no,es,os=E(()=>{"use strict";Zp=3600*1e3,qp=600*1e3,ef=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,tf=/^\.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$/,qr=new Set,no=new Map,es=new Map});import{lstat as rf,mkdir as sf,open as af,rename as cf,unlink as lf}from"node:fs/promises";import{randomUUID as uf}from"node:crypto";import{sanitizeTempFileKey as df}from"@wengine-ai/claude-code-router-shared";import{basename as pf,join as rs,resolve as ff}from"node:path";import{tmpdir as mf}from"node:os";var Ot,ss=E(()=>{"use strict";os();Ot=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=ff(rs(mf(),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=ns(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await sf(this.baseDir,{recursive:!0});let e=await rf(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}-${df(e)}${r}${o}`;if(pf(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return rs(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 ro(a,async()=>{await this.ensureDir();let i=rs(this.baseDir,`.ccr-tmp-${process.pid}-${uf()}.tmp`);return ro(i,async()=>{let c=!1;try{let l=await af(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await cf(i,a),!0}finally{c&&await lf(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return kc(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var is,et,Tc=E(()=>{"use strict";Xr();Zr();ss();is=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 Et(e.config);case"webhook":return new At(e.config);case"temp-file":return new Ot(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let c=this.handlers.get(i);if(!c){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await c.output(t,r)?s.success.push(i):s.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},et=new is});var as=E(()=>{"use strict";gc();Xr();Zr();ss();Tc()});import gf from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as hf}from"@wengine-ai/claude-code-router-shared";function so(){return{subdirectory:hf,extension:"json",includeTimestamp:!1,prefix:"session"}}function Cc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,yf);return Math.round(n/o)}function Mt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Sc(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 et.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var It,cs,yf,io,xc=E(()=>{"use strict";Yr();as();je();It=new Map,cs=new Map,yf=1,io={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:gf(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)et.registerHandlers(t.outputHandlers);else{let 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:so()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&et.registerHandlers(a)}t.outputOptions&&et.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,l=a.model,u=`${c}:${l}`;if(cs.has(u))return cs.get(u);let d=i.getTokenizerConfigForModel(c,l);if(!d)return n.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await i.getTokenizer(d,c);return cs.set(u,p),n.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return n.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}},s=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,c)=>{if(!s(a.url))return;let l=a.requestStartTime;if(!l||a.chatCompletionCapture)return;let u=a.id||Date.now().toString(),d=a.usageSessionId||u,p=a.sessionId;if(!p)try{p=be(a.body?.metadata?.user_id)||d}catch{p=d}let f=await r(a);if(c instanceof ReadableStream){It.set(u,{requestId:u,sessionId:p,statsKey:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[m,b]=c.tee(),_=async()=>{let k=null,v=async T=>{let S=It.get(u);if(!S)return;let w=S.firstTokenTime?S.firstTokenTime-S.startTime:0,R=(T?S.lastTokenTime:performance.now())-S.startTime;S.tokensPerSecond=Cc(S.tokenCount,R,w),await Sc(S,o,t.outputOptions,T).catch(A=>{n.log?.warn(`Failed to output streaming stats: ${A.message}`)})};try{let S=b.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();for(k=setInterval(async()=>{It.get(u)&&await v(!1)},1e3);;){let{done:w,value:P}=await S.read();if(w)break;let R=P,A=It.get(u);if(!A)continue;let D=performance.now(),x=R.event||R.data?.type,O=R.event==="content_block_start"||R.event==="content_block_delta"||R.event==="text_block"||R.event==="content_block"||x==="response.output_text.delta"||x==="response.function_call_arguments.delta"||x==="response.reasoning_summary_text.delta";!A.firstTokenTime&&O&&(A.firstTokenTime=D,A.timeToFirstToken=Math.round(D-A.startTime));let C="";if(R.event==="content_block_delta"&&R.data?.delta){let I=R.data.delta.type;I==="text_delta"?C=R.data.delta.text||"":I==="input_json_delta"?C=R.data.delta.partial_json||"":I==="thinking_delta"&&(C=R.data.delta.thinking||"")}if((x==="response.output_text.delta"||x==="response.function_call_arguments.delta"||x==="response.reasoning_summary_text.delta")&&(C=typeof R.data?.delta=="string"?R.data.delta:""),C){let I=f&&f.encodeText?f.encodeText(C).length:Mt(C);A.tokenCount+=I,A.lastTokenTime=D}(R.event==="message_stop"||x==="response.completed"||x==="response.failed")&&(k&&(clearInterval(k),k=null),await v(!0),It.delete(u))}}catch(T){k&&clearInterval(k),T.name!=="AbortError"&&T.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${T.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),m}let h=performance.now(),g=0,y=!1;if(c&&typeof c=="string")try{let m=JSON.parse(c);if(typeof m.usage?.output_tokens=="number")g=m.usage.output_tokens,y=!0;else{let b=m.content??m.message?.content;if(b!==void 0)if(y=!0,f)Array.isArray(b)?g=b.reduce((_,k)=>{if(k.type==="text"){let v=k.text||"";return _+(f.encodeText?f.encodeText(v).length:Mt(v))}return _},0):typeof b=="string"&&(g=f.encodeText?f.encodeText(b).length:Mt(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";g=Mt(_)}}}catch{}if(y){let m=h-l,b={requestId:u,sessionId:p,statsKey:d,startTime:l,lastTokenTime:h,tokenCount:g,tokensPerSecond:Cc(g,m),stream:!1};await Sc(b,o,t.outputOptions,!0)}return c})})}});var ls=E(()=>{"use strict";fc();mc();xc();as()});import re from"node:fs/promises";import Rc from"json5";import Ie from"node:path";import{CONFIG_FILE as ae,HOME_DIR as ao,PLUGINS_DIR as _f}from"@wengine-ai/claude-code-router-shared";function wc(){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 us,Lt,co,$t,X,lo,fe,bf,ds,Nt=E(()=>{"use strict";us=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(us);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=us(o);return e}return n},Lt=async n=>{try{await re.access(n)}catch{await re.mkdir(n,{recursive:!0})}},co=async()=>{await Lt(ao),await Lt(_f),await Lt(Ie.join(ao,"logs"))},$t=async()=>{let n=await re.readFile(ae,"utf-8");return Rc.parse(n)},X=async()=>{try{let n=await re.readFile(ae,"utf-8");try{let e=Rc.parse(n);return us(e)}catch(e){console.error(`Failed to parse config file at ${ae}`),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 co();let e=await lo();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await fe(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${ae}`),console.error("Error details:",n.message),process.exit(1)}};lo=async()=>{wc();try{if(await re.access(ae).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${ae}.${n}.bak`;await re.copyFile(ae,e);try{let t=Ie.dirname(ae),o=Ie.basename(ae),s=(await re.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=Ie.join(t,s[a]);await re.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},fe=async n=>{wc(),await Lt(ao),await bf();let e=`${JSON.stringify(n,null,2)}`;await re.writeFile(ae,e)},bf=async()=>{if(!await re.access(ae).then(()=>!0).catch(()=>!1))return;let e=Ie.join(ao,"config-history");await Lt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ie.join(e,`config-${t}.json`);await re.copyFile(ae,o);try{let s=(await re.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await re.unlink(Ie.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},ds=async()=>{let n=await X();return Object.assign(process.env,n),n}});function uo(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(ps(r,s))}return}if(Array.isArray(n)){for(let o of n)uo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))uo(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(ps(s,i))}return uo(n?.Router,t,o),uo(n?.fallback,t,o),o}function Ut(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(ps(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 po(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 kf,ps,Dt=E(()=>{"use strict";ce();kf="\0",ps=(n,e)=>`${n}${kf}${e}`});function vf(n){return/\[1m\]/i.test(n)?1e6:2e5}function Tf(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Cf(n,e=n){let t=vf(n),o=Tf(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 Sf(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function fs(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Cf(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=Sf(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var ms=E(()=>{"use strict"});function xf(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var fo,gs=E(()=>{"use strict";fo=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||xf(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],c=Array.isArray(i)?i[0]:i||"";if(!c){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let l="";if(c.startsWith("Bearer")?l=c.split(" ")[1]:l=c,l!==a){t.log.warn({url:e.url,gotPrefix:l.slice(0,10),gotSuffix:l.slice(-6),gotLen:l.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var Dc={};wo(Dc,{append:()=>Bt,clear:()=>bs,close:()=>Gf,getOldestRecordTimestamp:()=>Qf,query:()=>_s,querySummary:()=>Jt,readTokenSpeedStats:()=>ks});import{existsSync as Oc,mkdirSync as Rf,readFileSync as Ic}from"fs";import{join as ho}from"path";import{tmpdir as wf}from"os";import{openSqliteDatabase as Pf}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Ef,sanitizeTempFileKey as Af,TOKEN_SPEED_TEMP_SUBDIRECTORY as Of}from"@wengine-ai/claude-code-router-shared";function Nf(){Oc(go)||Rf(go,{recursive:!0})}function zt(){if(Se)return Se;Nf();let n=Pf(If),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&&(Uf(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")),Ff(e),$c(e,!0),ys=e.prepare(`
322
322
  INSERT INTO usage_records (
323
323
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
324
324
  scenario_type, client_type,
@@ -332,7 +332,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
332
332
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
333
333
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
334
334
  )
335
- `),Se=e,Se}function $f(n){n.exec(`
335
+ `),Se=e,Se}function Uf(n){n.exec(`
336
336
  CREATE TABLE IF NOT EXISTS usage_records (
337
337
  id TEXT PRIMARY KEY,
338
338
  timestamp TEXT NOT NULL,
@@ -369,12 +369,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
369
369
  CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
370
370
  CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
371
371
  CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
372
- `)}function Nf(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ut(n,e,t){n.prepare(`
372
+ `)}function Df(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ft(n,e,t){n.prepare(`
373
373
  INSERT INTO usage_meta (key, value)
374
374
  VALUES (?, ?)
375
375
  ON CONFLICT(key) DO UPDATE SET value = excluded.value
376
- `).run(e,t)}function Uf(n){if(Nf(n,wc)||!Ec(gs))return;let e=Ff(n,"INSERT OR IGNORE"),t=Ac(gs,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
377
- `)){let c=i.trim();if(c)try{let l=JSON.parse(c);if(!Df(l)){r++;continue}e.run(Ic(ho(l))).changes>0?o++:s++}catch{r++}}Ut(n,wc,new Date().toISOString()),Ut(n,"legacy_usage_jsonl_migrated_path",gs),Ut(n,"legacy_usage_jsonl_imported_count",String(o)),Ut(n,"legacy_usage_jsonl_skipped_count",String(r)),Ut(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function Df(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 Ff(n,e="INSERT"){return n.prepare(`
376
+ `).run(e,t)}function Ff(n){if(Df(n,Ec)||!Oc(hs))return;let e=Hf(n,"INSERT OR IGNORE"),t=Ic(hs,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
377
+ `)){let c=i.trim();if(c)try{let l=JSON.parse(c);if(!jf(l)){r++;continue}e.run(Lc(yo(l))).changes>0?o++:s++}catch{r++}}Ft(n,Ec,new Date().toISOString()),Ft(n,"legacy_usage_jsonl_migrated_path",hs),Ft(n,"legacy_usage_jsonl_imported_count",String(o)),Ft(n,"legacy_usage_jsonl_skipped_count",String(r)),Ft(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function jf(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 Hf(n,e="INSERT"){return n.prepare(`
378
378
  ${e} INTO usage_records (
379
379
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
380
380
  scenario_type, client_type,
@@ -388,11 +388,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
388
388
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
389
389
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
390
390
  )
391
- `)}function jf(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,Of);return Math.round(n/r)}function ho(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Ft(n.ttft):null;return{...n,ttft:r,tokensPerSecond:jf(e,o,r)}}function Ce(n){return typeof n=="string"?n:n==null?"":String(n)}function fo(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function Dt(n){let e=Number(n);return Number.isFinite(e)?e:0}function Oc(n){return n==="success"?"success":"error"}function Ic(n){let e=ho(n);return{id:Ce(e.id),timestamp:Ce(e.timestamp),session_id:Ce(e.sessionId),provider:Ce(e.provider),original_model:Ce(e.originalModel),model:Ce(e.model),upstream_model:fo(e.upstreamModel)??null,model_family:Ce(e.modelFamily),scenario_type:Ce(e.scenarioType),client_type:fo(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(Dt(e.inputTokens)),output_tokens:Math.trunc(Dt(e.outputTokens)),cache_read_input_tokens:Math.trunc(Dt(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(Dt(e.cacheCreationInputTokens)),ttft:Ft(e.ttft),tokens_per_second:Ft(e.tokensPerSecond),duration_ms:Math.trunc(Dt(e.durationMs)),status:Oc(e.status),error_message:fo(e.errorMessage)??null,response_body:fo(e.responseBody)??null}}function Hf(n){return ho({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:Oc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function zf(){return new Date(Date.now()-If*24*60*60*1e3).toISOString()}function Mc(n,e=!1){let t=Date.now();!e&&t-Pc<Mf||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(zf()),Pc=t)}function Lc(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 tt(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
392
- SELECT ${t} AS key, ${Bf}
391
+ `)}function zf(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,Mf);return Math.round(n/r)}function yo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Ht(n.ttft):null;return{...n,ttft:r,tokensPerSecond:zf(e,o,r)}}function Ce(n){return typeof n=="string"?n:n==null?"":String(n)}function mo(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function jt(n){let e=Number(n);return Number.isFinite(e)?e:0}function Mc(n){return n==="success"?"success":"error"}function Lc(n){let e=yo(n);return{id:Ce(e.id),timestamp:Ce(e.timestamp),session_id:Ce(e.sessionId),provider:Ce(e.provider),original_model:Ce(e.originalModel),model:Ce(e.model),upstream_model:mo(e.upstreamModel)??null,model_family:Ce(e.modelFamily),scenario_type:Ce(e.scenarioType),client_type:mo(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(jt(e.inputTokens)),output_tokens:Math.trunc(jt(e.outputTokens)),cache_read_input_tokens:Math.trunc(jt(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(jt(e.cacheCreationInputTokens)),ttft:Ht(e.ttft),tokens_per_second:Ht(e.tokensPerSecond),duration_ms:Math.trunc(jt(e.durationMs)),status:Mc(e.status),error_message:mo(e.errorMessage)??null,response_body:mo(e.responseBody)??null}}function Bf(n){return yo({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:Mc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function Jf(){return new Date(Date.now()-Lf*24*60*60*1e3).toISOString()}function $c(n,e=!1){let t=Date.now();!e&&t-Ac<$f||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(Jf()),Ac=t)}function Nc(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 tt(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
392
+ SELECT ${t} AS key, ${Wf}
393
393
  FROM usage_records ${r}
394
394
  GROUP BY key
395
- `).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 $c(n,e){let t=Lc(e),o=n.prepare(`
395
+ `).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 Uc(n,e){let t=Nc(e),o=n.prepare(`
396
396
  SELECT
397
397
  COUNT(*) AS totalRequests,
398
398
  COALESCE(SUM(usage_estimated), 0) AS estimatedCount,
@@ -404,15 +404,15 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
404
404
  AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
405
405
  AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
406
406
  FROM usage_records ${t.sql}
407
- `).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:tt(n,t,"model"),byProvider:tt(n,t,"provider"),byScenario:tt(n,t,"scenario_type"),byFamily:tt(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:tt(n,t,"date(timestamp, 'localtime')"),byClient:tt(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function Ht(n){let e=jt(),t=ho(n);hs.run(Ic(t)),Mc(e)}function ys(n){let e=jt(),t=Lc(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),Jf):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),c=$c(e,n);return{records:i.map(Hf),summary:c,total:a.count,page:o,pageSize:r}}function zt(n,e,t){let o=jt();return $c(o,{startTime:n,endTime:e,status:t})}function _s(n){let e=jt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Wf(){Se&&(Se.pragma("wal_checkpoint(TRUNCATE)"),Se.close(),Se=null,hs=null)}function Ft(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function bs(n){let e=go(xf(),Ef,`session-${Pf(n)}.json`);try{let t=JSON.parse(Ac(e,"utf-8"));return{ttft:Ft(t.timeToFirstToken),tokensPerSecond:Ft(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function Kf(n,e,t){return jt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var mo,Af,gs,Of,If,Mf,wc,Se,hs,Pc,Bf,Jf,Bt=P(()=>{"use strict";mo=go(wf,"data"),Af=go(mo,"usage.sqlite"),gs=go(mo,"usage.jsonl"),Of=1,If=180,Mf=3600*1e3,wc="legacy_usage_jsonl_migrated_at",Se=null,hs=null,Pc=0;Bf=`
407
+ `).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:tt(n,t,"model"),byProvider:tt(n,t,"provider"),byScenario:tt(n,t,"scenario_type"),byFamily:tt(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:tt(n,t,"date(timestamp, 'localtime')"),byClient:tt(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function Bt(n){let e=zt(),t=yo(n);ys.run(Lc(t)),$c(e)}function _s(n){let e=zt(),t=Nc(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),Kf):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),c=Uc(e,n);return{records:i.map(Bf),summary:c,total:a.count,page:o,pageSize:r}}function Jt(n,e,t){let o=zt();return Uc(o,{startTime:n,endTime:e,status:t})}function bs(n){let e=zt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Gf(){Se&&(Se.pragma("wal_checkpoint(TRUNCATE)"),Se.close(),Se=null,ys=null)}function Ht(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function ks(n){let e=ho(wf(),Of,`session-${Af(n)}.json`);try{let t=JSON.parse(Ic(e,"utf-8"));return{ttft:Ht(t.timeToFirstToken),tokensPerSecond:Ht(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function Qf(n,e,t){return zt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var go,If,hs,Mf,Lf,$f,Ec,Se,ys,Ac,Wf,Kf,Wt=E(()=>{"use strict";go=ho(Ef,"data"),If=ho(go,"usage.sqlite"),hs=ho(go,"usage.jsonl"),Mf=1,Lf=180,$f=3600*1e3,Ec="legacy_usage_jsonl_migrated_at",Se=null,ys=null,Ac=0;Wf=`
408
408
  COUNT(*) AS count,
409
409
  COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
410
410
  COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
411
411
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
412
412
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
413
- `;Jf=200});import{existsSync as Gf}from"fs";import{homedir as Qf}from"os";import{join as Vf}from"path";import{writeFile as Yf}from"fs/promises";async function Uc(){let n=Qf(),e=Vf(n,".claude.json");if(!Gf(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 Yf(e,JSON.stringify(o,null,2))}}var Dc=P(()=>{"use strict"});import{existsSync as Xf,readdirSync as Zf,statSync as qf,unlinkSync as em}from"fs";import{join as Fc}from"path";import{HOME_DIR as tm}from"@wengine-ai/claude-code-router-shared";function Hc(n=Fc(tm,"logs")){try{if(!Xf(n))return;let e=Date.now()-om;for(let t of Zf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=Fc(n,t),r=qf(o);r.isFile()&&r.mtime.getTime()<e&&em(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function zc(){jc||(jc=!0,Hc(),setInterval(Hc,rm).unref())}var nm,om,rm,jc,Bc=P(()=>{"use strict";nm=7,om=nm*24*60*60*1e3,rm=1440*60*1e3,jc=!1});async function Jc(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":Rt.registerPlugin(so,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:ro()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await Rt.enablePlugins(n)}var Wc=P(()=>{"use strict";cs()});function nt(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()),$t(e,t),Jr();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=xt(()=>n.providerService.getProviders(),o,r=>me(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var yo=P(()=>{"use strict";Nt();qn();te()});import{constants as ks,lstatSync as ot,realpathSync as Jt,openSync as sm,closeSync as im,fstatSync as am,readFileSync as Kc}from"node:fs";import{dirname as Hk,join as rt,sep as cm}from"node:path";import{pathToFileURL as lm}from"node:url";function Qc(n){try{let e=JSON.parse(Kc(rt(um(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function Ts(n,e){if(!Gc(e))return null;try{let t=Jt(n),o=rt(t,"plugins"),r=rt(o,e);return ot(o).isSymbolicLink()||!ot(o).isDirectory()||ot(r).isSymbolicLink()||!ot(r).isDirectory()||Jt(o)!==o||Jt(r)!==r||!r.startsWith(o+cm)?null:r}catch{return null}}function vs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=Ts(n,e);if(!o)throw new Error("unsafe plugin directory");let r=rt(o,t),s=ot(r);if(s.isSymbolicLink()||!s.isFile()||Jt(r)!==r)throw new Error("unsafe plugin file");let a=sm(r,ks.O_RDONLY|ks.O_NOFOLLOW|ks.O_NONBLOCK);try{let i=am(a),c=ot(r);if(!i.isFile()||c.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==c.dev||i.ino!==c.ino||Ts(n,e)!==o||Jt(r)!==r)throw new Error("plugin file changed while opening");return Kc(a)}finally{im(a)}}function dm(n){let e=n?.configService,t=e?Hs(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return zs(t)}async function Vc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??No(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>Mt(),writeConfig:i=>fe(i),reloadRuntime:async i=>nt(n.getServer(),i??await X(),t),getDirectDispatcher:Po,getSubscriptionDispatcher:()=>dm(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Qc(e)){let c;try{if(!Gc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let l=Ts(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let m=JSON.parse(vs(e,i.name,"plugin.json").toString("utf8"));if(!m||typeof m.name!="string"||typeof m.version!="string")throw new Error;u={name:m.name,version:m.version,coreApi:String(m.coreApi??"1"),description:m.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 d=o.beginActivation(u,{info:m=>t.info(`[plugin:${u.name}] ${m}`),warn:m=>t.warn(`[plugin:${u.name}] ${m}`),error:m=>t.error(`[plugin:${u.name}] ${m}`)},r,l);c=d,vs(e,i.name,"plugin.js");let p=await import(lm(rt(l,"plugin.js")).href),f=p?.activate??p?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(d.context);let h=d.cardPath?vs(e,i.name,d.cardPath):void 0;await d.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function Yc(n,e=No()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Qc(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 Gc,um,Cs=P(()=>{"use strict";Lo();ct();yo();Lt();te();Gc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),um=n=>rt(n,"plugins")});import{gt as pm,valid as Xc}from"semver";import{existsSync as Zc,readFileSync as fm}from"node:fs";import{join as Ss}from"node:path";import{NPM_SPEC_PATTERN as mm,PLUGIN_NAME_PATTERN as qc,PluginInstallError as gm,installPluginFromNpm as hm,readPluginRecords as ym}from"@wengine-ai/claude-code-router-shared";async function bm(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 km(n,e={}){let t=(e.registryBase??_m).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(el.map(y=>bm(t,y,o))),s=new Map,a=!1;for(let y of r)if(y.status==="fulfilled"){a=!0;for(let g of y.value){let _=g?.package,b=typeof _?.name=="string"?_.name:"";if(!b||!mm.test(b)||!(Array.isArray(_?.keywords)?_.keywords.filter(T=>typeof T=="string"):[]).some(T=>el.includes(T)))continue;let v=typeof _?.version=="string"?_.version:"";s.has(b)||s.set(b,{name:b,version:v,description:typeof _?.description=="string"?_.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=ym(n),c=new Map(i.map(y=>[y.name,y])),l=y=>{let g=y.indexOf("@",y.startsWith("@")?1:0);return g>0?y.slice(0,g):y},u=new Map(i.filter(y=>typeof y.source=="string"&&y.source!=="").map(y=>[l(y.source),y])),d=y=>{if(!qc.test(y))return null;try{let g=JSON.parse(fm(Ss(n,"plugins",y,"plugin.json"),"utf8"));return typeof g?.version=="string"?g.version:null}catch{return null}},p=[...s.values()].sort((y,g)=>y.name.localeCompare(g.name)).map(y=>{let g=c.get(y.name)??u.get(y.name),_=g!==void 0||Zc(Ss(n,"plugins",y.name)),b=_?d(g?g.name:y.name):null;return{...y,installed:_,installedVersion:b,..._&&b!==null&&Xc(b)&&Xc(y.version)&&pm(y.version,b)?{updateAvailable:!0}:{}}}),f=new Set(p.map(y=>y.name)),h=new Set,m=new Map;for(let[y,g]of u)h.add(g.name),!f.has(y)&&m.set(y,g.name);for(let y of i)f.has(y.name)||h.has(y.name)||m.set(y.name,y.name);for(let[y,g]of m){if(!qc.test(g)||!Zc(Ss(n,"plugins",g)))continue;let _=d(g);_!==null&&p.push({name:y,description:"",version:_,installed:!0,installedVersion:_,localOnly:!0})}return p.sort((y,g)=>y.name.localeCompare(g.name)),{ok:!0,plugins:p}}function vm(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 tl(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),c=n.headers?.host;if(typeof c=="string"&&!i.has(c))return!1;let l=n.headers?.origin;if(l!==void 0&&l!==""){if(typeof l!="string")return!1;let u="";try{let d=new URL(l);if(!["http:","https:"].includes(d.protocol))return!1;u=d.host}catch{return!1}if(!i.has(u))return!1}return!0}function nl(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(!tl(r,n,t))return o(s,403,"local_only");try{return await km(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(!tl(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,c=a.force===!0;try{let l=await hm({spec:i,configDir:e.configDir,force:c,registry:e.registry,timeoutMs:e.npmTimeoutMs});return n.log?.info?.(`provider plugin installed via API: ${l.manifest.name}@${l.manifest.version} (restart to activate)`),{ok:!0,name:l.manifest.name,version:l.manifest.version,restartRequired:!0}}catch(l){if(l instanceof gm){let u=vm(l.code);return u===502?n.log?.warn?.(`plugin install failed: ${l.code}`):n.log?.warn?.(`plugin install rejected: ${l.code}: ${l.message}`),o(s,u,l.code)}return n.log?.error?.(`plugin install crashed: ${l?.message??l}`),o(s,500,"install_failed")}})}var el,_m,ol=P(()=>{"use strict";el=["ccr-provider-plugin","claude-code-router-plugin"],_m="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Tm}from"@wengine-ai/claude-code-router-shared";import{join as Z,isAbsolute as Cm,normalize as Sm,dirname as xm}from"path";import{fileURLToPath as Rm}from"url";import wm from"@fastify/static";import{readdirSync as rl,statSync as Pm,readFileSync as sl,writeFileSync as Em,existsSync as de,unlinkSync as il,rmSync as Am}from"fs";import{homedir as xs}from"os";import{getPresetDir as _o,readManifestFromDir as Rs,manifestToPresetFile as al,saveManifest as cl,isPresetInstalled as ll,extractPreset as Om,HOME_DIR as ws,loadConfigFromManifest as Im,downloadPresetToTemp as Mm,findMarketPresetByName as Lm,getMarketPresets as $m,applyClientSelection as Nm,disableClient as Um,enableClient as Dm,isClientId as Fm,listClientStatuses as ul,restoreClient as jm,listProjectConfigs as Hm,readProjectConfigById as Ps,readProjectConfig as zm,writeProjectConfig as dl,deleteProjectConfig as Bm,getClaudeProjectId as Jm,getProjectConfigPath as Wm,refreshCcrProjectTakeover as Km,refreshPiProjectTakeover as Gm,refreshProjectTakeovers as Qm,syncGlobalProjectTakeovers as Es,getProjectTakeoverClients as As,setProjectTakeover as Os,isProjectTakeoverClient as Vm}from"@wengine-ai/claude-code-router-shared";import Ym from"@fastify/multipart";import Xm from"adm-zip";function pl(n){let e=H();return ps(n,(t,o)=>e.isAvailable(t,o))}function fl(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 Zm(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=zt(t,e),s=zt(o,e),a=[],i=new Set;for(let c of n||[])c&&c.name&&i.add(c.name);for(let c of Object.keys(r.byProvider||{}))i.add(c);for(let c of Object.keys(s.byProvider||{}))i.add(c);for(let c of i){let l=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},d=(l.inputTokens||0)+(l.outputTokens||0),p=(u.inputTokens||0)+(u.outputTokens||0),f,h,m=(n||[]).find(y=>y&&y.name===c);m&&m.quota&&(f=m.quota.limit5h,h=m.quota.limit7d),a.push({provider:c,used5h:d,used7d:p,limit5h:f,limit7d:h})}return a}async function ml(n,e){let t=n.app;dt(),mt(),t.register(Ym,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=pl(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,c)=>{let l=decodeURIComponent(i.params.modelId),u=pl(e).find(d=>d.id===l);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${l}`}})}),t.post("/v1/messages/count_tokens",async(i,c)=>{let{messages:l,tools:u,system:d,model:p}=i.body,f=t._server.tokenizerService;if(p&&p.includes(",")&&f)try{let[m,y]=p.split(",");i.log?.info(`Looking up tokenizer for provider: ${m}, model: ${y}`);let g=f.getTokenizerConfigForModel(m,y);g?i.log?.info(`Using tokenizer config: ${JSON.stringify(g)}`):i.log?.warn(`No tokenizer config found for ${m},${y}, using default tiktoken`);let _=await f.countTokens({messages:l,system:d,tools:u},g,m);return{input_tokens:_.tokenCount,tokenizer:_.tokenizerUsed}}catch(m){i.log?.error(`Error using configured tokenizer: ${m.message}`),i.log?.error(m.stack)}else p?p.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${p}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:fn(l,d,u)}}),t.get("/api/config",async(i,c)=>await Mt()),t.get("/api/transformers",async(i,c)=>{let l=t._server.transformerService.getAllTransformers();return{transformers:Array.from(l.entries()).map(([d,p])=>({name:d,endpoint:p.endPoint||null}))}}),t.post("/api/config",async(i,c)=>{let l=i.body,u=js(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(h=>`${h.key}: ${h.error}`).join("; "),proxyErrors:u};let d=await co();d&&console.log(`Backed up existing configuration file to ${d}`);let p=null;try{p=await X()}catch{}Tm(l,p),n.pluginRegistry.applyConfigProtectors(l,p),await fe(l);let f;try{f=await Es(l),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 nt(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,c)=>{try{let l=await X();return{clients:ul(l)}}catch(l){console.error("Failed to get client integrations:",l),c.status(500).send({error:l.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(i,c)=>{try{let l=i.body,u=Array.isArray(l?.enabled)?l.enabled:[],d=await X(),p=Nm(d,u);await fe(p.config);let f=await Es(p.config),h=fl(t,f,"clients/apply");return{...p,success:p.success&&h,projectTakeoverSync:f}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!Fm(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let d=await X(),p=l==="enable"?Dm(d,u):l==="restore"?jm(d,u):Um(d,u);await fe(d);let f=await Es(d),h=fl(t,f,`clients/${u}/${l}`);return{success:p.success&&h,result:p,results:[p],clients:ul(d),config:d,projectTakeoverSync:f}}catch(u){console.error(`Failed to ${l} client integration:`,u),c.status(500).send({error:u.message||`Failed to ${l} client integration`})}}t.post("/api/clients/:id/enable",async(i,c)=>o(i,c,"enable")),t.post("/api/clients/:id/disable",async(i,c)=>o(i,c,"disable")),t.post("/api/clients/:id/restore",async(i,c)=>o(i,c,"restore")),t.get("/api/projects",async(i,c)=>{try{let l=await Hm();return{projects:await Promise.all(l.map(async d=>{let p=await As(d.path);return{...d,ccrTakeoverClients:p,ccrTakeover:p.length>0}}))}}catch(l){console.error("Failed to list project configs:",l),c.status(500).send({error:l.message||"Failed to list project configs"})}}),t.post("/api/projects",async(i,c)=>{try{let{path:l}=i.body||{};if(!l||typeof l!="string"||!Cm(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=Sm(l).replace(/[\\/]+$/,"")||l;if(await zm(u)){c.status(409).send({error:"Project is already configured"});return}await dl(u,{Router:{}});try{let f=await X();await Os(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let p=await As(u);return{id:Jm(u),path:u,configPath:Wm(u),Router:{},ccrTakeoverClients:p,ccrTakeover:p.length>0}}catch(l){console.error("Failed to add project config:",l),c.status(500).send({error:l.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){c.status(400).send({error:"Router must be an object"});return}let d=await Ps(l);if(!d){c.status(404).send({error:"Project config not found"});return}await dl(d.path,{Router:u});let p=await X();Object.keys(u).length===0?await Qm(d.path,p):(await Km(d.path,p,u),await Gm(d.path,p,u));let f=await As(d.path);return{id:l,path:d.path,configPath:d.configPath,Router:u,ccrTakeoverClients:f,ccrTakeover:f.length>0}}catch(l){console.error("Failed to update project config:",l),c.status(500).send({error:l.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(i,c)=>{try{let{id:l}=i.params,u=i.body||{},d;if(Array.isArray(u.clients))d=u.clients.filter(Vm);else if(typeof u.enabled=="boolean")d=u.enabled?["claudeCode"]:[];else{c.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let p=await Ps(l);if(!p){c.status(404).send({error:"Project config not found"});return}let f=await X(),h=await Os(p.path,d,f);return{id:l,path:p.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await Ps(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let d=await X();await Os(u.path,[],d)}catch(d){console.error("Failed to remove ccr takeover while deleting project:",d)}return await Bm(u.path),{success:!0}}catch(l){console.error("Failed to delete project config:",l),c.status(500).send({error:l.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:xm(Rm(import.meta.url)),s=de(Z(r,"index.html"))?r:de(Z(r,"..","index.html"))?Z(r,".."):de(Z(r,"..","dist","index.html"))?Z(r,"..","dist"):de(Z(r,"..","..","dist","index.html"))?Z(r,"..","..","dist"):Z(r,"..","dist");t.register(wm,{root:s,prefix:"/ui/",cacheControl:!1,setHeaders:(i,c)=>{i.setHeader("Cache-Control","no-cache")}}),t.get("/ui",async(i,c)=>c.redirect("/ui/")),t.get("/api/logs/files",async(i,c)=>{try{let l=Z(xs(),".claude-code-router","logs"),u=[];if(de(l)){let d=rl(l);for(let p of d)if(p.endsWith(".log")){let f=Z(l,p),h=Pm(f);u.push({name:p,path:f,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((p,f)=>new Date(f.lastModified).getTime()-new Date(p.lastModified).getTime())}return u}catch(l){console.error("Failed to get log files:",l),c.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=Z(xs(),".claude-code-router","logs","app.log"),de(u)?sl(u,"utf8").split(`
414
- `).filter(f=>f.trim()):[]}catch(l){console.error("Failed to get logs:",l),c.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=Z(xs(),".claude-code-router","logs","app.log"),de(u)&&Em(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(l){console.error("Failed to clear logs:",l),c.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:Qt()})),t.put("/api/debug-log",async i=>{let{enabled:c}=i.body;return Io(c),{enabled:Qt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return ys({startTime:l.startDate,endTime:l.endDate,model:l.model,provider:l.provider,scenario:l.scenario,clientType:l.clientType,sessionId:l.sessionId,status:l.status,page:l.page?parseInt(l.page,10):void 0,pageSize:l.pageSize?parseInt(l.pageSize,10):void 0})}catch(l){console.error("Failed to query usage:",l),c.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(i,c)=>{try{let l=i.query;return zt(l.startDate,l.endDate,l.status)}catch(l){console.error("Failed to query usage summary:",l),c.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(i,c)=>{try{let l=i.query;return _s(l.beforeDate),{success:!0,message:l.beforeDate?"Usage data cleared before "+l.beforeDate:"All usage data cleared"}}catch(l){console.error("Failed to clear usage:",l),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,c)=>{try{let u=H().getAllStates(),p=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:p,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to get provider health:",l),c.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,c)=>{try{let{providerName:l}=i.body;if(!l)return c.status(400),{error:"providerName is required"};let d=t._server?.activeProbeService;if(!d?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let p=await d.probeProviderManually(l);return p.success&&uo(l,i.log),{provider:l,success:p.success,latencyMs:p.latencyMs,status:p.status,isSlow:p.isSlow,errorKind:p.errorKind??null,error:p.error,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe provider:",l),c.status(500).send({error:l.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,c)=>{try{let l=t._server,u=l?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let d=(l?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),p=await Promise.all(d.map(async f=>{let h=await u.probeProviderManually(f.name);return h.success&&uo(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:p,successCount:p.filter(f=>f.success).length,total:p.length,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe all providers:",l),c.status(500).send({error:l.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,c)=>{try{let u=(await X()).Providers||[],d=t._server?.pluginRegistry,p=t._server?.providerService;if(d&&p?.getProviders){let _=p.getProviders().filter(b=>b?.name&&b.enabled!==!1).map(b=>{let k=d.getManagedRuntimeFor(b);if(!(!k||typeof k.fetchQuota!="function"))return Xn(b.name,b,k)}).filter(b=>!!b);if(_.length){let b=new Promise(k=>{setTimeout(k,cc).unref?.()});await Promise.race([Promise.all(_),b])}}let f=Zm(u),h=new Map(f.map(g=>[g.provider,g])),m=Vo();for(let g of f){let _=m.find(b=>b.provider===g.provider);_&&_.limit!=null&&!nn(_.reset)&&(g.limit5h=_.limit,g.used5h=_.limit-(_.remaining??0),_.reset&&(g.reset5h=new Date(_.reset*1e3).toISOString()))}let y=ir();for(let g of y){let _=h.get(g.provider);_||(_={provider:g.provider,used5h:0,used7d:0},f.push(_),h.set(g.provider,_)),typeof g.totalBalance=="number"?(_.limit7d=g.totalBalance,_.type7d=g.currency?"balance":"rateLimit",g.currency&&(_.currency=g.currency),typeof g.usedBalance=="number"?_.used7d=g.usedBalance:typeof g.remainingBalance=="number"?_.used7d=Math.max(0,g.totalBalance-g.remainingBalance):(_.used7d=0,_.limit7d=g.totalBalance)):typeof g.usedBalance=="number"&&(_.used7d=g.usedBalance);let b=nn(typeof g.resetTime=="string"?Date.parse(g.resetTime)/1e3:void 0),k=nn(typeof g.resetTime7d=="string"?Date.parse(g.resetTime7d)/1e3:void 0);typeof g.usedDailyBalance=="number"&&!b&&(_.used5h=g.usedDailyBalance,_.type5h="rateLimit"),typeof g.limitDaily=="number"&&!b&&(_.limit5h=g.limitDaily,_.type5h="rateLimit"),typeof g.resetTime=="string"&&!b&&(g.limitDaily!==void 0?_.reset5h=g.resetTime:_.reset7d=g.resetTime),typeof g.resetTime7d=="string"&&!k&&(_.reset7d=g.resetTime7d)}return{quotas:f,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=Z(ws,"presets");if(!de(l))return{presets:[]};let d=rl(l,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),p=[];for(let f of d){let h=Z(l,f);try{let m=Z(h,"manifest.json"),y=sl(m,"utf-8"),g=JSON.parse(y),{Providers:_,Router:b,PORT:k,HOST:v,API_TIMEOUT_MS:T,PROXY_URL:x,PROXY_GLOBAL_ENABLED:w,LOG:E,LOG_LEVEL:C,StatusLine:A,NON_INTERACTIVE_MODE:F,...R}=g;p.push({id:f,name:R.name||f,version:R.version||"1.0.0",description:R.description,author:R.author,homepage:R.homepage,repository:R.repository,license:R.license,keywords:R.keywords,ccrVersion:R.ccrVersion,source:R.source,sourceType:R.sourceType,checksum:R.checksum,installed:!0})}catch(m){console.error(`Failed to read preset ${f}:`,m)}}return{presets:p}}catch(l){console.error("Failed to get presets:",l),c.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=_o(l);if(!de(u)){c.status(404).send({error:"Preset not found"});return}let d=await Rs(u);return{...al(d),config:Im(d,u),userValues:d.userValues||{}}}catch(l){console.error("Failed to get preset:",l),c.status(500).send({error:l.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(i,c)=>{try{let{name:l}=i.params,{secrets:u}=i.body,d=_o(l);if(!de(d)){c.status(404).send({error:"Preset not found"});return}let f={...await Rs(d)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await cl(l,f),{success:!0,message:"Preset applied successfully"}}catch(l){console.error("Failed to apply preset:",l),c.status(500).send({error:l.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=_o(l);if(!de(u)){c.status(404).send({error:"Preset not found"});return}return Am(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(l){console.error("Failed to delete preset:",l),c.status(500).send({error:l.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(i,c)=>{try{return{presets:await $m()}}catch(l){console.error("Failed to get market presets:",l),c.status(500).send({error:l.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(i,c)=>{try{let{presetName:l}=i.body;if(!l){c.status(400).send({error:"Preset name is required"});return}let u=await Lm(l);if(!u){c.status(400).send({error:"Preset not found in marketplace",message:`Preset '${l}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){c.status(400).send({error:"Invalid preset data",message:`Preset '${l}' does not have repository information`});return}let d=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!d){c.status(400).send({error:"Invalid GitHub repository URL"});return}let[,p,f]=d,h=u.name||l;if(await ll(h)){c.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let m=`https://github.com/${p}/${f}/archive/refs/heads/main.zip`,y=await Mm(m),g=await a(y);if(await ll(h)){il(y),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let _=_o(h);await Om(y,_);let b=await Rs(_);return b.repository=u.repo,u.url&&(b.source=u.url),await cl(h,b),il(y),{success:!0,presetName:h,preset:{...g.metadata,installed:!0}}}catch(l){console.error("Failed to install preset from GitHub:",l),c.status(500).send({error:l.message||"Failed to install preset from GitHub"})}});async function a(i){let c=new Xm(i),l=c.getEntry("manifest.json");if(l||(l=c.getEntries().find(p=>p.entryName.includes("manifest.json"))||null),!l)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(l.getData().toString("utf-8"));return al(u)}return t.get("/api/plugins",async()=>({plugins:Yc(ws,n.pluginRegistry)})),nl(t,{configDir:ws,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,c)=>{let{name:l,file:u}=i.params,d=n.pluginRegistry.getPublicCard(l,u);return d?(c.header("Content-Type","application/javascript; charset=utf-8"),c.header("X-Content-Type-Options","nosniff"),c.header("Cache-Control","no-store"),c.send(d)):c.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var gl=P(()=>{"use strict";Oe();ge();Pe();jr();ge();te();it();ae();Nt();yo();Cs();ol();Lt();Bt();fs()});import{createParser as qm}from"eventsource-parser";function Is(n){return typeof n?.finish_reason=="string"&&n.finish_reason.trim().length>0}function hl(n,e){let t=new TextDecoder,o=new Map,r=!1,s=!1,a=qm({onEvent({event:i,data:c}){if(s)return;if(c==="[DONE]"){s=!0;return}if(i==="error"){n.streamError=!0,n.rateLimited||=we(200,c);return}let l;try{l=JSON.parse(c)}catch{return}if(l?.error||l?.type==="error"){n.streamError=!0,n.rateLimited||=we(200,c);return}if(typeof l?.model=="string"&&l.model.trim()&&l.model!=="unknown"&&(n.model??=l.model),l?.usage&&(n.usage=le(n.usage,he(l.usage),!1)),!!Array.isArray(l?.choices))for(let u of l.choices){let d=u?.index??0,p=Is(u);o.get(d)||o.set(d,p);let f=u?.delta;(f?.content||f?.reasoning_content||f?.tool_calls?.length||f?.function_call)&&(n.ttft??=Math.round(performance.now()-e))}}});return new TransformStream({transform(i,c){let l=t.decode(i,{stream:!0});l&&(r=l.endsWith("\r")),a.feed(l),c.enqueue(i)},flush(){let i=t.decode();a.feed(!i&&r?`
415
- `:i),n.finished=o.size>0&&[...o.values()].every(Boolean)}})}var yl=P(()=>{"use strict";Ve();ge()});function eg(n,e){let t=n?.Router,{family:o}=_t(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function _l(n){return n?.Router?.image}function tg(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 ng(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 Ms,bo,Ls,bl,kl=P(()=>{"use strict";Oe();Ms=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},bo=new Ms;Ls=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=eg(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!tg(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&bt(e.body.model)?!1:(ng(e.body.messages),s&&!!_l(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let c=bo.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=bo.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(c=>c.type==="text"&&!c.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:_l(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
413
+ `;Kf=200});import{existsSync as Vf}from"fs";import{homedir as Yf}from"os";import{join as Xf}from"path";import{writeFile as Zf}from"fs/promises";async function Fc(){let n=Yf(),e=Xf(n,".claude.json");if(!Vf(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 Zf(e,JSON.stringify(o,null,2))}}var jc=E(()=>{"use strict"});import{existsSync as qf,readdirSync as em,statSync as tm,unlinkSync as nm}from"fs";import{join as Hc}from"path";import{HOME_DIR as om}from"@wengine-ai/claude-code-router-shared";function Bc(n=Hc(om,"logs")){try{if(!qf(n))return;let e=Date.now()-sm;for(let t of em(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=Hc(n,t),r=tm(o);r.isFile()&&r.mtime.getTime()<e&&nm(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function Jc(){zc||(zc=!0,Bc(),setInterval(Bc,im).unref())}var rm,sm,im,zc,Wc=E(()=>{"use strict";rm=7,sm=rm*24*60*60*1e3,im=1440*60*1e3,zc=!1});async function Kc(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":Pt.registerPlugin(io,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:so()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await Pt.enablePlugins(n)}var Gc=E(()=>{"use strict";ls()});function nt(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()),Ut(e,t),Wr();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=wt(()=>n.providerService.getProviders(),o,r=>me(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var _o=E(()=>{"use strict";Dt();eo();te()});import{constants as vs,lstatSync as ot,realpathSync as Kt,openSync as am,closeSync as cm,fstatSync as lm,readFileSync as Qc}from"node:fs";import{dirname as Jk,join as rt,sep as um}from"node:path";import{pathToFileURL as dm}from"node:url";function Yc(n){try{let e=JSON.parse(Qc(rt(pm(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function Cs(n,e){if(!Vc(e))return null;try{let t=Kt(n),o=rt(t,"plugins"),r=rt(o,e);return ot(o).isSymbolicLink()||!ot(o).isDirectory()||ot(r).isSymbolicLink()||!ot(r).isDirectory()||Kt(o)!==o||Kt(r)!==r||!r.startsWith(o+um)?null:r}catch{return null}}function Ts(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=Cs(n,e);if(!o)throw new Error("unsafe plugin directory");let r=rt(o,t),s=ot(r);if(s.isSymbolicLink()||!s.isFile()||Kt(r)!==r)throw new Error("unsafe plugin file");let a=am(r,vs.O_RDONLY|vs.O_NOFOLLOW|vs.O_NONBLOCK);try{let i=lm(a),c=ot(r);if(!i.isFile()||c.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==c.dev||i.ino!==c.ino||Cs(n,e)!==o||Kt(r)!==r)throw new Error("plugin file changed while opening");return Qc(a)}finally{cm(a)}}function fm(n){let e=n?.configService,t=e?zs(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Bs(t)}async function Xc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Uo(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>$t(),writeConfig:i=>fe(i),reloadRuntime:async i=>nt(n.getServer(),i??await X(),t),getDirectDispatcher:Eo,getSubscriptionDispatcher:()=>fm(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Yc(e)){let c;try{if(!Vc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let l=Cs(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let g=JSON.parse(Ts(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 d=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,l);c=d,Ts(e,i.name,"plugin.js");let p=await import(dm(rt(l,"plugin.js")).href),f=p?.activate??p?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(d.context);let h=d.cardPath?Ts(e,i.name,d.cardPath):void 0;await d.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function Zc(n,e=Uo()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Yc(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 Vc,pm,Ss=E(()=>{"use strict";$o();ct();_o();Nt();te();Vc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),pm=n=>rt(n,"plugins")});import{gt as mm,valid as qc}from"semver";import{existsSync as el,readFileSync as gm}from"node:fs";import{join as xs}from"node:path";import{NPM_SPEC_PATTERN as hm,PLUGIN_NAME_PATTERN as tl,PluginInstallError as ym,installPluginFromNpm as _m,readPluginRecords as bm}from"@wengine-ai/claude-code-router-shared";async function vm(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??km).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(nl.map(y=>vm(t,y,o))),s=new Map,a=!1;for(let y of r)if(y.status==="fulfilled"){a=!0;for(let m of y.value){let b=m?.package,_=typeof b?.name=="string"?b.name:"";if(!_||!hm.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(T=>typeof T=="string"):[]).some(T=>nl.includes(T)))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=bm(n),c=new Map(i.map(y=>[y.name,y])),l=y=>{let m=y.indexOf("@",y.startsWith("@")?1:0);return m>0?y.slice(0,m):y},u=new Map(i.filter(y=>typeof y.source=="string"&&y.source!=="").map(y=>[l(y.source),y])),d=y=>{if(!tl.test(y))return null;try{let m=JSON.parse(gm(xs(n,"plugins",y,"plugin.json"),"utf8"));return typeof m?.version=="string"?m.version:null}catch{return null}},p=[...s.values()].sort((y,m)=>y.name.localeCompare(m.name)).map(y=>{let m=c.get(y.name)??u.get(y.name),b=m!==void 0||el(xs(n,"plugins",y.name)),_=b?d(m?m.name:y.name):null;return{...y,installed:b,installedVersion:_,...b&&_!==null&&qc(_)&&qc(y.version)&&mm(y.version,_)?{updateAvailable:!0}:{}}}),f=new Set(p.map(y=>y.name)),h=new Set,g=new Map;for(let[y,m]of u)h.add(m.name),!f.has(y)&&g.set(y,m.name);for(let y of i)f.has(y.name)||h.has(y.name)||g.set(y.name,y.name);for(let[y,m]of g){if(!tl.test(m)||!el(xs(n,"plugins",m)))continue;let b=d(m);b!==null&&p.push({name:y,description:"",version:b,installed:!0,installedVersion:b,localOnly:!0})}return p.sort((y,m)=>y.name.localeCompare(m.name)),{ok:!0,plugins:p}}function Cm(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 ol(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),c=n.headers?.host;if(typeof c=="string"&&!i.has(c))return!1;let l=n.headers?.origin;if(l!==void 0&&l!==""){if(typeof l!="string")return!1;let u="";try{let d=new URL(l);if(!["http:","https:"].includes(d.protocol))return!1;u=d.host}catch{return!1}if(!i.has(u))return!1}return!0}function rl(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(!ol(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(!ol(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,c=a.force===!0;try{let l=await _m({spec:i,configDir:e.configDir,force:c,registry:e.registry,timeoutMs:e.npmTimeoutMs});return n.log?.info?.(`provider plugin installed via API: ${l.manifest.name}@${l.manifest.version} (restart to activate)`),{ok:!0,name:l.manifest.name,version:l.manifest.version,restartRequired:!0}}catch(l){if(l instanceof ym){let u=Cm(l.code);return u===502?n.log?.warn?.(`plugin install failed: ${l.code}`):n.log?.warn?.(`plugin install rejected: ${l.code}: ${l.message}`),o(s,u,l.code)}return n.log?.error?.(`plugin install crashed: ${l?.message??l}`),o(s,500,"install_failed")}})}var nl,km,sl=E(()=>{"use strict";nl=["ccr-provider-plugin","claude-code-router-plugin"],km="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Sm}from"@wengine-ai/claude-code-router-shared";import{join as Z,isAbsolute as xm,normalize as Rm,dirname as wm}from"path";import{fileURLToPath as Pm}from"url";import Em from"@fastify/static";import{readdirSync as il,statSync as Am,readFileSync as al,writeFileSync as Om,existsSync as de,unlinkSync as cl,rmSync as Im}from"fs";import{homedir as Rs}from"os";import{getPresetDir as bo,readManifestFromDir as ws,manifestToPresetFile as ll,saveManifest as ul,isPresetInstalled as dl,extractPreset as Mm,HOME_DIR as Ps,loadConfigFromManifest as Lm,downloadPresetToTemp as $m,findMarketPresetByName as Nm,getMarketPresets as Um,applyClientSelection as Dm,disableClient as Fm,enableClient as jm,isClientId as Hm,listClientStatuses as pl,restoreClient as zm,listProjectConfigs as Bm,readProjectConfigById as Es,readProjectConfig as Jm,writeProjectConfig as fl,deleteProjectConfig as Wm,getClaudeProjectId as Km,getProjectConfigPath as Gm,refreshCcrProjectTakeover as Qm,refreshPiProjectTakeover as Vm,refreshProjectTakeovers as Ym,syncGlobalProjectTakeovers as As,getProjectTakeoverClients as Os,setProjectTakeover as Is,isProjectTakeoverClient as Xm}from"@wengine-ai/claude-code-router-shared";import Zm from"@fastify/multipart";import qm from"adm-zip";function ml(n){let e=H();return fs(n,(t,o)=>e.isAvailable(t,o))}function gl(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 eg(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=Jt(t,e),s=Jt(o,e),a=[],i=new Set;for(let c of n||[])c&&c.name&&i.add(c.name);for(let c of Object.keys(r.byProvider||{}))i.add(c);for(let c of Object.keys(s.byProvider||{}))i.add(c);for(let c of i){let l=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},d=(l.inputTokens||0)+(l.outputTokens||0),p=(u.inputTokens||0)+(u.outputTokens||0),f,h,g=(n||[]).find(y=>y&&y.name===c);g&&g.quota&&(f=g.quota.limit5h,h=g.quota.limit7d),a.push({provider:c,used5h:d,used7d:p,limit5h:f,limit7d:h})}return a}async function hl(n,e){let t=n.app;dt(),mt(),t.register(Zm,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=ml(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,c)=>{let l=decodeURIComponent(i.params.modelId),u=ml(e).find(d=>d.id===l);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${l}`}})}),t.post("/v1/messages/count_tokens",async(i,c)=>{let{messages:l,tools:u,system:d,model:p}=i.body,f=t._server.tokenizerService;if(p&&p.includes(",")&&f)try{let[g,y]=p.split(",");i.log?.info(`Looking up tokenizer for provider: ${g}, model: ${y}`);let m=f.getTokenizerConfigForModel(g,y);m?i.log?.info(`Using tokenizer config: ${JSON.stringify(m)}`):i.log?.warn(`No tokenizer config found for ${g},${y}, using default tiktoken`);let b=await f.countTokens({messages:l,system:d,tools:u},m,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 p?p.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${p}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:gn(l,d,u)}}),t.get("/api/config",async(i,c)=>await $t()),t.get("/api/transformers",async(i,c)=>{let l=t._server.transformerService.getAllTransformers();return{transformers:Array.from(l.entries()).map(([d,p])=>({name:d,endpoint:p.endPoint||null}))}}),t.post("/api/config",async(i,c)=>{let l=i.body,u=Hs(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(h=>`${h.key}: ${h.error}`).join("; "),proxyErrors:u};let d=await lo();d&&console.log(`Backed up existing configuration file to ${d}`);let p=null;try{p=await X()}catch{}Sm(l,p),n.pluginRegistry.applyConfigProtectors(l,p),await fe(l);let f;try{f=await As(l),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 nt(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,c)=>{try{let l=await X();return{clients:pl(l)}}catch(l){console.error("Failed to get client integrations:",l),c.status(500).send({error:l.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(i,c)=>{try{let l=i.body,u=Array.isArray(l?.enabled)?l.enabled:[],d=await X(),p=Dm(d,u);await fe(p.config);let f=await As(p.config),h=gl(t,f,"clients/apply");return{...p,success:p.success&&h,projectTakeoverSync:f}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!Hm(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let d=await X(),p=l==="enable"?jm(d,u):l==="restore"?zm(d,u):Fm(d,u);await fe(d);let f=await As(d),h=gl(t,f,`clients/${u}/${l}`);return{success:p.success&&h,result:p,results:[p],clients:pl(d),config:d,projectTakeoverSync:f}}catch(u){console.error(`Failed to ${l} client integration:`,u),c.status(500).send({error:u.message||`Failed to ${l} client integration`})}}t.post("/api/clients/:id/enable",async(i,c)=>o(i,c,"enable")),t.post("/api/clients/:id/disable",async(i,c)=>o(i,c,"disable")),t.post("/api/clients/:id/restore",async(i,c)=>o(i,c,"restore")),t.get("/api/projects",async(i,c)=>{try{let l=await Bm();return{projects:await Promise.all(l.map(async d=>{let p=await Os(d.path);return{...d,ccrTakeoverClients:p,ccrTakeover:p.length>0}}))}}catch(l){console.error("Failed to list project configs:",l),c.status(500).send({error:l.message||"Failed to list project configs"})}}),t.post("/api/projects",async(i,c)=>{try{let{path:l}=i.body||{};if(!l||typeof l!="string"||!xm(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=Rm(l).replace(/[\\/]+$/,"")||l;if(await Jm(u)){c.status(409).send({error:"Project is already configured"});return}await fl(u,{Router:{}});try{let f=await X();await Is(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let p=await Os(u);return{id:Km(u),path:u,configPath:Gm(u),Router:{},ccrTakeoverClients:p,ccrTakeover:p.length>0}}catch(l){console.error("Failed to add project config:",l),c.status(500).send({error:l.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){c.status(400).send({error:"Router must be an object"});return}let d=await Es(l);if(!d){c.status(404).send({error:"Project config not found"});return}await fl(d.path,{Router:u});let p=await X();Object.keys(u).length===0?await Ym(d.path,p):(await Qm(d.path,p,u),await Vm(d.path,p,u));let f=await Os(d.path);return{id:l,path:d.path,configPath:d.configPath,Router:u,ccrTakeoverClients:f,ccrTakeover:f.length>0}}catch(l){console.error("Failed to update project config:",l),c.status(500).send({error:l.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(i,c)=>{try{let{id:l}=i.params,u=i.body||{},d;if(Array.isArray(u.clients))d=u.clients.filter(Xm);else if(typeof u.enabled=="boolean")d=u.enabled?["claudeCode"]:[];else{c.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let p=await Es(l);if(!p){c.status(404).send({error:"Project config not found"});return}let f=await X(),h=await Is(p.path,d,f);return{id:l,path:p.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await Es(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let d=await X();await Is(u.path,[],d)}catch(d){console.error("Failed to remove ccr takeover while deleting project:",d)}return await Wm(u.path),{success:!0}}catch(l){console.error("Failed to delete project config:",l),c.status(500).send({error:l.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:wm(Pm(import.meta.url)),s=de(Z(r,"index.html"))?r:de(Z(r,"..","index.html"))?Z(r,".."):de(Z(r,"..","dist","index.html"))?Z(r,"..","dist"):de(Z(r,"..","..","dist","index.html"))?Z(r,"..","..","dist"):Z(r,"..","dist");t.register(Em,{root:s,prefix:"/ui/",cacheControl:!1,setHeaders:(i,c)=>{i.setHeader("Cache-Control","no-cache")}}),t.get("/ui",async(i,c)=>c.redirect("/ui/")),t.get("/api/logs/files",async(i,c)=>{try{let l=Z(Rs(),".claude-code-router","logs"),u=[];if(de(l)){let d=il(l);for(let p of d)if(p.endsWith(".log")){let f=Z(l,p),h=Am(f);u.push({name:p,path:f,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((p,f)=>new Date(f.lastModified).getTime()-new Date(p.lastModified).getTime())}return u}catch(l){console.error("Failed to get log files:",l),c.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=Z(Rs(),".claude-code-router","logs","app.log"),de(u)?al(u,"utf8").split(`
414
+ `).filter(f=>f.trim()):[]}catch(l){console.error("Failed to get logs:",l),c.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=Z(Rs(),".claude-code-router","logs","app.log"),de(u)&&Om(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(l){console.error("Failed to clear logs:",l),c.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:Yt()})),t.put("/api/debug-log",async i=>{let{enabled:c}=i.body;return Mo(c),{enabled:Yt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return _s({startTime:l.startDate,endTime:l.endDate,model:l.model,provider:l.provider,scenario:l.scenario,clientType:l.clientType,sessionId:l.sessionId,status:l.status,page:l.page?parseInt(l.page,10):void 0,pageSize:l.pageSize?parseInt(l.pageSize,10):void 0})}catch(l){console.error("Failed to query usage:",l),c.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(i,c)=>{try{let l=i.query;return Jt(l.startDate,l.endDate,l.status)}catch(l){console.error("Failed to query usage summary:",l),c.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(i,c)=>{try{let l=i.query;return bs(l.beforeDate),{success:!0,message:l.beforeDate?"Usage data cleared before "+l.beforeDate:"All usage data cleared"}}catch(l){console.error("Failed to clear usage:",l),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,c)=>{try{let u=H().getAllStates(),p=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:p,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to get provider health:",l),c.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,c)=>{try{let{providerName:l}=i.body;if(!l)return c.status(400),{error:"providerName is required"};let d=t._server?.activeProbeService;if(!d?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let p=await d.probeProviderManually(l);return p.success&&po(l,i.log),{provider:l,success:p.success,latencyMs:p.latencyMs,status:p.status,isSlow:p.isSlow,errorKind:p.errorKind??null,error:p.error,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe provider:",l),c.status(500).send({error:l.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,c)=>{try{let l=t._server,u=l?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let d=(l?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),p=await Promise.all(d.map(async f=>{let h=await u.probeProviderManually(f.name);return h.success&&po(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:p,successCount:p.filter(f=>f.success).length,total:p.length,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe all providers:",l),c.status(500).send({error:l.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,c)=>{try{let u=(await X()).Providers||[],d=t._server?.pluginRegistry,p=t._server?.providerService;if(d&&p?.getProviders){let b=p.getProviders().filter(_=>_?.name&&_.enabled!==!1).map(_=>{let k=d.getManagedRuntimeFor(_);if(!(!k||typeof k.fetchQuota!="function"))return Zn(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,uc).unref?.()});await Promise.race([Promise.all(b),_])}}let f=eg(u),h=new Map(f.map(m=>[m.provider,m])),g=Yo();for(let m of f){let b=g.find(_=>_.provider===m.provider);b&&b.limit!=null&&!rn(b.reset)&&(m.limit5h=b.limit,m.used5h=b.limit-(b.remaining??0),b.reset&&(m.reset5h=new Date(b.reset*1e3).toISOString()))}let y=ar();for(let m of y){let b=h.get(m.provider);b||(b={provider:m.provider,used5h:0,used7d:0},f.push(b),h.set(m.provider,b)),typeof m.totalBalance=="number"?(b.limit7d=m.totalBalance,b.type7d=m.currency?"balance":"rateLimit",m.currency&&(b.currency=m.currency),typeof m.usedBalance=="number"?b.used7d=m.usedBalance:typeof m.remainingBalance=="number"?b.used7d=Math.max(0,m.totalBalance-m.remainingBalance):(b.used7d=0,b.limit7d=m.totalBalance)):typeof m.usedBalance=="number"&&(b.used7d=m.usedBalance);let _=rn(typeof m.resetTime=="string"?Date.parse(m.resetTime)/1e3:void 0),k=rn(typeof m.resetTime7d=="string"?Date.parse(m.resetTime7d)/1e3:void 0);typeof m.usedDailyBalance=="number"&&!_&&(b.used5h=m.usedDailyBalance,b.type5h="rateLimit"),typeof m.limitDaily=="number"&&!_&&(b.limit5h=m.limitDaily,b.type5h="rateLimit"),typeof m.resetTime=="string"&&!_&&(m.limitDaily!==void 0?b.reset5h=m.resetTime:b.reset7d=m.resetTime),typeof m.resetTime7d=="string"&&!k&&(b.reset7d=m.resetTime7d)}return{quotas:f,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=Z(Ps,"presets");if(!de(l))return{presets:[]};let d=il(l,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),p=[];for(let f of d){let h=Z(l,f);try{let g=Z(h,"manifest.json"),y=al(g,"utf-8"),m=JSON.parse(y),{Providers:b,Router:_,PORT:k,HOST:v,API_TIMEOUT_MS:T,PROXY_URL:S,PROXY_GLOBAL_ENABLED:w,LOG:P,LOG_LEVEL:R,StatusLine:A,NON_INTERACTIVE_MODE:D,...x}=m;p.push({id:f,name:x.name||f,version:x.version||"1.0.0",description:x.description,author:x.author,homepage:x.homepage,repository:x.repository,license:x.license,keywords:x.keywords,ccrVersion:x.ccrVersion,source:x.source,sourceType:x.sourceType,checksum:x.checksum,installed:!0})}catch(g){console.error(`Failed to read preset ${f}:`,g)}}return{presets:p}}catch(l){console.error("Failed to get presets:",l),c.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=bo(l);if(!de(u)){c.status(404).send({error:"Preset not found"});return}let d=await ws(u);return{...ll(d),config:Lm(d,u),userValues:d.userValues||{}}}catch(l){console.error("Failed to get preset:",l),c.status(500).send({error:l.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(i,c)=>{try{let{name:l}=i.params,{secrets:u}=i.body,d=bo(l);if(!de(d)){c.status(404).send({error:"Preset not found"});return}let f={...await ws(d)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await ul(l,f),{success:!0,message:"Preset applied successfully"}}catch(l){console.error("Failed to apply preset:",l),c.status(500).send({error:l.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=bo(l);if(!de(u)){c.status(404).send({error:"Preset not found"});return}return Im(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(l){console.error("Failed to delete preset:",l),c.status(500).send({error:l.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(i,c)=>{try{return{presets:await Um()}}catch(l){console.error("Failed to get market presets:",l),c.status(500).send({error:l.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(i,c)=>{try{let{presetName:l}=i.body;if(!l){c.status(400).send({error:"Preset name is required"});return}let u=await Nm(l);if(!u){c.status(400).send({error:"Preset not found in marketplace",message:`Preset '${l}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){c.status(400).send({error:"Invalid preset data",message:`Preset '${l}' does not have repository information`});return}let d=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!d){c.status(400).send({error:"Invalid GitHub repository URL"});return}let[,p,f]=d,h=u.name||l;if(await dl(h)){c.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let g=`https://github.com/${p}/${f}/archive/refs/heads/main.zip`,y=await $m(g),m=await a(y);if(await dl(h)){cl(y),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let b=bo(h);await Mm(y,b);let _=await ws(b);return _.repository=u.repo,u.url&&(_.source=u.url),await ul(h,_),cl(y),{success:!0,presetName:h,preset:{...m.metadata,installed:!0}}}catch(l){console.error("Failed to install preset from GitHub:",l),c.status(500).send({error:l.message||"Failed to install preset from GitHub"})}});async function a(i){let c=new qm(i),l=c.getEntry("manifest.json");if(l||(l=c.getEntries().find(p=>p.entryName.includes("manifest.json"))||null),!l)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(l.getData().toString("utf-8"));return ll(u)}return t.get("/api/plugins",async()=>({plugins:Zc(Ps,n.pluginRegistry)})),rl(t,{configDir:Ps,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,c)=>{let{name:l,file:u}=i.params,d=n.pluginRegistry.getPublicCard(l,u);return d?(c.header("Content-Type","application/javascript; charset=utf-8"),c.header("X-Content-Type-Options","nosniff"),c.header("Cache-Control","no-store"),c.send(d)):c.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var yl=E(()=>{"use strict";Oe();ge();Pe();Hr();ge();te();it();ce();Dt();_o();Ss();sl();Nt();Wt();ms()});import{createParser as tg}from"eventsource-parser";function Ms(n){return typeof n?.finish_reason=="string"&&n.finish_reason.trim().length>0}function ng(n){try{let e=JSON.parse(n);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function _l(n){let e=n?.error?.code;if(typeof e!="string")return;let t=e.trim();return/^[a-z][a-z0-9_]{0,63}$/.test(t)?t:void 0}function bl(n,e){let t=new TextDecoder,o=new Map,r=!1,s=!1,a=tg({onEvent({event:i,data:c}){if(s)return;if(c==="[DONE]"){s=!0;return}if(i==="error"){n.streamError=!0,n.streamErrorCode??=_l(ng(c)),n.rateLimited||=we(200,c);return}let l;try{l=JSON.parse(c)}catch{return}if(l?.error||l?.type==="error"){n.streamError=!0,n.streamErrorCode??=_l(l),n.rateLimited||=we(200,c);return}if(typeof l?.model=="string"&&l.model.trim()&&l.model!=="unknown"&&(n.model??=l.model),l?.usage&&(n.usage=se(n.usage,he(l.usage),!1)),!!Array.isArray(l?.choices))for(let u of l.choices){let d=u?.index??0,p=Ms(u);o.get(d)||o.set(d,p);let f=u?.delta;(f?.content||f?.reasoning_content||f?.tool_calls?.length||f?.function_call)&&(n.ttft??=Math.round(performance.now()-e))}}});return new TransformStream({transform(i,c){let l=t.decode(i,{stream:!0});l&&(r=l.endsWith("\r")),a.feed(l),c.enqueue(i)},flush(){let i=t.decode();a.feed(!i&&r?`
415
+ `:i),n.finished=o.size>0&&[...o.values()].every(Boolean)}})}var kl=E(()=>{"use strict";Ve();ge()});function og(n,e){let t=n?.Router,{family:o}=_t(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function vl(n){return n?.Router?.image}function rg(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 sg(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var Ls,ko,$s,Tl,Cl=E(()=>{"use strict";Oe();Ls=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},ko=new Ls;$s=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=og(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!rg(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&bt(e.body.model)?!1:(sg(e.body.messages),s&&!!vl(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let c=ko.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=ko.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(c=>c.type==="text"&&!c.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:vl(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
416
416
  When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
417
417
  Do not ignore or deviate from the task.
418
418
  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.
@@ -425,5 +425,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
425
425
 
426
426
  Do not attempt to describe or analyze the image directly yourself.
427
427
  Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
428
- Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")bo.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],c=a.content.filter(u=>u.type!=="image"?!0:(bo.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),l=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=c.length>0?[{type:"text",text:l},...c]:l}})})}},bl=new Ls});var $s,vl,ko,Tl=P(()=>{"use strict";kl();$s=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}},vl=new $s;vl.registerAgent(bl);ko=vl});import{EventEmitter as og}from"node:events";import{performance as Cl}from"node:perf_hooks";import rg from"json5";function To(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ee(n,e)}function Ns(n){return n.usageSessionId||n.id}function Co(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Ns(n)}`}function st(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function vo(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 xl(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(!e||typeof e!="object")return;let t=e.usage?he(e.usage):e.response?.usage?he(e.response.usage):void 0,o=e.model||e.response?.model;return{usage:t,model:o,choices:e.choices}}async function ig(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();po(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")){To(n,t);let r=Co(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function ag(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of ko.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 Rl(n){return{authClient:(e,t)=>ig(e,t,n),agent:(e,t)=>ag(e,t,n)}}function wl(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,t.method==="POST"&&o.pathname.endsWith("/v1/chat/completions")&&(t.chatCompletionCapture={}),(t.chatCompletionCapture||o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Cl.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=c=>c?a(c):s();po(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Sl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.chatCompletionCapture;if(a&&o.statusCode<400&&t.provider){if(To(t,e),r instanceof ReadableStream)return s(null,r.pipeThrough(hl(a,t.requestStartTime)));let l=xl(r);return a.finished=Array.isArray(l?.choices)&&l.choices.length>0&&l.choices.every(Is),a.usage=l?.usage,st(l?.model)&&(a.model=l.model),s(null,r)}let i=t.pathname?.endsWith("/v1/messages"),c=t.pathname?.endsWith("/v1/responses");if(i||c){To(t,e);let l=Ns(t),u=Co(t);if(r instanceof ReadableStream){if(i&&t.agents){let m=new AbortController,y=r.pipeThrough(new ue),g,_=-1,b="",k="",v="",T=[],x=[];return s(null,eo(y,async(w,E)=>{try{if(w.event==="content_block_start"&&w?.data?.content_block?.name){let C=t.agents.find(A=>ko.getAgent(A)?.tools.get(w.data.content_block.name));if(C){g=ko.getAgent(C),_=w.data.index,b=w.data.content_block.name,v=w.data.content_block.id;return}}if(_>-1&&w.data.index===_&&w.data?.delta?.type==="input_json_delta"){k+=w.data?.delta?.partial_json;return}if(_>-1&&w.data.index===_&&w.data?.type==="content_block_stop"){try{let C=rg.parse(k);x.push({type:"tool_use",id:v,name:b,input:C});let A=await g?.tools.get(b)?.handler(C,{req:t,config:e});T.push({tool_use_id:v,type:"tool_result",content:A}),g=void 0,_=-1,b="",k="",v=""}catch(C){console.log(C)}return}if(w.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:T});let C=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!C.ok)return;let F=C.body.pipeThrough(new ue).getReader();for(;;)try{let{value:R,done:O}=await F.read();if(O)break;let S=R;if(["message_start","message_stop"].includes(S.event))continue;if(!E.desiredSize)break;E.enqueue(S)}catch(R){if(R.name==="AbortError"||R.code==="ERR_STREAM_PREMATURE_CLOSE"){m.abort();break}throw R}return}return w}catch(C){if(console.error("Unexpected error in stream processing:",C),C.code==="ERR_STREAM_PREMATURE_CLOSE"){m.abort();return}throw C}}).pipeThrough(new qe))}let[p,f]=r.tee(),h=async m=>{let g=m.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();try{for(;;){let{done:_,value:b}=await g.read();if(_)break;let k=b.event,v=b.data;if(k==="message_start"&&st(v?.message?.model)&&(t.upstreamModel=v.message.model),!t.upstreamModel&&st(v?.response?.model)&&(t.upstreamModel=v.response.model),k==="response.completed"&&st(v?.response?.model)&&(t.upstreamModel=v.response.model),v?.usage){let T=Y.get(u)||{},x=he(v.usage),w=le(T,x,k==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:k,provider:t.provider,model:vo(t),usageSessionId:l,capturedUsage:x,mergedUsage:w}),(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(u,w)}if(v?.response?.usage){let T=he(v.response.usage),x=Y.get(u)||{},w=le(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:k,provider:t.provider,model:vo(t),usageSessionId:l,capturedUsage:T,mergedUsage:w}),Y.put(u,w)}}}catch(_){_.name==="AbortError"||_.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",_)}finally{g.releaseLock()}};return t.usageCapturePromise=h(f),s(null,p)}if(r instanceof ReadableStream){let[p,f]=r.tee();return t.usageCapturePromise=(async()=>{let h=f.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();try{for(;;){let{done:m,value:y}=await h.read();if(m)break;let g=y.event,_=y.data;g==="message_start"&&_?.message?.model&&st(_?.message?.model)&&(t.upstreamModel=_.message.model),g==="response.completed"&&_?.response?.model&&st(_?.response?.model)&&(t.upstreamModel=_.response.model);let b=_?.usage??_?.response?.usage;if(b){let k=he(b),v=Y.get(u)||{},T=le(v,k,g==="message_start");Y.put(u,T)}}}catch(m){m?.name!=="AbortError"&&m?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(m)})}finally{h.releaseLock()}})(),s(null,p)}let d=xl(r);if(d?.usage&&Y.put(u,d.usage),d?.model&&(t.upstreamModel=d.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(Sl.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=>{tr(t)}),n.addHook("onResponse",async(t,o)=>{(t.ccrHookOrder||=[]).push("onResponse"),tr(t);let r=t.chatCompletionCapture,s=o.statusCode>=400,a=s?r?.unbookedAttempt:void 0;if(!(r&&(!t.provider||s&&!a))&&!(!r&&!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let i=async F=>{if(!F)return;let R;try{await Promise.race([F,new Promise(O=>{R=setTimeout(O,sg)})])}finally{R&&clearTimeout(R)}};await i(t.usageCapturePromise),await i(t.tokenSpeedCapturePromise),a&&To(t,e);let c=Ns(t),l=c,u=t.sessionId||c,d=r?r.usage:s?void 0:Y.get(Co(t)),p=r?{ttft:r.ttft??null,tokensPerSecond:null}:bs(l),f=H(),h=a?.provider||t.provider||"",m=a?.model||vo(t),y,g,_=r?void 0:t.sseError,b=_&&(_.type||_.code||_.message),k=d?.output_tokens&&d.output_tokens>0,v=t.contentDelivered===!0,T;r&&(r.streamError?T="Chat stream returned an error":s?T=`Chat upstream request failed (HTTP ${o.statusCode})`:r.finished||(T="Chat completion ended without a finish_reason"));let x=!!T||s||b&&!k&&!v;x?(y=T||t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,b&&(y=y||JSON.stringify(_),g=JSON.stringify(_)),r||(g=g||t.errorResponseBody),(!a||r?.streamError)&&(r?.rateLimited||we(o.statusCode,y)?f.markRateLimited(h,m,120,y):f.recordFailure(h,m,y))):f.recordSuccess(h,m);let w=d?.cache_read_input_tokens??0,C=d?.input_tokens||0||(r?0:t.tokenCount)||0;!r&&!d?.usage_estimated&&!w&&t.tokenCount&&d?.input_tokens&&d.input_tokens<t.tokenCount&&(w=t.tokenCount-d.input_tokens,w&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:d.input_tokens,impliedCache:w}));let A=x?0:d?.output_tokens||0;!x&&t.body?.stream&&C===0&&A===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:vo(t),usageSessionId:u,tokenCount:t.tokenCount,cachedUsage:d,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),Ht({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:u,provider:h,originalModel:t.originalModel||t.body?.model||"",model:m,upstreamModel:r?.model||t.upstreamModel||m||void 0,...d?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Be(t),stream:t.body?.stream??!1,inputTokens:C,outputTokens:A,cacheReadInputTokens:w,cacheCreationInputTokens:d?.cache_creation_input_tokens||0,ttft:x||!t.body?.stream?null:p.ttft,tokensPerSecond:x?null:p.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Cl.now()-t.requestStartTime):0,status:x?"error":"success",errorMessage:y,responseBody:g}),!r&&t.clientContext?.usageScope!=="session"&&Y.delete(Co(t))}catch(i){console.error("Usage tracking error:",i)}})}var sg,Sl,Pl=P(()=>{"use strict";Je();cn();sn();ae();Kr();Gr();Qr();Bt();Ve();ge();yl();Tl();ms();gn();sg=1500,Sl=new og});var Al={};Ro(Al,{createCcrServer:()=>mg});import{homedir as cg}from"os";import{join as lg}from"path";import{createStream as ug}from"rotating-file-stream";import{CONFIG_FILE as dg,HOME_DIR as El,listPresets as pg,ensureCcrSelfProvider as fg}from"@wengine-ai/claude-code-router-shared";async function mg(n={}){await Uc(),await ao();let e=await us();fg(e).changed&&(await fe(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;bc();let c=f=>(f>9?"":"0")+f,l=(f,h)=>{let m;f?typeof f=="number"?m=new Date(f):m=f:m=new Date;let y=m.getFullYear()+""+c(m.getMonth()+1),g=c(m.getDate()),_=c(m.getHours()),b=c(m.getMinutes());return`./logs/ccr-${y}${g}${_}${b}${c(m.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(zc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:ug(l,{path:El,interval:"1d",size:"50M",compress:!1})}):u=!1);let d=await pg(),p=new Il({jsonPath:dg,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:lg(cg(),".claude-code-router","claude-code-router.log")},logger:u});try{await p.ready();let f=await Vc({configDir:El,registry:p.pluginRegistry,getServer:()=>p,log:{info:g=>p.app?.log?.info?.(g),warn:g=>p.app?.log?.warn?.(g),error:g=>p.app?.log?.error?.(g)}});f.failed.length&&p.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(g=>`${g.name} (${g.error})`).join("; ")}`),p.pluginRegistry.listLoadedPlugins().length&&p.app?.log?.info?.(`provider plugins active: ${p.pluginRegistry.listLoadedPlugins().map(g=>`${g.name}@${g.version}`).join(", ")}`),f.loaded.length&&nt(p,e,p.app.log),await ml(p,e),p.recordUsage=g=>{try{let _=g.req?g.req.clientType||Be(g.req):"unknown";Ht({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:g.sessionId||"",provider:g.provider||"",originalModel:g.originalModel||"",model:g.model||"",modelFamily:g.modelFamily||"",scenarioType:g.scenarioType||"default",clientType:_,stream:g.stream??!1,inputTokens:g.inputTokens||0,outputTokens:0,cacheReadInputTokens:g.cacheReadInputTokens||0,cacheCreationInputTokens:g.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:g.errorMessage,responseBody:void 0})}catch(_){console.error("Fallback usage tracking error:",_)}},wl(p,e),p.ccrPreHandlerCallbacks=Rl(e),(await Promise.allSettled(d.map(async g=>await p.registerNamespace(`/preset/${g.name}`,g.config)))).forEach((g,_)=>{if(g.status==="rejected"){let b=d[_],k=g.reason instanceof Error?g.reason.message:String(g.reason);p.app?.log?.error?.(`Failed to register preset "${b?.name}": ${k}`)}}),await Jc(p,e),$t(e,p.app?.log);let m=g=>{p.app.log.error({err:g},"Uncaught exception")},y=(g,_)=>{p.app.log.error({reason:g,promise:_},"Unhandled rejection")};return process.on("uncaughtException",m),process.on("unhandledRejection",y),p.app.addHook("onClose",async()=>{process.off("uncaughtException",m),process.off("unhandledRejection",y)}),p}catch(f){throw p.pluginRegistry.dispose(),await p.app.close().catch(()=>{}),f}}var Ol=P(()=>{"use strict";Ml();Dc();Lt();Bc();ns();Wc();gl();Cs();yo();Pl();Nt();Bt();Je()});import gg from"fastify";import hg from"@fastify/cors";function yg(n={}){let e=gg({bodyLimit:52428800,...n});return e.setErrorHandler(Ks),e.register(hg),e}async function _g(n={}){return(await Promise.resolve().then(()=>(Ol(),Al))).createCcrServer(n)}var Us,Il,dC,Ml=P(()=>{Ao();Gt();gn();fr();Tr();Sr();Oe();cn();qn();ae();ge();Pe();te();Je();gn();ct();je();Je();Oe();Ao();fr();Tr();Sr();cs();Vr();ae();ge();Fr();Pe();ae();qn();it();te();Lt();Ve();Nt();fs();ms();Bt();Us=class{app;pluginRegistry=new at;namespaceProviders=[];reloadProviders(e){let t=e?.Providers??e?.providers??[];this.configService.set("providers",t),this.providerService.reload();for(let o of this.namespaceProviders)o.providers.reload()}reloadNamespaceProviders(e,t){let o=this.namespaceProviders.find(r=>r.name===e);if(!o)throw new Error(`unknown namespace ${e}`);o.config.set("providers",t),o.providers.reload()}configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:i,...c}=e;this.app=yg({...c,logger:c.logger??!0}),this.app._server=this,this.app.addHook("onClose",async()=>{this.pluginRegistry.dispose(),this.tokenizerService?.dispose()});let l={initialConfig:t};o!==void 0&&(l.jsonPath=o),r!==void 0&&(l.envPath=r),s!==void 0&&(l.useEnvFile=s),a!==void 0&&(l.useJsonFile=a),i!==void 0&&(l.useEnvironmentVariables=i),this.configService=new Me(l),this.transformerService=new Xe(this.configService,this.app.log),this.tokenizerService=new Ze(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 Xe(o,this.app.log),a=new Ze(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 c=>{c.decorate("pluginRegistry",this.pluginRegistry),c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,u)=>{let d=new URL(`http://127.0.0.1${l.url}`);l.pathname=d.pathname;let p=d.pathname.endsWith("/v1/messages"),f=d.pathname.endsWith("/v1/responses");if(!p&&!f||!l.body||typeof l.body!="object")return;let h=l.ccrHookOrder||=[];if(h.push("request-normalize"),f&&l.body.input&&!l.body.messages&&kt(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),h.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),Ee(l,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){h.push("router"),l.body?.model&&await mn(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&Y.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let m=l.body;if(!m||!m.model)return u.code(400).send({error:"Missing model in request body"});let y=m.model.split(","),g=m.model;if(y.length>1){let[_,...b]=y;g=b.join(","),m.model=g,l.provider=_}l.model=g}catch(m){return l.log.error({error:m},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await ca(c)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{Br()}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 Eo()})}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{dt()}catch{}try{mt()}catch{}try{Wo()}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=xt(()=>this.providerService.getProviders(),t,o=>me(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)}}},Il=Us;dC=_g});Ml();export{Zn as ActiveProbeService,Me as ConfigService,oe as ProjectRoutingError,tn as ProviderHealthStore,Ge as ProviderService,ue as SSEParserTransform,qe as SSESerializerTransform,Ze as TokenizerService,Xe as TransformerService,po as apiKeyAuth,Ee as applyClientAdapter,co as backupConfigFile,Di as builtinClientAdapterRegistry,fn as calculateTokenCount,_d as clearClientAdapterCaches,uo as clearProviderHealth,Eo as closeProxyDispatchers,Rc as collectReachableModelKeys,_g as createCcrServer,Il as default,Be as detectClientType,Qi as diagnoseResolutionFailure,be as extractSessionIdFromUserId,uc as getActiveProbeService,ir as getAllQuotaResults,Vo as getAllRateLimitInfo,ji as getClientAdapter,Kt as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Ur as getQuotaAdapter,ln as getQuotaResult,Su as getRateLimitInfo,Qt as getRuntimeDebugLog,dC as getServer,us as initConfig,ao as initDir,Wo as initProviderHealthPersistence,mt as initQuotaStorePersistence,dt as initRateLimitPersistence,Fi as isClientType,Bs as isGlobalProxyEnabled,ps as listAnthropicCompatibleModels,le as mergeUsageCapture,_e as normalizeSessionId,he as normalizeUsagePayload,Rt as pluginManager,X as readConfigFile,Mt as readConfigFileRaw,$t as reconcileHealthStore,Jr as resetActiveProbeService,me as resolveProviderProxyUrl,eo as rewriteStream,mn as router,Xi as searchProjectBySession,Y as sessionUsageCache,Io as setRuntimeDebugLog,xt as startActiveProbe,Br as stopActiveProbe,ft as storeQuotaResult,so as tokenSpeedPlugin,Nc as usageStore,fe as writeConfigFile};
428
+ 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")ko.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],c=a.content.filter(u=>u.type!=="image"?!0:(ko.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),l=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=c.length>0?[{type:"text",text:l},...c]:l}})})}},Tl=new $s});var Ns,Sl,vo,xl=E(()=>{"use strict";Cl();Ns=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 Ns;Sl.registerAgent(Tl);vo=Sl});import{EventEmitter as ig}from"node:events";import{performance as Rl}from"node:perf_hooks";import ag from"json5";function Co(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ee(n,e)}function Us(n){return n.usageSessionId||n.id}function So(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Us(n)}`}function st(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function To(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 Pl(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(!e||typeof e!="object")return;let t=e.usage?he(e.usage):e.response?.usage?he(e.response.usage):void 0,o=e.model||e.response?.model;return{usage:t,model:o,choices:e.choices}}async function lg(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();fo(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")){Co(n,t);let r=So(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function ug(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of vo.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 El(n){return{authClient:(e,t)=>lg(e,t,n),agent:(e,t)=>ug(e,t,n)}}function Al(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,t.method==="POST"&&o.pathname.endsWith("/v1/chat/completions")&&(t.chatCompletionCapture={}),(t.chatCompletionCapture||o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Rl.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=c=>c?a(c):s();fo(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",wl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.chatCompletionCapture;if(a&&o.statusCode<400&&t.provider){if(Co(t,e),r instanceof ReadableStream)return s(null,r.pipeThrough(bl(a,t.requestStartTime)));let u=Pl(r);return a.finished=Array.isArray(u?.choices)&&u.choices.length>0&&u.choices.every(Ms),a.usage=u?.usage,st(u?.model)&&(a.model=u.model),s(null,r)}let i=t.pathname?.endsWith("/v1/messages"),c=t.pathname?.endsWith("/v1/responses"),l=!!t.chatCompletionCapture;if(i||c||l){Co(t,e);let u=Us(t),d=So(t);if(r instanceof ReadableStream){if(i&&t.agents){let y=new AbortController,m=r.pipeThrough(new ue),b,_=-1,k="",v="",T="",S=[],w=[];return s(null,to(m,async(P,R)=>{try{if(P.event==="content_block_start"&&P?.data?.content_block?.name){let A=t.agents.find(D=>vo.getAgent(D)?.tools.get(P.data.content_block.name));if(A){b=vo.getAgent(A),_=P.data.index,k=P.data.content_block.name,T=P.data.content_block.id;return}}if(_>-1&&P.data.index===_&&P.data?.delta?.type==="input_json_delta"){v+=P.data?.delta?.partial_json;return}if(_>-1&&P.data.index===_&&P.data?.type==="content_block_stop"){try{let A=ag.parse(v);w.push({type:"tool_use",id:T,name:k,input:A});let D=await b?.tools.get(k)?.handler(A,{req:t,config:e});S.push({tool_use_id:T,type:"tool_result",content:D}),b=void 0,_=-1,k="",v="",T=""}catch(A){console.log(A)}return}if(P.event==="message_delta"&&S.length){t.body.messages.push({role:"assistant",content:w}),t.body.messages.push({role:"user",content:S});let A=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(!A.ok)return;let x=A.body.pipeThrough(new ue).getReader();for(;;)try{let{value:O,done:C}=await x.read();if(C)break;let I=O;if(["message_start","message_stop"].includes(I.event))continue;if(!R.desiredSize)break;R.enqueue(I)}catch(O){if(O.name==="AbortError"||O.code==="ERR_STREAM_PREMATURE_CLOSE"){y.abort();break}throw O}return}return P}catch(A){if(console.error("Unexpected error in stream processing:",A),A.code==="ERR_STREAM_PREMATURE_CLOSE"){y.abort();return}throw A}}).pipeThrough(new qe))}let[f,h]=r.tee(),g=async y=>{let b=y.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();try{for(;;){let{done:_,value:k}=await b.read();if(_)break;let v=k.event,T=k.data;if(v==="message_start"&&st(T?.message?.model)&&(t.upstreamModel=T.message.model),!t.upstreamModel&&st(T?.response?.model)&&(t.upstreamModel=T.response.model),v==="response.completed"&&st(T?.response?.model)&&(t.upstreamModel=T.response.model),T?.usage){let S=Y.get(d)||{},w=he(T.usage),P=se(S,w,v==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:v,provider:t.provider,model:To(t),usageSessionId:u,capturedUsage:w,mergedUsage:P}),(w?.cache_read_input_tokens||w?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:w?.cache_read_input_tokens,cache_creation:w?.cache_creation_input_tokens}),Y.put(d,P)}if(T?.response?.usage){let S=he(T.response.usage),w=Y.get(d)||{},P=se(w,S,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:v,provider:t.provider,model:To(t),usageSessionId:u,capturedUsage:S,mergedUsage:P}),Y.put(d,P)}}}catch(_){_.name==="AbortError"||_.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",_)}finally{b.releaseLock()}};return t.usageCapturePromise=g(h),s(null,f)}if(r instanceof ReadableStream){let[f,h]=r.tee();return t.usageCapturePromise=(async()=>{let g=h.pipeThrough(new TextDecoderStream).pipeThrough(new ue).getReader();try{for(;;){let{done:y,value:m}=await g.read();if(y)break;let b=m.event,_=m.data;b==="message_start"&&_?.message?.model&&st(_?.message?.model)&&(t.upstreamModel=_.message.model),b==="response.completed"&&_?.response?.model&&st(_?.response?.model)&&(t.upstreamModel=_.response.model);let k=_?.usage??_?.response?.usage;if(k){let v=he(k),T=Y.get(d)||{},S=se(T,v,b==="message_start");Y.put(d,S)}}}catch(y){y?.name!=="AbortError"&&y?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(y)})}finally{g.releaseLock()}})(),s(null,f)}let p=Pl(r);if(p?.usage&&(l?t.chatCompletionCapture.usage=se(t.chatCompletionCapture.usage,p.usage,!1):Y.put(d,p.usage)),p?.model&&(t.upstreamModel=p.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(wl.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")||t.chatCompletionCapture))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{nr(t)}),n.addHook("onResponse",async(t,o)=>{(t.ccrHookOrder||=[]).push("onResponse"),nr(t);let r=t.chatCompletionCapture,s=o.statusCode>=400,a=s?r?.unbookedAttempt:void 0;if(!(r&&(!t.provider||s&&!a))&&!(!r&&!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let i=async x=>{if(!x)return;let O;try{await Promise.race([x,new Promise(C=>{O=setTimeout(C,cg)})])}finally{O&&clearTimeout(O)}};await i(t.usageCapturePromise),await i(t.tokenSpeedCapturePromise),a&&Co(t,e);let c=Us(t),l=c,u=t.sessionId||c,d=o.statusCode>=400,p=r?r.usage:d?void 0:Y.get(So(t)),f=r?{ttft:r.ttft??null,tokensPerSecond:null}:ks(l),h=H(),g=a?.provider||t.provider||"",y=a?.model||To(t),m,b,_=r?void 0:t.sseError,k=_&&(_.type||_.code||_.message),v=p?.output_tokens&&p.output_tokens>0,T=t.contentDelivered===!0,S;r&&(r.streamError?S=r.streamErrorCode?`Chat stream returned an error (${r.streamErrorCode})`:"Chat stream returned an error":d?S=`Chat upstream request failed (HTTP ${o.statusCode})`:r.finished||(S="Chat completion ended without a finish_reason"));let w=!!S||d||k&&!v&&!T;w?(m=S||t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,k&&(m=m||JSON.stringify(_),b=JSON.stringify(_)),r||(b=b||t.errorResponseBody),(!a||r?.streamError)&&(r?.rateLimited||we(o.statusCode,m)?h.markRateLimited(g,y,120,m):h.recordFailure(g,y,m))):h.recordSuccess(g,y);let P=p?.cache_read_input_tokens??0,A=p?.input_tokens||0||(r?0:t.tokenCount)||0;!r&&!p?.usage_estimated&&!P&&t.tokenCount&&p?.input_tokens&&p.input_tokens<t.tokenCount&&(P=t.tokenCount-p.input_tokens,P&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:p.input_tokens,impliedCache:P}));let D=w?0:p?.output_tokens||0;!w&&t.body?.stream&&A===0&&D===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:To(t),usageSessionId:u,tokenCount:t.tokenCount,cachedUsage:p,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),Bt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:u,provider:g,originalModel:t.originalModel||t.body?.model||"",model:y,upstreamModel:r?.model||t.upstreamModel||y||void 0,...p?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Be(t),stream:t.body?.stream??!1,inputTokens:A,outputTokens:D,cacheReadInputTokens:P,cacheCreationInputTokens:p?.cache_creation_input_tokens||0,ttft:w||!t.body?.stream?null:f.ttft,tokensPerSecond:w?null:f.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Rl.now()-t.requestStartTime):0,status:w?"error":"success",errorMessage:m,responseBody:b}),!r&&t.clientContext?.usageScope!=="session"&&Y.delete(So(t))}catch(i){console.error("Usage tracking error:",i)}})}var cg,wl,Ol=E(()=>{"use strict";Je();un();cn();ce();Gr();Qr();Vr();Wt();Ve();ge();kl();xl();gs();yn();cg=1500,wl=new ig});var Ml={};wo(Ml,{createCcrServer:()=>yg});import{homedir as dg}from"os";import{join as pg}from"path";import{createStream as fg}from"rotating-file-stream";import{CONFIG_FILE as mg,HOME_DIR as Il,listPresets as gg,ensureCcrSelfProvider as hg}from"@wengine-ai/claude-code-router-shared";async function yg(n={}){await Fc(),await co();let e=await ds();hg(e).changed&&(await fe(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;vc();let c=f=>(f>9?"":"0")+f,l=(f,h)=>{let g;f?typeof f=="number"?g=new Date(f):g=f:g=new Date;let y=g.getFullYear()+""+c(g.getMonth()+1),m=c(g.getDate()),b=c(g.getHours()),_=c(g.getMinutes());return`./logs/ccr-${y}${m}${b}${_}${c(g.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(Jc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:fg(l,{path:Il,interval:"1d",size:"50M",compress:!1})}):u=!1);let d=await gg(),p=new $l({jsonPath:mg,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:pg(dg(),".claude-code-router","claude-code-router.log")},logger:u});try{await p.ready();let f=await Xc({configDir:Il,registry:p.pluginRegistry,getServer:()=>p,log:{info:m=>p.app?.log?.info?.(m),warn:m=>p.app?.log?.warn?.(m),error:m=>p.app?.log?.error?.(m)}});f.failed.length&&p.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(m=>`${m.name} (${m.error})`).join("; ")}`),p.pluginRegistry.listLoadedPlugins().length&&p.app?.log?.info?.(`provider plugins active: ${p.pluginRegistry.listLoadedPlugins().map(m=>`${m.name}@${m.version}`).join(", ")}`),f.loaded.length&&nt(p,e,p.app.log),await hl(p,e),p.recordUsage=m=>{try{let b=m.req?m.req.clientType||Be(m.req):"unknown";Bt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:m.sessionId||"",provider:m.provider||"",originalModel:m.originalModel||"",model:m.model||"",modelFamily:m.modelFamily||"",scenarioType:m.scenarioType||"default",clientType:b,stream:m.stream??!1,inputTokens:m.inputTokens||0,outputTokens:0,cacheReadInputTokens:m.cacheReadInputTokens||0,cacheCreationInputTokens:m.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:m.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},Al(p,e),p.ccrPreHandlerCallbacks=El(e),(await Promise.allSettled(d.map(async m=>await p.registerNamespace(`/preset/${m.name}`,m.config)))).forEach((m,b)=>{if(m.status==="rejected"){let _=d[b],k=m.reason instanceof Error?m.reason.message:String(m.reason);p.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await Kc(p,e),Ut(e,p.app?.log);let g=m=>{p.app.log.error({err:m},"Uncaught exception")},y=(m,b)=>{p.app.log.error({reason:m,promise:b},"Unhandled rejection")};return process.on("uncaughtException",g),process.on("unhandledRejection",y),p.app.addHook("onClose",async()=>{process.off("uncaughtException",g),process.off("unhandledRejection",y)}),p}catch(f){throw p.pluginRegistry.dispose(),await p.app.close().catch(()=>{}),f}}var Ll=E(()=>{"use strict";Nl();jc();Nt();Wc();os();Gc();yl();Ss();_o();Ol();Dt();Wt();Je()});import _g from"fastify";import bg from"@fastify/cors";function kg(n={}){let e=_g({bodyLimit:52428800,...n});return e.setErrorHandler(Gs),e.register(bg),e}async function vg(n={}){return(await Promise.resolve().then(()=>(Ll(),Ml))).createCcrServer(n)}var Ds,$l,mC,Nl=E(()=>{Oo();Vt();yn();mr();Cr();xr();Oe();un();eo();ce();ge();Pe();te();Je();yn();ct();je();Je();Oe();Oo();mr();Cr();xr();ls();Yr();ce();ge();jr();Pe();ce();eo();it();te();Nt();Ve();Dt();ms();gs();Wt();Ds=class{app;pluginRegistry=new at;namespaceProviders=[];reloadProviders(e){let t=e?.Providers??e?.providers??[];this.configService.set("providers",t),this.providerService.reload();for(let o of this.namespaceProviders)o.providers.reload()}reloadNamespaceProviders(e,t){let o=this.namespaceProviders.find(r=>r.name===e);if(!o)throw new Error(`unknown namespace ${e}`);o.config.set("providers",t),o.providers.reload()}configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:i,...c}=e;this.app=kg({...c,logger:c.logger??!0}),this.app._server=this,this.app.addHook("onClose",async()=>{this.pluginRegistry.dispose(),this.tokenizerService?.dispose()});let l={initialConfig:t};o!==void 0&&(l.jsonPath=o),r!==void 0&&(l.envPath=r),s!==void 0&&(l.useEnvFile=s),a!==void 0&&(l.useJsonFile=a),i!==void 0&&(l.useEnvironmentVariables=i),this.configService=new Me(l),this.transformerService=new Xe(this.configService,this.app.log),this.tokenizerService=new Ze(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 Xe(o,this.app.log),a=new Ze(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 c=>{c.decorate("pluginRegistry",this.pluginRegistry),c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,u)=>{let d=new URL(`http://127.0.0.1${l.url}`);l.pathname=d.pathname;let p=d.pathname.endsWith("/v1/messages"),f=d.pathname.endsWith("/v1/responses");if(!p&&!f||!l.body||typeof l.body!="object")return;let h=l.ccrHookOrder||=[];if(h.push("request-normalize"),f&&l.body.input&&!l.body.messages&&kt(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),h.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),Ee(l,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){h.push("router"),l.body?.model&&await hn(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&Y.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let g=l.body;if(!g||!g.model)return u.code(400).send({error:"Missing model in request body"});let y=g.model.split(","),m=g.model;if(y.length>1){let[b,..._]=y;m=_.join(","),g.model=m,l.provider=b}l.model=m}catch(g){return l.log.error({error:g},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await la(c)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{Jr()}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 Ao()})}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{dt()}catch{}try{mt()}catch{}try{Ko()}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=wt(()=>this.providerService.getProviders(),t,o=>me(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)}}},$l=Ds;mC=vg});Nl();export{qn as ActiveProbeService,Me as ConfigService,oe as ProjectRoutingError,on as ProviderHealthStore,Ge as ProviderService,ue as SSEParserTransform,qe as SSESerializerTransform,Ze as TokenizerService,Xe as TransformerService,fo as apiKeyAuth,Ee as applyClientAdapter,lo as backupConfigFile,Fi as builtinClientAdapterRegistry,gn as calculateTokenCount,vd as clearClientAdapterCaches,po as clearProviderHealth,Ao as closeProxyDispatchers,Pc as collectReachableModelKeys,vg as createCcrServer,$l as default,Be as detectClientType,Vi as diagnoseResolutionFailure,be as extractSessionIdFromUserId,pc as getActiveProbeService,ar as getAllQuotaResults,Yo as getAllRateLimitInfo,Hi as getClientAdapter,Qt as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Dr as getQuotaAdapter,dn as getQuotaResult,wu as getRateLimitInfo,Yt as getRuntimeDebugLog,mC as getServer,ds as initConfig,co as initDir,Ko as initProviderHealthPersistence,mt as initQuotaStorePersistence,dt as initRateLimitPersistence,ji as isClientType,Js as isGlobalProxyEnabled,fs as listAnthropicCompatibleModels,se as mergeUsageCapture,_e as normalizeSessionId,he as normalizeUsagePayload,Pt as pluginManager,X as readConfigFile,$t as readConfigFileRaw,Ut as reconcileHealthStore,Wr as resetActiveProbeService,me as resolveProviderProxyUrl,to as rewriteStream,hn as router,Zi as searchProjectBySession,Y as sessionUsageCache,Mo as setRuntimeDebugLog,wt as startActiveProbe,Jr as stopActiveProbe,ft as storeQuotaResult,io as tokenSpeedPlugin,Dc as usageStore,fe as writeConfigFile};
429
429
  //# sourceMappingURL=server.mjs.map