@wengine-ai/llms 2.3.2423 → 2.3.2425

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,38 @@
1
1
  import { createRequire as __createRequire } from "node:module"; import { fileURLToPath as __fileURLToPath } from "node:url"; import { dirname as __pathDirname } from "node:path"; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __pathDirname(__filename);
2
- var go=Object.defineProperty;var ol=Object.getOwnPropertyDescriptor;var rl=Object.getOwnPropertyNames;var sl=Object.prototype.hasOwnProperty;var ot=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var ho=(n,e)=>{for(var t in e)go(n,t,{get:e[t],enumerable:!0})},il=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rl(e))!sl.call(n,r)&&r!==t&&go(n,r,{get:()=>e[r],enumerable:!(o=ol(e,r))||o.enumerable});return n};var al=n=>il(go({},"__esModule",{value:!0}),n);import{Agent as cl,ProxyAgent as ll}from"undici";function dl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(ul.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 xs(n){let e=[];for(let t of[...Ts,vs]){let o=n[t];if(o==null)continue;let r=dl(o);r.ok||e.push({key:t,error:r.error})}return e}function bo(){return yo||(yo=new cl({connect:{timeout:15e3}})),yo}function Ss(n){let e=n.get(vs);return(typeof e=="string"?e.trim():"")||void 0}function Cs(n){return n?K(n):bo()}function Ht(n){for(let e of Ts){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Rs(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 Rs(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function K(n){let e=pl(n),t=jt.get(e);if(t)return t;let o=new ll(e);return jt.set(e,o),o}async function _o(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function pl(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 Ts,vs,ul,jt,yo,q=w(()=>{"use strict";Ts=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],vs="SUBSCRIPTION_PROXY_URL",ul=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as fl,existsSync as ws}from"fs";import{join as Ps}from"path";import{config as ml}from"dotenv";import gl from"json5";var Ae,ko=w(()=>{"use strict";q();Ae=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:Ps(process.cwd(),this.options.jsonPath);if(ws(e))try{let t=fl(e,"utf-8"),o=gl.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:Ps(process.cwd(),this.options.envPath);if(ws(e))try{let t=ml({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 B(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 Es(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 vo(n){To=n}function Bt(){return To}function Jt(n){return To||n.get("DEBUG_LOG")===!0}function Is(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Oe:{maxBodyLength:e.maxBodyLength??Oe.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Oe.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();hl.has(r)||yl.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 Ms(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,Oe.maxBodyLength)})}function Ls(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,Oe.maxBodyLength)}:{}})}function As(n,e,t,o){let r=bl(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Oe.maxBodyLength)})}function bl(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 Os(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function $s(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 yo=Object.defineProperty;var sl=Object.getOwnPropertyDescriptor;var il=Object.getOwnPropertyNames;var al=Object.prototype.hasOwnProperty;var rt=(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 _o=(n,e)=>{for(var t in e)yo(n,t,{get:e[t],enumerable:!0})},cl=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of il(e))!al.call(n,r)&&r!==t&&yo(n,r,{get:()=>e[r],enumerable:!(o=sl(e,r))||o.enumerable});return n};var ll=n=>cl(yo({},"__esModule",{value:!0}),n);import{Agent as ul,ProxyAgent as dl}from"undici";function fl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(pl.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 Ss(n){let e=[];for(let t of[...xs,Cs]){let o=n[t];if(o==null)continue;let r=fl(o);r.ok||e.push({key:t,error:r.error})}return e}function ko(){return bo||(bo=new ul({connect:{timeout:15e3}})),bo}function Rs(n){let e=n.get(Cs);return(typeof e=="string"?e.trim():"")||void 0}function ws(n){return n?K(n):ko()}function Ht(n){for(let e of xs){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Ps(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 Ps(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function K(n){let e=ml(n),t=jt.get(e);if(t)return t;let o=new dl(e);return jt.set(e,o),o}async function To(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function ml(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 xs,Cs,pl,jt,bo,q=w(()=>{"use strict";xs=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Cs="SUBSCRIPTION_PROXY_URL",pl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as gl,existsSync as Es}from"fs";import{join as As}from"path";import{config as hl}from"dotenv";import yl from"json5";var Oe,vo=w(()=>{"use strict";q();Oe=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:As(process.cwd(),this.options.jsonPath);if(Es(e))try{let t=gl(e,"utf-8"),o=yl.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:As(process.cwd(),this.options.envPath);if(Es(e))try{let t=hl({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 B(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 Os(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 Co(n){xo=n}function Bt(){return xo}function Jt(n){return xo||n.get("DEBUG_LOG")===!0}function Ls(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Ie:{maxBodyLength:e.maxBodyLength??Ie.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Ie.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();_l.has(r)||bl.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 Ns(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,Ie.maxBodyLength)})}function $s(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,Ie.maxBodyLength)}:{}})}function Is(n,e,t,o){let r=kl(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Ie.maxBodyLength)})}function kl(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 Ms(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Fs(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:c}=await r.read();if(i)break;a+=c;let l=a.split(`
3
3
 
4
- `);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?As(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&&As(e,t,s,a.trim()),s++),Os(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Os(e,t,s)}finally{r.releaseLock()}})()}var hl,yl,Oe,To,rt=w(()=>{"use strict";hl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),yl=/token|secret|credential|passwd|password/i,Oe={maxBodyLength:4096,maxStreamChunks:100},To=!1});function Ns(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=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:_l(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function _l(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 Fs=w(()=>{q();rt()});function Tl(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Us(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function xo(n){if(Us(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(kl.some(s=>r.includes(s))){e=!0;break}vl.some(s=>r.includes(s))&&(t=!0)}}return e||Tl(n)?"content":t?"empty":"pending"}async function Ds(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(),h=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),h===p)return l(xo(a)==="content"?"content":"pending",Gt(o,f));if(h.done){a+=r.decode();let m=xo(a);return l(m==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let g=xo(a);if(g==="content")return l("content",Gt(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(Us(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 js(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 kl,vl,Hs=w(()=>{"use strict";kl=["content_block_start","content_block_delta","content_block_stop"];vl=["message_stop","response.completed","response.incomplete","[DONE]"]});function xl(n,e){return`${n.name}|${e?.name??""}`}function So(n){return n.__ccrPluginRequestState??={budgets:new Map}}function Ie(n,e,t){let o=So(n),r=xl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Co(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(Ie(n,e,o).terminalError=t,!0)}var zs=w(()=>{"use strict"});var Ro=w(()=>{"use strict"});import Sl from"fastify";function Bs(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,Cl,Po,Vt=w(()=>{"use strict";Ro();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 g of this.plugins.values()){for(let m of s.runtimes.keys())if(g.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(g.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([m,y])=>{if(g.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:g,name:m,value:g.preparePluginTransformer(y)}})),h=[];try{for(let g of f)h.push(g),g.service.registerTransformer(g.name,g.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(g){for(let m of h)m.service.removeTransformer(m.name);throw a="aborted",g}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,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=Sl({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")}},Cl=new st,Po=()=>Cl});function Js(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function Te(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?Rl(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=Bs(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function Rl(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 Ws=w(()=>{"use strict";Vt()});var Qt,Eo=w(()=>{Qt="2.3.2423"});var Ks={};ho(Ks,{getFallbackPromotionStore:()=>Me,resetFallbackPromotionStore:()=>El});function Me(n){return ve||(ve=new Ao,n&&ve.configure(n)),ve}function El(){ve&&(ve.clearAll(),ve=null)}var Pl,Ao,ve,Yt=w(()=>{"use strict";se();Pl=600*1e3,Ao=class{promotions=new Map;enabled=!0;ttlMs=Pl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!j().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},ve=null});import{existsSync as Qs,mkdirSync as Al,readFileSync as Ol,writeFileSync as Il}from"fs";import{join as Ys}from"path";import{HOME_DIR as Ml}from"@wengine-ai/claude-code-router-shared";function Fl(n){try{if(!Qs(Mo))return;let e=JSON.parse(Ol(Mo,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Vs(n){try{let e=n.getAllStates();if(e.length===0)return;Qs(Io)||Al(Io,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Il(Mo,JSON.stringify(t,null,2),"utf-8")}catch{}}function Lo(){if(Gs)return;Gs=!0;let n=j();Fl(n),Nl=setInterval(()=>Vs(n),6e4),process.on("exit",()=>Vs(n))}function j(n){return Oo||(Oo=new Xt(n)),Oo}var Ll,$l,Xt,Io,Mo,Gs,Nl,Oo,se=w(()=>{"use strict";Ll=120,$l={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...$l,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),al(Ks));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??Ll)*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)}},Io=Ys(Ml,"runtime"),Mo=Ys(Io,"provider-health.json"),Gs=!1,Nl=null;Oo=null});import{existsSync as ti,mkdirSync as Ul,readFileSync as Dl,writeFileSync as jl}from"fs";import{join as ni}from"path";import{HOME_DIR as Hl}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=$o(o,zl),s=$o(o,Bl),a=$o(o,Jl);(r||s||a)&&Le.set(n,{provider:n,remaining:qs(r),limit:qs(s),reset:Kl(a),capturedAt:Date.now()})}function Wl(n){return Le.get(n)}function Uo(){return Array.from(Le.values())}function $o(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function qs(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Kl(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=Gl(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Gl(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 Vl(){try{if(!ti(Fo))return;let n=JSON.parse(Dl(Fo,"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;Le.set(t.provider,t)}}catch{}}function ei(){try{if(Le.size===0)return;ti(No)||Ul(No,{recursive:!0}),jl(Fo,JSON.stringify(Array.from(Le.values()),null,2),"utf-8")}catch{}}function at(){Xs||(Xs=!0,Vl(),Zs=setInterval(ei,6e4),Zs.unref?.(),process.on("exit",ei))}var No,Fo,Le,Xs,Zs,zl,Bl,Jl,$e=w(()=>{"use strict";No=ni(Hl,"runtime"),Fo=ni(No,"rate-limit.json"),Le=new Map,Xs=!1,Zs=null,zl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Bl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Jl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function qt(){return Do||(Do=new Ho),Do}function Bo(){return jo||(jo=new zo),jo}function Ql(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function oi(n){let e=Ql(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 ri(n,e){let t=qt(),o=n?.[Zt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[Zt]=t.acquire(e)}function Jo(n){let e=n?.[Zt];e&&qt().release(e)}function si(n,e){let t=oi(n),o=n?.[Zt],r=t?Bo().get(t)!==void 0:!1;!o&&!r||(t&&Bo().bind(t,e),ri(n,e))}function Yl(n,e,t){let o=qt(),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 ii(n,e,t){let o=oi(n),r=Bo(),s=qt(),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=Yl(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 ri(n,i),i}var Ho,zo,Do,jo,Zt,en=w(()=>{"use strict";Ho=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()}},zo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},Do=null,jo=null;Zt="__concurrencyLease"});async function D(n){let e=await n.text();return Xl(e,n.status)}function Xl(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 ai(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=w(()=>{"use strict"});function Zl(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 tn(n){for(let e of Zl(n))if(e.startsWith("response."))return!0;return!1}var Ne,Wo=w(()=>{"use strict";V();Ne=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,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 D(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})),tn(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}):tn(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,h=new Map,g=0,m=!1,y=!1,_=!1,b=this,k=new ReadableStream({start(T){let x=(R,E=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:R,finish_reason:E}]})}
4
+ `);a=l.pop()||"";for(let u of l)u.trim()&&(s<o.maxStreamChunks?Is(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&&Is(e,t,s,a.trim()),s++),Ms(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Ms(e,t,s)}finally{r.releaseLock()}})()}var _l,bl,Ie,xo,st=w(()=>{"use strict";_l=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),bl=/token|secret|credential|passwd|password/i,Ie={maxBodyLength:4096,maxStreamChunks:100},xo=!1});function Us(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=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Tl(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function Tl(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 Ds=w(()=>{q();st()});function xl(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function js(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function So(n){if(js(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(vl.some(s=>r.includes(s))){e=!0;break}Cl.some(s=>r.includes(s))&&(t=!0)}}return e||xl(n)?"content":t?"empty":"pending"}async function Hs(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(),h=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),h===p)return l(So(a)==="content"?"content":"pending",Gt(o,f));if(h.done){a+=r.decode();let m=So(a);return l(m==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let g=So(a);if(g==="content")return l("content",Gt(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(js(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 zs(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 vl,Cl,Bs=w(()=>{"use strict";vl=["content_block_start","content_block_delta","content_block_stop"];Cl=["message_stop","response.completed","response.incomplete","[DONE]"]});function Sl(n,e){return`${n.name}|${e?.name??""}`}function Ro(n){return n.__ccrPluginRequestState??={budgets:new Map}}function Me(n,e,t){let o=Ro(n),r=Sl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function wo(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(Me(n,e,o).terminalError=t,!0)}var Js=w(()=>{"use strict"});var Po=w(()=>{"use strict"});import Rl from"fastify";function Ws(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 it,wl,Ao,Vt=w(()=>{"use strict";Po();it=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 g of this.plugins.values()){for(let m of s.runtimes.keys())if(g.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(g.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([m,y])=>{if(g.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:g,name:m,value:g.preparePluginTransformer(y)}})),h=[];try{for(let g of f)h.push(g),g.service.registerTransformer(g.name,g.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(g){for(let m of h)m.service.removeTransformer(m.name);throw a="aborted",g}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,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=Rl({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")}},wl=new it,Ao=()=>wl});function Ks(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function Te(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?Pl(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=Ws(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function Pl(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 Gs=w(()=>{"use strict";Vt()});var Qt,Oo=w(()=>{Qt="2.3.2425"});var Vs={};_o(Vs,{getFallbackPromotionStore:()=>Le,resetFallbackPromotionStore:()=>Ol});function Le(n){return ve||(ve=new Io,n&&ve.configure(n)),ve}function Ol(){ve&&(ve.clearAll(),ve=null)}var Al,Io,ve,Yt=w(()=>{"use strict";se();Al=600*1e3,Io=class{promotions=new Map;enabled=!0;ttlMs=Al;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!j().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},ve=null});import{existsSync as Xs,mkdirSync as Il,readFileSync as Ml,writeFileSync as Ll}from"fs";import{join as Zs}from"path";import{HOME_DIR as Nl}from"@wengine-ai/claude-code-router-shared";function Dl(n){try{if(!Xs(No))return;let e=JSON.parse(Ml(No,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Ys(n){try{let e=n.getAllStates();if(e.length===0)return;Xs(Lo)||Il(Lo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Ll(No,JSON.stringify(t,null,2),"utf-8")}catch{}}function $o(){if(Qs)return;Qs=!0;let n=j();Dl(n),Ul=setInterval(()=>Ys(n),6e4),process.on("exit",()=>Ys(n))}function j(n){return Mo||(Mo=new Xt(n)),Mo}var $l,Fl,Xt,Lo,No,Qs,Ul,Mo,se=w(()=>{"use strict";$l=120,Fl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Fl,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),ll(Vs));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??$l)*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)}},Lo=Zs(Nl,"runtime"),No=Zs(Lo,"provider-health.json"),Qs=!1,Ul=null;Mo=null});import{existsSync as oi,mkdirSync as jl,readFileSync as Hl,writeFileSync as zl}from"fs";import{join as ri}from"path";import{HOME_DIR as Bl}from"@wengine-ai/claude-code-router-shared";function at(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=Fo(o,Jl),s=Fo(o,Wl),a=Fo(o,Kl);(r||s||a)&&Ne.set(n,{provider:n,remaining:ti(r),limit:ti(s),reset:Vl(a),capturedAt:Date.now()})}function Gl(n){return Ne.get(n)}function jo(){return Array.from(Ne.values())}function Fo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ti(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Vl(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=Ql(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Ql(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 Yl(){try{if(!oi(Do))return;let n=JSON.parse(Hl(Do,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Ne.set(t.provider,t)}}catch{}}function ni(){try{if(Ne.size===0)return;oi(Uo)||jl(Uo,{recursive:!0}),zl(Do,JSON.stringify(Array.from(Ne.values()),null,2),"utf-8")}catch{}}function ct(){qs||(qs=!0,Yl(),ei=setInterval(ni,6e4),ei.unref?.(),process.on("exit",ni))}var Uo,Do,Ne,qs,ei,Jl,Wl,Kl,$e=w(()=>{"use strict";Uo=ri(Bl,"runtime"),Do=ri(Uo,"rate-limit.json"),Ne=new Map,qs=!1,ei=null,Jl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Wl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Kl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function qt(){return Ho||(Ho=new Bo),Ho}function Wo(){return zo||(zo=new Jo),zo}function Xl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function si(n){let e=Xl(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 ii(n,e){let t=qt(),o=n?.[Zt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[Zt]=t.acquire(e)}function Ko(n){let e=n?.[Zt];e&&qt().release(e)}function ai(n,e){let t=si(n),o=n?.[Zt],r=t?Wo().get(t)!==void 0:!1;!o&&!r||(t&&Wo().bind(t,e),ii(n,e))}function Zl(n,e,t){let o=qt(),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 ci(n,e,t){let o=si(n),r=Wo(),s=qt(),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=Zl(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 ii(n,i),i}var Bo,Jo,Ho,zo,Zt,en=w(()=>{"use strict";Bo=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},Jo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},Ho=null,zo=null;Zt="__concurrencyLease"});async function D(n){let e=await n.text();return ql(e,n.status)}function ql(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 li(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function lt(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})),lt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:lt(s)}}async function me(n){try{let e=await n.text();if(lt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var Q=w(()=>{"use strict"});function eu(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 tn(n){for(let e of eu(n))if(e.startsWith("response."))return!0;return!1}var Fe,Go=w(()=>{"use strict";Q();Fe=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,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 D(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})),tn(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}):tn(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,h=new Map,g=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(R,E=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:R,finish_reason:E}]})}
6
6
 
7
- `))},v=R=>{if(!R)return;let E=b.getCacheReadInputTokens(R),I=typeof R.input_tokens=="number"?R.input_tokens:void 0,O=b.getCacheCreationInputTokens(R);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:I,completion_tokens:typeof R.output_tokens=="number"?R.output_tokens:void 0,total_tokens:R.total_tokens,prompt_tokens_details:{cached_tokens:E,cache_creation_tokens:O},cache_read_input_tokens:E,cache_creation_input_tokens:O}})}
7
+ `))},v=R=>{if(!R)return;let E=_.getCacheReadInputTokens(R),I=typeof R.input_tokens=="number"?R.input_tokens:void 0,O=_.getCacheCreationInputTokens(R);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:I,completion_tokens:typeof R.output_tokens=="number"?R.output_tokens:void 0,total_tokens:R.total_tokens,prompt_tokens_details:{cached_tokens:E,cache_creation_tokens:O},cache_read_input_tokens:E,cache_creation_input_tokens:O}})}
8
8
 
9
- `))},C=R=>{m||(m=!0,T.enqueue(r.encode(`data: ${JSON.stringify({error:{message:R,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
9
+ `))},S=R=>{m||(m=!0,T.enqueue(r.encode(`data: ${JSON.stringify({error:{message:R,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
10
10
 
11
- `)))},S=R=>{y||(y=!0,v(u),x({},R))},P=()=>{_||(_=!0,T.enqueue(r.encode(`data: [DONE]
11
+ `)))},C=R=>{y||(y=!0,v(u),x({},R))},P=()=>{b||(b=!0,T.enqueue(r.encode(`data: [DONE]
12
12
 
13
- `)))},L=(R,E)=>{let I=R?.call_id||R?.id||(E!==void 0?`idx_${E}`:void 0);if(!I)return g++;let O=f.get(I);if(O!==void 0)return O;let M=g++;return f.set(I,M),R?.call_id&&R?.id?(f.set(R.id,M),E!==void 0&&f.set(`idx_${E}`,M)):R?.id&&E!==void 0&&f.set(`idx_${E}`,M),M},$=R=>{let E=!1;for(let I of Array.isArray(R)?R:[])if(I?.type==="function_call"){d="tool";let O=L(I,void 0),M=I.call_id||I.id;M&&h.set(O,M),x({role:"assistant",tool_calls:[{index:O,id:M,type:"function",function:{name:I.name||"",arguments:typeof I.arguments=="string"?I.arguments:""}}]}),E=!0}else if(I?.type==="message")for(let O of Array.isArray(I.content)?I.content:[])O?.type==="output_text"&&typeof O.text=="string"&&O.text.trim().length>0&&(d="text",x({role:"assistant",content:O.text}),E=!0);return E},A=R=>{switch(R?.response?.model&&(c=R.response.model),R?.response?.id&&(l=R.response.id),R?.type){case"response.output_item.added":{let E=R.item;if(E?.type!=="function_call")return;d="tool";let I=L(E,R.output_index),O=E.call_id||E.id;O&&h.set(I,O),x({role:"assistant",tool_calls:[{index:I,id:O,type:"function",function:{name:E.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let E=L({id:R.item_id},R.output_index);d="tool";let I=h.get(E);x({tool_calls:[{index:E,...I?{id:I,type:"function"}:{},function:{arguments:typeof R.delta=="string"?R.delta:""}}]});return}case"response.output_text.annotation.added":{let E=R.annotation;if(!E)return;d="annotation",x({annotations:[{type:"url_citation",url_citation:{url:E.url||"",title:E.title||"",content:"",start_index:E.start_index||0,end_index:E.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof R.delta!="string"||R.delta.length===0)return;d="thinking",x({thinking:{content:R.delta}});return}case"response.output_text.delta":{if(typeof R.delta!="string"||R.delta.length===0)return;d="text";let E=p!==R.item_id;p=R.item_id;let I={content:R.delta};E&&(I.role="assistant"),x(I);return}case"response.completed":{u=R.response?.usage;let E=Array.isArray(R.response?.output)?R.response.output:[],I=E.some(O=>O?.type==="function_call");if(d===""&&$(E),!I&&d===""){let O=String(R.response?.incomplete_details?.reason??"");C(E.length===0&&!O?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${O||"empty"})`);return}S(d==="tool"||I?"tool_calls":"stop");return}case"response.incomplete":{u=R.response?.usage;let E=String(R.response?.incomplete_details?.reason??"");d===""&&$(Array.isArray(R.response?.output)?R.response.output:[]);let I=E==="max_output_tokens"||E==="max_tokens";if(d===""){C(`Upstream Responses stream produced no content (${E||"incomplete"})`);return}S(I?"length":E==="content_filter"?"content_filter":"stop");return}case"response.failed":{let E=R.response?.error||R.error||void 0;C(E?.message||"Upstream Responses stream failed before completing");return}case"error":{C(R.error?.message||R.message||"Upstream Responses stream error");return}default:return}},U=e.getReader();(async()=>{try{for(;;){let{done:R,value:E}=await U.read();if(R)break;i+=o.decode(E,{stream:!0});let I=i.split(/\r?\n/);i=I.pop()||"";for(let O of I){let M=O.trim();if(!M||M.startsWith(":")||M.startsWith("event:")||!M.startsWith("data:"))continue;let H=M.slice(5).trim();if(!H)continue;if(H==="[DONE]"){P();continue}let re;try{re=JSON.parse(H)}catch{continue}A(re)}}if(i+=o.decode(),i.trim().startsWith("data:")){let R=i.trim().slice(5).trim();if(R&&R!=="[DONE]")try{A(JSON.parse(R))}catch{}}!m&&!y&&(d===""?C("Upstream Responses stream ended before any output"):S(d==="tool"?"tool_calls":"stop")),m||P()}catch(R){console.error("Responses\u2192Chat stream error:",R);try{T.error(R)}catch{}return}finally{try{U.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:h}=await a.read();if(h||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),tn(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")||tn(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 D(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=(g,m)=>r.encode(`event: ${g}
13
+ `)))},L=(R,E)=>{let I=R?.call_id||R?.id||(E!==void 0?`idx_${E}`:void 0);if(!I)return g++;let O=f.get(I);if(O!==void 0)return O;let M=g++;return f.set(I,M),R?.call_id&&R?.id?(f.set(R.id,M),E!==void 0&&f.set(`idx_${E}`,M)):R?.id&&E!==void 0&&f.set(`idx_${E}`,M),M},N=R=>{let E=!1;for(let I of Array.isArray(R)?R:[])if(I?.type==="function_call"){d="tool";let O=L(I,void 0),M=I.call_id||I.id;M&&h.set(O,M),x({role:"assistant",tool_calls:[{index:O,id:M,type:"function",function:{name:I.name||"",arguments:typeof I.arguments=="string"?I.arguments:""}}]}),E=!0}else if(I?.type==="message")for(let O of Array.isArray(I.content)?I.content:[])O?.type==="output_text"&&typeof O.text=="string"&&O.text.trim().length>0&&(d="text",x({role:"assistant",content:O.text}),E=!0);return E},A=R=>{switch(R?.response?.model&&(c=R.response.model),R?.response?.id&&(l=R.response.id),R?.type){case"response.output_item.added":{let E=R.item;if(E?.type!=="function_call")return;d="tool";let I=L(E,R.output_index),O=E.call_id||E.id;O&&h.set(I,O),x({role:"assistant",tool_calls:[{index:I,id:O,type:"function",function:{name:E.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let E=L({id:R.item_id},R.output_index);d="tool";let I=h.get(E);x({tool_calls:[{index:E,...I?{id:I,type:"function"}:{},function:{arguments:typeof R.delta=="string"?R.delta:""}}]});return}case"response.output_text.annotation.added":{let E=R.annotation;if(!E)return;d="annotation",x({annotations:[{type:"url_citation",url_citation:{url:E.url||"",title:E.title||"",content:"",start_index:E.start_index||0,end_index:E.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof R.delta!="string"||R.delta.length===0)return;d="thinking",x({thinking:{content:R.delta}});return}case"response.output_text.delta":{if(typeof R.delta!="string"||R.delta.length===0)return;d="text";let E=p!==R.item_id;p=R.item_id;let I={content:R.delta};E&&(I.role="assistant"),x(I);return}case"response.completed":{u=R.response?.usage;let E=Array.isArray(R.response?.output)?R.response.output:[],I=E.some(O=>O?.type==="function_call");if(d===""&&N(E),!I&&d===""){let O=String(R.response?.incomplete_details?.reason??"");S(E.length===0&&!O?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${O||"empty"})`);return}C(d==="tool"||I?"tool_calls":"stop");return}case"response.incomplete":{u=R.response?.usage;let E=String(R.response?.incomplete_details?.reason??"");d===""&&N(Array.isArray(R.response?.output)?R.response.output:[]);let I=E==="max_output_tokens"||E==="max_tokens";if(d===""){S(`Upstream Responses stream produced no content (${E||"incomplete"})`);return}C(I?"length":E==="content_filter"?"content_filter":"stop");return}case"response.failed":{let E=R.response?.error||R.error||void 0;S(E?.message||"Upstream Responses stream failed before completing");return}case"error":{S(R.error?.message||R.message||"Upstream Responses stream error");return}default:return}},U=e.getReader();(async()=>{try{for(;;){let{done:R,value:E}=await U.read();if(R)break;i+=o.decode(E,{stream:!0});let I=i.split(/\r?\n/);i=I.pop()||"";for(let O of I){let M=O.trim();if(!M||M.startsWith(":")||M.startsWith("event:")||!M.startsWith("data:"))continue;let H=M.slice(5).trim();if(!H)continue;if(H==="[DONE]"){P();continue}let re;try{re=JSON.parse(H)}catch{continue}A(re)}}if(i+=o.decode(),i.trim().startsWith("data:")){let R=i.trim().slice(5).trim();if(R&&R!=="[DONE]")try{A(JSON.parse(R))}catch{}}!m&&!y&&(d===""?S("Upstream Responses stream ended before any output"):C(d==="tool"?"tool_calls":"stop")),m||P()}catch(R){console.error("Responses\u2192Chat stream error:",R);try{T.error(R)}catch{}return}finally{try{U.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:h}=await a.read();if(h||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),tn(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")||tn(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 D(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=(g,m)=>r.encode(`event: ${g}
14
14
  data: ${JSON.stringify(m)}
15
15
 
16
- `),h=(g,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:g,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(g){try{let m=e.getReader(),y="",_=!1,b=k=>{if(!_){_=!0;for(let T of d)if(T.type==="function_call"){let x=d.indexOf(T);g.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",g.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",g.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}g.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value: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 C=v.trim();if(!C||C.startsWith("event:")||!C.startsWith("data:"))continue;let S=C.slice(5).trim();if(S==="[DONE]"){b({}),g.enqueue(r.encode(`data: [DONE]
16
+ `),h=(g,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:g,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(g){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let T of d)if(T.type==="function_call"){let x=d.indexOf(T);g.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",g.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",g.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}g.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value: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 S=v.trim();if(!S||S.startsWith("event:")||!S.startsWith("data:"))continue;let C=S.slice(5).trim();if(C==="[DONE]"){_({}),g.enqueue(r.encode(`data: [DONE]
18
18
 
19
- `));continue}let P;try{P=JSON.parse(S)}catch{continue}c||(c=!0,g.enqueue(f("response.created",{type:"response.created",response:h("in_progress")})),g.enqueue(f("response.in_progress",{type:"response.in_progress",response:h("in_progress")})));let L=P.choices?.[0];if(!L)continue;let $=L.delta;if($?.content){if(!l){l=!0;let A=i++,U={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(U),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:A,item:U}))}g.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:$.content}))}if(Array.isArray($?.tool_calls))for(let A of $.tool_calls){if(A.id){u=A.id,p=i++;let U={id:A.id,type:"function_call",status:"in_progress",call_id:A.id,name:A.function?.name||"",arguments:""};d.push(U),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:U}))}if(A.function?.arguments){g.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:A.function.arguments}));let U=d.find(R=>R.call_id===u);U&&(U.arguments+=A.function.arguments)}}L.finish_reason&&b(P)}}_||b({}),g.close()}catch(m){g.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",c="",l=-1,u="",p="",d="",f=-1,h="",g="",m=-1,y=0,_=!1,b=!1,k=!1,T=!1,x=null,v=[],C=(U,R)=>r.encode(`event: ${U}
19
+ `));continue}let P;try{P=JSON.parse(C)}catch{continue}c||(c=!0,g.enqueue(f("response.created",{type:"response.created",response:h("in_progress")})),g.enqueue(f("response.in_progress",{type:"response.in_progress",response:h("in_progress")})));let L=P.choices?.[0];if(!L)continue;let N=L.delta;if(N?.content){if(!l){l=!0;let A=i++,U={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(U),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:A,item:U}))}g.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:N.content}))}if(Array.isArray(N?.tool_calls))for(let A of N.tool_calls){if(A.id){u=A.id,p=i++;let U={id:A.id,type:"function_call",status:"in_progress",call_id:A.id,name:A.function?.name||"",arguments:""};d.push(U),g.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:U}))}if(A.function?.arguments){g.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:A.function.arguments}));let U=d.find(R=>R.call_id===u);U&&(U.arguments+=A.function.arguments)}}L.finish_reason&&_(P)}}b||_({}),g.close()}catch(m){g.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",c="",l=-1,u="",p="",d="",f=-1,h="",g="",m=-1,y=0,b=!1,_=!1,k=!1,T=!1,x=null,v=[],S=(U,R)=>r.encode(`event: ${U}
20
20
  data: ${JSON.stringify(R)}
21
21
 
22
- `),S=(U,R=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:U,model:s,output:R,usage:this.buildResponsesUsage()}),P=()=>{_||(_=!0,A.enqueue(C("response.created",{type:"response.created",response:S("in_progress")})),A.enqueue(C("response.in_progress",{type:"response.in_progress",response:S("in_progress")})))},L=(U,R)=>{A.enqueue(C("response.output_item.done",{type:"response.output_item.done",output_index:U,item:{...R,status:"completed"}}))},$=U=>{if(!T){if(T=!0,b){let R=v.find(E=>E.type==="message");R&&(R.content=[{type:"output_text",text:i}],R.status="completed")}for(let R of v)R.type==="function_call"&&(R.status="completed");return C("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:U?{...this.buildResponsesUsage(U)}:this.buildResponsesUsage()}})}},A;return new ReadableStream({async start(U){A=U;try{let R=e.getReader(),E="";for(;;){let{done:O,value:M}=await R.read();if(O)break;E+=o.decode(M,{stream:!0});let H=E.split(`
23
- `);E=H.pop()||"";for(let re of H){let z=re.trim();if(!z||z.startsWith("event:")||!z.startsWith("data:"))continue;let Z=z.slice(5).trim();if(Z==="[DONE]")continue;let J;try{J=JSON.parse(Z)}catch{continue}if(J.type==="message_start"&&(a=J.message?.id||a,P()),J.type==="content_block_start"){let N=J.content_block;if(x=N?.type||null,N?.type==="tool_use"){u=N.id||"",p=N.name||"",d="",f=y++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};v.push(W),A.enqueue(C("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if(N?.type==="thinking"&&(h=N.thinking||"",!k)){k=!0,m=y++,g=`rs_${a}`;let W={id:g,type:"reasoning",status:"in_progress",summary:[]};v.push(W),A.enqueue(C("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if(N?.type==="text"&&(i=N?.text||"",!b)){b=!0,l=y++,c=`${a}_msg`;let W={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),A.enqueue(C("response.output_item.added",{type:"response.output_item.added",output_index:l,item:W}))}}if(J.type==="content_block_delta"){let N=J.delta;if(N?.type==="text_delta"){if(!b){b=!0,l=y++,c=`${a}_msg`;let W={id:c,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),A.enqueue(C("response.output_item.added",{type:"response.output_item.added",output_index:l,item:W}))}i+=N.text||"",A.enqueue(C("response.output_text.delta",{type:"response.output_text.delta",item_id:c,output_index:l,content_index:0,delta:N.text||""}))}N?.type==="thinking_delta"&&(h+=N.thinking||"",A.enqueue(C("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:g||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:N.thinking||""}))),N?.type==="input_json_delta"&&(d+=N.partial_json||"",A.enqueue(C("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:f>=0?f:0,delta:N.partial_json||""})))}if(J.type==="content_block_stop"){if(x==="tool_use"&&u){A.enqueue(C("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:d}));let N=v.find(W=>W.call_id===u);N&&(N.arguments=d,N.status="completed"),N&&L(f,N)}if(x==="text"&&b){A.enqueue(C("response.output_text.done",{type:"response.output_text.done",item_id:c,output_index:l,content_index:0,text:i}));let N=v.find(W=>W.type==="message");N&&(N.content=[{type:"output_text",text:i}],L(l,N))}if(x==="thinking"&&k){let N=v.find(W=>W.type==="reasoning");N&&(N.summary=[{type:"summary_text",text:h}],L(m,N))}x=null}if(J.type==="message_delta"){let N=$(J.usage);N&&A.enqueue(N)}if(J.type==="message_stop"){let N=$();N&&A.enqueue(N),A.enqueue(r.encode(`data: [DONE]
22
+ `),C=(U,R=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:U,model:s,output:R,usage:this.buildResponsesUsage()}),P=()=>{b||(b=!0,A.enqueue(S("response.created",{type:"response.created",response:C("in_progress")})),A.enqueue(S("response.in_progress",{type:"response.in_progress",response:C("in_progress")})))},L=(U,R)=>{A.enqueue(S("response.output_item.done",{type:"response.output_item.done",output_index:U,item:{...R,status:"completed"}}))},N=U=>{if(!T){if(T=!0,_){let R=v.find(E=>E.type==="message");R&&(R.content=[{type:"output_text",text:i}],R.status="completed")}for(let R of v)R.type==="function_call"&&(R.status="completed");return S("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:U?{...this.buildResponsesUsage(U)}:this.buildResponsesUsage()}})}},A;return new ReadableStream({async start(U){A=U;try{let R=e.getReader(),E="";for(;;){let{done:O,value:M}=await R.read();if(O)break;E+=o.decode(M,{stream:!0});let H=E.split(`
23
+ `);E=H.pop()||"";for(let re of H){let z=re.trim();if(!z||z.startsWith("event:")||!z.startsWith("data:"))continue;let V=z.slice(5).trim();if(V==="[DONE]")continue;let J;try{J=JSON.parse(V)}catch{continue}if(J.type==="message_start"&&(a=J.message?.id||a,P()),J.type==="content_block_start"){let $=J.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),A.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if($?.type==="thinking"&&(h=$.thinking||"",!k)){k=!0,m=y++,g=`rs_${a}`;let W={id:g,type:"reasoning",status:"in_progress",summary:[]};v.push(W),A.enqueue(S("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),A.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:l,item:W}))}}if(J.type==="content_block_delta"){let $=J.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),A.enqueue(S("response.output_item.added",{type:"response.output_item.added",output_index:l,item:W}))}i+=$.text||"",A.enqueue(S("response.output_text.delta",{type:"response.output_text.delta",item_id:c,output_index:l,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(h+=$.thinking||"",A.enqueue(S("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:g||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(d+=$.partial_json||"",A.enqueue(S("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(J.type==="content_block_stop"){if(x==="tool_use"&&u){A.enqueue(S("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"),$&&L(f,$)}if(x==="text"&&_){A.enqueue(S("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}],L(l,$))}if(x==="thinking"&&k){let $=v.find(W=>W.type==="reasoning");$&&($.summary=[{type:"summary_text",text:h}],L(m,$))}x=null}if(J.type==="message_delta"){let $=N(J.usage);$&&A.enqueue($)}if(J.type==="message_stop"){let $=N();$&&A.enqueue($),A.enqueue(r.encode(`data: [DONE]
24
24
 
25
- `))}}}P();let I=$();I&&A.enqueue(I),E="",A.close()}catch(R){A.error(R)}}})}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 Ko,Q,nn=w(()=>{"use strict";Ko=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},Q=new Ko(100)});import{existsSync as di,mkdirSync as ql,readFileSync as eu,writeFileSync as tu}from"fs";import{join as pi}from"path";import{HOME_DIR as nu}from"@wengine-ai/claude-code-router-shared";function Qo(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function on(n){let e=Fe.get(n);return e?{...e}:void 0}function Yo(){return Array.from(Fe.values()).map(n=>({...n}))}function ou(){try{if(!di(Vo))return;let n=JSON.parse(eu(Vo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;Fe.set(t.provider,t)}}catch{}}function ui(){try{if(Fe.size===0)return;di(Go)||ql(Go,{recursive:!0}),tu(Vo,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function lt(){ci||(ci=!0,ou(),li=setInterval(ui,6e4),li.unref?.(),process.on("exit",ui))}var Go,Vo,Fe,ci,li,Ue=w(()=>{"use strict";Go=pi(nu,"runtime"),Vo=pi(Go,"quota-store.json"),Fe=new Map,ci=!1,li=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!ru.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 ru,De=w(()=>{"use strict";ru=/^[A-Za-z0-9_-]+$/});import{existsSync as gi}from"fs";import{readFile as su,readdir as iu}from"fs/promises";import{homedir as au}from"os";import{isAbsolute as cu,join as ut,normalize as lu}from"path";import{openSqliteDatabase as uu}from"@wengine-ai/claude-code-router-shared";function bu(){if(je.size<=fi)return;let n=[...je.keys()].slice(0,je.size-fi);for(let e of n)je.delete(e)}function _u(){if(He.size<=mi)return;let n=[...He].slice(0,He.size-mi);for(let e of n)He.delete(e)}function ku(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 Tu(n,e){let t;try{t=uu(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 vu(n,e){let t;try{t=await iu(n)}catch{return null}for(let o of t)for(let r of e){let s=ut(n,o,`${r}.json`);if(gi(s))try{let a=JSON.parse(await su(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function hi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=je.get(e);if(t)return t;let o=async()=>{let r=ku(e);if(r.length===0)return null;let s=ut(du(),pu),a=ut(s,fu);if(gi(a)){let i=Tu(a,r);if(i)return i}return vu(ut(s,mu),r)};try{let r=await o();if(!r&&!He.has(e)){He.add(e),_u();for(let a=0;a<gu&&!r;a++)await yu(hu),r=await o()}if(!r||!cu(r))return null;let s=lu(r);return je.set(e,s),bu(),s}catch{return null}}var du,pu,fu,mu,fi,mi,gu,hu,je,He,yu,yi=w(()=>{"use strict";du=()=>process.env.CCR_ZCODE_DIR||ut(au(),".zcode"),pu="v2",fu="tasks-index.sqlite",mu="sessions",fi=500,mi=500,gu=3,hu=50,je=new Map,He=new Set,yu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as xu}from"node:crypto";import{CCR_PROJECT_HEADER as Xo}from"@wengine-ai/claude-code-router-shared";function ki(n){return typeof n=="string"&&n.length<=Su}function Cu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of _i){let{value:t}=rn(n,e);if(!ki(t))continue;let o=ge(t);if(o)return o}}function wu(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 Pu(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function rn(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function bi(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function dt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Zo(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function vi(n){return typeof n=="string"&&Ru.includes(n)}function Fu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function ze(n){if(vi(n?.clientType))return n.clientType;let e=Pu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=wu(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(rn(n,Xo).present||rn(n,"x-session-affinity").present)return"pi";if(Fu(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 xi(n){return Ti[n]}function Uu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||xu();return n.__ccrRequestScopeId=e,e}function xe(n,e={}){let t=ze(n),o=xi(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Uu(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,bi(n,Xo),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of _i)bi(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Du(){}var _i,Su,Ru,Eu,Au,Ou,Iu,Mu,Lu,$u,Nu,Ti,Be=w(()=>{"use strict";De();_i=["x-session-affinity","x-session-id","x-litellm-session-id"],Su=256;Ru=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Eu={type:"claude-code",createContext(n){return Zo(n,"claude-code")}},Au={type:"zcode",createContext(n){return Zo(n,"zcode")}},Ou={type:"pi",createContext(n){let e=rn(n,Xo),t=Cu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=ki(t)?t:void 0;return{...dt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Iu={type:"qwen-code",createContext(n){return Zo(n,"qwen-code")}},Mu={type:"opencode",createContext(){return dt("opencode")}},Lu={type:"codex",createContext(){return dt("codex")}},$u={type:"api",createContext(){return dt("api")}},Nu={type:"unknown",createContext(){return dt("unknown")}},Ti={"claude-code":Eu,zcode:Au,pi:Ou,"qwen-code":Iu,opencode:Mu,codex:Lu,api:$u,unknown:Nu}});import{get_encoding as Hu}from"tiktoken";import{readFile as qo}from"fs/promises";import{opendir as zu,stat as Bu}from"fs/promises";import{join as er}from"path";import{CLAUDE_PROJECTS_DIR as Si,HOME_DIR as Ci,getClaudeProjectId as Ri,isZcodeProjectTakeoverActive as Ju}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Oi(e,t);if(r.code==="model_unhealthy"){let i=G(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=Ai[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 an(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function ft(n){let e=an(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function Ku(n,e){if(!e||!n)return null;let t=an(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=ft(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=an(r);if(a&&t.includes(a))return s}return null}function Gu(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function sn(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function pt(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Oi(n,e){let t=sn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!j().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let c=on(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 G(n,e,t,o,r,s,a){let i=sn(n);if(!i)return a?null:n;let{providerName:c,routeModel:l}=i,u=pt(e,c,l);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Me(),f=d.getPromotion(c,l,o,e);if(f){let h=sn(f);if(h){let g=pt(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Me(),f=d.getPromotion(c,l,o,e);if(f){let h=sn(f);if(h){let g=pt(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(c,l,o)}}if(!t&&!j().isAvailable(u.provider.name,u.model,u.provider.apiKey?.startsWith("ccr-managed-")===!0||u.provider.api_key?.startsWith("ccr-managed-")===!0))return null;let p=on(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 X(n,e,t,o,r,s){let a=j(),i=[t?.[n],o?.[n]];for(let c of i)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let u=G(l,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Vu(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function mt(n){let e=an(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function Ii(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Gu(e))}function Mi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Qu(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??c??6e4,h=Ii(e,r,d),g=n.modelFamily,m=Mi(d,t,l),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||h>m)&&t.extendedContext){let k=G(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?X("extendedContext",o,t.fallback,a,g,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, 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(h>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?G(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?X("longContext",o,t.fallback,a,g,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let 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=G(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let T=i?X("webSearch",o,t.fallback,a,g,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=G(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let T=i?X("think",o,t.fallback,a,g,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=G(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let T=i?X("default",o,t.fallback,a,g,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 ed(){if(Se.size<=wi)return;let n=[...Se.keys()].slice(0,Se.size-wi);for(let e of n)Se.delete(e)}function td(){if(Je.size<=Pi)return;let n=[...Je].slice(0,Je.size-Pi);for(let e of n)Je.delete(e)}var Ai,te,le,cn,Wu,Yu,ln,Se,wi,Je,Pi,Xu,Zu,qu,Ei,Li,Ce=w(()=>{"use strict";nn();se();Ue();Yt();en();De();yi();Be();Ai={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||Ai[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Hu("cl100k_base"),cn=(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},Wu=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 Li(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await hi(n.sessionId);s&&Ju(s)&&(r=Ri(s))}if(r){n.projectId=r;let s=er(Ci,r,"config.json");if(!t&&n.sessionId){let a=er(Ci,r,`${n.sessionId}.json`);try{let i=JSON.parse(await qo(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch{}}try{let a=JSON.parse(await qo(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Ri(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})}}}};Yu=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let v=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);v&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${v[1]}</CCR-SUBAGENT-MODEL>`,""),d=v[1])}let{family:f,extended:h,isCcrAlias:g}=ft(n.body.model),m=i?.families?.[f||""];if(m&&i?.enableFamilyRouting){n.log.info(`Using model family routing for: ${f}${h?" (1M)":""}`),n.modelFamily=f,n.familyFallback=m.fallback;let v=Qu(n,e,m,a,o,h,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=G(n.body.model,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let C=c?X("default",a,void 0,u,void 0,s):null;if(C)return n.log.info(`Using fallback for explicit model: ${C}`),{model:C,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let y=g&&!i?.enableFamilyRouting?null:Ku(n.body.model,i?.models);if(y){let v=G(y,a,!1,"modelMapping",c,p,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${y}`),{model:v,scenarioType:"modelMapping"};let C=c?X("modelMapping",a,void 0,u,void 0,s):null;if(C)return{model:C,scenarioType:"modelMapping"};if(s){let S=ee(n,y,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${y} unavailable (fail pool), skipping`)}let _=n.clientContext,b=Ii(e,o,_),k=Mi(_,void 0,i?.extendedContextThreshold);if(b>k&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${b}, estimated: ${e}, threshold: ${k}`);let v=G(i.extendedContext,a,!1,"extendedContext",c,p,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let C=c?X("extendedContext",a,void 0,u,void 0,s):null;if(C)return{model:C,scenarioType:"extendedContext"};if(s){let S=ee(n,i.extendedContext,a,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext"}}}let T=_?.longContextThreshold??i?.longContextThreshold??6e4;if(b>T&&i?.longContext){n.log.info(`Using long context model due to token count: ${b}, estimated: ${e}, threshold: ${T}`);let v=G(i.longContext,a,!1,"longContext",c,p,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let C=c?X("longContext",a,void 0,u,void 0,s):null;if(C)return{model:C,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 v=G(i.background,a,!1,"background",c,p,s);if(v)return{model:v,scenarioType:"background"};let C=c?X("background",a,void 0,u,void 0,s):null;if(C)return{model:C,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(v=>v.type?.startsWith("web_search"))&&i?.webSearch){let v=G(i.webSearch,a,!1,"webSearch",c,p,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let C=c?X("webSearch",a,void 0,u,void 0,s):null;if(C)return{model:C,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 v=G(i.think,a,!1,"think",c,p,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let C=c?X("think",a,void 0,u,void 0,s):null;if(C)return{model:C,scenarioType:"think"};if(s){let S=ee(n,i.think,a,"think");if(S)return{model:S,scenarioType:"think"}}}if(i?.default){let v=G(i.default,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let C=c?X("default",a,void 0,u,void 0,s):null;if(C)return{model:C,scenarioType:"default"};let S=G(i.default,a,!0,"default",c,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 v=ee(n,i?.default||n.body.model,a,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},ln=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,o.getAll());let s=await Wu(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??Q.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:f}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&d.length>1&&d[1]?.text?.includes("<env>")){let g=await qo(h,"utf-8");d[1].text=`${g}<env>${d[1].text.split("<env>").pop()}`}try{let[g,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(g,m),_;t.tokenizerService?_=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,g)).tokenCount:_=cn(p,d,f),n.tokenCount=_;let b,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{b=await ot(k)(n,o.getAll(),{event:r})}catch(C){n.log.error(`failed to load custom router: ${C.message}`)}if(b)n.scenarioType="default";else{let C=await Yu(n,_,o,u,s,!!s);b=C.model,n.scenarioType=C.scenarioType}let{family:T}=ft(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[x?.image,a?.image].filter((C,S,P)=>!!C&&P.indexOf(C)===S);if(v.length>0&&Vu(n)&&!mt(b))if(v.includes(b))n.scenarioType="image";else{let C=v.map(S=>G(S,c,!1,"image",i,!l,l)).find(S=>!!S);if(C)n.log.info(`Using image model fallback for ${b}`),b=C,n.scenarioType="image";else{let S=i?X("image",c,x?.fallback,n.fallbackConfig,T||void 0,l):null;if(S)n.log.info(`Using image fallback model: ${S}`),b=S,n.scenarioType="image";else if(l){let P=ee(n,v[0],c,"image");P&&(b=P,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${b}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof b=="string"&&b.trim()){let C=n.scenarioType||"default",S=[...(n.familyFallback||{})[C]||[],...(n.fallbackConfig||{})[C]||[]];b=ii(n,b,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:S,resolve:P=>G(P,c,!1,C,i,!l,l),log:P=>n.log.info(P)})}typeof b=="string"&&b.trim()?n.body.model=b:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(g){if(g instanceof te)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),l){let m=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${g.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Se=new Map,wi=1e3,Je=new Set,Pi=1e3,Xu=3,Zu=50,qu=n=>new Promise(e=>setTimeout(e,n));Ei=async n=>{let e=await zu(Si),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=er(Si,s,`${n}.jsonl`);try{return(await Bu(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Li=async n=>{let e=ge(n);if(!e)return null;if(Se.has(e))return Se.get(e)||null;try{let t=await Ei(e);if(!t&&!Je.has(e)){Je.add(e),td();for(let o=0;o<Xu&&!t;o++)await qu(Zu),t=await Ei(e)}return t?(Se.set(e,t),ed(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function gt(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
25
+ `))}}}P();let I=N();I&&A.enqueue(I),E="",A.close()}catch(R){A.error(R)}}})}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 Vo,Y,nn=w(()=>{"use strict";Vo=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 Vo(100)});import{existsSync as fi,mkdirSync as tu,readFileSync as nu,writeFileSync as ou}from"fs";import{join as mi}from"path";import{HOME_DIR as ru}from"@wengine-ai/claude-code-router-shared";function Xo(n,e){n&&Ue.set(n,{...e,provider:n,capturedAt:Date.now()})}function on(n){let e=Ue.get(n);return e?{...e}:void 0}function Zo(){return Array.from(Ue.values()).map(n=>({...n}))}function su(){try{if(!fi(Yo))return;let n=JSON.parse(nu(Yo,"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;Ue.set(t.provider,t)}}catch{}}function pi(){try{if(Ue.size===0)return;fi(Qo)||tu(Qo,{recursive:!0}),ou(Yo,JSON.stringify(Array.from(Ue.values()),null,2),"utf-8")}catch{}}function ut(){ui||(ui=!0,su(),di=setInterval(pi,6e4),di.unref?.(),process.on("exit",pi))}var Qo,Yo,Ue,ui,di,De=w(()=>{"use strict";Qo=mi(ru,"runtime"),Yo=mi(Qo,"quota-store.json"),Ue=new Map,ui=!1,di=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!iu.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 iu,je=w(()=>{"use strict";iu=/^[A-Za-z0-9_-]+$/});import{existsSync as yi}from"fs";import{readFile as au,readdir as cu}from"fs/promises";import{homedir as lu}from"os";import{isAbsolute as uu,join as dt,normalize as du}from"path";import{openSqliteDatabase as pu}from"@wengine-ai/claude-code-router-shared";function ku(){if(He.size<=gi)return;let n=[...He.keys()].slice(0,He.size-gi);for(let e of n)He.delete(e)}function Tu(){if(ze.size<=hi)return;let n=[...ze].slice(0,ze.size-hi);for(let e of n)ze.delete(e)}function vu(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 xu(n,e){let t;try{t=pu(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 Cu(n,e){let t;try{t=await cu(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(yi(s))try{let a=JSON.parse(await au(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function _i(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=vu(e);if(r.length===0)return null;let s=dt(fu(),mu),a=dt(s,gu);if(yi(a)){let i=xu(a,r);if(i)return i}return Cu(dt(s,hu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),Tu();for(let a=0;a<yu&&!r;a++)await bu(_u),r=await o()}if(!r||!uu(r))return null;let s=du(r);return He.set(e,s),ku(),s}catch{return null}}var fu,mu,gu,hu,gi,hi,yu,_u,He,ze,bu,bi=w(()=>{"use strict";fu=()=>process.env.CCR_ZCODE_DIR||dt(lu(),".zcode"),mu="v2",gu="tasks-index.sqlite",hu="sessions",gi=500,hi=500,yu=3,_u=50,He=new Map,ze=new Set,bu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as Su}from"node:crypto";import{CCR_PROJECT_HEADER as qo}from"@wengine-ai/claude-code-router-shared";function vi(n){return typeof n=="string"&&n.length<=Ru}function wu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Ti){let{value:t}=rn(n,e);if(!vi(t))continue;let o=ge(t);if(o)return o}}function Eu(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 Au(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function rn(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function ki(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 er(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Ci(n){return typeof n=="string"&&Pu.includes(n)}function Du(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(Ci(n?.clientType))return n.clientType;let e=Au(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Eu(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(rn(n,qo).present||rn(n,"x-session-affinity").present)return"pi";if(Du(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 Si(n){return xi[n]}function ju(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||Su();return n.__ccrRequestScopeId=e,e}function xe(n,e={}){let t=Be(n),o=Si(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:ju(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,ki(n,qo),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Ti)ki(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Hu(){}var Ti,Ru,Pu,Ou,Iu,Mu,Lu,Nu,$u,Fu,Uu,xi,Je=w(()=>{"use strict";je();Ti=["x-session-affinity","x-session-id","x-litellm-session-id"],Ru=256;Pu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Ou={type:"claude-code",createContext(n){return er(n,"claude-code")}},Iu={type:"zcode",createContext(n){return er(n,"zcode")}},Mu={type:"pi",createContext(n){let e=rn(n,qo),t=wu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=vi(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Lu={type:"qwen-code",createContext(n){return er(n,"qwen-code")}},Nu={type:"opencode",createContext(){return pt("opencode")}},$u={type:"codex",createContext(){return pt("codex")}},Fu={type:"api",createContext(){return pt("api")}},Uu={type:"unknown",createContext(){return pt("unknown")}},xi={"claude-code":Ou,zcode:Iu,pi:Mu,"qwen-code":Lu,opencode:Nu,codex:$u,api:Fu,unknown:Uu}});import{get_encoding as Bu}from"tiktoken";import{readFile as tr}from"fs/promises";import{opendir as Ju,stat as Wu}from"fs/promises";import{join as nr}from"path";import{CLAUDE_PROJECTS_DIR as Ri,HOME_DIR as wi,getClaudeProjectId as Pi,isZcodeProjectTakeoverActive as Ku}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Mi(e,t);if(r.code==="model_unhealthy"){let i=G(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=Ii[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 an(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function mt(n){let e=an(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function Vu(n,e){if(!e||!n)return null;let t=an(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=an(r);if(a&&t.includes(a))return s}return null}function Qu(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function sn(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 Mi(n,e){let t=sn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!j().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let c=on(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 G(n,e,t,o,r,s,a){let i=sn(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=Le(),f=d.getPromotion(c,l,o,e);if(f){let h=sn(f);if(h){let g=ft(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Le(),f=d.getPromotion(c,l,o,e);if(f){let h=sn(f);if(h){let g=ft(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(c,l,o)}}if(!t&&!j().isAvailable(u.provider.name,u.model,u.provider.apiKey?.startsWith("ccr-managed-")===!0||u.provider.api_key?.startsWith("ccr-managed-")===!0))return null;let p=on(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=j(),i=[t?.[n],o?.[n]];for(let c of i)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let u=G(l,e,!1,n,void 0,void 0,s);if(u)return u}return null}function Yu(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=an(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function Li(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Qu(e))}function Ni(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Xu(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??c??6e4,h=Li(e,r,d),g=n.modelFamily,m=Ni(d,t,l),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||h>m)&&t.extendedContext){let k=G(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?Z("extendedContext",o,t.fallback,a,g,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, 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(h>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?G(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?Z("longContext",o,t.fallback,a,g,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let 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=G(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,g,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=G(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,g,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=G(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,g,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 nd(){if(Ce.size<=Ei)return;let n=[...Ce.keys()].slice(0,Ce.size-Ei);for(let e of n)Ce.delete(e)}function od(){if(We.size<=Ai)return;let n=[...We].slice(0,We.size-Ai);for(let e of n)We.delete(e)}var Ii,te,le,cn,Gu,Zu,ln,Ce,Ei,We,Ai,qu,ed,td,Oi,$i,Se=w(()=>{"use strict";nn();se();De();Yt();en();je();bi();Je();Ii={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||Ii[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Bu("cl100k_base"),cn=(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},Gu=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 $i(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await _i(n.sessionId);s&&Ku(s)&&(r=Pi(s))}if(r){n.projectId=r;let s=nr(wi,r,"config.json");if(!t&&n.sessionId){let a=nr(wi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await tr(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch{}}try{let a=JSON.parse(await tr(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Pi(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})}}}};Zu=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let v=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);v&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${v[1]}</CCR-SUBAGENT-MODEL>`,""),d=v[1])}let{family:f,extended:h,isCcrAlias:g}=mt(n.body.model),m=i?.families?.[f||""];if(m&&i?.enableFamilyRouting){n.log.info(`Using model family routing for: ${f}${h?" (1M)":""}`),n.modelFamily=f,n.familyFallback=m.fallback;let v=Xu(n,e,m,a,o,h,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=G(n.body.model,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let S=c?Z("default",a,void 0,u,void 0,s):null;if(S)return n.log.info(`Using fallback for explicit model: ${S}`),{model:S,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let y=g&&!i?.enableFamilyRouting?null:Vu(n.body.model,i?.models);if(y){let v=G(y,a,!1,"modelMapping",c,p,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${y}`),{model:v,scenarioType:"modelMapping"};let S=c?Z("modelMapping",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};if(s){let C=ee(n,y,a,"modelMapping");if(C)return{model:C,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${y} unavailable (fail pool), skipping`)}let b=n.clientContext,_=Li(e,o,b),k=Ni(b,void 0,i?.extendedContextThreshold);if(_>k&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${_}, estimated: ${e}, threshold: ${k}`);let v=G(i.extendedContext,a,!1,"extendedContext",c,p,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let S=c?Z("extendedContext",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};if(s){let C=ee(n,i.extendedContext,a,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext"}}}let T=b?.longContextThreshold??i?.longContextThreshold??6e4;if(_>T&&i?.longContext){n.log.info(`Using long context model due to token count: ${_}, estimated: ${e}, threshold: ${T}`);let v=G(i.longContext,a,!1,"longContext",c,p,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let S=c?Z("longContext",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};if(s){let C=ee(n,i.longContext,a,"longContext");if(C)return{model:C,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let v=G(i.background,a,!1,"background",c,p,s);if(v)return{model:v,scenarioType:"background"};let S=c?Z("background",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};if(s){let C=ee(n,i.background,a,"background");if(C)return{model:C,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&i?.webSearch){let v=G(i.webSearch,a,!1,"webSearch",c,p,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let S=c?Z("webSearch",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};if(s){let C=ee(n,i.webSearch,a,"webSearch");if(C)return{model:C,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=G(i.think,a,!1,"think",c,p,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let S=c?Z("think",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};if(s){let C=ee(n,i.think,a,"think");if(C)return{model:C,scenarioType:"think"}}}if(i?.default){let v=G(i.default,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let S=c?Z("default",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};let C=G(i.default,a,!0,"default",c,p,s);if(C)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:C,scenarioType:"default"}}if(s){let v=ee(n,i?.default||n.body.model,a,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},ln=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,o.getAll());let s=await Gu(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,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&d.length>1&&d[1]?.text?.includes("<env>")){let g=await tr(h,"utf-8");d[1].text=`${g}<env>${d[1].text.split("<env>").pop()}`}try{let[g,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(g,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,g)).tokenCount:b=cn(p,d,f),n.tokenCount=b;let _,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{_=await rt(k)(n,o.getAll(),{event:r})}catch(S){n.log.error(`failed to load custom router: ${S.message}`)}if(_)n.scenarioType="default";else{let S=await Zu(n,b,o,u,s,!!s);_=S.model,n.scenarioType=S.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((S,C,P)=>!!S&&P.indexOf(S)===C);if(v.length>0&&Yu(n)&&!gt(_))if(v.includes(_))n.scenarioType="image";else{let S=v.map(C=>G(C,c,!1,"image",i,!l,l)).find(C=>!!C);if(S)n.log.info(`Using image model fallback for ${_}`),_=S,n.scenarioType="image";else{let C=i?Z("image",c,x?.fallback,n.fallbackConfig,T||void 0,l):null;if(C)n.log.info(`Using image fallback model: ${C}`),_=C,n.scenarioType="image";else if(l){let P=ee(n,v[0],c,"image");P&&(_=P,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 S=n.scenarioType||"default",C=[...(n.familyFallback||{})[S]||[],...(n.fallbackConfig||{})[S]||[]];_=ci(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:C,resolve:P=>G(P,c,!1,S,i,!l,l),log:P=>n.log.info(P)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(g){if(g instanceof te)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),l){let m=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${g.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Ce=new Map,Ei=1e3,We=new Set,Ai=1e3,qu=3,ed=50,td=n=>new Promise(e=>setTimeout(e,n));Oi=async n=>{let e=await Ju(Ri),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=nr(Ri,s,`${n}.jsonl`);try{return(await Wu(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},$i=async n=>{let e=ge(n);if(!e)return null;if(Ce.has(e))return Ce.get(e)||null;try{let t=await Oi(e);if(!t&&!We.has(e)){We.add(e),od();for(let o=0;o<qu&&!t;o++)await td(ed),t=await Oi(e)}return t?(Ce.set(e,t),nd(),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 Ni(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),So(n);let s=id(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&gt(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&nd.test(r.model)&&await ln(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 B(`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&&gt(r);let l={req:n,isCodexOnMessagesEndpoint:c,responseTargetFormat:Di(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Ui(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"){b.push(k);continue}let T=JSON.stringify(k.content??"");y.has(T)||(y.add(T),_.push(k))}_.length>0&&b.length>0&&(u.messages=[..._,...b])}let f=await ji(u,p,i,t,d,o,l);try{i?.baseUrl&&f?.headers&&it(a,i.baseUrl,f.headers)}catch{}let h=await Hi(u,f,i,o,d,l);h=await Fi(r,h,i.name||a);let g=zi(h,e,r,t);try{let m=r.model||n.originalModel;a&&m&&j().recordSuccess(a,m)}catch{}return g}catch(l){if(l instanceof te)throw l;if(!Co(n,t.pluginRegistry.getManagedRuntimeFor(i),l,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Ni(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;l=d}}let p=await od(n,e,t,o,l);if(p)return p;throw n.__fallbackExhausted=!0,l}}async function Fi(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(`
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 Ui(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Ro(n);let s=cd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&rd.test(r.model)&&await ln(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 B(`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:Hi(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await ji(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 zi(u,p,i,t,d,o,l);try{i?.baseUrl&&f?.headers&&at(a,i.baseUrl,f.headers)}catch{}let h=await Bi(u,f,i,o,d,l);h=await Di(r,h,i.name||a);let g=Ji(h,e,r,t);try{let m=r.model||n.originalModel;a&&m&&j().recordSuccess(a,m)}catch{}return g}catch(l){if(l instanceof te)throw l;if(!wo(n,t.pluginRegistry.getManagedRuntimeFor(i),l,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Ui(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;l=d}}let p=await sd(n,e,t,o,l);if(p)return p;throw n.__fallbackExhausted=!0,l}}async function Di(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
28
  `).some(h=>h.startsWith("data:"))))break}if(c+=a.decode(),i.length===0)throw s.releaseLock(),B(`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 B(`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 B(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let h of i)d.enqueue(h);let f=()=>{s.read().then(({done:h,value:g})=>{h?d.close():(d.enqueue(g),f())}).catch(h=>d.error(h))};f()},cancel:()=>{s.cancel()}}),p=await Ds(u);if(p.verdict==="empty")throw B(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(js(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function od(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,c=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),l=j(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&un(r.rawBody)||r?.message&&un(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 g=_=>{let[b,...k]=_.split(","),T=b?.trim(),x=k.join(",").trim();return!T||!x?null:{provider:T,model:x,key:`${T},${x}`}},m=[];if(i){let _=a?.[s];if(Array.isArray(_)&&_.length>0)m.push({name:`${i}/${s}`,models:_});else{let b=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${b?"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(x=>x.type==="image"||x.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 _ of m){n.log.info(`Trying ${_.name} fallback stage with ${_.models.length} models`);for(let b of _.models){let k=g(b);if(!k){n.log.warn(`Fallback model '${b}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let T=t.providerService.getProviders(),x=pt(T,k.provider,k.model);if(!x){n.log.warn(`Fallback model ${b} is not configured or provider is disabled, skipping`);continue}let v=x.provider.name,C=x.model;if(!l.isAvailable(v,C,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${b} unavailable (fail pool), skipping`);continue}let S=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(S&&Ie(n,S,{name:v}).terminalError)continue;let P;for(let L=1;L<=2;L++)try{n.log.info(`Trying fallback model: ${v},${C}${L>1?" (retry)":""}`);let $={...n.body};$.model=C;let A={...n,provider:v,body:$},U=x.provider,R={pluginRegistry:t.pluginRegistry,req:A,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Di(A,o,A.codexDetected===!0)},{requestBody:E,config:I,bypass:O}=await Ui($,U,o,n.headers,R),M=await ji(E,I,U,t,O,o,R);try{U?.baseUrl&&M?.headers&&it(v,U.baseUrl,M.headers)}catch{}let H=await Hi(E,M,U,o,O,R);return H=await Fi($,H,v),n.log.info(`Fallback model ${v},${C} succeeded`),l.recordSuccess(v,C),u&&p&&!n.strictProjectRouting&&(Me().promote(u,p,s,v,C),n.log.info(`Promoted fallback model ${v},${C} 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=$,si(n,`${v},${C}`),zi(H,e,$,t)}catch($){if(P=$,Co(n,S,$,{name:v}))break;if(L===1){n.log.warn(`Fallback model ${v},${C} failed, retrying once: ${$.message}`);continue}}l.recordFailure(v,C,P?.message),n.log.warn(`Fallback model ${v},${C} failed after retry: ${P?.message}`),t.recordUsage?.({provider:v,model:C,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:P?.message||String(P),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 Ui(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw B("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=Ie(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=rd(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 rd(n,e,t){return e.endPoint==="/v1/chat/completions"&&Array.isArray(t?.system)?!1:n.transformer?.use?.length===1&&n.transformer.use[0].name===e.name&&(!n.transformer?.[t.model]?.use.length||n.transformer?.[t.model]?.use.length===1&&n.transformer?.[t.model]?.use[0].name===e.name)}function sd(n,e){if(e?.clientType!=="pi")return;let t=e?.clientContext?.stableSessionId;if(!(typeof t!="string"||!t)){for(let o of Object.keys(n))o.toLowerCase()==="x-litellm-session-id"&&delete n[o];n["x-litellm-session-id"]=t}}function Di(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function id(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 ji(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>$i(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):$i(n,e,t,o,r,s,a)}function We(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
30
- `):""}async function $i(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})),sd(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)&&Ms(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>Ns(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 Te(i,0,void 0,We(n),Js(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!Ie(a.req,i,t).refreshUsed){Ie(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(h){throw i?await Te(i,u.status,void 0,We(n)):h}if(i){let h=await Te(i,u.status,d,We(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${h.code}`),h}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let f=B(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||un(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 h="";try{if(h=await u.clone().text(),!h||h.trim()==="")throw new SyntaxError("Empty JSON body");if(ct(h))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let m=JSON.parse(h);if(i?.isErrorEnvelope?.(m))throw await Te(i,u.status,h,We(n));if(m&&typeof m=="object"&&m.error&&(typeof m.error=="string"||typeof m.error=="object"&&Object.keys(m.error).length>0)){if(i)throw await Te(i,u.status,h,We(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${h}`);let _=un(h),b=B(`Error from provider(${t.name},${n.model}: ${u.status}): ${h}`,400,"provider_response_error");throw b.isRateLimit=_,b.rawBody=h,b}}catch(g){if(i)throw g?.pluginClassified===!0?g:await Te(i,u.status,void 0,We(n));if(g instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${h}"`);let m=B(`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=h,m}throw g}}}if(!i?.suppressDebugLog&&!n.stream&&Jt(o.configService)){let f=await u.clone().text();Ls(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Hi(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 Ne().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function zi(n,e,t,o){n.ok||e.code(n.status);let r=ai(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=Is(o.configService);return $s(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return D(n)}function un(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 ad(n){try{return new URL(n),!0}catch{return!1}}var nd,Bi,dn=w(()=>{"use strict";Fs();zt();Hs();zs();Ws();rt();Eo();se();$e();Yt();en();Wo();V();Ce();q();nd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Bi=async n=>{n.get("/",async()=>({message:"LLMs API",version:Qt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:j().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Ni(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 B("Provider name is required",400,"invalid_request");if(!s||!ad(s))throw B("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw B("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw B("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw B(`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 B("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 B("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 B("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 B("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ke,tr=w(()=>{"use strict";Ke=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var ye,pn,Ji,cd,Wi,Ge=w(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",pn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Ji=["low","medium","high"],cd={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"},Wi=n=>{if(typeof n=="string")return cd[n.trim().toLowerCase()]}});var nr,Ki=w(()=>{nr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function ld(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Gi(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let h=t[f],g=h?.text??JSON.stringify(h),m=d.get(g);if(m===void 0){d.set(g,f);continue}!t[m]?.cache_control&&h?.cache_control&&(t[m]=h),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let h=f.content;try{typeof f.content=="string"&&(h=JSON.parse(f.content))}catch{}h!=null&&typeof h!="object"&&typeof h!="string"&&(h=String(h));let g={type:"tool_result",tool_use_id:f.tool_call_id,content:h};f.cache_control&&(g.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(g):s.push({role:"user",content:[g]})}else if(f.role==="user"){let h=[];typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?h.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):h.push(m)});let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"user",content:h.length>0?h:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let h=[];f.content&&(typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&h.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}h.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&h.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let g=s[s.length-1];g&&g.role==="assistant"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"assistant",content:h.length>0?h:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(h=>h?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},c=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let h=f.find(g=>g?.cache_control);if(h?.cache_control)return h.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},l=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(g=>g?.cache_control))return!1;let h=d.content.find(g=>g&&typeof g=="object"&&!g.cache_control);return h?(h.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,h=c(),g=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||g.push(m);for(let m of g){if(d<=0)break;l(f[m],h)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||pn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let h=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Ji.includes(h)&&(p.output_config={...p.output_config||{},effort:h})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
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 B(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let h of i)d.enqueue(h);let f=()=>{s.read().then(({done:h,value:g})=>{h?d.close():(d.enqueue(g),f())}).catch(h=>d.error(h))};f()},cancel:()=>{s.cancel()}}),p=await Hs(u);if(p.verdict==="empty")throw B(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(zs(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function sd(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,c=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),l=j(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&un(r.rawBody)||r?.message&&un(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 g=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(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(x=>x.type==="image"||x.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=g(_);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,S=x.model;if(!l.isAvailable(v,S,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let C=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(C&&Me(n,C,{name:v}).terminalError)continue;let P;for(let L=1;L<=2;L++)try{n.log.info(`Trying fallback model: ${v},${S}${L>1?" (retry)":""}`);let N={...n.body};N.model=S;let A={...n,provider:v,body:N},U=x.provider,R={pluginRegistry:t.pluginRegistry,req:A,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Hi(A,o,A.codexDetected===!0)},{requestBody:E,config:I,bypass:O}=await ji(N,U,o,n.headers,R),M=await zi(E,I,U,t,O,o,R);try{U?.baseUrl&&M?.headers&&at(v,U.baseUrl,M.headers)}catch{}let H=await Bi(E,M,U,o,O,R);return H=await Di(N,H,v),n.log.info(`Fallback model ${v},${S} succeeded`),l.recordSuccess(v,S),u&&p&&!n.strictProjectRouting&&(Le().promote(u,p,s,v,S),n.log.info(`Promoted fallback model ${v},${S} 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=N,ai(n,`${v},${S}`),Ji(H,e,N,t)}catch(N){if(P=N,wo(n,C,N,{name:v}))break;if(L===1){n.log.warn(`Fallback model ${v},${S} failed, retrying once: ${N.message}`);continue}}l.recordFailure(v,S,P?.message),n.log.warn(`Fallback model ${v},${S} failed after retry: ${P?.message}`),t.recordUsage?.({provider:v,model:S,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:P?.message||String(P),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 ji(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw B("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=Me(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=id(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 id(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 ad(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 Hi(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function cd(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 zi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>Fi(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):Fi(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 Fi(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})),ad(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)&&Ns(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>Us(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 Te(i,0,void 0,Ke(n),Ks(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!Me(a.req,i,t).refreshUsed){Me(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(h){throw i?await Te(i,u.status,void 0,Ke(n)):h}if(i){let h=await Te(i,u.status,d,Ke(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${h.code}`),h}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let f=B(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||un(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 h="";try{if(h=await u.clone().text(),!h||h.trim()==="")throw new SyntaxError("Empty JSON body");if(lt(h))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let m=JSON.parse(h);if(i?.isErrorEnvelope?.(m))throw await Te(i,u.status,h,Ke(n));if(m&&typeof m=="object"&&m.error&&(typeof m.error=="string"||typeof m.error=="object"&&Object.keys(m.error).length>0)){if(i)throw await Te(i,u.status,h,Ke(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${h}`);let b=un(h),_=B(`Error from provider(${t.name},${n.model}: ${u.status}): ${h}`,400,"provider_response_error");throw _.isRateLimit=b,_.rawBody=h,_}}catch(g){if(i)throw g?.pluginClassified===!0?g:await Te(i,u.status,void 0,Ke(n));if(g instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${h}"`);let m=B(`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=h,m}throw g}}}if(!i?.suppressDebugLog&&!n.stream&&Jt(o.configService)){let f=await u.clone().text();$s(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Bi(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 Fe().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function Ji(n,e,t,o){n.ok||e.code(n.status);let r=li(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=Ls(o.configService);return Fs(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return D(n)}function un(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 ld(n){try{return new URL(n),!0}catch{return!1}}var rd,Wi,dn=w(()=>{"use strict";Ds();zt();Bs();Js();Gs();st();Oo();se();$e();Yt();en();Go();Q();Se();q();rd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Wi=async n=>{n.get("/",async()=>({message:"LLMs API",version:Qt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:j().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Ui(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 B("Provider name is required",400,"invalid_request");if(!s||!ld(s))throw B("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw B("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw B("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw B(`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 B("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 B("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 B("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 B("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ge,or=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,pn,Ki,ud,Gi,Ve=w(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",pn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Ki=["low","medium","high"],ud={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"},Gi=n=>{if(typeof n=="string")return ud[n.trim().toLowerCase()]}});var rr,Vi=w(()=>{rr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function dd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Qi(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let h=t[f],g=h?.text??JSON.stringify(h),m=d.get(g);if(m===void 0){d.set(g,f);continue}!t[m]?.cache_control&&h?.cache_control&&(t[m]=h),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let h=f.content;try{typeof f.content=="string"&&(h=JSON.parse(f.content))}catch{}h!=null&&typeof h!="object"&&typeof h!="string"&&(h=String(h));let g={type:"tool_result",tool_use_id:f.tool_call_id,content:h};f.cache_control&&(g.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(g):s.push({role:"user",content:[g]})}else if(f.role==="user"){let h=[];typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?h.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):h.push(m)});let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"user",content:h.length>0?h:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let h=[];f.content&&(typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&h.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}h.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&h.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let g=s[s.length-1];g&&g.role==="assistant"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"assistant",content:h.length>0?h:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(h=>h?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},c=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let h=f.find(g=>g?.cache_control);if(h?.cache_control)return h.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},l=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(g=>g?.cache_control))return!1;let h=d.content.find(g=>g&&typeof g=="object"&&!g.cache_control);return h?(h.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,h=c(),g=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||g.push(m);for(let m of g){if(d<=0)break;l(f[m],h)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||pn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let h=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Ki.includes(h)&&(p.output_config={...p.output_config||{},effort:h})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
31
31
 
32
- `)}return n.tools&&n.tools.length>0&&(p.tools=ld(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 Vi=w(()=>{Ge()});import{v4 as or}from"uuid";function ud(n){if(n===!0)return!0;if(n===!1)return!1;if(typeof n!="string")return;let e=n.trim().toLowerCase();if(e==="enabled"||e==="adaptive"||e==="true")return!0;if(e==="disabled"||e==="off"||e==="none"||e==="false")return!1}var fn,Qi=w(()=>{"use strict";Ge();zt();V();Ki();Vi();Ce();fn=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=mt(String(e.model??"")),p=[];c.forEach(d=>{let f=Array.isArray(d.content)?d.content:null,h=f?f.filter(y=>y?.type==="image"&&y?.source):[],g=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(h.length>0){let y=f.filter(_=>!(_?.type==="image"&&_?.source)).map(_=>_?.type==="text"?String(_.text??""):JSON.stringify(_)).filter(_=>_.length>0).join(`
33
- `);u?(g=y||"[tool image]",p.push(...h)):(g=[y,...h.map(()=>"(tool image omitted: target model does not support image input)")].filter(_=>_.length>0).join(`
34
- `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:h.length}))}let m={role:"tool",content:g,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?nr(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"?nr(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=Wi(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=ud(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=Gi(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 D(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,d=new Map,f=new Map,h=0,g=0,m=0,y=!1,_=!1,b=0,k=-1,T=()=>{let S=b;return b++,S},x=S=>{if(!y)try{r.enqueue(S);let P=new TextDecoder().decode(S);this.logger.debug({reqId:t.req.id,data:P,type:"send data"})}catch(P){if(P instanceof TypeError&&P.message.includes("Controller is already closed"))y=!0;else throw this.logger.debug({reqId:t.req.id,error:P instanceof Error?P.message:String(P),type:"send data error"}),P}},v=()=>{if(!y)try{if(!l){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),y=!0;return}if(k>=0){let P={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
32
+ `)}return n.tools&&n.tools.length>0&&(p.tools=dd(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 Yi=w(()=>{Ve()});function pd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function fn(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 Re(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:pd(n),cache_creation_input_tokens:fn(n)}}function we(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 mn=w(()=>{"use strict"});import{v4 as sr}from"uuid";function fd(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 ir(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 gn,Xi=w(()=>{"use strict";Ve();zt();Q();Vi();Yi();Se();mn();gn=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,h=f?f.filter(y=>y?.type==="image"&&y?.source):[],g=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(h.length>0){let y=f.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
33
+ `);u?(g=y||"[tool image]",p.push(...h)):(g=[y,...h.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
34
+ `),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:h.length}))}let m={role:"tool",content:g,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?rr(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"?rr(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=Gi(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=fd(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=Qi(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 D(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,d=new Map,f=new Map,h=0,g=0,m=0,y=!1,b=!1,_=0,k=-1,T=()=>{let C=_;return _++,C},x=C=>{if(!y)try{r.enqueue(C);let P=new TextDecoder().decode(C);this.logger.debug({reqId:t.req.id,data:P,type:"send data"})}catch(P){if(P instanceof TypeError&&P.message.includes("Controller is already closed"))y=!0;else throw this.logger.debug({reqId:t.req.id,error:P instanceof Error?P.message:String(P),type:"send data error"}),P}},v=()=>{if(!y)try{if(!l){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),y=!0;return}if(k>=0){let P={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
36
36
  data: ${JSON.stringify(P)}
37
37
 
38
38
  `)),k=-1}if(i)x(s.encode(`event: message_delta
@@ -41,20 +41,20 @@ data: ${JSON.stringify(i)}
41
41
  `)),i=null;else{let P=t?.req?.tokenCount||0;x(s.encode(`event: message_delta
42
42
  data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:P,output_tokens:0,cache_read_input_tokens:0}})}
43
43
 
44
- `))}let S={type:"message_stop"};x(s.encode(`event: message_stop
45
- data: ${JSON.stringify(S)}
44
+ `))}let C={type:"message_stop"};x(s.encode(`event: message_stop
45
+ data: ${JSON.stringify(C)}
46
46
 
47
- `)),r.close(),y=!0}catch(S){if(S instanceof TypeError&&S.message.includes("Controller is already closed"))y=!0;else throw S}},C=null;try{C=e.getReader();let S=new TextDecoder,P="";for(;!y;){let{done:L,value:$}=await C.read();if(L)break;P+=S.decode($,{stream:!0});let A=P.split(`
47
+ `)),r.close(),y=!0}catch(C){if(C instanceof TypeError&&C.message.includes("Controller is already closed"))y=!0;else throw C}},S=null;try{S=e.getReader();let C=new TextDecoder,P="";for(;!y;){let{done:L,value:N}=await S.read();if(L)break;P+=C.decode(N,{stream:!0});let A=P.split(`
48
48
  `);P=A.pop()||"";for(let U of A){if(y)break;if(!U.startsWith("data:"))continue;let R=U.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:R}),R!=="[DONE]")try{let E=JSON.parse(R);if(h++,this.logger.debug({reqId:t.req.id,response:E,tppe:"Original Response"}),E.error){t?.req&&(t.req.sseError=E.error);let O={type:"error",message:{type:"api_error",message:JSON.stringify(E.error)}};x(s.encode(`event: error
49
49
  data: ${JSON.stringify(O)}
50
50
 
51
51
  `));continue}if(c=E.model&&E.model!=="unknown"?E.model:c,!l&&!y&&!p){l=!0;let O=t?.req?.tokenCount||0,M={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:c,stop_reason:null,stop_sequence:null,usage:{input_tokens:O,output_tokens:0}}};x(s.encode(`event: message_start
52
52
  data: ${JSON.stringify(M)}
53
53
 
54
- `))}let I=E.choices?.[0];if(E.usage){let O=E.usage?.prompt_tokens_details?.cached_tokens??E.usage?.prompt_cache_hit_tokens??0,H=(E.usage?.prompt_tokens||0)-O,re=E.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:E.usage,mappedUsage:{input_tokens:H,output_tokens:re,cache_read_input_tokens:O},choicesLength:Array.isArray(E.choices)?E.choices.length:void 0,finishReason:I?.finish_reason});let z={input_tokens:H,output_tokens:re,cache_read_input_tokens:O};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...z}};else{let Z=i.usage||{};i.usage={input_tokens:z.input_tokens||Z.input_tokens||0,output_tokens:z.output_tokens||Z.output_tokens||0,cache_read_input_tokens:z.cache_read_input_tokens||Z.cache_read_input_tokens||0}}}if(!I)continue;if(I?.delta?.thinking&&!y&&!p&&!u){if(!_){let O=T(),M={type:"content_block_start",index:O,content_block:{type:"thinking",thinking:""}};x(s.encode(`event: content_block_start
54
+ `))}let I=E.choices?.[0];if(E.usage){let O=E.usage?.prompt_tokens_details?.cached_tokens??E.usage?.prompt_cache_hit_tokens??0,H=(E.usage?.prompt_tokens||0)-O,re=E.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:E.usage,mappedUsage:{input_tokens:H,output_tokens:re,cache_read_input_tokens:O},choicesLength:Array.isArray(E.choices)?E.choices.length:void 0,finishReason:I?.finish_reason});let z={input_tokens:H,output_tokens:re,cache_read_input_tokens:O,...ir(E.usage)?{cache_creation_input_tokens:fn(E.usage)}:{},...E.usage.kiro_estimated===!0||E.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...z}};else{let V=i.usage||{};ir(E.usage)||"cache_creation_input_tokens"in V?i.usage=we(V,z,!1):i.usage={input_tokens:z.input_tokens||V.input_tokens||0,output_tokens:z.output_tokens||V.output_tokens||0,cache_read_input_tokens:z.cache_read_input_tokens||V.cache_read_input_tokens||0}}}if(!I)continue;if(I?.delta?.thinking&&!y&&!p&&!u){if(!b){let O=T(),M={type:"content_block_start",index:O,content_block:{type:"thinking",thinking:""}};x(s.encode(`event: content_block_start
55
55
  data: ${JSON.stringify(M)}
56
56
 
57
- `)),k=O,_=!0}if(I.delta.thinking.signature){let O={type:"content_block_delta",index:k,delta:{type:"signature_delta",signature:I.delta.thinking.signature}};x(s.encode(`event: content_block_delta
57
+ `)),k=O,b=!0}if(I.delta.thinking.signature){let O={type:"content_block_delta",index:k,delta:{type:"signature_delta",signature:I.delta.thinking.signature}};x(s.encode(`event: content_block_delta
58
58
  data: ${JSON.stringify(O)}
59
59
 
60
60
  `));let M={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
@@ -75,56 +75,56 @@ data: ${JSON.stringify(O)}
75
75
  `))}}if(I?.delta?.annotations?.length&&!y&&!p){if(k>=0&&u){let O={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
76
76
  data: ${JSON.stringify(O)}
77
77
 
78
- `)),k=-1,u=!1}I?.delta?.annotations.forEach(O=>{let M=T(),H={type:"content_block_start",index:M,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${or()}`,content:[{type:"web_search_result",title:O.url_citation.title,url:O.url_citation.url}]}};x(s.encode(`event: content_block_start
78
+ `)),k=-1,u=!1}I?.delta?.annotations.forEach(O=>{let M=T(),H={type:"content_block_start",index:M,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${sr()}`,content:[{type:"web_search_result",title:O.url_citation.title,url:O.url_citation.url}]}};x(s.encode(`event: content_block_start
79
79
  data: ${JSON.stringify(H)}
80
80
 
81
81
  `));let re={type:"content_block_stop",index:M};x(s.encode(`event: content_block_stop
82
82
  data: ${JSON.stringify(re)}
83
83
 
84
- `)),k=-1})}if(I?.delta?.tool_calls&&!y&&!p){m++;let O=new Set;for(let M of I.delta.tool_calls){if(y)break;let H=M.index??0;if(O.has(H))continue;if(O.add(H),!f.has(H)){if(k>=0){let nl={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
85
- data: ${JSON.stringify(nl)}
84
+ `)),k=-1})}if(I?.delta?.tool_calls&&!y&&!p){m++;let O=new Set;for(let M of I.delta.tool_calls){if(y)break;let H=M.index??0;if(O.has(H))continue;if(O.add(H),!f.has(H)){if(k>=0){let rl={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
85
+ data: ${JSON.stringify(rl)}
86
86
 
87
- `)),k=-1}let z=T();f.set(H,z);let Z=M.id||`call_ccr_${H}`,J=M.function?.name||`tool_${H}`,N={type:"content_block_start",index:z,content_block:{type:"tool_use",id:Z,name:J,input:{}}};x(s.encode(`event: content_block_start
88
- data: ${JSON.stringify(N)}
87
+ `)),k=-1}let z=T();f.set(H,z);let V=M.id||`call_ccr_${H}`,J=M.function?.name||`tool_${H}`,$={type:"content_block_start",index:z,content_block:{type:"tool_use",id:V,name:J,input:{}}};x(s.encode(`event: content_block_start
88
+ data: ${JSON.stringify($)}
89
89
 
90
- `)),k=z;let W={id:Z,name:J,arguments:"",contentBlockIndex:z};d.set(H,W)}else if(M.id&&M.function?.name){let z=d.get(H);z.id.startsWith("call_")&&z.name.startsWith("tool_")&&(z.id=M.id,z.name=M.function.name)}if(M.function?.arguments&&!y&&!p){let z=f.get(H);if(z===void 0)continue;let Z=d.get(H);Z&&(Z.arguments+=M.function.arguments);try{let J={type:"content_block_delta",index:z,delta:{type:"input_json_delta",partial_json:M.function.arguments}};x(s.encode(`event: content_block_delta
90
+ `)),k=z;let W={id:V,name:J,arguments:"",contentBlockIndex:z};d.set(H,W)}else if(M.id&&M.function?.name){let z=d.get(H);z.id.startsWith("call_")&&z.name.startsWith("tool_")&&(z.id=M.id,z.name=M.function.name)}if(M.function?.arguments&&!y&&!p){let z=f.get(H);if(z===void 0)continue;let V=d.get(H);V&&(V.arguments+=M.function.arguments);try{let J={type:"content_block_delta",index:z,delta:{type:"input_json_delta",partial_json:M.function.arguments}};x(s.encode(`event: content_block_delta
91
91
  data: ${JSON.stringify(J)}
92
92
 
93
- `))}catch{try{let J=M.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),N={type:"content_block_delta",index:z,delta:{type:"input_json_delta",partial_json:J}};x(s.encode(`event: content_block_delta
94
- data: ${JSON.stringify(N)}
93
+ `))}catch{try{let J=M.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),$={type:"content_block_delta",index:z,delta:{type:"input_json_delta",partial_json:J}};x(s.encode(`event: content_block_delta
94
+ data: ${JSON.stringify($)}
95
95
 
96
96
  `))}catch(J){console.error(J)}}}}}if(I?.finish_reason&&!y&&!p){if(g===0&&m===0&&console.error("Warning: No content in the stream response!"),k>=0){let O={type:"content_block_stop",index:k};x(s.encode(`event: content_block_stop
97
97
  data: ${JSON.stringify(O)}
98
98
 
99
- `)),k=-1}if(!y){let M={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[I.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:M,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:M,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(E){this.logger?.error(`parseError: ${E.name} message: ${E.message} stack: ${E.stack} data: ${R}`)}}}v()}catch(S){if(!y)try{r.error(S)}catch(P){console.error(P)}}finally{if(C)try{C.releaseLock()}catch(S){console.error(S)}}},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_${or()}`;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_${or().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw B(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function dd(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 ht(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&dd(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]=ht(i);else if(o.includes(a)){let c=[];for(let l of i){if(l.type=="null"){e.nullable=!0;continue}c.push(ht(l))}e[a]=c}else if(r.includes(a)){let c={};for(let[l,u]of Object.entries(i))c[l]=ht(u);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=i}return e}function pd(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=ht(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ht(e.response));return n}function mn(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(pd({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(h=>h.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let 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 gn(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 hn(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 _=m.slice(6).trim();if(_){t?.debug({chunkStr:_},`${e} chunk:`);try{let b=JSON.parse(_);if(!b.candidates||!b.candidates[0]){t?.debug({chunkStr:_},"Invalid chunk structure");return}let k=b.candidates[0],T=k.content?.parts||[];T.filter(S=>S.text&&S.thought===!0).forEach(S=>{i||(i=!0);let P={choices:[{delta:{role:"assistant",content:null,thinking:{content:S.text}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(P)}
99
+ `)),k=-1}if(!y){let M={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[I.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:M,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:M,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(E){this.logger?.error(`parseError: ${E.name} message: ${E.message} stack: ${E.stack} data: ${R}`)}}}v()}catch(C){if(!y)try{r.error(C)}catch(P){console.error(P)}}finally{if(S)try{S.releaseLock()}catch(C){console.error(C)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let c=`srvtoolu_${sr()}`;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_${sr().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:ir(e.usage)?fn(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 B(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function md(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Qe).includes(o)?o:Qe.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Qe).includes(r)?r:Qe.TYPE_UNSPECIFIED})}}}function yt(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&md(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(Qe).includes(c)?c:Qe.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 gd(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 hn(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(gd({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(h=>h.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let 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 yn(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 _n(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(C=>C.text&&C.thought===!0).forEach(C=>{i||(i=!0);let P={choices:[{delta:{role:"assistant",content:null,thinking:{content:C.text}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(P)}
101
101
 
102
- `))});let x=T.find(S=>S.thoughtSignature)?.thoughtSignature;if(x&&!s){if(!i){let P={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(P)}
102
+ `))});let x=T.find(C=>C.thoughtSignature)?.thoughtSignature;if(x&&!s){if(!i){let P={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(P)}
103
103
 
104
- `))}let S={choices:[{delta:{role:"assistant",content:null,thinking:{signature:x}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(S)}
104
+ `))}let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:x}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(C)}
105
105
 
106
- `)),s=!0,l++,c){let P={choices:[{delta:{role:"assistant",content:c},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(P)}
106
+ `)),s=!0,l++,c){let P={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(P)}
107
107
 
108
- `)),c="",a||(a=!0)}}let v=T.filter(S=>S.functionCall).map(S=>({id:S.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:S.functionCall?.name,arguments:JSON.stringify(S.functionCall?.args||{})}})),C=T.filter(S=>S.text&&S.thought!==!0).map(S=>S.text).join(`
109
- `);if(!C&&s&&!a){let S={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(S)}
108
+ `)),c="",a||(a=!0)}}let v=T.filter(C=>C.functionCall).map(C=>({id:C.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})}})),S=T.filter(C=>C.text&&C.thought!==!0).map(C=>C.text).join(`
109
+ `);if(!S&&s&&!a){let C={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(C)}
110
110
 
111
- `)),a||(a=!0)}if(i&&C&&!s)if(b.modelVersion.includes("3")){c+=C;return}else{let S={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(S)}
111
+ `)),a||(a=!0)}if(i&&S&&!s)if(_.modelVersion.includes("3")){c+=S;return}else{let C={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(C)}
112
112
 
113
- `)),s=!0}if(C){c||l++;let S={choices:[{delta:{role:"assistant",content:C},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};k?.groundingMetadata?.groundingChunks?.length&&(S.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((P,L)=>{let $=k?.groundingMetadata?.groundingSupports?.filter(A=>A.groundingChunkIndices?.includes(L));return{type:"url_citation",url_citation:{url:P?.web?.uri||"",title:P?.web?.title||"",content:$?.[0]?.segment?.text||"",start_index:$?.[0]?.segment?.startIndex||0,end_index:$?.[0]?.segment?.endIndex||0}}})),y.enqueue(r.encode(`data: ${JSON.stringify(S)}
113
+ `)),s=!0}if(S){c||l++;let C={choices:[{delta:{role:"assistant",content:S},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&&(C.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((P,L)=>{let N=k?.groundingMetadata?.groundingSupports?.filter(A=>A.groundingChunkIndices?.includes(L));return{type:"url_citation",url_citation:{url:P?.web?.uri||"",title:P?.web?.title||"",content:N?.[0]?.segment?.text||"",start_index:N?.[0]?.segment?.startIndex||0,end_index:N?.[0]?.segment?.endIndex||0}}})),y.enqueue(r.encode(`data: ${JSON.stringify(C)}
114
114
 
115
- `)),!a&&C&&(a=!0)}v.length>0&&(v.forEach(S=>{l++,u++;let P={choices:[{delta:{role:"assistant",tool_calls:[{...S,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};k?.groundingMetadata?.groundingChunks?.length&&(P.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((L,$)=>{let A=k?.groundingMetadata?.groundingSupports?.filter(U=>U.groundingChunkIndices?.includes($));return{type:"url_citation",url_citation:{url:L?.web?.uri||"",title:L?.web?.title||"",content:A?.[0]?.segment?.text||"",start_index:A?.[0]?.segment?.startIndex||0,end_index:A?.[0]?.segment?.endIndex||0}}})),y.enqueue(r.encode(`data: ${JSON.stringify(P)}
115
+ `)),!a&&S&&(a=!0)}v.length>0&&(v.forEach(C=>{l++,u++;let P={choices:[{delta:{role:"assistant",tool_calls:[{...C,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.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&&(P.choices[0].delta.annotations=k.groundingMetadata.groundingChunks.map((L,N)=>{let A=k?.groundingMetadata?.groundingSupports?.filter(U=>U.groundingChunkIndices?.includes(N));return{type:"url_citation",url_citation:{url:L?.web?.uri||"",title:L?.web?.title||"",content:A?.[0]?.segment?.text||"",start_index:A?.[0]?.segment?.startIndex||0,end_index:A?.[0]?.segment?.endIndex||0}}})),y.enqueue(r.encode(`data: ${JSON.stringify(P)}
116
116
 
117
- `))}),!a&&C&&(a=!0))}catch(b){t?.error(`Error parsing ${e} stream chunk`,_,b.message)}}}},h=n.body.getReader(),g="";try{for(;;){let{done:m,value:y}=await h.read();if(m){g&&await f(g,d);break}g+=o.decode(y,{stream:!0});let _=g.split(`
118
- `);g=_.pop()||"";for(let b of _)await f(b,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ve,rr=w(()=>{"use strict";Ve={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var yn,Yi=w(()=>{"use strict";rr();yn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:mn(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=gn;async transformResponseOut(e){return hn(e,this.name,this.logger)}}});async function fd(){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
+ `))}),!a&&S&&(a=!0))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},h=n.body.getReader(),g="";try{for(;;){let{done:m,value:y}=await h.read();if(m){g&&await f(g,d);break}g+=o.decode(y,{stream:!0});let b=g.split(`
118
+ `);g=b.pop()||"";for(let _ of b)await f(_,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Qe,ar=w(()=>{"use strict";Qe={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var bn,Zi=w(()=>{"use strict";ar();bn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:hn(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=yn;async transformResponseOut(e){return _n(e,this.name,this.logger)}}});async function hd(){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
119
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
120
120
  2. Run "gcloud auth application-default login"
121
- 3. Use Google Cloud environment with default service account`)}}var bn,Xi=w(()=>{"use strict";rr();bn=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 fd();return{body:mn(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 gn(e)}async transformResponseOut(e){return hn(e,this.name)}}});var _n,Zi=w(()=>{"use strict";V();_n=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 D(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,h)=>{let g=d.split(`
121
+ 3. Use Google Cloud environment with default service account`)}}var kn,qi=w(()=>{"use strict";ar();kn=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 hd();return{body:hn(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 yn(e)}async transformResponseOut(e){return _n(e,this.name)}}});var Tn,ea=w(()=>{"use strict";Q();Tn=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 D(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,h)=>{let g=d.split(`
122
122
  `);for(let m of g)m.trim()&&f.enqueue(h.encode(m+`
123
- `))},p=(d,f)=>{let{controller:h,encoder:g}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(y)}
123
+ `))},p=(d,f)=>{let{controller:h,encoder:g}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
124
124
 
125
- `;h.enqueue(g.encode(_));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",_=m.choices[0].delta.content,b={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete b.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(b)}
125
+ `;h.enqueue(g.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
126
126
 
127
- `;h.enqueue(g.encode(k));let T={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:_}}]};delete T.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(T)}
127
+ `;h.enqueue(g.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
128
 
129
129
  `;h.enqueue(g.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
130
 
@@ -132,67 +132,67 @@ data: ${JSON.stringify(O)}
132
132
  `))}else h.enqueue(g.encode(d+`
133
133
  `))};try{for(;;){let{done:d,value:f}=await l.read();if(d){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
134
134
  `);a=g.pop()||"";for(let m of g)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 kn,qi=w(()=>{"use strict";V();kn=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.
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 vn,ta=w(()=>{"use strict";Q();vn=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
136
  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
137
  Examples:
138
138
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
139
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 D(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,h)=>{let g=d.split(`
140
140
  `);for(let m of g)m.trim()&&f.enqueue(h.encode(m+`
141
- `))},p=(d,f)=>{let{controller:h,encoder:g,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:_}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let b=JSON.parse(d.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let k=b.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){_(k.function.arguments);try{let T=JSON.parse(f.exitToolResponse());b.choices=[{delta:{role:"assistant",content:T.response||""}}];let x=`data: ${JSON.stringify(b)}
141
+ `))},p=(d,f)=>{let{controller:h,encoder:g,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let T=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:T.response||""}}];let x=`data: ${JSON.stringify(_)}
142
142
 
143
- `;h.enqueue(g.encode(x))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let k=`data: ${JSON.stringify(b)}
143
+ `;h.enqueue(g.encode(x))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
144
144
 
145
145
  `;h.enqueue(g.encode(k))}}catch{h.enqueue(g.encode(d+`
146
146
  `))}else h.enqueue(g.encode(d+`
147
147
  `))};try{for(;;){let{done:d,value:f}=await l.read();if(d){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
148
148
  `);a=g.pop()||"";for(let m of g)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 md}from"uuid";var Tn,ea=w(()=>{"use strict";V();Tn=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 D(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
150
- `);for(let _ of y)_.trim()&&g.enqueue(m.encode(_+`
151
- `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let _=h.slice(6);try{let b=JSON.parse(_);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:i},"usage"),b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
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 yd}from"uuid";var xn,na=w(()=>{"use strict";Q();xn=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 D(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
150
+ `);for(let b of y)b.trim()&&g.enqueue(m.encode(b+`
151
+ `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let b=h.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
152
152
 
153
- `));return}b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0);let k=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(k){g.appendReasoningContent(k);let S={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:k}}}]};S.choices?.[0]?.delta&&(delete S.choices[0].delta.reasoning,delete S.choices[0].delta.reasoning_content);let P=`data: ${JSON.stringify(S)}
153
+ `));return}_.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0);let k=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(k){g.appendReasoningContent(k);let C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let P=`data: ${JSON.stringify(C)}
154
154
 
155
- `;m.enqueue(y.encode(P));return}if(b.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let S="ccr_think_signature",P=b.choices[0].delta.content,L={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:S}}}]};L.choices?.[0]?.delta&&delete L.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(L)}
155
+ `;m.enqueue(y.encode(P));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let C="ccr_think_signature",P=_.choices[0].delta.content,L={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:C}}}]};L.choices?.[0]?.delta&&delete L.choices[0].delta.reasoning;let N=`data: ${JSON.stringify(L)}
156
156
 
157
- `;m.enqueue(y.encode($));let A={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:P}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content);let U=`data: ${JSON.stringify(A)}
157
+ `;m.enqueue(y.encode(N));let A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:P}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content);let U=`data: ${JSON.stringify(A)}
158
158
 
159
- `;m.enqueue(y.encode(U));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(S=>{S.id=`call_${md()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let T=b.choices?.[0]?.delta,x=T&&Object.keys(T).length>0,v=b.choices?.[0]?.finish_reason,C=b.usage;if(x||v||C){let S=`data: ${JSON.stringify(b)}
159
+ `;m.enqueue(y.encode(U));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(C=>{C.id=`call_${yd()}`}),_.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,S=_.usage;if(x||v||S){let C=`data: ${JSON.stringify(_)}
160
160
 
161
- `;m.enqueue(y.encode(S))}}catch{m.enqueue(y.encode(h+`
161
+ `;m.enqueue(y.encode(C))}}catch{m.enqueue(y.encode(h+`
162
162
  `))}}else m.enqueue(y.encode(h+`
163
- `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(m.length===0)continue;if(c+=m,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=c.split(`
164
- `);c=_.pop()||"";for(let b of _)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",b,k),u.enqueue(o.encode(b+`
163
+ `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(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
165
  `))}continue}let y=c.split(`
166
- `);c=y.pop()||"";for(let _ of y)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),u.enqueue(o.encode(_+`
167
- `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var vn,ta=w(()=>{"use strict";vn=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 gd}from"uuid";var xn,na=w(()=>{"use strict";V();xn=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 D(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,h,g)=>{let m=f.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(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Cn,oa=w(()=>{"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 _d}from"uuid";var Sn,ra=w(()=>{"use strict";Q();Sn=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 D(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,h,g)=>{let m=f.split(`
168
168
  `);for(let y of m)y.trim()&&h.enqueue(g.encode(y+`
169
- `))},d=(f,h)=>{let{controller:g,encoder:m}=h;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let _=JSON.parse(y);if(_.error)throw new Error(JSON.stringify(_));_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.tool_calls?.length&&_.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${gd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let b=`data: ${JSON.stringify(_)}
169
+ `))},d=(f,h)=>{let{controller:g,encoder:m}=h;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let b=JSON.parse(y);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${_d()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let _=`data: ${JSON.stringify(b)}
170
170
 
171
- `;g.enqueue(m.encode(b))}catch{g.enqueue(m.encode(f+`
171
+ `;g.enqueue(m.encode(_))}catch{g.enqueue(m.encode(f+`
172
172
  `))}}else g.enqueue(m.encode(f+`
173
173
  `))};try{for(;;){let{done:f,value:h}=await u.read();if(f){i.trim()&&p(i,l,o);break}if(!h||h.length===0)continue;let g;try{g=t.decode(h,{stream:!0})}catch(y){console.warn("Failed to decode chunk",y);continue}if(g.length===0)continue;if(i+=g,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let y=i.split(`
174
- `);i=y.pop()||"";for(let _ of y)if(_.trim())try{d(_,{controller:l,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),l.enqueue(o.encode(_+`
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+`
175
175
  `))}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:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",y,_),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 Sn,oa=w(()=>{"use strict";Sn=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 hd from"json5";import{jsonrepair as yd}from"jsonrepair";function sr(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=hd.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=yd(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 ra=w(()=>{});var Cn,sa=w(()=>{"use strict";ra();V();Cn=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await D(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=sr(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,_)=>{let b=m.split(`
178
- `);for(let k of b)k.trim()&&y.enqueue(_.encode(k+`
179
- `))},h=(m,y,_)=>{let b="";try{b=sr(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)}`),b=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:b},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)}
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 Rn,sa=w(()=>{"use strict";Rn=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 bd from"json5";import{jsonrepair as kd}from"jsonrepair";function cr(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=bd.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=kd(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 ia=w(()=>{});var wn,aa=w(()=>{"use strict";ia();Q();wn=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await D(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=cr(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(`
178
+ `);for(let k of _)k.trim()&&y.enqueue(b.encode(k+`
179
+ `))},h=(m,y,b)=>{let _="";try{_=cr(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
180
 
181
- `;y.enqueue(_.encode(x))},g=(m,y)=>{let{controller:_,encoder:b}=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 C=`data: ${JSON.stringify(T)}
181
+ `;y.enqueue(b.encode(x))},g=(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 S=`data: ${JSON.stringify(T)}
182
182
 
183
- `;_.enqueue(b.encode(C));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{h(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){h(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)}
183
+ `;b.enqueue(_.encode(S));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{h(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){h(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
184
 
185
- `;_.enqueue(b.encode(x))}catch{_.enqueue(b.encode(m+`
186
- `))}}else _.enqueue(b.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 _;try{_=t.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(_.length===0)continue;if(l+=_,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
185
+ `;b.enqueue(_.encode(x))}catch{b.enqueue(_.encode(m+`
186
+ `))}}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
188
  `);l=k.pop()||"";for(let T of k)if(T.trim())try{g(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+`
189
- `))}continue}let b=l.split(`
190
- `);l=b.pop()||"";for(let k of b)if(k.trim())try{g(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 Rn,ia=w(()=>{"use strict";V();Ge();Rn=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??pn(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 D(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,h)=>{let g=d.split(`
189
+ `))}continue}let _=l.split(`
190
+ `);l=_.pop()||"";for(let k of _)if(k.trim())try{g(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 Pn,ca=w(()=>{"use strict";Q();Ve();Pn=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??pn(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 D(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,h)=>{let g=d.split(`
192
192
  `);for(let m of g)m.trim()&&f.enqueue(h.encode(m+`
193
- `))},p=(d,f)=>{let{controller:h,encoder:g}=f;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(console.log(JSON.stringify(m)),m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(y)}
193
+ `))},p=(d,f)=>{let{controller:h,encoder:g}=f;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(console.log(JSON.stringify(m)),m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
194
194
 
195
- `;h.enqueue(g.encode(_));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",_=m.choices[0].delta.content,b={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete b.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(b)}
195
+ `;h.enqueue(g.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
196
196
 
197
197
  `;h.enqueue(g.encode(k))}if(m.choices?.[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){f.isReasoningComplete()&&m.choices[0].index++;let y=`data: ${JSON.stringify(m)}
198
198
 
@@ -200,7 +200,7 @@ Examples:
200
200
  `))}else h.enqueue(g.encode(d+`
201
201
  `))};try{for(;;){let{done:d,value:f}=await l.read();if(d){a.trim()&&u(a,c,o);break}let h=t.decode(f,{stream:!0});a+=h;let g=a.split(`
202
202
  `);a=g.pop()||"";for(let m of g)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 wn,aa=w(()=>{"use strict";wn=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 Pn,ca=w(()=>{"use strict";Pn=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function la(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(c=>{c.type==="text"?i.push({type:"text",text:c.text||""}):c.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:c.media_type||"image/jpeg",data:c.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function ua(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function da(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,c)=>{if(i.startsWith("data: ")){let l=i.slice(6).trim();if(l){t?.debug({chunkStr:l},`${e} chunk:`);try{let u=JSON.parse(l);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let 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)}
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 En,la=w(()=>{"use strict";En=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 An,ua=w(()=>{"use strict";An=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function da(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 pa(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 fa(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)}
204
204
 
205
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)}
206
206
 
@@ -213,50 +213,50 @@ Examples:
213
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)}
214
214
 
215
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 pa=w(()=>{"use strict"});async function bd(){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:
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 ma=w(()=>{"use strict"});async function Td(){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
217
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
218
218
  2. Run "gcloud auth application-default login"
219
- 3. Use Google Cloud environment with default service account`)}}var En,fa=w(()=>{"use strict";pa();En=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 bd();return{body:la(e),config:{url:new URL(`/v1/projects/${o}/locations/${r}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${r}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return ua(e)}async transformResponseOut(e){return da(e,this.name,this.logger)}}});var An,ma=w(()=>{"use strict";An=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 On,ga=w(()=>{"use strict";On=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var In,ha=w(()=>{"use strict";In=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Mn,ya=w(()=>{"use strict";Mn=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 _d}from"uuid";var Ln,ba=w(()=>{"use strict";V();Ln=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 D(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
220
- `);for(let _ of y)_.trim()&&g.enqueue(m.encode(_+`
221
- `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let _=h.slice(6);try{let b=JSON.parse(_);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:i},"usage"),b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
219
+ 3. Use Google Cloud environment with default service account`)}}var On,ga=w(()=>{"use strict";ma();On=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 Td();return{body:da(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 pa(e)}async transformResponseOut(e){return fa(e,this.name,this.logger)}}});var In,ha=w(()=>{"use strict";In=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 Mn,ya=w(()=>{"use strict";Mn=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Ln,_a=w(()=>{"use strict";Ln=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Nn,ba=w(()=>{"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 vd}from"uuid";var $n,ka=w(()=>{"use strict";Q();$n=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 D(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
220
+ `);for(let b of y)b.trim()&&g.enqueue(m.encode(b+`
221
+ `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]"){let b=h.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"&&m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
222
222
 
223
- `)),b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){g.appendReasoningContent(b.choices[0].delta.reasoning);let T={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(T)}
223
+ `)),_.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){g.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
224
 
225
- `;m.enqueue(y.encode(x));return}if(b.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let x={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(x)}
225
+ `;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let x={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(x)}
226
226
 
227
- `;m.enqueue(y.encode(v))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${_d()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),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 k=`data: ${JSON.stringify(b)}
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_${vd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),_.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let k=`data: ${JSON.stringify(_)}
228
228
 
229
229
  `;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(h+`
230
230
  `))}}else m.enqueue(y.encode(h+`
231
- `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(m.length===0)continue;if(c+=m,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=c.split(`
232
- `);c=_.pop()||"";for(let b of _)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",b,k),u.enqueue(o.encode(b+`
231
+ `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(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
233
  `))}continue}let y=c.split(`
234
- `);c=y.pop()||"";for(let _ of y)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),u.enqueue(o.encode(_+`
235
- `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var ir,kd,$n,_a=w(()=>{"use strict";V();ir=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
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(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var lr,xd,Fn,Ta=w(()=>{"use strict";Q();lr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
236
236
 
237
237
  Output format:
238
238
  <reasoning_content>
239
239
  Your detailed thinking process goes here
240
240
  </reasoning_content>
241
- Your final answer must follow after the closing tag above.`,kd=10,$n=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<kd)&&(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:ir}):o.content=[{type:"text",text:ir},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:ir}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await D(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="",h=(g,m)=>{if(typeof m!="string"){g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0&&!g.choices[0].delta.content&&(g.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(g)}
241
+ Your final answer must follow after the closing tag above.`,xd=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<xd)&&(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:lr}):o.content=[{type:"text",text:lr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:lr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await D(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="",h=(g,m)=>{if(typeof m!="string"){g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0&&!g.choices[0].delta.content&&(g.choices[0].index=r,c.enqueue(a.encode(`data: ${JSON.stringify(g)}
243
243
 
244
- `)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let _=y.indexOf(t);if(_!==-1)y=y.substring(_+t.length),p="REASONING";else{for(let b=t.length-1;b>0;b--)if(y.endsWith(t.substring(0,b))){d=y.substring(y.length-b);break}y=""}}else if(p==="REASONING"){let _=y.indexOf(o);if(_!==-1){let b=y.substring(0,_);if(b.length>0){let x={...g.choices[0].delta,thinking:{content:b}};delete x.content;let v={...g,choices:[{...g.choices[0],delta:x,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
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 x={...g.choices[0].delta,thinking:{content:_}};delete x.content;let v={...g,choices:[{...g.choices[0],delta:x,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(v)}
245
245
 
246
246
  `))}let k={...g.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let T={...g,choices:[{...g.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
247
247
 
248
- `)),r++,y=y.substring(_+o.length),p="FINAL"}else{let b=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),b=y.substring(0,y.length-k);break}if(b.length>0){let k={...g.choices[0].delta,thinking:{content:b}};delete k.content;let T={...g,choices:[{...g.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
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={...g.choices[0].delta,thinking:{content:_}};delete k.content;let T={...g,choices:[{...g.choices[0],delta:k,index:r}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
249
249
 
250
- `))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let b=f+y,k={...g.choices[0].delta,content:b};k.thinking&&delete k.thinking;let T={...g,choices:[{...g.choices[0],delta:k}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
250
+ `))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...g.choices[0].delta,content:_};k.thinking&&delete k.thinking;let T={...g,choices:[{...g.choices[0],delta:k}]};c.enqueue(a.encode(`data: ${JSON.stringify(T)}
251
251
 
252
- `)),f=""}r++,y=""}};try{for(;;){let{done:g,value:m}=await l.read();if(g)break;let y=s.decode(m,{stream:!0});u+=y;let _=u.split(`
253
- `);u=_.pop()||"";for(let b of _)if(b.trim()){if(b.trim()==="data: [DONE]"){c.enqueue(a.encode(b+`
252
+ `)),f=""}r++,y=""}};try{for(;;){let{done:g,value:m}=await l.read();if(g)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(_+`
254
254
 
255
- `));break}if(b.startsWith("data:"))try{let k=JSON.parse(b.slice(5));h(k,k.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(b+`
256
- `))}else c.enqueue(a.encode(b+`
255
+ `));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));h(k,k.choices?.[0]?.delta?.content)}catch{c.enqueue(a.encode(_+`
256
+ `))}else c.enqueue(a.encode(_+`
257
257
  `))}}}catch(g){console.error("Stream error:",g),c.error(g)}finally{try{l.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}if(p==="REASONING"){let m={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};c.enqueue(a.encode(`data: ${JSON.stringify(m)}
258
258
 
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 Nn,ka=w(()=>{"use strict";V();Nn=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+`
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 Un,va=w(()=>{"use strict";Q();Un=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+`
260
260
  `));break}let d=o.decode(p,{stream:!0});a+=d;let f=a.split(`
261
261
  `);a=f.pop()||"";for(let h of f)if(h.trim())if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let g=JSON.parse(h.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){s+=g.choices[0].delta.reasoning_content;let m={...g,choices:[{...g.choices[0],delta:{thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content,c.enqueue(r.encode(`data: ${JSON.stringify(m)}
262
262
 
@@ -266,55 +266,55 @@ ${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return
266
266
 
267
267
  `))}catch{c.enqueue(r.encode(h+`
268
268
  `))}else c.enqueue(r.encode(h+`
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 D(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 Ta}from"uuid";var Fn,va=w(()=>{"use strict";V();De();Fn=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")||Ta()}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 D(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
270
- `);for(let _ of y)_.trim()&&g.enqueue(m.encode(_+`
271
- `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let _=JSON.parse(h.slice(6));if(_.usage&&(_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0]?.error})}
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 D(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 xa}from"uuid";var Dn,Ca=w(()=>{"use strict";Q();je();Dn=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")||xa()}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 D(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,c="",l=new ReadableStream({async start(u){let p=e.body.getReader(),d=(h,g,m)=>{let y=h.split(`
270
+ `);for(let b of y)b.trim()&&g.enqueue(m.encode(b+`
271
+ `))},f=(h,g)=>{let{controller:m,encoder:y}=g;if(h.startsWith("data: ")&&h.trim()!=="data: [DONE]")try{let b=JSON.parse(h.slice(6));if(b.usage&&(b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
272
272
 
273
- `));return}_.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0);let b=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(b){g.appendReasoningContent(b);let C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:b}}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(C)}
273
+ `));return}b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0);let _=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(_){g.appendReasoningContent(_);let S={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:_}}}]};S.choices?.[0]?.delta&&(delete S.choices[0].delta.reasoning,delete S.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(S)}
274
274
 
275
- `));return}if(_.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let C="ccr_think_signature",S=_.choices[0].delta.content,P={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:C}}}]};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)}
275
+ `));return}if(b.choices?.[0]?.delta?.content&&g.reasoningContent()&&!g.isReasoningComplete()){g.setReasoningComplete(!0);let S="ccr_think_signature",C=b.choices[0].delta.content,P={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:g.reasoningContent(),signature:S}}}]};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)}
276
276
 
277
- `));let L={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:S}}]};L.choices?.[0]?.delta&&(delete L.choices[0].delta.reasoning,delete L.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(L)}
277
+ `));let L={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:C}}]};L.choices?.[0]?.delta&&(delete L.choices[0].delta.reasoning,delete L.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(L)}
278
278
 
279
- `));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(C=>{C.id=`call_${Ta()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=_.choices?.[0]?.delta,T=k&&Object.keys(k).length>0,x=_.choices?.[0]?.finish_reason,v=_.usage;(T||x||v)&&m.enqueue(y.encode(`data: ${JSON.stringify(_)}
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(S=>{S.id=`call_${xa()}`}),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
280
 
281
281
  `))}catch{m.enqueue(y.encode(h+`
282
282
  `))}else m.enqueue(y.encode(h+`
283
- `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(_){console.warn("Failed to decode chunk",_);continue}if(m.length===0)continue;if(c+=m,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let _=c.split(`
284
- `);c=_.pop()||"";for(let b of _)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",b,k),u.enqueue(o.encode(b+`
283
+ `))};try{for(;;){let{done:h,value:g}=await p.read();if(h){c.trim()&&d(c,u,o);break}if(!g||g.length===0)continue;let m;try{m=t.decode(g,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(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
285
  `))}continue}let y=c.split(`
286
- `);c=y.pop()||"";for(let _ of y)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",_,b),u.enqueue(o.encode(_+`
287
- `))}}}catch(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function vd(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 xd(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 Td,Un,xa=w(()=>{"use strict";Ge();Td={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Un=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=vd(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=xd(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=Td[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 Sa(n,e=!1){if(!n||typeof n!="object"||n.thinking)return!1;let t=n.reasoning,o=typeof t=="string"?t:t?.content;return typeof o=="string"&&o.length>0?(e&&typeof t=="object"?n.thinking={content:o}:(n.thinking=typeof t=="string"?{content:o}:{...t},delete n.reasoning),!0):typeof n.reasoning_content=="string"&&n.reasoning_content?(n.thinking={content:n.reasoning_content},!0):!1}var Dn,Ca=w(()=>{"use strict";Ge();V();Dn=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),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 D(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)Sa(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 h of f)Sa(h?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:l},a=(l,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,h="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)h+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(h+=s(r),r=""),h&&l.enqueue(o.encode(h))},i=e.body.pipeThrough(new TransformStream({transform(l,u){r+=t.decode(l,{stream:!0}),a(u)},flush(l){r+=t.decode(),a(l,!0)}})),c=new Headers(e.headers);return c.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:c})}}});var Ra,wa=w(()=>{Qi();Yi();Xi();Zi();qi();ea();ta();na();oa();sa();ia();aa();ca();fa();ma();ga();ha();ya();ba();Wo();_a();ka();va();xa();Ca();Ra={AnthropicTransformer:fn,GeminiTransformer:yn,VertexGeminiTransformer:bn,VertexClaudeTransformer:En,DeepseekTransformer:_n,TooluseTransformer:kn,OpenrouterTransformer:Tn,OpenAITransformer:In,MaxTokenTransformer:vn,GroqTransformer:xn,CleancacheTransformer:Sn,EnhanceToolTransformer:Cn,ReasoningTransformer:Rn,SamplingTransformer:wn,MaxCompletionTokens:Pn,CerebrasTransformer:An,StreamOptionsTransformer:On,CustomParamsTransformer:Mn,VercelTransformer:Ln,OpenAIResponsesTransformer:Ne,ForceReasoningTransformer:$n,KimiTransformer:Nn,OpenCodeTransformer:Fn,DefaultThinkingTransformer:Un,AmdTransformer:Dn}});var Qe,ar=w(()=>{"use strict";wa();Qe=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;preparePluginTransformer(e){if(typeof e.TransformerName=="string")return e;let t=new e;if(!t?.name)throw new Error("plugin transformer has no name");return t.logger=this.logger,t}registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=ot(ot.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
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(h){console.error("Stream error:",h),u.error(h)}finally{try{p.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}u.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function Sd(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim();if(!e)return;let t=e.toLowerCase();return["none","low","medium","high","max"].includes(t)?t:/^\d+$/.test(e)?parseInt(e,10):e}function Rd(n){let e="";try{e=new URL(String(n||"")).pathname.replace(/\/+$/,"")}catch{return"chat"}return e.endsWith("/messages")?"anthropic":e.endsWith("/responses")?"responses":"chat"}var Cd,jn,Sa=w(()=>{"use strict";Ve();Cd={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};jn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=Sd(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Rd(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=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=Cd[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 Ra(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 Hn,wa=w(()=>{"use strict";Ve();Q();Hn=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 D(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)Ra(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 h of f)Ra(h?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:l},a=(l,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,h="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)h+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(h+=s(r),r=""),h&&l.enqueue(o.encode(h))},i=e.body.pipeThrough(new TransformStream({transform(l,u){r+=t.decode(l,{stream:!0}),a(u)},flush(l){r+=t.decode(),a(l,!0)}})),c=new Headers(e.headers);return c.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:c})}}});var Pa,Ea=w(()=>{Xi();Zi();qi();ea();ta();na();oa();ra();sa();aa();ca();la();ua();ga();ha();ya();_a();ba();ka();Go();Ta();va();Ca();Sa();wa();Pa={AnthropicTransformer:gn,GeminiTransformer:bn,VertexGeminiTransformer:kn,VertexClaudeTransformer:On,DeepseekTransformer:Tn,TooluseTransformer:vn,OpenrouterTransformer:xn,OpenAITransformer:Ln,MaxTokenTransformer:Cn,GroqTransformer:Sn,CleancacheTransformer:Rn,EnhanceToolTransformer:wn,ReasoningTransformer:Pn,SamplingTransformer:En,MaxCompletionTokens:An,CerebrasTransformer:In,StreamOptionsTransformer:Mn,CustomParamsTransformer:Nn,VercelTransformer:$n,OpenAIResponsesTransformer:Fe,ForceReasoningTransformer:Fn,KimiTransformer:Un,OpenCodeTransformer:Dn,DefaultThinkingTransformer:jn,AmdTransformer:Hn}});var Ye,ur=w(()=>{"use strict";Ea();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=rt(rt.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
288
  error: ${t.message}
289
289
  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(Ra).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 Sd}from"tiktoken";var yt,Pa=w(()=>{"use strict";yt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Sd(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 jn}from"path";import{homedir as Cd}from"os";import{existsSync as cr,mkdirSync as Rd}from"fs";import{promises as Hn}from"fs";import{Tokenizer as wd}from"@huggingface/tokenizers";var zn,Ea=w(()=>{"use strict";zn=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(Cd(),".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){cr(e)||Rd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!cr(e.tokenizerJson)||!cr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Hn.readFile(e.tokenizerJson,"utf-8"),Hn.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([Hn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Hn.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 wd(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 Bn,Aa=w(()=>{"use strict";q();Bn=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=K(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 Ye,lr=w(()=>{"use strict";Pa();Ea();Aa();q();Ye=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new yt("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new yt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new zn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Bn(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 Oa(n){if(!n||typeof n!="object"||Ld(n))return null;for(let t of Md(n)){let o=Id(t);if(o)return o}return null}function Id(n){if(!n||typeof n!="object")return null;let e={},t=Jn(n,Pd);if(t!==void 0){let a=Ia(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Jn(n,Ed);if(o!==void 0){let a=Ia(o);e.usedBalance=a,e.totalBalance=100}let r=Jn(n,Ad);if(r!==void 0){let a=Ma(r);a&&(e.resetTime=a)}let s=Jn(n,Od);if(s!==void 0){let a=Ma(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 Ia(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Jn(n,e){for(let t of e){let o=F(n?.[t]);if(o!==void 0)return o}}function Md(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 Ld(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 Ma(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 Tr(n){let e=vr(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")?Bd:e==="deepseek.com"||e.endsWith(".deepseek.com")?$d:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Nd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Fd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Ud:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Dd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?jd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Hd:null:null}function Jd(n){let e=vr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Wd(n,e){let t=_r(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function _r(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>_r(e)):Object.values(n).flatMap(e=>_r(e))}function kr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function vr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function F(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var ie,ur,dr,pr,fr,mr,Pd,Ed,Ad,Od,gr,hr,yr,br,$d,Nd,Fd,Ud,Dd,jd,Hd,zd,Bd,xr=w(()=>{"use strict";q();ie=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=K(r));let c=await fetch(e,i);return c.ok?await c.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},ur=class extends ie{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>F(c?.total_balance)!==void 0);if(!a)return null;let i=F(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},dr=class extends ie{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=F(s.limit),c=F(s.limit_remaining),l=F(s.usage),u=F(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},pr=class extends ie{async queryQuota(e,t,o){let r=Jd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=F(a.totalBalance),l=F(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}},fr=class extends ie{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let 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=F(l.currentValue),h=F(l.usage),g=F(l.remaining),m=F(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),h!==void 0?d.limitDaily=h:f!==void 0&&g!==void 0&&(d.limitDaily=f+g),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=F(u.currentValue),h=F(u.usage),g=F(u.remaining),m=F(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),h!==void 0?d.totalBalance=h:f!==void 0&&g!==void 0&&(d.totalBalance=f+g),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=F(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=F(p.usage),h=F(p.currentValue),g=F(p.remaining);f!==void 0?d.limitDaily=f:h!==void 0&&g!==void 0&&(d.limitDaily=h+g)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},mr=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","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=K(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=F(u.per5HourUsedQuota),f=F(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let h=F(u.perWeekUsedQuota),g=F(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),g!==void 0&&(p.totalBalance=g),this.hasQuotaData(p)?p:null}catch{return null}}};Pd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Ed=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Ad=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Od=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];gr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=kr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=K(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,l);if(!u.ok)return null;let p=await u.json();return Oa(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=K(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 Oa(l)}catch{return null}}},hr=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(kr(e.quotaToken,"atp-auth-token")||kr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(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=Wd(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=F(l.rp5hUsage),d=F(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=F(l.rpwUsage),h=F(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,h-f)),this.hasQuotaData(u)?u:null}catch{return null}}},yr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(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=F(p.limit),f=F(p.remaining),h=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),h&&(c.resetTime=new Date(h).toISOString())}let u=i?.usage;if(u){let p=F(u.limit),d=F(u.remaining),f=F(u.used),h=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)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},br=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=vr(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=F(u.current_interval_total_count),f=F(u.current_interval_usage_count),h=F(u.current_interval_remaining_percent),g=F(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),g&&(p.resetTime=new Date(g).toISOString());let m=F(u.current_weekly_total_count),y=F(u.current_weekly_usage_count),_=F(u.current_weekly_remaining_percent),b=F(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):_!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-_),p.remainingBalance=_),b&&!p.resetTime&&(p.resetTime=new Date(b).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},$d=new ur,Nd=new dr,Fd=new pr,Ud=new fr,Dd=new mr,jd=new gr,Hd=new hr,zd=new yr,Bd=new br});function La(n){return{[Kd]:n,[Gd]:Qt}}function Re(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function Qd(n){return n===!0||n==="true"||n===1||n==="1"}function Yd(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 Xd(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 Zd(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Sr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Re(n))return{success:!1,skipped:!0,error:Cr,latencyMs:r()};let s=Xd(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=K(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 qd(n,e,t,o){if(Re(n))return{success:!1,skipped:!0,error:Cr};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",...La("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=K(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 ep(n,e,t,o,r){if(Re(n))return{success:!1,skipped:!0,error:Cr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...La("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=K(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 $a(n,e,t,o,r,s){return be||(be=new Wn(n,e,t,o,r,s)),be}function bt(n,e,t,o,r,s){let a=$a(n,e,t,o,r,s);return a.start(),a}function Rr(){be&&be.stop()}function wr(){be&&(be.stop(),be=null)}var Kd,Gd,Vd,Cr,Wn,be,Kn=w(()=>{"use strict";se();$e();xr();Ue();Eo();q();Kd="x-claude-code-router-source",Gd="x-claude-code-router-version";Vd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Cr="Managed provider requires its plugin's authenticated model sync";Wn=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={...Vd,...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&&!Re(s)&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let a=Tr(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){Qo(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`))}}})}),Zd(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Sr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=j(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Re(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Sr(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=j();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=j(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&Re(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 ep(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&&!Re(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=Yd(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,h=(p*60+d)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(f||g)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),qd(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?Qd(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 Sr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)j().recordSuccess(o.name,i);else for(let i of a)j().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},be=null});var Na=w(()=>{"use strict"});var Pr,_t,Fa=w(()=>{"use strict";Pr=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},_t=new Pr});var ae,Er=w(()=>{"use strict";ae=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 Xe,Ar=w(()=>{"use strict";Xe=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
290
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Pa).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 wd}from"tiktoken";var _t,Aa=w(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=wd(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 zn}from"path";import{homedir as Pd}from"os";import{existsSync as dr,mkdirSync as Ed}from"fs";import{promises as Bn}from"fs";import{Tokenizer as Ad}from"@huggingface/tokenizers";var Jn,Oa=w(()=>{"use strict";Jn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||zn(Pd(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=zn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:zn(e,"tokenizer.json"),tokenizerConfig:zn(e,"tokenizer_config.json")}}ensureDir(e){dr(e)||Ed(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!dr(e.tokenizerJson)||!dr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Bn.readFile(e.tokenizerJson,"utf-8"),Bn.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([Bn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Bn.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 Ad(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 Wn,Ia=w(()=>{"use strict";q();Wn=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=K(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,pr=w(()=>{"use strict";Aa();Oa();Ia();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 Jn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Wn(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 Ma(n){if(!n||typeof n!="object"||Fd(n))return null;for(let t of $d(n)){let o=Nd(t);if(o)return o}return null}function Nd(n){if(!n||typeof n!="object")return null;let e={},t=Kn(n,Od);if(t!==void 0){let a=La(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Kn(n,Id);if(o!==void 0){let a=La(o);e.usedBalance=a,e.totalBalance=100}let r=Kn(n,Md);if(r!==void 0){let a=Na(r);a&&(e.resetTime=a)}let s=Kn(n,Ld);if(s!==void 0){let a=Na(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 La(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Kn(n,e){for(let t of e){let o=F(n?.[t]);if(o!==void 0)return o}}function $d(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 Fd(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 Na(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 Cr(n){let e=Sr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Wd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Kd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Ud:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Dd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?jd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Hd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?zd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Bd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Jd:null:null}function Gd(n){let e=Sr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Vd(n,e){let t=vr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(c=>c.includes(i)||i.includes(c))})||t[0]}function vr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>vr(e)):Object.values(n).flatMap(e=>vr(e))}function xr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Sr(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function F(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var ie,fr,mr,gr,hr,yr,Od,Id,Md,Ld,_r,br,kr,Tr,Ud,Dd,jd,Hd,zd,Bd,Jd,Wd,Kd,Rr=w(()=>{"use strict";q();ie=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=K(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}},fr=class extends ie{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>F(c?.total_balance)!==void 0);if(!a)return null;let i=F(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},mr=class extends ie{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=F(s.limit),c=F(s.limit_remaining),l=F(s.usage),u=F(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}},gr=class extends ie{async queryQuota(e,t,o){let r=Gd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=F(a.totalBalance),l=F(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}},hr=class extends ie{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let 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=F(l.currentValue),h=F(l.usage),g=F(l.remaining),m=F(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),h!==void 0?d.limitDaily=h:f!==void 0&&g!==void 0&&(d.limitDaily=f+g),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=F(u.currentValue),h=F(u.usage),g=F(u.remaining),m=F(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),h!==void 0?d.totalBalance=h:f!==void 0&&g!==void 0&&(d.totalBalance=f+g),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=F(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=F(p.usage),h=F(p.currentValue),g=F(p.remaining);f!==void 0?d.limitDaily=f:h!==void 0&&g!==void 0&&(d.limitDaily=h+g)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},yr=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","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=K(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=F(u.per5HourUsedQuota),f=F(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let h=F(u.perWeekUsedQuota),g=F(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),g!==void 0&&(p.totalBalance=g),this.hasQuotaData(p)?p:null}catch{return null}}};Od=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Id=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Md=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Ld=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];_r=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=xr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=K(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,l);if(!u.ok)return null;let p=await u.json();return Ma(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=K(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 Ma(l)}catch{return null}}},br=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(xr(e.quotaToken,"atp-auth-token")||xr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let c=Vd(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=F(l.rp5hUsage),d=F(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=F(l.rpwUsage),h=F(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,h-f)),this.hasQuotaData(u)?u:null}catch{return null}}},kr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=K(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=F(p.limit),f=F(p.remaining),h=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),h&&(c.resetTime=new Date(h).toISOString())}let u=i?.usage;if(u){let p=F(u.limit),d=F(u.remaining),f=F(u.used),h=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)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},Tr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Sr(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=F(u.current_interval_total_count),f=F(u.current_interval_usage_count),h=F(u.current_interval_remaining_percent),g=F(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),g&&(p.resetTime=new Date(g).toISOString());let m=F(u.current_weekly_total_count),y=F(u.current_weekly_usage_count),b=F(u.current_weekly_remaining_percent),_=F(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}}},Ud=new fr,Dd=new mr,jd=new gr,Hd=new hr,zd=new yr,Bd=new _r,Jd=new br,Wd=new kr,Kd=new Tr});function $a(n){return{[Qd]:n,[Yd]:Qt}}function Pe(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function Zd(n){return n===!0||n==="true"||n===1||n==="1"}function qd(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 ep(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 tp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function wr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Pe(n))return{success:!1,skipped:!0,error:Pr,latencyMs:r()};let s=ep(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=K(t));let i=await fetch(s,a);if(i.headers&&at(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 np(n,e,t,o){if(Pe(n))return{success:!1,skipped:!0,error:Pr};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",...$a("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=K(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 op(n,e,t,o,r){if(Pe(n))return{success:!1,skipped:!0,error:Pr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...$a("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=K(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 Fa(n,e,t,o,r,s){return _e||(_e=new Gn(n,e,t,o,r,s)),_e}function bt(n,e,t,o,r,s){let a=Fa(n,e,t,o,r,s);return a.start(),a}function Er(){_e&&_e.stop()}function Ar(){_e&&(_e.stop(),_e=null)}var Qd,Yd,Xd,Pr,Gn,_e,Vn=w(()=>{"use strict";se();$e();Rr();De();Oo();q();Qd="x-claude-code-router-source",Yd="x-claude-code-router-version";Xd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Pr="Managed provider requires its plugin's authenticated model sync";Gn=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={...Xd,...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&&!Pe(s)&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let a=Cr(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){Xo(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`))}}})}),tp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:wr(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=j(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Pe(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=>wr(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=j();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=j(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&Pe(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 op(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&&!Pe(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=qd(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,h=(p*60+d)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(f||g)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),np(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?Zd(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 wr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)j().recordSuccess(o.name,i);else for(let i of a)j().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},_e=null});var Ua=w(()=>{"use strict"});var Or,kt,Da=w(()=>{"use strict";Or=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 Or});var ae,Ir=w(()=>{"use strict";ae=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,Mr=w(()=>{"use strict";Ze=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
293
293
  `),e.id&&(o+=`id: ${e.id}
294
294
  `),e.retry&&(o+=`retry: ${e.retry}
295
295
  `),e.data&&(e.data.type==="done"?o+=`data: [DONE]
296
296
  `:o+=`data: ${JSON.stringify(e.data)}
297
297
  `),o+=`
298
- `,t.enqueue(o)}})}}});var Gn,Or=w(()=>{"use strict";Gn=(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 Ir=w(()=>{"use strict";Er();Ar();Or()});var Ua=w(()=>{"use strict"});var kt,Mr=w(()=>{"use strict";kt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata: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+=`
298
+ `,t.enqueue(o)}})}}});var Qn,Lr=w(()=>{"use strict";Qn=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var Nr=w(()=>{"use strict";Ir();Mr();Lr()});var ja=w(()=>{"use strict"});var Tt,$r=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 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+=`
299
299
  `+(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
300
  ${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
301
301
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
302
302
  ${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 Tt,Lr=w(()=>{"use strict";Tt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let 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 np,unlink as op}from"node:fs/promises";import{join as ja,resolve as Fr}from"node:path";import{tmpdir as rp}from"node:os";async function Yn(n,e){let t=Fr(n),o=Vn.get(t),r,s=new Promise(a=>{r=a});Vn.set(t,s);try{return await o,await e()}finally{r(),Vn.get(t)===s&&Vn.delete(t)}}function Ha(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Da(n,e){try{let t=await Qn(n);return t.isDirectory()&&!t.isSymbolicLink()&&Ha(e,t)}catch{return!1}}function lp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function za(n,e,t,o){let r=Fr(n);if(o?.aborted||$r.has(r))return 0;$r.add(r);let s=0;try{let a=await Qn(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await np(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=ja(r,u.name);try{let d=await Qn(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await Yn(p,async()=>{if(o?.aborted||!await Da(r,a))return!1;let h=await Qn(p);return!h.isFile()||h.isSymbolicLink()||!Ha(d,h)||h.mtimeMs!==d.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await op(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await lp(),l=!o?.aborted&&await Da(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{$r.delete(r)}return s}function Ba(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=>cp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function up(n,e){let t=Date.now()-sp;return za(n,t,o=>{let r=ap.exec(o);return r!==null&&Number(r[1])<t},e)}function Ur(n,e,t){let o=Nr.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,ip),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},Nr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Nr.delete(n)))}}function Ja(n=ja(rp(),"claude-code-router")){return Ur(`legacy:${Fr(n)}`,e=>up(n,e),1e3)}var sp,ip,ap,cp,$r,Vn,Nr,Dr=w(()=>{"use strict";sp=3600*1e3,ip=600*1e3,ap=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,cp=/^\.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$/,$r=new Set,Vn=new Map,Nr=new Map});import{lstat as dp,mkdir as pp,open as fp,rename as mp,unlink as gp}from"node:fs/promises";import{randomUUID as hp}from"node:crypto";import{sanitizeTempFileKey as yp}from"@wengine-ai/claude-code-router-shared";import{basename as bp,join as jr,resolve as _p}from"node:path";import{tmpdir as kp}from"node:os";var vt,Hr=w(()=>{"use strict";Dr();vt=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=_p(jr(kp(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=Ur(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await pp(this.baseDir,{recursive:!0});let e=await dp(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}-${yp(e)}${r}${o}`;if(bp(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return jr(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 Yn(a,async()=>{await this.ensureDir();let i=jr(this.baseDir,`.ccr-tmp-${process.pid}-${hp()}.tmp`);return Yn(i,async()=>{let c=!1;try{let l=await fp(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await mp(i,a),!0}finally{c&&await gp(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return Ba(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var zr,Ze,Wa=w(()=>{"use strict";Mr();Lr();Hr();zr=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new kt(e.config);case"webhook":return new Tt(e.config);case"temp-file":return new vt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([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)}},Ze=new zr});var Br=w(()=>{"use strict";Ua();Mr();Lr();Hr();Wa()});import Tp from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as vp}from"@wengine-ai/claude-code-router-shared";function Xn(){return{subdirectory:vp,extension:"json",includeTimestamp:!1,prefix:"session"}}function Ka(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,xp);return Math.round(n/o)}function St(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Ga(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await Ze.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var xt,Jr,xp,Zn,Va=w(()=>{"use strict";Ir();Br();De();xt=new Map,Jr=new Map,xp=1,Zn={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:Tp(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)Ze.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:Xn()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&Ze.registerHandlers(a)}t.outputOptions&&Ze.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,l=a.model,u=`${c}:${l}`;if(Jr.has(u))return Jr.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 Jr.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){xt.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,_]=c.tee(),b=async()=>{let k=null,T=async x=>{let v=xt.get(u);if(!v)return;let C=v.firstTokenTime?v.firstTokenTime-v.startTime:0,P=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Ka(v.tokenCount,P,C),await Ga(v,o,t.outputOptions,x).catch(L=>{n.log?.warn(`Failed to output streaming stats: ${L.message}`)})};try{let v=_.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();for(k=setInterval(async()=>{xt.get(u)&&await T(!1)},1e3);;){let{done:C,value:S}=await v.read();if(C)break;let P=S,L=xt.get(u);if(!L)continue;let $=performance.now(),A=P.event||P.data?.type,U=P.event==="content_block_start"||P.event==="content_block_delta"||P.event==="text_block"||P.event==="content_block"||A==="response.output_text.delta"||A==="response.function_call_arguments.delta"||A==="response.reasoning_summary_text.delta";!L.firstTokenTime&&U&&(L.firstTokenTime=$,L.timeToFirstToken=Math.round($-L.startTime));let R="";if(P.event==="content_block_delta"&&P.data?.delta){let E=P.data.delta.type;E==="text_delta"?R=P.data.delta.text||"":E==="input_json_delta"?R=P.data.delta.partial_json||"":E==="thinking_delta"&&(R=P.data.delta.thinking||"")}if((A==="response.output_text.delta"||A==="response.function_call_arguments.delta"||A==="response.reasoning_summary_text.delta")&&(R=typeof P.data?.delta=="string"?P.data.delta:""),R){let E=f&&f.encodeText?f.encodeText(R).length:St(R);L.tokenCount+=E,L.lastTokenTime=$}(P.event==="message_stop"||A==="response.completed"||A==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),xt.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=b().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let h=performance.now(),g=0,m=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")g=y.usage.output_tokens,m=!0;else{let _=y.content??y.message?.content;if(_!==void 0)if(m=!0,f)Array.isArray(_)?g=_.reduce((b,k)=>{if(k.type==="text"){let T=k.text||"";return b+(f.encodeText?f.encodeText(T).length:St(T))}return b},0):typeof _=="string"&&(g=f.encodeText?f.encodeText(_).length:St(_));else{let b=Array.isArray(_)?_.map(k=>k.text).join(""):typeof _=="string"?_:"";g=St(b)}}}catch{}if(m){let y=h-l,_={requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:h,tokenCount:g,tokensPerSecond:Ka(g,y),stream:!1};await Ga(_,o,t.outputOptions,!0)}return c})})}});var Wr=w(()=>{"use strict";Na();Fa();Va();Br()});import ne from"node:fs/promises";import Qa from"json5";import we from"node:path";import{CONFIG_FILE as oe,HOME_DIR as qn,PLUGINS_DIR as Sp}from"@wengine-ai/claude-code-router-shared";function Ya(){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 Kr,Ct,eo,Rt,Y,to,ue,Cp,Gr,wt=w(()=>{"use strict";Kr=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(Kr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Kr(o);return e}return n},Ct=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},eo=async()=>{await Ct(qn),await Ct(Sp),await Ct(we.join(qn,"logs"))},Rt=async()=>{let n=await ne.readFile(oe,"utf-8");return Qa.parse(n)},Y=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=Qa.parse(n);return Kr(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 eo();let e=await to();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)}};to=async()=>{Ya();try{if(await ne.access(oe).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${oe}.${n}.bak`;await ne.copyFile(oe,e);try{let t=we.dirname(oe),o=we.basename(oe),s=(await ne.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=we.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=>{Ya(),await Ct(qn),await Cp();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},Cp=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=we.join(qn,"config-history");await Ct(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=we.join(e,`config-${t}.json`);await ne.copyFile(oe,o);try{let s=(await ne.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ne.unlink(we.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},Gr=async()=>{let n=await Y();return Object.assign(process.env,n),n}});function Rp(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function wp(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Pe(n){if(!(!n||typeof n!="object"))return{...n,input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:Rp(n),cache_creation_input_tokens:wp(n)}}function Pt(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var Vr=w(()=>{"use strict"});function no(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(Qr(r,s))}return}if(Array.isArray(n)){for(let o of n)no(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))no(o,e,t)}}function Xa(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(Qr(s,i))}return no(n?.Router,t,o),no(n?.fallback,t,o),o}function Et(n,e){try{let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=Xa(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(Qr(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 oo(n,e){try{if(!n)return 0;let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var Pp,Qr,At=w(()=>{"use strict";se();Pp="\0",Qr=(n,e)=>`${n}${Pp}${e}`});function Ep(n){return/\[1m\]/i.test(n)?1e6:2e5}function Ap(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Op(n,e=n){let t=Ep(n),o=Ap(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 Ip(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Yr(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Op(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=Ip(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var Xr=w(()=>{"use strict"});function Mp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var ro,Zr=w(()=>{"use strict";ro=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Mp(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 ac={};ho(ac,{append:()=>$t,clear:()=>ns,close:()=>tf,getOldestRecordTimestamp:()=>nf,query:()=>ts,querySummary:()=>Nt,readTokenSpeedStats:()=>os});import{existsSync as ec,mkdirSync as Lp,readFileSync as tc}from"fs";import{join as ao}from"path";import{tmpdir as $p}from"os";import{openSqliteDatabase as Np}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Fp,sanitizeTempFileKey as Up,TOKEN_SPEED_TEMP_SUBDIRECTORY as Dp}from"@wengine-ai/claude-code-router-shared";function Jp(){ec(io)||Lp(io,{recursive:!0})}function Lt(){if(ke)return ke;Jp();let n=Np(jp),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&&(Wp(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")),Gp(e),rc(e,!0),es=e.prepare(`
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,Fr=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 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 Xn,opendir as sp,unlink as ip}from"node:fs/promises";import{join as za,resolve as jr}from"node:path";import{tmpdir as ap}from"node:os";async function Zn(n,e){let t=jr(n),o=Yn.get(t),r,s=new Promise(a=>{r=a});Yn.set(t,s);try{return await o,await e()}finally{r(),Yn.get(t)===s&&Yn.delete(t)}}function Ba(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Ha(n,e){try{let t=await Xn(n);return t.isDirectory()&&!t.isSymbolicLink()&&Ba(e,t)}catch{return!1}}function pp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Ja(n,e,t,o){let r=jr(n);if(o?.aborted||Ur.has(r))return 0;Ur.add(r);let s=0;try{let a=await Xn(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await sp(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=za(r,u.name);try{let d=await Xn(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await Zn(p,async()=>{if(o?.aborted||!await Ha(r,a))return!1;let h=await Xn(p);return!h.isFile()||h.isSymbolicLink()||!Ba(d,h)||h.mtimeMs!==d.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await ip(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await pp(),l=!o?.aborted&&await Ha(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Ur.delete(r)}return s}function Wa(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Ja(n,Date.now()-o,i=>dp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function fp(n,e){let t=Date.now()-cp;return Ja(n,t,o=>{let r=up.exec(o);return r!==null&&Number(r[1])<t},e)}function Hr(n,e,t){let o=Dr.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,lp),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},Dr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Dr.delete(n)))}}function Ka(n=za(ap(),"claude-code-router")){return Hr(`legacy:${jr(n)}`,e=>fp(n,e),1e3)}var cp,lp,up,dp,Ur,Yn,Dr,zr=w(()=>{"use strict";cp=3600*1e3,lp=600*1e3,up=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,dp=/^\.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$/,Ur=new Set,Yn=new Map,Dr=new Map});import{lstat as mp,mkdir as gp,open as hp,rename as yp,unlink as _p}from"node:fs/promises";import{randomUUID as bp}from"node:crypto";import{sanitizeTempFileKey as kp}from"@wengine-ai/claude-code-router-shared";import{basename as Tp,join as Br,resolve as vp}from"node:path";import{tmpdir as xp}from"node:os";var xt,Jr=w(()=>{"use strict";zr();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=vp(Br(xp(),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=Hr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await gp(this.baseDir,{recursive:!0});let e=await mp(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}-${kp(e)}${r}${o}`;if(Tp(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Br(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 Zn(a,async()=>{await this.ensureDir();let i=Br(this.baseDir,`.ccr-tmp-${process.pid}-${bp()}.tmp`);return Zn(i,async()=>{let c=!1;try{let l=await hp(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await yp(i,a),!0}finally{c&&await _p(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return Wa(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Wr,qe,Ga=w(()=>{"use strict";$r();Fr();Jr();Wr=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new 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 Wr});var Kr=w(()=>{"use strict";ja();$r();Fr();Jr();Ga()});import Cp from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Sp}from"@wengine-ai/claude-code-router-shared";function qn(){return{subdirectory:Sp,extension:"json",includeTimestamp:!1,prefix:"session"}}function Va(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Rp);return Math.round(n/o)}function St(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Qa(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 Ct,Gr,Rp,eo,Ya=w(()=>{"use strict";Nr();Kr();je();Ct=new Map,Gr=new Map,Rp=1,eo={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:Cp(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:qn()}):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(Gr.has(u))return Gr.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 Gr.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){Ct.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 x=>{let v=Ct.get(u);if(!v)return;let S=v.firstTokenTime?v.firstTokenTime-v.startTime:0,P=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Va(v.tokenCount,P,S),await Qa(v,o,t.outputOptions,x).catch(L=>{n.log?.warn(`Failed to output streaming stats: ${L.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();for(k=setInterval(async()=>{Ct.get(u)&&await T(!1)},1e3);;){let{done:S,value:C}=await v.read();if(S)break;let P=C,L=Ct.get(u);if(!L)continue;let N=performance.now(),A=P.event||P.data?.type,U=P.event==="content_block_start"||P.event==="content_block_delta"||P.event==="text_block"||P.event==="content_block"||A==="response.output_text.delta"||A==="response.function_call_arguments.delta"||A==="response.reasoning_summary_text.delta";!L.firstTokenTime&&U&&(L.firstTokenTime=N,L.timeToFirstToken=Math.round(N-L.startTime));let R="";if(P.event==="content_block_delta"&&P.data?.delta){let E=P.data.delta.type;E==="text_delta"?R=P.data.delta.text||"":E==="input_json_delta"?R=P.data.delta.partial_json||"":E==="thinking_delta"&&(R=P.data.delta.thinking||"")}if((A==="response.output_text.delta"||A==="response.function_call_arguments.delta"||A==="response.reasoning_summary_text.delta")&&(R=typeof P.data?.delta=="string"?P.data.delta:""),R){let E=f&&f.encodeText?f.encodeText(R).length:St(R);L.tokenCount+=E,L.lastTokenTime=N}(P.event==="message_stop"||A==="response.completed"||A==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),Ct.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 h=performance.now(),g=0,m=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")g=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?g=b.reduce((_,k)=>{if(k.type==="text"){let T=k.text||"";return _+(f.encodeText?f.encodeText(T).length:St(T))}return _},0):typeof b=="string"&&(g=f.encodeText?f.encodeText(b).length:St(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";g=St(_)}}}catch{}if(m){let y=h-l,b={requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:h,tokenCount:g,tokensPerSecond:Va(g,y),stream:!1};await Qa(b,o,t.outputOptions,!0)}return c})})}});var Vr=w(()=>{"use strict";Ua();Da();Ya();Kr()});import ne from"node:fs/promises";import Xa from"json5";import Ee from"node:path";import{CONFIG_FILE as oe,HOME_DIR as to,PLUGINS_DIR as wp}from"@wengine-ai/claude-code-router-shared";function Za(){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 Qr,Rt,no,wt,X,oo,ue,Pp,Yr,Pt=w(()=>{"use strict";Qr=n=>{if(typeof n=="string")return n.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,t,o)=>{let r=t||o;return process.env[r]||e});if(Array.isArray(n))return n.map(Qr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Qr(o);return e}return n},Rt=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},no=async()=>{await Rt(to),await Rt(wp),await Rt(Ee.join(to,"logs"))},wt=async()=>{let n=await ne.readFile(oe,"utf-8");return Xa.parse(n)},X=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=Xa.parse(n);return Qr(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 no();let e=await oo();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)}};oo=async()=>{Za();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=Ee.dirname(oe),o=Ee.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=Ee.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=>{Za(),await Rt(to),await Pp();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},Pp=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=Ee.join(to,"config-history");await Rt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ee.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(Ee.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},Yr=async()=>{let n=await X();return Object.assign(process.env,n),n}});function ro(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(Xr(r,s))}return}if(Array.isArray(n)){for(let o of n)ro(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))ro(o,e,t)}}function qa(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(Xr(s,i))}return ro(n?.Router,t,o),ro(n?.fallback,t,o),o}function Et(n,e){try{let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=qa(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(Xr(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 so(n,e){try{if(!n)return 0;let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var Ep,Xr,At=w(()=>{"use strict";se();Ep="\0",Xr=(n,e)=>`${n}${Ep}${e}`});function Ap(n){return/\[1m\]/i.test(n)?1e6:2e5}function Op(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Ip(n,e=n){let t=Ap(n),o=Op(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 Mp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Zr(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Ip(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=Mp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var qr=w(()=>{"use strict"});function Lp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var io,es=w(()=>{"use strict";io=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Lp(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 lc={};_o(lc,{append:()=>Nt,clear:()=>rs,close:()=>nf,getOldestRecordTimestamp:()=>of,query:()=>os,querySummary:()=>$t,readTokenSpeedStats:()=>ss});import{existsSync as nc,mkdirSync as Np,readFileSync as oc}from"fs";import{join as lo}from"path";import{tmpdir as $p}from"os";import{openSqliteDatabase as Fp}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Up,sanitizeTempFileKey as Dp,TOKEN_SPEED_TEMP_SUBDIRECTORY as jp}from"@wengine-ai/claude-code-router-shared";function Wp(){nc(co)||Np(co,{recursive:!0})}function Lt(){if(ke)return ke;Wp();let n=Fp(Hp),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&&(Kp(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")),Vp(e),ic(e,!0),ns=e.prepare(`
304
304
  INSERT INTO usage_records (
305
305
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
306
306
  scenario_type, client_type,
307
- stream, input_tokens, output_tokens, cache_read_input_tokens,
307
+ stream, usage_estimated, input_tokens, output_tokens, cache_read_input_tokens,
308
308
  cache_creation_input_tokens, ttft, tokens_per_second, duration_ms,
309
309
  status, error_message, response_body
310
310
  ) VALUES (
311
311
  @id, @timestamp, @session_id, @provider, @original_model, @model, @upstream_model,
312
312
  @model_family, @scenario_type, @client_type,
313
- @stream, @input_tokens, @output_tokens,
313
+ @stream, @usage_estimated, @input_tokens, @output_tokens,
314
314
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
315
315
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
316
316
  )
317
- `),ke=e,ke}function Wp(n){n.exec(`
317
+ `),ke=e,ke}function Kp(n){n.exec(`
318
318
  CREATE TABLE IF NOT EXISTS usage_records (
319
319
  id TEXT PRIMARY KEY,
320
320
  timestamp TEXT NOT NULL,
@@ -351,32 +351,33 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
351
351
  CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
352
352
  CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
353
353
  CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
354
- `)}function Kp(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
354
+ `)}function Gp(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
355
355
  INSERT INTO usage_meta (key, value)
356
356
  VALUES (?, ?)
357
357
  ON CONFLICT(key) DO UPDATE SET value = excluded.value
358
- `).run(e,t)}function Gp(n){if(Kp(n,Za)||!ec(qr))return;let e=Qp(n,"INSERT OR IGNORE"),t=tc(qr,"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(!Vp(l)){r++;continue}e.run(oc(co(l))).changes>0?o++:s++}catch{r++}}Ot(n,Za,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",qr),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 Vp(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 Qp(n,e="INSERT"){return n.prepare(`
358
+ `).run(e,t)}function Vp(n){if(Gp(n,ec)||!nc(ts))return;let e=Yp(n,"INSERT OR IGNORE"),t=oc(ts,"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(!Qp(l)){r++;continue}e.run(sc(uo(l))).changes>0?o++:s++}catch{r++}}Ot(n,ec,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",ts),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 Qp(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 Yp(n,e="INSERT"){return n.prepare(`
360
360
  ${e} INTO usage_records (
361
361
  id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
362
362
  scenario_type, client_type,
363
- stream, input_tokens, output_tokens, cache_read_input_tokens,
363
+ stream, usage_estimated, input_tokens, output_tokens, cache_read_input_tokens,
364
364
  cache_creation_input_tokens, ttft, tokens_per_second, duration_ms,
365
365
  status, error_message, response_body
366
366
  ) VALUES (
367
367
  @id, @timestamp, @session_id, @provider, @original_model, @model, @upstream_model,
368
368
  @model_family, @scenario_type, @client_type,
369
- @stream, @input_tokens, @output_tokens,
369
+ @stream, @usage_estimated, @input_tokens, @output_tokens,
370
370
  @cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
371
371
  @tokens_per_second, @duration_ms, @status, @error_message, @response_body
372
372
  )
373
- `)}function Yp(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,Hp);return Math.round(n/r)}function co(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:Yp(e,o,r)}}function _e(n){return typeof n=="string"?n:n==null?"":String(n)}function so(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 nc(n){return n==="success"?"success":"error"}function oc(n){let e=co(n);return{id:_e(e.id),timestamp:_e(e.timestamp),session_id:_e(e.sessionId),provider:_e(e.provider),original_model:_e(e.originalModel),model:_e(e.model),upstream_model:so(e.upstreamModel)??null,model_family:_e(e.modelFamily),scenario_type:_e(e.scenarioType),client_type:so(e.clientType)??null,stream:e.stream?1:0,input_tokens:Math.trunc(It(e.inputTokens)),output_tokens:Math.trunc(It(e.outputTokens)),cache_read_input_tokens:Math.trunc(It(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(It(e.cacheCreationInputTokens)),ttft:Mt(e.ttft),tokens_per_second:Mt(e.tokensPerSecond),duration_ms:Math.trunc(It(e.durationMs)),status:nc(e.status),error_message:so(e.errorMessage)??null,response_body:so(e.responseBody)??null}}function Xp(n){return co({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,stream:n.stream===1,inputTokens:n.input_tokens,outputTokens:n.output_tokens,cacheReadInputTokens:n.cache_read_input_tokens,cacheCreationInputTokens:n.cache_creation_input_tokens,ttft:n.ttft,tokensPerSecond:n.tokens_per_second,durationMs:n.duration_ms,status:nc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function Zp(){return new Date(Date.now()-zp*24*60*60*1e3).toISOString()}function rc(n,e=!1){let t=Date.now();!e&&t-qa<Bp||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(Zp()),qa=t)}function sc(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function qe(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, ${qp}
373
+ `)}function Xp(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,zp);return Math.round(n/r)}function uo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Mt(n.ttft):null;return{...n,ttft:r,tokensPerSecond:Xp(e,o,r)}}function be(n){return typeof n=="string"?n:n==null?"":String(n)}function ao(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 rc(n){return n==="success"?"success":"error"}function sc(n){let e=uo(n);return{id:be(e.id),timestamp:be(e.timestamp),session_id:be(e.sessionId),provider:be(e.provider),original_model:be(e.originalModel),model:be(e.model),upstream_model:ao(e.upstreamModel)??null,model_family:be(e.modelFamily),scenario_type:be(e.scenarioType),client_type:ao(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:rc(e.status),error_message:ao(e.errorMessage)??null,response_body:ao(e.responseBody)??null}}function Zp(n){return uo({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,stream:n.stream===1,...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:rc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function qp(){return new Date(Date.now()-Bp*24*60*60*1e3).toISOString()}function ic(n,e=!1){let t=Date.now();!e&&t-tc<Jp||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(qp()),tc=t)}function ac(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, ${ef}
375
375
  FROM usage_records ${r}
376
376
  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 ic(n,e){let t=sc(e),o=n.prepare(`
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 cc(n,e){let t=ac(e),o=n.prepare(`
378
378
  SELECT
379
379
  COUNT(*) AS totalRequests,
380
+ COALESCE(SUM(usage_estimated), 0) AS estimatedCount,
380
381
  COALESCE(SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END), 0) AS successCount,
381
382
  COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS totalInputTokens,
382
383
  COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS totalOutputTokens,
@@ -385,14 +386,14 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
385
386
  AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
386
387
  AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
387
388
  FROM usage_records ${t.sql}
388
- `).get(...t.params);return{totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:qe(n,t,"model"),byProvider:qe(n,t,"provider"),byScenario:qe(n,t,"scenario_type"),byFamily:qe(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:qe(n,t,"date(timestamp, 'localtime')"),byClient:qe(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function $t(n){let e=Lt(),t=co(n);es.run(oc(t)),rc(e)}function ts(n){let e=Lt(),t=sc(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.min(Math.floor(n.pageSize),ef):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=ic(e,n);return{records:i.map(Xp),summary:c,total:a.count,page:o,pageSize:r}}function Nt(n,e,t){let o=Lt();return ic(o,{startTime:n,endTime:e,status:t})}function ns(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 tf(){ke&&(ke.pragma("wal_checkpoint(TRUNCATE)"),ke.close(),ke=null,es=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 os(n){let e=ao($p(),Dp,`session-${Up(n)}.json`);try{let t=JSON.parse(tc(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function nf(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 io,jp,qr,Hp,zp,Bp,Za,ke,es,qa,qp,ef,Ft=w(()=>{"use strict";io=ao(Fp,"data"),jp=ao(io,"usage.sqlite"),qr=ao(io,"usage.jsonl"),Hp=1,zp=180,Bp=3600*1e3,Za="legacy_usage_jsonl_migrated_at",ke=null,es=null,qa=0;qp=`
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 Nt(n){let e=Lt(),t=uo(n);ns.run(sc(t)),ic(e)}function os(n){let e=Lt(),t=ac(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),tf):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=cc(e,n);return{records:i.map(Zp),summary:c,total:a.count,page:o,pageSize:r}}function $t(n,e,t){let o=Lt();return cc(o,{startTime:n,endTime:e,status:t})}function rs(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 nf(){ke&&(ke.pragma("wal_checkpoint(TRUNCATE)"),ke.close(),ke=null,ns=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 ss(n){let e=lo($p(),jp,`session-${Dp(n)}.json`);try{let t=JSON.parse(oc(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function of(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 co,Hp,ts,zp,Bp,Jp,ec,ke,ns,tc,ef,tf,Ft=w(()=>{"use strict";co=lo(Up,"data"),Hp=lo(co,"usage.sqlite"),ts=lo(co,"usage.jsonl"),zp=1,Bp=180,Jp=3600*1e3,ec="legacy_usage_jsonl_migrated_at",ke=null,ns=null,tc=0;ef=`
389
390
  COUNT(*) AS count,
390
391
  COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
391
392
  COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
392
393
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
393
394
  COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
394
- `;ef=200});import{existsSync as of}from"fs";import{homedir as rf}from"os";import{join as sf}from"path";import{writeFile as af}from"fs/promises";async function cc(){let n=rf(),e=sf(n,".claude.json");if(!of(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 af(e,JSON.stringify(o,null,2))}}var lc=w(()=>{"use strict"});import{existsSync as cf,readdirSync as lf,statSync as uf,unlinkSync as df}from"fs";import{join as uc}from"path";import{HOME_DIR as pf}from"@wengine-ai/claude-code-router-shared";function pc(n=uc(pf,"logs")){try{if(!cf(n))return;let e=Date.now()-mf;for(let t of lf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=uc(n,t),r=uf(o);r.isFile()&&r.mtime.getTime()<e&&df(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function fc(){dc||(dc=!0,pc(),setInterval(pc,gf).unref())}var ff,mf,gf,dc,mc=w(()=>{"use strict";ff=7,mf=ff*24*60*60*1e3,gf=1440*60*1e3,dc=!1});async function gc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":_t.registerPlugin(Zn,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:Xn()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await _t.enablePlugins(n)}var hc=w(()=>{"use strict";Wr()});function et(n,e,t){if(n?.configService)try{n.configService.reload(),n.reloadProviders?n.reloadProviders(e):(n.configService.set("providers",e?.Providers??e?.providers??[]),n.providerService?.reload()),Et(e,t),wr();let o={enabled:n.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:n.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:n.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(n.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:n.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:n.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};n.activeProbeService=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 lo=w(()=>{"use strict";At();Kn();q()});import{constants as rs,lstatSync as tt,realpathSync as Ut,openSync as hf,closeSync as yf,fstatSync as bf,readFileSync as yc}from"node:fs";import{dirname as H_,join as nt,sep as _f}from"node:path";import{pathToFileURL as kf}from"node:url";function _c(n){try{let e=JSON.parse(yc(nt(Tf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function is(n,e){if(!bc(e))return null;try{let t=Ut(n),o=nt(t,"plugins"),r=nt(o,e);return tt(o).isSymbolicLink()||!tt(o).isDirectory()||tt(r).isSymbolicLink()||!tt(r).isDirectory()||Ut(o)!==o||Ut(r)!==r||!r.startsWith(o+_f)?null:r}catch{return null}}function ss(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=is(n,e);if(!o)throw new Error("unsafe plugin directory");let r=nt(o,t),s=tt(r);if(s.isSymbolicLink()||!s.isFile()||Ut(r)!==r)throw new Error("unsafe plugin file");let a=hf(r,rs.O_RDONLY|rs.O_NOFOLLOW|rs.O_NONBLOCK);try{let i=bf(a),c=tt(r);if(!i.isFile()||c.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==c.dev||i.ino!==c.ino||is(n,e)!==o||Ut(r)!==r)throw new Error("plugin file changed while opening");return yc(a)}finally{yf(a)}}function vf(n){let e=n?.configService,t=e?Ss(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Cs(t)}async function kc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Po(),r={configDir:e,readConfig:()=>Y(),readRawConfig:()=>Rt(),writeConfig:i=>ue(i),reloadRuntime:async i=>et(n.getServer(),i??await Y(),t),getDirectDispatcher:bo,getSubscriptionDispatcher:()=>vf(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of _c(e)){let c;try{if(!bc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let l=is(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let g=JSON.parse(ss(e,i.name,"plugin.json").toString("utf8"));if(!g||typeof g.name!="string"||typeof g.version!="string")throw new Error;u={name:g.name,version:g.version,coreApi:String(g.coreApi??"1"),description:g.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:g=>t.info(`[plugin:${u.name}] ${g}`),warn:g=>t.warn(`[plugin:${u.name}] ${g}`),error:g=>t.error(`[plugin:${u.name}] ${g}`)},r,l);c=p,ss(e,i.name,"plugin.js");let d=await import(kf(nt(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 h=p.cardPath?ss(e,i.name,p.cardPath):void 0;await p.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function Tc(n,e=Po()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return _c(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 bc,Tf,as=w(()=>{"use strict";Ro();Vt();lo();wt();q();bc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Tf=n=>nt(n,"plugins")});import{existsSync as vc,readFileSync as xf}from"node:fs";import{join as cs}from"node:path";import{NPM_SPEC_PATTERN as Sf,PLUGIN_NAME_PATTERN as xc,PluginInstallError as Cf,installPluginFromNpm as Rf,readPluginRecords as wf}from"@wengine-ai/claude-code-router-shared";async function Ef(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 Af(n,e={}){let t=(e.registryBase??Pf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(Sc.map(m=>Ef(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 _=y?.package,b=typeof _?.name=="string"?_.name:"";if(!b||!Sf.test(b)||!(Array.isArray(_?.keywords)?_.keywords.filter(x=>typeof x=="string"):[]).some(x=>Sc.includes(x)))continue;let T=typeof _?.version=="string"?_.version:"";s.has(b)||s.set(b,{name:b,version:T,description:typeof _?.description=="string"?_.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=wf(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(!xc.test(m))return null;try{let y=JSON.parse(xf(cs(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),_=y!==void 0||vc(cs(n,"plugins",m.name)),b=_?p(y?y.name:m.name):null;return{...m,installed:_,installedVersion:b,..._&&b!==null&&b!==m.version?{updateAvailable:!0}:{}}}),f=new Set(d.map(m=>m.name)),h=new Set,g=new Map;for(let[m,y]of u)h.add(y.name),!f.has(m)&&g.set(m,y.name);for(let m of i)f.has(m.name)||h.has(m.name)||g.set(m.name,m.name);for(let[m,y]of g){if(!xc.test(y)||!vc(cs(n,"plugins",y)))continue;let _=p(y);_!==null&&d.push({name:m,description:"",version:_,installed:!0,installedVersion:_,localOnly:!0})}return d.sort((m,y)=>m.name.localeCompare(y.name)),{ok:!0,plugins:d}}function Of(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 Cc(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 Rc(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(!Cc(r,n,t))return o(s,403,"local_only");try{return await Af(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(!Cc(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 Rf({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 Cf){let u=Of(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 Sc,Pf,wc=w(()=>{"use strict";Sc=["ccr-provider-plugin","claude-code-router-plugin"],Pf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as If}from"@wengine-ai/claude-code-router-shared";import{join as ce,isAbsolute as Mf,normalize as Lf,dirname as $f}from"path";import{fileURLToPath as Nf}from"url";import Ff from"@fastify/static";import{readdirSync as Pc,statSync as Uf,readFileSync as Ec,writeFileSync as Df,existsSync as fe,unlinkSync as Ac,rmSync as jf}from"fs";import{homedir as ls}from"os";import{getPresetDir as uo,readManifestFromDir as us,manifestToPresetFile as Oc,saveManifest as Ic,isPresetInstalled as Mc,extractPreset as Hf,HOME_DIR as ds,loadConfigFromManifest as zf,downloadPresetToTemp as Bf,findMarketPresetByName as Jf,getMarketPresets as Wf,applyClientSelection as Kf,disableClient as Gf,enableClient as Vf,isClientId as Qf,listClientStatuses as Lc,restoreClient as Yf,listProjectConfigs as Xf,readProjectConfigById as ps,readProjectConfig as Zf,writeProjectConfig as $c,deleteProjectConfig as qf,getClaudeProjectId as em,getProjectConfigPath as tm,refreshCcrProjectTakeover as nm,refreshPiProjectTakeover as om,refreshProjectTakeovers as rm,syncGlobalProjectTakeovers as fs,getProjectTakeoverClients as ms,setProjectTakeover as gs,isProjectTakeoverClient as sm}from"@wengine-ai/claude-code-router-shared";import im from"@fastify/multipart";import am from"adm-zip";function Nc(n){let e=j();return Yr(n,(t,o)=>e.isAvailable(t,o))}function Fc(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 cm(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,h,g=(n||[]).find(m=>m&&m.name===c);g&&g.quota&&(f=g.quota.limit5h,h=g.quota.limit7d),a.push({provider:c,used5h:p,used7d:d,limit5h:f,limit7d:h})}return a}async function Uc(n,e){let t=n.app;at(),lt(),t.register(im,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Nc(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=Nc(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[g,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${g}, model: ${m}`);let y=f.getTokenizerConfigForModel(g,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${g},${m}, using default tiktoken`);let _=await f.countTokens({messages:l,system:p,tools:u},y,g);return{input_tokens:_.tokenCount,tokenizer:_.tokenizerUsed}}catch(g){i.log?.error(`Error using configured tokenizer: ${g.message}`),i.log?.error(g.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:cn(l,p,u)}}),t.get("/api/config",async(i,c)=>await Rt()),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=xs(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 to();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await Y()}catch{}let f=If(l,d);n.pluginRegistry.applyConfigProtectors(l,d),await ue(l);let h;try{h=await fs(l),h.failed.length>0&&t.log?.warn?.({projectTakeoverSync:h},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}return et(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:h}}),t.get("/api/clients",async(i,c)=>{try{let l=await Y();return{clients:Lc(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 Y(),d=Kf(p,u);await ue(d.config);let f=await fs(d.config),h=Fc(t,f,"clients/apply");return{...d,success:d.success&&h,projectTakeoverSync:f}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!Qf(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await Y(),d=l==="enable"?Vf(p,u):l==="restore"?Yf(p,u):Gf(p,u);await ue(p);let f=await fs(p),h=Fc(t,f,`clients/${u}/${l}`);return{success:d.success&&h,result:d,results:[d],clients:Lc(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 Xf();return{projects:await Promise.all(l.map(async p=>{let d=await ms(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"||!Mf(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=Lf(l).replace(/[\\/]+$/,"")||l;if(await Zf(u)){c.status(409).send({error:"Project is already configured"});return}await $c(u,{Router:{}});try{let f=await Y();await gs(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await ms(u);return{id:em(u),path:u,configPath:tm(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 ps(l);if(!p){c.status(404).send({error:"Project config not found"});return}await $c(p.path,{Router:u});let d=await Y();Object.keys(u).length===0?await rm(p.path,d):(await nm(p.path,d,u),await om(p.path,d,u));let f=await ms(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(sm);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 ps(l);if(!d){c.status(404).send({error:"Project config not found"});return}let f=await Y(),h=await gs(d.path,p,f);return{id:l,path:d.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await ps(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await Y();await gs(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await qf(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:$f(Nf(import.meta.url)),s=fe(ce(r,"index.html"))?r:fe(ce(r,"..","index.html"))?ce(r,".."):ce(r,"..","dist");t.register(Ff,{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=ce(ls(),".claude-code-router","logs"),u=[];if(fe(l)){let p=Pc(l);for(let d of p)if(d.endsWith(".log")){let f=ce(l,d),h=Uf(f);u.push({name:d,path:f,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(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=ce(ls(),".claude-code-router","logs","app.log"),fe(u)?Ec(u,"utf8").split(`
395
- `).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=ce(ls(),".claude-code-router","logs","app.log"),fe(u)&&Df(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 vo(c),{enabled:Bt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return ts({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 ns(l.beforeDate),{success:!0,message:l.beforeDate?"Usage data cleared before "+l.beforeDate:"All usage data cleared"}}catch(l){console.error("Failed to clear usage:",l),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,c)=>{try{let u=j().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,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&&oo(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 h=await u.probeProviderManually(f.name);return h.success&&oo(f.name,i?.log),{provider:f.name,success:h.success,latencyMs:h.latencyMs,status:h.status,isSlow:h.isSlow,errorKind:h.errorKind??null,error:h.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(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 Y()).Providers||[],p=cm(u),d=new Map(p.map(g=>[g.provider,g])),f=Uo();for(let g of p){let m=f.find(y=>y.provider===g.provider);m&&m.limit!=null&&(g.limit5h=m.limit,g.used5h=m.limit-(m.remaining??0),m.reset&&(g.reset5h=new Date(m.reset*1e3).toISOString()))}let h=Yo();for(let g of h){let m=d.get(g.provider);m||(m={provider:g.provider,used5h:0,used7d:0},p.push(m),d.set(g.provider,m)),typeof g.totalBalance=="number"?(m.limit7d=g.totalBalance,m.type7d=g.currency?"balance":"rateLimit",g.currency&&(m.currency=g.currency),typeof g.usedBalance=="number"?m.used7d=g.usedBalance:typeof g.remainingBalance=="number"?m.used7d=Math.max(0,g.totalBalance-g.remainingBalance):(m.used7d=0,m.limit7d=g.totalBalance)):typeof g.usedBalance=="number"&&(m.used7d=g.usedBalance),typeof g.usedDailyBalance=="number"&&(m.used5h=g.usedDailyBalance,m.type5h="rateLimit"),typeof g.limitDaily=="number"&&(m.limit5h=g.limitDaily,m.type5h="rateLimit"),typeof g.resetTime=="string"&&(g.limitDaily!==void 0?m.reset5h=g.resetTime:m.reset7d=g.resetTime),typeof g.resetTime7d=="string"&&(m.reset7d=g.resetTime7d)}return{quotas:p,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=ce(ds,"presets");if(!fe(l))return{presets:[]};let p=Pc(l,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let h=ce(l,f);try{let g=ce(h,"manifest.json"),m=Ec(g,"utf-8"),y=JSON.parse(m),{Providers:_,Router:b,PORT:k,HOST:T,API_TIMEOUT_MS:x,PROXY_URL:v,PROXY_GLOBAL_ENABLED:C,LOG:S,LOG_LEVEL:P,StatusLine:L,NON_INTERACTIVE_MODE:$,...A}=y;d.push({id:f,name:A.name||f,version:A.version||"1.0.0",description:A.description,author:A.author,homepage:A.homepage,repository:A.repository,license:A.license,keywords:A.keywords,ccrVersion:A.ccrVersion,source:A.source,sourceType:A.sourceType,checksum:A.checksum,installed:!0})}catch(g){console.error(`Failed to read preset ${f}:`,g)}}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=uo(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}let p=await us(u);return{...Oc(p),config:zf(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=uo(l);if(!fe(p)){c.status(404).send({error:"Preset not found"});return}let f={...await us(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await Ic(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=uo(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}return jf(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 Wf()}}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 Jf(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,h=u.name||l;if(await Mc(h)){c.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let g=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await Bf(g),y=await a(m);if(await Mc(h)){Ac(m),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let _=uo(h);await Hf(m,_);let b=await us(_);return b.repository=u.repo,u.url&&(b.source=u.url),await Ic(h,b),Ac(m),{success:!0,presetName:h,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 am(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 Oc(u)}return t.get("/api/plugins",async()=>({plugins:Tc(ds,n.pluginRegistry)})),Rc(t,{configDir:ds,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 Dc=w(()=>{"use strict";Ce();$e();Ue();q();rt();se();At();lo();as();wc();wt();Ft();Xr()});function lm(n,e){let t=n?.Router,{family:o}=ft(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function jc(n){return n?.Router?.image}function um(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 dm(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 hs,po,ys,Hc,zc=w(()=>{"use strict";Ce();hs=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}},po=new hs;ys=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=lm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!um(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&mt(e.body.model)?!1:(dm(e.body.messages),s&&!!jc(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=po.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=po.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:jc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
395
+ `;tf=200});import{existsSync as rf}from"fs";import{homedir as sf}from"os";import{join as af}from"path";import{writeFile as cf}from"fs/promises";async function uc(){let n=sf(),e=af(n,".claude.json");if(!rf(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 cf(e,JSON.stringify(o,null,2))}}var dc=w(()=>{"use strict"});import{existsSync as lf,readdirSync as uf,statSync as df,unlinkSync as pf}from"fs";import{join as pc}from"path";import{HOME_DIR as ff}from"@wengine-ai/claude-code-router-shared";function mc(n=pc(ff,"logs")){try{if(!lf(n))return;let e=Date.now()-gf;for(let t of uf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=pc(n,t),r=df(o);r.isFile()&&r.mtime.getTime()<e&&pf(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function gc(){fc||(fc=!0,mc(),setInterval(mc,hf).unref())}var mf,gf,hf,fc,hc=w(()=>{"use strict";mf=7,gf=mf*24*60*60*1e3,hf=1440*60*1e3,fc=!1});async function yc(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(eo,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:qn()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var _c=w(()=>{"use strict";Vr()});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),Ar();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 po=w(()=>{"use strict";At();Vn();q()});import{constants as is,lstatSync as nt,realpathSync as Ut,openSync as yf,closeSync as _f,fstatSync as bf,readFileSync as bc}from"node:fs";import{dirname as Bb,join as ot,sep as kf}from"node:path";import{pathToFileURL as Tf}from"node:url";function Tc(n){try{let e=JSON.parse(bc(ot(vf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function cs(n,e){if(!kc(e))return null;try{let t=Ut(n),o=ot(t,"plugins"),r=ot(o,e);return nt(o).isSymbolicLink()||!nt(o).isDirectory()||nt(r).isSymbolicLink()||!nt(r).isDirectory()||Ut(o)!==o||Ut(r)!==r||!r.startsWith(o+kf)?null:r}catch{return null}}function as(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=cs(n,e);if(!o)throw new Error("unsafe plugin directory");let r=ot(o,t),s=nt(r);if(s.isSymbolicLink()||!s.isFile()||Ut(r)!==r)throw new Error("unsafe plugin file");let a=yf(r,is.O_RDONLY|is.O_NOFOLLOW|is.O_NONBLOCK);try{let i=bf(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||cs(n,e)!==o||Ut(r)!==r)throw new Error("plugin file changed while opening");return bc(a)}finally{_f(a)}}function xf(n){let e=n?.configService,t=e?Rs(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return ws(t)}async function vc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Ao(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>wt(),writeConfig:i=>ue(i),reloadRuntime:async i=>tt(n.getServer(),i??await X(),t),getDirectDispatcher:ko,getSubscriptionDispatcher:()=>xf(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Tc(e)){let c;try{if(!kc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let l=cs(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let g=JSON.parse(as(e,i.name,"plugin.json").toString("utf8"));if(!g||typeof g.name!="string"||typeof g.version!="string")throw new Error;u={name:g.name,version:g.version,coreApi:String(g.coreApi??"1"),description:g.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:g=>t.info(`[plugin:${u.name}] ${g}`),warn:g=>t.warn(`[plugin:${u.name}] ${g}`),error:g=>t.error(`[plugin:${u.name}] ${g}`)},r,l);c=p,as(e,i.name,"plugin.js");let d=await import(Tf(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 h=p.cardPath?as(e,i.name,p.cardPath):void 0;await p.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function xc(n,e=Ao()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Tc(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 kc,vf,ls=w(()=>{"use strict";Po();Vt();po();Pt();q();kc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),vf=n=>ot(n,"plugins")});import{existsSync as Cc,readFileSync as Cf}from"node:fs";import{join as us}from"node:path";import{NPM_SPEC_PATTERN as Sf,PLUGIN_NAME_PATTERN as Sc,PluginInstallError as Rf,installPluginFromNpm as wf,readPluginRecords as Pf}from"@wengine-ai/claude-code-router-shared";async function Af(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 Of(n,e={}){let t=(e.registryBase??Ef).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(Rc.map(m=>Af(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(!_||!Sf.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>Rc.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=Pf(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(!Sc.test(m))return null;try{let y=JSON.parse(Cf(us(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||Cc(us(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)),h=new Set,g=new Map;for(let[m,y]of u)h.add(y.name),!f.has(m)&&g.set(m,y.name);for(let m of i)f.has(m.name)||h.has(m.name)||g.set(m.name,m.name);for(let[m,y]of g){if(!Sc.test(y)||!Cc(us(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 If(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 wc(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 Pc(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(!wc(r,n,t))return o(s,403,"local_only");try{return await Of(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(!wc(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 wf({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 Rf){let u=If(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 Rc,Ef,Ec=w(()=>{"use strict";Rc=["ccr-provider-plugin","claude-code-router-plugin"],Ef="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Mf}from"@wengine-ai/claude-code-router-shared";import{join as ce,isAbsolute as Lf,normalize as Nf,dirname as $f}from"path";import{fileURLToPath as Ff}from"url";import Uf from"@fastify/static";import{readdirSync as Ac,statSync as Df,readFileSync as Oc,writeFileSync as jf,existsSync as fe,unlinkSync as Ic,rmSync as Hf}from"fs";import{homedir as ds}from"os";import{getPresetDir as fo,readManifestFromDir as ps,manifestToPresetFile as Mc,saveManifest as Lc,isPresetInstalled as Nc,extractPreset as zf,HOME_DIR as fs,loadConfigFromManifest as Bf,downloadPresetToTemp as Jf,findMarketPresetByName as Wf,getMarketPresets as Kf,applyClientSelection as Gf,disableClient as Vf,enableClient as Qf,isClientId as Yf,listClientStatuses as $c,restoreClient as Xf,listProjectConfigs as Zf,readProjectConfigById as ms,readProjectConfig as qf,writeProjectConfig as Fc,deleteProjectConfig as em,getClaudeProjectId as tm,getProjectConfigPath as nm,refreshCcrProjectTakeover as om,refreshPiProjectTakeover as rm,refreshProjectTakeovers as sm,syncGlobalProjectTakeovers as gs,getProjectTakeoverClients as hs,setProjectTakeover as ys,isProjectTakeoverClient as im}from"@wengine-ai/claude-code-router-shared";import am from"@fastify/multipart";import cm from"adm-zip";function Uc(n){let e=j();return Zr(n,(t,o)=>e.isAvailable(t,o))}function Dc(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 lm(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=$t(t,e),s=$t(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,h,g=(n||[]).find(m=>m&&m.name===c);g&&g.quota&&(f=g.quota.limit5h,h=g.quota.limit7d),a.push({provider:c,used5h:p,used7d:d,limit5h:f,limit7d:h})}return a}async function jc(n,e){let t=n.app;ct(),ut(),t.register(am,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Uc(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=Uc(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[g,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${g}, model: ${m}`);let y=f.getTokenizerConfigForModel(g,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${g},${m}, using default tiktoken`);let b=await f.countTokens({messages:l,system:p,tools:u},y,g);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(g){i.log?.error(`Error using configured tokenizer: ${g.message}`),i.log?.error(g.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:cn(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=Ss(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 oo();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}let f=Mf(l,d);n.pluginRegistry.applyConfigProtectors(l,d),await ue(l);let h;try{h=await gs(l),h.failed.length>0&&t.log?.warn?.({projectTakeoverSync:h},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}return tt(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:h}}),t.get("/api/clients",async(i,c)=>{try{let l=await X();return{clients:$c(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=Gf(p,u);await ue(d.config);let f=await gs(d.config),h=Dc(t,f,"clients/apply");return{...d,success:d.success&&h,projectTakeoverSync:f}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!Yf(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=l==="enable"?Qf(p,u):l==="restore"?Xf(p,u):Vf(p,u);await ue(p);let f=await gs(p),h=Dc(t,f,`clients/${u}/${l}`);return{success:d.success&&h,result:d,results:[d],clients:$c(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 Zf();return{projects:await Promise.all(l.map(async p=>{let d=await hs(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"||!Lf(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=Nf(l).replace(/[\\/]+$/,"")||l;if(await qf(u)){c.status(409).send({error:"Project is already configured"});return}await Fc(u,{Router:{}});try{let f=await X();await ys(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await hs(u);return{id:tm(u),path:u,configPath:nm(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 ms(l);if(!p){c.status(404).send({error:"Project config not found"});return}await Fc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await sm(p.path,d):(await om(p.path,d,u),await rm(p.path,d,u));let f=await hs(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(im);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 ms(l);if(!d){c.status(404).send({error:"Project config not found"});return}let f=await X(),h=await ys(d.path,p,f);return{id:l,path:d.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await ms(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await X();await ys(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await em(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:$f(Ff(import.meta.url)),s=fe(ce(r,"index.html"))?r:fe(ce(r,"..","index.html"))?ce(r,".."):ce(r,"..","dist");t.register(Uf,{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=ce(ds(),".claude-code-router","logs"),u=[];if(fe(l)){let p=Ac(l);for(let d of p)if(d.endsWith(".log")){let f=ce(l,d),h=Df(f);u.push({name:d,path:f,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(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=ce(ds(),".claude-code-router","logs","app.log"),fe(u)?Oc(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=ce(ds(),".claude-code-router","logs","app.log"),fe(u)&&jf(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 Co(c),{enabled:Bt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return os({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 $t(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 rs(l.beforeDate),{success:!0,message:l.beforeDate?"Usage data cleared before "+l.beforeDate:"All usage data cleared"}}catch(l){console.error("Failed to clear usage:",l),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,c)=>{try{let u=j().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,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&&so(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 h=await u.probeProviderManually(f.name);return h.success&&so(f.name,i?.log),{provider:f.name,success:h.success,latencyMs:h.latencyMs,status:h.status,isSlow:h.isSlow,errorKind:h.errorKind??null,error:h.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(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=lm(u),d=new Map(p.map(g=>[g.provider,g])),f=jo();for(let g of p){let m=f.find(y=>y.provider===g.provider);m&&m.limit!=null&&(g.limit5h=m.limit,g.used5h=m.limit-(m.remaining??0),m.reset&&(g.reset5h=new Date(m.reset*1e3).toISOString()))}let h=Zo();for(let g of h){let m=d.get(g.provider);m||(m={provider:g.provider,used5h:0,used7d:0},p.push(m),d.set(g.provider,m)),typeof g.totalBalance=="number"?(m.limit7d=g.totalBalance,m.type7d=g.currency?"balance":"rateLimit",g.currency&&(m.currency=g.currency),typeof g.usedBalance=="number"?m.used7d=g.usedBalance:typeof g.remainingBalance=="number"?m.used7d=Math.max(0,g.totalBalance-g.remainingBalance):(m.used7d=0,m.limit7d=g.totalBalance)):typeof g.usedBalance=="number"&&(m.used7d=g.usedBalance),typeof g.usedDailyBalance=="number"&&(m.used5h=g.usedDailyBalance,m.type5h="rateLimit"),typeof g.limitDaily=="number"&&(m.limit5h=g.limitDaily,m.type5h="rateLimit"),typeof g.resetTime=="string"&&(g.limitDaily!==void 0?m.reset5h=g.resetTime:m.reset7d=g.resetTime),typeof g.resetTime7d=="string"&&(m.reset7d=g.resetTime7d)}return{quotas:p,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=ce(fs,"presets");if(!fe(l))return{presets:[]};let p=Ac(l,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let h=ce(l,f);try{let g=ce(h,"manifest.json"),m=Oc(g,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:T,API_TIMEOUT_MS:x,PROXY_URL:v,PROXY_GLOBAL_ENABLED:S,LOG:C,LOG_LEVEL:P,StatusLine:L,NON_INTERACTIVE_MODE:N,...A}=y;d.push({id:f,name:A.name||f,version:A.version||"1.0.0",description:A.description,author:A.author,homepage:A.homepage,repository:A.repository,license:A.license,keywords:A.keywords,ccrVersion:A.ccrVersion,source:A.source,sourceType:A.sourceType,checksum:A.checksum,installed:!0})}catch(g){console.error(`Failed to read preset ${f}:`,g)}}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=fo(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}let p=await ps(u);return{...Mc(p),config:Bf(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=fo(l);if(!fe(p)){c.status(404).send({error:"Preset not found"});return}let f={...await ps(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await Lc(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=fo(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}return Hf(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 Kf()}}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 Wf(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,h=u.name||l;if(await Nc(h)){c.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let g=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await Jf(g),y=await a(m);if(await Nc(h)){Ic(m),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let b=fo(h);await zf(m,b);let _=await ps(b);return _.repository=u.repo,u.url&&(_.source=u.url),await Lc(h,_),Ic(m),{success:!0,presetName:h,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 cm(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 Mc(u)}return t.get("/api/plugins",async()=>({plugins:xc(fs,n.pluginRegistry)})),Pc(t,{configDir:fs,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 Hc=w(()=>{"use strict";Se();$e();De();q();st();se();At();po();ls();Ec();Pt();Ft();qr()});function um(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 zc(n){return n?.Router?.image}function dm(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 pm(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var _s,mo,bs,Bc,Jc=w(()=>{"use strict";Se();_s=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},mo=new _s;bs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=um(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!dm(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&gt(e.body.model)?!1:(pm(e.body.messages),s&&!!zc(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=mo.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=mo.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:zc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
396
397
  When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
397
398
  Do not ignore or deviate from the task.
398
399
  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.
@@ -405,5 +406,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
405
406
 
406
407
  Do not attempt to describe or analyze the image directly yourself.
407
408
  Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
408
- 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")po.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:(po.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}})})}},Hc=new ys});var bs,Bc,fo,Jc=w(()=>{"use strict";zc();bs=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}},Bc=new bs;Bc.registerAgent(Hc);fo=Bc});import{EventEmitter as pm}from"node:events";import{performance as Wc}from"node:perf_hooks";import fm from"json5";function gm(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 Gc(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,e)}function _s(n){return n.usageSessionId||n.id}function mo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${_s(n)}`}function Dt(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ee(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function hm(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Pe(e.usage):e.response?.usage?Pe(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function ym(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();ro(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){Gc(n,t);let r=mo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Q.get(r))}}async function bm(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of fo.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 Vc(n){return{authClient:(e,t)=>ym(e,t,n),agent:(e,t)=>bm(e,t,n)}}function Qc(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Wc.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=c=>c?a(c):s();ro(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Kc.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){Gc(t,e);let c=_s(t),l=mo(t);if(r instanceof ReadableStream){if(a&&t.agents){let h=new AbortController,g=r.pipeThrough(new ae),m,y=-1,_="",b="",k="",T=[],x=[];return s(null,Gn(g,async(v,C)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let S=t.agents.find(P=>fo.getAgent(P)?.tools.get(v.data.content_block.name));if(S){m=fo.getAgent(S),y=v.data.index,_=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"){b+=v.data?.delta?.partial_json;return}if(y>-1&&v.data.index===y&&v.data?.type==="content_block_stop"){try{let S=fm.parse(b);x.push({type:"tool_use",id:k,name:_,input:S});let P=await m?.tools.get(_)?.handler(S,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:P}),m=void 0,y=-1,_="",b="",k=""}catch(S){console.log(S)}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 S=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(!S.ok)return;let L=S.body.pipeThrough(new ae).getReader();for(;;)try{let{value:$,done:A}=await L.read();if(A)break;let U=$;if(["message_start","message_stop"].includes(U.event))continue;if(!C.desiredSize)break;C.enqueue(U)}catch($){if($.name==="AbortError"||$.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw $}return}return v}catch(S){if(console.error("Unexpected error in stream processing:",S),S.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();return}throw S}}).pipeThrough(new Xe))}let[p,d]=r.tee(),f=async h=>{let m=h.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();try{for(;;){let{done:y,value:_}=await m.read();if(y)break;let b=_.event,k=_.data;if(b==="message_start"&&Dt(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&Dt(k?.response?.model)&&(t.upstreamModel=k.response.model),b==="response.completed"&&Dt(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=Q.get(l)||{},x=Pe(k.usage),v=Pt(T,x,b==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:b,provider:t.provider,model:Ee(t),usageSessionId:c,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}),Q.put(l,v)}if(k?.response?.usage){let T=Pe(k.response.usage),x=Q.get(l)||{},v=Pt(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:b,provider:t.provider,model:Ee(t),usageSessionId:c,capturedUsage:T,mergedUsage:v}),Q.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 ae).getReader();try{for(;;){let{done:h,value:g}=await f.read();if(h)break;let m=g.event,y=g.data;m==="message_start"&&y?.message?.model&&Dt(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&Dt(y?.response?.model)&&(t.upstreamModel=y.response.model);let _=y?.usage??y?.response?.usage;if(_){let b=Pe(_),k=Q.get(l)||{},T=Pt(k,b,m==="message_start");Q.put(l,T)}}}catch(h){h?.name!=="AbortError"&&h?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(h)})}finally{f.releaseLock()}})(),s(null,p)}let u=hm(r);if(u?.usage&&Q.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(Kc.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=>{Jo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Jo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async x=>{if(!x)return;let v;try{await Promise.race([x,new Promise(C=>{v=setTimeout(C,mm)})])}finally{v&&clearTimeout(v)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=_s(t),a=s,i=t.sessionId||s,c=o.statusCode>=400,l=c?void 0:Q.get(mo(t)),u=os(a),p=j(),d,f,h=t.sseError,g=h&&(h.type||h.code||h.message),m=l?.output_tokens&&l.output_tokens>0,y=c||g&&!m;if(y){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,g&&(d=d||JSON.stringify(h),f=JSON.stringify(h)),f=f||t.errorResponseBody;let x=Ee(t);gm(o.statusCode,d)?p.markRateLimited(t.provider||"",x,120,d):p.recordFailure(t.provider||"",x,d)}else{let x=Ee(t);p.recordSuccess(t.provider||"",x)}let _=l?.cache_read_input_tokens??0,k=l?.input_tokens||0||t.tokenCount||0;!_&&t.tokenCount&&l?.input_tokens&&l.input_tokens<t.tokenCount&&(_=t.tokenCount-l.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:l.input_tokens,impliedCache:_}));let T=y?0:l?.output_tokens||0;!y&&t.body?.stream&&k===0&&T===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ee(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:Ee(t),upstreamModel:t.upstreamModel||Ee(t)||void 0,modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||ze(t),stream:t.body?.stream??!1,inputTokens:k,outputTokens:T,cacheReadInputTokens:_,cacheCreationInputTokens:l?.cache_creation_input_tokens||0,ttft:y||!t.body?.stream?null:u.ttft,tokensPerSecond:y?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Wc.now()-t.requestStartTime):0,status:y?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Q.delete(mo(t))}catch(r){console.error("Usage tracking error:",r)}})}var mm,Kc,Yc=w(()=>{"use strict";Be();nn();en();se();Er();Ar();Or();Ft();Vr();Jc();Zr();dn();mm=1500;Kc=new pm});var Zc={};ho(Zc,{createCcrServer:()=>Cm});import{homedir as _m}from"os";import{join as km}from"path";import{createStream as Tm}from"rotating-file-stream";import{CONFIG_FILE as vm,HOME_DIR as Xc,listPresets as xm,ensureCcrSelfProvider as Sm}from"@wengine-ai/claude-code-router-shared";async function Cm(n={}){await cc(),await eo();let e=await Gr();Sm(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;Ja();let c=f=>(f>9?"":"0")+f,l=(f,h)=>{let g;f?typeof f=="number"?g=new Date(f):g=f:g=new Date;let m=g.getFullYear()+""+c(g.getMonth()+1),y=c(g.getDate()),_=c(g.getHours()),b=c(g.getMinutes());return`./logs/ccr-${m}${y}${_}${b}${c(g.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(fc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:Tm(l,{path:Xc,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await xm(),d=new el({jsonPath:vm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:km(_m(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await kc({configDir:Xc,registry:d.pluginRegistry,getServer:()=>d,log:{info:y=>d.app?.log?.info?.(y),warn:y=>d.app?.log?.warn?.(y),error:y=>d.app?.log?.error?.(y)}});f.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(y=>`${y.name} (${y.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(y=>`${y.name}@${y.version}`).join(", ")}`),f.loaded.length&&et(d,e,d.app.log),await Uc(d,e),d.recordUsage=y=>{try{let _=y.req?y.req.clientType||ze(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:_,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(_){console.error("Fallback usage tracking error:",_)}},Qc(d,e),d.ccrPreHandlerCallbacks=Vc(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,_)=>{if(y.status==="rejected"){let b=p[_],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${b?.name}": ${k}`)}}),await gc(d,e),Et(e,d.app?.log);let g=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,_)=>{d.app.log.error({reason:y,promise:_},"Unhandled rejection")};return process.on("uncaughtException",g),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",g),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var qc=w(()=>{"use strict";tl();lc();wt();mc();Dr();hc();Dc();as();lo();Yc();At();Ft();Be()});import Rm from"fastify";import wm from"@fastify/cors";function Pm(n={}){let e=Rm({bodyLimit:52428800,...n});return e.setErrorHandler(Es),e.register(wm),e}async function Em(n={}){return(await Promise.resolve().then(()=>(qc(),Zc))).createCcrServer(n)}var ks,el,nv,tl=w(()=>{ko();zt();dn();tr();ar();lr();Ce();nn();Kn();se();$e();Ue();q();Be();dn();Vt();De();Be();Ce();ko();tr();ar();lr();Wr();Ir();se();$e();xr();Ue();se();Kn();rt();q();wt();Vr();At();Xr();Zr();Ft();ks=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=Pm({...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 Ae(l),this.transformerService=new Qe(this.configService,this.app.log),this.tokenizerService=new Ye(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ke(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Ae({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Qe(o,this.app.log),a=new Ye(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ke(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async 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 h=l.ccrHookOrder||=[];if(h.push("request-normalize"),f&&l.body.input&&!l.body.messages&&gt(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),h.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),xe(l,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){h.push("router"),l.body?.model&&await ln(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&Q.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let g=l.body;if(!g||!g.model)return u.code(400).send({error:"Missing model in request body"});let m=g.model.split(","),y=g.model;if(m.length>1){let[_,...b]=m;y=b.join(","),g.model=y,l.provider=_}l.model=y}catch(g){return l.log.error({error:g},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Bi(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{Rr()}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 _o()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{at()}catch{}try{lt()}catch{}try{Lo()}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)}}},el=ks;nv=Em});tl();export{Wn as ActiveProbeService,Ae as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ke as ProviderService,ae as SSEParserTransform,Xe as SSESerializerTransform,Ye as TokenizerService,Qe as TransformerService,ro as apiKeyAuth,xe as applyClientAdapter,to as backupConfigFile,Ti as builtinClientAdapterRegistry,cn as calculateTokenCount,Du as clearClientAdapterCaches,oo as clearProviderHealth,_o as closeProxyDispatchers,Xa as collectReachableModelKeys,Em as createCcrServer,el as default,ze as detectClientType,Oi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,$a as getActiveProbeService,Yo as getAllQuotaResults,Uo as getAllRateLimitInfo,xi as getClientAdapter,Ht as getConfiguredProxyUrl,j as getHealthStore,K as getProxyDispatcher,Tr as getQuotaAdapter,on as getQuotaResult,Wl as getRateLimitInfo,Bt as getRuntimeDebugLog,nv as getServer,Gr as initConfig,eo as initDir,Lo as initProviderHealthPersistence,lt as initQuotaStorePersistence,at as initRateLimitPersistence,vi as isClientType,Rs as isGlobalProxyEnabled,Yr as listAnthropicCompatibleModels,Pt as mergeUsageCapture,ge as normalizeSessionId,Pe as normalizeUsagePayload,_t as pluginManager,Y as readConfigFile,Rt as readConfigFileRaw,Et as reconcileHealthStore,wr as resetActiveProbeService,de as resolveProviderProxyUrl,Gn as rewriteStream,ln as router,Li as searchProjectBySession,Q as sessionUsageCache,vo as setRuntimeDebugLog,bt as startActiveProbe,Rr as stopActiveProbe,Qo as storeQuotaResult,Zn as tokenSpeedPlugin,ac as usageStore,ue as writeConfigFile};
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")mo.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:(mo.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}})})}},Bc=new bs});var ks,Wc,go,Kc=w(()=>{"use strict";Jc();ks=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}},Wc=new ks;Wc.registerAgent(Bc);go=Wc});import{EventEmitter as fm}from"node:events";import{performance as Gc}from"node:perf_hooks";import mm from"json5";function hm(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 Qc(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&xe(n,e)}function Ts(n){return n.usageSessionId||n.id}function ho(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Ts(n)}`}function Dt(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ae(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 ym(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?Re(e.usage):e.response?.usage?Re(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function _m(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();io(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){Qc(n,t);let r=ho(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function bm(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of go.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 Yc(n){return{authClient:(e,t)=>_m(e,t,n),agent:(e,t)=>bm(e,t,n)}}function Xc(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Gc.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=c=>c?a(c):s();io(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Vc.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){Qc(t,e);let c=Ts(t),l=ho(t);if(r instanceof ReadableStream){if(a&&t.agents){let h=new AbortController,g=r.pipeThrough(new ae),m,y=-1,b="",_="",k="",T=[],x=[];return s(null,Qn(g,async(v,S)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let C=t.agents.find(P=>go.getAgent(P)?.tools.get(v.data.content_block.name));if(C){m=go.getAgent(C),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 C=mm.parse(_);x.push({type:"tool_use",id:k,name:b,input:C});let P=await m?.tools.get(b)?.handler(C,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:P}),m=void 0,y=-1,b="",_="",k=""}catch(C){console.log(C)}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 C=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!C.ok)return;let L=C.body.pipeThrough(new ae).getReader();for(;;)try{let{value:N,done:A}=await L.read();if(A)break;let U=N;if(["message_start","message_stop"].includes(U.event))continue;if(!S.desiredSize)break;S.enqueue(U)}catch(N){if(N.name==="AbortError"||N.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw N}return}return v}catch(C){if(console.error("Unexpected error in stream processing:",C),C.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();return}throw C}}).pipeThrough(new Ze))}let[p,d]=r.tee(),f=async h=>{let m=h.pipeThrough(new TextDecoderStream).pipeThrough(new ae).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&Dt(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&Dt(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&Dt(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=Y.get(l)||{},x=Re(k.usage),v=we(T,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Ae(t),usageSessionId:c,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(l,v)}if(k?.response?.usage){let T=Re(k.response.usage),x=Y.get(l)||{},v=we(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Ae(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 ae).getReader();try{for(;;){let{done:h,value:g}=await f.read();if(h)break;let m=g.event,y=g.data;m==="message_start"&&y?.message?.model&&Dt(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&Dt(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Re(b),k=Y.get(l)||{},T=we(k,_,m==="message_start");Y.put(l,T)}}}catch(h){h?.name!=="AbortError"&&h?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(h)})}finally{f.releaseLock()}})(),s(null,p)}let u=ym(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(Vc.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=>{Ko(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Ko(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async x=>{if(!x)return;let v;try{await Promise.race([x,new Promise(S=>{v=setTimeout(S,gm)})])}finally{v&&clearTimeout(v)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=Ts(t),a=s,i=t.sessionId||s,c=o.statusCode>=400,l=c?void 0:Y.get(ho(t)),u=ss(a),p=j(),d,f,h=t.sseError,g=h&&(h.type||h.code||h.message),m=l?.output_tokens&&l.output_tokens>0,y=c||g&&!m;if(y){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,g&&(d=d||JSON.stringify(h),f=JSON.stringify(h)),f=f||t.errorResponseBody;let x=Ae(t);hm(o.statusCode,d)?p.markRateLimited(t.provider||"",x,120,d):p.recordFailure(t.provider||"",x,d)}else{let x=Ae(t);p.recordSuccess(t.provider||"",x)}let b=l?.cache_read_input_tokens??0,k=l?.input_tokens||0||t.tokenCount||0;!l?.usage_estimated&&!b&&t.tokenCount&&l?.input_tokens&&l.input_tokens<t.tokenCount&&(b=t.tokenCount-l.input_tokens,b&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:l.input_tokens,impliedCache:b}));let T=y?0:l?.output_tokens||0;!y&&t.body?.stream&&k===0&&T===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ae(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."}),Nt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:i,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:Ae(t),upstreamModel:t.upstreamModel||Ae(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:k,outputTokens:T,cacheReadInputTokens:b,cacheCreationInputTokens:l?.cache_creation_input_tokens||0,ttft:y||!t.body?.stream?null:u.ttft,tokensPerSecond:y?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Gc.now()-t.requestStartTime):0,status:y?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(ho(t))}catch(r){console.error("Usage tracking error:",r)}})}var gm,Vc,Zc=w(()=>{"use strict";Je();nn();en();se();Ir();Mr();Lr();Ft();mn();Kc();es();dn();gm=1500;Vc=new fm});var el={};_o(el,{createCcrServer:()=>Rm});import{homedir as km}from"os";import{join as Tm}from"path";import{createStream as vm}from"rotating-file-stream";import{CONFIG_FILE as xm,HOME_DIR as qc,listPresets as Cm,ensureCcrSelfProvider as Sm}from"@wengine-ai/claude-code-router-shared";async function Rm(n={}){await uc(),await no();let e=await Yr();Sm(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;Ka();let c=f=>(f>9?"":"0")+f,l=(f,h)=>{let g;f?typeof f=="number"?g=new Date(f):g=f:g=new Date;let m=g.getFullYear()+""+c(g.getMonth()+1),y=c(g.getDate()),b=c(g.getHours()),_=c(g.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${c(g.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(gc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:vm(l,{path:qc,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await Cm(),d=new nl({jsonPath:xm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:Tm(km(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await vc({configDir:qc,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 jc(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Be(y.req):"unknown";Nt({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:y.sessionId||"",provider:y.provider||"",originalModel:y.originalModel||"",model:y.model||"",modelFamily:y.modelFamily||"",scenarioType:y.scenarioType||"default",clientType:b,stream:y.stream??!1,inputTokens:y.inputTokens||0,outputTokens:0,cacheReadInputTokens:y.cacheReadInputTokens||0,cacheCreationInputTokens:y.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:y.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},Xc(d,e),d.ccrPreHandlerCallbacks=Yc(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 yc(d,e),Et(e,d.app?.log);let g=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",g),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",g),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var tl=w(()=>{"use strict";ol();dc();Pt();hc();zr();_c();Hc();ls();po();Zc();At();Ft();Je()});import wm from"fastify";import Pm from"@fastify/cors";function Em(n={}){let e=wm({bodyLimit:52428800,...n});return e.setErrorHandler(Os),e.register(Pm),e}async function Am(n={}){return(await Promise.resolve().then(()=>(tl(),el))).createCcrServer(n)}var vs,nl,rv,ol=w(()=>{vo();zt();dn();or();ur();pr();Se();nn();Vn();se();$e();De();q();Je();dn();Vt();je();Je();Se();vo();or();ur();pr();Vr();Nr();se();$e();Rr();De();se();Vn();st();q();Pt();mn();At();qr();es();Ft();vs=class{app;pluginRegistry=new it;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=Em({...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 Oe(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 Oe({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 h=l.ccrHookOrder||=[];if(h.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"}),h.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),xe(l,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){h.push("router"),l.body?.model&&await ln(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&Y.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let g=l.body;if(!g||!g.model)return u.code(400).send({error:"Missing model in request body"});let m=g.model.split(","),y=g.model;if(m.length>1){let[b,..._]=m;y=_.join(","),g.model=y,l.provider=b}l.model=y}catch(g){return l.log.error({error:g},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Wi(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{Er()}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 To()})}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{ct()}catch{}try{ut()}catch{}try{$o()}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)}}},nl=vs;rv=Am});ol();export{Gn as ActiveProbeService,Oe as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ge as ProviderService,ae as SSEParserTransform,Ze as SSESerializerTransform,Xe as TokenizerService,Ye as TransformerService,io as apiKeyAuth,xe as applyClientAdapter,oo as backupConfigFile,xi as builtinClientAdapterRegistry,cn as calculateTokenCount,Hu as clearClientAdapterCaches,so as clearProviderHealth,To as closeProxyDispatchers,qa as collectReachableModelKeys,Am as createCcrServer,nl as default,Be as detectClientType,Mi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Fa as getActiveProbeService,Zo as getAllQuotaResults,jo as getAllRateLimitInfo,Si as getClientAdapter,Ht as getConfiguredProxyUrl,j as getHealthStore,K as getProxyDispatcher,Cr as getQuotaAdapter,on as getQuotaResult,Gl as getRateLimitInfo,Bt as getRuntimeDebugLog,rv as getServer,Yr as initConfig,no as initDir,$o as initProviderHealthPersistence,ut as initQuotaStorePersistence,ct as initRateLimitPersistence,Ci as isClientType,Ps as isGlobalProxyEnabled,Zr as listAnthropicCompatibleModels,we as mergeUsageCapture,ge as normalizeSessionId,Re as normalizeUsagePayload,kt as pluginManager,X as readConfigFile,wt as readConfigFileRaw,Et as reconcileHealthStore,Ar as resetActiveProbeService,de as resolveProviderProxyUrl,Qn as rewriteStream,ln as router,$i as searchProjectBySession,Y as sessionUsageCache,Co as setRuntimeDebugLog,bt as startActiveProbe,Er as stopActiveProbe,Xo as storeQuotaResult,eo as tokenSpeedPlugin,lc as usageStore,ue as writeConfigFile};
409
410
  //# sourceMappingURL=server.mjs.map