@wengine-ai/llms 2.3.2429 → 2.3.2430

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,57 +1,57 @@
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 bo=Object.defineProperty;var dl=Object.getOwnPropertyDescriptor;var pl=Object.getOwnPropertyNames;var fl=Object.prototype.hasOwnProperty;var ko=(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 To=(n,e)=>{for(var t in e)bo(n,t,{get:e[t],enumerable:!0})},ml=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pl(e))!fl.call(n,r)&&r!==t&&bo(n,r,{get:()=>e[r],enumerable:!(o=dl(e,r))||o.enumerable});return n};var gl=n=>ml(bo({},"__esModule",{value:!0}),n);import{Agent as hl,ProxyAgent as yl}from"undici";function bl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(_l.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 Ps(n){let e=[];for(let t of[...Rs,ws]){let o=n[t];if(o==null)continue;let r=bl(o);r.ok||e.push({key:t,error:r.error})}return e}function xo(){return vo||(vo=new hl({connect:{timeout:15e3}})),vo}function Es(n){let e=n.get(ws);return(typeof e=="string"?e.trim():"")||void 0}function As(n){return n?G(n):xo()}function Ht(n){for(let e of Rs){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Os(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=Ht(n);if(t)return Os(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=kl(n),t=jt.get(e);if(t)return t;let o=new yl(e);return jt.set(e,o),o}async function So(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function kl(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 Rs,ws,_l,jt,vo,q=P(()=>{"use strict";Rs=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],ws="SUBSCRIPTION_PROXY_URL",_l=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as Tl,existsSync as Is}from"fs";import{join as Ms}from"path";import{config as vl}from"dotenv";import xl from"json5";var Me,Co=P(()=>{"use strict";q();Me=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Ms(process.cwd(),this.options.jsonPath);if(Is(e))try{let t=Tl(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:Ms(process.cwd(),this.options.envPath);if(Is(e))try{let t=vl({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return Ht(this)}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}}});function K(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Ls(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var zt=P(()=>{"use strict"});function wo(n){Ro=n}function Bt(){return Ro}function Jt(n){return Ro||n.get("DEBUG_LOG")===!0}function Us(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();Sl.has(r)||Cl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Kt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Ds(n,e,t){let o=typeof t.body=="string"?t.body:JSON.stringify(t.body);n.info({debug_log:!0,reqId:e,phase:"provider_request",url:t.url,headers:Wt(t.headers),body:Kt(o,Le.maxBodyLength)})}function Fs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Wt(t.headers),...t.body!==void 0?{body:Kt(t.body,Le.maxBodyLength)}:{}})}function $s(n,e,t,o){let r=Rl(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Le.maxBodyLength)})}function Rl(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Kt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Ns(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function js(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 ko=Object.defineProperty;var ml=Object.getOwnPropertyDescriptor;var gl=Object.getOwnPropertyNames;var hl=Object.prototype.hasOwnProperty;var To=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var vo=(n,e)=>{for(var t in e)ko(n,t,{get:e[t],enumerable:!0})},yl=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gl(e))!hl.call(n,r)&&r!==t&&ko(n,r,{get:()=>e[r],enumerable:!(o=ml(e,r))||o.enumerable});return n};var _l=n=>yl(ko({},"__esModule",{value:!0}),n);import{Agent as bl,ProxyAgent as kl}from"undici";function vl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Tl.test(e))return{ok:!0};try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:`Unsupported proxy protocol: ${t.protocol}. Only http:// and https:// are allowed.`}:{ok:!0}}catch{return{ok:!1,error:`Invalid proxy URL: ${e}`}}}function Os(n){let e=[];for(let t of[...Es,As]){let o=n[t];if(o==null)continue;let r=vl(o);r.ok||e.push({key:t,error:r.error})}return e}function So(){return xo||(xo=new bl({connect:{timeout:15e3}})),xo}function Is(n){let e=n.get(As);return(typeof e=="string"?e.trim():"")||void 0}function Ms(n){return n?G(n):So()}function Ht(n){for(let e of Es){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Ls(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=Ht(n);if(t)return Ls(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=xl(n),t=jt.get(e);if(t)return t;let o=new kl(e);return jt.set(e,o),o}async function Co(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function xl(n){let e=n.trim();if(!e)throw new TypeError("Proxy URL must not be empty");let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new TypeError(`Unsupported proxy protocol: ${t.protocol}`);return t.toString()}var Es,As,Tl,jt,xo,q=w(()=>{"use strict";Es=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],As="SUBSCRIPTION_PROXY_URL",Tl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as Sl,existsSync as $s}from"fs";import{join as Ns}from"path";import{config as Cl}from"dotenv";import Rl from"json5";var Me,Ro=w(()=>{"use strict";q();Me=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Ns(process.cwd(),this.options.jsonPath);if($s(e))try{let t=Sl(e,"utf-8"),o=Rl.parse(t);this.config={...this.config,...o},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Ns(process.cwd(),this.options.envPath);if($s(e))try{let t=Cl({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return Ht(this)}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}}});function K(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Us(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var zt=w(()=>{"use strict"});function Po(n){wo=n}function Bt(){return wo}function Jt(n){return wo||n.get("DEBUG_LOG")===!0}function js(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();wl.has(r)||Pl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Kt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Hs(n,e,t){let o=typeof t.body=="string"?t.body:JSON.stringify(t.body);n.info({debug_log:!0,reqId:e,phase:"provider_request",url:t.url,headers:Wt(t.headers),body:Kt(o,Le.maxBodyLength)})}function zs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Wt(t.headers),...t.body!==void 0?{body:Kt(t.body,Le.maxBodyLength)}:{}})}function Ds(n,e,t,o){let r=El(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Le.maxBodyLength)})}function El(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Kt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Fs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Bs(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:l}=await r.read();if(i)break;a+=l;let c=a.split(`
3
3
 
4
- `);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?$s(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&&$s(e,t,s,a.trim()),s++),Ns(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Ns(e,t,s)}finally{r.releaseLock()}})()}var Sl,Cl,Le,Ro,rt=P(()=>{"use strict";Sl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Cl=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},Ro=!1});function Hs(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:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:wl(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function wl(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 zs=P(()=>{q();rt()});function El(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Bs(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Po(n){if(Bs(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(Pl.some(s=>r.includes(s))){e=!0;break}Al.some(s=>r.includes(s))&&(t=!0)}}return e||El(n)?"content":t?"empty":"pending"}async function Js(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=c-Date.now(),p=Symbol("timeout"),d,f=o.read(),g=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),g===p)return l(Po(a)==="content"?"content":"pending",Gt(o,f));if(g.done){a+=r.decode();let m=Po(a);return l(m==="empty"?"empty":"pending",null)}if(!g.value)continue;s.push(g.value),i+=g.value.byteLength,a+=r.decode(g.value,{stream:!0});let h=Po(a);if(h==="content")return l("content",Gt(o));if(h==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(Bs(a)||i>=e)return l("pending",Gt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Gt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Ws(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 Pl,Al,Ks=P(()=>{"use strict";Pl=["content_block_start","content_block_delta","content_block_stop"];Al=["message_stop","response.completed","response.incomplete","[DONE]"]});function Ol(n,e){return`${n.name}|${e?.name??""}`}function Eo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function $e(n,e,t){let o=Eo(n),r=Ol(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Ao(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:($e(n,e,o).terminalError=t,!0)}var Gs=P(()=>{"use strict"});var Oo=P(()=>{"use strict"});import Il from"fastify";function Qs(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var st,Ml,Mo,Qt=P(()=>{"use strict";Oo();st=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let h of this.plugins.values()){for(let m of s.runtimes.keys())if(h.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(h.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(h=>[...s.transformers].map(([m,y])=>{if(h.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:h,name:m,value:h.preparePluginTransformer(y)}})),g=[];try{for(let h of f)g.push(h),h.service.registerTransformer(h.name,h.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(h){for(let m of g)m.service.removeTransformer(m.name);throw a="aborted",h}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:d??p}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=Il({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")}},Ml=new st,Mo=()=>Ml});function Vs(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 ve(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?Ll(r):{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(i)}catch{}let c=Qs(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function Ll(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 Ys=P(()=>{"use strict";Qt()});var Vt,Lo=P(()=>{Vt="2.3.2428"});var Xs={};To(Xs,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>Ul});function Ne(n){return xe||(xe=new $o,n&&xe.configure(n)),xe}function Ul(){xe&&(xe.clearAll(),xe=null)}var Nl,$o,xe,Yt=P(()=>{"use strict";re();Nl=600*1e3,$o=class{promotions=new Map;enabled=!0;ttlMs=Nl;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 d=r.find(g=>g.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(g=>String(g).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});import{existsSync as ei,mkdirSync as Dl,readFileSync as Fl,writeFileSync as jl}from"fs";import{join as ti}from"path";import{HOME_DIR as Hl}from"@wengine-ai/claude-code-router-shared";function Wl(n){try{if(!ei(Do))return;let e=JSON.parse(Fl(Do,"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 qs(n){try{let e=n.getAllStates();if(e.length===0)return;ei(Uo)||Dl(Uo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));jl(Do,JSON.stringify(t,null,2),"utf-8")}catch{}}function Fo(){if(Zs)return;Zs=!0;let n=H();Wl(n),Jl=setInterval(()=>qs(n),6e4),process.on("exit",()=>qs(n))}function H(n){return No||(No=new Xt(n)),No}var zl,Bl,Xt,Uo,Do,Zs,Jl,No,re=P(()=>{"use strict";zl=120,Bl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Bl,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.lastSuccessTime=Date.now(),r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),gl(Xs));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??zl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Uo=ti(Hl,"runtime"),Do=ti(Uo,"provider-health.json"),Zs=!1,Jl=null;No=null});import{existsSync as ii,mkdirSync as Kl,readFileSync as Gl,writeFileSync as Ql}from"fs";import{join as ai}from"path";import{HOME_DIR as Vl}from"@wengine-ai/claude-code-router-shared";function it(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let c=Object.keys(t).find(l=>l.toLowerCase()===i);return c?t[c]:null},r=jo(o,Yl),s=jo(o,Xl),a=jo(o,Zl);(r||s||a)&&Ue.set(n,{provider:n,remaining:ri(r),limit:ri(s),reset:eu(a),capturedAt:Date.now()})}function ql(n){return Ue.get(n)}function Bo(){return Array.from(Ue.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function jo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ri(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function eu(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=tu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function tu(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 nu(){try{if(!ii(zo))return;let n=JSON.parse(Gl(zo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Ue.set(t.provider,t)}}catch{}}function si(){try{if(Ue.size===0)return;ii(Ho)||Kl(Ho,{recursive:!0}),Ql(zo,JSON.stringify(Array.from(Ue.values()),null,2),"utf-8")}catch{}}function at(){ni||(ni=!0,nu(),oi=setInterval(si,6e4),oi.unref?.(),process.on("exit",si))}var Ho,zo,Ue,ni,oi,Yl,Xl,Zl,Se=P(()=>{"use strict";Ho=ai(Vl,"runtime"),zo=ai(Ho,"rate-limit.json"),Ue=new Map,ni=!1,oi=null,Yl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Xl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Zl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return Jo||(Jo=new Ko),Jo}function Qo(){return Wo||(Wo=new Go),Wo}function ou(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function ci(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 li(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Vo(n){let e=n?.[qt];e&&en().release(e)}function ui(n,e){let t=ci(n),o=n?.[qt],r=t?Qo().get(t)!==void 0:!1;!o&&!r||(t&&Qo().bind(t,e),li(n,e))}function ru(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function di(n,e,t){let o=ci(n),r=Qo(),s=en(),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=ru(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 li(n,i),i}var Ko,Go,Jo,Wo,qt,tn=P(()=>{"use strict";Ko=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()}},Go=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()}},Jo=null,Wo=null;qt="__concurrencyLease"});async function j(n){let e=await n.text();return su(e,n.status)}function su(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 pi(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function ct(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:c}=await o.read();if(c||(i&&(s+=r.decode(i,{stream:!0})),ct(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:ct(s)}}async function me(n){try{let e=await n.text();if(ct(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=P(()=>{"use strict"});function iu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function nn(n){for(let e of iu(n))if(e.startsWith("response."))return!0;return!1}var De,Yo=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){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role==="system")return;if(Array.isArray(r.content)){let i=r.content.map(c=>this.normalizeRequestContent(c,r.role)).filter(c=>c!==null);i.length>0?r.content=i:delete r.content}if(r.role==="tool"){let i={...r};i.type="function_call_output",i.call_id=r.tool_call_id,i.output=r.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}let{thinking:s,...a}=r;r.role==="assistant"&&a.content===void 0||t.push(a)}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await j(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",c=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=c.decode(p,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",c,l,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let S=(x,O=null)=>{T.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:x,finish_reason:O}]})}
4
+ `);a=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Ds(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Ds(e,t,s,a.trim()),s++),Fs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Fs(e,t,s)}finally{r.releaseLock()}})()}var wl,Pl,Le,wo,rt=w(()=>{"use strict";wl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Pl=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},wo=!1});function Js(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([c,u])=>{u&&s.set(c,u)});let a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=c.signal}else a=i;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?l.dispatcher=t.dispatcher:t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Al(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function Al(n){if(!(typeof n!="string"||!n.trim()))try{let e=new URL(n);return e.username||e.password?(e.username="",e.password="",`${e.toString()} (credentials redacted)`):e.toString()}catch{return"[invalid proxy URL]"}}var Ws=w(()=>{q();rt()});function Il(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Ks(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Eo(n){if(Ks(n))return"pending";let e=!1,t=!1;for(let o of n.split(`
5
+ `)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(Ol.some(s=>r.includes(s))){e=!0;break}Ml.some(s=>r.includes(s))&&(t=!0)}}return e||Il(n)?"content":t?"empty":"pending"}async function Gs(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,l=Date.now()+t,c=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=l-Date.now(),p=Symbol("timeout"),d,f=o.read(),g=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),g===p)return c(Eo(a)==="content"?"content":"pending",Gt(o,f));if(g.done){a+=r.decode();let m=Eo(a);return c(m==="empty"?"empty":"pending",null)}if(!g.value)continue;s.push(g.value),i+=g.value.byteLength,a+=r.decode(g.value,{stream:!0});let h=Eo(a);if(h==="content")return c("content",Gt(o));if(h==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if(Ks(a)||i>=e)return c("pending",Gt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Gt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Qs(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var Ol,Ml,Vs=w(()=>{"use strict";Ol=["content_block_start","content_block_delta","content_block_stop"];Ml=["message_stop","response.completed","response.incomplete","[DONE]"]});function Ll(n,e){return`${n.name}|${e?.name??""}`}function Ao(n){return n.__ccrPluginRequestState??={budgets:new Map}}function $e(n,e,t){let o=Ao(n),r=Ll(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Oo(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:($e(n,e,o).terminalError=t,!0)}var Ys=w(()=>{"use strict"});var Io=w(()=>{"use strict"});import $l from"fastify";function Xs(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var st,Nl,Lo,Qt=w(()=>{"use strict";Io();st=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,l=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>l(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>l(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>l(()=>{s.routes.push(u)}),registerConfigProtector:u=>l(()=>{s.protectors.push(u)}),registerUiCard:u=>l(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>l(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let h of this.plugins.values()){for(let m of s.runtimes.keys())if(h.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(h.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(h=>[...s.transformers].map(([m,y])=>{if(h.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:h,name:m,value:h.preparePluginTransformer(y)}})),g=[];try{for(let h of f)g.push(h),h.service.registerTransformer(h.name,h.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(h){for(let m of g)m.service.removeTransformer(m.name);throw a="aborted",h}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,l)=>{if(l==="route")return u=>(r.push(u),s);if(o.has(String(l)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:l==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(l).toUpperCase(),url:u,handler:d??p}),s);let c=Reflect.get(i,l);return typeof c=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(l)}`)}:c}}),a=$l({logger:!1});try{for(let i of e){let l=i(s);l!==s&&await l}for(let i of this.plugins.values())for(let l of i.preparedRoutes)a.route(l);for(let i of r){let l=Array.isArray(i.method)?i.method:[i.method];for(let c of l)if(t.hasRoute({method:c,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${c} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},Nl=new st,Lo=()=>Nl});function Zs(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function ve(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?Ul(r):{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(i)}catch{}let l=Xs(n.name,i);return l.isRateLimit=i.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function Ul(n){let e=[n?.causeCode,n?.causeDetail].filter(Boolean).join(" ");return{code:"plugin_network_error",message:e?`Provider plugin network failure (${e}).`:n?.errorName?`Provider plugin network failure (${n.errorName}).`:"Provider plugin network failure.",httpStatus:502,retryable:!0}}var qs=w(()=>{"use strict";Qt()});var Vt,$o=w(()=>{Vt="2.3.2430"});var ei={};vo(ei,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>jl});function Ne(n){return xe||(xe=new No,n&&xe.configure(n)),xe}function jl(){xe&&(xe.clearAll(),xe=null)}var Fl,No,xe,Yt=w(()=>{"use strict";re();Fl=600*1e3,No=class{promotions=new Map;enabled=!0;ttlMs=Fl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(i,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...c]=a.promotedModel.split(","),u=c.join(",");if(!H().isAvailable(l,u))return this.promotions.delete(s),null;let d=r.find(g=>g.name.toLowerCase()===l.toLowerCase()),f=d?.models?.find(g=>String(g).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});import{existsSync as oi,mkdirSync as Hl,readFileSync as zl,writeFileSync as Bl}from"fs";import{join as ri}from"path";import{HOME_DIR as Jl}from"@wengine-ai/claude-code-router-shared";function Ql(n){try{if(!oi(Fo))return;let e=JSON.parse(zl(Fo,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastSuccessTime:o.lastSuccessTime,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function ni(n){try{let e=n.getAllStates();if(e.length===0)return;oi(Do)||Hl(Do,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Bl(Fo,JSON.stringify(t,null,2),"utf-8")}catch{}}function jo(){if(ti)return;ti=!0;let n=H();Ql(n),Gl=setInterval(()=>ni(n),6e4),process.on("exit",()=>ni(n))}function H(n){return Uo||(Uo=new Xt(n)),Uo}var Wl,Kl,Xt,Do,Fo,ti,Gl,Uo,re=w(()=>{"use strict";Wl=120,Kl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Kl,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.lastSuccessTime=Date.now(),r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),_l(ei));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t,o=!1){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let s=this.getState(e,t);return s?s.status==="open"&&s.rateLimitUntil?!(Date.now()<s.rateLimitUntil):s.status==="open"&&o&&Date.now()-Math.max(s.lastFailureTime,s.lastProbeTime)>=this.config.probeIntervalMinutes*6e4?(s.status="half-open",s.successCount=0,s.lastProbeTime=Date.now(),!0):s.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}recordProbeAttempt(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.lastProbeTime=Date.now())}markParkedUntil(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s&&(!Number.isFinite(o)||o<=Date.now()||s.rateLimitUntil&&s.rateLimitUntil>=o||(s.rateLimitUntil=o))}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??Wl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Do=ri(Jl,"runtime"),Fo=ri(Do,"provider-health.json"),ti=!1,Gl=null;Uo=null});import{existsSync as li,mkdirSync as Vl,readFileSync as Yl,writeFileSync as Xl}from"fs";import{join as ui}from"path";import{HOME_DIR as Zl}from"@wengine-ai/claude-code-router-shared";function it(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let l=Object.keys(t).find(c=>c.toLowerCase()===i);return l?t[l]:null},r=Ho(o,ql),s=Ho(o,eu),a=Ho(o,tu);(r||s||a)&&Ue.set(n,{provider:n,remaining:ai(r),limit:ai(s),reset:ou(a),capturedAt:Date.now()})}function nu(n){return Ue.get(n)}function Jo(){return Array.from(Ue.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Ho(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ai(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function ou(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 su(){try{if(!li(Bo))return;let n=JSON.parse(Yl(Bo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Ue.set(t.provider,t)}}catch{}}function ci(){try{if(Ue.size===0)return;li(zo)||Vl(zo,{recursive:!0}),Xl(Bo,JSON.stringify(Array.from(Ue.values()),null,2),"utf-8")}catch{}}function at(){si||(si=!0,su(),ii=setInterval(ci,6e4),ii.unref?.(),process.on("exit",ci))}var zo,Bo,Ue,si,ii,ql,eu,tu,Se=w(()=>{"use strict";zo=ui(Zl,"runtime"),Bo=ui(zo,"rate-limit.json"),Ue=new Map,si=!1,ii=null,ql=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],eu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],tu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return Wo||(Wo=new Go),Wo}function Vo(){return Ko||(Ko=new Qo),Ko}function iu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function di(n){let e=iu(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function pi(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Yo(n){let e=n?.[qt];e&&en().release(e)}function fi(n,e){let t=di(n),o=n?.[qt],r=t?Vo().get(t)!==void 0:!1;!o&&!r||(t&&Vo().bind(t,e),pi(n,e))}function au(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let l=o.count(i);l<s&&(r=i,s=l)}return r}function mi(n,e,t){let o=di(n),r=Vo(),s=en(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(i=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(i=e)}if(!i){let l=s.count(e);if(l>=a){let c=au(e,t.fallbackModels,t.resolve);c&&(i=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}i=i||e,o&&r.bind(o,i)}return pi(n,i),i}var Go,Qo,Wo,Ko,qt,tn=w(()=>{"use strict";Go=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},Qo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},Wo=null,Ko=null;qt="__concurrencyLease"});async function j(n){let e=await n.text();return cu(e,n.status)}function cu(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function gi(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function ct(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:l}=await o.read();if(l||(i&&(s+=r.decode(i,{stream:!0})),ct(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:ct(s)}}async function me(n){try{let e=await n.text();if(ct(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=w(()=>{"use strict"});function 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 nn(n){for(let e of lu(n))if(e.startsWith("response."))return!0;return!1}var De,Xo=w(()=>{"use strict";V();De=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role==="system")return;if(Array.isArray(r.content)){let i=r.content.map(l=>this.normalizeRequestContent(l,r.role)).filter(l=>l!==null);i.length>0?r.content=i:delete r.content}if(r.role==="tool"){let i={...r};i.type="function_call_output",i.call_id=r.tool_call_id,i.output=r.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}let{thinking:s,...a}=r;r.role==="assistant"&&a.content===void 0||t.push(a)}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await j(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",l=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=l.decode(p,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",l,c,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(S,I=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[{index:0,delta:S,finish_reason:I}]})}
6
6
 
7
- `))},v=x=>{if(!x)return;let O=_.getCacheReadInputTokens(x),M=typeof x.input_tokens=="number"?x.input_tokens:void 0,N=_.getCacheCreationInputTokens(x);T.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 x.output_tokens=="number"?x.output_tokens:void 0,total_tokens:x.total_tokens,prompt_tokens_details:{cached_tokens:O,cache_creation_tokens:N},cache_read_input_tokens:O,cache_creation_input_tokens:N}})}
7
+ `))},v=S=>{if(!S)return;let I=_.getCacheReadInputTokens(S),M=typeof S.input_tokens=="number"?S.input_tokens:void 0,N=_.getCacheCreationInputTokens(S);T.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[],usage:{prompt_tokens:M,completion_tokens:typeof S.output_tokens=="number"?S.output_tokens:void 0,total_tokens:S.total_tokens,prompt_tokens_details:{cached_tokens:I,cache_creation_tokens:N},cache_read_input_tokens:I,cache_creation_input_tokens:N}})}
8
8
 
9
- `))},w=x=>{m||(m=!0,T.enqueue(r.encode(`data: ${JSON.stringify({error:{message:x,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
9
+ `))},P=S=>{m||(m=!0,T.enqueue(r.encode(`data: ${JSON.stringify({error:{message:S,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
10
10
 
11
- `)))},R=x=>{y||(y=!0,v(u),S({},x))},E=()=>{b||(b=!0,T.enqueue(r.encode(`data: [DONE]
11
+ `)))},E=S=>{y||(y=!0,v(u),x({},S))},R=()=>{b||(b=!0,T.enqueue(r.encode(`data: [DONE]
12
12
 
13
- `)))},I=(x,O)=>{let M=x?.call_id||x?.id||(O!==void 0?`idx_${O}`:void 0);if(!M)return h++;let N=f.get(M);if(N!==void 0)return N;let L=h++;return f.set(M,L),x?.call_id&&x?.id?(f.set(x.id,L),O!==void 0&&f.set(`idx_${O}`,L)):x?.id&&O!==void 0&&f.set(`idx_${O}`,L),L},U=x=>{let O=!1;for(let M of Array.isArray(x)?x:[])if(M?.type==="function_call"){d="tool";let N=I(M,void 0),L=M.call_id||M.id;L&&g.set(N,L),S({role:"assistant",tool_calls:[{index:N,id:L,type:"function",function:{name:M.name||"",arguments:typeof M.arguments=="string"?M.arguments:""}}]}),O=!0}else if(M?.type==="message")for(let N of Array.isArray(M.content)?M.content:[])N?.type==="output_text"&&typeof N.text=="string"&&N.text.trim().length>0&&(d="text",S({role:"assistant",content:N.text}),O=!0);return O},C=x=>{switch(x?.response?.model&&(c=x.response.model),x?.response?.id&&(l=x.response.id),x?.type){case"response.output_item.added":{let O=x.item;if(O?.type!=="function_call")return;d="tool";let M=I(O,x.output_index),N=O.call_id||O.id;N&&g.set(M,N),S({role:"assistant",tool_calls:[{index:M,id:N,type:"function",function:{name:O.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let O=I({id:x.item_id},x.output_index);d="tool";let M=g.get(O);S({tool_calls:[{index:O,...M?{id:M,type:"function"}:{},function:{arguments:typeof x.delta=="string"?x.delta:""}}]});return}case"response.output_text.annotation.added":{let O=x.annotation;if(!O)return;d="annotation",S({annotations:[{type:"url_citation",url_citation:{url:O.url||"",title:O.title||"",content:"",start_index:O.start_index||0,end_index:O.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof x.delta!="string"||x.delta.length===0)return;d="thinking",S({thinking:{content:x.delta}});return}case"response.output_text.delta":{if(typeof x.delta!="string"||x.delta.length===0)return;d="text";let O=p!==x.item_id;p=x.item_id;let M={content:x.delta};O&&(M.role="assistant"),S(M);return}case"response.completed":{u=x.response?.usage;let O=Array.isArray(x.response?.output)?x.response.output:[],M=O.some(N=>N?.type==="function_call");if(d===""&&U(O),!M&&d===""){let N=String(x.response?.incomplete_details?.reason??"");w(O.length===0&&!N?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${N||"empty"})`);return}R(d==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=x.response?.usage;let O=String(x.response?.incomplete_details?.reason??"");d===""&&U(Array.isArray(x.response?.output)?x.response.output:[]);let M=O==="max_output_tokens"||O==="max_tokens";if(d===""){w(`Upstream Responses stream produced no content (${O||"incomplete"})`);return}R(M?"length":O==="content_filter"?"content_filter":"stop");return}case"response.failed":{let O=x.response?.error||x.error||void 0;w(O?.message||"Upstream Responses stream failed before completing");return}case"error":{w(x.error?.message||x.message||"Upstream Responses stream error");return}default:return}},A=e.getReader();(async()=>{try{for(;;){let{done:x,value:O}=await A.read();if(x)break;i+=o.decode(O,{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]"){E();continue}let J;try{J=JSON.parse(F)}catch{continue}C(J)}}if(i+=o.decode(),i.trim().startsWith("data:")){let x=i.trim().slice(5).trim();if(x&&x!=="[DONE]")try{C(JSON.parse(x))}catch{}}!m&&!y&&(d===""?w("Upstream Responses stream ended before any output"):R(d==="tool"?"tool_calls":"stop")),m||E()}catch(x){console.error("Responses\u2192Chat stream error:",x);try{T.error(x)}catch{}return}finally{try{A.releaseLock()}catch{}}try{T.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:g}=await a.read();if(g||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}i+=new TextDecoder().decode()}finally{a.releaseLock()}r.cancel().catch(()=>{});let 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")||nn(i))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(l&&!c){let d=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let p=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await 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="",p=-1,d=[],f=(h,m)=>r.encode(`event: ${h}
13
+ `)))},A=(S,I)=>{let M=S?.call_id||S?.id||(I!==void 0?`idx_${I}`:void 0);if(!M)return h++;let N=f.get(M);if(N!==void 0)return N;let L=h++;return f.set(M,L),S?.call_id&&S?.id?(f.set(S.id,L),I!==void 0&&f.set(`idx_${I}`,L)):S?.id&&I!==void 0&&f.set(`idx_${I}`,L),L},D=S=>{let I=!1;for(let M of Array.isArray(S)?S:[])if(M?.type==="function_call"){d="tool";let N=A(M,void 0),L=M.call_id||M.id;L&&g.set(N,L),x({role:"assistant",tool_calls:[{index:N,id:L,type:"function",function:{name:M.name||"",arguments:typeof M.arguments=="string"?M.arguments:""}}]}),I=!0}else if(M?.type==="message")for(let N of Array.isArray(M.content)?M.content:[])N?.type==="output_text"&&typeof N.text=="string"&&N.text.trim().length>0&&(d="text",x({role:"assistant",content:N.text}),I=!0);return I},C=S=>{switch(S?.response?.model&&(l=S.response.model),S?.response?.id&&(c=S.response.id),S?.type){case"response.output_item.added":{let I=S.item;if(I?.type!=="function_call")return;d="tool";let M=A(I,S.output_index),N=I.call_id||I.id;N&&g.set(M,N),x({role:"assistant",tool_calls:[{index:M,id:N,type:"function",function:{name:I.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let I=A({id:S.item_id},S.output_index);d="tool";let M=g.get(I);x({tool_calls:[{index:I,...M?{id:M,type:"function"}:{},function:{arguments:typeof S.delta=="string"?S.delta:""}}]});return}case"response.output_text.annotation.added":{let I=S.annotation;if(!I)return;d="annotation",x({annotations:[{type:"url_citation",url_citation:{url:I.url||"",title:I.title||"",content:"",start_index:I.start_index||0,end_index:I.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;d="thinking",x({thinking:{content:S.delta}});return}case"response.output_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;d="text";let I=p!==S.item_id;p=S.item_id;let M={content:S.delta};I&&(M.role="assistant"),x(M);return}case"response.completed":{u=S.response?.usage;let I=Array.isArray(S.response?.output)?S.response.output:[],M=I.some(N=>N?.type==="function_call");if(d===""&&D(I),!M&&d===""){let N=String(S.response?.incomplete_details?.reason??"");P(I.length===0&&!N?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${N||"empty"})`);return}E(d==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=S.response?.usage;let I=String(S.response?.incomplete_details?.reason??"");d===""&&D(Array.isArray(S.response?.output)?S.response.output:[]);let M=I==="max_output_tokens"||I==="max_tokens";if(d===""){P(`Upstream Responses stream produced no content (${I||"incomplete"})`);return}E(M?"length":I==="content_filter"?"content_filter":"stop");return}case"response.failed":{let I=S.response?.error||S.error||void 0;P(I?.message||"Upstream Responses stream failed before completing");return}case"error":{P(S.error?.message||S.message||"Upstream Responses stream error");return}default:return}},O=e.getReader();(async()=>{try{for(;;){let{done:S,value:I}=await O.read();if(S)break;i+=o.decode(I,{stream:!0});let M=i.split(/\r?\n/);i=M.pop()||"";for(let N of M){let L=N.trim();if(!L||L.startsWith(":")||L.startsWith("event:")||!L.startsWith("data:"))continue;let F=L.slice(5).trim();if(!F)continue;if(F==="[DONE]"){R();continue}let J;try{J=JSON.parse(F)}catch{continue}C(J)}}if(i+=o.decode(),i.trim().startsWith("data:")){let S=i.trim().slice(5).trim();if(S&&S!=="[DONE]")try{C(JSON.parse(S))}catch{}}!m&&!y&&(d===""?P("Upstream Responses stream ended before any output"):E(d==="tool"?"tool_calls":"stop")),m||R()}catch(S){console.error("Responses\u2192Chat stream error:",S);try{T.error(S)}catch{}return}finally{try{O.releaseLock()}catch{}}try{T.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:g}=await a.read();if(g||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}i+=new TextDecoder().decode()}finally{a.releaseLock()}r.cancel().catch(()=>{});let l=i.includes("message_start")||i.includes("content_block_start"),c=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")||nn(i))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(c&&!l){let d=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let p=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await j(e);return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i=0,l=!1,c=!1,u="",p=-1,d=[],f=(h,m)=>r.encode(`event: ${h}
14
14
  data: ${JSON.stringify(m)}
15
15
 
16
- `),g=(h,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:h,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(h){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let T of d)if(T.type==="function_call"){let S=d.indexOf(T);h.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:S,arguments:T.arguments||""})),T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:S,item:T}))}for(let T of d)if(T.type==="message"){let S=d.indexOf(T);T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:S,item:T}))}h.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:T}=await m.read();if(k)break;y+=o.decode(T,{stream:!0});let S=y.split(`
17
- `);y=S.pop()||"";for(let v of S){let w=v.trim();if(!w||w.startsWith("event:")||!w.startsWith("data:"))continue;let R=w.slice(5).trim();if(R==="[DONE]"){_({}),h.enqueue(r.encode(`data: [DONE]
16
+ `),g=(h,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:h,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(h){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let T of d)if(T.type==="function_call"){let x=d.indexOf(T);h.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:x,arguments:T.arguments||""})),T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}for(let T of d)if(T.type==="message"){let x=d.indexOf(T);T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}h.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:T}=await m.read();if(k)break;y+=o.decode(T,{stream:!0});let x=y.split(`
17
+ `);y=x.pop()||"";for(let v of x){let P=v.trim();if(!P||P.startsWith("event:")||!P.startsWith("data:"))continue;let E=P.slice(5).trim();if(E==="[DONE]"){_({}),h.enqueue(r.encode(`data: [DONE]
18
18
 
19
- `));continue}let E;try{E=JSON.parse(R)}catch{continue}c||(c=!0,h.enqueue(f("response.created",{type:"response.created",response:g("in_progress")})),h.enqueue(f("response.in_progress",{type:"response.in_progress",response:g("in_progress")})));let I=E.choices?.[0];if(!I)continue;let U=I.delta;if(U?.content){if(!l){l=!0;let C=i++,A={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(A),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:C,item:A}))}h.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:U.content}))}if(Array.isArray(U?.tool_calls))for(let C of U.tool_calls){if(C.id){u=C.id,p=i++;let A={id:C.id,type:"function_call",status:"in_progress",call_id:C.id,name:C.function?.name||"",arguments:""};d.push(A),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:A}))}if(C.function?.arguments){h.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:C.function.arguments}));let A=d.find(x=>x.call_id===u);A&&(A.arguments+=C.function.arguments)}}I.finish_reason&&_(E)}}b||_({}),h.close()}catch(m){h.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",c="",l=-1,u="",p="",d="",f=-1,g="",h="",m=-1,y=0,b=!1,_=!1,k=!1,T=!1,S=null,v=[],w=(A,x)=>r.encode(`event: ${A}
20
- data: ${JSON.stringify(x)}
19
+ `));continue}let R;try{R=JSON.parse(E)}catch{continue}l||(l=!0,h.enqueue(f("response.created",{type:"response.created",response:g("in_progress")})),h.enqueue(f("response.in_progress",{type:"response.in_progress",response:g("in_progress")})));let A=R.choices?.[0];if(!A)continue;let D=A.delta;if(D?.content){if(!c){c=!0;let C=i++,O={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(O),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:C,item:O}))}h.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:D.content}))}if(Array.isArray(D?.tool_calls))for(let C of D.tool_calls){if(C.id){u=C.id,p=i++;let O={id:C.id,type:"function_call",status:"in_progress",call_id:C.id,name:C.function?.name||"",arguments:""};d.push(O),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:O}))}if(C.function?.arguments){h.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:C.function.arguments}));let O=d.find(S=>S.call_id===u);O&&(O.arguments+=C.function.arguments)}}A.finish_reason&&_(R)}}b||_({}),h.close()}catch(m){h.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",l="",c=-1,u="",p="",d="",f=-1,g="",h="",m=-1,y=0,b=!1,_=!1,k=!1,T=!1,x=null,v=[],P=(O,S)=>r.encode(`event: ${O}
20
+ data: ${JSON.stringify(S)}
21
21
 
22
- `),R=(A,x=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:A,model:s,output:x,usage:this.buildResponsesUsage()}),E=()=>{b||(b=!0,C.enqueue(w("response.created",{type:"response.created",response:R("in_progress")})),C.enqueue(w("response.in_progress",{type:"response.in_progress",response:R("in_progress")})))},I=(A,x)=>{C.enqueue(w("response.output_item.done",{type:"response.output_item.done",output_index:A,item:{...x,status:"completed"}}))},U=A=>{if(!T){if(T=!0,_){let x=v.find(O=>O.type==="message");x&&(x.content=[{type:"output_text",text:i}],x.status="completed")}for(let x of v)x.type==="function_call"&&(x.status="completed");return w("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:A?{...this.buildResponsesUsage(A)}:this.buildResponsesUsage()}})}},C;return new ReadableStream({async start(A){C=A;try{let x=e.getReader(),O="";for(;;){let{done:N,value:L}=await x.read();if(N)break;O+=o.decode(L,{stream:!0});let F=O.split(`
23
- `);O=F.pop()||"";for(let J of F){let ce=J.trim();if(!ce||ce.startsWith("event:")||!ce.startsWith("data:"))continue;let B=ce.slice(5).trim();if(B==="[DONE]")continue;let z;try{z=JSON.parse(B)}catch{continue}if(z.type==="message_start"&&(a=z.message?.id||a,E()),z.type==="content_block_start"){let $=z.content_block;if(S=$?.type||null,$?.type==="tool_use"){u=$.id||"",p=$.name||"",d="",f=y++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};v.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if($?.type==="thinking"&&(g=$.thinking||"",!k)){k=!0,m=y++,h=`rs_${a}`;let W={id:h,type:"reasoning",status:"in_progress",summary:[]};v.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if($?.type==="text"&&(i=$?.text||"",!_)){_=!0,l=y++,c=`${a}_msg`;let W={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:l,item:W}))}}if(z.type==="content_block_delta"){let $=z.delta;if($?.type==="text_delta"){if(!_){_=!0,l=y++,c=`${a}_msg`;let W={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),C.enqueue(w("response.output_item.added",{type:"response.output_item.added",output_index:l,item:W}))}i+=$.text||"",C.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"&&(g+=$.thinking||"",C.enqueue(w("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:h||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(d+=$.partial_json||"",C.enqueue(w("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:f>=0?f:0,delta:$.partial_json||""})))}if(z.type==="content_block_stop"){if(S==="tool_use"&&u){C.enqueue(w("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:d}));let $=v.find(W=>W.call_id===u);$&&($.arguments=d,$.status="completed"),$&&I(f,$)}if(S==="text"&&_){C.enqueue(w("response.output_text.done",{type:"response.output_text.done",item_id:c,output_index:l,content_index:0,text:i}));let $=v.find(W=>W.type==="message");$&&($.content=[{type:"output_text",text:i}],I(l,$))}if(S==="thinking"&&k){let $=v.find(W=>W.type==="reasoning");$&&($.summary=[{type:"summary_text",text:g}],I(m,$))}S=null}if(z.type==="message_delta"){let $=U(z.usage);$&&C.enqueue($)}if(z.type==="message_stop"){let $=U();$&&C.enqueue($),C.enqueue(r.encode(`data: [DONE]
22
+ `),E=(O,S=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:O,model:s,output:S,usage:this.buildResponsesUsage()}),R=()=>{b||(b=!0,C.enqueue(P("response.created",{type:"response.created",response:E("in_progress")})),C.enqueue(P("response.in_progress",{type:"response.in_progress",response:E("in_progress")})))},A=(O,S)=>{C.enqueue(P("response.output_item.done",{type:"response.output_item.done",output_index:O,item:{...S,status:"completed"}}))},D=O=>{if(!T){if(T=!0,_){let S=v.find(I=>I.type==="message");S&&(S.content=[{type:"output_text",text:i}],S.status="completed")}for(let S of v)S.type==="function_call"&&(S.status="completed");return P("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:O?{...this.buildResponsesUsage(O)}:this.buildResponsesUsage()}})}},C;return new ReadableStream({async start(O){C=O;try{let S=e.getReader(),I="";for(;;){let{done:N,value:L}=await S.read();if(N)break;I+=o.decode(L,{stream:!0});let F=I.split(`
23
+ `);I=F.pop()||"";for(let J of F){let ce=J.trim();if(!ce||ce.startsWith("event:")||!ce.startsWith("data:"))continue;let B=ce.slice(5).trim();if(B==="[DONE]")continue;let z;try{z=JSON.parse(B)}catch{continue}if(z.type==="message_start"&&(a=z.message?.id||a,R()),z.type==="content_block_start"){let $=z.content_block;if(x=$?.type||null,$?.type==="tool_use"){u=$.id||"",p=$.name||"",d="",f=y++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if($?.type==="thinking"&&(g=$.thinking||"",!k)){k=!0,m=y++,h=`rs_${a}`;let W={id:h,type:"reasoning",status:"in_progress",summary:[]};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if($?.type==="text"&&(i=$?.text||"",!_)){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}}if(z.type==="content_block_delta"){let $=z.delta;if($?.type==="text_delta"){if(!_){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}i+=$.text||"",C.enqueue(P("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(g+=$.thinking||"",C.enqueue(P("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:h||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(d+=$.partial_json||"",C.enqueue(P("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:f>=0?f:0,delta:$.partial_json||""})))}if(z.type==="content_block_stop"){if(x==="tool_use"&&u){C.enqueue(P("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:d}));let $=v.find(W=>W.call_id===u);$&&($.arguments=d,$.status="completed"),$&&A(f,$)}if(x==="text"&&_){C.enqueue(P("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:c,content_index:0,text:i}));let $=v.find(W=>W.type==="message");$&&($.content=[{type:"output_text",text:i}],A(c,$))}if(x==="thinking"&&k){let $=v.find(W=>W.type==="reasoning");$&&($.summary=[{type:"summary_text",text:g}],A(m,$))}x=null}if(z.type==="message_delta"){let $=D(z.usage);$&&C.enqueue($)}if(z.type==="message_stop"){let $=D();$&&C.enqueue($),C.enqueue(r.encode(`data: [DONE]
24
24
 
25
- `))}}}E();let M=U();M&&C.enqueue(M),O="",C.close()}catch(x){C.error(x)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(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(p=>{if(p.type==="output_text")l.push(p.text||"");else if(p.type==="output_image"){let d=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});d&&u.push(d)}else if(p.type==="output_image_base64"){let d=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});d&&u.push(d)}}),u.length>0){let p=[];l.length>0&&p.push({type:"text",text:l.join("")}),p.push(...u),r=p}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 Xo,Y,on=P(()=>{"use strict";Xo=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 Xo(100)});import{existsSync as hi,mkdirSync as au,readFileSync as cu,writeFileSync as lu}from"fs";import{join as yi}from"path";import{HOME_DIR as uu}from"@wengine-ai/claude-code-router-shared";function lt(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function rn(n){let e=Fe.get(n);return e?{...e}:void 0}function er(){return Array.from(Fe.values()).map(n=>({...n}))}function du(){try{if(!hi(qo))return;let n=JSON.parse(cu(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>1440*60*1e3)continue;Fe.set(t.provider,t)}}catch{}}function gi(){try{if(Fe.size===0)return;hi(Zo)||au(Zo,{recursive:!0}),lu(qo,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function ut(){fi||(fi=!0,du(),mi=setInterval(gi,6e4),mi.unref?.(),process.on("exit",gi))}var Zo,qo,Fe,fi,mi,Ce=P(()=>{"use strict";Zo=yi(uu,"runtime"),qo=yi(Zo,"quota-store.json"),Fe=new Map,fi=!1,mi=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!pu.test(e)))return e}function he(n){if(!n)return;if(typeof n=="object")return ge(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=ge(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return ge(e.slice(o+t.length))}var pu,je=P(()=>{"use strict";pu=/^[A-Za-z0-9_-]+$/});import{existsSync as ki}from"fs";import{readFile as fu,readdir as mu}from"fs/promises";import{homedir as gu}from"os";import{isAbsolute as hu,join as dt,normalize as yu}from"path";import{openSqliteDatabase as _u}from"@wengine-ai/claude-code-router-shared";function Ru(){if(He.size<=_i)return;let n=[...He.keys()].slice(0,He.size-_i);for(let e of n)He.delete(e)}function wu(){if(ze.size<=bi)return;let n=[...ze].slice(0,ze.size-bi);for(let e of n)ze.delete(e)}function Pu(n){let e=n.trim();if(!e||e==="."||e===".."||/[/\\\0]/.test(e))return[];let t=e.replace(/^sess_/,"");return[...new Set([e,t,`sess_${t}`])].filter(Boolean)}function Eu(n,e){let t;try{t=_u(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 Au(n,e){let t;try{t=await mu(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(ki(s))try{let a=JSON.parse(await fu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Ti(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=Pu(e);if(r.length===0)return null;let s=dt(bu(),ku),a=dt(s,Tu);if(ki(a)){let i=Eu(a,r);if(i)return i}return Au(dt(s,vu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),wu();for(let a=0;a<xu&&!r;a++)await Cu(Su),r=await o()}if(!r||!hu(r))return null;let s=yu(r);return He.set(e,s),Ru(),s}catch{return null}}var bu,ku,Tu,vu,_i,bi,xu,Su,He,ze,Cu,vi=P(()=>{"use strict";bu=()=>process.env.CCR_ZCODE_DIR||dt(gu(),".zcode"),ku="v2",Tu="tasks-index.sqlite",vu="sessions",_i=500,bi=500,xu=3,Su=50,He=new Map,ze=new Set,Cu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as Ou}from"node:crypto";import{CCR_PROJECT_HEADER as tr}from"@wengine-ai/claude-code-router-shared";function Ci(n){return typeof n=="string"&&n.length<=Iu}function Mu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Si){let{value:t}=sn(n,e);if(!Ci(t))continue;let o=ge(t);if(o)return o}}function $u(n){if(typeof n=="string")return n.slice(0,1e3);if(Array.isArray(n)){let e=n.find(t=>t&&typeof t.text=="string");return e?String(e.text).slice(0,1e3):""}return""}function Nu(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function sn(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function xi(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function pt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function nr(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function wi(n){return typeof n=="string"&&Lu.includes(n)}function Wu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(wi(n?.clientType))return n.clientType;let e=Nu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=$u(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(sn(n,tr).present||sn(n,"x-session-affinity").present)return"pi";if(Wu(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 Pi(n){return Ri[n]}function Ku(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||Ou();return n.__ccrRequestScopeId=e,e}function Re(n,e={}){let t=Be(n),o=Pi(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Ku(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,xi(n,tr),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Si)xi(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Gu(){}var Si,Iu,Lu,Uu,Du,Fu,ju,Hu,zu,Bu,Ju,Ri,Je=P(()=>{"use strict";je();Si=["x-session-affinity","x-session-id","x-litellm-session-id"],Iu=256;Lu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Uu={type:"claude-code",createContext(n){return nr(n,"claude-code")}},Du={type:"zcode",createContext(n){return nr(n,"zcode")}},Fu={type:"pi",createContext(n){let e=sn(n,tr),t=Mu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=Ci(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},ju={type:"qwen-code",createContext(n){return nr(n,"qwen-code")}},Hu={type:"opencode",createContext(){return pt("opencode")}},zu={type:"codex",createContext(){return pt("codex")}},Bu={type:"api",createContext(){return pt("api")}},Ju={type:"unknown",createContext(){return pt("unknown")}},Ri={"claude-code":Uu,zcode:Du,pi:Fu,"qwen-code":ju,opencode:Hu,codex:zu,api:Bu,unknown:Ju}});import{get_encoding as Vu}from"tiktoken";import{readFile as or}from"fs/promises";import{opendir as Yu,stat as Xu}from"fs/promises";import{isAbsolute as Zu,join as rr}from"path";import{CLAUDE_PROJECTS_DIR as Ei,HOME_DIR as Ai,getClaudeProjectId as Oi,isZcodeProjectTakeoverActive as qu}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Ni(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=$i[r.code]||502;throw new te(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function cn(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function mt(n){let e=cn(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function td(n,e){if(!e||!n)return null;let t=cn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=cn(r);if(a&&t.includes(a))return s}return null}function nd(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function an(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function ft(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Ni(n,e){let t=an(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(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=rn(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=an(n);if(!i)return a?null:n;let{providerName:c,routeModel:l}=i,u=ft(e,c,l);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(c,l,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(c,l,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(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 p=rn(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,f=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||f)return null}return`${u.provider.name},${u.model}`}function Z(n,e,t,o,r,s){let a=[t?.[n],o?.[n]];for(let i of a)if(!(!Array.isArray(i)||i.length===0))for(let c of i){let l=Q(c,e,!1,n,void 0,void 0,s);if(l)return l}return null}function od(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function gt(n){let e=cn(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function Ui(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,nd(e))}function Di(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function rd(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??c??6e4,g=Ui(e,r,d),h=n.modelFamily,m=Di(d,t,l),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||g>m)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?Z("extendedContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let S=ee(n,t.extendedContext,o,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(g>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?Q(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${g}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?Z("longContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${g}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let S=ee(n,t.longContext,o,"longContext");if(S)return{model:S,scenarioType:"longContext",isFallback:!1}}n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(k=>k.type?.startsWith("web_search"))&&t.webSearch){let k=Q(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let T=i?Z("webSearch",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let S=ee(n,t.webSearch,o,"webSearch");if(S)return{model:S,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let k=Q(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let T=i?Z("think",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let S=ee(n,t.think,o,"think");if(S)return{model:S,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let k=Q(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let T=i?Z("default",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let S=ee(n,t.default,o,"default");if(S)return{model:S,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function ld(){if(we.size<=Ii)return;let n=[...we.keys()].slice(0,we.size-Ii);for(let e of n)we.delete(e)}function ud(){if(We.size<=Mi)return;let n=[...We].slice(0,We.size-Mi);for(let e of n)We.delete(e)}var $i,te,le,ln,ed,sd,un,we,Ii,We,Mi,id,ad,cd,Li,Fi,Pe=P(()=>{"use strict";on();re();Ce();Yt();tn();je();vi();Je();$i={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500,invalid_project_id:400,project_config_not_found:404},te=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||$i[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Vu("cl100k_base"),ln=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=le.encode(s.text).length;else if(s.type==="tool_use")o+=le.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=le.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=le.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},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 te(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Fi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Ti(n.sessionId);s&&qu(s)&&(r=Oi(s))}if(r){n.projectId=r;let s=rr(Ai,r,"config.json");if(!t&&n.sessionId){let a=rr(Ai,r,`${n.sessionId}.json`);try{let i=JSON.parse(await or(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await or(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Oi(a.projectPath)!==o))throw new te(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch(a){if(a instanceof te)throw a;if(t&&a?.code==="ENOENT")throw new te(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!a||a.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${a.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};sd=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),d=C[1])}let f=typeof n.body?.model=="string"?n.body.model:"",g=f.indexOf(",")>0,m=(g?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),y,b;if(!s&&m)for(let C of a){if(C?.enabled===!1||!Array.isArray(C?.models))continue;let A=C.models.find(x=>typeof x=="string"&&x.toLowerCase()===m);if(A){y=C,b=A;break}}let{family:_,extended:k,isCcrAlias:T}=mt(n.body.model),S=i?.families?.[_||""];if(S&&i?.enableFamilyRouting&&!y){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=S.fallback;let C=rd(n,e,S,a,o,k,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(C)return{model:C.model,scenarioType:C.scenarioType}}if(g&&y&&b){let C=`${y.name},${b}`;n.body.model!==C&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${C}`),n.body.model=C)}if(n.body.model.includes(",")&&!s){let C=Q(n.body.model,a,!1,"default",c,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let A=c?Z("default",a,void 0,u,void 0,s):null;if(A)return n.log.info(`Using fallback for explicit model: ${A}`),{model:A,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let v=T&&!i?.enableFamilyRouting?null:td(n.body.model,i?.models);if(v){let C=Q(v,a,!1,"modelMapping",c,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${v}`),{model:C,scenarioType:"modelMapping"};let A=c?Z("modelMapping",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"modelMapping"};if(s){let x=ee(n,v,a,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${v} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let w=n.clientContext,R=Ui(e,o,w),E=Di(w,void 0,i?.extendedContextThreshold);if(R>E&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${R}, estimated: ${e}, threshold: ${E}`);let C=Q(i.extendedContext,a,!1,"extendedContext",c,p,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let A=c?Z("extendedContext",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"extendedContext"};if(s){let x=ee(n,i.extendedContext,a,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext"}}}let I=w?.longContextThreshold??i?.longContextThreshold??6e4;if(R>I&&i?.longContext){n.log.info(`Using long context model due to token count: ${R}, estimated: ${e}, threshold: ${I}`);let C=Q(i.longContext,a,!1,"longContext",c,p,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let A=c?Z("longContext",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"longContext"};if(s){let x=ee(n,i.longContext,a,"longContext");if(x)return{model:x,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let C=Q(i.background,a,!1,"background",c,p,s);if(C)return{model:C,scenarioType:"background"};let A=c?Z("background",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"background"};if(s){let x=ee(n,i.background,a,"background");if(x)return{model:x,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&i?.webSearch){let C=Q(i.webSearch,a,!1,"webSearch",c,p,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let A=c?Z("webSearch",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"webSearch"};if(s){let x=ee(n,i.webSearch,a,"webSearch");if(x)return{model:x,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=Q(i.think,a,!1,"think",c,p,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let A=c?Z("think",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"think"};if(s){let x=ee(n,i.think,a,"think");if(x)return{model:x,scenarioType:"think"}}}if(i?.default){let C=Q(i.default,a,!1,"default",c,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let A=c?Z("default",a,void 0,u,void 0,s):null;if(A)return{model:A,scenarioType:"default"};let x=Q(i.default,a,!0,"default",c,p,s);if(x)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:x,scenarioType:"default"}}if(s){let C=ee(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},un=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,o.getAll());let s=await 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:p,system:d=[],tools:f}=n.body,g=o.get("REWRITE_SYSTEM_PROMPT");if(g&&d.length>1&&d[1]?.text?.includes("<env>")){let h=await or(g,"utf-8");d[1].text=`${h}<env>${d[1].text.split("<env>").pop()}`}try{let[h,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(h,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,h)).tokenCount:b=ln(p,d,f),n.tokenCount=b;let _,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!Zu(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),R=typeof w=="function"?w:w?.default;if(typeof R!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await R(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 sd(n,b,o,u,s,!!s);_=w.model,n.scenarioType=w.scenarioType}let{family:T}=mt(n.originalModel||n.body.model),S=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[S?.image,a?.image].filter((w,R,E)=>!!w&&E.indexOf(w)===R);if(v.length>0&&od(n)&&!gt(_))if(v.includes(_))n.scenarioType="image";else{let w=v.map(R=>Q(R,c,!1,"image",i,!l,l)).find(R=>!!R);if(w)n.log.info(`Using image model fallback for ${_}`),_=w,n.scenarioType="image";else{let R=i?Z("image",c,S?.fallback,n.fallbackConfig,T||void 0,l):null;if(R)n.log.info(`Using image fallback model: ${R}`),_=R,n.scenarioType="image";else if(l){let E=ee(n,v[0],c,"image");E&&(_=E,n.scenarioType="image")}else n.log.warn(`Image models ${v.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",R=[...(n.familyFallback||{})[w]||[],...(n.fallbackConfig||{})[w]||[]];_=di(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:R,resolve:E=>Q(E,c,!1,w,i,!l,l),log:E=>n.log.info(E)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(h){if(h instanceof te)throw h;if(n.log.error(`Error in router middleware: ${h.message}`),l){let m=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${h.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},we=new Map,Ii=1e3,We=new Set,Mi=1e3,id=3,ad=50,cd=n=>new Promise(e=>setTimeout(e,n));Li=async n=>{let e=await Yu(Ei),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=rr(Ei,s,`${n}.jsonl`);try{return(await Xu(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Fi=async n=>{let e=ge(n);if(!e)return null;if(we.has(e))return we.get(e)||null;try{let t=await Li(e);if(!t&&!We.has(e)){We.add(e),ud();for(let o=0;o<id&&!t;o++)await cd(ad),t=await Li(e)}return t?(we.set(e,t),ld(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
25
+ `))}}}R();let M=D();M&&C.enqueue(M),I="",C.close()}catch(S){C.error(S)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(c=>c.type==="message"),o;t?.content?.length&&t?.content[0].annotations&&(o=t.content[0].annotations.map(c=>({type:"url_citation",url_citation:{url:c.url||"",title:c.title||"",content:"",start_index:c.start_index||0,end_index:c.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let r=null,s=null,a=null;if(t&&t.reasoning&&(a={content:t.reasoning}),t&&t.content){let c=[],u=[];if(t.content.forEach(p=>{if(p.type==="output_text")c.push(p.text||"");else if(p.type==="output_image"){let d=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});d&&u.push(d)}else if(p.type==="output_image_base64"){let d=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});d&&u.push(d)}}),u.length>0){let p=[];c.length>0&&p.push({type:"text",text:c.join("")}),p.push(...u),r=p}else r=c.join("")}let i=(e.output??[]).filter(c=>c.type==="function_call");return i.length>0&&(s=i.map(c=>({id:c.call_id||c.id,type:"function",function:{name:c.name,arguments:c.arguments}}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:r||null,tool_calls:s,thinking:a,annotations:o},logprobs:null,finish_reason:s?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var Zo,Y,on=w(()=>{"use strict";Zo=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},Y=new Zo(100)});import{existsSync as bi,mkdirSync as uu,readFileSync as du,writeFileSync as pu}from"fs";import{join as ki}from"path";import{HOME_DIR as fu}from"@wengine-ai/claude-code-router-shared";function lt(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function rn(n){let e=Fe.get(n);return e?{...e}:void 0}function tr(){return Array.from(Fe.values()).map(n=>({...n}))}function mu(){try{if(!bi(er))return;let n=JSON.parse(du(er,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;Fe.set(t.provider,t)}}catch{}}function _i(){try{if(Fe.size===0)return;bi(qo)||uu(qo,{recursive:!0}),pu(er,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function ut(){hi||(hi=!0,mu(),yi=setInterval(_i,6e4),yi.unref?.(),process.on("exit",_i))}var qo,er,Fe,hi,yi,Ce=w(()=>{"use strict";qo=ki(fu,"runtime"),er=ki(qo,"quota-store.json"),Fe=new Map,hi=!1,yi=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!gu.test(e)))return e}function he(n){if(!n)return;if(typeof n=="object")return ge(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=ge(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return ge(e.slice(o+t.length))}var gu,je=w(()=>{"use strict";gu=/^[A-Za-z0-9_-]+$/});import{existsSync as xi}from"fs";import{readFile as hu,readdir as yu}from"fs/promises";import{homedir as _u}from"os";import{isAbsolute as bu,join as dt,normalize as ku}from"path";import{openSqliteDatabase as Tu}from"@wengine-ai/claude-code-router-shared";function Eu(){if(He.size<=Ti)return;let n=[...He.keys()].slice(0,He.size-Ti);for(let e of n)He.delete(e)}function Au(){if(ze.size<=vi)return;let n=[...ze].slice(0,ze.size-vi);for(let e of n)ze.delete(e)}function Ou(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 Iu(n,e){let t;try{t=Tu(n,{readonly:!0}).db;let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let a=o.get(r,r)?.workspace_path;if(typeof a=="string"&&a.trim())return a.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function Mu(n,e){let t;try{t=await yu(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(xi(s))try{let a=JSON.parse(await hu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Si(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=He.get(e);if(t)return t;let o=async()=>{let r=Ou(e);if(r.length===0)return null;let s=dt(vu(),xu),a=dt(s,Su);if(xi(a)){let i=Iu(a,r);if(i)return i}return Mu(dt(s,Cu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),Au();for(let a=0;a<Ru&&!r;a++)await Pu(wu),r=await o()}if(!r||!bu(r))return null;let s=ku(r);return He.set(e,s),Eu(),s}catch{return null}}var vu,xu,Su,Cu,Ti,vi,Ru,wu,He,ze,Pu,Ci=w(()=>{"use strict";vu=()=>process.env.CCR_ZCODE_DIR||dt(_u(),".zcode"),xu="v2",Su="tasks-index.sqlite",Cu="sessions",Ti=500,vi=500,Ru=3,wu=50,He=new Map,ze=new Set,Pu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as Lu}from"node:crypto";import{CCR_PROJECT_HEADER as nr}from"@wengine-ai/claude-code-router-shared";function Pi(n){return typeof n=="string"&&n.length<=$u}function Nu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of wi){let{value:t}=sn(n,e);if(!Pi(t))continue;let o=ge(t);if(o)return o}}function Du(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 Fu(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function sn(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function Ri(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function pt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function or(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Ai(n){return typeof n=="string"&&Uu.includes(n)}function Qu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(Ai(n?.clientType))return n.clientType;let e=Fu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Du(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(sn(n,nr).present||sn(n,"x-session-affinity").present)return"pi";if(Qu(t,o))return"zcode";let a=t["x-anthropic-billing-header"];if(typeof a=="string"&&a.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let i=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(i)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(i).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Oi(n){return Ei[n]}function Vu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||Lu();return n.__ccrRequestScopeId=e,e}function Re(n,e={}){let t=Be(n),o=Oi(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Vu(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,Ri(n,nr),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of wi)Ri(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Yu(){}var wi,$u,Uu,ju,Hu,zu,Bu,Ju,Wu,Ku,Gu,Ei,Je=w(()=>{"use strict";je();wi=["x-session-affinity","x-session-id","x-litellm-session-id"],$u=256;Uu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];ju={type:"claude-code",createContext(n){return or(n,"claude-code")}},Hu={type:"zcode",createContext(n){return or(n,"zcode")}},zu={type:"pi",createContext(n){let e=sn(n,nr),t=Nu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=Pi(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Bu={type:"qwen-code",createContext(n){return or(n,"qwen-code")}},Ju={type:"opencode",createContext(){return pt("opencode")}},Wu={type:"codex",createContext(){return pt("codex")}},Ku={type:"api",createContext(){return pt("api")}},Gu={type:"unknown",createContext(){return pt("unknown")}},Ei={"claude-code":ju,zcode:Hu,pi:zu,"qwen-code":Bu,opencode:Ju,codex:Wu,api:Ku,unknown:Gu}});import{get_encoding as Zu}from"tiktoken";import{readFile as rr}from"fs/promises";import{opendir as qu,stat as ed}from"fs/promises";import{isAbsolute as td,join as sr}from"path";import{CLAUDE_PROJECTS_DIR as Ii,HOME_DIR as Mi,getClaudeProjectId as Li,isZcodeProjectTakeoverActive as nd}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Fi(e,t);if(r.code==="model_unhealthy"){let i=Q(e,t,!0);if(i)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),i}let s=n.sessionId||n.clientContext?.stableSessionId,a=Di[r.code]||502;throw new te(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function cn(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function mt(n){let e=cn(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function rd(n,e){if(!e||!n)return null;let t=cn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=cn(r);if(a&&t.includes(a))return s}return null}function sd(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function an(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function ft(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Fi(n,e){let t=an(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(c=>c.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!H().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let l=rn(s.name);if(l){let c=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,u=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(c||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function Q(n,e,t,o,r,s,a){let i=an(n);if(!i)return a?null:n;let{providerName:l,routeModel:c}=i,u=ft(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(l,c,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(l,c,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(l,c,o)}}if(!t&&!H().isAvailable(u.provider.name,u.model,u.provider.apiKey?.startsWith("ccr-managed-")===!0||u.provider.api_key?.startsWith("ccr-managed-")===!0))return null;let p=rn(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,f=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||f)return null}return`${u.provider.name},${u.model}`}function Z(n,e,t,o,r,s){let a=[t?.[n],o?.[n]];for(let i of a)if(!(!Array.isArray(i)||i.length===0))for(let l of i){let c=Q(l,e,!1,n,void 0,void 0,s);if(c)return c}return null}function 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 gt(n){let e=cn(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function ji(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,sd(e))}function Hi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function ad(n,e,t,o,r,s,a,i,l,c,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??l??6e4,g=ji(e,r,d),h=n.modelFamily,m=Hi(d,t,c),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||g>m)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?Z("extendedContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let x=ee(n,t.extendedContext,o,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(g>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?Q(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${g}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?Z("longContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${g}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let x=ee(n,t.longContext,o,"longContext");if(x)return{model:x,scenarioType:"longContext",isFallback:!1}}n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(k=>k.type?.startsWith("web_search"))&&t.webSearch){let k=Q(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let T=i?Z("webSearch",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let x=ee(n,t.webSearch,o,"webSearch");if(x)return{model:x,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let k=Q(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let T=i?Z("think",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let x=ee(n,t.think,o,"think");if(x)return{model:x,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let k=Q(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let T=i?Z("default",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let x=ee(n,t.default,o,"default");if(x)return{model:x,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function pd(){if(we.size<=$i)return;let n=[...we.keys()].slice(0,we.size-$i);for(let e of n)we.delete(e)}function fd(){if(We.size<=Ni)return;let n=[...We].slice(0,We.size-Ni);for(let e of n)We.delete(e)}var Di,te,le,ln,od,cd,un,we,$i,We,Ni,ld,ud,dd,Ui,zi,Pe=w(()=>{"use strict";on();re();Ce();Yt();tn();je();Ci();Je();Di={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500,invalid_project_id:400,project_config_not_found:404},te=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Di[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Zu("cl100k_base"),ln=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=le.encode(s.text).length;else if(s.type==="tool_use")o+=le.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=le.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=le.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},od=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new te(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await zi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Si(n.sessionId);s&&nd(s)&&(r=Li(s))}if(r){n.projectId=r;let s=sr(Mi,r,"config.json");if(!t&&n.sessionId){let a=sr(Mi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await rr(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await rr(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Li(a.projectPath)!==o))throw new te(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch(a){if(a instanceof te)throw a;if(t&&a?.code==="ENOENT")throw new te(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!a||a.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${a.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};cd=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),l=i?.enableFallback===!0,c=l?i?.fallback:void 0,u=l&&!s?c||t.get("fallback"):c,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),d=C[1])}let f=typeof n.body?.model=="string"?n.body.model:"",g=f.indexOf(",")>0,m=(g?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),y,b;if(!s&&m)for(let C of a){if(C?.enabled===!1||!Array.isArray(C?.models))continue;let O=C.models.find(S=>typeof S=="string"&&S.toLowerCase()===m);if(O){y=C,b=O;break}}let{family:_,extended:k,isCcrAlias:T}=mt(n.body.model),x=i?.families?.[_||""];if(x&&i?.enableFamilyRouting&&!y){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=x.fallback;let C=ad(n,e,x,a,o,k,u,l,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(C)return{model:C.model,scenarioType:C.scenarioType}}if(g&&y&&b){let C=`${y.name},${b}`;n.body.model!==C&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${C}`),n.body.model=C)}if(n.body.model.includes(",")&&!s){let C=Q(n.body.model,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=l?Z("default",a,void 0,u,void 0,s):null;if(O)return n.log.info(`Using fallback for explicit model: ${O}`),{model:O,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let v=T&&!i?.enableFamilyRouting?null:rd(n.body.model,i?.models);if(v){let C=Q(v,a,!1,"modelMapping",l,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${v}`),{model:C,scenarioType:"modelMapping"};let O=l?Z("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let S=ee(n,v,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${v} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let P=n.clientContext,E=ji(e,o,P),R=Hi(P,void 0,i?.extendedContextThreshold);if(E>R&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${E}, estimated: ${e}, threshold: ${R}`);let C=Q(i.extendedContext,a,!1,"extendedContext",l,p,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=l?Z("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let S=ee(n,i.extendedContext,a,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext"}}}let A=P?.longContextThreshold??i?.longContextThreshold??6e4;if(E>A&&i?.longContext){n.log.info(`Using long context model due to token count: ${E}, estimated: ${e}, threshold: ${A}`);let C=Q(i.longContext,a,!1,"longContext",l,p,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=l?Z("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let S=ee(n,i.longContext,a,"longContext");if(S)return{model:S,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let C=Q(i.background,a,!1,"background",l,p,s);if(C)return{model:C,scenarioType:"background"};let O=l?Z("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let S=ee(n,i.background,a,"background");if(S)return{model:S,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&i?.webSearch){let C=Q(i.webSearch,a,!1,"webSearch",l,p,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=l?Z("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let S=ee(n,i.webSearch,a,"webSearch");if(S)return{model:S,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=Q(i.think,a,!1,"think",l,p,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=l?Z("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let S=ee(n,i.think,a,"think");if(S)return{model:S,scenarioType:"think"}}}if(i?.default){let C=Q(i.default,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=l?Z("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let S=Q(i.default,a,!0,"default",l,p,s);if(S)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:S,scenarioType:"default"}}if(s){let C=ee(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},un=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,o.getAll());let s=await od(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=i,n.strictProjectRouting=c,n.fallbackConfig=c?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Y.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:f}=n.body,g=o.get("REWRITE_SYSTEM_PROMPT");if(g&&d.length>1&&d[1]?.text?.includes("<env>")){let h=await rr(g,"utf-8");d[1].text=`${h}<env>${d[1].text.split("<env>").pop()}`}try{let[h,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(h,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,h)).tokenCount:b=ln(p,d,f),n.tokenCount=b;let _,k=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!td(k)||!/\.(c|m)?js$/i.test(k))throw new Error(`CUSTOM_ROUTER_PATH must be an absolute .js/.cjs/.mjs path, got: ${String(k).slice(0,120)}`);let P=await import(k),E=typeof P=="function"?P:P?.default;if(typeof E!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await E(n,o.getAll(),{event:r})}catch(P){n.log.error(`failed to load custom router: ${P.message}`)}if(_)n.scenarioType="default";else{let P=await cd(n,b,o,u,s,!!s);_=P.model,n.scenarioType=P.scenarioType}let{family:T}=mt(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[x?.image,a?.image].filter((P,E,R)=>!!P&&R.indexOf(P)===E);if(v.length>0&&id(n)&&!gt(_))if(v.includes(_))n.scenarioType="image";else{let P=v.map(E=>Q(E,l,!1,"image",i,!c,c)).find(E=>!!E);if(P)n.log.info(`Using image model fallback for ${_}`),_=P,n.scenarioType="image";else{let E=i?Z("image",l,x?.fallback,n.fallbackConfig,T||void 0,c):null;if(E)n.log.info(`Using image fallback model: ${E}`),_=E,n.scenarioType="image";else if(c){let R=ee(n,v[0],l,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let P=n.scenarioType||"default",E=[...(n.familyFallback||{})[P]||[],...(n.fallbackConfig||{})[P]||[]];_=mi(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:E,resolve:R=>Q(R,l,!1,P,i,!c,c),log:R=>n.log.info(R)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(h){if(h instanceof te)throw h;if(n.log.error(`Error in router middleware: ${h.message}`),c){let m=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${h.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},we=new Map,$i=1e3,We=new Set,Ni=1e3,ld=3,ud=50,dd=n=>new Promise(e=>setTimeout(e,n));Ui=async n=>{let e=await qu(Ii),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=sr(Ii,s,`${n}.jsonl`);try{return(await ed(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},zi=async n=>{let e=ge(n);if(!e)return null;if(we.has(e))return we.get(e)||null;try{let t=await Ui(e);if(!t&&!We.has(e)){We.add(e),fd();for(let o=0;o<ld&&!t;o++)await dd(ud),t=await Ui(e)}return t?(we.set(e,t),pd(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
26
26
  `):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
27
- ${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function Hi(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Eo(n);let s=gd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&dd.test(r.model)&&await un(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let a=n.provider;if(!a&&r?.model){let l=r.model.split(",");l.length>1&&(a=l[0],r.model=l.slice(1).join(","))}let i=a?t.providerService.getProvider(a):void 0;if(!i&&r?.model){let l=t.providerService.resolveModelRoute(r.model);l&&(i=l.provider,r.model=l.targetModel)}if(!i&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[p,...d]=u.split(","),f=t.providerService.getProvider(p);f&&(i=f,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw K(`Provider '${a}' not found`,404,"provider_not_found");n.provider=i.name||a;let c=o.endPoint==="/v1/messages"&&s;s&&e.header("X-Codex-Detected","true"),c&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=c;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&ht(r);let l={req:n,isCodexOnMessagesEndpoint:c,responseTargetFormat:Ji(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Bi(r,i,o,n.headers,l);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let T=JSON.stringify(k.content??"");y.has(T)||(y.add(T),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await Wi(u,p,i,t,d,o,l);try{i?.baseUrl&&f?.headers&&it(a,i.baseUrl,f.headers)}catch{}let g=await Ki(u,f,i,o,d,l);g=await zi(r,g,i.name||a);let h=Gi(g,e,r,t);try{let m=r.model||n.originalModel;a&&m&&H().recordSuccess(a,m)}catch{}return h}catch(l){if(l instanceof te)throw l;if(!Ao(n,t.pluginRegistry.getManagedRuntimeFor(i),l,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Hi(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;l=d}}let p=await pd(n,e,t,o,l);if(p)return p;throw n.__fallbackExhausted=!0,l}}async function zi(n,e,t){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let s=e.body.getReader(),a=new TextDecoder,i=[],c="";for(let d=0;d<8;d++){let f=await s.read();if(f.done||(f.value&&(i.push(f.value),c+=a.decode(f.value,{stream:!0})),c.split(`
28
- `).some(g=>g.startsWith("data:"))))break}if(c+=a.decode(),i.length===0)throw s.releaseLock(),K(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(c.includes("event: error")){s.releaseLock();let d=c.length<500?c:c.slice(0,500);throw K(`Provider ${t} returned error in SSE stream: ${d}`,400,"provider_response_error")}if(c.split(`
29
- `).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=c.length<500?c:c.slice(0,500);throw K(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let g of i)d.enqueue(g);let f=()=>{s.read().then(({done:g,value:h})=>{g?d.close():(d.enqueue(h),f())}).catch(g=>d.error(g))};f()},cancel:()=>{s.cancel()}}),p=await Js(u);if(p.verdict==="empty")throw K(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(Ws(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function pd(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,c=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),l=H(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&dn(r.rawBody)||r?.message&&dn(r.message);if(u&&p&&(f?(l.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):l.recordFailure(u,p,r?.message),d.add(`${u},${p}`),t.recordUsage?.({provider:u,model:p,originalModel:n.originalModel||p,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let h=b=>{let[_,...k]=b.split(","),T=_?.trim(),S=k.join(",").trim();return!T||!S?null:{provider:T,model:S,key:`${T},${S}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(c?.[s])&&c[s].length>0&&m.push({name:`global/${s}`,models:c[s]}),m.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(S=>S.type==="image"||S.type==="image_url")))&&Array.isArray(c?.image)&&c.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),m.push({name:"global/image (auto-detected)",models:c.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=h(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let T=t.providerService.getProviders(),S=ft(T,k.provider,k.model);if(!S){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let v=S.provider.name,w=S.model;if(!l.isAvailable(v,w,S.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let R=t.pluginRegistry.getManagedRuntimeFor(S.provider);if(R&&$e(n,R,{name:v}).terminalError)continue;let E;for(let I=1;I<=2;I++)try{n.log.info(`Trying fallback model: ${v},${w}${I>1?" (retry)":""}`);let U={...n.body};U.model=w;let C={...n,provider:v,body:U},A=S.provider,x={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Ji(C,o,C.codexDetected===!0)},{requestBody:O,config:M,bypass:N}=await Bi(U,A,o,n.headers,x),L=await Wi(O,M,A,t,N,o,x);try{A?.baseUrl&&L?.headers&&it(v,A.baseUrl,L.headers)}catch{}let F=await Ki(O,L,A,o,N,x);return F=await zi(U,F,v),n.log.info(`Fallback model ${v},${w} succeeded`),l.recordSuccess(v,w),u&&p&&!n.strictProjectRouting&&(Ne().promote(u,p,s,v,w),n.log.info(`Promoted fallback model ${v},${w} for ${u},${p}:${s}`),f?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(l.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=v,n.body=U,ui(n,`${v},${w}`),Gi(F,e,U,t)}catch(U){if(E=U,Ao(n,R,U,{name:v}))break;if(I===1){n.log.warn(`Fallback model ${v},${w} failed, retrying once: ${U.message}`);continue}}l.recordFailure(v,w,E?.message),n.log.warn(`Fallback model ${v},${w} failed after retry: ${E?.message}`),t.recordUsage?.({provider:v,model:w,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:E?.message||String(E),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Bi(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw K("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=$e(r.req,s,e).terminalError;if(u)throw u;await s.ensureUsable?.()}let a=JSON.parse(JSON.stringify(n)),i=a?.system;if(typeof i=="string"&&i.includes("cch="))a.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let u=0;u<i.length;u++){let p=i[u],d=typeof p=="string"?p:p?.text??"";if(d.includes("cch=")){let f=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?i[u]=f:typeof p?.text=="string"&&(p.text=f)}}let c={},l=!1;if(l=fd(e,t,n),l&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],c.headers=o),!l&&typeof t.transformRequestOut=="function"){let u=await t.transformRequestOut(a);u.body?(a=u.body,c=u.config||{}):a=u}if(!l&&e.transformer?.use?.length)for(let u of e.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let p=await u.transformRequestIn(a,e,r);p.body?(a=p.body,c={...c,...p.config}):a=p}if(!l&&e.transformer?.[n.model]?.use?.length)for(let u of e.transformer[n.model].use)!u||typeof u.transformRequestIn!="function"||(a=await u.transformRequestIn(a,e,r));return{requestBody:a,config:c,bypass:l}}function fd(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 md(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 Ji(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function gd(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 Wi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>ji(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):ji(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 ji(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);i&&(await i.ensureUsable?.(),await i.lockUpstream?.(e,t));let c=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let d=o.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(r&&typeof s.auth=="function"){let d=await s.auth(n,t,a);if(d.body){n=d.body;let f=e.headers||{};d.config?.headers&&(f={...f,...d.config.headers},delete f.host,delete d.config.headers),e={...e,...d.config,headers:f}}else n=d}let l={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(l=await i.signRequest({headers:l,requestBody:n,provider:t,config:e})),md(l,a?.req);for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];!i?.suppressDebugLog&&Jt(o.configService)&&Ds(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>Hs(c,n,{...e,headers:JSON.parse(JSON.stringify(l)),httpsProxy:i?void 0:de(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await ve(i,0,void 0,Ke(n),Vs(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!$e(a.req,i,t).refreshUsed){$e(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(g){throw i?await ve(i,u.status,void 0,Ke(n)):g}if(i){let g=await ve(i,u.status,d,Ke(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${g.code}`),g}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let f=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||dn(d),f.rawBody=d,f}if(u.ok){let d=u.headers.get("content-type")||"",f=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${f} contentType=${d} ok=${u.ok} status=${u.status} hasBody=${!!u.body}`),!f||d.includes("application/json")){let g="";try{if(g=await u.clone().text(),!g||g.trim()==="")throw new SyntaxError("Empty JSON body");if(ct(g))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let m=JSON.parse(g);if(i?.isErrorEnvelope?.(m))throw await ve(i,u.status,g,Ke(n));if(m&&typeof m=="object"&&m.error&&(typeof m.error=="string"||typeof m.error=="object"&&Object.keys(m.error).length>0)){if(i)throw await ve(i,u.status,g,Ke(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let b=dn(g),_=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${g}`,400,"provider_response_error");throw _.isRateLimit=b,_.rawBody=g,_}}catch(h){if(i)throw h?.pluginClassified===!0?h:await ve(i,u.status,void 0,Ke(n));if(h instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let m=K(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw m.rawBody=g,m}throw h}}}if(!i?.suppressDebugLog&&!n.stream&&Jt(o.configService)){let f=await u.clone().text();Fs(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Ki(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 Gi(n,e,t,o){n.ok||e.code(n.status);let r=pi(n);if(!r){let s=await pe(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let a=await me(n);n=a.response,a.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Jt(o.configService)){let[s,a]=n.body.tee(),i=Us(o.configService);return js(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function dn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function hd(n){try{return new URL(n),!0}catch{return!1}}var dd,Qi,pn=P(()=>{"use strict";zs();zt();Ks();Gs();Ys();rt();Lo();re();Se();Yt();tn();Yo();V();Pe();q();dd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Qi=async n=>{n.get("/",async()=>({message:"LLMs API",version:Vt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:H().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Hi(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw K("Provider name is required",400,"invalid_request");if(!s||!hd(s))throw K("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw K("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw K("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw K(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw K("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw K("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw K("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw K("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ge,sr=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 ye,fn,Vi,yd,Yi,Qe=P(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",fn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Vi=["low","medium","high"],yd={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"},Yi=n=>{if(typeof n=="string")return yd[n.trim().toLowerCase()]}});var ir,Xi=P(()=>{ir=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function _d(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Zi(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let g=t[f],h=g?.text??JSON.stringify(g),m=d.get(h);if(m===void 0){d.set(h,f);continue}!t[m]?.cache_control&&g?.cache_control&&(t[m]=g),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let g=f.content;try{typeof f.content=="string"&&(g=JSON.parse(f.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let h={type:"tool_result",tool_use_id:f.tool_call_id,content:g};f.cache_control&&(h.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(h):s.push({role:"user",content:[h]})}else if(f.role==="user"){let g=[];typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?g.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):g.push(m)});let h=s[s.length-1];h&&h.role==="user"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let g=[];f.content&&(typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&g.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}g.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&g.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let h=s[s.length-1];h&&h.role==="assistant"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(g=>g?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},c=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let g=f.find(h=>h?.cache_control);if(g?.cache_control)return g.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},l=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(h=>h?.cache_control))return!1;let g=d.content.find(h=>h&&typeof h=="object"&&!h.cache_control);return g?(g.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,g=c(),h=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||h.push(m);for(let m of h){if(d<=0)break;l(f[m],g)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||fn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let g=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Vi.includes(g)&&(p.output_config={...p.output_config||{},effort:g})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
27
+ ${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function Ji(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Ao(n);let s=_d(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&md.test(r.model)&&await un(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let a=n.provider;if(!a&&r?.model){let c=r.model.split(",");c.length>1&&(a=c[0],r.model=c.slice(1).join(","))}let i=a?t.providerService.getProvider(a):void 0;if(!i&&r?.model){let c=t.providerService.resolveModelRoute(r.model);c&&(i=c.provider,r.model=c.targetModel)}if(!i&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[p,...d]=u.split(","),f=t.providerService.getProvider(p);f&&(i=f,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw K(`Provider '${a}' not found`,404,"provider_not_found");n.provider=i.name||a;let l=o.endPoint==="/v1/messages"&&s;s&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=l;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&ht(r);let c={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:Gi(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Ki(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let T=JSON.stringify(k.content??"");y.has(T)||(y.add(T),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await Qi(u,p,i,t,d,o,c);try{i?.baseUrl&&f?.headers&&it(a,i.baseUrl,f.headers)}catch{}let g=await Vi(u,f,i,o,d,c);g=await Wi(r,g,i.name||a);let h=Yi(g,e,r,t);try{let m=r.model||n.originalModel;a&&m&&H().recordSuccess(a,m)}catch{}return h}catch(c){if(c instanceof te)throw c;if(!Oo(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Ji(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await gd(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function Wi(n,e,t){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let s=e.body.getReader(),a=new TextDecoder,i=[],l="";for(let d=0;d<8;d++){let f=await s.read();if(f.done||(f.value&&(i.push(f.value),l+=a.decode(f.value,{stream:!0})),l.split(`
28
+ `).some(g=>g.startsWith("data:"))))break}if(l+=a.decode(),i.length===0)throw s.releaseLock(),K(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(l.includes("event: error")){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned error in SSE stream: ${d}`,400,"provider_response_error")}if(l.split(`
29
+ `).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let g of i)d.enqueue(g);let f=()=>{s.read().then(({done:g,value:h})=>{g?d.close():(d.enqueue(h),f())}).catch(g=>d.error(g))};f()},cancel:()=>{s.cancel()}}),p=await Gs(u);if(p.verdict==="empty")throw K(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(Qs(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function gd(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),c=H(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&dn(r.rawBody)||r?.message&&dn(r.message);if(u&&p&&(f?(c.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):c.recordFailure(u,p,r?.message),d.add(`${u},${p}`),t.recordUsage?.({provider:u,model:p,originalModel:n.originalModel||p,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let h=b=>{let[_,...k]=b.split(","),T=_?.trim(),x=k.join(",").trim();return!T||!x?null:{provider:T,model:x,key:`${T},${x}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(x=>x.type==="image"||x.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=h(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let T=t.providerService.getProviders(),x=ft(T,k.provider,k.model);if(!x){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let v=x.provider.name,P=x.model;if(!c.isAvailable(v,P,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let E=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(E&&$e(n,E,{name:v}).terminalError)continue;let R;for(let A=1;A<=2;A++)try{n.log.info(`Trying fallback model: ${v},${P}${A>1?" (retry)":""}`);let D={...n.body};D.model=P;let C={...n,provider:v,body:D},O=x.provider,S={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Gi(C,o,C.codexDetected===!0)},{requestBody:I,config:M,bypass:N}=await Ki(D,O,o,n.headers,S),L=await Qi(I,M,O,t,N,o,S);try{O?.baseUrl&&L?.headers&&it(v,O.baseUrl,L.headers)}catch{}let F=await Vi(I,L,O,o,N,S);return F=await Wi(D,F,v),n.log.info(`Fallback model ${v},${P} succeeded`),c.recordSuccess(v,P),u&&p&&!n.strictProjectRouting&&(Ne().promote(u,p,s,v,P),n.log.info(`Promoted fallback model ${v},${P} for ${u},${p}:${s}`),f?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(c.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=v,n.body=D,fi(n,`${v},${P}`),Yi(F,e,D,t)}catch(D){if(R=D,Oo(n,E,D,{name:v}))break;if(A===1){n.log.warn(`Fallback model ${v},${P} failed, retrying once: ${D.message}`);continue}}c.recordFailure(v,P,R?.message),n.log.warn(`Fallback model ${v},${P} failed after retry: ${R?.message}`),t.recordUsage?.({provider:v,model:P,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:R?.message||String(R),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Ki(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw K("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=$e(r.req,s,e).terminalError;if(u)throw u;await s.ensureUsable?.()}let a=JSON.parse(JSON.stringify(n)),i=a?.system;if(typeof i=="string"&&i.includes("cch="))a.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let u=0;u<i.length;u++){let p=i[u],d=typeof p=="string"?p:p?.text??"";if(d.includes("cch=")){let f=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?i[u]=f:typeof p?.text=="string"&&(p.text=f)}}let l={},c=!1;if(c=hd(e,t,n),c&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!c&&typeof t.transformRequestOut=="function"){let u=await t.transformRequestOut(a);u.body?(a=u.body,l=u.config||{}):a=u}if(!c&&e.transformer?.use?.length)for(let u of e.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let p=await u.transformRequestIn(a,e,r);p.body?(a=p.body,l={...l,...p.config}):a=p}if(!c&&e.transformer?.[n.model]?.use?.length)for(let u of e.transformer[n.model].use)!u||typeof u.transformRequestIn!="function"||(a=await u.transformRequestIn(a,e,r));return{requestBody:a,config:l,bypass:c}}function 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 yd(n,e){if(e?.clientType!=="pi")return;let t=e?.clientContext?.stableSessionId;if(!(typeof t!="string"||!t)){for(let o of Object.keys(n))o.toLowerCase()==="x-litellm-session-id"&&delete n[o];n["x-litellm-session-id"]=t}}function Gi(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function _d(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Qi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>Bi(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):Bi(n,e,t,o,r,s,a)}function Ke(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
30
+ `):""}async function Bi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);i&&(await i.ensureUsable?.(),await i.lockUpstream?.(e,t));let l=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let d=o.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(r&&typeof s.auth=="function"){let d=await s.auth(n,t,a);if(d.body){n=d.body;let f=e.headers||{};d.config?.headers&&(f={...f,...d.config.headers},delete f.host,delete d.config.headers),e={...e,...d.config,headers:f}}else n=d}let c={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(c=await i.signRequest({headers:c,requestBody:n,provider:t,config:e})),yd(c,a?.req);for(let d in c)(c[d]==="undefined"||["authorization","Authorization"].includes(d)&&c[d]?.includes("undefined"))&&delete c[d];!i?.suppressDebugLog&&Jt(o.configService)&&Hs(o.log,a.req.id,{url:String(l),headers:c,body:n});let u,p=()=>Js(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:i?void 0:de(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await ve(i,0,void 0,Ke(n),Zs(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!$e(a.req,i,t).refreshUsed){$e(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),c=await i.signRequest({headers:c,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(g){throw i?await ve(i,u.status,void 0,Ke(n)):g}if(i){let g=await ve(i,u.status,d,Ke(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${g.code}`),g}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let f=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||dn(d),f.rawBody=d,f}if(u.ok){let d=u.headers.get("content-type")||"",f=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${f} contentType=${d} ok=${u.ok} status=${u.status} hasBody=${!!u.body}`),!f||d.includes("application/json")){let g="";try{if(g=await u.clone().text(),!g||g.trim()==="")throw new SyntaxError("Empty JSON body");if(ct(g))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let m=JSON.parse(g);if(i?.isErrorEnvelope?.(m))throw await ve(i,u.status,g,Ke(n));if(m&&typeof m=="object"&&m.error&&(typeof m.error=="string"||typeof m.error=="object"&&Object.keys(m.error).length>0)){if(i)throw await ve(i,u.status,g,Ke(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let b=dn(g),_=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${g}`,400,"provider_response_error");throw _.isRateLimit=b,_.rawBody=g,_}}catch(h){if(i)throw h?.pluginClassified===!0?h:await ve(i,u.status,void 0,Ke(n));if(h instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let m=K(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw m.rawBody=g,m}throw h}}}if(!i?.suppressDebugLog&&!n.stream&&Jt(o.configService)){let f=await u.clone().text();zs(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Vi(n,e,t,o,r,s){let a=e;if(!r&&t.transformer?.use?.length)for(let i of Array.from(t.transformer.use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let i of Array.from(t.transformer[n.model].use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),a=await o.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new De().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function Yi(n,e,t,o){n.ok||e.code(n.status);let r=gi(n);if(!r){let s=await pe(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let a=await me(n);n=a.response,a.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Jt(o.configService)){let[s,a]=n.body.tee(),i=js(o.configService);return Bs(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function dn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function bd(n){try{return new URL(n),!0}catch{return!1}}var md,Xi,pn=w(()=>{"use strict";Ws();zt();Vs();Ys();qs();rt();$o();re();Se();Yt();tn();Xo();V();Pe();q();md=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Xi=async n=>{n.get("/",async()=>({message:"LLMs API",version:Vt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:H().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Ji(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw K("Provider name is required",400,"invalid_request");if(!s||!bd(s))throw K("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw K("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw K("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw K(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw K("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw K("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw K("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw K("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ge,ir=w(()=>{"use strict";Ge=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var ye,fn,Zi,kd,qi,Qe=w(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",fn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Zi=["low","medium","high"],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"},qi=n=>{if(typeof n=="string")return kd[n.trim().toLowerCase()]}});var ar,ea=w(()=>{ar=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Td(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ta(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let g=t[f],h=g?.text??JSON.stringify(g),m=d.get(h);if(m===void 0){d.set(h,f);continue}!t[m]?.cache_control&&g?.cache_control&&(t[m]=g),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let g=f.content;try{typeof f.content=="string"&&(g=JSON.parse(f.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let h={type:"tool_result",tool_use_id:f.tool_call_id,content:g};f.cache_control&&(h.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(h):s.push({role:"user",content:[h]})}else if(f.role==="user"){let g=[];typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?g.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):g.push(m)});let h=s[s.length-1];h&&h.role==="user"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let g=[];f.content&&(typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&g.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}g.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&g.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let h=s[s.length-1];h&&h.role==="assistant"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(g=>g?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},l=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let g=f.find(h=>h?.cache_control);if(g?.cache_control)return g.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},c=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(h=>h?.cache_control))return!1;let g=d.content.find(h=>h&&typeof h=="object"&&!h.cache_control);return g?(g.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,g=l(),h=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||h.push(m);for(let m of h){if(d<=0)break;c(f[m],g)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||fn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let g=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Zi.includes(g)&&(p.output_config={...p.output_config||{},effort:g})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
31
31
 
32
- `)}return n.tools&&n.tools.length>0&&(p.tools=_d(n.tools),n.tool_choice&&(n.tool_choice==="auto"?p.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?p.tool_choice={type:"any"}:typeof n.tool_choice=="string"?p.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:n.tool_choice.function.name}))),p}var qi=P(()=>{Qe()});function bd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function mn(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Ee(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:bd(n),cache_creation_input_tokens:mn(n)}}function Ae(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,...r.usage_estimated===!0||o.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var gn=P(()=>{"use strict"});import{v4 as ar}from"uuid";function kd(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 cr(n){if(!n||typeof n!="object")return!1;let e=n;return e.usage_source==="kiro"||e.usage_estimated===!0||e.kiro_estimated===!0}var hn,ea=P(()=>{"use strict";Qe();zt();V();Xi();qi();Pe();gn();hn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(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=gt(String(e.model??"")),p=[];c.forEach(d=>{let f=Array.isArray(d.content)?d.content:null,g=f?f.filter(y=>y?.type==="image"&&y?.source):[],h=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(g.length>0){let y=f.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
32
+ `)}return n.tools&&n.tools.length>0&&(p.tools=Td(n.tools),n.tool_choice&&(n.tool_choice==="auto"?p.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?p.tool_choice={type:"any"}:typeof n.tool_choice=="string"?p.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:n.tool_choice.function.name}))),p}var na=w(()=>{Qe()});function vd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function mn(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Ee(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:vd(n),cache_creation_input_tokens:mn(n)}}function Ae(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,...r.usage_estimated===!0||o.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var gn=w(()=>{"use strict"});import{v4 as cr}from"uuid";function xd(n){if(n===!0)return!0;if(n===!1)return!1;if(typeof n!="string")return;let e=n.trim().toLowerCase();if(e==="enabled"||e==="adaptive"||e==="true")return!0;if(e==="disabled"||e==="off"||e==="none"||e==="false")return!1}function lr(n){if(!n||typeof n!="object")return!1;let e=n;return e.usage_source==="kiro"||e.usage_estimated===!0||e.kiro_estimated===!0}var hn,oa=w(()=>{"use strict";Qe();zt();V();ea();na();Pe();gn();hn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(l=>l.type==="text"&&l.text).map(l=>({type:"text",text:l.text,cache_control:l.cache_control}));t.push({role:"system",content:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let l=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(l.length){let u=gt(String(e.model??"")),p=[];l.forEach(d=>{let f=Array.isArray(d.content)?d.content:null,g=f?f.filter(y=>y?.type==="image"&&y?.source):[],h=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(g.length>0){let y=f.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
33
33
  `);u?(h=y||"[tool image]",p.push(...g)):(h=[y,...g.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
34
- `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:g.length}))}let m={role:"tool",content:h,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?ir(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let l=i.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);l.length&&t.push({role:"user",content:l.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?ir(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let c={role:"assistant",content:""},l=i.content.filter(d=>d.type==="text"&&d.text);l.length&&(c.content=l.map(d=>d.text).join(`
35
- `));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(c.tool_calls=u.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let p=i.content.find(d=>d.type==="thinking");p&&(c.thinking={content:p.thinking,signature:p.signature}),t.push(c)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice},s=Yi(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=kd(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=ye(a)),a!==void 0&&a>0&&(i.max_tokens=a),Object.keys(i).length>0&&(r.reasoning=i)}return e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=Zi(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let r=await this.convertOpenAIStreamToAnthropic(e.body,t);return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let r=await pe(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 me(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,p=!1;t?.req&&(t.req.contentDelivered=!1);let d=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,g=new Map,h=0,m=0,y=0,b=!1,_=!1,k=0,T=-1,S=()=>{let E=k;return k++,E},v=E=>{if(!b)try{r.enqueue(E);let I=new TextDecoder().decode(E);this.logger.debug({reqId:t.req.id,data:I,type:"send data"})}catch(I){if(I instanceof TypeError&&I.message.includes("Controller is already closed"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:I instanceof Error?I.message:String(I),type:"send data error"}),I}},w=()=>{if(!b)try{if(!l){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(T>=0){let I={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
36
- data: ${JSON.stringify(I)}
34
+ `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:g.length}))}let m={role:"tool",content:h,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?ar(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let c=i.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);c.length&&t.push({role:"user",content:c.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?ar(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let l={role:"assistant",content:""},c=i.content.filter(d=>d.type==="text"&&d.text);c.length&&(l.content=c.map(d=>d.text).join(`
35
+ `));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(l.tool_calls=u.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let p=i.content.find(d=>d.type==="thinking");p&&(l.thinking={content:p.thinking,signature:p.signature}),t.push(l)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice},s=qi(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},c=xd(e.thinking?.type)??(s!==void 0||(a??0)>0);c!==void 0&&(i.enabled=c),s!==void 0?i.effort=s:a!==void 0&&(i.effort=ye(a)),a!==void 0&&a>0&&(i.max_tokens=a),Object.keys(i).length>0&&(r.reasoning=i)}return e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=ta(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let r=await this.convertOpenAIStreamToAnthropic(e.body,t);return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let r=await pe(e);if((r?.isSSE??!1)&&r?.body){let c=await this.convertOpenAIStreamToAnthropic(r.body,t);return new Response(c,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let a;if(r?.body)a=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else{let c=await me(e);if(c.isSSE){let u=await this.convertOpenAIStreamToAnthropic(c.response.body,t);return new Response(u,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}a=c.response}let i=await j(a),l=this.convertOpenAIResponseToAnthropic(i,t);return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,a=`msg_${Date.now()}`,i=null,l=String(t?.req?.body?.model??"unknown"),c=!1,u=!1,p=!1;t?.req&&(t.req.contentDelivered=!1);let d=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,g=new Map,h=0,m=0,y=0,b=!1,_=!1,k=0,T=-1,x=()=>{let R=k;return k++,R},v=R=>{if(!b)try{r.enqueue(R);let A=new TextDecoder().decode(R);this.logger.debug({reqId:t.req.id,data:A,type:"send data"})}catch(A){if(A instanceof TypeError&&A.message.includes("Controller is already closed"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:A instanceof Error?A.message:String(A),type:"send data error"}),A}},P=()=>{if(!b)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(T>=0){let A={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
36
+ data: ${JSON.stringify(A)}
37
37
 
38
38
  `)),T=-1}if(i)v(s.encode(`event: message_delta
39
39
  data: ${JSON.stringify(i)}
40
40
 
41
- `)),i=null;else{let I=t?.req?.tokenCount||0;v(s.encode(`event: message_delta
42
- data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:I,output_tokens:0,cache_read_input_tokens:0}})}
41
+ `)),i=null;else{let A=t?.req?.tokenCount||0;v(s.encode(`event: message_delta
42
+ 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}})}
43
43
 
44
- `))}let E={type:"message_stop"};v(s.encode(`event: message_stop
45
- data: ${JSON.stringify(E)}
44
+ `))}let R={type:"message_stop"};v(s.encode(`event: message_stop
45
+ data: ${JSON.stringify(R)}
46
46
 
47
- `)),r.close(),b=!0}catch(E){if(E instanceof TypeError&&E.message.includes("Controller is already closed"))b=!0;else throw E}},R=null;try{R=e.getReader();let E=new TextDecoder,I="";for(;!b;){let{done:U,value:C}=await R.read();if(U)break;I+=E.decode(C,{stream:!0});let A=I.split(`
48
- `);I=A.pop()||"";for(let x of A){if(b)break;if(!x.startsWith("data:"))continue;let O=x.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:O}),O!=="[DONE]")try{let M=JSON.parse(O);if(h++,this.logger.debug({reqId:t.req.id,response:M,tppe:"Original Response"}),M.error){t?.req&&(t.req.sseError=M.error);let L={type:"error",message:{type:"api_error",message:JSON.stringify(M.error)}};v(s.encode(`event: error
47
+ `)),r.close(),b=!0}catch(R){if(R instanceof TypeError&&R.message.includes("Controller is already closed"))b=!0;else throw R}},E=null;try{E=e.getReader();let R=new TextDecoder,A="";for(;!b;){let{done:D,value:C}=await E.read();if(D)break;A+=R.decode(C,{stream:!0});let O=A.split(`
48
+ `);A=O.pop()||"";for(let S of O){if(b)break;if(!S.startsWith("data:"))continue;let I=S.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:I}),I!=="[DONE]")try{let M=JSON.parse(I);if(h++,this.logger.debug({reqId:t.req.id,response:M,tppe:"Original Response"}),M.error){t?.req&&(t.req.sseError=M.error);let L={type:"error",message:{type:"api_error",message:JSON.stringify(M.error)}};v(s.encode(`event: error
49
49
  data: ${JSON.stringify(L)}
50
50
 
51
- `));continue}if(c=M.model&&M.model!=="unknown"?M.model:c,!l&&!b&&!p){l=!0;let L=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:c,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};v(s.encode(`event: message_start
51
+ `));continue}if(l=M.model&&M.model!=="unknown"?M.model:l,!c&&!b&&!p){c=!0;let L=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};v(s.encode(`event: message_start
52
52
  data: ${JSON.stringify(F)}
53
53
 
54
- `))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,J=(M.usage?.prompt_tokens||0)-L,ce=M.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:M.usage,mappedUsage:{input_tokens:J,output_tokens:ce,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let B={input_tokens:J,output_tokens:ce,cache_read_input_tokens:L,...cr(M.usage)?{cache_creation_input_tokens:mn(M.usage)}:{},...M.usage.kiro_estimated===!0||M.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...B}};else{let z=i.usage||{};cr(M.usage)||"cache_creation_input_tokens"in z?i.usage=Ae(z,B,!1):i.usage={input_tokens:B.input_tokens||z.input_tokens||0,output_tokens:B.output_tokens||z.output_tokens||0,cache_read_input_tokens:B.cache_read_input_tokens||z.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!b&&!p&&!u){if(!_){let L=S();d();let F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};v(s.encode(`event: content_block_start
54
+ `))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,J=(M.usage?.prompt_tokens||0)-L,ce=M.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:M.usage,mappedUsage:{input_tokens:J,output_tokens:ce,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let B={input_tokens:J,output_tokens:ce,cache_read_input_tokens:L,...lr(M.usage)?{cache_creation_input_tokens:mn(M.usage)}:{},...M.usage.kiro_estimated===!0||M.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...B}};else{let z=i.usage||{};lr(M.usage)||"cache_creation_input_tokens"in z?i.usage=Ae(z,B,!1):i.usage={input_tokens:B.input_tokens||z.input_tokens||0,output_tokens:B.output_tokens||z.output_tokens||0,cache_read_input_tokens:B.cache_read_input_tokens||z.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!b&&!p&&!u){if(!_){let L=x();d();let F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};v(s.encode(`event: content_block_start
55
55
  data: ${JSON.stringify(F)}
56
56
 
57
57
  `)),T=L,_=!0}if(N.delta.thinking.signature){let L={type:"content_block_delta",index:T,delta:{type:"signature_delta",signature:N.delta.thinking.signature}};v(s.encode(`event: content_block_delta
@@ -66,7 +66,7 @@ data: ${JSON.stringify(L)}
66
66
  `))}}if(N?.delta?.content&&!b&&!p){if(m++,T>=0&&!u){let F={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
67
67
  data: ${JSON.stringify(F)}
68
68
 
69
- `)),T=-1}if(!u&&!p){u=!0;let L=S();d();let F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};v(s.encode(`event: content_block_start
69
+ `)),T=-1}if(!u&&!p){u=!0;let L=x();d();let F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};v(s.encode(`event: content_block_start
70
70
  data: ${JSON.stringify(F)}
71
71
 
72
72
  `)),T=L}if(!b&&!p){let L={type:"content_block_delta",index:T,delta:{type:"text_delta",text:N.delta.content}};v(s.encode(`event: content_block_delta
@@ -75,19 +75,19 @@ data: ${JSON.stringify(L)}
75
75
  `))}}if(N?.delta?.annotations?.length&&!b&&!p){if(T>=0&&u){let L={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
76
76
  data: ${JSON.stringify(L)}
77
77
 
78
- `)),T=-1,u=!1}N?.delta?.annotations.forEach(L=>{let F=S();d();let J={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${ar()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};v(s.encode(`event: content_block_start
78
+ `)),T=-1,u=!1}N?.delta?.annotations.forEach(L=>{let F=x();d();let J={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${cr()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};v(s.encode(`event: content_block_start
79
79
  data: ${JSON.stringify(J)}
80
80
 
81
81
  `));let ce={type:"content_block_stop",index:F};v(s.encode(`event: content_block_stop
82
82
  data: ${JSON.stringify(ce)}
83
83
 
84
- `)),T=-1})}if(N?.delta?.tool_calls&&!b&&!p){y++;let L=new Set;for(let F of N.delta.tool_calls){if(b)break;let J=F.index??0;if(L.has(J))continue;if(L.add(J),!g.has(J)){if(T>=0){let ul={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
85
- data: ${JSON.stringify(ul)}
84
+ `)),T=-1})}if(N?.delta?.tool_calls&&!b&&!p){y++;let L=new Set;for(let F of N.delta.tool_calls){if(b)break;let J=F.index??0;if(L.has(J))continue;if(L.add(J),!g.has(J)){if(T>=0){let fl={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
85
+ data: ${JSON.stringify(fl)}
86
86
 
87
- `)),T=-1}let B=S();g.set(J,B);let z=F.id||`call_ccr_${J}`,$=F.function?.name||`tool_${J}`;d();let W={type:"content_block_start",index:B,content_block:{type:"tool_use",id:z,name:$,input:{}}};v(s.encode(`event: content_block_start
87
+ `)),T=-1}let B=x();g.set(J,B);let z=F.id||`call_ccr_${J}`,$=F.function?.name||`tool_${J}`;d();let W={type:"content_block_start",index:B,content_block:{type:"tool_use",id:z,name:$,input:{}}};v(s.encode(`event: content_block_start
88
88
  data: ${JSON.stringify(W)}
89
89
 
90
- `)),T=B;let ll={id:z,name:$,arguments:"",contentBlockIndex:B};f.set(J,ll)}else if(F.id&&F.function?.name){let B=f.get(J);B.id.startsWith("call_")&&B.name.startsWith("tool_")&&(B.id=F.id,B.name=F.function.name)}if(F.function?.arguments&&!b&&!p){let B=g.get(J);if(B===void 0)continue;let z=f.get(J);z&&(z.arguments+=F.function.arguments);try{let $={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:F.function.arguments}};v(s.encode(`event: content_block_delta
90
+ `)),T=B;let pl={id:z,name:$,arguments:"",contentBlockIndex:B};f.set(J,pl)}else if(F.id&&F.function?.name){let B=f.get(J);B.id.startsWith("call_")&&B.name.startsWith("tool_")&&(B.id=F.id,B.name=F.function.name)}if(F.function?.arguments&&!b&&!p){let B=g.get(J);if(B===void 0)continue;let z=f.get(J);z&&(z.arguments+=F.function.arguments);try{let $={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:F.function.arguments}};v(s.encode(`event: content_block_delta
91
91
  data: ${JSON.stringify($)}
92
92
 
93
93
  `))}catch{try{let $=F.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),W={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:$}};v(s.encode(`event: content_block_delta
@@ -96,99 +96,105 @@ data: ${JSON.stringify(W)}
96
96
  `))}catch($){console.error($)}}}}}if(N?.finish_reason&&!b&&!p){if(m===0&&y===0&&console.error("Warning: No content in the stream response!"),T>=0){let L={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
97
97
  data: ${JSON.stringify(L)}
98
98
 
99
- `)),T=-1}if(!b){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[N.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:F,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(M){this.logger?.error(`parseError: ${M.name} message: ${M.message} stack: ${M.stack} data: ${O}`)}}}w()}catch(E){if(!b)try{r.error(E)}catch(I){console.error(I)}}finally{if(R)try{R.releaseLock()}catch(E){console.error(E)}}},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_${ar()}`;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_${ar().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:cr(e.usage)?mn(e.usage):0,...e.usage?.kiro_estimated===!0||e.usage?.usage_estimated===!0?{usage_estimated:!0}:{},cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw K(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Td(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ve).includes(o)?o:Ve.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ve).includes(r)?r:Ve.TYPE_UNSPECIFIED})}}}function yt(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&Td(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(Ve).includes(c)?c:Ve.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=yt(i);else if(o.includes(a)){let c=[];for(let l of i){if(l.type=="null"){e.nullable=!0;continue}c.push(yt(l))}e[a]=c}else if(r.includes(a)){let c={};for(let[l,u]of Object.entries(i))c[l]=yt(u);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=i}return e}function vd(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=yt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=yt(e.response));return n}function yn(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(vd({functionDeclarations:t})),n.tools?.find(c=>c.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(c=>c.role==="tool");n.messages.filter(c=>c.role!=="tool").forEach(c=>{let l;c.role==="assistant"?l="model":(["user","system"].includes(c.role),l="user");let u=[];if(typeof c.content=="string"){let p={text:c.content};c.thinking?.signature&&(p.thoughtSignature=c.thinking.signature),u.push(p)}else Array.isArray(c.content)?u.push(...c.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):c.content&&typeof c.content=="object"&&(c.content.text?u.push({text:c.content.text}):u.push({text:JSON.stringify(c.content)}));if(Array.isArray(c.tool_calls)&&u.push(...c.tool_calls.map(p=>{let d={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return c.thinking?.signature&&(d.thoughtSignature=c.thinking.signature),d})),u.length===0&&u.push({text:""}),r.push({role:l,parts:u}),l==="model"&&c.tool_calls){let p=c.tool_calls.map(d=>{let f=s.find(g=>g.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let 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 _n(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,c={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};return Array.isArray(e)&&e.forEach(l=>{typeof l=="string"?c.messages.push({role:"user",content:l}):typeof l.text=="string"?c.messages.push({role:"user",content:l.text||null}):l.role==="user"?c.messages.push({role:"user",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):l.role==="model"&&c.messages.push({role:"assistant",content:l?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(c.tools=[],t.forEach(l=>{Array.isArray(l.functionDeclarations)&&l.functionDeclarations.forEach(u=>{c.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),c}async function bn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],i=[];for(let p of a)p.text&&p.thought===!0?r+=p.text:i.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let c=i?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],l=i?.filter(p=>p.text)?.map(p=>p.text)?.join(`
100
- `)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:l,role:"assistant",tool_calls:c.length>0?c:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,c="",l=0,u=-1,p=new ReadableStream({async start(d){let f=async(m,y)=>{if(m.startsWith("data: ")){let b=m.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],T=k.content?.parts||[];T.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let E={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"};y.enqueue(r.encode(`data: ${JSON.stringify(E)}
99
+ `)),T=-1}if(!b){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[N.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:F,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(M){this.logger?.error(`parseError: ${M.name} message: ${M.message} stack: ${M.stack} data: ${I}`)}}}P()}catch(R){if(!b)try{r.error(R)}catch(A){console.error(A)}}finally{if(E)try{E.releaseLock()}catch(R){console.error(R)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let l=`srvtoolu_${cr()}`;r.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:l,content:o.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(l=>{let c={};try{let u=l.function.arguments||"{}";typeof u=="object"?c=u:typeof u=="string"&&(c=JSON.parse(u))}catch{c={text:l.function.arguments||""}}r.push({type:"tool_use",id:l.id,name:l.function.name,input:c})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens??e.usage?.prompt_cache_hit_tokens??0,a=(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${cr().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:lr(e.usage)?mn(e.usage):0,...e.usage?.kiro_estimated===!0||e.usage?.usage_estimated===!0?{usage_estimated:!0}:{},cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw K(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Sd(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ve).includes(o)?o:Ve.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ve).includes(r)?r:Ve.TYPE_UNSPECIFIED})}}}function yt(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&Sd(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let l=i.toUpperCase();e.type=Object.values(Ve).includes(l)?l:Ve.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=yt(i);else if(o.includes(a)){let l=[];for(let c of i){if(c.type=="null"){e.nullable=!0;continue}l.push(yt(c))}e[a]=l}else if(r.includes(a)){let l={};for(let[c,u]of Object.entries(i))l[c]=yt(u);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=i}return e}function Cd(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=yt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=yt(e.response));return n}function _n(n){let e=[],t=n.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));t?.length&&e.push(Cd({functionDeclarations:t})),n.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(l=>l.role==="tool");n.messages.filter(l=>l.role!=="tool").forEach(l=>{let c;l.role==="assistant"?c="model":(["user","system"].includes(l.role),c="user");let u=[];if(typeof l.content=="string"){let p={text:l.content};l.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),u.push(p)}else Array.isArray(l.content)?u.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?u.push({text:l.content.text}):u.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&u.push(...l.tool_calls.map(p=>{let d={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return l.thinking?.signature&&(d.thoughtSignature=l.thinking.signature),d})),u.length===0&&u.push({text:""}),r.push({role:c,parts:u}),c==="model"&&l.tool_calls){let p=l.tool_calls.map(d=>{let f=s.find(g=>g.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let l=n.model.includes("pro")?[128,32768]:[0,24576],c,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=l[0]&&u<=l[1]?c=u:u<l[0]?c=l[0]:u>l[1]&&(c=l[1]),a.thinkingConfig.thinkingBudget=c)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};if(n.tool_choice){let l={functionCallingConfig:{}};n.tool_choice==="auto"?l.functionCallingConfig.mode="auto":n.tool_choice==="none"?l.functionCallingConfig.mode="none":n.tool_choice==="required"?l.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),i.toolConfig=l}return i}function bn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,l={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};return Array.isArray(e)&&e.forEach(c=>{typeof c=="string"?l.messages.push({role:"user",content:c}):typeof c.text=="string"?l.messages.push({role:"user",content:c.text||null}):c.role==="user"?l.messages.push({role:"user",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):c.role==="model"&&l.messages.push({role:"assistant",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(l.tools=[],t.forEach(c=>{Array.isArray(c.functionDeclarations)&&c.functionDeclarations.forEach(u=>{l.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),l}function yn(n){return{completion_tokens:n?.candidatesTokenCount||0,prompt_tokens:n?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n?.cachedContentTokenCount||0},total_tokens:n?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n?.thoughtsTokenCount||0}}}function dr(n){if(n?.groundingMetadata?.groundingChunks?.length)return n.groundingMetadata.groundingChunks.map((e,t)=>{let o=n?.groundingMetadata?.groundingSupports?.filter(r=>r.groundingChunkIndices?.includes(t));return{type:"url_citation",url_citation:{url:e?.web?.uri||"",title:e?.web?.title||"",content:o?.[0]?.segment?.text||"",start_index:o?.[0]?.segment?.startIndex||0,end_index:o?.[0]?.segment?.endIndex||0}}})}function ur(n,e,t){let o=e?dr(e):void 0,r=e?.finishReason?.toLowerCase()||null;return{choices:r||o?[{delta:o?{role:"assistant",annotations:o}:{},finish_reason:r,index:t,logprobs:null}]:[],created:parseInt(new Date().getTime()/1e3+"",10),id:n.responseId||"",model:n.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...n.usageMetadata?{usage:yn(n.usageMetadata)}:{}}}async function kn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],i=[];for(let p of a)p.text&&p.thought===!0?r+=p.text:i.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=i?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],c=i?.filter(p=>p.text)?.map(p=>p.text)?.join(`
100
+ `)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:c,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:yn(o.usageMetadata)};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,l="",c=0,u=-1,p=new ReadableStream({async start(d){let f=async(m,y)=>{if(m.startsWith("data: ")){let b=m.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){if(_.usageMetadata){y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,void 0,c))}
101
101
 
102
- `))});let S=T.find(R=>R.thoughtSignature)?.thoughtSignature;if(S&&!s){if(!i){let E={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"};y.enqueue(r.encode(`data: ${JSON.stringify(E)}
102
+ `));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],T=!1,x=k.content?.parts||[];x.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:R.text}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
103
103
 
104
- `))}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(y.enqueue(r.encode(`data: ${JSON.stringify(R)}
104
+ `))});let v=x.find(R=>R.thoughtSignature)?.thoughtSignature;if(v&&!s){if(!i){let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
105
105
 
106
- `)),s=!0,l++,c){let E={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"};y.enqueue(r.encode(`data: ${JSON.stringify(E)}
106
+ `))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:v}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(R)}
107
107
 
108
- `)),c="",a||(a=!0)}}let v=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||{})}})),w=T.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
109
- `);if(!w&&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"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
108
+ `)),s=!0,c++,l){let A={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
110
109
 
111
- `)),a||(a=!0)}if(i&&w&&!s)if(_.modelVersion.includes("3")){c+=w;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"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
110
+ `)),l="",a||(a=!0)}}let P=x.filter(R=>R.functionCall).map(R=>({id:R.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:R.functionCall?.name,arguments:JSON.stringify(R.functionCall?.args||{})}})),E=x.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
111
+ `);if(!E&&s&&!a){let R={choices:[{delta:{role:"assistant",content:"(no content)"},index:c,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
112
112
 
113
- `)),s=!0}if(w){c||l++;let R={choices:[{delta:{role:"assistant",content:w},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:{completion_tokens:_.usageMetadata?.candidatesTokenCount||0,prompt_tokens:_.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:_.usageMetadata?.cachedContentTokenCount||0},total_tokens:_.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:_.usageMetadata?.thoughtsTokenCount||0}}};k?.groundingMetadata?.groundingChunks?.length&&(R.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((E,I)=>{let U=k?.groundingMetadata?.groundingSupports?.filter(C=>C.groundingChunkIndices?.includes(I));return{type:"url_citation",url_citation:{url:E?.web?.uri||"",title:E?.web?.title||"",content:U?.[0]?.segment?.text||"",start_index:U?.[0]?.segment?.startIndex||0,end_index:U?.[0]?.segment?.endIndex||0}}})),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
113
+ `)),a||(a=!0)}if(i&&E&&!s)if(_.modelVersion?.includes("3")){l+=E,_.usageMetadata&&y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,k,c))}
114
114
 
115
- `)),!a&&w&&(a=!0)}v.length>0&&(v.forEach(R=>{l++,u++;let E={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:{completion_tokens:_.usageMetadata?.candidatesTokenCount||0,prompt_tokens:_.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:_.usageMetadata?.cachedContentTokenCount||0},total_tokens:_.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:_.usageMetadata?.thoughtsTokenCount||0}}};k?.groundingMetadata?.groundingChunks?.length&&(E.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((I,U)=>{let C=k?.groundingMetadata?.groundingSupports?.filter(A=>A.groundingChunkIndices?.includes(U));return{type:"url_citation",url_citation:{url:I?.web?.uri||"",title:I?.web?.title||"",content:C?.[0]?.segment?.text||"",start_index:C?.[0]?.segment?.startIndex||0,end_index:C?.[0]?.segment?.endIndex||0}}})),y.enqueue(r.encode(`data: ${JSON.stringify(E)}
115
+ `));return}else{let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
116
116
 
117
- `))}),!a&&w&&(a=!0))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},g=n.body.getReader(),h="";try{for(;;){let{done:m,value:y}=await g.read();if(m){h&&await f(h,d);break}h+=o.decode(y,{stream:!0});let b=h.split(`
118
- `);h=b.pop()||"";for(let _ of b)await f(_,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ve,lr=P(()=>{"use strict";Ve={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var kn,ta=P(()=>{"use strict";lr();kn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:yn(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=_n;async transformResponseOut(e){return bn(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:
117
+ `)),s=!0}if(E){l||c++;let R={choices:[{delta:{role:"assistant",content:E},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:yn(_.usageMetadata)},A=dr(k);A&&(R.choices[0].delta.annotations=A),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
118
+
119
+ `)),T=!0,!a&&E&&(a=!0)}P.length>0&&(P.forEach(R=>{c++,u++;let A={choices:[{delta:{role:"assistant",tool_calls:[{...R,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:yn(_.usageMetadata)},D=dr(k);D&&(A.choices[0].delta.annotations=D),y.enqueue(r.encode(`data: ${JSON.stringify(A)}
120
+
121
+ `)),T=!0}),!a&&E&&(a=!0)),!T&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,k,c))}
122
+
123
+ `))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},g=n.body.getReader(),h="";try{for(;;){let{done:m,value:y}=await g.read();if(m){h&&await f(h,d);break}h+=o.decode(y,{stream:!0});let b=h.split(`
124
+ `);h=b.pop()||"";for(let _ of b)await f(_,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ve,pr=w(()=>{"use strict";Ve={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var Tn,ra=w(()=>{"use strict";pr();Tn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:_n(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=bn;async transformResponseOut(e){return kn(e,this.name,this.logger)}}});async function Rd(){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:
119
125
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
120
126
  2. Run "gcloud auth application-default login"
121
- 3. Use Google Cloud environment with default service account`)}}var Tn,na=P(()=>{"use strict";lr();Tn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),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:yn(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 _n(e)}async transformResponseOut(e){return bn(e,this.name)}}});var vn,oa=P(()=>{"use strict";V();vn=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=(d,f,g)=>{let h=d.split(`
127
+ 3. Use Google Cloud environment with default service account`)}}var vn,sa=w(()=>{"use strict";pr();vn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Rd();return{body:_n(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return bn(e)}async transformResponseOut(e){return kn(e,this.name)}}});var xn,ia=w(()=>{"use strict";V();xn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,i="";if(typeof r.content=="string"){let c=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);c&&(i=c[1].trim(),r.content=r.content.replace(c[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
122
128
  `);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
123
129
  `))},p=(d,f)=>{let{controller:g,encoder:h}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
124
130
 
125
131
  `;g.enqueue(h.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
126
132
 
127
- `;g.enqueue(h.encode(k));let T={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete T.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(T)}
133
+ `;g.enqueue(h.encode(k));let T={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete T.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(T)}
128
134
 
129
- `;g.enqueue(h.encode(S));return}if(m.choices[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){let y=`data: ${JSON.stringify(m)}
135
+ `;g.enqueue(h.encode(x));return}if(m.choices[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){let y=`data: ${JSON.stringify(m)}
130
136
 
131
137
  `;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
132
138
  `))}else g.enqueue(h.encode(d+`
133
- `))};try{for(;;){let{done:d,value:f}=await l.read();if(d){a.trim()&&u(a,c,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
134
- `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),c.enqueue(o.encode(m+`
135
- `))}}}catch(d){console.error("Stream error:",d),c.error(d)}finally{try{l.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var xn,ra=P(()=>{"use strict";V();xn=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.
139
+ `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
140
+ `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
141
+ `))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Sn,aa=w(()=>{"use strict";V();Sn=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
136
142
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
137
143
  Examples:
138
144
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
139
- 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=(d,f,g)=>{let h=d.split(`
145
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
140
146
  `);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
141
- `))},p=(d,f)=>{let{controller:g,encoder:h,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let T=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:T.response||""}}];let S=`data: ${JSON.stringify(_)}
147
+ `))},p=(d,f)=>{let{controller:g,encoder:h,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let T=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:T.response||""}}];let x=`data: ${JSON.stringify(_)}
142
148
 
143
- `;g.enqueue(h.encode(S))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
149
+ `;g.enqueue(h.encode(x))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
144
150
 
145
151
  `;g.enqueue(h.encode(k))}}catch{g.enqueue(h.encode(d+`
146
152
  `))}else g.enqueue(h.encode(d+`
147
- `))};try{for(;;){let{done:d,value:f}=await l.read();if(d){a.trim()&&u(a,c,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
148
- `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:c,encoder:o,exitToolIndex:()=>r,setExitToolIndex:y=>r=y,exitToolResponse:()=>s,appendExitToolResponse:y=>s+=y})}catch(y){console.error("Error processing line:",m,y),c.enqueue(o.encode(m+`
149
- `))}}}catch(d){console.error("Stream error:",d),c.error(d)}finally{try{l.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as Sd}from"uuid";var Sn,sa=P(()=>{"use strict";V();Sn=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 p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
153
+ `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
154
+ `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,exitToolIndex:()=>r,setExitToolIndex:y=>r=y,exitToolResponse:()=>s,appendExitToolResponse:y=>s+=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
155
+ `))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as wd}from"uuid";var Cn,ca=w(()=>{"use strict";V();Cn=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
150
156
  `);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
151
157
  `))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
152
158
 
153
- `));return}_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let k=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(k){h.appendReasoningContent(k);let R={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content);let E=`data: ${JSON.stringify(R)}
159
+ `));return}_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let k=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(k){h.appendReasoningContent(k);let E={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let R=`data: ${JSON.stringify(E)}
154
160
 
155
- `;m.enqueue(y.encode(E));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let R="ccr_think_signature",E=_.choices[0].delta.content,I={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:R}}}]};I.choices?.[0]?.delta&&delete I.choices[0].delta.reasoning;let U=`data: ${JSON.stringify(I)}
161
+ `;m.enqueue(y.encode(R));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let E="ccr_think_signature",R=_.choices[0].delta.content,A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:E}}}]};A.choices?.[0]?.delta&&delete A.choices[0].delta.reasoning;let D=`data: ${JSON.stringify(A)}
156
162
 
157
- `;m.enqueue(y.encode(U));let C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:E}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let A=`data: ${JSON.stringify(C)}
163
+ `;m.enqueue(y.encode(D));let C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:R}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let O=`data: ${JSON.stringify(C)}
158
164
 
159
- `;m.enqueue(y.encode(A));return}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${Sd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let T=_.choices?.[0]?.delta,S=T&&Object.keys(T).length>0,v=_.choices?.[0]?.finish_reason,w=_.usage;if(S||v||w){let R=`data: ${JSON.stringify(_)}
165
+ `;m.enqueue(y.encode(O));return}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(E=>{E.id=`call_${wd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let T=_.choices?.[0]?.delta,x=T&&Object.keys(T).length>0,v=_.choices?.[0]?.finish_reason,P=_.usage;if(x||v||P){let E=`data: ${JSON.stringify(_)}
160
166
 
161
- `;m.enqueue(y.encode(R))}}catch{m.enqueue(y.encode(g+`
167
+ `;m.enqueue(y.encode(E))}}catch{m.enqueue(y.encode(g+`
162
168
  `))}}else m.enqueue(y.encode(g+`
163
- `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){c.trim()&&d(c,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(c+=m,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
164
- `);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(_+`
165
- `))}continue}let y=c.split(`
166
- `);c=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
167
- `))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Cn,ia=P(()=>{"use strict";Cn=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 Cd}from"uuid";var Rn,aa=P(()=>{"use strict";V();Rn=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(),p=(f,g,h)=>{let m=f.split(`
169
+ `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
170
+ `);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
171
+ `))}continue}let y=l.split(`
172
+ `);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
173
+ `))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Rn,la=w(()=>{"use strict";Rn=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});import{v4 as Pd}from"uuid";var wn,ua=w(()=>{"use strict";V();wn=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i="",l=new ReadableStream({async start(c){let u=e.body.getReader(),p=(f,g,h)=>{let m=f.split(`
168
174
  `);for(let y of m)y.trim()&&g.enqueue(h.encode(y+`
169
- `))},d=(f,g)=>{let{controller:h,encoder:m}=g;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let b=JSON.parse(y);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${Cd()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let _=`data: ${JSON.stringify(b)}
175
+ `))},d=(f,g)=>{let{controller:h,encoder:m}=g;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let b=JSON.parse(y);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${Pd()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let _=`data: ${JSON.stringify(b)}
170
176
 
171
177
  `;h.enqueue(m.encode(_))}catch{h.enqueue(m.encode(f+`
172
178
  `))}}else h.enqueue(m.encode(f+`
173
- `))};try{for(;;){let{done:f,value:g}=await u.read();if(f){i.trim()&&p(i,l,o);break}if(!g||g.length===0)continue;let h;try{h=t.decode(g,{stream:!0})}catch(y){console.warn("Failed to decode chunk",y);continue}if(h.length===0)continue;if(i+=h,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let y=i.split(`
174
- `);i=y.pop()||"";for(let b of y)if(b.trim())try{d(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+`
179
+ `))};try{for(;;){let{done:f,value:g}=await u.read();if(f){i.trim()&&p(i,c,o);break}if(!g||g.length===0)continue;let h;try{h=t.decode(g,{stream:!0})}catch(y){console.warn("Failed to decode chunk",y);continue}if(h.length===0)continue;if(i+=h,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let y=i.split(`
180
+ `);i=y.pop()||"";for(let b of y)if(b.trim())try{d(b,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),c.enqueue(o.encode(b+`
175
181
  `))}continue}let m=i.split(`
176
- `);i=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{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:",y,b),l.enqueue(o.encode(y+`
177
- `))}}}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 wn,ca=P(()=>{"use strict";wn=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 Rd from"json5";import{jsonrepair as wd}from"jsonrepair";function ur(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=Rd.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=wd(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 la=P(()=>{});var Pn,ua=P(()=>{"use strict";la();V();Pn=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=ur(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,c=!1,l="",u=new ReadableStream({async start(p){let d=e.body.getReader(),f=(m,y,b)=>{let _=m.split(`
182
+ `);i=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",y,b),c.enqueue(o.encode(y+`
183
+ `))}}}catch(f){console.error("Stream error:",f),c.error(f)}finally{try{u.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Pn,da=w(()=>{"use strict";Pn=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),e}}});import Ed from"json5";import{jsonrepair as Ad}from"jsonrepair";function fr(n,e){if(!n||n.trim()===""||n==="{}")return"{}";try{return JSON.parse(n),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),n}catch(t){try{let o=Ed.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=Ad(n);return e?.debug("Tool arguments safely repaired"),r}catch(r){return e?.error(`JSON parsing failed: ${t.message}. JSON5 parsing failed: ${o.message}. JSON repair failed: ${r.message}. Input data: ${JSON.stringify(n)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var pa=w(()=>{});var En,fa=w(()=>{"use strict";pa();V();En=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);if(t?.choices?.[0]?.message?.tool_calls?.length)for(let o of t.choices[0].message.tool_calls)o.function?.arguments&&(o.function.arguments=fr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,l=!1,c="",u=new ReadableStream({async start(p){let d=e.body.getReader(),f=(m,y,b)=>{let _=m.split(`
178
184
  `);for(let k of _)k.trim()&&y.enqueue(b.encode(k+`
179
- `))},g=(m,y,b)=>{let _="";try{_=ur(r.arguments||"",this.logger)}catch(v){console.error(`${v.message} ${v.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},T={...m,choices:[{...m.choices[0],delta:k}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let S=`data: ${JSON.stringify(T)}
185
+ `))},g=(m,y,b)=>{let _="";try{_=fr(r.arguments||"",this.logger)}catch(v){console.error(`${v.message} ${v.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},T={...m,choices:[{...m.choices[0],delta:k}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let x=`data: ${JSON.stringify(T)}
180
186
 
181
- `;y.enqueue(b.encode(S))},h=(m,y)=>{let{controller:b,encoder:_}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.slice(6);try{let T=JSON.parse(k);if(T.choices?.[0]?.delta?.tool_calls?.length){let v=T.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""},v.function?.arguments&&(v.function.arguments="");let w=`data: ${JSON.stringify(T)}
187
+ `;y.enqueue(b.encode(x))},h=(m,y)=>{let{controller:b,encoder:_}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.slice(6);try{let T=JSON.parse(k);if(T.choices?.[0]?.delta?.tool_calls?.length){let v=T.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""},v.function?.arguments&&(v.function.arguments="");let P=`data: ${JSON.stringify(T)}
182
188
 
183
- `;b.enqueue(_.encode(w));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{g(T,b,_),r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){g(T,b,_),r={};return}T.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let S=`data: ${JSON.stringify(T)}
189
+ `;b.enqueue(_.encode(P));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{g(T,b,_),r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){g(T,b,_),r={};return}T.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let x=`data: ${JSON.stringify(T)}
184
190
 
185
- `;b.enqueue(_.encode(S))}catch{b.enqueue(_.encode(m+`
191
+ `;b.enqueue(_.encode(x))}catch{b.enqueue(_.encode(m+`
186
192
  `))}}else b.enqueue(_.encode(m+`
187
- `))};try{for(;;){let{done:m,value:y}=await d.read();if(m){l.trim()&&f(l,p,o);break}if(!y||y.length===0)continue;let b;try{b=t.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(b.length===0)continue;if(l+=b,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
188
- `);l=k.pop()||"";for(let T of k)if(T.trim())try{h(T,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:S=>s=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>i,setReasoningComplete:S=>i=S})}catch(S){console.error("Error processing line:",T,S),p.enqueue(o.encode(T+`
189
- `))}continue}let _=l.split(`
190
- `);l=_.pop()||"";for(let k of _)if(k.trim())try{h(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",k,T),p.enqueue(o.encode(k+`
191
- `))}}}catch(m){console.error("Stream error:",m),p.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}p.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var En,da=P(()=>{"use strict";V();Qe();En=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens??fn(e.reasoning.effort||"medium")},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(c){let l=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
193
+ `))};try{for(;;){let{done:m,value:y}=await d.read();if(m){c.trim()&&f(c,p,o);break}if(!y||y.length===0)continue;let b;try{b=t.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(b.length===0)continue;if(c+=b,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
194
+ `);c=k.pop()||"";for(let T of k)if(T.trim())try{h(T,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>i,setReasoningComplete:x=>i=x})}catch(x){console.error("Error processing line:",T,x),p.enqueue(o.encode(T+`
195
+ `))}continue}let _=c.split(`
196
+ `);c=_.pop()||"";for(let k of _)if(k.trim())try{h(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",k,T),p.enqueue(o.encode(k+`
197
+ `))}}}catch(m){console.error("Stream error:",m),p.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}p.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var An,ma=w(()=>{"use strict";V();Qe();An=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens??fn(e.reasoning.effort||"medium")},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
192
198
  `);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
193
199
  `))},p=(d,f)=>{let{controller:g,encoder:h}=f;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(console.log(JSON.stringify(m)),m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
194
200
 
@@ -198,109 +204,109 @@ Examples:
198
204
 
199
205
  `;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
200
206
  `))}else g.enqueue(h.encode(d+`
201
- `))};try{for(;;){let{done:d,value:f}=await l.read();if(d){a.trim()&&u(a,c,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
202
- `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:c,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),c.enqueue(o.encode(m+`
203
- `))}}}catch(d){console.error("Stream error:",d),c.error(d)}finally{try{l.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}c.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var An,pa=P(()=>{"use strict";An=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 On,fa=P(()=>{"use strict";On=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ma(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 ga(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 ha(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,c)=>{if(i.startsWith("data: ")){let l=i.slice(6).trim();if(l){t?.debug({chunkStr:l},`${e} chunk:`);try{let u=JSON.parse(l);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
207
+ `))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
208
+ `);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
209
+ `))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var On,ga=w(()=>{"use strict";On=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var In,ha=w(()=>{"use strict";In=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ya(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(l=>{l.type==="text"?i.push({type:"text",text:l.text||""}):l.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function _a(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function ba(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,l)=>{if(i.startsWith("data: ")){let c=i.slice(6).trim();if(c){t?.debug({chunkStr:c},`${e} chunk:`);try{let u=JSON.parse(c);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
204
210
 
205
- `))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
211
+ `))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
206
212
 
207
- `))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
213
+ `))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
208
214
 
209
- `))}else if(u.type==="message_delta"){let p={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
215
+ `))}else if(u.type==="message_delta"){let p={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
210
216
 
211
- `))}else if(u.type==="message_stop")c.enqueue(r.encode(`data: [DONE]
217
+ `))}else if(u.type==="message_stop")l.enqueue(r.encode(`data: [DONE]
212
218
 
213
- `));else{let p={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};c.enqueue(r.encode(`data: ${JSON.stringify(p)}
219
+ `));else{let p={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
214
220
 
215
- `))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,l,u.message)}}}},a=new ReadableStream({async start(i){let c=n.body.getReader(),l="";try{for(;;){let{done:u,value:p}=await c.read();if(u){l&&s(l,i);break}l+=o.decode(p,{stream:!0});let d=l.split(`
216
- `);l=d.pop()||"";for(let f of d)s(f,i)}}catch(u){i.error(u)}finally{i.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var ya=P(()=>{"use strict"});async function Pd(){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:
221
+ `))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,c,u.message)}}}},a=new ReadableStream({async start(i){let l=n.body.getReader(),c="";try{for(;;){let{done:u,value:p}=await l.read();if(u){c&&s(c,i);break}c+=o.decode(p,{stream:!0});let d=c.split(`
222
+ `);c=d.pop()||"";for(let f of d)s(f,i)}}catch(u){i.error(u)}finally{i.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var ka=w(()=>{"use strict"});async function Od(){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:
217
223
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
218
224
  2. Run "gcloud auth application-default login"
219
- 3. Use Google Cloud environment with default service account`)}}var In,_a=P(()=>{"use strict";ya();In=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 Pd();return{body:ma(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 ga(e)}async transformResponseOut(e){return ha(e,this.name,this.logger)}}});var Mn,ba=P(()=>{"use strict";Mn=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 Ln,ka=P(()=>{"use strict";Ln=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var $n,Ta=P(()=>{"use strict";$n=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Nn,va=P(()=>{"use strict";Nn=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 Ed}from"uuid";var Un,xa=P(()=>{"use strict";V();Un=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 p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
225
+ 3. Use Google Cloud environment with default service account`)}}var Mn,Ta=w(()=>{"use strict";ka();Mn=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Od();return{body:ya(e),config:{url:new URL(`/v1/projects/${o}/locations/${r}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${r}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return _a(e)}async transformResponseOut(e){return ba(e,this.name,this.logger)}}});var Ln,va=w(()=>{"use strict";Ln=class{name="cerebras";async transformRequestIn(e,t){let o=JSON.parse(JSON.stringify(e));return o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}}});var $n,xa=w(()=>{"use strict";$n=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Nn,Sa=w(()=>{"use strict";Nn=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Un,Ca=w(()=>{"use strict";Un=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let t={...e},o=Object.entries(this.options);for(let[r,s]of o)if(r in t)if(typeof t[r]=="object"&&typeof s=="object"&&!Array.isArray(t[r])&&!Array.isArray(s)&&t[r]!==null&&s!==null)t[r]=this.deepMergeObjects(t[r],s);else continue;else t[r]=this.cloneValue(s);return t}async transformResponseOut(e){return e}deepMergeObjects(e,t){let o={...e};for(let[r,s]of Object.entries(t))r in o&&typeof o[r]=="object"&&typeof s=="object"&&!Array.isArray(o[r])&&!Array.isArray(s)&&o[r]!==null&&s!==null?o[r]=this.deepMergeObjects(o[r],s):o[r]=this.cloneValue(s);return o}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>this.cloneValue(o));let t={};for(let[o,r]of Object.entries(e))t[o]=this.cloneValue(r);return t}}});import{v4 as Id}from"uuid";var Dn,Ra=w(()=>{"use strict";V();Dn=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
220
226
  `);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
221
227
  `))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"&&m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
222
228
 
223
- `)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let T={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let S=`data: ${JSON.stringify(T)}
229
+ `)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let T={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(T)}
224
230
 
225
- `;m.enqueue(y.encode(S));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let S={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:"ccr_think_signature"}}}]};S.choices?.[0]?.delta&&delete S.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(S)}
231
+ `;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let x={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(x)}
226
232
 
227
- `;m.enqueue(y.encode(v))}_.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(T=>{T.id=`call_${Ed()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),_.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let k=`data: ${JSON.stringify(_)}
233
+ `;m.enqueue(y.encode(v))}_.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(T=>{T.id=`call_${Id()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),_.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let k=`data: ${JSON.stringify(_)}
228
234
 
229
235
  `;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(g+`
230
236
  `))}}else m.enqueue(y.encode(g+`
231
- `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){c.trim()&&d(c,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(c+=m,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
232
- `);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(_+`
233
- `))}continue}let y=c.split(`
234
- `);c=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
235
- `))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var dr,Ad,Dn,Sa=P(()=>{"use strict";V();dr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
237
+ `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
238
+ `);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
239
+ `))}continue}let y=l.split(`
240
+ `);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
241
+ `))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var mr,Md,Fn,wa=w(()=>{"use strict";V();mr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
236
242
 
237
243
  Output format:
238
244
  <reasoning_content>
239
245
  Your detailed thinking process goes here
240
246
  </reasoning_content>
241
- Your final answer must follow after the closing tag above.`,Ad=10,Dn=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<Ad)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
242
- ${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:dr}):o.content=[{type:"text",text:dr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:dr}]}),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="",p="SEARCHING",d="",f="",g=(h,m)=>{if(typeof m!="string"){h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&!h.choices[0].delta.content&&(h.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(h)}
247
+ Your final answer must follow after the closing tag above.`,Md=10,Fn=class{name="forcereasoning";async transformRequestIn(e){let t=0;e.messages.filter(r=>r.role==="assistant").reverse().forEach(r=>{r.thinking&&(r.thinking.content&&(!r.content||t<Md)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
248
+ ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:mr}):o.content=[{type:"text",text:mr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:mr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await j(e);if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=r.choices[0]?.message.content.match(s);a&&a[1]&&(r.thinking={content:a[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,a=new TextEncoder,i=new ReadableStream({async start(l){let c=e.body.getReader(),u="",p="SEARCHING",d="",f="",g=(h,m)=>{if(typeof m!="string"){h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&!h.choices[0].delta.content&&(h.choices[0].index=r,l.enqueue(a.encode(`data: ${JSON.stringify(h)}
243
249
 
244
- `)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let S={...h.choices[0].delta,thinking:{content:_}};delete S.content;let v={...h,choices:[{...h.choices[0],delta:S,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
250
+ `)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let x={...h.choices[0].delta,thinking:{content:_}};delete x.content;let v={...h,choices:[{...h.choices[0],delta:x,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
245
251
 
246
- `))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
252
+ `))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
247
253
 
248
- `)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...h.choices[0].delta,thinking:{content:_}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
254
+ `)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...h.choices[0].delta,thinking:{content:_}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
249
255
 
250
- `))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...h.choices[0].delta,content:_};k.thinking&&delete k.thinking;let T={...h,choices:[{...h.choices[0],delta:k}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
256
+ `))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...h.choices[0].delta,content:_};k.thinking&&delete k.thinking;let T={...h,choices:[{...h.choices[0],delta:k}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
251
257
 
252
- `)),f=""}r++,y=""}};try{for(;;){let{done:h,value:m}=await l.read();if(h)break;let y=s.decode(m,{stream:!0});u+=y;let b=u.split(`
253
- `);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){c.enqueue(a.encode(_+`
258
+ `)),f=""}r++,y=""}};try{for(;;){let{done:h,value:m}=await c.read();if(h)break;let y=s.decode(m,{stream:!0});u+=y;let b=u.split(`
259
+ `);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){l.enqueue(a.encode(_+`
254
260
 
255
- `));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(_+`
256
- `))}else c.enqueue(a.encode(_+`
257
- `))}}}catch(h){console.error("Stream error:",h),c.error(h)}finally{try{l.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}if(p==="REASONING"){let m={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};c.enqueue(a.encode(`data: ${JSON.stringify(m)}
261
+ `));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(_+`
262
+ `))}else l.enqueue(a.encode(_+`
263
+ `))}}}catch(h){console.error("Stream error:",h),l.error(h)}finally{try{c.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}if(p==="REASONING"){let m={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(m)}
258
264
 
259
- `))}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 Fn,Ca=P(()=>{"use strict";V();Fn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(c){let l=e.body.getReader();try{for(;;){let{done:u,value:p}=await l.read();if(u){a.trim()&&c.enqueue(r.encode(a+`
265
+ `))}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var jn,Pa=w(()=>{"use strict";V();jn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u){a.trim()&&l.enqueue(r.encode(a+`
260
266
  `));break}let d=o.decode(p,{stream:!0});a+=d;let f=a.split(`
261
- `);a=f.pop()||"";for(let g of f)if(g.trim())if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let h=JSON.parse(g.slice(6));if(h.choices?.[0]?.delta?.reasoning_content){s+=h.choices[0].delta.reasoning_content;let m={...h,choices:[{...h.choices[0],delta:{thinking:{content:h.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content,c.enqueue(r.encode(`data: ${JSON.stringify(m)}
267
+ `);a=f.pop()||"";for(let g of f)if(g.trim())if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let h=JSON.parse(g.slice(6));if(h.choices?.[0]?.delta?.reasoning_content){s+=h.choices[0].delta.reasoning_content;let m={...h,choices:[{...h.choices[0],delta:{thinking:{content:h.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content,l.enqueue(r.encode(`data: ${JSON.stringify(m)}
262
268
 
263
- `));continue}if(h.choices?.[0]?.delta?.content&&s&&!h.choices[0]?.delta?.reasoning_content){let m=Date.now().toString(),y={...h,choices:[{...h.choices[0],delta:{content:null,thinking:{content:s,signature:m}}}]};c.enqueue(r.encode(`data: ${JSON.stringify(y)}
269
+ `));continue}if(h.choices?.[0]?.delta?.content&&s&&!h.choices[0]?.delta?.reasoning_content){let m=Date.now().toString(),y={...h,choices:[{...h.choices[0],delta:{content:null,thinking:{content:s,signature:m}}}]};l.enqueue(r.encode(`data: ${JSON.stringify(y)}
264
270
 
265
- `)),s=""}h.choices?.[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&c.enqueue(r.encode(`data: ${JSON.stringify(h)}
271
+ `)),s=""}h.choices?.[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&l.enqueue(r.encode(`data: ${JSON.stringify(h)}
266
272
 
267
- `))}catch{c.enqueue(r.encode(g+`
268
- `))}else c.enqueue(r.encode(g+`
269
- `))}}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 Ra}from"uuid";var jn,wa=P(()=>{"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||he(e.metadata?.user_id)||s("session_id")||Ra()}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 p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
273
+ `))}catch{l.enqueue(r.encode(g+`
274
+ `))}else l.enqueue(r.encode(g+`
275
+ `))}}catch(u){l.error(u)}finally{try{c.releaseLock()}catch{}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await j(e);return o.choices?.[0]?.message?.reasoning_content&&(o.choices[0].message.thinking={content:o.choices[0].message.reasoning_content},delete o.choices[0].message.reasoning_content),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}}});import{v4 as Ea}from"uuid";var Hn,Aa=w(()=>{"use strict";V();je();Hn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(c=>c.toLowerCase()===a),l=i?r[i]:void 0;return typeof l=="string"&&l.trim()?l.trim():void 0};return s("x-opencode-session")||o?.clientContext?.stableSessionId||o?.sessionId||he(e.metadata?.user_id)||s("session_id")||Ea()}async transformRequestIn(e,t,o){let r=e.reasoning?.enabled||e.messages.some(s=>s.thinking?.content);return e.messages.forEach(s=>{if(Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)}),s.role==="assistant"){let a=s.thinking?.content,i=s.thinking?.signature;a&&typeof a=="string"&&a.trim()?(s.reasoning_content=a,i&&(s.reasoning_content_signature=i)):r&&s.tool_calls?.length&&!s.reasoning_content&&(s.reasoning_content=" "),s.thinking&&delete s.thinking}}),Object.assign(e,this.options||{}),{body:e,config:{headers:{"x-opencode-session":this.resolveSessionId(e,o)}}}}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
270
276
  `);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
271
277
  `))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let b=JSON.parse(g.slice(6));if(b.usage&&(b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
272
278
 
273
- `));return}b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let _=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(_){h.appendReasoningContent(_);let w={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:_}}}]};w.choices?.[0]?.delta&&(delete w.choices[0].delta.reasoning,delete w.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(w)}
279
+ `));return}b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let _=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(_){h.appendReasoningContent(_);let P={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:_}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(P)}
274
280
 
275
- `));return}if(b.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let w="ccr_think_signature",R=b.choices[0].delta.content,E={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:w}}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(E)}
281
+ `));return}if(b.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let P="ccr_think_signature",E=b.choices[0].delta.content,R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:P}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(R)}
276
282
 
277
- `));let I={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:R}}]};I.choices?.[0]?.delta&&(delete I.choices[0].delta.reasoning,delete I.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(I)}
283
+ `));let A={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:E}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(A)}
278
284
 
279
- `));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_${Ra()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,T=k&&Object.keys(k).length>0,S=b.choices?.[0]?.finish_reason,v=b.usage;(T||S||v)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
285
+ `));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(P=>{P.id=`call_${Ea()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,T=k&&Object.keys(k).length>0,x=b.choices?.[0]?.finish_reason,v=b.usage;(T||x||v)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
280
286
 
281
287
  `))}catch{m.enqueue(y.encode(g+`
282
288
  `))}else m.enqueue(y.encode(g+`
283
- `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){c.trim()&&d(c,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(c+=m,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=c.split(`
284
- `);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(_+`
285
- `))}continue}let y=c.split(`
286
- `);c=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
287
- `))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function Id(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 Md(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 Od,Hn,Pa=P(()=>{"use strict";Qe();Od={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Hn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=Id(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Md(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=ye(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=Od[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 Ea(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 zn,Aa=P(()=>{"use strict";Qe();V();zn=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),a=!r&&!s&&o.includes("deepseek");if(e==="none")return a||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return a?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return a?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,a=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,a=a||r.effort==="none"):typeof r?.max_tokens=="number"?s=ye(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!a&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(a=!0));let i=this.resolveEffort(a?"none":s,o);return i?t.reasoning_effort=i:delete t.reasoning_effort,delete t.reasoning,delete t.thinking,delete t.enable_thinking,t}async transformResponseOut(e){let t=e.headers.get("Content-Type")??"";if(t.includes("application/json")){if(!e.body)return e;let o=await pe(e);if(o){let a=new Headers(e.headers);if(o.isSSE&&a.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:a}),o.isSSE)return this.transformStream(e)}else{let a=await me(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await j(e);this.liftMessageReasoning(r);let s=new Headers(e.headers);return s.delete("content-length"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}return(t.includes("stream")||t.includes("event-stream"))&&e.body?this.transformStream(e):e}liftMessageReasoning(e){if(Array.isArray(e?.choices))for(let t of e.choices)Ea(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=l=>{if(!l.startsWith("data:"))return l;let u=l.slice(5).trim();if(u==="[DONE]")return l;let p;try{p=JSON.parse(u)}catch{return l}let d=!1,f=Array.isArray(p?.choices)?p.choices:[];for(let g of f)Ea(g?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:l},a=(l,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,g="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)g+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(g+=s(r),r=""),g&&l.enqueue(o.encode(g))},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 Oa,Ia=P(()=>{ea();ta();na();oa();ra();sa();ia();aa();ca();ua();da();pa();fa();_a();ba();ka();Ta();va();xa();Yo();Sa();Ca();wa();Pa();Aa();Oa={AnthropicTransformer:hn,GeminiTransformer:kn,VertexGeminiTransformer:Tn,VertexClaudeTransformer:In,DeepseekTransformer:vn,TooluseTransformer:xn,OpenrouterTransformer:Sn,OpenAITransformer:$n,MaxTokenTransformer:Cn,GroqTransformer:Rn,CleancacheTransformer:wn,EnhanceToolTransformer:Pn,ReasoningTransformer:En,SamplingTransformer:An,MaxCompletionTokens:On,CerebrasTransformer:Mn,StreamOptionsTransformer:Ln,CustomParamsTransformer:Nn,VercelTransformer:Un,OpenAIResponsesTransformer:De,ForceReasoningTransformer:Dn,KimiTransformer:Fn,OpenCodeTransformer:jn,DefaultThinkingTransformer:Hn,AmdTransformer:zn}});var Ye,pr=P(()=>{"use strict";Ia();Ye=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;preparePluginTransformer(e){if(typeof e.TransformerName=="string")return e;let t=new e;if(!t?.name)throw new Error("plugin transformer has no name");return t.logger=this.logger,t}registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=ko(ko.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})
289
+ `))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
290
+ `);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
291
+ `))}continue}let y=l.split(`
292
+ `);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
293
+ `))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function $d(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 Nd(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 Ld,zn,Oa=w(()=>{"use strict";Qe();Ld={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};zn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=$d(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Nd(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=ye(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=Ld[o.toLowerCase()];return s?(r==="anthropic"?e.reasoning={enabled:!0,effort:s}:r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e):(r==="chat"?e.reasoning_effort=o:r==="responses"&&(e.reasoning={enabled:!0,effort:o}),e)}}});function Ia(n,e=!1){if(!n||typeof n!="object"||n.thinking)return!1;let t=n.reasoning,o=typeof t=="string"?t:t?.content;return typeof o=="string"&&o.length>0?(e&&typeof t=="object"?n.thinking={content:o}:(n.thinking=typeof t=="string"?{content:o}:{...t},delete n.reasoning),!0):typeof n.reasoning_content=="string"&&n.reasoning_content?(n.thinking={content:n.reasoning_content},!0):!1}var Bn,Ma=w(()=>{"use strict";Qe();V();Bn=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),a=!r&&!s&&o.includes("deepseek");if(e==="none")return a||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return a?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return a?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,a=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,a=a||r.effort==="none"):typeof r?.max_tokens=="number"?s=ye(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!a&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(a=!0));let i=this.resolveEffort(a?"none":s,o);return i?t.reasoning_effort=i:delete t.reasoning_effort,delete t.reasoning,delete t.thinking,delete t.enable_thinking,t}async transformResponseOut(e){let t=e.headers.get("Content-Type")??"";if(t.includes("application/json")){if(!e.body)return e;let o=await pe(e);if(o){let a=new Headers(e.headers);if(o.isSSE&&a.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:a}),o.isSSE)return this.transformStream(e)}else{let a=await me(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await j(e);this.liftMessageReasoning(r);let s=new Headers(e.headers);return s.delete("content-length"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}return(t.includes("stream")||t.includes("event-stream"))&&e.body?this.transformStream(e):e}liftMessageReasoning(e){if(Array.isArray(e?.choices))for(let t of e.choices)Ia(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=c=>{if(!c.startsWith("data:"))return c;let u=c.slice(5).trim();if(u==="[DONE]")return c;let p;try{p=JSON.parse(u)}catch{return c}let d=!1,f=Array.isArray(p?.choices)?p.choices:[];for(let g of f)Ia(g?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:c},a=(c,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,g="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)g+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(g+=s(r),r=""),g&&c.enqueue(o.encode(g))},i=e.body.pipeThrough(new TransformStream({transform(c,u){r+=t.decode(c,{stream:!0}),a(u)},flush(c){r+=t.decode(),a(c,!0)}})),l=new Headers(e.headers);return l.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:l})}}});var La,$a=w(()=>{oa();ra();sa();ia();aa();ca();la();ua();da();fa();ma();ga();ha();Ta();va();xa();Sa();Ca();Ra();Xo();wa();Pa();Aa();Oa();Ma();La={AnthropicTransformer:hn,GeminiTransformer:Tn,VertexGeminiTransformer:vn,VertexClaudeTransformer:Mn,DeepseekTransformer:xn,TooluseTransformer:Sn,OpenrouterTransformer:Cn,OpenAITransformer:Nn,MaxTokenTransformer:Rn,GroqTransformer:wn,CleancacheTransformer:Pn,EnhanceToolTransformer:En,ReasoningTransformer:An,SamplingTransformer:On,MaxCompletionTokens:In,CerebrasTransformer:Ln,StreamOptionsTransformer:$n,CustomParamsTransformer:Un,VercelTransformer:Dn,OpenAIResponsesTransformer:De,ForceReasoningTransformer:Fn,KimiTransformer:jn,OpenCodeTransformer:Hn,DefaultThinkingTransformer:zn,AmdTransformer:Bn}});var Ye,gr=w(()=>{"use strict";$a();Ye=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;preparePluginTransformer(e){if(typeof e.TransformerName=="string")return e;let t=new e;if(!t?.name)throw new Error("plugin transformer has no name");return t.logger=this.logger,t}registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=To(To.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
288
294
  error: ${t.message}
289
295
  stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
290
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Oa).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 Ld}from"tiktoken";var _t,Ma=P(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Ld(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 Bn}from"path";import{homedir as $d}from"os";import{existsSync as fr,mkdirSync as Nd}from"fs";import{promises as Jn}from"fs";import{Tokenizer as Ud}from"@huggingface/tokenizers";var Wn,La=P(()=>{"use strict";Wn=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||Bn($d(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Bn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Bn(e,"tokenizer.json"),tokenizerConfig:Bn(e,"tokenizer_config.json")}}ensureDir(e){fr(e)||Nd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!fr(e.tokenizerJson)||!fr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Jn.readFile(e.tokenizerJson,"utf-8"),Jn.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([Jn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Jn.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 Ud(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 Kn,$a=P(()=>{"use strict";q();Kn=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(`
291
- `):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Xe,mr=P(()=>{"use strict";Ma();La();$a();q();Xe=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new _t("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Wn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Kn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function Na(n){if(!n||typeof n!="object"||Jd(n))return null;for(let t of Bd(n)){let o=zd(t);if(o)return o}return null}function zd(n){if(!n||typeof n!="object")return null;let e={},t=Gn(n,Dd);if(t!==void 0){let a=Ua(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Gn(n,Fd);if(o!==void 0){let a=Ua(o);e.usedBalance=a,e.totalBalance=100}let r=Gn(n,jd);if(r!==void 0){let a=Da(r);a&&(e.resetTime=a)}let s=Gn(n,Hd);if(s!==void 0){let a=Da(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 Ua(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Gn(n,e){for(let t of e){let o=D(n?.[t]);if(o!==void 0)return o}}function Bd(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 Jd(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 Da(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 Rr(n){let e=wr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Zd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?qd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Wd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Kd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Gd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Qd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Vd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Yd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Xd:null:null}function ep(n){let e=wr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function tp(n,e){let t=Sr(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 Sr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>Sr(e)):Object.values(n).flatMap(e=>Sr(e))}function Cr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function wr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function D(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,gr,hr,yr,_r,br,Dd,Fd,jd,Hd,kr,Tr,vr,xr,Wd,Kd,Gd,Qd,Vd,Yd,Xd,Zd,qd,Pr=P(()=>{"use strict";q();se=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=G(r));let 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}},gr=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=>D(c?.total_balance)!==void 0);if(!a)return null;let i=D(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},hr=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=D(s.limit),c=D(s.limit_remaining),l=D(s.usage),u=D(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}},yr=class extends se{async queryQuota(e,t,o){let r=ep(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=D(a.totalBalance),l=D(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}},_r=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,p=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"&&(p=f);let d={};if(l){let f=D(l.currentValue),g=D(l.usage),h=D(l.remaining),m=D(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),g!==void 0?d.limitDaily=g:f!==void 0&&h!==void 0&&(d.limitDaily=f+h),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=D(u.currentValue),g=D(u.usage),h=D(u.remaining),m=D(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),g!==void 0?d.totalBalance=g:f!==void 0&&h!==void 0&&(d.totalBalance=f+h),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=D(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=D(p.usage),g=D(p.currentValue),h=D(p.remaining);f!==void 0?d.limitDaily=f:g!==void 0&&h!==void 0&&(d.limitDaily=g+h)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},br=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 p={},d=D(u.per5HourUsedQuota),f=D(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let g=D(u.perWeekUsedQuota),h=D(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),h!==void 0&&(p.totalBalance=h),this.hasQuotaData(p)?p:null}catch{return null}}};Dd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Fd=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],jd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Hd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];kr=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=Cr(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 p=await u.json();return Na(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=G(o));let 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 Na(l)}catch{return null}}},Tr=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:(Cr(e.quotaToken,"atp-auth-token")||Cr(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=tp(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=D(l.rp5hUsage),d=D(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=D(l.rpwUsage),g=D(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),g!==void 0&&(u.totalBalance=g),u.remainingBalance===void 0&&g!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,g-f)),this.hasQuotaData(u)?u:null}catch{return null}}},vr=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 p=l[0].detail,d=D(p.limit),f=D(p.remaining),g=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),g&&(c.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let p=D(u.limit),d=D(u.remaining),f=D(u.used),g=u.resetTime;p!==void 0&&(c.totalBalance=p,f!==void 0?c.usedBalance=f:d!==void 0&&(c.usedBalance=Math.max(0,p-d),c.remainingBalance=d)),g&&(c.resetTime7d=new Date(g).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},xr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=wr(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],c=null;for(let k of i)if(c=await this.fetchJson(k,e,t,o,r.trim()),c)break;if(!c)return null;if(c?.base_resp){let k=c.base_resp.status_code;if(k!==void 0&&k!==0)return null}let l=Array.isArray(c?.model_remains)?c.model_remains:[];if(l.length===0)return null;let u=l[0],p={},d=D(u.current_interval_total_count),f=D(u.current_interval_usage_count),g=D(u.current_interval_remaining_percent),h=D(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):g!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-g)),h&&(p.resetTime=new Date(h).toISOString());let m=D(u.current_weekly_total_count),y=D(u.current_weekly_usage_count),b=D(u.current_weekly_remaining_percent),_=D(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Wd=new gr,Kd=new hr,Gd=new yr,Qd=new _r,Vd=new br,Yd=new kr,Xd=new Tr,Zd=new vr,qd=new xr});async function Qn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=Fa.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&&lt(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),Fa.set(n,r),r.pending}var np,ja,Fa,Er=P(()=>{"use strict";Ce();np=6e4,ja=2500,Fa=new Map});function Ha(n){return{[op]:n,[rp]:Vt}}function _e(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function ip(n){return n===!0||n==="true"||n===1||n==="1"}function ap(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 cp(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 lp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Ar(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(_e(n))return{success:!1,skipped:!0,error:Or,latencyMs:r()};let s=cp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=G(t));let i=await fetch(s,a);if(i.headers&&it(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let 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 up(n,e,t,o){if(_e(n))return{success:!1,skipped:!0,error:Or};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",...Ha("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 dp(n,e,t,o,r){if(_e(n))return{success:!1,skipped:!0,error:Or};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Ha("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 za(n,e,t,o,r,s){return be||(be=new Vn(n,e,t,o,r,s)),be}function bt(n,e,t,o,r,s){let a=za(n,e,t,o,r,s);return a.start(),a}function Ir(){be&&be.stop()}function Mr(){be&&(be.stop(),be=null)}var op,rp,sp,Or,Vn,be,Yn=P(()=>{"use strict";re();Se();Pr();Ce();Er();Lo();q();op="x-claude-code-router-source",rp="x-claude-code-router-version";sp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Or="Managed provider requires its plugin's authenticated model sync";Vn=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={...sp,...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&&!_e(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Rr(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){lt(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,p=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.totalBalance})`;for(let f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),lp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Ar(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&&_e(a)&&!this.config.excludeProviders.includes(a.name));for(let a of s){let i=this.resolveManagedRuntime(a);i&&typeof i.fetchQuota=="function"&&o.push({provider:a.name,models:Array.isArray(a.models)?a.models:[],type:"managed-plugin-quota",promise:Qn(a.name,a,i)})}}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=H(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!_e(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Ar(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),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(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let c=s[0],l=e.getState(r,c);!l||l.status!=="open"||l.rateLimitUntil&&Date.now()<l.rateLimitUntil||Date.now()-(l.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,c,s,e)||await this.probeManagedLiveness(r,i,a,c,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=this.config.probeTimeoutMs,c={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},l=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(c),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt: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(p?.ok){for(let d of s)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=H(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&_e(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await dp(p,c,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!_e(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=ap(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),p=parseInt(l,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,g=(p*60+d)*6e4-(o*60+r)*6e4,h=g>0&&g<=300*1e3;(f||h)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),up(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?ip(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 Ar(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)H().recordSuccess(o.name,i);else for(let i of a)H().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},be=null});var Ba=P(()=>{"use strict"});var Lr,kt,Ja=P(()=>{"use strict";Lr=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},kt=new Lr});var ie,$r=P(()=>{"use strict";ie=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
292
- `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Ze,Nr=P(()=>{"use strict";Ze=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
296
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(La).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});import{get_encoding as Ud}from"tiktoken";var _t,Na=w(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Ud(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(l=>{if(l.type==="text")o+=t.encode(l.text).length;else if(l.type==="tool_use")o+=t.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let c=l.content;if(Array.isArray(c))for(let u of c)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof c=="string"?c:JSON.stringify(c);o+=t.encode(u).length}}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(l=>{o+=t.encode(l||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Jn}from"path";import{homedir as Dd}from"os";import{existsSync as hr,mkdirSync as Fd}from"fs";import{promises as Wn}from"fs";import{Tokenizer as jd}from"@huggingface/tokenizers";var Kn,Ua=w(()=>{"use strict";Kn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||Jn(Dd(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Jn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Jn(e,"tokenizer.json"),tokenizerConfig:Jn(e,"tokenizer_config.json")}}ensureDir(e){hr(e)||Fd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!hr(e.tokenizerJson)||!hr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Wn.readFile(e.tokenizerJson,"utf-8"),Wn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Wn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Wn.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:i,tokenizerConfig:l}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new jd(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let l of i.content)l?.type!=="image"&&t.push(l?.type==="text"?String(l.text??""):JSON.stringify(l));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Gn,Da=w(()=>{"use strict";q();Gn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},i=this.options.resolveProxyUrl?.();i&&(a.dispatcher=G(i));let l=await fetch(this.config.url,a);if(clearTimeout(s),!l.ok)throw new Error(`API tokenizer request failed: ${l.status} ${l.statusText}`);let c=await l.json();return this.extractTokenCount(c)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
297
+ `):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Xe,yr=w(()=>{"use strict";Na();Ua();Da();q();Xe=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new _t("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Kn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Gn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function Fa(n){if(!n||typeof n!="object"||Gd(n))return null;for(let t of Kd(n)){let o=Wd(t);if(o)return o}return null}function Wd(n){if(!n||typeof n!="object")return null;let e={},t=Qn(n,Hd);if(t!==void 0){let a=ja(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Qn(n,zd);if(o!==void 0){let a=ja(o);e.usedBalance=a,e.totalBalance=100}let r=Qn(n,Bd);if(r!==void 0){let a=Ha(r);a&&(e.resetTime=a)}let s=Qn(n,Jd);if(s!==void 0){let a=Ha(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function ja(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Qn(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function Kd(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 Gd(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function Ha(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Er(n){let e=Ar(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?tp:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?np:e==="deepseek.com"||e.endsWith(".deepseek.com")?Qd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Vd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Yd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Xd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Zd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?qd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?ep:null:null}function op(n){let e=Ar(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function rp(n,e){let t=wr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(l=>l.includes(i)||i.includes(l))})||t[0]}function wr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>wr(e)):Object.values(n).flatMap(e=>wr(e))}function Pr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Ar(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function U(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var se,_r,br,kr,Tr,vr,Hd,zd,Bd,Jd,xr,Sr,Cr,Rr,Qd,Vd,Yd,Xd,Zd,qd,ep,tp,np,Or=w(()=>{"use strict";q();se=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=G(r));let l=await fetch(e,i);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},_r=class extends se{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(l=>U(l?.total_balance)!==void 0);if(!a)return null;let i=U(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},br=class extends se{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=U(s.limit),l=U(s.limit_remaining),c=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),l!==void 0&&(a.remainingBalance=l),c!==void 0&&(a.usedBalance=c),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},kr=class extends se{async queryQuota(e,t,o){let r=op(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},l=U(a.totalBalance),c=U(a.balance);return l!==void 0&&(i.totalBalance=l),c!==void 0&&(i.remainingBalance=c),l!==void 0&&c!==void 0&&(i.usedBalance=Math.max(0,l-c)),this.hasQuotaData(i)?i:null}},Tr=class extends se{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),l=Array.isArray(i?.data?.limits)?i.data.limits:[],c=null,u=null,p=null;for(let f of l)f.type==="TOKENS_LIMIT"?f.unit===3?c=f:f.unit===6?u=f:c||(c=f):f.type==="TIME_LIMIT"&&(p=f);let d={};if(c){let f=U(c.currentValue),g=U(c.usage),h=U(c.remaining),m=U(c.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),g!==void 0?d.limitDaily=g:f!==void 0&&h!==void 0&&(d.limitDaily=f+h),c.nextResetTime&&(d.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),g=U(u.usage),h=U(u.remaining),m=U(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),g!==void 0?d.totalBalance=g:f!==void 0&&h!==void 0&&(d.totalBalance=f+h),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=U(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=U(p.usage),g=U(p.currentValue),h=U(p.remaining);f!==void 0?d.limitDaily=f:g!==void 0&&h!==void 0&&(d.limitDaily=g+h)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},vr=class extends se{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=G(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let c=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(c)||c.length===0)return null;let u=c[0]?.codingPlanQuotaInfo;if(!u)return null;let p={},d=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let g=U(u.perWeekUsedQuota),h=U(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),h!==void 0&&(p.totalBalance=h),this.hasQuotaData(p)?p:null}catch{return null}}};Hd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],zd=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Bd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Jd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];xr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Pr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),l=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),c={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:l,signal:AbortSignal.timeout(o)};try{r&&(c.dispatcher=G(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,c);if(!u.ok)return null;let p=await u.json();return Fa(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=G(o));let l=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!l.ok)return null;let c=await l.json();return Fa(c)}catch{return null}}},Sr=class extends se{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Pr(e.quotaToken,"atp-auth-token")||Pr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let l=rp(i,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},p=U(c.rp5hUsage),d=U(c.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=U(c.rpwUsage),g=U(c.rpwLimit);return f!==void 0&&(u.usedBalance=f),g!==void 0&&(u.totalBalance=g),u.remainingBalance===void 0&&g!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,g-f)),this.hasQuotaData(u)?u:null}catch{return null}}},Cr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),l={},c=Array.isArray(i?.limits)?i.limits:[];if(c.length>0&&c[0]?.detail){let p=c[0].detail,d=U(p.limit),f=U(p.remaining),g=p.resetTime;d!==void 0&&f!==void 0&&(l.usedDailyBalance=Math.max(0,d-f),l.limitDaily=d),g&&(l.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let p=U(u.limit),d=U(u.remaining),f=U(u.used),g=u.resetTime;p!==void 0&&(l.totalBalance=p,f!==void 0?l.usedBalance=f:d!==void 0&&(l.usedBalance=Math.max(0,p-d),l.remainingBalance=d)),g&&(l.resetTime7d=new Date(g).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Rr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Ar(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let k of i)if(l=await this.fetchJson(k,e,t,o,r.trim()),l)break;if(!l)return null;if(l?.base_resp){let k=l.base_resp.status_code;if(k!==void 0&&k!==0)return null}let c=Array.isArray(l?.model_remains)?l.model_remains:[];if(c.length===0)return null;let u=c[0],p={},d=U(u.current_interval_total_count),f=U(u.current_interval_usage_count),g=U(u.current_interval_remaining_percent),h=U(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):g!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-g)),h&&(p.resetTime=new Date(h).toISOString());let m=U(u.current_weekly_total_count),y=U(u.current_weekly_usage_count),b=U(u.current_weekly_remaining_percent),_=U(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Qd=new _r,Vd=new br,Yd=new kr,Xd=new Tr,Zd=new vr,qd=new xr,ep=new Sr,tp=new Cr,np=new Rr});async function Vn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=za.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<sp)return;let r=o??{fetchedAt:0};return r.pending=(async()=>{try{let s=await t.fetchQuota(e);s&&lt(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),za.set(n,r),r.pending}var sp,Ba,za,Ir=w(()=>{"use strict";Ce();sp=6e4,Ba=2500,za=new Map});function Ja(n){return{[ip]:n,[ap]:Vt}}function _e(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function lp(n){return n===!0||n==="true"||n===1||n==="1"}function up(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 dp(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 pp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Mr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(_e(n))return{success:!1,skipped:!0,error:Lr,latencyMs:r()};let s=dp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=G(t));let i=await fetch(s,a);if(i.headers&&it(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let l=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${l.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",l=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:l?"timeout":"network"}}}async function fp(n,e,t,o){if(_e(n))return{success:!1,skipped:!0,error:Lr};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Ja("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(l.dispatcher=G(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let c=await fetch(s,l);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function mp(n,e,t,o,r){if(_e(n))return{success:!1,skipped:!0,error:Lr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Ja("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(l.dispatcher=G(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let c=await fetch(s,l);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function Wa(n,e,t,o,r,s){return be||(be=new Yn(n,e,t,o,r,s)),be}function bt(n,e,t,o,r,s){let a=Wa(n,e,t,o,r,s);return a.start(),a}function $r(){be&&be.stop()}function Nr(){be&&(be.stop(),be=null)}var ip,ap,cp,Lr,Yn,be,Xn=w(()=>{"use strict";re();Se();Or();Ce();Ir();$o();q();ip="x-claude-code-router-source",ap="x-claude-code-router-version";cp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Lr="Managed provider requires its plugin's authenticated model sync";Yn=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,a){this.config={...cp,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),l={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,l),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),l}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.managedProbeTimer=setInterval(()=>this.runManagedRecoveryProbe(),this.config.quotaProbeIntervalMinutes*60*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.managedProbeTimer&&(clearInterval(this.managedProbeTimer),this.managedProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!_e(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Er(s.baseUrl),i=Array.isArray(s.models)?s.models:[],l=this.resolveProxyUrl?.(s);if(!a){let c;try{c=new URL(s.baseUrl).hostname}catch{c=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(c?` (host: ${c})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,l).then(c=>{if(c){lt(s.name,c),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,p=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${c.usedDailyBalance}/${c.limitDaily})`:`Quota exhausted: 7d balance depleted (${c.usedBalance}/${c.totalBalance})`;for(let f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),pp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Mr(s,this.config.probeTimeoutMs,l).then(c=>{this.recordProbe(s.name,c,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&_e(a)&&!this.config.excludeProviders.includes(a.name));for(let a of s){let i=this.resolveManagedRuntime(a);i&&typeof i.fetchQuota=="function"&&o.push({provider:a.name,models:Array.isArray(a.models)?a.models:[],type:"managed-plugin-quota",promise:Vn(a.name,a,i)})}}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=H(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!_e(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Mr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let l=a.value;if(l.skipped)continue;if(this.recordProbe(s.name,l,"health"),l.success){let c=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),c++}c>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let c of i)e.recordFailure(s.name,c,l.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${l.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let l of i)e.recordFailure(s.name,l,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=H();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let l=o.get(s)??[];l.push(i),o.set(s,l)}for(let[r,s]of o){let a=this.getProviders().find(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let l=s[0],c=e.getState(r,l);!c||c.status!=="open"||c.rateLimitUntil&&Date.now()<c.rateLimitUntil||Date.now()-(c.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,l,s,e)||await this.probeManagedLiveness(r,i,a,l,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=this.config.probeTimeoutMs,l={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},c=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(l),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:c,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:c,requestBody:l,config:u,provider:o}):await c();if(p?.ok){for(let d of s)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=H(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),l=i.join(",");if(!a||!l)continue;let c=o.find(d=>d?.name===a);if(c&&_e(c))continue;let u=e.getState(a,l);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,l),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await mp(p,l,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,l);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!_e(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=up(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let l=i.wakeupTime||a,[c,u]=l.split(":"),p=parseInt(c,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,g=(p*60+d)*6e4-(o*60+r)*6e4,h=g>0&&g<=300*1e3;(f||h)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${l}`),fp(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?lp(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Mr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)H().recordSuccess(o.name,i);else for(let i of a)H().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},be=null});var Ka=w(()=>{"use strict"});var Ur,kt,Ga=w(()=>{"use strict";Ur=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},kt=new Ur});var ie,Dr=w(()=>{"use strict";ie=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
298
+ `);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Ze,Fr=w(()=>{"use strict";Ze=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
293
299
  `),e.id&&(o+=`id: ${e.id}
294
300
  `),e.retry&&(o+=`retry: ${e.retry}
295
301
  `),e.data&&(e.data.type==="done"?o+=`data: [DONE]
296
302
  `:o+=`data: ${JSON.stringify(e.data)}
297
303
  `),o+=`
298
- `,t.enqueue(o)}})}}});var Xn,Ur=P(()=>{"use strict";Xn=(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 Dr=P(()=>{"use strict";$r();Nr();Ur()});var Wa=P(()=>{"use strict"});var Tt,Fr=P(()=>{"use strict";Tt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let 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+=`
304
+ `,t.enqueue(o)}})}}});var Zn,jr=w(()=>{"use strict";Zn=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var Hr=w(()=>{"use strict";Dr();Fr();jr()});var Qa=w(()=>{"use strict"});var Tt,zr=w(()=>{"use strict";Tt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let l=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
299
305
  `+(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}-
300
306
  ${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
301
307
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
302
308
  ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
303
- `):`${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 vt,jr=P(()=>{"use strict";vt=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 qn,opendir as fp,unlink as mp}from"node:fs/promises";import{join as Ga,resolve as Br}from"node:path";import{tmpdir as gp}from"node:os";async function eo(n,e){let t=Br(n),o=Zn.get(t),r,s=new Promise(a=>{r=a});Zn.set(t,s);try{return await o,await e()}finally{r(),Zn.get(t)===s&&Zn.delete(t)}}function Qa(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Ka(n,e){try{let t=await qn(n);return t.isDirectory()&&!t.isSymbolicLink()&&Qa(e,t)}catch{return!1}}function kp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Va(n,e,t,o){let r=Br(n);if(o?.aborted||Hr.has(r))return 0;Hr.add(r);let s=0;try{let a=await qn(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await fp(r,{bufferSize:32});try{let c=0,l=!0;for await(let u of i){if(o?.aborted||!l)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let p=Ga(r,u.name);try{let d=await qn(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await eo(p,async()=>{if(o?.aborted||!await Ka(r,a))return!1;let g=await qn(p);return!g.isFile()||g.isSymbolicLink()||!Qa(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await mp(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await kp(),l=!o?.aborted&&await Ka(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Hr.delete(r)}return s}function Ya(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Va(n,Date.now()-o,i=>bp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function Tp(n,e){let t=Date.now()-hp;return Va(n,t,o=>{let r=_p.exec(o);return r!==null&&Number(r[1])<t},e)}function Jr(n,e,t){let o=zr.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,yp),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},zr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),zr.delete(n)))}}function Xa(n=Ga(gp(),"claude-code-router")){return Jr(`legacy:${Br(n)}`,e=>Tp(n,e),1e3)}var hp,yp,_p,bp,Hr,Zn,zr,Wr=P(()=>{"use strict";hp=3600*1e3,yp=600*1e3,_p=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,bp=/^\.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$/,Hr=new Set,Zn=new Map,zr=new Map});import{lstat as vp,mkdir as xp,open as Sp,rename as Cp,unlink as Rp}from"node:fs/promises";import{randomUUID as wp}from"node:crypto";import{sanitizeTempFileKey as Pp}from"@wengine-ai/claude-code-router-shared";import{basename as Ep,join as Kr,resolve as Ap}from"node:path";import{tmpdir as Op}from"node:os";var xt,Gr=P(()=>{"use strict";Wr();xt=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=Ap(Kr(Op(),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=Jr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await xp(this.baseDir,{recursive:!0});let e=await vp(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}-${Pp(e)}${r}${o}`;if(Ep(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Kr(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 eo(a,async()=>{await this.ensureDir();let i=Kr(this.baseDir,`.ccr-tmp-${process.pid}-${wp()}.tmp`);return eo(i,async()=>{let c=!1;try{let l=await Sp(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await Cp(i,a),!0}finally{c&&await Rp(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return Ya(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Qr,qe,Za=P(()=>{"use strict";Fr();jr();Gr();Qr=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new Tt(e.config);case"webhook":return new vt(e.config);case"temp-file":return new xt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(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)}},qe=new Qr});var Vr=P(()=>{"use strict";Wa();Fr();jr();Gr();Za()});import Ip from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Mp}from"@wengine-ai/claude-code-router-shared";function to(){return{subdirectory:Mp,extension:"json",includeTimestamp:!1,prefix:"session"}}function qa(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Lp);return Math.round(n/o)}function Ct(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function ec(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await qe.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var St,Yr,Lp,no,tc=P(()=>{"use strict";Dr();Vr();je();St=new Map,Yr=new Map,Lp=1,no={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:Ip(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)qe.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:to()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&qe.registerHandlers(a)}t.outputOptions&&qe.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,l=a.model,u=`${c}:${l}`;if(Yr.has(u))return Yr.get(u);let p=i.getTokenizerConfigForModel(c,l);if(!p)return n.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let d=await i.getTokenizer(p,c);return Yr.set(u,d),n.log?.info(`Created tokenizer for ${c}:${l} - ${d.name}`),d}catch(d){return n.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${d.message}`),null}},s=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,c)=>{let l=a.requestStartTime;if(!l)return;let u=a.id||Date.now().toString(),p=a.usageSessionId||u,d=a.sessionId;if(!d)try{d=he(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(c instanceof ReadableStream){St.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=c.tee(),_=async()=>{let k=null,T=async S=>{let v=St.get(u);if(!v)return;let w=v.firstTokenTime?v.firstTokenTime-v.startTime:0,E=(S?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=qa(v.tokenCount,E,w),await ec(v,o,t.outputOptions,S).catch(I=>{n.log?.warn(`Failed to output streaming stats: ${I.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();for(k=setInterval(async()=>{St.get(u)&&await T(!1)},1e3);;){let{done:w,value:R}=await v.read();if(w)break;let E=R,I=St.get(u);if(!I)continue;let U=performance.now(),C=E.event||E.data?.type,A=E.event==="content_block_start"||E.event==="content_block_delta"||E.event==="text_block"||E.event==="content_block"||C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta";!I.firstTokenTime&&A&&(I.firstTokenTime=U,I.timeToFirstToken=Math.round(U-I.startTime));let x="";if(E.event==="content_block_delta"&&E.data?.delta){let O=E.data.delta.type;O==="text_delta"?x=E.data.delta.text||"":O==="input_json_delta"?x=E.data.delta.partial_json||"":O==="thinking_delta"&&(x=E.data.delta.thinking||"")}if((C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta")&&(x=typeof E.data?.delta=="string"?E.data.delta:""),x){let O=f&&f.encodeText?f.encodeText(x).length:Ct(x);I.tokenCount+=O,I.lastTokenTime=U}(E.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),St.delete(u))}}catch(S){k&&clearInterval(k),S.name!=="AbortError"&&S.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${S.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let g=performance.now(),h=0,m=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")h=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?h=b.reduce((_,k)=>{if(k.type==="text"){let T=k.text||"";return _+(f.encodeText?f.encodeText(T).length:Ct(T))}return _},0):typeof b=="string"&&(h=f.encodeText?f.encodeText(b).length:Ct(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";h=Ct(_)}}}catch{}if(m){let y=g-l,b={requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:g,tokenCount:h,tokensPerSecond:qa(h,y),stream:!1};await ec(b,o,t.outputOptions,!0)}return c})})}});var Xr=P(()=>{"use strict";Ba();Ja();tc();Vr()});import ne from"node:fs/promises";import nc from"json5";import Oe from"node:path";import{CONFIG_FILE as oe,HOME_DIR as oo,PLUGINS_DIR as $p}from"@wengine-ai/claude-code-router-shared";function oc(){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 Zr,Rt,ro,wt,X,so,ue,Np,qr,Pt=P(()=>{"use strict";Zr=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(Zr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Zr(o);return e}return n},Rt=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},ro=async()=>{await Rt(oo),await Rt($p),await Rt(Oe.join(oo,"logs"))},wt=async()=>{let n=await ne.readFile(oe,"utf-8");return nc.parse(n)},X=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=nc.parse(n);return Zr(e)}catch(e){console.error(`Failed to parse config file at ${oe}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await ro();let e=await so();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await ue(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${oe}`),console.error("Error details:",n.message),process.exit(1)}};so=async()=>{oc();try{if(await ne.access(oe).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${oe}.${n}.bak`;await ne.copyFile(oe,e);try{let t=Oe.dirname(oe),o=Oe.basename(oe),s=(await ne.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=Oe.join(t,s[a]);await ne.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},ue=async n=>{oc(),await Rt(oo),await Np();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},Np=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=Oe.join(oo,"config-history");await Rt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Oe.join(e,`config-${t}.json`);await ne.copyFile(oe,o);try{let s=(await ne.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ne.unlink(Oe.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},qr=async()=>{let n=await X();return Object.assign(process.env,n),n}});function io(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(es(r,s))}return}if(Array.isArray(n)){for(let o of n)io(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))io(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(es(s,i))}return io(n?.Router,t,o),io(n?.fallback,t,o),o}function Et(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(es(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 ao(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 Up,es,At=P(()=>{"use strict";re();Up="\0",es=(n,e)=>`${n}${Up}${e}`});function Dp(n){return/\[1m\]/i.test(n)?1e6:2e5}function Fp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function jp(n,e=n){let t=Dp(n),o=Fp(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 Hp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function ts(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,jp(r,s))};o("ccr-opus","CCR Opus"),o("ccr-sonnet","CCR Sonnet"),o("ccr-haiku","CCR Haiku"),o("ccr-opus[1m]","CCR Opus 1M"),o("ccr-sonnet[1m]","CCR Sonnet 1M"),o("ccr-haiku[1m]","CCR Haiku 1M");for(let r of n.Providers||n.providers||[])if(!(!r?.name||!Array.isArray(r.models)))for(let s of r.models){if(typeof s!="string"||!s)continue;let a=Hp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var ns=P(()=>{"use strict"});function zp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var co,os=P(()=>{"use strict";co=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||zp(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 mc={};To(mc,{append:()=>$t,clear:()=>as,close:()=>df,getOldestRecordTimestamp:()=>pf,query:()=>is,querySummary:()=>Nt,readTokenSpeedStats:()=>cs});import{existsSync as ac,mkdirSync as Bp,readFileSync as cc}from"fs";import{join as po}from"path";import{tmpdir as Jp}from"os";import{openSqliteDatabase as Wp}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Kp,sanitizeTempFileKey as Gp,TOKEN_SPEED_TEMP_SUBDIRECTORY as Qp}from"@wengine-ai/claude-code-router-shared";function qp(){ac(uo)||Bp(uo,{recursive:!0})}function Lt(){if(Te)return Te;qp();let n=Wp(Vp),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&&(ef(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")),nf(e),dc(e,!0),ss=e.prepare(`
309
+ `):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var vt,Br=w(()=>{"use strict";vt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(i),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(i=c,l===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as eo,opendir as hp,unlink as yp}from"node:fs/promises";import{join as Ya,resolve as Kr}from"node:path";import{tmpdir as _p}from"node:os";async function to(n,e){let t=Kr(n),o=qn.get(t),r,s=new Promise(a=>{r=a});qn.set(t,s);try{return await o,await e()}finally{r(),qn.get(t)===s&&qn.delete(t)}}function Xa(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Va(n,e){try{let t=await eo(n);return t.isDirectory()&&!t.isSymbolicLink()&&Xa(e,t)}catch{return!1}}function xp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Za(n,e,t,o){let r=Kr(n);if(o?.aborted||Jr.has(r))return 0;Jr.add(r);let s=0;try{let a=await eo(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await hp(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of i){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let p=Ya(r,u.name);try{let d=await eo(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await to(p,async()=>{if(o?.aborted||!await Va(r,a))return!1;let g=await eo(p);return!g.isFile()||g.isSymbolicLink()||!Xa(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await yp(p),!0)})&&s++}catch{}}finally{++l%64===0&&(await xp(),c=!o?.aborted&&await Va(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Jr.delete(r)}return s}function qa(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Za(n,Date.now()-o,i=>vp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function Sp(n,e){let t=Date.now()-bp;return Za(n,t,o=>{let r=Tp.exec(o);return r!==null&&Number(r[1])<t},e)}function Gr(n,e,t){let o=Wr.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,kp),a.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),a&&clearInterval(a)}},Wr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Wr.delete(n)))}}function ec(n=Ya(_p(),"claude-code-router")){return Gr(`legacy:${Kr(n)}`,e=>Sp(n,e),1e3)}var bp,kp,Tp,vp,Jr,qn,Wr,Qr=w(()=>{"use strict";bp=3600*1e3,kp=600*1e3,Tp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,vp=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,Jr=new Set,qn=new Map,Wr=new Map});import{lstat as Cp,mkdir as Rp,open as wp,rename as Pp,unlink as Ep}from"node:fs/promises";import{randomUUID as Ap}from"node:crypto";import{sanitizeTempFileKey as Op}from"@wengine-ai/claude-code-router-shared";import{basename as Ip,join as Vr,resolve as Mp}from"node:path";import{tmpdir as Lp}from"node:os";var xt,Yr=w(()=>{"use strict";Qr();xt=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=Mp(Vr(Lp(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=Gr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await Rp(this.baseDir,{recursive:!0});let e=await Cp(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}-${Op(e)}${r}${o}`;if(Ip(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Vr(this.baseDir,s)}async output(e,t={}){try{let o=typeof t.metadata?.statsKey=="string"&&t.metadata.statsKey?t.metadata.statsKey:t.metadata?.sessionId;if(!o)return!1;let r=t.metadata?.sessionId??o,s=JSON.stringify({...e,timestamp:Date.now(),sessionId:r},null,2),a=this.getFilePath(o);return await to(a,async()=>{await this.ensureDir();let i=Vr(this.baseDir,`.ccr-tmp-${process.pid}-${Ap()}.tmp`);return to(i,async()=>{let l=!1;try{let c=await wp(i,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await Pp(i,a),!0}finally{l&&await Ep(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return qa(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Xr,qe,tc=w(()=>{"use strict";zr();Br();Yr();Xr=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new Tt(e.config);case"webhook":return new vt(e.config);case"temp-file":return new xt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let l=this.handlers.get(i);if(!l){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await l.output(t,r)?s.success.push(i):s.failed.push(i)}catch(c){console.error(`[OutputManager] Handler ${i} failed:`,c),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},qe=new Xr});var Zr=w(()=>{"use strict";Qa();zr();Br();Yr();tc()});import $p from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Np}from"@wengine-ai/claude-code-router-shared";function no(){return{subdirectory:Np,extension:"json",includeTimestamp:!1,prefix:"session"}}function nc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Up);return Math.round(n/o)}function Ct(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function oc(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await qe.outputToType(i,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,l)}}var St,qr,Up,oo,rc=w(()=>{"use strict";Hr();Zr();je();St=new Map,qr=new Map,Up=1,oo={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:$p(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)qe.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:no()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&qe.registerHandlers(a)}t.outputOptions&&qe.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,c=a.model,u=`${l}:${c}`;if(qr.has(u))return qr.get(u);let p=i.getTokenizerConfigForModel(l,c);if(!p)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let d=await i.getTokenizer(p,l);return qr.set(u,d),n.log?.info(`Created tokenizer for ${l}:${c} - ${d.name}`),d}catch(d){return n.log?.warn(`Failed to create tokenizer for ${l}:${c}: ${d.message}`),null}},s=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,l)=>{let c=a.requestStartTime;if(!c)return;let u=a.id||Date.now().toString(),p=a.usageSessionId||u,d=a.sessionId;if(!d)try{d=he(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(l instanceof ReadableStream){St.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=l.tee(),_=async()=>{let k=null,T=async x=>{let v=St.get(u);if(!v)return;let P=v.firstTokenTime?v.firstTokenTime-v.startTime:0,R=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=nc(v.tokenCount,R,P),await oc(v,o,t.outputOptions,x).catch(A=>{n.log?.warn(`Failed to output streaming stats: ${A.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();for(k=setInterval(async()=>{St.get(u)&&await T(!1)},1e3);;){let{done:P,value:E}=await v.read();if(P)break;let R=E,A=St.get(u);if(!A)continue;let D=performance.now(),C=R.event||R.data?.type,O=R.event==="content_block_start"||R.event==="content_block_delta"||R.event==="text_block"||R.event==="content_block"||C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta";!A.firstTokenTime&&O&&(A.firstTokenTime=D,A.timeToFirstToken=Math.round(D-A.startTime));let S="";if(R.event==="content_block_delta"&&R.data?.delta){let I=R.data.delta.type;I==="text_delta"?S=R.data.delta.text||"":I==="input_json_delta"?S=R.data.delta.partial_json||"":I==="thinking_delta"&&(S=R.data.delta.thinking||"")}if((C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta")&&(S=typeof R.data?.delta=="string"?R.data.delta:""),S){let I=f&&f.encodeText?f.encodeText(S).length:Ct(S);A.tokenCount+=I,A.lastTokenTime=D}(R.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),St.delete(u))}}catch(x){k&&clearInterval(k),x.name!=="AbortError"&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${x.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let g=performance.now(),h=0,m=!1;if(l&&typeof l=="string")try{let y=JSON.parse(l);if(typeof y.usage?.output_tokens=="number")h=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?h=b.reduce((_,k)=>{if(k.type==="text"){let T=k.text||"";return _+(f.encodeText?f.encodeText(T).length:Ct(T))}return _},0):typeof b=="string"&&(h=f.encodeText?f.encodeText(b).length:Ct(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";h=Ct(_)}}}catch{}if(m){let y=g-c,b={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:g,tokenCount:h,tokensPerSecond:nc(h,y),stream:!1};await oc(b,o,t.outputOptions,!0)}return l})})}});var es=w(()=>{"use strict";Ka();Ga();rc();Zr()});import ne from"node:fs/promises";import sc from"json5";import Oe from"node:path";import{CONFIG_FILE as oe,HOME_DIR as ro,PLUGINS_DIR as Dp}from"@wengine-ai/claude-code-router-shared";function ic(){if(process.env.VITEST||process.env.CI)throw new Error("Config write attempted during test/CI. Set CCR_CONFIG_DIR to a temp dir to isolate.")}var ts,Rt,so,wt,X,io,ue,Fp,ns,Pt=w(()=>{"use strict";ts=n=>{if(typeof n=="string")return n.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,t,o)=>{let r=t||o;return process.env[r]||e});if(Array.isArray(n))return n.map(ts);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=ts(o);return e}return n},Rt=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},so=async()=>{await Rt(ro),await Rt(Dp),await Rt(Oe.join(ro,"logs"))},wt=async()=>{let n=await ne.readFile(oe,"utf-8");return sc.parse(n)},X=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=sc.parse(n);return ts(e)}catch(e){console.error(`Failed to parse config file at ${oe}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await so();let e=await io();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await ue(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${oe}`),console.error("Error details:",n.message),process.exit(1)}};io=async()=>{ic();try{if(await ne.access(oe).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${oe}.${n}.bak`;await ne.copyFile(oe,e);try{let t=Oe.dirname(oe),o=Oe.basename(oe),s=(await ne.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=Oe.join(t,s[a]);await ne.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},ue=async n=>{ic(),await Rt(ro),await Fp();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},Fp=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=Oe.join(ro,"config-history");await Rt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Oe.join(e,`config-${t}.json`);await ne.copyFile(oe,o);try{let s=(await ne.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ne.unlink(Oe.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},ns=async()=>{let n=await X();return Object.assign(process.env,n),n}});function ao(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(os(r,s))}return}if(Array.isArray(n)){for(let o of n)ao(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))ao(o,e,t)}}function ac(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let i of a)i&&o.add(os(s,i))}return ao(n?.Router,t,o),ao(n?.fallback,t,o),o}function Et(n,e){try{let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=ac(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(os(a,i))||(t.recover(a,i),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function co(n,e){try{if(!n)return 0;let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var jp,os,At=w(()=>{"use strict";re();jp="\0",os=(n,e)=>`${n}${jp}${e}`});function Hp(n){return/\[1m\]/i.test(n)?1e6:2e5}function zp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Bp(n,e=n){let t=Hp(n),o=zp(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 Jp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function rs(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Bp(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=Jp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var ss=w(()=>{"use strict"});function Wp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var lo,is=w(()=>{"use strict";lo=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Wp(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(i)?i[0]:i||"";if(!l){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let c="";if(l.startsWith("Bearer")?c=l.split(" ")[1]:c=l,c!==a){t.log.warn({url:e.url,gotPrefix:c.slice(0,10),gotSuffix:c.slice(-6),gotLen:c.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var yc={};vo(yc,{append:()=>$t,clear:()=>us,close:()=>mf,getOldestRecordTimestamp:()=>gf,query:()=>ls,querySummary:()=>Nt,readTokenSpeedStats:()=>ds});import{existsSync as uc,mkdirSync as Kp,readFileSync as dc}from"fs";import{join as fo}from"path";import{tmpdir as Gp}from"os";import{openSqliteDatabase as Qp}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Vp,sanitizeTempFileKey as Yp,TOKEN_SPEED_TEMP_SUBDIRECTORY as Xp}from"@wengine-ai/claude-code-router-shared";function nf(){uc(po)||Kp(po,{recursive:!0})}function Lt(){if(Te)return Te;nf();let n=Qp(Zp),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&&(of(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")),sf(e),mc(e,!0),cs=e.prepare(`
304
310
  INSERT INTO usage_records (
305
311
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
306
312
  scenario_type, client_type,
@@ -314,7 +320,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
314
320
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
315
321
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
316
322
  )
317
- `),Te=e,Te}function ef(n){n.exec(`
323
+ `),Te=e,Te}function of(n){n.exec(`
318
324
  CREATE TABLE IF NOT EXISTS usage_records (
319
325
  id TEXT PRIMARY KEY,
320
326
  timestamp TEXT NOT NULL,
@@ -351,12 +357,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
351
357
  CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
352
358
  CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
353
359
  CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
354
- `)}function tf(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
360
+ `)}function rf(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
355
361
  INSERT INTO usage_meta (key, value)
356
362
  VALUES (?, ?)
357
363
  ON CONFLICT(key) DO UPDATE SET value = excluded.value
358
- `).run(e,t)}function nf(n){if(tf(n,sc)||!ac(rs))return;let e=rf(n,"INSERT OR IGNORE"),t=cc(rs,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
359
- `)){let c=i.trim();if(c)try{let l=JSON.parse(c);if(!of(l)){r++;continue}e.run(uc(fo(l))).changes>0?o++:s++}catch{r++}}Ot(n,sc,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",rs),Ot(n,"legacy_usage_jsonl_imported_count",String(o)),Ot(n,"legacy_usage_jsonl_skipped_count",String(r)),Ot(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function of(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 rf(n,e="INSERT"){return n.prepare(`
364
+ `).run(e,t)}function sf(n){if(rf(n,cc)||!uc(as))return;let e=cf(n,"INSERT OR IGNORE"),t=dc(as,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
365
+ `)){let l=i.trim();if(l)try{let c=JSON.parse(l);if(!af(c)){r++;continue}e.run(fc(mo(c))).changes>0?o++:s++}catch{r++}}Ot(n,cc,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",as),Ot(n,"legacy_usage_jsonl_imported_count",String(o)),Ot(n,"legacy_usage_jsonl_skipped_count",String(r)),Ot(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function af(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 cf(n,e="INSERT"){return n.prepare(`
360
366
  ${e} INTO usage_records (
361
367
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
362
368
  scenario_type, client_type,
@@ -370,11 +376,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
370
376
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
371
377
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
372
378
  )
373
- `)}function sf(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,Yp);return Math.round(n/r)}function fo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Mt(n.ttft):null;return{...n,ttft:r,tokensPerSecond:sf(e,o,r)}}function ke(n){return typeof n=="string"?n:n==null?"":String(n)}function lo(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function It(n){let e=Number(n);return Number.isFinite(e)?e:0}function lc(n){return n==="success"?"success":"error"}function uc(n){let e=fo(n);return{id:ke(e.id),timestamp:ke(e.timestamp),session_id:ke(e.sessionId),provider:ke(e.provider),original_model:ke(e.originalModel),model:ke(e.model),upstream_model:lo(e.upstreamModel)??null,model_family:ke(e.modelFamily),scenario_type:ke(e.scenarioType),client_type:lo(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(It(e.inputTokens)),output_tokens:Math.trunc(It(e.outputTokens)),cache_read_input_tokens:Math.trunc(It(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(It(e.cacheCreationInputTokens)),ttft:Mt(e.ttft),tokens_per_second:Mt(e.tokensPerSecond),duration_ms:Math.trunc(It(e.durationMs)),status:lc(e.status),error_message:lo(e.errorMessage)??null,response_body:lo(e.responseBody)??null}}function af(n){return fo({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:lc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function cf(){return new Date(Date.now()-Xp*24*60*60*1e3).toISOString()}function dc(n,e=!1){let t=Date.now();!e&&t-ic<Zp||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(cf()),ic=t)}function pc(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function et(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
374
- SELECT ${t} AS key, ${lf}
379
+ `)}function lf(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,qp);return Math.round(n/r)}function mo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Mt(n.ttft):null;return{...n,ttft:r,tokensPerSecond:lf(e,o,r)}}function ke(n){return typeof n=="string"?n:n==null?"":String(n)}function uo(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function It(n){let e=Number(n);return Number.isFinite(e)?e:0}function pc(n){return n==="success"?"success":"error"}function fc(n){let e=mo(n);return{id:ke(e.id),timestamp:ke(e.timestamp),session_id:ke(e.sessionId),provider:ke(e.provider),original_model:ke(e.originalModel),model:ke(e.model),upstream_model:uo(e.upstreamModel)??null,model_family:ke(e.modelFamily),scenario_type:ke(e.scenarioType),client_type:uo(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(It(e.inputTokens)),output_tokens:Math.trunc(It(e.outputTokens)),cache_read_input_tokens:Math.trunc(It(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(It(e.cacheCreationInputTokens)),ttft:Mt(e.ttft),tokens_per_second:Mt(e.tokensPerSecond),duration_ms:Math.trunc(It(e.durationMs)),status:pc(e.status),error_message:uo(e.errorMessage)??null,response_body:uo(e.responseBody)??null}}function uf(n){return mo({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,stream:n.stream===1,...n.usage_estimated===1?{usageEstimated:!0}:{},inputTokens:n.input_tokens,outputTokens:n.output_tokens,cacheReadInputTokens:n.cache_read_input_tokens,cacheCreationInputTokens:n.cache_creation_input_tokens,ttft:n.ttft,tokensPerSecond:n.tokens_per_second,durationMs:n.duration_ms,status:pc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function df(){return new Date(Date.now()-ef*24*60*60*1e3).toISOString()}function mc(n,e=!1){let t=Date.now();!e&&t-lc<tf||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(df()),lc=t)}function gc(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function et(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
380
+ SELECT ${t} AS key, ${pf}
375
381
  FROM usage_records ${r}
376
382
  GROUP BY key
377
- `).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 fc(n,e){let t=pc(e),o=n.prepare(`
383
+ `).all(...e.params),a={};for(let i of s)i.key!=null&&(a[String(i.key)]={count:i.count,inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadInputTokens:i.cacheReadInputTokens,cacheCreationInputTokens:i.cacheCreationInputTokens});return a}function hc(n,e){let t=gc(e),o=n.prepare(`
378
384
  SELECT
379
385
  COUNT(*) AS totalRequests,
380
386
  COALESCE(SUM(usage_estimated), 0) AS estimatedCount,
@@ -386,14 +392,14 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
386
392
  AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
387
393
  AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
388
394
  FROM usage_records ${t.sql}
389
- `).get(...t.params);return{estimatedCount:o.estimatedCount,totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:et(n,t,"model"),byProvider:et(n,t,"provider"),byScenario:et(n,t,"scenario_type"),byFamily:et(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:et(n,t,"date(timestamp, 'localtime')"),byClient:et(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function $t(n){let e=Lt(),t=fo(n);ss.run(uc(t)),dc(e)}function is(n){let e=Lt(),t=pc(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),uf):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=fc(e,n);return{records:i.map(af),summary:c,total:a.count,page:o,pageSize:r}}function Nt(n,e,t){let o=Lt();return fc(o,{startTime:n,endTime:e,status:t})}function as(n){let e=Lt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function df(){Te&&(Te.pragma("wal_checkpoint(TRUNCATE)"),Te.close(),Te=null,ss=null)}function Mt(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function cs(n){let e=po(Jp(),Qp,`session-${Gp(n)}.json`);try{let t=JSON.parse(cc(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function pf(n,e,t){return Lt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var uo,Vp,rs,Yp,Xp,Zp,sc,Te,ss,ic,lf,uf,Ut=P(()=>{"use strict";uo=po(Kp,"data"),Vp=po(uo,"usage.sqlite"),rs=po(uo,"usage.jsonl"),Yp=1,Xp=180,Zp=3600*1e3,sc="legacy_usage_jsonl_migrated_at",Te=null,ss=null,ic=0;lf=`
395
+ `).get(...t.params);return{estimatedCount:o.estimatedCount,totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:et(n,t,"model"),byProvider:et(n,t,"provider"),byScenario:et(n,t,"scenario_type"),byFamily:et(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:et(n,t,"date(timestamp, 'localtime')"),byClient:et(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function $t(n){let e=Lt(),t=mo(n);cs.run(fc(t)),mc(e)}function ls(n){let e=Lt(),t=gc(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.min(Math.floor(n.pageSize),ff):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),l=hc(e,n);return{records:i.map(uf),summary:l,total:a.count,page:o,pageSize:r}}function Nt(n,e,t){let o=Lt();return hc(o,{startTime:n,endTime:e,status:t})}function us(n){let e=Lt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function mf(){Te&&(Te.pragma("wal_checkpoint(TRUNCATE)"),Te.close(),Te=null,cs=null)}function Mt(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function ds(n){let e=fo(Gp(),Xp,`session-${Yp(n)}.json`);try{let t=JSON.parse(dc(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function gf(n,e,t){return Lt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var po,Zp,as,qp,ef,tf,cc,Te,cs,lc,pf,ff,Ut=w(()=>{"use strict";po=fo(Vp,"data"),Zp=fo(po,"usage.sqlite"),as=fo(po,"usage.jsonl"),qp=1,ef=180,tf=3600*1e3,cc="legacy_usage_jsonl_migrated_at",Te=null,cs=null,lc=0;pf=`
390
396
  COUNT(*) AS count,
391
397
  COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
392
398
  COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
393
399
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
394
400
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
395
- `;uf=200});import{existsSync as ff}from"fs";import{homedir as mf}from"os";import{join as gf}from"path";import{writeFile as hf}from"fs/promises";async function gc(){let n=mf(),e=gf(n,".claude.json");if(!ff(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 hf(e,JSON.stringify(o,null,2))}}var hc=P(()=>{"use strict"});import{existsSync as yf,readdirSync as _f,statSync as bf,unlinkSync as kf}from"fs";import{join as yc}from"path";import{HOME_DIR as Tf}from"@wengine-ai/claude-code-router-shared";function bc(n=yc(Tf,"logs")){try{if(!yf(n))return;let e=Date.now()-xf;for(let t of _f(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=yc(n,t),r=bf(o);r.isFile()&&r.mtime.getTime()<e&&kf(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function kc(){_c||(_c=!0,bc(),setInterval(bc,Sf).unref())}var vf,xf,Sf,_c,Tc=P(()=>{"use strict";vf=7,xf=vf*24*60*60*1e3,Sf=1440*60*1e3,_c=!1});async function vc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":kt.registerPlugin(no,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:to()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var xc=P(()=>{"use strict";Xr()});function tt(n,e,t){if(n?.configService)try{n.configService.reload(),n.reloadProviders?n.reloadProviders(e):(n.configService.set("providers",e?.Providers??e?.providers??[]),n.providerService?.reload()),Et(e,t),Mr();let o={enabled:n.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:n.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:n.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(n.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:n.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:n.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};n.activeProbeService=bt(()=>n.providerService.getProviders(),o,r=>de(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var mo=P(()=>{"use strict";At();Yn();q()});import{constants as ls,lstatSync as nt,realpathSync as Dt,openSync as Cf,closeSync as Rf,fstatSync as wf,readFileSync as Sc}from"node:fs";import{dirname as qb,join as ot,sep as Pf}from"node:path";import{pathToFileURL as Ef}from"node:url";function Rc(n){try{let e=JSON.parse(Sc(ot(Af(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function ds(n,e){if(!Cc(e))return null;try{let t=Dt(n),o=ot(t,"plugins"),r=ot(o,e);return nt(o).isSymbolicLink()||!nt(o).isDirectory()||nt(r).isSymbolicLink()||!nt(r).isDirectory()||Dt(o)!==o||Dt(r)!==r||!r.startsWith(o+Pf)?null:r}catch{return null}}function us(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=ds(n,e);if(!o)throw new Error("unsafe plugin directory");let r=ot(o,t),s=nt(r);if(s.isSymbolicLink()||!s.isFile()||Dt(r)!==r)throw new Error("unsafe plugin file");let a=Cf(r,ls.O_RDONLY|ls.O_NOFOLLOW|ls.O_NONBLOCK);try{let i=wf(a),c=nt(r);if(!i.isFile()||c.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==c.dev||i.ino!==c.ino||ds(n,e)!==o||Dt(r)!==r)throw new Error("plugin file changed while opening");return Sc(a)}finally{Rf(a)}}function Of(n){let e=n?.configService,t=e?Es(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return As(t)}async function wc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Mo(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>wt(),writeConfig:i=>ue(i),reloadRuntime:async i=>tt(n.getServer(),i??await X(),t),getDirectDispatcher:xo,getSubscriptionDispatcher:()=>Of(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Rc(e)){let c;try{if(!Cc(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=ds(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(us(e,i.name,"plugin.json").toString("utf8"));if(!h||typeof h.name!="string"||typeof h.version!="string")throw new Error;u={name:h.name,version:h.version,coreApi:String(h.coreApi??"1"),description:h.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:h=>t.info(`[plugin:${u.name}] ${h}`),warn:h=>t.warn(`[plugin:${u.name}] ${h}`),error:h=>t.error(`[plugin:${u.name}] ${h}`)},r,l);c=p,us(e,i.name,"plugin.js");let d=await import(Ef(ot(l,"plugin.js")).href),f=d?.activate??d?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(p.context);let g=p.cardPath?us(e,i.name,p.cardPath):void 0;await p.commit(g,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(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 Pc(n,e=Mo()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Rc(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 Cc,Af,ps=P(()=>{"use strict";Oo();Qt();mo();Pt();q();Cc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Af=n=>ot(n,"plugins")});import{existsSync as Ec,readFileSync as If}from"node:fs";import{join as fs}from"node:path";import{NPM_SPEC_PATTERN as Mf,PLUGIN_NAME_PATTERN as Ac,PluginInstallError as Lf,installPluginFromNpm as $f,readPluginRecords as Nf}from"@wengine-ai/claude-code-router-shared";async function Df(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 Ff(n,e={}){let t=(e.registryBase??Uf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(Oc.map(m=>Df(t,m,o))),s=new Map,a=!1;for(let m of r)if(m.status==="fulfilled"){a=!0;for(let y of m.value){let b=y?.package,_=typeof b?.name=="string"?b.name:"";if(!_||!Mf.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(S=>typeof S=="string"):[]).some(S=>Oc.includes(S)))continue;let T=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:T,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=Nf(n),c=new Map(i.map(m=>[m.name,m])),l=m=>{let y=m.indexOf("@",m.startsWith("@")?1:0);return y>0?m.slice(0,y):m},u=new Map(i.filter(m=>typeof m.source=="string"&&m.source!=="").map(m=>[l(m.source),m])),p=m=>{if(!Ac.test(m))return null;try{let y=JSON.parse(If(fs(n,"plugins",m,"plugin.json"),"utf8"));return typeof y?.version=="string"?y.version:null}catch{return null}},d=[...s.values()].sort((m,y)=>m.name.localeCompare(y.name)).map(m=>{let y=c.get(m.name)??u.get(m.name),b=y!==void 0||Ec(fs(n,"plugins",m.name)),_=b?p(y?y.name:m.name):null;return{...m,installed:b,installedVersion:_,...b&&_!==null&&_!==m.version?{updateAvailable:!0}:{}}}),f=new Set(d.map(m=>m.name)),g=new Set,h=new Map;for(let[m,y]of u)g.add(y.name),!f.has(m)&&h.set(m,y.name);for(let m of i)f.has(m.name)||g.has(m.name)||h.set(m.name,m.name);for(let[m,y]of h){if(!Ac.test(y)||!Ec(fs(n,"plugins",y)))continue;let b=p(y);b!==null&&d.push({name:m,description:"",version:b,installed:!0,installedVersion:b,localOnly:!0})}return d.sort((m,y)=>m.name.localeCompare(y.name)),{ok:!0,plugins:d}}function jf(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 Ic(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),c=n.headers?.host;if(typeof c=="string"&&!i.has(c))return!1;let l=n.headers?.origin;if(l!==void 0&&l!==""){if(typeof l!="string")return!1;let u="";try{let p=new URL(l);if(!["http:","https:"].includes(p.protocol))return!1;u=p.host}catch{return!1}if(!i.has(u))return!1}return!0}function Mc(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(!Ic(r,n,t))return o(s,403,"local_only");try{return await Ff(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(!Ic(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 $f({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 Lf){let u=jf(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 Oc,Uf,Lc=P(()=>{"use strict";Oc=["ccr-provider-plugin","claude-code-router-plugin"],Uf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Hf}from"@wengine-ai/claude-code-router-shared";import{join as ae,isAbsolute as zf,normalize as Bf,dirname as Jf}from"path";import{fileURLToPath as Wf}from"url";import Kf from"@fastify/static";import{readdirSync as $c,statSync as Gf,readFileSync as Nc,writeFileSync as Qf,existsSync as fe,unlinkSync as Uc,rmSync as Vf}from"fs";import{homedir as ms}from"os";import{getPresetDir as go,readManifestFromDir as gs,manifestToPresetFile as Dc,saveManifest as Fc,isPresetInstalled as jc,extractPreset as Yf,HOME_DIR as hs,loadConfigFromManifest as Xf,downloadPresetToTemp as Zf,findMarketPresetByName as qf,getMarketPresets as em,applyClientSelection as tm,disableClient as nm,enableClient as om,isClientId as rm,listClientStatuses as Hc,restoreClient as sm,listProjectConfigs as im,readProjectConfigById as ys,readProjectConfig as am,writeProjectConfig as zc,deleteProjectConfig as cm,getClaudeProjectId as lm,getProjectConfigPath as um,refreshCcrProjectTakeover as dm,refreshPiProjectTakeover as pm,refreshProjectTakeovers as fm,syncGlobalProjectTakeovers as _s,getProjectTakeoverClients as bs,setProjectTakeover as ks,isProjectTakeoverClient as mm}from"@wengine-ai/claude-code-router-shared";import gm from"@fastify/multipart";import hm from"adm-zip";function Bc(n){let e=H();return ts(n,(t,o)=>e.isAvailable(t,o))}function Jc(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 ym(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=Nt(t,e),s=Nt(o,e),a=[],i=new Set;for(let c of n||[])c&&c.name&&i.add(c.name);for(let c of Object.keys(r.byProvider||{}))i.add(c);for(let c of Object.keys(s.byProvider||{}))i.add(c);for(let c of i){let l=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},p=(l.inputTokens||0)+(l.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),f,g,h=(n||[]).find(m=>m&&m.name===c);h&&h.quota&&(f=h.quota.limit5h,g=h.quota.limit7d),a.push({provider:c,used5h:p,used7d:d,limit5h:f,limit7d:g})}return a}async function Wc(n,e){let t=n.app;at(),ut(),t.register(gm,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Bc(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=Bc(e).find(p=>p.id===l);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${l}`}})}),t.post("/v1/messages/count_tokens",async(i,c)=>{let{messages:l,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[h,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${h}, model: ${m}`);let y=f.getTokenizerConfigForModel(h,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${h},${m}, using default tiktoken`);let b=await f.countTokens({messages:l,system:p,tools:u},y,h);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(h){i.log?.error(`Error using configured tokenizer: ${h.message}`),i.log?.error(h.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:ln(l,p,u)}}),t.get("/api/config",async(i,c)=>await wt()),t.get("/api/transformers",async(i,c)=>{let l=t._server.transformerService.getAllTransformers();return{transformers:Array.from(l.entries()).map(([p,d])=>({name:p,endpoint:d.endPoint||null}))}}),t.post("/api/config",async(i,c)=>{let l=i.body,u=Ps(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(g=>`${g.key}: ${g.error}`).join("; "),proxyErrors:u};let p=await so();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}Hf(l,d),n.pluginRegistry.applyConfigProtectors(l,d),await ue(l);let f;try{f=await _s(l),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}return tt(n,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:Hc(l)}}catch(l){console.error("Failed to get client integrations:",l),c.status(500).send({error:l.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(i,c)=>{try{let l=i.body,u=Array.isArray(l?.enabled)?l.enabled:[],p=await X(),d=tm(p,u);await ue(d.config);let f=await _s(d.config),g=Jc(t,f,"clients/apply");return{...d,success:d.success&&g,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(!rm(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=l==="enable"?om(p,u):l==="restore"?sm(p,u):nm(p,u);await ue(p);let f=await _s(p),g=Jc(t,f,`clients/${u}/${l}`);return{success:d.success&&g,result:d,results:[d],clients:Hc(p),config:p,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 im();return{projects:await Promise.all(l.map(async p=>{let d=await bs(p.path);return{...p,ccrTakeoverClients:d,ccrTakeover:d.length>0}}))}}catch(l){console.error("Failed to list project configs:",l),c.status(500).send({error:l.message||"Failed to list project configs"})}}),t.post("/api/projects",async(i,c)=>{try{let{path:l}=i.body||{};if(!l||typeof l!="string"||!zf(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=Bf(l).replace(/[\\/]+$/,"")||l;if(await am(u)){c.status(409).send({error:"Project is already configured"});return}await zc(u,{Router:{}});try{let f=await X();await ks(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await bs(u);return{id:lm(u),path:u,configPath:um(u),Router:{},ccrTakeoverClients:d,ccrTakeover:d.length>0}}catch(l){console.error("Failed to add project config:",l),c.status(500).send({error:l.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){c.status(400).send({error:"Router must be an object"});return}let p=await ys(l);if(!p){c.status(404).send({error:"Project config not found"});return}await zc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await fm(p.path,d):(await dm(p.path,d,u),await pm(p.path,d,u));let f=await bs(p.path);return{id:l,path:p.path,configPath:p.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||{},p;if(Array.isArray(u.clients))p=u.clients.filter(mm);else if(typeof u.enabled=="boolean")p=u.enabled?["claudeCode"]:[];else{c.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let d=await ys(l);if(!d){c.status(404).send({error:"Project config not found"});return}let f=await X(),g=await ks(d.path,p,f);return{id:l,path:d.path,ccrTakeoverClients:g,ccrTakeover:g.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 ys(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await X();await ks(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await cm(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:Jf(Wf(import.meta.url)),s=fe(ae(r,"index.html"))?r:fe(ae(r,"..","index.html"))?ae(r,".."):ae(r,"..","dist");t.register(Kf,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(i,c)=>c.redirect("/ui/")),t.get("/api/logs/files",async(i,c)=>{try{let l=ae(ms(),".claude-code-router","logs"),u=[];if(fe(l)){let p=$c(l);for(let d of p)if(d.endsWith(".log")){let f=ae(l,d),g=Gf(f);u.push({name:d,path:f,size:g.size,lastModified:g.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(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=ae(ms(),".claude-code-router","logs","app.log"),fe(u)?Nc(u,"utf8").split(`
396
- `).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=ae(ms(),".claude-code-router","logs","app.log"),fe(u)&&Qf(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:Bt()})),t.put("/api/debug-log",async i=>{let{enabled:c}=i.body;return wo(c),{enabled:Bt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return is({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 Nt(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 as(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(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,lastSuccessTime:f.lastSuccessTime??null,lastError:f.lastError,rateLimitUntil:f.rateLimitUntil??null})),probes:d,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to get provider health:",l),c.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,c)=>{try{let{providerName:l}=i.body;if(!l)return c.status(400),{error:"providerName is required"};let p=t._server?.activeProbeService;if(!p?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let d=await p.probeProviderManually(l);return d.success&&ao(l,i.log),{provider:l,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.error,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe provider:",l),c.status(500).send({error:l.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,c)=>{try{let l=t._server,u=l?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let p=(l?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let g=await u.probeProviderManually(f.name);return g.success&&ao(f.name,i?.log),{provider:f.name,success:g.success,latencyMs:g.latencyMs,status:g.status,isSlow:g.isSlow,errorKind:g.errorKind??null,error:g.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(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||[],p=t._server?.pluginRegistry,d=t._server?.providerService;if(p&&d?.getProviders){let b=d.getProviders().filter(_=>_?.name&&_.enabled!==!1).map(_=>{let k=p.getManagedRuntimeFor(_);if(!(!k||typeof k.fetchQuota!="function"))return Qn(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,ja).unref?.()});await Promise.race([Promise.all(b),_])}}let f=ym(u),g=new Map(f.map(y=>[y.provider,y])),h=Bo();for(let y of f){let b=h.find(_=>_.provider===y.provider);b&&b.limit!=null&&!Zt(b.reset)&&(y.limit5h=b.limit,y.used5h=b.limit-(b.remaining??0),b.reset&&(y.reset5h=new Date(b.reset*1e3).toISOString()))}let m=er();for(let y of m){let b=g.get(y.provider);b||(b={provider:y.provider,used5h:0,used7d:0},f.push(b),g.set(y.provider,b)),typeof y.totalBalance=="number"?(b.limit7d=y.totalBalance,b.type7d=y.currency?"balance":"rateLimit",y.currency&&(b.currency=y.currency),typeof y.usedBalance=="number"?b.used7d=y.usedBalance:typeof y.remainingBalance=="number"?b.used7d=Math.max(0,y.totalBalance-y.remainingBalance):(b.used7d=0,b.limit7d=y.totalBalance)):typeof y.usedBalance=="number"&&(b.used7d=y.usedBalance);let _=Zt(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=Zt(typeof y.resetTime7d=="string"?Date.parse(y.resetTime7d)/1e3:void 0);typeof y.usedDailyBalance=="number"&&!_&&(b.used5h=y.usedDailyBalance,b.type5h="rateLimit"),typeof y.limitDaily=="number"&&!_&&(b.limit5h=y.limitDaily,b.type5h="rateLimit"),typeof y.resetTime=="string"&&!_&&(y.limitDaily!==void 0?b.reset5h=y.resetTime:b.reset7d=y.resetTime),typeof y.resetTime7d=="string"&&!k&&(b.reset7d=y.resetTime7d)}return{quotas:f,timestamp:new Date().toISOString()}}catch(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=ae(hs,"presets");if(!fe(l))return{presets:[]};let p=$c(l,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let g=ae(l,f);try{let h=ae(g,"manifest.json"),m=Nc(h,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:T,API_TIMEOUT_MS:S,PROXY_URL:v,PROXY_GLOBAL_ENABLED:w,LOG:R,LOG_LEVEL:E,StatusLine:I,NON_INTERACTIVE_MODE:U,...C}=y;d.push({id:f,name:C.name||f,version:C.version||"1.0.0",description:C.description,author:C.author,homepage:C.homepage,repository:C.repository,license:C.license,keywords:C.keywords,ccrVersion:C.ccrVersion,source:C.source,sourceType:C.sourceType,checksum:C.checksum,installed:!0})}catch(h){console.error(`Failed to read preset ${f}:`,h)}}return{presets:d}}catch(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=go(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}let p=await gs(u);return{...Dc(p),config:Xf(p,u),userValues:p.userValues||{}}}catch(l){console.error("Failed to get preset:",l),c.status(500).send({error:l.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(i,c)=>{try{let{name:l}=i.params,{secrets:u}=i.body,p=go(l);if(!fe(p)){c.status(404).send({error:"Preset not found"});return}let f={...await gs(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await Fc(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=go(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}return Vf(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 em()}}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 qf(l);if(!u){c.status(400).send({error:"Preset not found in marketplace",message:`Preset '${l}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){c.status(400).send({error:"Invalid preset data",message:`Preset '${l}' does not have repository information`});return}let p=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!p){c.status(400).send({error:"Invalid GitHub repository URL"});return}let[,d,f]=p,g=u.name||l;if(await jc(g)){c.status(409).send({error:"Preset already installed",message:`Preset '${g}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:g});return}let h=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await Zf(h),y=await a(m);if(await jc(g)){Uc(m),c.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let b=go(g);await Yf(m,b);let _=await gs(b);return _.repository=u.repo,u.url&&(_.source=u.url),await Fc(g,_),Uc(m),{success:!0,presetName:g,preset:{...y.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 hm(i),l=c.getEntry("manifest.json");if(l||(l=c.getEntries().find(d=>d.entryName.includes("manifest.json"))||null),!l)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(l.getData().toString("utf-8"));return Dc(u)}return t.get("/api/plugins",async()=>({plugins:Pc(hs,n.pluginRegistry)})),Mc(t,{configDir:hs,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,c)=>{let{name:l,file:u}=i.params,p=n.pluginRegistry.getPublicCard(l,u);return p?(c.header("Content-Type","application/javascript; charset=utf-8"),c.header("X-Content-Type-Options","nosniff"),c.header("Cache-Control","no-store"),c.send(p)):c.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var Kc=P(()=>{"use strict";Pe();Se();Ce();Er();Se();q();rt();re();At();mo();ps();Lc();Pt();Ut();ns()});function _m(n,e){let t=n?.Router,{family:o}=mt(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function Gc(n){return n?.Router?.image}function bm(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 km(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 Ts,ho,vs,Qc,Vc=P(()=>{"use strict";Pe();Ts=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}},ho=new Ts;vs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=_m(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!bm(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&gt(e.body.model)?!1:(km(e.body.messages),s&&!!Gc(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=ho.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=ho.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:Gc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
401
+ `;ff=200});import{existsSync as hf}from"fs";import{homedir as yf}from"os";import{join as _f}from"path";import{writeFile as bf}from"fs/promises";async function _c(){let n=yf(),e=_f(n,".claude.json");if(!hf(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 bf(e,JSON.stringify(o,null,2))}}var bc=w(()=>{"use strict"});import{existsSync as kf,readdirSync as Tf,statSync as vf,unlinkSync as xf}from"fs";import{join as kc}from"path";import{HOME_DIR as Sf}from"@wengine-ai/claude-code-router-shared";function vc(n=kc(Sf,"logs")){try{if(!kf(n))return;let e=Date.now()-Rf;for(let t of Tf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=kc(n,t),r=vf(o);r.isFile()&&r.mtime.getTime()<e&&xf(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function xc(){Tc||(Tc=!0,vc(),setInterval(vc,wf).unref())}var Cf,Rf,wf,Tc,Sc=w(()=>{"use strict";Cf=7,Rf=Cf*24*60*60*1e3,wf=1440*60*1e3,Tc=!1});async function Cc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":kt.registerPlugin(oo,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:no()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var Rc=w(()=>{"use strict";es()});function tt(n,e,t){if(n?.configService)try{n.configService.reload(),n.reloadProviders?n.reloadProviders(e):(n.configService.set("providers",e?.Providers??e?.providers??[]),n.providerService?.reload()),Et(e,t),Nr();let o={enabled:n.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:n.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:n.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(n.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:n.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:n.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};n.activeProbeService=bt(()=>n.providerService.getProviders(),o,r=>de(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var go=w(()=>{"use strict";At();Xn();q()});import{constants as ps,lstatSync as nt,realpathSync as Dt,openSync as Pf,closeSync as Ef,fstatSync as Af,readFileSync as wc}from"node:fs";import{dirname as nk,join as ot,sep as Of}from"node:path";import{pathToFileURL as If}from"node:url";function Ec(n){try{let e=JSON.parse(wc(ot(Mf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function ms(n,e){if(!Pc(e))return null;try{let t=Dt(n),o=ot(t,"plugins"),r=ot(o,e);return nt(o).isSymbolicLink()||!nt(o).isDirectory()||nt(r).isSymbolicLink()||!nt(r).isDirectory()||Dt(o)!==o||Dt(r)!==r||!r.startsWith(o+Of)?null:r}catch{return null}}function fs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=ms(n,e);if(!o)throw new Error("unsafe plugin directory");let r=ot(o,t),s=nt(r);if(s.isSymbolicLink()||!s.isFile()||Dt(r)!==r)throw new Error("unsafe plugin file");let a=Pf(r,ps.O_RDONLY|ps.O_NOFOLLOW|ps.O_NONBLOCK);try{let i=Af(a),l=nt(r);if(!i.isFile()||l.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==l.dev||i.ino!==l.ino||ms(n,e)!==o||Dt(r)!==r)throw new Error("plugin file changed while opening");return wc(a)}finally{Ef(a)}}function Lf(n){let e=n?.configService,t=e?Is(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Ms(t)}async function Ac(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Lo(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>wt(),writeConfig:i=>ue(i),reloadRuntime:async i=>tt(n.getServer(),i??await X(),t),getDirectDispatcher:So,getSubscriptionDispatcher:()=>Lf(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Ec(e)){let l;try{if(!Pc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let c=ms(e,i.name);if(!c){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(fs(e,i.name,"plugin.json").toString("utf8"));if(!h||typeof h.name!="string"||typeof h.version!="string")throw new Error;u={name:h.name,version:h.version,coreApi:String(h.coreApi??"1"),description:h.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:h=>t.info(`[plugin:${u.name}] ${h}`),warn:h=>t.warn(`[plugin:${u.name}] ${h}`),error:h=>t.error(`[plugin:${u.name}] ${h}`)},r,c);l=p,fs(e,i.name,"plugin.js");let d=await import(If(ot(c,"plugin.js")).href),f=d?.activate??d?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(p.context);let g=p.cardPath?fs(e,i.name,p.cardPath):void 0;await p.commit(g,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(c){l?.abort(),s.failed.push({name:i.name,error:c?.message??String(c)}),t.warn(`plugin ${i.name} failed to load: ${c?.message??String(c)}`)}}return s}function Oc(n,e=Lo()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Ec(n).map(o=>{let r=o.enabled!==!1?t.get(o.name):void 0;return r?{...r,enabled:!0}:{name:o.name,version:null,enabled:o.enabled!==!1,error:"plugin missing or failed to load \u2014 its providers are unavailable until it is reinstalled"}})}var Pc,Mf,gs=w(()=>{"use strict";Io();Qt();go();Pt();q();Pc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Mf=n=>ot(n,"plugins")});import{existsSync as Ic,readFileSync as $f}from"node:fs";import{join as hs}from"node:path";import{NPM_SPEC_PATTERN as Nf,PLUGIN_NAME_PATTERN as Mc,PluginInstallError as Uf,installPluginFromNpm as Df,readPluginRecords as Ff}from"@wengine-ai/claude-code-router-shared";async function Hf(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 zf(n,e={}){let t=(e.registryBase??jf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(Lc.map(m=>Hf(t,m,o))),s=new Map,a=!1;for(let m of r)if(m.status==="fulfilled"){a=!0;for(let y of m.value){let b=y?.package,_=typeof b?.name=="string"?b.name:"";if(!_||!Nf.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>Lc.includes(x)))continue;let T=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:T,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=Ff(n),l=new Map(i.map(m=>[m.name,m])),c=m=>{let y=m.indexOf("@",m.startsWith("@")?1:0);return y>0?m.slice(0,y):m},u=new Map(i.filter(m=>typeof m.source=="string"&&m.source!=="").map(m=>[c(m.source),m])),p=m=>{if(!Mc.test(m))return null;try{let y=JSON.parse($f(hs(n,"plugins",m,"plugin.json"),"utf8"));return typeof y?.version=="string"?y.version:null}catch{return null}},d=[...s.values()].sort((m,y)=>m.name.localeCompare(y.name)).map(m=>{let y=l.get(m.name)??u.get(m.name),b=y!==void 0||Ic(hs(n,"plugins",m.name)),_=b?p(y?y.name:m.name):null;return{...m,installed:b,installedVersion:_,...b&&_!==null&&_!==m.version?{updateAvailable:!0}:{}}}),f=new Set(d.map(m=>m.name)),g=new Set,h=new Map;for(let[m,y]of u)g.add(y.name),!f.has(m)&&h.set(m,y.name);for(let m of i)f.has(m.name)||g.has(m.name)||h.set(m.name,m.name);for(let[m,y]of h){if(!Mc.test(y)||!Ic(hs(n,"plugins",y)))continue;let b=p(y);b!==null&&d.push({name:m,description:"",version:b,installed:!0,installedVersion:b,localOnly:!0})}return d.sort((m,y)=>m.name.localeCompare(y.name)),{ok:!0,plugins:d}}function Bf(n){switch(n){case"invalid_spec":return 400;case"already_installed":case"plugins_json_corrupted":return 409;case"npm_pack_failed":case"npm_pack_timeout":return 502;case"archive_too_large":case"archive_too_many_files":case"unsafe_archive_member":case"extract_failed":case"invalid_manifest":return 422;default:return 500}}function $c(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),l=n.headers?.host;if(typeof l=="string"&&!i.has(l))return!1;let c=n.headers?.origin;if(c!==void 0&&c!==""){if(typeof c!="string")return!1;let u="";try{let p=new URL(c);if(!["http:","https:"].includes(p.protocol))return!1;u=p.host}catch{return!1}if(!i.has(u))return!1}return!0}function Nc(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(!$c(r,n,t))return o(s,403,"local_only");try{return await zf(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(!$c(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,l=a.force===!0;try{let c=await Df({spec:i,configDir:e.configDir,force:l,registry:e.registry,timeoutMs:e.npmTimeoutMs});return n.log?.info?.(`provider plugin installed via API: ${c.manifest.name}@${c.manifest.version} (restart to activate)`),{ok:!0,name:c.manifest.name,version:c.manifest.version,restartRequired:!0}}catch(c){if(c instanceof Uf){let u=Bf(c.code);return u===502?n.log?.warn?.(`plugin install failed: ${c.code}`):n.log?.warn?.(`plugin install rejected: ${c.code}: ${c.message}`),o(s,u,c.code)}return n.log?.error?.(`plugin install crashed: ${c?.message??c}`),o(s,500,"install_failed")}})}var Lc,jf,Uc=w(()=>{"use strict";Lc=["ccr-provider-plugin","claude-code-router-plugin"],jf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Jf}from"@wengine-ai/claude-code-router-shared";import{join as ae,isAbsolute as Wf,normalize as Kf,dirname as Gf}from"path";import{fileURLToPath as Qf}from"url";import Vf from"@fastify/static";import{readdirSync as Dc,statSync as Yf,readFileSync as Fc,writeFileSync as Xf,existsSync as fe,unlinkSync as jc,rmSync as Zf}from"fs";import{homedir as ys}from"os";import{getPresetDir as ho,readManifestFromDir as _s,manifestToPresetFile as Hc,saveManifest as zc,isPresetInstalled as Bc,extractPreset as qf,HOME_DIR as bs,loadConfigFromManifest as em,downloadPresetToTemp as tm,findMarketPresetByName as nm,getMarketPresets as om,applyClientSelection as rm,disableClient as sm,enableClient as im,isClientId as am,listClientStatuses as Jc,restoreClient as cm,listProjectConfigs as lm,readProjectConfigById as ks,readProjectConfig as um,writeProjectConfig as Wc,deleteProjectConfig as dm,getClaudeProjectId as pm,getProjectConfigPath as fm,refreshCcrProjectTakeover as mm,refreshPiProjectTakeover as gm,refreshProjectTakeovers as hm,syncGlobalProjectTakeovers as Ts,getProjectTakeoverClients as vs,setProjectTakeover as xs,isProjectTakeoverClient as ym}from"@wengine-ai/claude-code-router-shared";import _m from"@fastify/multipart";import bm from"adm-zip";function Kc(n){let e=H();return rs(n,(t,o)=>e.isAvailable(t,o))}function Gc(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 km(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=Nt(t,e),s=Nt(o,e),a=[],i=new Set;for(let l of n||[])l&&l.name&&i.add(l.name);for(let l of Object.keys(r.byProvider||{}))i.add(l);for(let l of Object.keys(s.byProvider||{}))i.add(l);for(let l of i){let c=r.byProvider[l]||{inputTokens:0,outputTokens:0},u=s.byProvider[l]||{inputTokens:0,outputTokens:0},p=(c.inputTokens||0)+(c.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),f,g,h=(n||[]).find(m=>m&&m.name===l);h&&h.quota&&(f=h.quota.limit5h,g=h.quota.limit7d),a.push({provider:l,used5h:p,used7d:d,limit5h:f,limit7d:g})}return a}async function Qc(n,e){let t=n.app;at(),ut(),t.register(_m,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Kc(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,l)=>{let c=decodeURIComponent(i.params.modelId),u=Kc(e).find(p=>p.id===c);return u||(l.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${c}`}})}),t.post("/v1/messages/count_tokens",async(i,l)=>{let{messages:c,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[h,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${h}, model: ${m}`);let y=f.getTokenizerConfigForModel(h,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${h},${m}, using default tiktoken`);let b=await f.countTokens({messages:c,system:p,tools:u},y,h);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(h){i.log?.error(`Error using configured tokenizer: ${h.message}`),i.log?.error(h.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:ln(c,p,u)}}),t.get("/api/config",async(i,l)=>await wt()),t.get("/api/transformers",async(i,l)=>{let c=t._server.transformerService.getAllTransformers();return{transformers:Array.from(c.entries()).map(([p,d])=>({name:p,endpoint:d.endPoint||null}))}}),t.post("/api/config",async(i,l)=>{let c=i.body,u=Os(c||{});if(u.length>0)return l.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(g=>`${g.key}: ${g.error}`).join("; "),proxyErrors:u};let p=await io();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}Jf(c,d),n.pluginRegistry.applyConfigProtectors(c,d),await ue(c);let f;try{f=await Ts(c),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}return tt(n,c,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,l)=>{try{let c=await X();return{clients:Jc(c)}}catch(c){console.error("Failed to get client integrations:",c),l.status(500).send({error:c.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(i,l)=>{try{let c=i.body,u=Array.isArray(c?.enabled)?c.enabled:[],p=await X(),d=rm(p,u);await ue(d.config);let f=await Ts(d.config),g=Gc(t,f,"clients/apply");return{...d,success:d.success&&g,projectTakeoverSync:f}}catch(c){console.error("Failed to apply client integrations:",c),l.status(500).send({error:c.message||"Failed to apply client integrations"})}});async function o(i,l,c){try{let{id:u}=i.params;if(!am(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=c==="enable"?im(p,u):c==="restore"?cm(p,u):sm(p,u);await ue(p);let f=await Ts(p),g=Gc(t,f,`clients/${u}/${c}`);return{success:d.success&&g,result:d,results:[d],clients:Jc(p),config:p,projectTakeoverSync:f}}catch(u){console.error(`Failed to ${c} client integration:`,u),l.status(500).send({error:u.message||`Failed to ${c} client integration`})}}t.post("/api/clients/:id/enable",async(i,l)=>o(i,l,"enable")),t.post("/api/clients/:id/disable",async(i,l)=>o(i,l,"disable")),t.post("/api/clients/:id/restore",async(i,l)=>o(i,l,"restore")),t.get("/api/projects",async(i,l)=>{try{let c=await lm();return{projects:await Promise.all(c.map(async p=>{let d=await vs(p.path);return{...p,ccrTakeoverClients:d,ccrTakeover:d.length>0}}))}}catch(c){console.error("Failed to list project configs:",c),l.status(500).send({error:c.message||"Failed to list project configs"})}}),t.post("/api/projects",async(i,l)=>{try{let{path:c}=i.body||{};if(!c||typeof c!="string"||!Wf(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=Kf(c).replace(/[\\/]+$/,"")||c;if(await um(u)){l.status(409).send({error:"Project is already configured"});return}await Wc(u,{Router:{}});try{let f=await X();await xs(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await vs(u);return{id:pm(u),path:u,configPath:fm(u),Router:{},ccrTakeoverClients:d,ccrTakeover:d.length>0}}catch(c){console.error("Failed to add project config:",c),l.status(500).send({error:c.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(i,l)=>{try{let{id:c}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){l.status(400).send({error:"Router must be an object"});return}let p=await ks(c);if(!p){l.status(404).send({error:"Project config not found"});return}await Wc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await hm(p.path,d):(await mm(p.path,d,u),await gm(p.path,d,u));let f=await vs(p.path);return{id:c,path:p.path,configPath:p.configPath,Router:u,ccrTakeoverClients:f,ccrTakeover:f.length>0}}catch(c){console.error("Failed to update project config:",c),l.status(500).send({error:c.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(i,l)=>{try{let{id:c}=i.params,u=i.body||{},p;if(Array.isArray(u.clients))p=u.clients.filter(ym);else if(typeof u.enabled=="boolean")p=u.enabled?["claudeCode"]:[];else{l.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let d=await ks(c);if(!d){l.status(404).send({error:"Project config not found"});return}let f=await X(),g=await xs(d.path,p,f);return{id:c,path:d.path,ccrTakeoverClients:g,ccrTakeover:g.length>0}}catch(c){console.error("Failed to update ccr takeover status:",c),l.status(500).send({error:c.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,l)=>{try{let{id:c}=i.params,u=await ks(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let p=await X();await xs(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await dm(u.path),{success:!0}}catch(c){console.error("Failed to delete project config:",c),l.status(500).send({error:c.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:Gf(Qf(import.meta.url)),s=fe(ae(r,"index.html"))?r:fe(ae(r,"..","index.html"))?ae(r,".."):ae(r,"..","dist");t.register(Vf,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(i,l)=>l.redirect("/ui/")),t.get("/api/logs/files",async(i,l)=>{try{let c=ae(ys(),".claude-code-router","logs"),u=[];if(fe(c)){let p=Dc(c);for(let d of p)if(d.endsWith(".log")){let f=ae(c,d),g=Yf(f);u.push({name:d,path:f,size:g.size,lastModified:g.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(c){console.error("Failed to get log files:",c),l.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=ae(ys(),".claude-code-router","logs","app.log"),fe(u)?Fc(u,"utf8").split(`
402
+ `).filter(f=>f.trim()):[]}catch(c){console.error("Failed to get logs:",c),l.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=ae(ys(),".claude-code-router","logs","app.log"),fe(u)&&Xf(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(c){console.error("Failed to clear logs:",c),l.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:Bt()})),t.put("/api/debug-log",async i=>{let{enabled:l}=i.body;return Po(l),{enabled:Bt()}}),t.get("/api/usage",async(i,l)=>{try{let c=i.query;return ls({startTime:c.startDate,endTime:c.endDate,model:c.model,provider:c.provider,scenario:c.scenario,clientType:c.clientType,sessionId:c.sessionId,status:c.status,page:c.page?parseInt(c.page,10):void 0,pageSize:c.pageSize?parseInt(c.pageSize,10):void 0})}catch(c){console.error("Failed to query usage:",c),l.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(i,l)=>{try{let c=i.query;return Nt(c.startDate,c.endDate,c.status)}catch(c){console.error("Failed to query usage summary:",c),l.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(i,l)=>{try{let c=i.query;return us(c.beforeDate),{success:!0,message:c.beforeDate?"Usage data cleared before "+c.beforeDate:"All usage data cleared"}}catch(c){console.error("Failed to clear usage:",c),l.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,l)=>{try{let u=H().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,lastSuccessTime:f.lastSuccessTime??null,lastError:f.lastError,rateLimitUntil:f.rateLimitUntil??null})),probes:d,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to get provider health:",c),l.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,l)=>{try{let{providerName:c}=i.body;if(!c)return l.status(400),{error:"providerName is required"};let p=t._server?.activeProbeService;if(!p?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let d=await p.probeProviderManually(c);return d.success&&co(c,i.log),{provider:c,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.error,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe provider:",c),l.status(500).send({error:c.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,l)=>{try{let c=t._server,u=c?.activeProbeService;if(!u?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let p=(c?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let g=await u.probeProviderManually(f.name);return g.success&&co(f.name,i?.log),{provider:f.name,success:g.success,latencyMs:g.latencyMs,status:g.status,isSlow:g.isSlow,errorKind:g.errorKind??null,error:g.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe all providers:",c),l.status(500).send({error:c.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,l)=>{try{let u=(await X()).Providers||[],p=t._server?.pluginRegistry,d=t._server?.providerService;if(p&&d?.getProviders){let b=d.getProviders().filter(_=>_?.name&&_.enabled!==!1).map(_=>{let k=p.getManagedRuntimeFor(_);if(!(!k||typeof k.fetchQuota!="function"))return Vn(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,Ba).unref?.()});await Promise.race([Promise.all(b),_])}}let f=km(u),g=new Map(f.map(y=>[y.provider,y])),h=Jo();for(let y of f){let b=h.find(_=>_.provider===y.provider);b&&b.limit!=null&&!Zt(b.reset)&&(y.limit5h=b.limit,y.used5h=b.limit-(b.remaining??0),b.reset&&(y.reset5h=new Date(b.reset*1e3).toISOString()))}let m=tr();for(let y of m){let b=g.get(y.provider);b||(b={provider:y.provider,used5h:0,used7d:0},f.push(b),g.set(y.provider,b)),typeof y.totalBalance=="number"?(b.limit7d=y.totalBalance,b.type7d=y.currency?"balance":"rateLimit",y.currency&&(b.currency=y.currency),typeof y.usedBalance=="number"?b.used7d=y.usedBalance:typeof y.remainingBalance=="number"?b.used7d=Math.max(0,y.totalBalance-y.remainingBalance):(b.used7d=0,b.limit7d=y.totalBalance)):typeof y.usedBalance=="number"&&(b.used7d=y.usedBalance);let _=Zt(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=Zt(typeof y.resetTime7d=="string"?Date.parse(y.resetTime7d)/1e3:void 0);typeof y.usedDailyBalance=="number"&&!_&&(b.used5h=y.usedDailyBalance,b.type5h="rateLimit"),typeof y.limitDaily=="number"&&!_&&(b.limit5h=y.limitDaily,b.type5h="rateLimit"),typeof y.resetTime=="string"&&!_&&(y.limitDaily!==void 0?b.reset5h=y.resetTime:b.reset7d=y.resetTime),typeof y.resetTime7d=="string"&&!k&&(b.reset7d=y.resetTime7d)}return{quotas:f,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to compute provider quota:",c),l.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,l)=>{try{let c=ae(bs,"presets");if(!fe(c))return{presets:[]};let p=Dc(c,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let g=ae(c,f);try{let h=ae(g,"manifest.json"),m=Fc(h,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:T,API_TIMEOUT_MS:x,PROXY_URL:v,PROXY_GLOBAL_ENABLED:P,LOG:E,LOG_LEVEL:R,StatusLine:A,NON_INTERACTIVE_MODE:D,...C}=y;d.push({id:f,name:C.name||f,version:C.version||"1.0.0",description:C.description,author:C.author,homepage:C.homepage,repository:C.repository,license:C.license,keywords:C.keywords,ccrVersion:C.ccrVersion,source:C.source,sourceType:C.sourceType,checksum:C.checksum,installed:!0})}catch(h){console.error(`Failed to read preset ${f}:`,h)}}return{presets:d}}catch(c){console.error("Failed to get presets:",c),l.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(i,l)=>{try{let{name:c}=i.params,u=ho(c);if(!fe(u)){l.status(404).send({error:"Preset not found"});return}let p=await _s(u);return{...Hc(p),config:em(p,u),userValues:p.userValues||{}}}catch(c){console.error("Failed to get preset:",c),l.status(500).send({error:c.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(i,l)=>{try{let{name:c}=i.params,{secrets:u}=i.body,p=ho(c);if(!fe(p)){l.status(404).send({error:"Preset not found"});return}let f={...await _s(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await zc(c,f),{success:!0,message:"Preset applied successfully"}}catch(c){console.error("Failed to apply preset:",c),l.status(500).send({error:c.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(i,l)=>{try{let{name:c}=i.params,u=ho(c);if(!fe(u)){l.status(404).send({error:"Preset not found"});return}return Zf(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(c){console.error("Failed to delete preset:",c),l.status(500).send({error:c.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(i,l)=>{try{return{presets:await om()}}catch(c){console.error("Failed to get market presets:",c),l.status(500).send({error:c.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(i,l)=>{try{let{presetName:c}=i.body;if(!c){l.status(400).send({error:"Preset name is required"});return}let u=await nm(c);if(!u){l.status(400).send({error:"Preset not found in marketplace",message:`Preset '${c}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){l.status(400).send({error:"Invalid preset data",message:`Preset '${c}' does not have repository information`});return}let p=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!p){l.status(400).send({error:"Invalid GitHub repository URL"});return}let[,d,f]=p,g=u.name||c;if(await Bc(g)){l.status(409).send({error:"Preset already installed",message:`Preset '${g}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:g});return}let h=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await tm(h),y=await a(m);if(await Bc(g)){jc(m),l.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let b=ho(g);await qf(m,b);let _=await _s(b);return _.repository=u.repo,u.url&&(_.source=u.url),await zc(g,_),jc(m),{success:!0,presetName:g,preset:{...y.metadata,installed:!0}}}catch(c){console.error("Failed to install preset from GitHub:",c),l.status(500).send({error:c.message||"Failed to install preset from GitHub"})}});async function a(i){let l=new bm(i),c=l.getEntry("manifest.json");if(c||(c=l.getEntries().find(d=>d.entryName.includes("manifest.json"))||null),!c)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(c.getData().toString("utf-8"));return Hc(u)}return t.get("/api/plugins",async()=>({plugins:Oc(bs,n.pluginRegistry)})),Nc(t,{configDir:bs,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,l)=>{let{name:c,file:u}=i.params,p=n.pluginRegistry.getPublicCard(c,u);return p?(l.header("Content-Type","application/javascript; charset=utf-8"),l.header("X-Content-Type-Options","nosniff"),l.header("Cache-Control","no-store"),l.send(p)):l.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var Vc=w(()=>{"use strict";Pe();Se();Ce();Ir();Se();q();rt();re();At();go();gs();Uc();Pt();Ut();ss()});function Tm(n,e){let t=n?.Router,{family:o}=mt(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function Yc(n){return n?.Router?.image}function vm(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 xm(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var Ss,yo,Cs,Xc,Zc=w(()=>{"use strict";Pe();Ss=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},yo=new Ss;Cs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Tm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!vm(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&gt(e.body.model)?!1:(xm(e.body.messages),s&&!!Yc(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let l=yo.getImage(`${t.req.id}_Image#${i}`);l&&o.push({type:"image",source:l})});else{let i=yo.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(l=>l.type==="text"&&!l.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:Yc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
397
403
  When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
398
404
  Do not ignore or deviate from the task.
399
405
  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.
@@ -406,5 +412,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
406
412
 
407
413
  Do not attempt to describe or analyze the image directly yourself.
408
414
  Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
409
- 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")ho.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:(ho.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}})})}},Qc=new vs});var xs,Yc,yo,Xc=P(()=>{"use strict";Vc();xs=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}},Yc=new xs;Yc.registerAgent(Qc);yo=Yc});import{EventEmitter as Tm}from"node:events";import{performance as Zc}from"node:perf_hooks";import vm from"json5";function Sm(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 el(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,e)}function Ss(n){return n.usageSessionId||n.id}function _o(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Ss(n)}`}function Ft(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ie(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function Cm(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Ee(e.usage):e.response?.usage?Ee(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Rm(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();co(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")){el(n,t);let r=_o(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function wm(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of yo.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 tl(n){return{authClient:(e,t)=>Rm(e,t,n),agent:(e,t)=>wm(e,t,n)}}function nl(n,e){n.addHook("onRequest",async t=>{let o;try{o=new URL(`http://127.0.0.1${t.url}`)}catch{return}t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Zc.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();co(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",qc.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){el(t,e);let c=Ss(t),l=_o(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new ie),m,y=-1,b="",_="",k="",T=[],S=[];return s(null,Xn(h,async(v,w)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let R=t.agents.find(E=>yo.getAgent(E)?.tools.get(v.data.content_block.name));if(R){m=yo.getAgent(R),y=v.data.index,b=v.data.content_block.name,k=v.data.content_block.id;return}}if(y>-1&&v.data.index===y&&v.data?.delta?.type==="input_json_delta"){_+=v.data?.delta?.partial_json;return}if(y>-1&&v.data.index===y&&v.data?.type==="content_block_stop"){try{let R=vm.parse(_);S.push({type:"tool_use",id:k,name:b,input:R});let E=await m?.tools.get(b)?.handler(R,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:E}),m=void 0,y=-1,b="",_="",k=""}catch(R){console.log(R)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:S}),t.body.messages.push({role:"user",content:T});let R=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(!R.ok)return;let I=R.body.pipeThrough(new ie).getReader();for(;;)try{let{value:U,done:C}=await I.read();if(C)break;let A=U;if(["message_start","message_stop"].includes(A.event))continue;if(!w.desiredSize)break;w.enqueue(A)}catch(U){if(U.name==="AbortError"||U.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw U}return}return v}catch(R){if(console.error("Unexpected error in stream processing:",R),R.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw R}}).pipeThrough(new Ze))}let[p,d]=r.tee(),f=async g=>{let m=g.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&Ft(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=Y.get(l)||{},S=Ee(k.usage),v=Ae(T,S,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:c,capturedUsage:S,mergedUsage:v}),(S?.cache_read_input_tokens||S?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:S?.cache_read_input_tokens,cache_creation:S?.cache_creation_input_tokens}),Y.put(l,v)}if(k?.response?.usage){let T=Ee(k.response.usage),S=Y.get(l)||{},v=Ae(S,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:c,capturedUsage:T,mergedUsage:v}),Y.put(l,v)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:g,value:h}=await f.read();if(g)break;let m=h.event,y=h.data;m==="message_start"&&y?.message?.model&&Ft(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&Ft(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ee(b),k=Y.get(l)||{},T=Ae(k,_,m==="message_start");Y.put(l,T)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{f.releaseLock()}})(),s(null,p)}let u=Cm(r);if(u?.usage&&Y.put(l,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(qc.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=>{Vo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Vo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async v=>{if(!v)return;let w;try{await Promise.race([v,new Promise(R=>{w=setTimeout(R,xm)})])}finally{w&&clearTimeout(w)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=Ss(t),a=s,i=t.sessionId||s,c=o.statusCode>=400,l=c?void 0:Y.get(_o(t)),u=cs(a),p=H(),d,f,g=t.sseError,h=g&&(g.type||g.code||g.message),m=l?.output_tokens&&l.output_tokens>0,y=t.contentDelivered===!0,b=c||h&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(g),f=JSON.stringify(g)),f=f||t.errorResponseBody;let v=Ie(t);Sm(o.statusCode,d)?p.markRateLimited(t.provider||"",v,120,d):p.recordFailure(t.provider||"",v,d)}else{let v=Ie(t);p.recordSuccess(t.provider||"",v)}let _=l?.cache_read_input_tokens??0,T=l?.input_tokens||0||t.tokenCount||0;!l?.usage_estimated&&!_&&t.tokenCount&&l?.input_tokens&&l.input_tokens<t.tokenCount&&(_=t.tokenCount-l.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:l.input_tokens,impliedCache:_}));let S=b?0:l?.output_tokens||0;!b&&t.body?.stream&&T===0&&S===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ie(t),usageSessionId:i,tokenCount:t.tokenCount,cachedUsage:l,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:i,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:Ie(t),upstreamModel:t.upstreamModel||Ie(t)||void 0,...l?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Be(t),stream:t.body?.stream??!1,inputTokens:T,outputTokens:S,cacheReadInputTokens:_,cacheCreationInputTokens:l?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Zc.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(_o(t))}catch(r){console.error("Usage tracking error:",r)}})}var xm,qc,ol=P(()=>{"use strict";Je();on();tn();re();$r();Nr();Ur();Ut();gn();Xc();os();pn();xm=1500;qc=new Tm});var sl={};To(sl,{createCcrServer:()=>Lm});import{homedir as Pm}from"os";import{join as Em}from"path";import{createStream as Am}from"rotating-file-stream";import{CONFIG_FILE as Om,HOME_DIR as rl,listPresets as Im,ensureCcrSelfProvider as Mm}from"@wengine-ai/claude-code-router-shared";async function Lm(n={}){await gc(),await ro();let e=await qr();Mm(e).changed&&(await ue(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;Xa();let c=f=>(f>9?"":"0")+f,l=(f,g)=>{let h;f?typeof f=="number"?h=new Date(f):h=f:h=new Date;let m=h.getFullYear()+""+c(h.getMonth()+1),y=c(h.getDate()),b=c(h.getHours()),_=c(h.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${c(h.getSeconds())}${g?`_${g}`:""}.log`},u;n.logger!==void 0?u=n.logger:(kc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:Am(l,{path:rl,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await Im(),d=new al({jsonPath:Om,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:Em(Pm(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await wc({configDir:rl,registry:d.pluginRegistry,getServer:()=>d,log:{info:y=>d.app?.log?.info?.(y),warn:y=>d.app?.log?.warn?.(y),error:y=>d.app?.log?.error?.(y)}});f.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(y=>`${y.name} (${y.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(y=>`${y.name}@${y.version}`).join(", ")}`),f.loaded.length&&tt(d,e,d.app.log),await Wc(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Be(y.req):"unknown";$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:y.sessionId||"",provider:y.provider||"",originalModel:y.originalModel||"",model:y.model||"",modelFamily:y.modelFamily||"",scenarioType:y.scenarioType||"default",clientType:b,stream:y.stream??!1,inputTokens:y.inputTokens||0,outputTokens:0,cacheReadInputTokens:y.cacheReadInputTokens||0,cacheCreationInputTokens:y.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:y.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},nl(d,e),d.ccrPreHandlerCallbacks=tl(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,b)=>{if(y.status==="rejected"){let _=p[b],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await vc(d,e),Et(e,d.app?.log);let h=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",h),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",h),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var il=P(()=>{"use strict";cl();hc();Pt();Tc();Wr();xc();Kc();ps();mo();ol();At();Ut();Je()});import $m from"fastify";import Nm from"@fastify/cors";function Um(n={}){let e=$m({bodyLimit:52428800,...n});return e.setErrorHandler(Ls),e.register(Nm),e}async function Dm(n={}){return(await Promise.resolve().then(()=>(il(),sl))).createCcrServer(n)}var Cs,al,hv,cl=P(()=>{Co();zt();pn();sr();pr();mr();Pe();on();Yn();re();Se();Ce();q();Je();pn();Qt();je();Je();Pe();Co();sr();pr();mr();Xr();Dr();re();Se();Pr();Ce();re();Yn();rt();q();Pt();gn();At();ns();os();Ut();Cs=class{app;pluginRegistry=new st;namespaceProviders=[];reloadProviders(e){let t=e?.Providers??e?.providers??[];this.configService.set("providers",t),this.providerService.reload();for(let o of this.namespaceProviders)o.providers.reload()}reloadNamespaceProviders(e,t){let o=this.namespaceProviders.find(r=>r.name===e);if(!o)throw new Error(`unknown namespace ${e}`);o.config.set("providers",t),o.providers.reload()}configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:i,...c}=e;this.app=Um({...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 Ye(this.configService,this.app.log),this.tokenizerService=new Xe(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ge(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Me({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ye(o,this.app.log),a=new Xe(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ge(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async c=>{c.decorate("pluginRegistry",this.pluginRegistry),c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,u)=>{let p=new URL(`http://127.0.0.1${l.url}`);l.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!l.body||typeof l.body!="object")return;let g=l.ccrHookOrder||=[];if(g.push("request-normalize"),f&&l.body.input&&!l.body.messages&&ht(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),g.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),Re(l,o.getAll()),g.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(g.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){g.push("router"),l.body?.model&&await un(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}),g.push("provider-model-normalize");try{let h=l.body;if(!h||!h.model)return u.code(400).send({error:"Missing model in request body"});let m=h.model.split(","),y=h.model;if(m.length>1){let[b,..._]=m;y=_.join(","),h.model=y,l.provider=b}l.model=y}catch(h){return l.log.error({error:h},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Qi(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{Ir()}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 So()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{at()}catch{}try{ut()}catch{}try{Fo()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=bt(()=>this.providerService.getProviders(),t,o=>de(this.configService,o),this.app.log,o=>this.configService.get(o),o=>this.pluginRegistry?.getManagedRuntimeFor(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},al=Cs;hv=Dm});cl();export{Vn as ActiveProbeService,Me as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ge as ProviderService,ie as SSEParserTransform,Ze as SSESerializerTransform,Xe as TokenizerService,Ye as TransformerService,co as apiKeyAuth,Re as applyClientAdapter,so as backupConfigFile,Ri as builtinClientAdapterRegistry,ln as calculateTokenCount,Gu as clearClientAdapterCaches,ao as clearProviderHealth,So as closeProxyDispatchers,rc as collectReachableModelKeys,Dm as createCcrServer,al as default,Be as detectClientType,Ni as diagnoseResolutionFailure,he as extractSessionIdFromUserId,za as getActiveProbeService,er as getAllQuotaResults,Bo as getAllRateLimitInfo,Pi as getClientAdapter,Ht as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Rr as getQuotaAdapter,rn as getQuotaResult,ql as getRateLimitInfo,Bt as getRuntimeDebugLog,hv as getServer,qr as initConfig,ro as initDir,Fo as initProviderHealthPersistence,ut as initQuotaStorePersistence,at as initRateLimitPersistence,wi as isClientType,Os as isGlobalProxyEnabled,ts as listAnthropicCompatibleModels,Ae as mergeUsageCapture,ge as normalizeSessionId,Ee as normalizeUsagePayload,kt as pluginManager,X as readConfigFile,wt as readConfigFileRaw,Et as reconcileHealthStore,Mr as resetActiveProbeService,de as resolveProviderProxyUrl,Xn as rewriteStream,un as router,Fi as searchProjectBySession,Y as sessionUsageCache,wo as setRuntimeDebugLog,bt as startActiveProbe,Ir as stopActiveProbe,lt as storeQuotaResult,no as tokenSpeedPlugin,mc as usageStore,ue as writeConfigFile};
415
+ Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")yo.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],l=a.content.filter(u=>u.type!=="image"?!0:(yo.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),c=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=l.length>0?[{type:"text",text:c},...l]:c}})})}},Xc=new Cs});var Rs,qc,_o,el=w(()=>{"use strict";Zc();Rs=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},qc=new Rs;qc.registerAgent(Xc);_o=qc});import{EventEmitter as Sm}from"node:events";import{performance as tl}from"node:perf_hooks";import Cm from"json5";function wm(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 ol(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,e)}function ws(n){return n.usageSessionId||n.id}function bo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${ws(n)}`}function Ft(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ie(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function Pm(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Ee(e.usage):e.response?.usage?Ee(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Em(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();lo(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o;try{o=new URL(`http://127.0.0.1${n.url}`)}catch{return}if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){ol(n,t);let r=bo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function Am(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of _o.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function rl(n){return{authClient:(e,t)=>Em(e,t,n),agent:(e,t)=>Am(e,t,n)}}function sl(n,e){n.addHook("onRequest",async t=>{let o;try{o=new URL(`http://127.0.0.1${t.url}`)}catch{return}t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=tl.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname;if(!r)try{r=new URL(`http://127.0.0.1${t.url}`).pathname}catch{r=""}r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=l=>l?a(l):s();lo(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",nl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){ol(t,e);let l=ws(t),c=bo(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new ie),m,y=-1,b="",_="",k="",T=[],x=[];return s(null,Zn(h,async(v,P)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let E=t.agents.find(R=>_o.getAgent(R)?.tools.get(v.data.content_block.name));if(E){m=_o.getAgent(E),y=v.data.index,b=v.data.content_block.name,k=v.data.content_block.id;return}}if(y>-1&&v.data.index===y&&v.data?.delta?.type==="input_json_delta"){_+=v.data?.delta?.partial_json;return}if(y>-1&&v.data.index===y&&v.data?.type==="content_block_stop"){try{let E=Cm.parse(_);x.push({type:"tool_use",id:k,name:b,input:E});let R=await m?.tools.get(b)?.handler(E,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:R}),m=void 0,y=-1,b="",_="",k=""}catch(E){console.log(E)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:T});let E=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!E.ok)return;let A=E.body.pipeThrough(new ie).getReader();for(;;)try{let{value:D,done:C}=await A.read();if(C)break;let O=D;if(["message_start","message_stop"].includes(O.event))continue;if(!P.desiredSize)break;P.enqueue(O)}catch(D){if(D.name==="AbortError"||D.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw D}return}return v}catch(E){if(console.error("Unexpected error in stream processing:",E),E.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw E}}).pipeThrough(new Ze))}let[p,d]=r.tee(),f=async g=>{let m=g.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&Ft(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=Y.get(c)||{},x=Ee(k.usage),v=Ae(T,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:x,mergedUsage:v}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),Y.put(c,v)}if(k?.response?.usage){let T=Ee(k.response.usage),x=Y.get(c)||{},v=Ae(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:T,mergedUsage:v}),Y.put(c,v)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:g,value:h}=await f.read();if(g)break;let m=h.event,y=h.data;m==="message_start"&&y?.message?.model&&Ft(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&Ft(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ee(b),k=Y.get(c)||{},T=Ae(k,_,m==="message_start");Y.put(c,T)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{f.releaseLock()}})(),s(null,p)}let u=Pm(r);if(u?.usage&&Y.put(c,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(nl.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{Yo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Yo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async v=>{if(!v)return;let P;try{await Promise.race([v,new Promise(E=>{P=setTimeout(E,Rm)})])}finally{P&&clearTimeout(P)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=ws(t),a=s,i=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:Y.get(bo(t)),u=ds(a),p=H(),d,f,g=t.sseError,h=g&&(g.type||g.code||g.message),m=c?.output_tokens&&c.output_tokens>0,y=t.contentDelivered===!0,b=l||h&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(g),f=JSON.stringify(g)),f=f||t.errorResponseBody;let v=Ie(t);wm(o.statusCode,d)?p.markRateLimited(t.provider||"",v,120,d):p.recordFailure(t.provider||"",v,d)}else{let v=Ie(t);p.recordSuccess(t.provider||"",v)}let _=c?.cache_read_input_tokens??0,T=c?.input_tokens||0||t.tokenCount||0;!c?.usage_estimated&&!_&&t.tokenCount&&c?.input_tokens&&c.input_tokens<t.tokenCount&&(_=t.tokenCount-c.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:c.input_tokens,impliedCache:_}));let x=b?0:c?.output_tokens||0;!b&&t.body?.stream&&T===0&&x===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ie(t),usageSessionId:i,tokenCount:t.tokenCount,cachedUsage:c,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:i,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:Ie(t),upstreamModel:t.upstreamModel||Ie(t)||void 0,...c?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Be(t),stream:t.body?.stream??!1,inputTokens:T,outputTokens:x,cacheReadInputTokens:_,cacheCreationInputTokens:c?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(tl.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(bo(t))}catch(r){console.error("Usage tracking error:",r)}})}var Rm,nl,il=w(()=>{"use strict";Je();on();tn();re();Dr();Fr();jr();Ut();gn();el();is();pn();Rm=1500;nl=new Sm});var cl={};vo(cl,{createCcrServer:()=>Um});import{homedir as Om}from"os";import{join as Im}from"path";import{createStream as Mm}from"rotating-file-stream";import{CONFIG_FILE as Lm,HOME_DIR as al,listPresets as $m,ensureCcrSelfProvider as Nm}from"@wengine-ai/claude-code-router-shared";async function Um(n={}){await _c(),await so();let e=await ns();Nm(e).changed&&(await ue(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;ec();let l=f=>(f>9?"":"0")+f,c=(f,g)=>{let h;f?typeof f=="number"?h=new Date(f):h=f:h=new Date;let m=h.getFullYear()+""+l(h.getMonth()+1),y=l(h.getDate()),b=l(h.getHours()),_=l(h.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${l(h.getSeconds())}${g?`_${g}`:""}.log`},u;n.logger!==void 0?u=n.logger:(xc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:Mm(c,{path:al,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await $m(),d=new ul({jsonPath:Lm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:Im(Om(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await Ac({configDir:al,registry:d.pluginRegistry,getServer:()=>d,log:{info:y=>d.app?.log?.info?.(y),warn:y=>d.app?.log?.warn?.(y),error:y=>d.app?.log?.error?.(y)}});f.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(y=>`${y.name} (${y.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(y=>`${y.name}@${y.version}`).join(", ")}`),f.loaded.length&&tt(d,e,d.app.log),await Qc(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Be(y.req):"unknown";$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:y.sessionId||"",provider:y.provider||"",originalModel:y.originalModel||"",model:y.model||"",modelFamily:y.modelFamily||"",scenarioType:y.scenarioType||"default",clientType:b,stream:y.stream??!1,inputTokens:y.inputTokens||0,outputTokens:0,cacheReadInputTokens:y.cacheReadInputTokens||0,cacheCreationInputTokens:y.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:y.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},sl(d,e),d.ccrPreHandlerCallbacks=rl(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,b)=>{if(y.status==="rejected"){let _=p[b],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await Cc(d,e),Et(e,d.app?.log);let h=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",h),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",h),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var ll=w(()=>{"use strict";dl();bc();Pt();Sc();Qr();Rc();Vc();gs();go();il();At();Ut();Je()});import Dm from"fastify";import Fm from"@fastify/cors";function jm(n={}){let e=Dm({bodyLimit:52428800,...n});return e.setErrorHandler(Us),e.register(Fm),e}async function Hm(n={}){return(await Promise.resolve().then(()=>(ll(),cl))).createCcrServer(n)}var Ps,ul,bv,dl=w(()=>{Ro();zt();pn();ir();gr();yr();Pe();on();Xn();re();Se();Ce();q();Je();pn();Qt();je();Je();Pe();Ro();ir();gr();yr();es();Hr();re();Se();Or();Ce();re();Xn();rt();q();Pt();gn();At();ss();is();Ut();Ps=class{app;pluginRegistry=new st;namespaceProviders=[];reloadProviders(e){let t=e?.Providers??e?.providers??[];this.configService.set("providers",t),this.providerService.reload();for(let o of this.namespaceProviders)o.providers.reload()}reloadNamespaceProviders(e,t){let o=this.namespaceProviders.find(r=>r.name===e);if(!o)throw new Error(`unknown namespace ${e}`);o.config.set("providers",t),o.providers.reload()}configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:i,...l}=e;this.app=jm({...l,logger:l.logger??!0}),this.app._server=this,this.app.addHook("onClose",async()=>{this.pluginRegistry.dispose(),this.tokenizerService?.dispose()});let c={initialConfig:t};o!==void 0&&(c.jsonPath=o),r!==void 0&&(c.envPath=r),s!==void 0&&(c.useEnvFile=s),a!==void 0&&(c.useJsonFile=a),i!==void 0&&(c.useEnvironmentVariables=i),this.configService=new Me(c),this.transformerService=new Ye(this.configService,this.app.log),this.tokenizerService=new Xe(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ge(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Me({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ye(o,this.app.log),a=new Xe(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ge(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async l=>{l.decorate("pluginRegistry",this.pluginRegistry),l.decorate("configService",o),l.decorate("transformerService",r),l.decorate("providerService",s),l.decorate("tokenizerService",a),l.decorate("recordUsage",this.recordUsage||(()=>{})),l.addHook("preHandler",async(c,u)=>{let p=new URL(`http://127.0.0.1${c.url}`);c.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!c.body||typeof c.body!="object")return;let g=c.ccrHookOrder||=[];if(g.push("request-normalize"),f&&c.body.input&&!c.body.messages&&ht(c.body),c.body.stream===void 0&&(c.body.stream=!1),c.log.info({data:c.body,type:"request body"}),g.push("adapter"),!c.originalModel&&c.body.model&&(c.originalModel=c.body.model),Re(c,o.getAll()),g.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(c,u),u.sent))&&(g.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(c,u),u.sent)))){g.push("router"),c.body?.model&&await un(c,u,{configService:o,tokenizerService:a}),c.usageCacheKey&&Y.put(c.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),g.push("provider-model-normalize");try{let h=c.body;if(!h||!h.model)return u.code(400).send({error:"Missing model in request body"});let m=h.model.split(","),y=h.model;if(m.length>1){let[b,..._]=m;y=_.join(","),h.model=y,c.provider=b}c.model=y}catch(h){return c.log.error({error:h},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Xi(l)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{$r()}catch{}await this.app.close(),process.exit(0)},o=()=>void t("SIGINT"),r=()=>void t("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",r),this.app.addHook("onClose",async()=>{process.off("SIGINT",o),process.off("SIGTERM",r),this.signalHandlersRegistered=!1;try{this.tokenizerService.dispose()}catch{}await Co()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{at()}catch{}try{ut()}catch{}try{jo()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=bt(()=>this.providerService.getProviders(),t,o=>de(this.configService,o),this.app.log,o=>this.configService.get(o),o=>this.pluginRegistry?.getManagedRuntimeFor(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},ul=Ps;bv=Hm});dl();export{Yn as ActiveProbeService,Me as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ge as ProviderService,ie as SSEParserTransform,Ze as SSESerializerTransform,Xe as TokenizerService,Ye as TransformerService,lo as apiKeyAuth,Re as applyClientAdapter,io as backupConfigFile,Ei as builtinClientAdapterRegistry,ln as calculateTokenCount,Yu as clearClientAdapterCaches,co as clearProviderHealth,Co as closeProxyDispatchers,ac as collectReachableModelKeys,Hm as createCcrServer,ul as default,Be as detectClientType,Fi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Wa as getActiveProbeService,tr as getAllQuotaResults,Jo as getAllRateLimitInfo,Oi as getClientAdapter,Ht as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Er as getQuotaAdapter,rn as getQuotaResult,nu as getRateLimitInfo,Bt as getRuntimeDebugLog,bv as getServer,ns as initConfig,so as initDir,jo as initProviderHealthPersistence,ut as initQuotaStorePersistence,at as initRateLimitPersistence,Ai as isClientType,Ls as isGlobalProxyEnabled,rs as listAnthropicCompatibleModels,Ae as mergeUsageCapture,ge as normalizeSessionId,Ee as normalizeUsagePayload,kt as pluginManager,X as readConfigFile,wt as readConfigFileRaw,Et as reconcileHealthStore,Nr as resetActiveProbeService,de as resolveProviderProxyUrl,Zn as rewriteStream,un as router,zi as searchProjectBySession,Y as sessionUsageCache,Po as setRuntimeDebugLog,bt as startActiveProbe,$r as stopActiveProbe,lt as storeQuotaResult,oo as tokenSpeedPlugin,yc as usageStore,ue as writeConfigFile};
410
416
  //# sourceMappingURL=server.mjs.map