@wengine-ai/llms 2.3.2428 → 2.3.2430
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -14
- package/dist/cjs/server.cjs +216 -210
- package/dist/cjs/server.cjs.map +4 -4
- package/dist/esm/server.mjs +215 -209
- package/dist/esm/server.mjs.map +4 -4
- package/dist/index.html +16 -16
- package/dist/provider-plugins/types.d.ts +35 -0
- package/dist/services/plugin-quota.d.ts +44 -0
- package/dist/services/provider-health.d.ts +6 -0
- package/dist/services/quota-store.d.ts +2 -0
- package/dist/transformer/anthropic.transformer.d.ts +1 -1
- package/package.json +2 -2
package/dist/esm/server.mjs
CHANGED
|
@@ -1,306 +1,312 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; import { fileURLToPath as __fileURLToPath } from "node:url"; import { dirname as __pathDirname } from "node:path"; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __pathDirname(__filename);
|
|
2
|
-
var
|
|
2
|
+
var ko=Object.defineProperty;var ml=Object.getOwnPropertyDescriptor;var gl=Object.getOwnPropertyNames;var hl=Object.prototype.hasOwnProperty;var To=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var vo=(n,e)=>{for(var t in e)ko(n,t,{get:e[t],enumerable:!0})},yl=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gl(e))!hl.call(n,r)&&r!==t&&ko(n,r,{get:()=>e[r],enumerable:!(o=ml(e,r))||o.enumerable});return n};var _l=n=>yl(ko({},"__esModule",{value:!0}),n);import{Agent as bl,ProxyAgent as kl}from"undici";function vl(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Tl.test(e))return{ok:!0};try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:`Unsupported proxy protocol: ${t.protocol}. Only http:// and https:// are allowed.`}:{ok:!0}}catch{return{ok:!1,error:`Invalid proxy URL: ${e}`}}}function Os(n){let e=[];for(let t of[...Es,As]){let o=n[t];if(o==null)continue;let r=vl(o);r.ok||e.push({key:t,error:r.error})}return e}function So(){return xo||(xo=new bl({connect:{timeout:15e3}})),xo}function Is(n){let e=n.get(As);return(typeof e=="string"?e.trim():"")||void 0}function Ms(n){return n?G(n):So()}function Ht(n){for(let e of Es){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function Ls(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=Ht(n);if(t)return Ls(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function G(n){let e=xl(n),t=jt.get(e);if(t)return t;let o=new kl(e);return jt.set(e,o),o}async function Co(){let n=Array.from(jt.values());jt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function xl(n){let e=n.trim();if(!e)throw new TypeError("Proxy URL must not be empty");let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new TypeError(`Unsupported proxy protocol: ${t.protocol}`);return t.toString()}var Es,As,Tl,jt,xo,q=w(()=>{"use strict";Es=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],As="SUBSCRIPTION_PROXY_URL",Tl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;jt=new Map});import{readFileSync as Sl,existsSync as $s}from"fs";import{join as Ns}from"path";import{config as Cl}from"dotenv";import Rl from"json5";var Me,Ro=w(()=>{"use strict";q();Me=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Ns(process.cwd(),this.options.jsonPath);if($s(e))try{let t=Sl(e,"utf-8"),o=Rl.parse(t);this.config={...this.config,...o},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Ns(process.cwd(),this.options.envPath);if($s(e))try{let t=Cl({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let o=this.config[e];return o!==void 0?o:t}getAll(){return{...this.config}}getHttpsProxy(){return Ht(this)}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}}});function K(n,e=500,t="internal_error",o="api_error"){let r=new Error(n);return r.statusCode=e,r.code=t,r.type=o,r}async function Us(n,e,t){e.log.error(n);let o=n.statusCode||500;if(n.rawBody)try{let s=JSON.parse(n.rawBody);return t.code(o).send(s)}catch{return t.code(o).send(n.rawBody)}let r={error:{message:n.message||"Internal Server Error",type:n.type||"api_error",code:n.code||"internal_error"}};return t.code(o).send(r)}var zt=w(()=>{"use strict"});function Po(n){wo=n}function Bt(){return wo}function Jt(n){return wo||n.get("DEBUG_LOG")===!0}function js(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function Wt(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();wl.has(r)||Pl.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function Kt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Hs(n,e,t){let o=typeof t.body=="string"?t.body:JSON.stringify(t.body);n.info({debug_log:!0,reqId:e,phase:"provider_request",url:t.url,headers:Wt(t.headers),body:Kt(o,Le.maxBodyLength)})}function zs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:Wt(t.headers),...t.body!==void 0?{body:Kt(t.body,Le.maxBodyLength)}:{}})}function Ds(n,e,t,o){let r=El(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Kt(o,Le.maxBodyLength)})}function El(n){let e=[];for(let t of n.split(/\r?\n/)){if(!t.startsWith("data:"))continue;let o=t.slice(5).trim();if(!(!o||o==="[DONE]"))try{let r=JSON.parse(o),s=r?.usage||r?.response?.usage;s&&e.push({path:r?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(r?.choices)?r.choices.length:void 0,finishReason:r?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:Kt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Fs(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Bs(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:l}=await r.read();if(i)break;a+=l;let c=a.split(`
|
|
3
3
|
|
|
4
|
-
`);a=
|
|
5
|
-
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(xl.some(s=>r.includes(s))){e=!0;break}Sl.some(s=>r.includes(s))&&(t=!0)}}return e||Cl(n)?"content":t?"empty":"pending"}async function zs(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(Ro(a)==="content"?"content":"pending",Gt(o,f));if(h.done){a+=r.decode();let m=Ro(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=Ro(a);if(g==="content")return l("content",Gt(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(Hs(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 Bs(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 xl,Sl,Js=w(()=>{"use strict";xl=["content_block_start","content_block_delta","content_block_stop"];Sl=["message_stop","response.completed","response.incomplete","[DONE]"]});function Rl(n,e){return`${n.name}|${e?.name??""}`}function wo(n){return n.__ccrPluginRequestState??={budgets:new Map}}function Le(n,e,t){let o=wo(n),r=Rl(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Po(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(Le(n,e,o).terminalError=t,!0)}var Ws=w(()=>{"use strict"});var Eo=w(()=>{"use strict"});import wl from"fastify";function Ks(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,Pl,Oo,Vt=w(()=>{"use strict";Eo();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=wl({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")}},Pl=new it,Oo=()=>Pl});function Gs(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?El(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=Ks(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function El(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 Vs=w(()=>{"use strict";Vt()});var Qt,Io=w(()=>{Qt="2.3.2428"});var Qs={};bo(Qs,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>Il});function Ne(n){return ve||(ve=new Mo,n&&ve.configure(n)),ve}function Il(){ve&&(ve.clearAll(),ve=null)}var Ol,Mo,ve,Yt=w(()=>{"use strict";se();Ol=600*1e3,Mo=class{promotions=new Map;enabled=!0;ttlMs=Ol;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 Zs,mkdirSync as Ml,readFileSync as Ll,writeFileSync as Nl}from"fs";import{join as qs}from"path";import{HOME_DIR as $l}from"@wengine-ai/claude-code-router-shared";function jl(n){try{if(!Zs($o))return;let e=JSON.parse(Ll($o,"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 Xs(n){try{let e=n.getAllStates();if(e.length===0)return;Zs(No)||Ml(No,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Nl($o,JSON.stringify(t,null,2),"utf-8")}catch{}}function Fo(){if(Ys)return;Ys=!0;let n=j();jl(n),Dl=setInterval(()=>Xs(n),6e4),process.on("exit",()=>Xs(n))}function j(n){return Lo||(Lo=new Xt(n)),Lo}var Fl,Ul,Xt,No,$o,Ys,Dl,Lo,se=w(()=>{"use strict";Fl=120,Ul={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ul,...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(),ul(Qs));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??Fl)*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)}},No=qs($l,"runtime"),$o=qs(No,"provider-health.json"),Ys=!1,Dl=null;Lo=null});import{existsSync as ri,mkdirSync as Hl,readFileSync as zl,writeFileSync as Bl}from"fs";import{join as si}from"path";import{HOME_DIR as Jl}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=Uo(o,Wl),s=Uo(o,Kl),a=Uo(o,Gl);(r||s||a)&&$e.set(n,{provider:n,remaining:ni(r),limit:ni(s),reset:Ql(a),capturedAt:Date.now()})}function Vl(n){return $e.get(n)}function Ho(){return Array.from($e.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Uo(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ni(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Ql(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=Yl(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Yl(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 Xl(){try{if(!ri(jo))return;let n=JSON.parse(zl(jo,"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;$e.set(t.provider,t)}}catch{}}function oi(){try{if($e.size===0)return;ri(Do)||Hl(Do,{recursive:!0}),Bl(jo,JSON.stringify(Array.from($e.values()),null,2),"utf-8")}catch{}}function ct(){ei||(ei=!0,Xl(),ti=setInterval(oi,6e4),ti.unref?.(),process.on("exit",oi))}var Do,jo,$e,ei,ti,Wl,Kl,Gl,xe=w(()=>{"use strict";Do=si(Jl,"runtime"),jo=si(Do,"rate-limit.json"),$e=new Map,ei=!1,ti=null,Wl=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Kl=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Gl=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return zo||(zo=new Jo),zo}function Ko(){return Bo||(Bo=new Wo),Bo}function Zl(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function ii(n){let e=Zl(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function ai(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Go(n){let e=n?.[qt];e&&en().release(e)}function ci(n,e){let t=ii(n),o=n?.[qt],r=t?Ko().get(t)!==void 0:!1;!o&&!r||(t&&Ko().bind(t,e),ai(n,e))}function ql(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let c=o.count(i);c<s&&(r=i,s=c)}return r}function li(n,e,t){let o=ii(n),r=Ko(),s=en(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let c=r.get(o);if(c&&c!==e){let l=t.resolve(c);l?(i=l,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${l}`)):r.unbind(o)}else c&&(i=e)}if(!i){let c=s.count(e);if(c>=a){let l=ql(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 ai(n,i),i}var Jo,Wo,zo,Bo,qt,tn=w(()=>{"use strict";Jo=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()}},Wo=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()}},zo=null,Bo=null;qt="__concurrencyLease"});async function D(n){let e=await n.text();return eu(e,n.status)}function eu(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 ui(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 tu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function nn(n){for(let e of tu(n))if(e.startsWith("response."))return!0;return!1}var Fe,Vo=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})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",c,l,u,p,d="",f=new Map,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}]})}
|
|
4
|
+
`);a=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Ds(e,t,s,u):s===o.maxStreamChunks&&e.info({debug_log:!0,reqId:t,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${o.maxStreamChunks}]`}),s++)}a.trim()&&(s<o.maxStreamChunks&&Ds(e,t,s,a.trim()),s++),Fs(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Fs(e,t,s)}finally{r.releaseLock()}})()}var wl,Pl,Le,wo,rt=w(()=>{"use strict";wl=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Pl=/token|secret|credential|passwd|password/i,Le={maxBodyLength:4096,maxStreamChunks:100},wo=!1});function Js(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([c,u])=>{u&&s.set(c,u)});let a,i=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),i.addEventListener("abort",u),a=c.signal}else a=i;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a,...t.redirect?{redirect:t.redirect}:{}};return t.dispatcher?l.dispatcher=t.dispatcher:t.httpsProxy&&(l.dispatcher=G(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:Wt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Al(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function Al(n){if(!(typeof n!="string"||!n.trim()))try{let e=new URL(n);return e.username||e.password?(e.username="",e.password="",`${e.toString()} (credentials redacted)`):e.toString()}catch{return"[invalid proxy URL]"}}var Ws=w(()=>{q();rt()});function Il(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function Ks(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function Eo(n){if(Ks(n))return"pending";let e=!1,t=!1;for(let o of n.split(`
|
|
5
|
+
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(Ol.some(s=>r.includes(s))){e=!0;break}Ml.some(s=>r.includes(s))&&(t=!0)}}return e||Il(n)?"content":t?"empty":"pending"}async function Gs(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,l=Date.now()+t,c=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=l-Date.now(),p=Symbol("timeout"),d,f=o.read(),g=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),g===p)return c(Eo(a)==="content"?"content":"pending",Gt(o,f));if(g.done){a+=r.decode();let m=Eo(a);return c(m==="empty"?"empty":"pending",null)}if(!g.value)continue;s.push(g.value),i+=g.value.byteLength,a+=r.decode(g.value,{stream:!0});let h=Eo(a);if(h==="content")return c("content",Gt(o));if(h==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if(Ks(a)||i>=e)return c("pending",Gt(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function Gt(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function Qs(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var Ol,Ml,Vs=w(()=>{"use strict";Ol=["content_block_start","content_block_delta","content_block_stop"];Ml=["message_stop","response.completed","response.incomplete","[DONE]"]});function Ll(n,e){return`${n.name}|${e?.name??""}`}function Ao(n){return n.__ccrPluginRequestState??={budgets:new Map}}function $e(n,e,t){let o=Ao(n),r=Ll(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function Oo(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:($e(n,e,o).terminalError=t,!0)}var Ys=w(()=>{"use strict"});var Io=w(()=>{"use strict"});import $l from"fastify";function Xs(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var st,Nl,Lo,Qt=w(()=>{"use strict";Io();st=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,l=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>l(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>l(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>l(()=>{s.routes.push(u)}),registerConfigProtector:u=>l(()=>{s.protectors.push(u)}),registerUiCard:u=>l(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>l(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let h of this.plugins.values()){for(let m of s.runtimes.keys())if(h.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(h.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(h=>[...s.transformers].map(([m,y])=>{if(h.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:h,name:m,value:h.preparePluginTransformer(y)}})),g=[];try{for(let h of f)g.push(h),h.service.registerTransformer(h.name,h.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(h){for(let m of g)m.service.removeTransformer(m.name);throw a="aborted",h}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,l)=>{if(l==="route")return u=>(r.push(u),s);if(o.has(String(l)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:l==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(l).toUpperCase(),url:u,handler:d??p}),s);let c=Reflect.get(i,l);return typeof c=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(l)}`)}:c}}),a=$l({logger:!1});try{for(let i of e){let l=i(s);l!==s&&await l}for(let i of this.plugins.values())for(let l of i.preparedRoutes)a.route(l);for(let i of r){let l=Array.isArray(i.method)?i.method:[i.method];for(let c of l)if(t.hasRoute({method:c,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${c} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},Nl=new st,Lo=()=>Nl});function Zs(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function ve(n,e,t,o,r){let s;try{s=n.classifyError?.(e,t,o)}catch{}let a=s&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(s.code)?s.code:"plugin_upstream_error",i=s?{...s,code:a,message:`Provider plugin request failed (${a}).`}:e===0?Ul(r):{code:a,message:"Provider plugin returned an invalid upstream response.",httpStatus:e>=400&&e<=599?e:502,retryable:e>=500};try{await n.noteUpstreamError?.(i)}catch{}let l=Xs(n.name,i);return l.isRateLimit=i.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function Ul(n){let e=[n?.causeCode,n?.causeDetail].filter(Boolean).join(" ");return{code:"plugin_network_error",message:e?`Provider plugin network failure (${e}).`:n?.errorName?`Provider plugin network failure (${n.errorName}).`:"Provider plugin network failure.",httpStatus:502,retryable:!0}}var qs=w(()=>{"use strict";Qt()});var Vt,$o=w(()=>{Vt="2.3.2430"});var ei={};vo(ei,{getFallbackPromotionStore:()=>Ne,resetFallbackPromotionStore:()=>jl});function Ne(n){return xe||(xe=new No,n&&xe.configure(n)),xe}function jl(){xe&&(xe.clearAll(),xe=null)}var Fl,No,xe,Yt=w(()=>{"use strict";re();Fl=600*1e3,No=class{promotions=new Map;enabled=!0;ttlMs=Fl;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),l=`${r},${s}`;this.promotions.set(i,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...c]=a.promotedModel.split(","),u=c.join(",");if(!H().isAvailable(l,u))return this.promotions.delete(s),null;let d=r.find(g=>g.name.toLowerCase()===l.toLowerCase()),f=d?.models?.find(g=>String(g).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});import{existsSync as oi,mkdirSync as Hl,readFileSync as zl,writeFileSync as Bl}from"fs";import{join as ri}from"path";import{HOME_DIR as Jl}from"@wengine-ai/claude-code-router-shared";function Ql(n){try{if(!oi(Fo))return;let e=JSON.parse(zl(Fo,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastSuccessTime:o.lastSuccessTime,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function ni(n){try{let e=n.getAllStates();if(e.length===0)return;oi(Do)||Hl(Do,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));Bl(Fo,JSON.stringify(t,null,2),"utf-8")}catch{}}function jo(){if(ti)return;ti=!0;let n=H();Ql(n),Gl=setInterval(()=>ni(n),6e4),process.on("exit",()=>ni(n))}function H(n){return Uo||(Uo=new Xt(n)),Uo}var Wl,Kl,Xt,Do,Fo,ti,Gl,Uo,re=w(()=>{"use strict";Wl=120,Kl={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Xt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Kl,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.lastSuccessTime=Date.now(),r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(Yt(),_l(ei));o().clearByPrimary(e,t)}catch{}}recordFailure(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s||(s={provider:e,model:t,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(r,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=o,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,t){let o=this.getKey(e,t);if(o)return this.states.get(o)}isAvailable(e,t,o=!1){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let s=this.getState(e,t);return s?s.status==="open"&&s.rateLimitUntil?!(Date.now()<s.rateLimitUntil):s.status==="open"&&o&&Date.now()-Math.max(s.lastFailureTime,s.lastProbeTime)>=this.config.probeIntervalMinutes*6e4?(s.status="half-open",s.successCount=0,s.lastProbeTime=Date.now(),!0):s.status!=="open":!0}getPriority(e,t){if(!this.config.enabled)return 0;if(!this.getKey(e,t))return 2;let r=this.getState(e,t);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&e.push(t);return e}recordProbeAttempt(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&(r.lastProbeTime=Date.now())}markParkedUntil(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s&&(!Number.isFinite(o)||o<=Date.now()||s.rateLimitUntil&&s.rateLimitUntil>=o||(s.rateLimitUntil=o))}getHalfOpenModels(){let e=[];for(let[t,o]of this.states)o.status==="half-open"&&e.push(t);return e}forceOpen(e,t,o){if(!this.config.enabled)return;let r=this.getKey(e,t);if(!r)return;let s=this.states.get(r);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=o,s.lastProbeTime=0):(s={provider:e,model:t,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o},this.states.set(r,s))}markRateLimited(e,t,o,r){if(!this.config.enabled)return;let s=this.getKey(e,t);if(!s)return;let a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=r||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,a));let i=(o??Wl)*1e3;a.rateLimitUntil=Date.now()+i}getRateLimitedModels(){let e=[];for(let[t,o]of this.states)o.status==="open"&&o.rateLimitUntil&&e.push(t);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,t){let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);r&&r.status==="open"&&(r.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,t){let o=this.getKey(e,t);o&&this.states.delete(o)}getAllStates(){return Array.from(this.states.values())}restore(e){let t=this.getKey(e.provider,e.model);t&&this.states.set(t,{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Do=ri(Jl,"runtime"),Fo=ri(Do,"provider-health.json"),ti=!1,Gl=null;Uo=null});import{existsSync as li,mkdirSync as Vl,readFileSync as Yl,writeFileSync as Xl}from"fs";import{join as ui}from"path";import{HOME_DIR as Zl}from"@wengine-ai/claude-code-router-shared";function it(n,e,t){let o=i=>{if(t instanceof Headers)return t.get(i);let l=Object.keys(t).find(c=>c.toLowerCase()===i);return l?t[l]:null},r=Ho(o,ql),s=Ho(o,eu),a=Ho(o,tu);(r||s||a)&&Ue.set(n,{provider:n,remaining:ai(r),limit:ai(s),reset:ou(a),capturedAt:Date.now()})}function nu(n){return Ue.get(n)}function Jo(){return Array.from(Ue.values())}function Zt(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function Ho(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ai(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function ou(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):t>1e9?Math.floor(t):Math.floor(Date.now()/1e3+t);let o=Date.parse(e);if(Number.isFinite(o))return Math.floor(o/1e3);let r=ru(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function ru(n){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,t=0,o=!1;for(let r of n.matchAll(e)){o=!0;let s=Number(r[1]),a=r[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":t+=s;break;case"s":t+=s*1e3;break;case"m":t+=s*60*1e3;break;case"h":t+=s*60*60*1e3;break;case"d":t+=s*24*60*60*1e3;break}}return o?t:null}function su(){try{if(!li(Bo))return;let n=JSON.parse(Yl(Bo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Ue.set(t.provider,t)}}catch{}}function ci(){try{if(Ue.size===0)return;li(zo)||Vl(zo,{recursive:!0}),Xl(Bo,JSON.stringify(Array.from(Ue.values()),null,2),"utf-8")}catch{}}function at(){si||(si=!0,su(),ii=setInterval(ci,6e4),ii.unref?.(),process.on("exit",ci))}var zo,Bo,Ue,si,ii,ql,eu,tu,Se=w(()=>{"use strict";zo=ui(Zl,"runtime"),Bo=ui(zo,"rate-limit.json"),Ue=new Map,si=!1,ii=null,ql=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],eu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],tu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function en(){return Wo||(Wo=new Go),Wo}function Vo(){return Ko||(Ko=new Qo),Ko}function iu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function di(n){let e=iu(n);if(!e)return"";let t=typeof n?.modelFamily=="string"?n.modelFamily:"",o=typeof n?.scenarioType=="string"&&n.scenarioType?n.scenarioType:"default";return`${e}:${t}:${o}`}function pi(n,e){let t=en(),o=n?.[qt];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[qt]=t.acquire(e)}function Yo(n){let e=n?.[qt];e&&en().release(e)}function fi(n,e){let t=di(n),o=n?.[qt],r=t?Vo().get(t)!==void 0:!1;!o&&!r||(t&&Vo().bind(t,e),pi(n,e))}function au(n,e,t){let o=en(),r=null,s=1/0;for(let a of e){if(!a||typeof a!="string")continue;let i=t(a);if(!i||i===n)continue;let l=o.count(i);l<s&&(r=i,s=l)}return r}function mi(n,e,t){let o=di(n),r=Vo(),s=en(),a=Number.isFinite(t.threshold)&&t.threshold>0?Math.floor(t.threshold):3,i;if(o){let l=r.get(o);if(l&&l!==e){let c=t.resolve(l);c?(i=c,t.log?.(`Concurrency priority: session slot ${o} sticking to bound model ${c}`)):r.unbind(o)}else l&&(i=e)}if(!i){let l=s.count(e);if(l>=a){let c=au(e,t.fallbackModels,t.resolve);c&&(i=c,t.log?.(`Concurrency priority: model ${e} has ${l} in-flight request(s) (>= ${a}); assigning ${o?`session slot ${o} `:"request "}to overflow model ${c}`))}i=i||e,o&&r.bind(o,i)}return pi(n,i),i}var Go,Qo,Wo,Ko,qt,tn=w(()=>{"use strict";Go=class{leases=new Map;nextId=1;acquire(e){let t={id:this.nextId++,key:e,createdAt:Date.now(),released:!1};return this.leases.set(t.id,t),t}release(e){!e||e.released||(e.released=!0,this.leases.delete(e.id))}prune(){let e=Date.now();for(let[t,o]of this.leases)e-o.createdAt>18e5&&this.leases.delete(t)}count(e){this.prune();let t=0;for(let o of this.leases.values())o.key===e&&t++;return t}clear(){this.leases.clear()}},Qo=class{bindings=new Map;get(e){let t=this.bindings.get(e);if(t){if(Date.now()-t.updatedAt>864e5){this.bindings.delete(e);return}return t.updatedAt=Date.now(),this.bindings.delete(e),this.bindings.set(e,t),t.modelKey}}bind(e,t){for(this.bindings.delete(e),this.bindings.set(e,{modelKey:t,updatedAt:Date.now()});this.bindings.size>2e3;){let o=this.bindings.keys().next().value;if(o===void 0)break;this.bindings.delete(o)}}unbind(e){this.bindings.delete(e)}clear(){this.bindings.clear()}},Wo=null,Ko=null;qt="__concurrencyLease"});async function j(n){let e=await n.text();return cu(e,n.status)}function cu(n,e){let t=n.replace(/^/,"").trim();try{return JSON.parse(t)}catch{let o=t.length>200?`${t.slice(0,200)}...`:t,r=e!==void 0?` (HTTP ${e})`:"";throw new Error(`Upstream returned a non-JSON response${r}: ${o||"(empty body)"}`)}}function gi(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function ct(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function pe(n){if(!n.body||n.body.locked)return null;let[e,t]=n.body.tee(),o=e.getReader(),r=new TextDecoder,s="";try{for(let a=0;a<8;a++){let{value:i,done:l}=await o.read();if(l||(i&&(s+=r.decode(i,{stream:!0})),ct(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:ct(s)}}async function me(n){try{let e=await n.text();if(ct(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var V=w(()=>{"use strict"});function lu(n){let e=new Set;for(let t of n.split(/\r?\n/)){let o=t.replace(/\\"/g,'"');for(let s of o.matchAll(/"type"\s*:\s*"(response\.[A-Za-z0-9_.]+)"/g))e.add(s[1]);let r=t.match(/^event:\s*(response\.[A-Za-z0-9_.]+)/);r&&e.add(r[1])}return e}function nn(n){for(let e of lu(n))if(e.startsWith("response."))return!0;return!1}var De,Xo=w(()=>{"use strict";V();De=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role==="system")return;if(Array.isArray(r.content)){let i=r.content.map(l=>this.normalizeRequestContent(l,r.role)).filter(l=>l!==null);i.length>0?r.content=i:delete r.content}if(r.role==="tool"){let i={...r};i.type="function_call_output",i.call_id=r.tool_call_id,i.output=r.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}let{thinking:s,...a}=r;r.role==="assistant"&&a.content===void 0||t.push(a)}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}r?.body&&(e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers}))}if(o.includes("application/json")){let r=await pe(e);if(r?.isSSE&&r.body){let s=new Response(r.body,{status:e.status,statusText:e.statusText,headers:new Headers({...Object.fromEntries(e.headers.entries()),"content-type":"text/event-stream"})});return this.transformResponseOut(s,t)}if(r?.body)e=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else if(r===null){let s=await me(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await j(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",l=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=l.decode(p,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}}finally{a.releaseLock()}return r.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")?new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):nn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",l,c,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(S,I=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[{index:0,delta:S,finish_reason:I}]})}
|
|
6
6
|
|
|
7
|
-
`))},v=
|
|
7
|
+
`))},v=S=>{if(!S)return;let I=_.getCacheReadInputTokens(S),M=typeof S.input_tokens=="number"?S.input_tokens:void 0,N=_.getCacheCreationInputTokens(S);T.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[],usage:{prompt_tokens:M,completion_tokens:typeof S.output_tokens=="number"?S.output_tokens:void 0,total_tokens:S.total_tokens,prompt_tokens_details:{cached_tokens:I,cache_creation_tokens:N},cache_read_input_tokens:I,cache_creation_input_tokens:N}})}
|
|
8
8
|
|
|
9
|
-
`))},S
|
|
9
|
+
`))},P=S=>{m||(m=!0,T.enqueue(r.encode(`data: ${JSON.stringify({error:{message:S,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
|
|
10
10
|
|
|
11
|
-
`)))},
|
|
11
|
+
`)))},E=S=>{y||(y=!0,v(u),x({},S))},R=()=>{b||(b=!0,T.enqueue(r.encode(`data: [DONE]
|
|
12
12
|
|
|
13
|
-
`)))},
|
|
13
|
+
`)))},A=(S,I)=>{let M=S?.call_id||S?.id||(I!==void 0?`idx_${I}`:void 0);if(!M)return h++;let N=f.get(M);if(N!==void 0)return N;let L=h++;return f.set(M,L),S?.call_id&&S?.id?(f.set(S.id,L),I!==void 0&&f.set(`idx_${I}`,L)):S?.id&&I!==void 0&&f.set(`idx_${I}`,L),L},D=S=>{let I=!1;for(let M of Array.isArray(S)?S:[])if(M?.type==="function_call"){d="tool";let N=A(M,void 0),L=M.call_id||M.id;L&&g.set(N,L),x({role:"assistant",tool_calls:[{index:N,id:L,type:"function",function:{name:M.name||"",arguments:typeof M.arguments=="string"?M.arguments:""}}]}),I=!0}else if(M?.type==="message")for(let N of Array.isArray(M.content)?M.content:[])N?.type==="output_text"&&typeof N.text=="string"&&N.text.trim().length>0&&(d="text",x({role:"assistant",content:N.text}),I=!0);return I},C=S=>{switch(S?.response?.model&&(l=S.response.model),S?.response?.id&&(c=S.response.id),S?.type){case"response.output_item.added":{let I=S.item;if(I?.type!=="function_call")return;d="tool";let M=A(I,S.output_index),N=I.call_id||I.id;N&&g.set(M,N),x({role:"assistant",tool_calls:[{index:M,id:N,type:"function",function:{name:I.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let I=A({id:S.item_id},S.output_index);d="tool";let M=g.get(I);x({tool_calls:[{index:I,...M?{id:M,type:"function"}:{},function:{arguments:typeof S.delta=="string"?S.delta:""}}]});return}case"response.output_text.annotation.added":{let I=S.annotation;if(!I)return;d="annotation",x({annotations:[{type:"url_citation",url_citation:{url:I.url||"",title:I.title||"",content:"",start_index:I.start_index||0,end_index:I.end_index||0}}]});return}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;d="thinking",x({thinking:{content:S.delta}});return}case"response.output_text.delta":{if(typeof S.delta!="string"||S.delta.length===0)return;d="text";let I=p!==S.item_id;p=S.item_id;let M={content:S.delta};I&&(M.role="assistant"),x(M);return}case"response.completed":{u=S.response?.usage;let I=Array.isArray(S.response?.output)?S.response.output:[],M=I.some(N=>N?.type==="function_call");if(d===""&&D(I),!M&&d===""){let N=String(S.response?.incomplete_details?.reason??"");P(I.length===0&&!N?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${N||"empty"})`);return}E(d==="tool"||M?"tool_calls":"stop");return}case"response.incomplete":{u=S.response?.usage;let I=String(S.response?.incomplete_details?.reason??"");d===""&&D(Array.isArray(S.response?.output)?S.response.output:[]);let M=I==="max_output_tokens"||I==="max_tokens";if(d===""){P(`Upstream Responses stream produced no content (${I||"incomplete"})`);return}E(M?"length":I==="content_filter"?"content_filter":"stop");return}case"response.failed":{let I=S.response?.error||S.error||void 0;P(I?.message||"Upstream Responses stream failed before completing");return}case"error":{P(S.error?.message||S.message||"Upstream Responses stream error");return}default:return}},O=e.getReader();(async()=>{try{for(;;){let{done:S,value:I}=await O.read();if(S)break;i+=o.decode(I,{stream:!0});let M=i.split(/\r?\n/);i=M.pop()||"";for(let N of M){let L=N.trim();if(!L||L.startsWith(":")||L.startsWith("event:")||!L.startsWith("data:"))continue;let F=L.slice(5).trim();if(!F)continue;if(F==="[DONE]"){R();continue}let J;try{J=JSON.parse(F)}catch{continue}C(J)}}if(i+=o.decode(),i.trim().startsWith("data:")){let S=i.trim().slice(5).trim();if(S&&S!=="[DONE]")try{C(JSON.parse(S))}catch{}}!m&&!y&&(d===""?P("Upstream Responses stream ended before any output"):E(d==="tool"?"tool_calls":"stop")),m||R()}catch(S){console.error("Responses\u2192Chat stream error:",S);try{T.error(S)}catch{}return}finally{try{O.releaseLock()}catch{}}try{T.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:g}=await a.read();if(g||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),nn(i)||i.includes("message_start")||i.includes("content_block_start")||i.includes("chat.completion.chunk")||/^\s*[{[]/.test(i)))break}i+=new TextDecoder().decode()}finally{a.releaseLock()}r.cancel().catch(()=>{});let l=i.includes("message_start")||i.includes("content_block_start"),c=i.includes("chat.completion.chunk");if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")||nn(i))return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});if(c&&!l){let d=this.convertOpenAIChatStreamToResponsesAPI(s,t);return new Response(d,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let p=this.convertAnthropicStreamToResponsesAPI(s,t);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let r=await j(e);return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i=0,l=!1,c=!1,u="",p=-1,d=[],f=(h,m)=>r.encode(`event: ${h}
|
|
14
14
|
data: ${JSON.stringify(m)}
|
|
15
15
|
|
|
16
|
-
`),
|
|
17
|
-
`);y=x.pop()||"";for(let v of x){let
|
|
16
|
+
`),g=(h,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:h,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(h){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let T of d)if(T.type==="function_call"){let x=d.indexOf(T);h.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:x,arguments:T.arguments||""})),T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}for(let T of d)if(T.type==="message"){let x=d.indexOf(T);T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}h.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:T}=await m.read();if(k)break;y+=o.decode(T,{stream:!0});let x=y.split(`
|
|
17
|
+
`);y=x.pop()||"";for(let v of x){let P=v.trim();if(!P||P.startsWith("event:")||!P.startsWith("data:"))continue;let E=P.slice(5).trim();if(E==="[DONE]"){_({}),h.enqueue(r.encode(`data: [DONE]
|
|
18
18
|
|
|
19
|
-
`));continue}let
|
|
20
|
-
data: ${JSON.stringify(
|
|
19
|
+
`));continue}let R;try{R=JSON.parse(E)}catch{continue}l||(l=!0,h.enqueue(f("response.created",{type:"response.created",response:g("in_progress")})),h.enqueue(f("response.in_progress",{type:"response.in_progress",response:g("in_progress")})));let A=R.choices?.[0];if(!A)continue;let D=A.delta;if(D?.content){if(!c){c=!0;let C=i++,O={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(O),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:C,item:O}))}h.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:D.content}))}if(Array.isArray(D?.tool_calls))for(let C of D.tool_calls){if(C.id){u=C.id,p=i++;let O={id:C.id,type:"function_call",status:"in_progress",call_id:C.id,name:C.function?.name||"",arguments:""};d.push(O),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:O}))}if(C.function?.arguments){h.enqueue(f("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u,output_index:p,delta:C.function.arguments}));let O=d.find(S=>S.call_id===u);O&&(O.arguments+=C.function.arguments)}}A.finish_reason&&_(R)}}b||_({}),h.close()}catch(m){h.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",l="",c=-1,u="",p="",d="",f=-1,g="",h="",m=-1,y=0,b=!1,_=!1,k=!1,T=!1,x=null,v=[],P=(O,S)=>r.encode(`event: ${O}
|
|
20
|
+
data: ${JSON.stringify(S)}
|
|
21
21
|
|
|
22
|
-
`),
|
|
23
|
-
`);
|
|
22
|
+
`),E=(O,S=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:O,model:s,output:S,usage:this.buildResponsesUsage()}),R=()=>{b||(b=!0,C.enqueue(P("response.created",{type:"response.created",response:E("in_progress")})),C.enqueue(P("response.in_progress",{type:"response.in_progress",response:E("in_progress")})))},A=(O,S)=>{C.enqueue(P("response.output_item.done",{type:"response.output_item.done",output_index:O,item:{...S,status:"completed"}}))},D=O=>{if(!T){if(T=!0,_){let S=v.find(I=>I.type==="message");S&&(S.content=[{type:"output_text",text:i}],S.status="completed")}for(let S of v)S.type==="function_call"&&(S.status="completed");return P("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage:O?{...this.buildResponsesUsage(O)}:this.buildResponsesUsage()}})}},C;return new ReadableStream({async start(O){C=O;try{let S=e.getReader(),I="";for(;;){let{done:N,value:L}=await S.read();if(N)break;I+=o.decode(L,{stream:!0});let F=I.split(`
|
|
23
|
+
`);I=F.pop()||"";for(let J of F){let ce=J.trim();if(!ce||ce.startsWith("event:")||!ce.startsWith("data:"))continue;let B=ce.slice(5).trim();if(B==="[DONE]")continue;let z;try{z=JSON.parse(B)}catch{continue}if(z.type==="message_start"&&(a=z.message?.id||a,R()),z.type==="content_block_start"){let $=z.content_block;if(x=$?.type||null,$?.type==="tool_use"){u=$.id||"",p=$.name||"",d="",f=y++;let W={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:f,item:W}))}if($?.type==="thinking"&&(g=$.thinking||"",!k)){k=!0,m=y++,h=`rs_${a}`;let W={id:h,type:"reasoning",status:"in_progress",summary:[]};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:m,item:W}))}if($?.type==="text"&&(i=$?.text||"",!_)){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}}if(z.type==="content_block_delta"){let $=z.delta;if($?.type==="text_delta"){if(!_){_=!0,c=y++,l=`${a}_msg`;let W={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};v.push(W),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:W}))}i+=$.text||"",C.enqueue(P("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:$.text||""}))}$?.type==="thinking_delta"&&(g+=$.thinking||"",C.enqueue(P("response.reasoning_summary_text.delta",{type:"response.reasoning_summary_text.delta",item_id:h||`rs_${a}`,output_index:m>=0?m:0,summary_index:0,delta:$.thinking||""}))),$?.type==="input_json_delta"&&(d+=$.partial_json||"",C.enqueue(P("response.function_call_arguments.delta",{type:"response.function_call_arguments.delta",item_id:u||"call_0",output_index:f>=0?f:0,delta:$.partial_json||""})))}if(z.type==="content_block_stop"){if(x==="tool_use"&&u){C.enqueue(P("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:u,output_index:f,arguments:d}));let $=v.find(W=>W.call_id===u);$&&($.arguments=d,$.status="completed"),$&&A(f,$)}if(x==="text"&&_){C.enqueue(P("response.output_text.done",{type:"response.output_text.done",item_id:l,output_index:c,content_index:0,text:i}));let $=v.find(W=>W.type==="message");$&&($.content=[{type:"output_text",text:i}],A(c,$))}if(x==="thinking"&&k){let $=v.find(W=>W.type==="reasoning");$&&($.summary=[{type:"summary_text",text:g}],A(m,$))}x=null}if(z.type==="message_delta"){let $=D(z.usage);$&&C.enqueue($)}if(z.type==="message_stop"){let $=D();$&&C.enqueue($),C.enqueue(r.encode(`data: [DONE]
|
|
24
24
|
|
|
25
|
-
`))}}}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 Qo,Y,on=w(()=>{"use strict";Qo=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 Qo(100)});import{existsSync as mi,mkdirSync as nu,readFileSync as ou,writeFileSync as ru}from"fs";import{join as gi}from"path";import{HOME_DIR as su}from"@wengine-ai/claude-code-router-shared";function Zo(n,e){n&&Ue.set(n,{...e,provider:n,capturedAt:Date.now()})}function rn(n){let e=Ue.get(n);return e?{...e}:void 0}function qo(){return Array.from(Ue.values()).map(n=>({...n}))}function iu(){try{if(!mi(Xo))return;let n=JSON.parse(ou(Xo,"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 fi(){try{if(Ue.size===0)return;mi(Yo)||nu(Yo,{recursive:!0}),ru(Xo,JSON.stringify(Array.from(Ue.values()),null,2),"utf-8")}catch{}}function ut(){di||(di=!0,iu(),pi=setInterval(fi,6e4),pi.unref?.(),process.on("exit",fi))}var Yo,Xo,Ue,di,pi,De=w(()=>{"use strict";Yo=gi(su,"runtime"),Xo=gi(Yo,"quota-store.json"),Ue=new Map,di=!1,pi=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!au.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 au,je=w(()=>{"use strict";au=/^[A-Za-z0-9_-]+$/});import{existsSync as _i}from"fs";import{readFile as cu,readdir as lu}from"fs/promises";import{homedir as uu}from"os";import{isAbsolute as du,join as dt,normalize as pu}from"path";import{openSqliteDatabase as fu}from"@wengine-ai/claude-code-router-shared";function Tu(){if(He.size<=hi)return;let n=[...He.keys()].slice(0,He.size-hi);for(let e of n)He.delete(e)}function vu(){if(ze.size<=yi)return;let n=[...ze].slice(0,ze.size-yi);for(let e of n)ze.delete(e)}function xu(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 Cu(n,e){let t;try{t=fu(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 Su(n,e){let t;try{t=await lu(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(_i(s))try{let a=JSON.parse(await cu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function bi(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=xu(e);if(r.length===0)return null;let s=dt(mu(),gu),a=dt(s,hu);if(_i(a)){let i=Cu(a,r);if(i)return i}return Su(dt(s,yu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),vu();for(let a=0;a<_u&&!r;a++)await ku(bu),r=await o()}if(!r||!du(r))return null;let s=pu(r);return He.set(e,s),Tu(),s}catch{return null}}var mu,gu,hu,yu,hi,yi,_u,bu,He,ze,ku,ki=w(()=>{"use strict";mu=()=>process.env.CCR_ZCODE_DIR||dt(uu(),".zcode"),gu="v2",hu="tasks-index.sqlite",yu="sessions",hi=500,yi=500,_u=3,bu=50,He=new Map,ze=new Set,ku=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as Ru}from"node:crypto";import{CCR_PROJECT_HEADER as er}from"@wengine-ai/claude-code-router-shared";function xi(n){return typeof n=="string"&&n.length<=wu}function Pu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of vi){let{value:t}=sn(n,e);if(!xi(t))continue;let o=ge(t);if(o)return o}}function Au(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 Ou(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function sn(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function Ti(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 tr(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Si(n){return typeof n=="string"&&Eu.includes(n)}function ju(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(Si(n?.clientType))return n.clientType;let e=Ou(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Au(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(sn(n,er).present||sn(n,"x-session-affinity").present)return"pi";if(ju(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 Ri(n){return Ci[n]}function Hu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||Ru();return n.__ccrRequestScopeId=e,e}function Ce(n,e={}){let t=Be(n),o=Ri(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Hu(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,Ti(n,er),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of vi)Ti(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function zu(){}var vi,wu,Eu,Iu,Mu,Lu,Nu,$u,Fu,Uu,Du,Ci,Je=w(()=>{"use strict";je();vi=["x-session-affinity","x-session-id","x-litellm-session-id"],wu=256;Eu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Iu={type:"claude-code",createContext(n){return tr(n,"claude-code")}},Mu={type:"zcode",createContext(n){return tr(n,"zcode")}},Lu={type:"pi",createContext(n){let e=sn(n,er),t=Pu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=xi(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Nu={type:"qwen-code",createContext(n){return tr(n,"qwen-code")}},$u={type:"opencode",createContext(){return pt("opencode")}},Fu={type:"codex",createContext(){return pt("codex")}},Uu={type:"api",createContext(){return pt("api")}},Du={type:"unknown",createContext(){return pt("unknown")}},Ci={"claude-code":Iu,zcode:Mu,pi:Lu,"qwen-code":Nu,opencode:$u,codex:Fu,api:Uu,unknown:Du}});import{get_encoding as Ju}from"tiktoken";import{readFile as nr}from"fs/promises";import{opendir as Wu,stat as Ku}from"fs/promises";import{join as or}from"path";import{CLAUDE_PROJECTS_DIR as wi,HOME_DIR as Pi,getClaudeProjectId as Ei,isZcodeProjectTakeoverActive as Gu}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Li(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=Mi[r.code]||502;throw new te(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function cn(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function mt(n){let e=cn(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function Qu(n,e){if(!e||!n)return null;let t=cn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=cn(r);if(a&&t.includes(a))return s}return null}function Yu(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function an(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function ft(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Li(n,e){let t=an(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!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=rn(s.name);if(c){let l=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,u=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(l||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function G(n,e,t,o,r,s,a){let i=an(n);if(!i)return a?null:n;let{providerName:c,routeModel:l}=i,u=ft(e,c,l);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(c,l,o,e);if(f){let h=an(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=Ne(),f=d.getPromotion(c,l,o,e);if(f){let h=an(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=rn(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,f=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||f)return null}return`${u.provider.name},${u.model}`}function Z(n,e,t,o,r,s){let a=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 Xu(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function gt(n){let e=cn(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function Ni(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Yu(e))}function $i(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function Zu(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??c??6e4,h=Ni(e,r,d),g=n.modelFamily,m=$i(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 od(){if(Se.size<=Ai)return;let n=[...Se.keys()].slice(0,Se.size-Ai);for(let e of n)Se.delete(e)}function rd(){if(We.size<=Oi)return;let n=[...We].slice(0,We.size-Oi);for(let e of n)We.delete(e)}var Mi,te,le,ln,Vu,qu,un,Se,Ai,We,Oi,ed,td,nd,Ii,Fi,Re=w(()=>{"use strict";on();se();De();Yt();tn();je();ki();Je();Mi={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||Mi[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Ju("cl100k_base"),ln=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=le.encode(s.text).length;else if(s.type==="tool_use")o+=le.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=le.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=le.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},Vu=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new te(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Fi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await bi(n.sessionId);s&&Gu(s)&&(r=Ei(s))}if(r){n.projectId=r;let s=or(Pi,r,"config.json");if(!t&&n.sessionId){let a=or(Pi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await nr(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch{}}try{let a=JSON.parse(await nr(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Ei(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})}}}};qu=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=Zu(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:Qu(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,_=Ni(e,o,b),k=$i(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"}},un=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ce(n,o.getAll());let s=await Vu(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 nr(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=ln(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 qu(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&&Xu(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]||[]];_=li(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"}},Se=new Map,Ai=1e3,We=new Set,Oi=1e3,ed=3,td=50,nd=n=>new Promise(e=>setTimeout(e,n));Ii=async n=>{let e=await Wu(wi),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=or(wi,s,`${n}.jsonl`);try{return(await Ku(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Fi=async n=>{let e=ge(n);if(!e)return null;if(Se.has(e))return Se.get(e)||null;try{let t=await Ii(e);if(!t&&!We.has(e)){We.add(e),rd();for(let o=0;o<ed&&!t;o++)await nd(td),t=await Ii(e)}return t?(Se.set(e,t),od(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
25
|
+
`))}}}R();let M=D();M&&C.enqueue(M),I="",C.close()}catch(S){C.error(S)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(c=>c.type==="message"),o;t?.content?.length&&t?.content[0].annotations&&(o=t.content[0].annotations.map(c=>({type:"url_citation",url_citation:{url:c.url||"",title:c.title||"",content:"",start_index:c.start_index||0,end_index:c.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let r=null,s=null,a=null;if(t&&t.reasoning&&(a={content:t.reasoning}),t&&t.content){let c=[],u=[];if(t.content.forEach(p=>{if(p.type==="output_text")c.push(p.text||"");else if(p.type==="output_image"){let d=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});d&&u.push(d)}else if(p.type==="output_image_base64"){let d=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});d&&u.push(d)}}),u.length>0){let p=[];c.length>0&&p.push({type:"text",text:c.join("")}),p.push(...u),r=p}else r=c.join("")}let i=(e.output??[]).filter(c=>c.type==="function_call");return i.length>0&&(s=i.map(c=>({id:c.call_id||c.id,type:"function",function:{name:c.name,arguments:c.arguments}}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:r||null,tool_calls:s,thinking:a,annotations:o},logprobs:null,finish_reason:s?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var Zo,Y,on=w(()=>{"use strict";Zo=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},Y=new Zo(100)});import{existsSync as bi,mkdirSync as uu,readFileSync as du,writeFileSync as pu}from"fs";import{join as ki}from"path";import{HOME_DIR as fu}from"@wengine-ai/claude-code-router-shared";function lt(n,e){n&&Fe.set(n,{...e,provider:n,capturedAt:Date.now()})}function rn(n){let e=Fe.get(n);return e?{...e}:void 0}function tr(){return Array.from(Fe.values()).map(n=>({...n}))}function mu(){try{if(!bi(er))return;let n=JSON.parse(du(er,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;Fe.set(t.provider,t)}}catch{}}function _i(){try{if(Fe.size===0)return;bi(qo)||uu(qo,{recursive:!0}),pu(er,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function ut(){hi||(hi=!0,mu(),yi=setInterval(_i,6e4),yi.unref?.(),process.on("exit",_i))}var qo,er,Fe,hi,yi,Ce=w(()=>{"use strict";qo=ki(fu,"runtime"),er=ki(qo,"quota-store.json"),Fe=new Map,hi=!1,yi=null});function ge(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!gu.test(e)))return e}function he(n){if(!n)return;if(typeof n=="object")return ge(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=ge(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return ge(e.slice(o+t.length))}var gu,je=w(()=>{"use strict";gu=/^[A-Za-z0-9_-]+$/});import{existsSync as xi}from"fs";import{readFile as hu,readdir as yu}from"fs/promises";import{homedir as _u}from"os";import{isAbsolute as bu,join as dt,normalize as ku}from"path";import{openSqliteDatabase as Tu}from"@wengine-ai/claude-code-router-shared";function Eu(){if(He.size<=Ti)return;let n=[...He.keys()].slice(0,He.size-Ti);for(let e of n)He.delete(e)}function Au(){if(ze.size<=vi)return;let n=[...ze].slice(0,ze.size-vi);for(let e of n)ze.delete(e)}function Ou(n){let e=n.trim();if(!e||e==="."||e===".."||/[/\\\0]/.test(e))return[];let t=e.replace(/^sess_/,"");return[...new Set([e,t,`sess_${t}`])].filter(Boolean)}function Iu(n,e){let t;try{t=Tu(n,{readonly:!0}).db;let o=t.prepare("SELECT workspace_path FROM tasks WHERE task_id = ? OR acp_session_id = ? ORDER BY updated_at DESC LIMIT 1");for(let r of e){let a=o.get(r,r)?.workspace_path;if(typeof a=="string"&&a.trim())return a.trim()}return null}catch{return null}finally{try{t?.close()}catch{}}}async function Mu(n,e){let t;try{t=await yu(n)}catch{return null}for(let o of t)for(let r of e){let s=dt(n,o,`${r}.json`);if(xi(s))try{let a=JSON.parse(await hu(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Si(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=He.get(e);if(t)return t;let o=async()=>{let r=Ou(e);if(r.length===0)return null;let s=dt(vu(),xu),a=dt(s,Su);if(xi(a)){let i=Iu(a,r);if(i)return i}return Mu(dt(s,Cu),r)};try{let r=await o();if(!r&&!ze.has(e)){ze.add(e),Au();for(let a=0;a<Ru&&!r;a++)await Pu(wu),r=await o()}if(!r||!bu(r))return null;let s=ku(r);return He.set(e,s),Eu(),s}catch{return null}}var vu,xu,Su,Cu,Ti,vi,Ru,wu,He,ze,Pu,Ci=w(()=>{"use strict";vu=()=>process.env.CCR_ZCODE_DIR||dt(_u(),".zcode"),xu="v2",Su="tasks-index.sqlite",Cu="sessions",Ti=500,vi=500,Ru=3,wu=50,He=new Map,ze=new Set,Pu=n=>new Promise(e=>setTimeout(e,n))});import{randomUUID as Lu}from"node:crypto";import{CCR_PROJECT_HEADER as nr}from"@wengine-ai/claude-code-router-shared";function Pi(n){return typeof n=="string"&&n.length<=$u}function Nu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of wi){let{value:t}=sn(n,e);if(!Pi(t))continue;let o=ge(t);if(o)return o}}function Du(n){if(typeof n=="string")return n.slice(0,1e3);if(Array.isArray(n)){let e=n.find(t=>t&&typeof t.text=="string");return e?String(e.text).slice(0,1e3):""}return""}function Fu(n){if(typeof n?.pathname=="string")return n.pathname;if(typeof n?.url!="string")return"";try{return new URL(n.url,"http://127.0.0.1").pathname}catch{return n.url}}function sn(n,e){let t=n?.headers;if(!t||typeof t!="object")return{present:!1};let o=Object.keys(t).find(s=>s.toLowerCase()===e);if(!o)return{present:!1};let r=t[o];return typeof r=="string"?{present:!0,value:r.trim()}:Array.isArray(r)&&typeof r[0]=="string"?{present:!0,value:r[0].trim()}:{present:!0}}function Ri(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function pt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function or(n,e,t=!0){let o=he(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Ai(n){return typeof n=="string"&&Uu.includes(n)}function Qu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Be(n){if(Ai(n?.clientType))return n.clientType;let e=Fu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Du(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(sn(n,nr).present||sn(n,"x-session-affinity").present)return"pi";if(Qu(t,o))return"zcode";let a=t["x-anthropic-billing-header"];if(typeof a=="string"&&a.includes("cc_version="))return"claude-code";if(o.includes("codex")||o.includes("Codex")||e.endsWith("/v1/responses"))return"codex";if(r.metadata&&typeof r.metadata=="object"&&typeof r.metadata.user_id=="string")return"claude-code";if(o.includes("opencode"))return"opencode";if(o.includes("pi-coding-agent"))return"pi";if(o.includes("QwenCode"))return"qwen-code";let i=n?.originalModel||r.model||"";return/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i.test(i)?o.includes("Anthropic/")?"pi":o.includes("claude-cli")||o.includes("Claude-CLI")?"qwen-code":typeof t["x-stainless-package-version"]=="string"?"pi":"claude-code":o.includes("claude-cli")||o.includes("Claude-CLI")?"claude-code":String(i).toLowerCase()==="ccr-codex"?"codex":e.endsWith("/v1/messages")?"api":"unknown"}function Oi(n){return Ei[n]}function Vu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||Lu();return n.__ccrRequestScopeId=e,e}function Re(n,e={}){let t=Be(n),o=Oi(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Vu(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,Ri(n,nr),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of wi)Ri(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Yu(){}var wi,$u,Uu,ju,Hu,zu,Bu,Ju,Wu,Ku,Gu,Ei,Je=w(()=>{"use strict";je();wi=["x-session-affinity","x-session-id","x-litellm-session-id"],$u=256;Uu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];ju={type:"claude-code",createContext(n){return or(n,"claude-code")}},Hu={type:"zcode",createContext(n){return or(n,"zcode")}},zu={type:"pi",createContext(n){let e=sn(n,nr),t=Nu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||he(n?.body?.metadata?.user_id),o=Pi(t)?t:void 0;return{...pt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Bu={type:"qwen-code",createContext(n){return or(n,"qwen-code")}},Ju={type:"opencode",createContext(){return pt("opencode")}},Wu={type:"codex",createContext(){return pt("codex")}},Ku={type:"api",createContext(){return pt("api")}},Gu={type:"unknown",createContext(){return pt("unknown")}},Ei={"claude-code":ju,zcode:Hu,pi:zu,"qwen-code":Bu,opencode:Ju,codex:Wu,api:Ku,unknown:Gu}});import{get_encoding as Zu}from"tiktoken";import{readFile as rr}from"fs/promises";import{opendir as qu,stat as ed}from"fs/promises";import{isAbsolute as td,join as sr}from"path";import{CLAUDE_PROJECTS_DIR as Ii,HOME_DIR as Mi,getClaudeProjectId as Li,isZcodeProjectTakeoverActive as nd}from"@wengine-ai/claude-code-router-shared";function ee(n,e,t,o){let r=Fi(e,t);if(r.code==="model_unhealthy"){let i=Q(e,t,!0);if(i)return n.log.warn(`Strict project target ${e} is in the health fail-pool; retrying it anyway (no fallback available). scenario=${o}`),i}let s=n.sessionId||n.clientContext?.stableSessionId,a=Di[r.code]||502;throw new te(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function cn(n){let e=n||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function mt(n){let e=cn(n),t=e.includes("[1m]")||e.endsWith("[1m"),o=e.replace(/\[1m\]|\[1m$/g,""),r=o.match(/^ccr-(opus|sonnet|haiku)$/i);if(r)return{family:r[1].toLowerCase(),extended:t,isCcrAlias:!0};let s=o.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||o.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:t,isCcrAlias:!1}:{family:null,extended:t,isCcrAlias:!1}}function rd(n,e){if(!e||!n)return null;let t=cn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=mt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=cn(r);if(a&&t.includes(a))return s}return null}function sd(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function an(n){if(!n?.includes(","))return null;let[e,...t]=n.split(","),o=e.trim(),r=t.join(",").trim();return!o||!r?null:{providerName:o,routeModel:r}}function ft(n,e,t){let o=n.find(s=>s.name.toLowerCase()===e.toLowerCase());if(!o||o.enabled===!1)return null;let r=o.models?.find(s=>String(s).toLowerCase()===t.toLowerCase());return r?{provider:o,model:String(r)}:null}function Fi(n,e){let t=an(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(c=>c.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(c=>String(c).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!H().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let l=rn(s.name);if(l){let c=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,u=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(c||u)return{reason:`provider "${o}" quota is exhausted`,code:"quota_exhausted"}}return{reason:`unable to resolve model "${n}"`,code:"resolution_failed"}}function Q(n,e,t,o,r,s,a){let i=an(n);if(!i)return a?null:n;let{providerName:l,routeModel:c}=i,u=ft(e,l,c);if(!u){if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(l,c,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(l,c,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=Ne(),f=d.getPromotion(l,c,o,e);if(f){let g=an(f);if(g){let h=ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(l,c,o)}}if(!t&&!H().isAvailable(u.provider.name,u.model,u.provider.apiKey?.startsWith("ccr-managed-")===!0||u.provider.api_key?.startsWith("ccr-managed-")===!0))return null;let p=rn(u.provider.name);if(p){let d=p.limitDaily!==void 0&&p.usedDailyBalance!==void 0&&p.usedDailyBalance>=p.limitDaily,f=p.totalBalance!==void 0&&p.usedBalance!==void 0&&p.usedBalance>=p.totalBalance;if(d||f)return null}return`${u.provider.name},${u.model}`}function Z(n,e,t,o,r,s){let a=[t?.[n],o?.[n]];for(let i of a)if(!(!Array.isArray(i)||i.length===0))for(let l of i){let c=Q(l,e,!1,n,void 0,void 0,s);if(c)return c}return null}function id(n){return n.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function gt(n){let e=cn(n);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(o=>o.test(e))}function ji(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,sd(e))}function Hi(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function ad(n,e,t,o,r,s,a,i,l,c,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??l??6e4,g=ji(e,r,d),h=n.modelFamily,m=Hi(d,t,c),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||g>m)&&t.extendedContext){let k=Q(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?Z("extendedContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let x=ee(n,t.extendedContext,o,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(g>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?Q(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${g}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?Z("longContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${g}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let x=ee(n,t.longContext,o,"longContext");if(x)return{model:x,scenarioType:"longContext",isFallback:!1}}n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(k=>k.type?.startsWith("web_search"))&&t.webSearch){let k=Q(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let T=i?Z("webSearch",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let x=ee(n,t.webSearch,o,"webSearch");if(x)return{model:x,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let k=Q(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let T=i?Z("think",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let x=ee(n,t.think,o,"think");if(x)return{model:x,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let k=Q(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let T=i?Z("default",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let x=ee(n,t.default,o,"default");if(x)return{model:x,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function pd(){if(we.size<=$i)return;let n=[...we.keys()].slice(0,we.size-$i);for(let e of n)we.delete(e)}function fd(){if(We.size<=Ni)return;let n=[...We].slice(0,We.size-Ni);for(let e of n)We.delete(e)}var Di,te,le,ln,od,cd,un,we,$i,We,Ni,ld,ud,dd,Ui,zi,Pe=w(()=>{"use strict";on();re();Ce();Yt();tn();je();Ci();Je();Di={provider_not_found:404,model_not_found:404,invalid_model_format:400,provider_disabled:503,model_unhealthy:503,quota_exhausted:503,resolution_failed:502,project_config_error:500,invalid_project_id:400,project_config_not_found:404},te=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||Di[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};le=Zu("cl100k_base"),ln=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=le.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=le.encode(s.text).length;else if(s.type==="tool_use")o+=le.encode(JSON.stringify(s.input)).length;else if(s.type==="tool_result"){let a=s.content;if(Array.isArray(a))for(let i of a)i?.type!=="image"&&(o+=le.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=le.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=le.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=le.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=le.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=le.encode(r.name+r.description).length),r.input_schema&&(o+=le.encode(JSON.stringify(r.input_schema)).length)}),o},od=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new te(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await zi(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Si(n.sessionId);s&&nd(s)&&(r=Li(s))}if(r){n.projectId=r;let s=sr(Mi,r,"config.json");if(!t&&n.sessionId){let a=sr(Mi,r,`${n.sessionId}.json`);try{let i=JSON.parse(await rr(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await rr(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||Li(a.projectPath)!==o))throw new te(`Project routing error: managed project id "${o}" does not match its stored project path.`,{configuredTarget:s,code:"invalid_project_id"});if(a&&a.Router&&Object.keys(a.Router).length>0)return a.Router}catch(a){if(a instanceof te)throw a;if(t&&a?.code==="ENOENT")throw new te(`Project routing error: managed project "${o}" no longer has a project config.`,{configuredTarget:s,code:"project_config_not_found"});if(!a||a.code!=="ENOENT"){let i=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: project config.json is malformed or unreadable in project "${r}". ${a.message}. Session: "${i||"unknown"}".`,{sessionId:i,configuredTarget:s,code:"project_config_error",statusCode:500})}}}};cd=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),l=i?.enableFallback===!0,c=l?i?.fallback:void 0,u=l&&!s?c||t.get("fallback"):c,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),d=C[1])}let f=typeof n.body?.model=="string"?n.body.model:"",g=f.indexOf(",")>0,m=(g?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),y,b;if(!s&&m)for(let C of a){if(C?.enabled===!1||!Array.isArray(C?.models))continue;let O=C.models.find(S=>typeof S=="string"&&S.toLowerCase()===m);if(O){y=C,b=O;break}}let{family:_,extended:k,isCcrAlias:T}=mt(n.body.model),x=i?.families?.[_||""];if(x&&i?.enableFamilyRouting&&!y){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=x.fallback;let C=ad(n,e,x,a,o,k,u,l,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(C)return{model:C.model,scenarioType:C.scenarioType}}if(g&&y&&b){let C=`${y.name},${b}`;n.body.model!==C&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${C}`),n.body.model=C)}if(n.body.model.includes(",")&&!s){let C=Q(n.body.model,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=l?Z("default",a,void 0,u,void 0,s):null;if(O)return n.log.info(`Using fallback for explicit model: ${O}`),{model:O,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let v=T&&!i?.enableFamilyRouting?null:rd(n.body.model,i?.models);if(v){let C=Q(v,a,!1,"modelMapping",l,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${v}`),{model:C,scenarioType:"modelMapping"};let O=l?Z("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let S=ee(n,v,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${v} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let P=n.clientContext,E=ji(e,o,P),R=Hi(P,void 0,i?.extendedContextThreshold);if(E>R&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${E}, estimated: ${e}, threshold: ${R}`);let C=Q(i.extendedContext,a,!1,"extendedContext",l,p,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=l?Z("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let S=ee(n,i.extendedContext,a,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext"}}}let A=P?.longContextThreshold??i?.longContextThreshold??6e4;if(E>A&&i?.longContext){n.log.info(`Using long context model due to token count: ${E}, estimated: ${e}, threshold: ${A}`);let C=Q(i.longContext,a,!1,"longContext",l,p,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=l?Z("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let S=ee(n,i.longContext,a,"longContext");if(S)return{model:S,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let C=Q(i.background,a,!1,"background",l,p,s);if(C)return{model:C,scenarioType:"background"};let O=l?Z("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let S=ee(n,i.background,a,"background");if(S)return{model:S,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&i?.webSearch){let C=Q(i.webSearch,a,!1,"webSearch",l,p,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=l?Z("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let S=ee(n,i.webSearch,a,"webSearch");if(S)return{model:S,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=Q(i.think,a,!1,"think",l,p,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=l?Z("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let S=ee(n,i.think,a,"think");if(S)return{model:S,scenarioType:"think"}}}if(i?.default){let C=Q(i.default,a,!1,"default",l,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=l?Z("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let S=Q(i.default,a,!0,"default",l,p,s);if(S)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:S,scenarioType:"default"}}if(s){let C=ee(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},un=async(n,e,t)=>{let{configService:o,event:r}=t;!n.originalModel&&n.body.model&&(n.originalModel=n.body.model),(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,o.getAll());let s=await od(n,o),a=s||o.get("Router"),i=a?.enableFallback===!0,l=o.get("providers")||[],c=!!s;n.enableFallback=i,n.strictProjectRouting=c,n.fallbackConfig=c?a?.fallback:a?.fallback||o.get("fallback");let u=n.clientContext?.usageScope==="session"?n.previousUsage??Y.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:f}=n.body,g=o.get("REWRITE_SYSTEM_PROMPT");if(g&&d.length>1&&d[1]?.text?.includes("<env>")){let h=await rr(g,"utf-8");d[1].text=`${h}<env>${d[1].text.split("<env>").pop()}`}try{let[h,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(h,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,h)).tokenCount:b=ln(p,d,f),n.tokenCount=b;let _,k=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!td(k)||!/\.(c|m)?js$/i.test(k))throw new Error(`CUSTOM_ROUTER_PATH must be an absolute .js/.cjs/.mjs path, got: ${String(k).slice(0,120)}`);let P=await import(k),E=typeof P=="function"?P:P?.default;if(typeof E!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await E(n,o.getAll(),{event:r})}catch(P){n.log.error(`failed to load custom router: ${P.message}`)}if(_)n.scenarioType="default";else{let P=await cd(n,b,o,u,s,!!s);_=P.model,n.scenarioType=P.scenarioType}let{family:T}=mt(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[x?.image,a?.image].filter((P,E,R)=>!!P&&R.indexOf(P)===E);if(v.length>0&&id(n)&&!gt(_))if(v.includes(_))n.scenarioType="image";else{let P=v.map(E=>Q(E,l,!1,"image",i,!c,c)).find(E=>!!E);if(P)n.log.info(`Using image model fallback for ${_}`),_=P,n.scenarioType="image";else{let E=i?Z("image",l,x?.fallback,n.fallbackConfig,T||void 0,c):null;if(E)n.log.info(`Using image fallback model: ${E}`),_=E,n.scenarioType="image";else if(c){let R=ee(n,v[0],l,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let P=n.scenarioType||"default",E=[...(n.familyFallback||{})[P]||[],...(n.fallbackConfig||{})[P]||[]];_=mi(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:E,resolve:R=>Q(R,l,!1,P,i,!c,c),log:R=>n.log.info(R)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(h){if(h instanceof te)throw h;if(n.log.error(`Error in router middleware: ${h.message}`),c){let m=n.sessionId||n.clientContext?.stableSessionId;throw new te(`Project routing error: router failure in project mode. ${h.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},we=new Map,$i=1e3,We=new Set,Ni=1e3,ld=3,ud=50,dd=n=>new Promise(e=>setTimeout(e,n));Ui=async n=>{let e=await qu(Ii),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=sr(Ii,s,`${n}.jsonl`);try{return(await ed(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},zi=async n=>{let e=ge(n);if(!e)return null;if(we.has(e))return we.get(e)||null;try{let t=await Ui(e);if(!t&&!We.has(e)){We.add(e),fd();for(let o=0;o<ld&&!t;o++)await dd(ud),t=await Ui(e)}return t?(we.set(e,t),pd(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function ht(n){let e=[],t=Array.isArray(n.input)?n.input:[n.input];for(let o of t)if(o.type==="function_call")e.push({role:"assistant",tool_calls:[{id:o.call_id,type:"function",function:{name:o.name,arguments:o.arguments||"{}"}}]});else if(o.type==="function_call_output")e.push({role:"tool",tool_call_id:o.call_id,content:typeof o.output=="string"?o.output:JSON.stringify(o.output)});else if(o.type==="reasoning"){let r=Array.isArray(o.summary)?o.summary.filter(s=>s.type==="summary_text"&&s.text).map(s=>s.text).join(`
|
|
26
26
|
`):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
|
|
27
|
-
${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function
|
|
28
|
-
`).some(
|
|
29
|
-
`).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=
|
|
30
|
-
`):""}async function Ui(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})),cd(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)&&$s(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>Ds(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),Gs(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!Le(a.req,i,t).refreshUsed){Le(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||dn(d),f.rawBody=d,f}if(u.ok){let d=u.headers.get("content-type")||"",f=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${f} contentType=${d} ok=${u.ok} status=${u.status} hasBody=${!!u.body}`),!f||d.includes("application/json")){let 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=dn(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();Fs(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Ji(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 Wi(n,e,t,o){n.ok||e.code(n.status);let r=ui(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=Ns(o.configService);return Us(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return D(n)}function dn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function ud(n){try{return new URL(n),!0}catch{return!1}}var sd,Ki,pn=w(()=>{"use strict";js();zt();Js();Ws();Vs();st();Io();se();xe();Yt();tn();Vo();Q();Re();q();sd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Ki=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)=>Di(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||!ud(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,rr=w(()=>{"use strict";Ge=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var ye,fn,Gi,dd,Vi,Ve=w(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",fn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Gi=["low","medium","high"],dd={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"},Vi=n=>{if(typeof n=="string")return dd[n.trim().toLowerCase()]}});var sr,Qi=w(()=>{sr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function pd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Yi(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||fn(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);Gi.includes(h)&&(p.output_config={...p.output_config||{},effort:h})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
|
|
31
|
-
|
|
32
|
-
`)}return n.tools&&n.tools.length>0&&(p.tools=
|
|
33
|
-
`);u?(
|
|
34
|
-
`),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:
|
|
35
|
-
`));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(
|
|
36
|
-
data: ${JSON.stringify(
|
|
37
|
-
|
|
38
|
-
`)),
|
|
27
|
+
${r}`}],_reasoningItem:!0})}else if(o.role){let r=o.content;Array.isArray(r)&&(r=r.map(s=>s.type==="input_text"?{type:"text",text:s.text}:s.type==="output_text"?{type:"text",text:s.text}:s.type==="input_image"?{type:"image_url",image_url:{url:s.image_url},media_type:s.mime_type}:s)),e.push({role:o.role,content:r})}n.messages=e,delete n.input,n.instructions&&typeof n.instructions=="string"&&(n.system=n.instructions,delete n.instructions),Array.isArray(n.tools)&&(n.tools=n.tools.filter(o=>o&&typeof o=="object").map(o=>o.type==="function"&&o.name&&!o.function?{type:"function",function:{name:o.name,description:o.description||"",parameters:o.parameters||{type:"object",properties:{}}}}:o.function?.name?o:o.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),n.reasoning&&typeof n.reasoning=="object"&&(n.reasoning={enabled:!0,effort:n.reasoning.effort}),delete n.store,delete n.previous_response_id,delete n.include}async function Ji(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),Ao(n);let s=_d(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&ht(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&md.test(r.model)&&await un(n,e,{configService:t.configService,tokenizerService:t.tokenizerService});let a=n.provider;if(!a&&r?.model){let c=r.model.split(",");c.length>1&&(a=c[0],r.model=c.slice(1).join(","))}let i=a?t.providerService.getProvider(a):void 0;if(!i&&r?.model){let c=t.providerService.resolveModelRoute(r.model);c&&(i=c.provider,r.model=c.targetModel)}if(!i&&r?.model){let u=t.configService.get("Router")?.default;if(u&&u.includes(",")){let[p,...d]=u.split(","),f=t.providerService.getProvider(p);f&&(i=f,r.model=d.join(","))}}if(n.originalModel||(n.originalModel=r?.model),!i)throw K(`Provider '${a}' not found`,404,"provider_not_found");n.provider=i.name||a;let l=o.endPoint==="/v1/messages"&&s;s&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true"),n.isCodexOnMessagesEndpoint=l;try{o.endPoint==="/v1/responses"&&r.input&&!r.messages&&ht(r);let c={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:Gi(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await Ki(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let T=JSON.stringify(k.content??"");y.has(T)||(y.add(T),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await Qi(u,p,i,t,d,o,c);try{i?.baseUrl&&f?.headers&&it(a,i.baseUrl,f.headers)}catch{}let g=await Vi(u,f,i,o,d,c);g=await Wi(r,g,i.name||a);let h=Yi(g,e,r,t);try{let m=r.model||n.originalModel;a&&m&&H().recordSuccess(a,m)}catch{}return h}catch(c){if(c instanceof te)throw c;if(!Oo(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await Ji(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await gd(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function Wi(n,e,t){if(!e?.body||!(e.headers?.get?.("content-type")??"").includes("text/event-stream")&&!n?.stream)return e;let s=e.body.getReader(),a=new TextDecoder,i=[],l="";for(let d=0;d<8;d++){let f=await s.read();if(f.done||(f.value&&(i.push(f.value),l+=a.decode(f.value,{stream:!0})),l.split(`
|
|
28
|
+
`).some(g=>g.startsWith("data:"))))break}if(l+=a.decode(),i.length===0)throw s.releaseLock(),K(`Provider returned empty streaming response from ${t}`,400,"provider_response_error");if(l.includes("event: error")){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned error in SSE stream: ${d}`,400,"provider_response_error")}if(l.split(`
|
|
29
|
+
`).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw K(`Provider ${t} returned streaming response with no SSE data lines: ${d}`,400,"provider_response_error")}let u=new ReadableStream({start:d=>{for(let g of i)d.enqueue(g);let f=()=>{s.read().then(({done:g,value:h})=>{g?d.close():(d.enqueue(h),f())}).catch(g=>d.error(g))};f()},cancel:()=>{s.cancel()}}),p=await Gs(u);if(p.verdict==="empty")throw K(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(Qs(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function gd(n,e,t,o,r){let s=n.scenarioType||"default",a=n.familyFallback,i=n.modelFamily,l=n.strictProjectRouting?n.fallbackConfig:n.fallbackConfig??t.configService.get("fallback"),c=H(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&dn(r.rawBody)||r?.message&&dn(r.message);if(u&&p&&(f?(c.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):c.recordFailure(u,p,r?.message),d.add(`${u},${p}`),t.recordUsage?.({provider:u,model:p,originalModel:n.originalModel||p,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let h=b=>{let[_,...k]=b.split(","),T=_?.trim(),x=k.join(",").trim();return!T||!x?null:{provider:T,model:x,key:`${T},${x}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(x=>x.type==="image"||x.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=h(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let T=t.providerService.getProviders(),x=ft(T,k.provider,k.model);if(!x){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let v=x.provider.name,P=x.model;if(!c.isAvailable(v,P,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let E=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(E&&$e(n,E,{name:v}).terminalError)continue;let R;for(let A=1;A<=2;A++)try{n.log.info(`Trying fallback model: ${v},${P}${A>1?" (retry)":""}`);let D={...n.body};D.model=P;let C={...n,provider:v,body:D},O=x.provider,S={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:Gi(C,o,C.codexDetected===!0)},{requestBody:I,config:M,bypass:N}=await Ki(D,O,o,n.headers,S),L=await Qi(I,M,O,t,N,o,S);try{O?.baseUrl&&L?.headers&&it(v,O.baseUrl,L.headers)}catch{}let F=await Vi(I,L,O,o,N,S);return F=await Wi(D,F,v),n.log.info(`Fallback model ${v},${P} succeeded`),c.recordSuccess(v,P),u&&p&&!n.strictProjectRouting&&(Ne().promote(u,p,s,v,P),n.log.info(`Promoted fallback model ${v},${P} for ${u},${p}:${s}`),f?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(c.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=v,n.body=D,fi(n,`${v},${P}`),Yi(F,e,D,t)}catch(D){if(R=D,Oo(n,E,D,{name:v}))break;if(A===1){n.log.warn(`Fallback model ${v},${P} failed, retrying once: ${D.message}`);continue}}c.recordFailure(v,P,R?.message),n.log.warn(`Fallback model ${v},${P} failed after retry: ${R?.message}`),t.recordUsage?.({provider:v,model:P,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:R?.message||String(R),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function Ki(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw K("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=$e(r.req,s,e).terminalError;if(u)throw u;await s.ensureUsable?.()}let a=JSON.parse(JSON.stringify(n)),i=a?.system;if(typeof i=="string"&&i.includes("cch="))a.system=i.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(i))for(let u=0;u<i.length;u++){let p=i[u],d=typeof p=="string"?p:p?.text??"";if(d.includes("cch=")){let f=d.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof p=="string"?i[u]=f:typeof p?.text=="string"&&(p.text=f)}}let l={},c=!1;if(c=hd(e,t,n),c&&(o instanceof Headers?o.delete("content-length"):delete o["content-length"],l.headers=o),!c&&typeof t.transformRequestOut=="function"){let u=await t.transformRequestOut(a);u.body?(a=u.body,l=u.config||{}):a=u}if(!c&&e.transformer?.use?.length)for(let u of e.transformer.use){if(!u||typeof u.transformRequestIn!="function")continue;let p=await u.transformRequestIn(a,e,r);p.body?(a=p.body,l={...l,...p.config}):a=p}if(!c&&e.transformer?.[n.model]?.use?.length)for(let u of e.transformer[n.model].use)!u||typeof u.transformRequestIn!="function"||(a=await u.transformRequestIn(a,e,r));return{requestBody:a,config:l,bypass:c}}function hd(n,e,t){return e.endPoint==="/v1/chat/completions"&&Array.isArray(t?.system)?!1:n.transformer?.use?.length===1&&n.transformer.use[0].name===e.name&&(!n.transformer?.[t.model]?.use.length||n.transformer?.[t.model]?.use.length===1&&n.transformer?.[t.model]?.use[0].name===e.name)}function yd(n,e){if(e?.clientType!=="pi")return;let t=e?.clientContext?.stableSessionId;if(!(typeof t!="string"||!t)){for(let o of Object.keys(n))o.toLowerCase()==="x-litellm-session-id"&&delete n[o];n["x-litellm-session-id"]=t}}function Gi(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function _d(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function Qi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>Bi(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):Bi(n,e,t,o,r,s,a)}function Ke(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
|
|
30
|
+
`):""}async function Bi(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);i&&(await i.ensureUsable?.(),await i.lockUpstream?.(e,t));let l=e.url||new URL(t.baseUrl);if(!e.TIMEOUT){let d=o.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(r&&typeof s.auth=="function"){let d=await s.auth(n,t,a);if(d.body){n=d.body;let f=e.headers||{};d.config?.headers&&(f={...f,...d.config.headers},delete f.host,delete d.config.headers),e={...e,...d.config,headers:f}}else n=d}let c={Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}};i&&(c=await i.signRequest({headers:c,requestBody:n,provider:t,config:e})),yd(c,a?.req);for(let d in c)(c[d]==="undefined"||["authorization","Authorization"].includes(d)&&c[d]?.includes("undefined"))&&delete c[d];!i?.suppressDebugLog&&Jt(o.configService)&&Hs(o.log,a.req.id,{url:String(l),headers:c,body:n});let u,p=()=>Js(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:i?void 0:de(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await ve(i,0,void 0,Ke(n),Zs(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!$e(a.req,i,t).refreshUsed){$e(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),c=await i.signRequest({headers:c,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(g){throw i?await ve(i,u.status,void 0,Ke(n)):g}if(i){let g=await ve(i,u.status,d,Ke(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${g.code}`),g}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let f=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||dn(d),f.rawBody=d,f}if(u.ok){let d=u.headers.get("content-type")||"",f=n.stream===!0;if(o.log.info(`[hidden-error-check] provider=${t.name} model=${n.model} stream=${n.stream} isStreamRequest=${f} contentType=${d} ok=${u.ok} status=${u.status} hasBody=${!!u.body}`),!f||d.includes("application/json")){let g="";try{if(g=await u.clone().text(),!g||g.trim()==="")throw new SyntaxError("Empty JSON body");if(ct(g))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let m=JSON.parse(g);if(i?.isErrorEnvelope?.(m))throw await ve(i,u.status,g,Ke(n));if(m&&typeof m=="object"&&m.error&&(typeof m.error=="string"||typeof m.error=="object"&&Object.keys(m.error).length>0)){if(i)throw await ve(i,u.status,g,Ke(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let b=dn(g),_=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${g}`,400,"provider_response_error");throw _.isRateLimit=b,_.rawBody=g,_}}catch(h){if(i)throw h?.pluginClassified===!0?h:await ve(i,u.status,void 0,Ke(n));if(h instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${g}"`);let m=K(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw m.rawBody=g,m}throw h}}}if(!i?.suppressDebugLog&&!n.stream&&Jt(o.configService)){let f=await u.clone().text();zs(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function Vi(n,e,t,o,r,s){let a=e;if(!r&&t.transformer?.use?.length)for(let i of Array.from(t.transformer.use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&t.transformer?.[n.model]?.use?.length)for(let i of Array.from(t.transformer[n.model].use).reverse())!i||typeof i.transformResponseOut!="function"||(a=await i.transformResponseOut(a,s));if(!r&&o.transformResponseIn&&(s.provider||(s.provider=t),a=await o.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new De().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function Yi(n,e,t,o){n.ok||e.code(n.status);let r=gi(n);if(!r){let s=await pe(n);if(s)s.isSSE&&(r=!0),n=new Response(s.body,{status:n.status,statusText:n.statusText,headers:n.headers});else{let a=await me(n);n=a.response,a.isSSE&&(r=!0)}}if(r){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),o&&!o.pluginRegistry.getManagedRuntimeFor(o.providerService.getProvider(e.request.provider||""))?.suppressDebugLog&&Jt(o.configService)){let[s,a]=n.body.tee(),i=js(o.configService);return Bs(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(n)}function dn(n){let e=n.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function bd(n){try{return new URL(n),!0}catch{return!1}}var md,Xi,pn=w(()=>{"use strict";Ws();zt();Vs();Ys();qs();rt();$o();re();Se();Yt();tn();Xo();V();Pe();q();md=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;Xi=async n=>{n.get("/",async()=>({message:"LLMs API",version:Vt})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:H().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>Ji(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw K("Provider name is required",400,"invalid_request");if(!s||!bd(s))throw K("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw K("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw K("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw K(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw K("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw K("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw K("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw K("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ge,ir=w(()=>{"use strict";Ge=class n{constructor(e,t,o){this.configService=e;this.transformerService=t;this.logger=o;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;reload(){let e=new n(this.configService,this.transformerService,this.logger);this.providers=e.providers,this.modelRoutes=e.modelRoutes}initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let o={};t.transformer&&Object.keys(t.transformer).forEach(s=>{s==="use"?Array.isArray(t.transformer.use)&&(o.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[s]?.use)&&(o[s]={use:t.transformer[s].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let i=this.transformerService.getTransformer(a[0]);if(i)return new i(a[1])}if(typeof a=="string"){let i=this.transformerService.getTransformer(a);return typeof i=="function"?new i:i}}).filter(a=>typeof a<"u")})});let r=t.default_thinking_level;if(r){let s=this.transformerService.getTransformer("defaultthinking");if(s){let a=new s({level:r});o.use=[a,...o.use||[]]}else this.logger.warn(`default_thinking_level set on ${t.name} but defaultthinking transformer is not registered`)}this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,pluginManaged:t.ccr_managed===!0,models:t.models||[],quotaToken:t.quota_token,quotaSecToken:t.quota_sec_token,transformer:t.transformer?o:void 0,cacheMode:t.cache_mode||"exclusive",enabled:t.enabled!==!1,proxyEnabled:t.proxy_enabled===!0,wakeupEnabled:t.wakeup_enabled===!0,wakeupTime:t.wakeup_time||"06:00",wakeupModel:t.wakeup_model||""}),this.logger.info(`${t.name} provider registered`)}catch(o){this.logger.error(`${t.name} provider registered error: ${o}`)}})}registerProvider(e){let t={...e,enabled:e.enabled!==!1,proxyEnabled:e.proxyEnabled===!0,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(t.name,t),e.models.forEach(o=>{let r=`${t.name},${o}`,s={provider:t.name,model:o,fullModel:r};this.modelRoutes.set(r,s),this.modelRoutes.has(o)||this.modelRoutes.set(o,s)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let o=this.providers.get(e);if(!o)return null;let r={...o,...t,updatedAt:new Date};return this.providers.set(e,r),t.models&&(o.models.forEach(s=>{let a=`${o.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),t.models.forEach(s=>{let a=`${o.name},${s}`,i={provider:o.name,model:s,fullModel:a};this.modelRoutes.set(a,i),this.modelRoutes.has(s)||this.modelRoutes.set(s,i)})),r}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(o=>{let r=`${t.name},${o}`;this.modelRoutes.delete(r),this.modelRoutes.delete(o)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){let o=this.providers.get(e);if(!o)return!1;o.enabled=t;let r=this.configService.get("providers");if(r&&Array.isArray(r)){let s=r.find(a=>a.name===e);s&&(s.enabled=t)}return!0}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let o=this.providers.get(t.provider);return o?{provider:o,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push(o),e.push(`${t.name},${o}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,o)=>{if(Array.isArray(o)){let[r,s={}]=o;t[r]=s}else t[o]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.enabled!==!1&&t.models.forEach(o=>{e.push({id:o,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${o}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}}});var ye,fn,Zi,kd,qi,Qe=w(()=>{"use strict";ye=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",fn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,Zi=["low","medium","high"],kd={none:"none",off:"none",disabled:"none",min:"low",minimal:"low",light:"low",low:"low",medium:"medium",mid:"medium",high:"high",xhigh:"max",max:"max",maximum:"max",ultra:"max",ultracode:"max"},qi=n=>{if(typeof n=="string")return kd[n.trim().toLowerCase()]}});var ar,ea=w(()=>{ar=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function Td(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ta(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let g=t[f],h=g?.text??JSON.stringify(g),m=d.get(h);if(m===void 0){d.set(h,f);continue}!t[m]?.cache_control&&g?.cache_control&&(t[m]=g),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let g=f.content;try{typeof f.content=="string"&&(g=JSON.parse(f.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let h={type:"tool_result",tool_use_id:f.tool_call_id,content:g};f.cache_control&&(h.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(h):s.push({role:"user",content:[h]})}else if(f.role==="user"){let g=[];typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?g.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):g.push(m)});let h=s[s.length-1];h&&h.role==="user"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let g=[];f.content&&(typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&g.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}g.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&g.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let h=s[s.length-1];h&&h.role==="assistant"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(g=>g?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},l=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let g=f.find(h=>h?.cache_control);if(g?.cache_control)return g.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},c=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(h=>h?.cache_control))return!1;let g=d.content.find(h=>h&&typeof h=="object"&&!h.cache_control);return g?(g.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,g=l(),h=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||h.push(m);for(let m of h){if(d<=0)break;c(f[m],g)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||fn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let g=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:ye(d);Zi.includes(g)&&(p.output_config={...p.output_config||{},effort:g})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
|
|
31
|
+
|
|
32
|
+
`)}return n.tools&&n.tools.length>0&&(p.tools=Td(n.tools),n.tool_choice&&(n.tool_choice==="auto"?p.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?p.tool_choice={type:"any"}:typeof n.tool_choice=="string"?p.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:n.tool_choice.function.name}))),p}var na=w(()=>{Qe()});function vd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function mn(n){return n?.cache_creation_input_tokens??n?.input_tokens_details?.cache_creation_tokens??n?.input_tokens_details?.cache_write_tokens??n?.prompt_tokens_details?.cache_creation_tokens??n?.prompt_tokens_details?.cache_write_tokens??0}function Ee(n){if(!(!n||typeof n!="object"))return{...n,...n.kiro_estimated===!0||n.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:n.input_tokens??n.prompt_tokens??0,output_tokens:n.output_tokens??n.completion_tokens??0,cache_read_input_tokens:vd(n),cache_creation_input_tokens:mn(n)}}function Ae(n,e,t){let o=t?{}:n||{},r=e||{};return{...o,...r.usage_estimated===!0||o.usage_estimated===!0?{usage_estimated:!0}:{},input_tokens:r.input_tokens||o.input_tokens||0,output_tokens:r.output_tokens||o.output_tokens||0,cache_read_input_tokens:r.cache_read_input_tokens||o.cache_read_input_tokens||0,cache_creation_input_tokens:r.cache_creation_input_tokens||o.cache_creation_input_tokens||0}}var gn=w(()=>{"use strict"});import{v4 as cr}from"uuid";function xd(n){if(n===!0)return!0;if(n===!1)return!1;if(typeof n!="string")return;let e=n.trim().toLowerCase();if(e==="enabled"||e==="adaptive"||e==="true")return!0;if(e==="disabled"||e==="off"||e==="none"||e==="false")return!1}function lr(n){if(!n||typeof n!="object")return!1;let e=n;return e.usage_source==="kiro"||e.usage_estimated===!0||e.kiro_estimated===!0}var hn,oa=w(()=>{"use strict";Qe();zt();V();ea();na();Pe();gn();hn=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,t){let o={};return this.useBearer?(o.authorization=`Bearer ${t.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=t.apiKey,o.authorization=void 0),{body:e,config:{headers:o}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(l=>l.type==="text"&&l.text).map(l=>({type:"text",text:l.text,cache_control:l.cache_control}));t.push({role:"system",content:i})}}let o=JSON.parse(JSON.stringify(e.messages||[]));o?.forEach(i=>{i.role==="system"&&t.push({role:"system",content:i.content})}),o?.forEach(i=>{if(i.role!=="system"&&(i.role==="user"||i.role==="assistant")){if(typeof i.content=="string"){t.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let l=i.content.filter(u=>u.type==="tool_result"&&u.tool_use_id);if(l.length){let u=gt(String(e.model??"")),p=[];l.forEach(d=>{let f=Array.isArray(d.content)?d.content:null,g=f?f.filter(y=>y?.type==="image"&&y?.source):[],h=typeof d.content=="string"?d.content:JSON.stringify(d.content);if(g.length>0){let y=f.filter(b=>!(b?.type==="image"&&b?.source)).map(b=>b?.type==="text"?String(b.text??""):JSON.stringify(b)).filter(b=>b.length>0).join(`
|
|
33
|
+
`);u?(h=y||"[tool image]",p.push(...g)):(h=[y,...g.map(()=>"(tool image omitted: target model does not support image input)")].filter(b=>b.length>0).join(`
|
|
34
|
+
`),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:g.length}))}let m={role:"tool",content:h,tool_call_id:d.tool_use_id,cache_control:d.cache_control};t.push(m)}),p.length>0&&t.push({role:"user",content:p.map(d=>({type:"image_url",image_url:{url:d.source?.type==="base64"?ar(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type}))})}let c=i.content.filter(u=>u.type==="text"&&u.text||u.type==="image"&&u.source);c.length&&t.push({role:"user",content:c.map(u=>u?.type==="image"?{type:"image_url",image_url:{url:u.source?.type==="base64"?ar(u.source.data,u.source.media_type):u.source.url},media_type:u.source.media_type}:u)})}else if(i.role==="assistant"){let l={role:"assistant",content:""},c=i.content.filter(d=>d.type==="text"&&d.text);c.length&&(l.content=c.map(d=>d.text).join(`
|
|
35
|
+
`));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(l.tool_calls=u.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let p=i.content.find(d=>d.type==="thinking");p&&(l.thinking={content:p.thinking,signature:p.signature}),t.push(l)}return}}});let r={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice},s=qi(e.output_config?.effort),a=typeof e.thinking?.budget_tokens=="number"?e.thinking.budget_tokens:void 0;if(e.thinking!==void 0||s!==void 0){let i={},c=xd(e.thinking?.type)??(s!==void 0||(a??0)>0);c!==void 0&&(i.enabled=c),s!==void 0?i.effort=s:a!==void 0&&(i.effort=ye(a)),a!==void 0&&a>0&&(i.max_tokens=a),Object.keys(i).length>0&&(r.reasoning=i)}return e.tool_choice&&(e.tool_choice.type==="tool"?r.tool_choice={type:"function",function:{name:e.tool_choice.name}}:r.tool_choice=e.tool_choice.type),r}async transformRequestIn(e,t,o){if(!this.isAnthropicMessagesEndpoint(t.baseUrl))return e;o&&o.req&&(o.req.isTargetAnthropic=!0);let r=ta(e),s={};return this.useBearer?(s.authorization=`Bearer ${t.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=t.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:r,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,t){if(t?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let r=await this.convertOpenAIStreamToAnthropic(e.body,t);return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let r=await pe(e);if((r?.isSSE??!1)&&r?.body){let c=await this.convertOpenAIStreamToAnthropic(r.body,t);return new Response(c,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let a;if(r?.body)a=new Response(r.body,{status:e.status,statusText:e.statusText,headers:e.headers});else{let c=await me(e);if(c.isSSE){let u=await this.convertOpenAIStreamToAnthropic(c.response.body,t);return new Response(u,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}a=c.response}let i=await j(a),l=this.convertOpenAIResponseToAnthropic(i,t);return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,a=`msg_${Date.now()}`,i=null,l=String(t?.req?.body?.model??"unknown"),c=!1,u=!1,p=!1;t?.req&&(t.req.contentDelivered=!1);let d=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,g=new Map,h=0,m=0,y=0,b=!1,_=!1,k=0,T=-1,x=()=>{let R=k;return k++,R},v=R=>{if(!b)try{r.enqueue(R);let A=new TextDecoder().decode(R);this.logger.debug({reqId:t.req.id,data:A,type:"send data"})}catch(A){if(A instanceof TypeError&&A.message.includes("Controller is already closed"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:A instanceof Error?A.message:String(A),type:"send data error"}),A}},P=()=>{if(!b)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(T>=0){let A={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
36
|
+
data: ${JSON.stringify(A)}
|
|
37
|
+
|
|
38
|
+
`)),T=-1}if(i)v(s.encode(`event: message_delta
|
|
39
39
|
data: ${JSON.stringify(i)}
|
|
40
40
|
|
|
41
|
-
`)),i=null;else{let
|
|
42
|
-
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:
|
|
41
|
+
`)),i=null;else{let A=t?.req?.tokenCount||0;v(s.encode(`event: message_delta
|
|
42
|
+
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:A,output_tokens:0,cache_read_input_tokens:0}})}
|
|
43
|
+
|
|
44
|
+
`))}let R={type:"message_stop"};v(s.encode(`event: message_stop
|
|
45
|
+
data: ${JSON.stringify(R)}
|
|
43
46
|
|
|
44
|
-
`))}let
|
|
45
|
-
data:
|
|
47
|
+
`)),r.close(),b=!0}catch(R){if(R instanceof TypeError&&R.message.includes("Controller is already closed"))b=!0;else throw R}},E=null;try{E=e.getReader();let R=new TextDecoder,A="";for(;!b;){let{done:D,value:C}=await E.read();if(D)break;A+=R.decode(C,{stream:!0});let O=A.split(`
|
|
48
|
+
`);A=O.pop()||"";for(let S of O){if(b)break;if(!S.startsWith("data:"))continue;let I=S.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:I}),I!=="[DONE]")try{let M=JSON.parse(I);if(h++,this.logger.debug({reqId:t.req.id,response:M,tppe:"Original Response"}),M.error){t?.req&&(t.req.sseError=M.error);let L={type:"error",message:{type:"api_error",message:JSON.stringify(M.error)}};v(s.encode(`event: error
|
|
49
|
+
data: ${JSON.stringify(L)}
|
|
46
50
|
|
|
47
|
-
`))
|
|
48
|
-
|
|
49
|
-
data: ${JSON.stringify(O)}
|
|
51
|
+
`));continue}if(l=M.model&&M.model!=="unknown"?M.model:l,!c&&!b&&!p){c=!0;let L=t?.req?.tokenCount||0,F={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:L,output_tokens:0}}};v(s.encode(`event: message_start
|
|
52
|
+
data: ${JSON.stringify(F)}
|
|
50
53
|
|
|
51
|
-
`));
|
|
52
|
-
data: ${JSON.stringify(
|
|
54
|
+
`))}let N=M.choices?.[0];if(M.usage){let L=M.usage?.prompt_tokens_details?.cached_tokens??M.usage?.prompt_cache_hit_tokens??0,J=(M.usage?.prompt_tokens||0)-L,ce=M.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:M.usage,mappedUsage:{input_tokens:J,output_tokens:ce,cache_read_input_tokens:L},choicesLength:Array.isArray(M.choices)?M.choices.length:void 0,finishReason:N?.finish_reason});let B={input_tokens:J,output_tokens:ce,cache_read_input_tokens:L,...lr(M.usage)?{cache_creation_input_tokens:mn(M.usage)}:{},...M.usage.kiro_estimated===!0||M.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...B}};else{let z=i.usage||{};lr(M.usage)||"cache_creation_input_tokens"in z?i.usage=Ae(z,B,!1):i.usage={input_tokens:B.input_tokens||z.input_tokens||0,output_tokens:B.output_tokens||z.output_tokens||0,cache_read_input_tokens:B.cache_read_input_tokens||z.cache_read_input_tokens||0}}}if(!N)continue;if(N?.delta?.thinking&&!b&&!p&&!u){if(!_){let L=x();d();let F={type:"content_block_start",index:L,content_block:{type:"thinking",thinking:""}};v(s.encode(`event: content_block_start
|
|
55
|
+
data: ${JSON.stringify(F)}
|
|
53
56
|
|
|
54
|
-
`))
|
|
55
|
-
data: ${JSON.stringify(
|
|
57
|
+
`)),T=L,_=!0}if(N.delta.thinking.signature){let L={type:"content_block_delta",index:T,delta:{type:"signature_delta",signature:N.delta.thinking.signature}};v(s.encode(`event: content_block_delta
|
|
58
|
+
data: ${JSON.stringify(L)}
|
|
56
59
|
|
|
57
|
-
`))
|
|
58
|
-
data: ${JSON.stringify(
|
|
60
|
+
`));let F={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
61
|
+
data: ${JSON.stringify(F)}
|
|
59
62
|
|
|
60
|
-
`))
|
|
61
|
-
data: ${JSON.stringify(
|
|
63
|
+
`)),T=-1}else if(N.delta.thinking.content){let L={type:"content_block_delta",index:T,delta:{type:"thinking_delta",thinking:N.delta.thinking.content||""}};v(s.encode(`event: content_block_delta
|
|
64
|
+
data: ${JSON.stringify(L)}
|
|
62
65
|
|
|
63
|
-
`))
|
|
64
|
-
data: ${JSON.stringify(
|
|
66
|
+
`))}}if(N?.delta?.content&&!b&&!p){if(m++,T>=0&&!u){let F={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
67
|
+
data: ${JSON.stringify(F)}
|
|
65
68
|
|
|
66
|
-
`))}
|
|
67
|
-
data: ${JSON.stringify(
|
|
69
|
+
`)),T=-1}if(!u&&!p){u=!0;let L=x();d();let F={type:"content_block_start",index:L,content_block:{type:"text",text:""}};v(s.encode(`event: content_block_start
|
|
70
|
+
data: ${JSON.stringify(F)}
|
|
68
71
|
|
|
69
|
-
`)),
|
|
70
|
-
data: ${JSON.stringify(
|
|
72
|
+
`)),T=L}if(!b&&!p){let L={type:"content_block_delta",index:T,delta:{type:"text_delta",text:N.delta.content}};v(s.encode(`event: content_block_delta
|
|
73
|
+
data: ${JSON.stringify(L)}
|
|
71
74
|
|
|
72
|
-
`))
|
|
73
|
-
data: ${JSON.stringify(
|
|
75
|
+
`))}}if(N?.delta?.annotations?.length&&!b&&!p){if(T>=0&&u){let L={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
76
|
+
data: ${JSON.stringify(L)}
|
|
74
77
|
|
|
75
|
-
`))}
|
|
76
|
-
data: ${JSON.stringify(
|
|
78
|
+
`)),T=-1,u=!1}N?.delta?.annotations.forEach(L=>{let F=x();d();let J={type:"content_block_start",index:F,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${cr()}`,content:[{type:"web_search_result",title:L.url_citation.title,url:L.url_citation.url}]}};v(s.encode(`event: content_block_start
|
|
79
|
+
data: ${JSON.stringify(J)}
|
|
77
80
|
|
|
78
|
-
`))
|
|
79
|
-
data: ${JSON.stringify(
|
|
81
|
+
`));let ce={type:"content_block_stop",index:F};v(s.encode(`event: content_block_stop
|
|
82
|
+
data: ${JSON.stringify(ce)}
|
|
80
83
|
|
|
81
|
-
`));let
|
|
82
|
-
data: ${JSON.stringify(
|
|
84
|
+
`)),T=-1})}if(N?.delta?.tool_calls&&!b&&!p){y++;let L=new Set;for(let F of N.delta.tool_calls){if(b)break;let J=F.index??0;if(L.has(J))continue;if(L.add(J),!g.has(J)){if(T>=0){let fl={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
85
|
+
data: ${JSON.stringify(fl)}
|
|
83
86
|
|
|
84
|
-
`)),
|
|
85
|
-
data: ${JSON.stringify(
|
|
87
|
+
`)),T=-1}let B=x();g.set(J,B);let z=F.id||`call_ccr_${J}`,$=F.function?.name||`tool_${J}`;d();let W={type:"content_block_start",index:B,content_block:{type:"tool_use",id:z,name:$,input:{}}};v(s.encode(`event: content_block_start
|
|
88
|
+
data: ${JSON.stringify(W)}
|
|
86
89
|
|
|
87
|
-
`)),
|
|
90
|
+
`)),T=B;let pl={id:z,name:$,arguments:"",contentBlockIndex:B};f.set(J,pl)}else if(F.id&&F.function?.name){let B=f.get(J);B.id.startsWith("call_")&&B.name.startsWith("tool_")&&(B.id=F.id,B.name=F.function.name)}if(F.function?.arguments&&!b&&!p){let B=g.get(J);if(B===void 0)continue;let z=f.get(J);z&&(z.arguments+=F.function.arguments);try{let $={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:F.function.arguments}};v(s.encode(`event: content_block_delta
|
|
88
91
|
data: ${JSON.stringify($)}
|
|
89
92
|
|
|
90
|
-
`))
|
|
91
|
-
data: ${JSON.stringify(
|
|
93
|
+
`))}catch{try{let $=F.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),W={type:"content_block_delta",index:B,delta:{type:"input_json_delta",partial_json:$}};v(s.encode(`event: content_block_delta
|
|
94
|
+
data: ${JSON.stringify(W)}
|
|
92
95
|
|
|
93
|
-
`))}catch{
|
|
94
|
-
data: ${JSON.stringify(
|
|
96
|
+
`))}catch($){console.error($)}}}}}if(N?.finish_reason&&!b&&!p){if(m===0&&y===0&&console.error("Warning: No content in the stream response!"),T>=0){let L={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
97
|
+
data: ${JSON.stringify(L)}
|
|
98
|
+
|
|
99
|
+
`)),T=-1}if(!b){let F={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[N.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:F,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:F,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(M){this.logger?.error(`parseError: ${M.name} message: ${M.message} stack: ${M.stack} data: ${I}`)}}}P()}catch(R){if(!b)try{r.error(R)}catch(A){console.error(A)}}finally{if(E)try{E.releaseLock()}catch(R){console.error(R)}}},cancel:r=>{this.logger.debug({reqId:t.req.id},`cancle stream: ${r}`)}})}convertOpenAIResponseToAnthropic(e,t){this.logger.debug({reqId:t.req.id,response:e},"Original OpenAI response");try{let o=e.choices[0];if(!o)throw new Error("No choices found in OpenAI response");let r=[];if(o.message.annotations){let l=`srvtoolu_${cr()}`;r.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),r.push({type:"web_search_tool_result",tool_use_id:l,content:o.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}o.message.content&&r.push({type:"text",text:o.message.content}),o.message.tool_calls&&o.message.tool_calls.length>0&&o.message.tool_calls.forEach(l=>{let c={};try{let u=l.function.arguments||"{}";typeof u=="object"?c=u:typeof u=="string"&&(c=JSON.parse(u))}catch{c={text:l.function.arguments||""}}r.push({type:"tool_use",id:l.id,name:l.function.name,input:c})}),o.message?.thinking?.content&&r.push({type:"thinking",thinking:o.message.thinking.content,signature:o.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens??e.usage?.prompt_cache_hit_tokens??0,a=(e.usage?.prompt_tokens||0)-s,i={id:e.id?.startsWith("msg_")?e.id:`msg_${cr().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:r,stop_reason:o.finish_reason==="stop"?"end_turn":o.finish_reason==="length"?"max_tokens":o.finish_reason==="tool_calls"?"tool_use":o.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:lr(e.usage)?mn(e.usage):0,...e.usage?.kiro_estimated===!0||e.usage?.usage_estimated===!0?{usage_estimated:!0}:{},cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:t.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw K(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Sd(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1){let o=t[0].toUpperCase();e.type=Object.values(Ve).includes(o)?o:Ve.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(Ve).includes(r)?r:Ve.TYPE_UNSPECIFIED})}}}function yt(n){let e={},t=["items"],o=["anyOf"],r=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type&&Array.isArray(n.type)&&Sd(n.type,e);for(let[a,i]of Object.entries(n))if(i!=null)if(a=="type"){if(i==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(i))continue;let l=i.toUpperCase();e.type=Object.values(Ve).includes(l)?l:Ve.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=yt(i);else if(o.includes(a)){let l=[];for(let c of i){if(c.type=="null"){e.nullable=!0;continue}l.push(yt(c))}e[a]=l}else if(r.includes(a)){let l={};for(let[c,u]of Object.entries(i))l[c]=yt(u);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=i}return e}function Cd(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=yt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=yt(e.response));return n}function _n(n){let e=[],t=n.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));t?.length&&e.push(Cd({functionDeclarations:t})),n.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let r=[],s=n.messages.filter(l=>l.role==="tool");n.messages.filter(l=>l.role!=="tool").forEach(l=>{let c;l.role==="assistant"?c="model":(["user","system"].includes(l.role),c="user");let u=[];if(typeof l.content=="string"){let p={text:l.content};l.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),u.push(p)}else Array.isArray(l.content)?u.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?u.push({text:l.content.text}):u.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&u.push(...l.tool_calls.map(p=>{let d={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return l.thinking?.signature&&(d.thoughtSignature=l.thinking.signature),d})),u.length===0&&u.push({text:""}),r.push({role:c,parts:u}),c==="model"&&l.tool_calls){let p=l.tool_calls.map(d=>{let f=s.find(g=>g.tool_call_id===d.id);return{functionResponse:{name:d?.function?.name,response:{result:f?.content}}}});r.push({role:"user",parts:p})}});let a={};if(n.reasoning&&n.reasoning.effort&&n.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},n.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=n.reasoning.effort;else{let l=n.model.includes("pro")?[128,32768]:[0,24576],c,u=n.reasoning.max_tokens;typeof u<"u"&&(u>=l[0]&&u<=l[1]?c=u:u<l[0]?c=l[0]:u>l[1]&&(c=l[1]),a.thinkingConfig.thinkingBudget=c)}let i={contents:r,tools:e.length?e:void 0,generationConfig:a};if(n.tool_choice){let l={functionCallingConfig:{}};n.tool_choice==="auto"?l.functionCallingConfig.mode="auto":n.tool_choice==="none"?l.functionCallingConfig.mode="none":n.tool_choice==="required"?l.functionCallingConfig.mode="any":n.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[n.tool_choice?.function?.name]),i.toolConfig=l}return i}function bn(n){let e=n.contents,t=n.tools,o=n.model,r=n.max_tokens,s=n.temperature,a=n.stream,i=n.tool_choice,l={messages:[],model:o,max_tokens:r,temperature:s,stream:a,tool_choice:i};return Array.isArray(e)&&e.forEach(c=>{typeof c=="string"?l.messages.push({role:"user",content:c}):typeof c.text=="string"?l.messages.push({role:"user",content:c.text||null}):c.role==="user"?l.messages.push({role:"user",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]}):c.role==="model"&&l.messages.push({role:"assistant",content:c?.parts?.map(u=>({type:"text",text:u.text||""}))||[]})}),Array.isArray(t)&&(l.tools=[],t.forEach(c=>{Array.isArray(c.functionDeclarations)&&c.functionDeclarations.forEach(u=>{l.tools.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})})})),l}function yn(n){return{completion_tokens:n?.candidatesTokenCount||0,prompt_tokens:n?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n?.cachedContentTokenCount||0},total_tokens:n?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n?.thoughtsTokenCount||0}}}function dr(n){if(n?.groundingMetadata?.groundingChunks?.length)return n.groundingMetadata.groundingChunks.map((e,t)=>{let o=n?.groundingMetadata?.groundingSupports?.filter(r=>r.groundingChunkIndices?.includes(t));return{type:"url_citation",url_citation:{url:e?.web?.uri||"",title:e?.web?.title||"",content:o?.[0]?.segment?.text||"",start_index:o?.[0]?.segment?.startIndex||0,end_index:o?.[0]?.segment?.endIndex||0}}})}function ur(n,e,t){let o=e?dr(e):void 0,r=e?.finishReason?.toLowerCase()||null;return{choices:r||o?[{delta:o?{role:"assistant",annotations:o}:{},finish_reason:r,index:t,logprobs:null}]:[],created:parseInt(new Date().getTime()/1e3+"",10),id:n.responseId||"",model:n.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...n.usageMetadata?{usage:yn(n.usageMetadata)}:{}}}async function kn(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json();t?.debug({response:o},`${e} response:`);let r="",s="",a=o.candidates[0]?.content?.parts||[],i=[];for(let p of a)p.text&&p.thought===!0?r+=p.text:i.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=i?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],c=i?.filter(p=>p.text)?.map(p=>p.text)?.join(`
|
|
100
|
+
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:c,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:yn(o.usageMetadata)};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,l="",c=0,u=-1,p=new ReadableStream({async start(d){let f=async(m,y)=>{if(m.startsWith("data: ")){let b=m.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){if(_.usageMetadata){y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,void 0,c))}
|
|
101
|
+
|
|
102
|
+
`));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],T=!1,x=k.content?.parts||[];x.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:R.text}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
|
|
95
103
|
|
|
96
|
-
`))}
|
|
97
|
-
data: ${JSON.stringify(O)}
|
|
104
|
+
`))});let v=x.find(R=>R.thoughtSignature)?.thoughtSignature;if(v&&!s){if(!i){let A={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
|
|
98
105
|
|
|
99
|
-
`))
|
|
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)}
|
|
106
|
+
`))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:v}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
101
107
|
|
|
102
|
-
`))
|
|
108
|
+
`)),s=!0,c++,l){let A={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(A)}
|
|
103
109
|
|
|
104
|
-
`))}let
|
|
110
|
+
`)),l="",a||(a=!0)}}let P=x.filter(R=>R.functionCall).map(R=>({id:R.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:R.functionCall?.name,arguments:JSON.stringify(R.functionCall?.args||{})}})),E=x.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
|
|
111
|
+
`);if(!E&&s&&!a){let R={choices:[{delta:{role:"assistant",content:"(no content)"},index:c,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
105
112
|
|
|
106
|
-
`)),
|
|
113
|
+
`)),a||(a=!0)}if(i&&E&&!s)if(_.modelVersion?.includes("3")){l+=E,_.usageMetadata&&y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,k,c))}
|
|
107
114
|
|
|
108
|
-
`))
|
|
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)}
|
|
115
|
+
`));return}else{let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
110
116
|
|
|
111
|
-
`)),
|
|
117
|
+
`)),s=!0}if(E){l||c++;let R={choices:[{delta:{role:"assistant",content:E},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:yn(_.usageMetadata)},A=dr(k);A&&(R.choices[0].delta.annotations=A),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
112
118
|
|
|
113
|
-
`)),
|
|
119
|
+
`)),T=!0,!a&&E&&(a=!0)}P.length>0&&(P.forEach(R=>{c++,u++;let A={choices:[{delta:{role:"assistant",tool_calls:[{...R,index:u}]},finish_reason:k.finishReason?.toLowerCase()||null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:yn(_.usageMetadata)},D=dr(k);D&&(A.choices[0].delta.annotations=D),y.enqueue(r.encode(`data: ${JSON.stringify(A)}
|
|
114
120
|
|
|
115
|
-
`)),!a&&
|
|
121
|
+
`)),T=!0}),!a&&E&&(a=!0)),!T&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&y.enqueue(r.encode(`data: ${JSON.stringify(ur(_,k,c))}
|
|
116
122
|
|
|
117
|
-
`))}
|
|
118
|
-
`);
|
|
123
|
+
`))}catch(_){t?.error(`Error parsing ${e} stream chunk`,b,_.message)}}}},g=n.body.getReader(),h="";try{for(;;){let{done:m,value:y}=await g.read();if(m){h&&await f(h,d);break}h+=o.decode(y,{stream:!0});let b=h.split(`
|
|
124
|
+
`);h=b.pop()||"";for(let _ of b)await f(_,d)}}catch(m){d.error(m)}finally{d.close()}}});return new Response(p,{status:n.status,statusText:n.statusText,headers:n.headers})}}var Ve,pr=w(()=>{"use strict";Ve={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var Tn,ra=w(()=>{"use strict";pr();Tn=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:_n(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=bn;async transformResponseOut(e){return kn(e,this.name,this.logger)}}});async function Rd(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
119
125
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
120
126
|
2. Run "gcloud auth application-default login"
|
|
121
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
122
|
-
`);for(let m of
|
|
123
|
-
`))},p=(d,f)=>{let{controller:
|
|
127
|
+
3. Use Google Cloud environment with default service account`)}}var vn,sa=w(()=>{"use strict";pr();vn=class{name="vertex-gemini";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Rd();return{body:_n(e),config:{url:new URL(`./v1beta1/projects/${o}/locations/${r}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${r}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return bn(e)}async transformResponseOut(e){return kn(e,this.name)}}});var xn,ia=w(()=>{"use strict";V();xn=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let t=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),o=e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content)||t;return o&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(r=>{if(r.role==="assistant"){let s=r.thinking?.content,a=r.thinking?.signature,i="";if(typeof r.content=="string"){let c=/<thinking>([\s\S]*?)<\/thinking>/g.exec(r.content);c&&(i=c[1].trim(),r.content=r.content.replace(c[0],"").trim())}s&&typeof s=="string"&&s.trim()?(r.reasoning_content=s,a&&(r.reasoning_content_signature=a)):i&&(r.reasoning_content=i),o&&!r.reasoning_content&&(r.reasoning_content=" "),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
|
|
128
|
+
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
129
|
+
`))},p=(d,f)=>{let{controller:g,encoder:h}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
|
|
124
130
|
|
|
125
|
-
`;
|
|
131
|
+
`;g.enqueue(h.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
|
|
126
132
|
|
|
127
|
-
`;
|
|
133
|
+
`;g.enqueue(h.encode(k));let T={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete T.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(T)}
|
|
128
134
|
|
|
129
|
-
`;
|
|
135
|
+
`;g.enqueue(h.encode(x));return}if(m.choices[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){let y=`data: ${JSON.stringify(m)}
|
|
130
136
|
|
|
131
|
-
`;
|
|
132
|
-
`))}else
|
|
133
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
134
|
-
`);a=
|
|
135
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
137
|
+
`;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
|
|
138
|
+
`))}else g.enqueue(h.encode(d+`
|
|
139
|
+
`))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
|
|
140
|
+
`);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
|
|
141
|
+
`))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Sn,aa=w(()=>{"use strict";V();Sn=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
|
|
136
142
|
IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
|
|
137
143
|
Examples:
|
|
138
144
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
139
|
-
2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await
|
|
140
|
-
`);for(let m of
|
|
141
|
-
`))},p=(d,f)=>{let{controller:
|
|
142
|
-
|
|
143
|
-
`;
|
|
144
|
-
|
|
145
|
-
`;
|
|
146
|
-
`))}else
|
|
147
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
148
|
-
`);a=
|
|
149
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
150
|
-
`);for(let b of y)b.trim()&&
|
|
151
|
-
`))},f=(h
|
|
152
|
-
|
|
153
|
-
`));return}_.choices?.[0]?.delta?.content&&!
|
|
154
|
-
|
|
155
|
-
`;m.enqueue(y.encode(
|
|
156
|
-
|
|
157
|
-
`;m.enqueue(y.encode(
|
|
158
|
-
|
|
159
|
-
`;m.enqueue(y.encode(
|
|
160
|
-
|
|
161
|
-
`;m.enqueue(y.encode(
|
|
162
|
-
`))}}else m.enqueue(y.encode(
|
|
163
|
-
`))};try{for(;;){let{done:
|
|
164
|
-
`);
|
|
165
|
-
`))}continue}let y=
|
|
166
|
-
`);
|
|
167
|
-
`))}}}catch(
|
|
168
|
-
`);for(let y of m)y.trim()&&
|
|
169
|
-
`))},d=(f,
|
|
170
|
-
|
|
171
|
-
`;
|
|
172
|
-
`))}}else
|
|
173
|
-
`))};try{for(;;){let{done:f,value:
|
|
174
|
-
`);i=y.pop()||"";for(let b of y)if(b.trim())try{d(b,{controller:
|
|
145
|
+
2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let o=t?.choices[0]?.message.tool_calls[0],r=JSON.parse(o.function.arguments||"{}");t.choices[0].message.content=r.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=-1,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
|
|
146
|
+
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
147
|
+
`))},p=(d,f)=>{let{controller:g,encoder:h,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let T=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:T.response||""}}];let x=`data: ${JSON.stringify(_)}
|
|
148
|
+
|
|
149
|
+
`;g.enqueue(h.encode(x))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
|
|
150
|
+
|
|
151
|
+
`;g.enqueue(h.encode(k))}}catch{g.enqueue(h.encode(d+`
|
|
152
|
+
`))}else g.enqueue(h.encode(d+`
|
|
153
|
+
`))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
|
|
154
|
+
`);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,exitToolIndex:()=>r,setExitToolIndex:y=>r=y,exitToolResponse:()=>s,appendExitToolResponse:y=>s+=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
|
|
155
|
+
`))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});import{v4 as wd}from"uuid";var Cn,ca=w(()=>{"use strict";V();Cn=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
|
|
156
|
+
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
157
|
+
`))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
|
|
158
|
+
|
|
159
|
+
`));return}_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let k=_.choices?.[0]?.delta?.reasoning||_.choices?.[0]?.delta?.reasoning_content;if(k){h.appendReasoningContent(k);let E={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};E.choices?.[0]?.delta&&(delete E.choices[0].delta.reasoning,delete E.choices[0].delta.reasoning_content);let R=`data: ${JSON.stringify(E)}
|
|
160
|
+
|
|
161
|
+
`;m.enqueue(y.encode(R));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let E="ccr_think_signature",R=_.choices[0].delta.content,A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:E}}}]};A.choices?.[0]?.delta&&delete A.choices[0].delta.reasoning;let D=`data: ${JSON.stringify(A)}
|
|
162
|
+
|
|
163
|
+
`;m.enqueue(y.encode(D));let C={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:R}}]};C.choices?.[0]?.delta&&(delete C.choices[0].delta.reasoning,delete C.choices[0].delta.reasoning_content);let O=`data: ${JSON.stringify(C)}
|
|
164
|
+
|
|
165
|
+
`;m.enqueue(y.encode(O));return}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(E=>{E.id=`call_${wd()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let T=_.choices?.[0]?.delta,x=T&&Object.keys(T).length>0,v=_.choices?.[0]?.finish_reason,P=_.usage;if(x||v||P){let E=`data: ${JSON.stringify(_)}
|
|
166
|
+
|
|
167
|
+
`;m.enqueue(y.encode(E))}}catch{m.enqueue(y.encode(g+`
|
|
168
|
+
`))}}else m.enqueue(y.encode(g+`
|
|
169
|
+
`))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
|
|
170
|
+
`);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
|
|
171
|
+
`))}continue}let y=l.split(`
|
|
172
|
+
`);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
|
|
173
|
+
`))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Rn,la=w(()=>{"use strict";Rn=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}}});import{v4 as Pd}from"uuid";var wn,ua=w(()=>{"use strict";V();wn=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i="",l=new ReadableStream({async start(c){let u=e.body.getReader(),p=(f,g,h)=>{let m=f.split(`
|
|
174
|
+
`);for(let y of m)y.trim()&&g.enqueue(h.encode(y+`
|
|
175
|
+
`))},d=(f,g)=>{let{controller:h,encoder:m}=g;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]"){let y=f.slice(6);try{let b=JSON.parse(y);if(b.error)throw new Error(JSON.stringify(b));b.choices?.[0]?.delta?.content&&!g.hasTextContent()&&g.setHasTextContent(!0),b.choices?.[0]?.delta?.tool_calls?.length&&b.choices?.[0]?.delta?.tool_calls.forEach(k=>{k.id=`call_${Pd()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let _=`data: ${JSON.stringify(b)}
|
|
176
|
+
|
|
177
|
+
`;h.enqueue(m.encode(_))}catch{h.enqueue(m.encode(f+`
|
|
178
|
+
`))}}else h.enqueue(m.encode(f+`
|
|
179
|
+
`))};try{for(;;){let{done:f,value:g}=await u.read();if(f){i.trim()&&p(i,c,o);break}if(!g||g.length===0)continue;let h;try{h=t.decode(g,{stream:!0})}catch(y){console.warn("Failed to decode chunk",y);continue}if(h.length===0)continue;if(i+=h,i.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let y=i.split(`
|
|
180
|
+
`);i=y.pop()||"";for(let b of y)if(b.trim())try{d(b,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),c.enqueue(o.encode(b+`
|
|
175
181
|
`))}continue}let m=i.split(`
|
|
176
|
-
`);i=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:
|
|
177
|
-
`))}}}catch(f){console.error("Stream error:",f),
|
|
182
|
+
`);i=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:c,encoder:o,hasTextContent:()=>r,setHasTextContent:b=>r=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",y,b),c.enqueue(o.encode(y+`
|
|
183
|
+
`))}}}catch(f){console.error("Stream error:",f),c.error(f)}finally{try{u.releaseLock()}catch(f){console.error("Error releasing reader lock:",f)}c.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var Pn,da=w(()=>{"use strict";Pn=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control}):t.cache_control&&delete t.cache_control}),e}}});import Ed from"json5";import{jsonrepair as Ad}from"jsonrepair";function fr(n,e){if(!n||n.trim()===""||n==="{}")return"{}";try{return JSON.parse(n),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),n}catch(t){try{let o=Ed.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=Ad(n);return e?.debug("Tool arguments safely repaired"),r}catch(r){return e?.error(`JSON parsing failed: ${t.message}. JSON5 parsing failed: ${o.message}. JSON repair failed: ${r.message}. Input data: ${JSON.stringify(n)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var pa=w(()=>{});var En,fa=w(()=>{"use strict";pa();V();En=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);if(t?.choices?.[0]?.message?.tool_calls?.length)for(let o of t.choices[0].message.tool_calls)o.function?.arguments&&(o.function.arguments=fr(o.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r={},s=!1,a="",i=!1,l=!1,c="",u=new ReadableStream({async start(p){let d=e.body.getReader(),f=(m,y,b)=>{let _=m.split(`
|
|
178
184
|
`);for(let k of _)k.trim()&&y.enqueue(b.encode(k+`
|
|
179
|
-
`))},
|
|
185
|
+
`))},g=(m,y,b)=>{let _="";try{_=fr(r.arguments||"",this.logger)}catch(v){console.error(`${v.message} ${v.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},T={...m,choices:[{...m.choices[0],delta:k}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let x=`data: ${JSON.stringify(T)}
|
|
180
186
|
|
|
181
|
-
`;y.enqueue(b.encode(x))},
|
|
187
|
+
`;y.enqueue(b.encode(x))},h=(m,y)=>{let{controller:b,encoder:_}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.slice(6);try{let T=JSON.parse(k);if(T.choices?.[0]?.delta?.tool_calls?.length){let v=T.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""},v.function?.arguments&&(v.function.arguments="");let P=`data: ${JSON.stringify(T)}
|
|
182
188
|
|
|
183
|
-
`;b.enqueue(_.encode(
|
|
189
|
+
`;b.enqueue(_.encode(P));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{g(T,b,_),r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){g(T,b,_),r={};return}T.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let x=`data: ${JSON.stringify(T)}
|
|
184
190
|
|
|
185
191
|
`;b.enqueue(_.encode(x))}catch{b.enqueue(_.encode(m+`
|
|
186
192
|
`))}}else b.enqueue(_.encode(m+`
|
|
187
|
-
`))};try{for(;;){let{done:m,value:y}=await d.read();if(m){
|
|
188
|
-
`);
|
|
189
|
-
`))}continue}let _=
|
|
190
|
-
`);
|
|
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
|
|
192
|
-
`);for(let m of
|
|
193
|
-
`))},p=(d,f)=>{let{controller:
|
|
193
|
+
`))};try{for(;;){let{done:m,value:y}=await d.read();if(m){c.trim()&&f(c,p,o);break}if(!y||y.length===0)continue;let b;try{b=t.decode(y,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(b.length===0)continue;if(c+=b,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=c.split(`
|
|
194
|
+
`);c=k.pop()||"";for(let T of k)if(T.trim())try{h(T,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>i,setReasoningComplete:x=>i=x})}catch(x){console.error("Error processing line:",T,x),p.enqueue(o.encode(T+`
|
|
195
|
+
`))}continue}let _=c.split(`
|
|
196
|
+
`);c=_.pop()||"";for(let k of _)if(k.trim())try{h(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",k,T),p.enqueue(o.encode(k+`
|
|
197
|
+
`))}}}catch(m){console.error("Stream error:",m),p.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}p.close()}}});return new Response(u,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var An,ma=w(()=>{"use strict";V();Qe();An=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens??fn(e.reasoning.effort||"medium")},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices[0]?.message.reasoning_content&&(t.thinking={content:t.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r="",s=!1,a="",i=new ReadableStream({async start(l){let c=e.body.getReader(),u=(d,f,g)=>{let h=d.split(`
|
|
198
|
+
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
199
|
+
`))},p=(d,f)=>{let{controller:g,encoder:h}=f;if(this.logger?.debug({line:d},"Processing reason line"),d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let m=JSON.parse(d.slice(6));if(console.log(JSON.stringify(m)),m.choices?.[0]?.delta?.reasoning_content){f.appendReasoningContent(m.choices[0].delta.reasoning_content);let y={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,thinking:{content:m.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(y)}
|
|
194
200
|
|
|
195
|
-
`;
|
|
201
|
+
`;g.enqueue(h.encode(b));return}if(m.choices?.[0]?.delta?.content&&f.reasoningContent()&&!f.isReasoningComplete()){f.setReasoningComplete(!0);let y="ccr_think_signature",b=m.choices[0].delta.content,_={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:null,thinking:{content:f.reasoningContent(),signature:y}}}]};delete _.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(_)}
|
|
196
202
|
|
|
197
|
-
`;
|
|
203
|
+
`;g.enqueue(h.encode(k))}if(m.choices?.[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){f.isReasoningComplete()&&m.choices[0].index++;let y=`data: ${JSON.stringify(m)}
|
|
198
204
|
|
|
199
|
-
`;
|
|
200
|
-
`))}else
|
|
201
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
202
|
-
`);a=
|
|
203
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
205
|
+
`;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
|
|
206
|
+
`))}else g.enqueue(h.encode(d+`
|
|
207
|
+
`))};try{for(;;){let{done:d,value:f}=await c.read();if(d){a.trim()&&u(a,l,o);break}let g=t.decode(f,{stream:!0});a+=g;let h=a.split(`
|
|
208
|
+
`);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:l,encoder:o,reasoningContent:()=>r,appendReasoningContent:y=>r+=y,isReasoningComplete:()=>s,setReasoningComplete:y=>s=y})}catch(y){console.error("Error processing line:",m,y),l.enqueue(o.encode(m+`
|
|
209
|
+
`))}}}catch(d){console.error("Stream error:",d),l.error(d)}finally{try{c.releaseLock()}catch(d){console.error("Error releasing reader lock:",d)}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var On,ga=w(()=>{"use strict";On=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}}});var In,ha=w(()=>{"use strict";In=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function ya(n){let e=[];for(let o=0;o<n.messages.length;o++){let r=n.messages[o],s=o===n.messages.length-1,a=r.role==="assistant",i=[];typeof r.content=="string"?i.push({type:"text",text:r.content}):Array.isArray(r.content)&&r.content.forEach(l=>{l.type==="text"?i.push({type:"text",text:l.text||""}):l.type==="image_url"&&i.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&i.length===0&&!r.tool_calls&&!r.content)&&(s&&a&&i.length===0&&r.tool_calls&&i.push({type:"text",text:""}),e.push({role:r.role==="assistant"?"assistant":"user",content:i}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:n.max_tokens||1e3,stream:n.stream||!1,...n.temperature&&{temperature:n.temperature}};return n.tools&&n.tools.length>0&&(t.tools=n.tools.map(o=>({name:o.function.name,description:o.function.description,input_schema:o.function.parameters}))),n.tool_choice&&(n.tool_choice==="auto"||n.tool_choice==="none"?t.tool_choice=n.tool_choice:typeof n.tool_choice=="string"&&(t.tool_choice={type:"tool",name:n.tool_choice})),t}function _a(n){let e=n,o={messages:e.messages.map(r=>{let s=r.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:r.role,content:s}}),model:n.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(o.tools=e.tools.map(r=>({type:"function",function:{name:r.name,description:r.description,parameters:{type:"object",properties:r.input_schema.properties,required:r.input_schema.required,additionalProperties:r.input_schema.additionalProperties,$schema:r.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?o.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(o.tool_choice=e.tool_choice.name)),o}async function ba(n,e,t){if(n.headers.get("Content-Type")?.includes("application/json")){let o=await n.json(),r;o.tool_use&&o.tool_use.length>0&&(r=o.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:o.id,choices:[{finish_reason:o.stop_reason||null,index:0,message:{content:o.content[0]?.text||"",role:"assistant",...r&&{tool_calls:r}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.model,object:"chat.completion",usage:{completion_tokens:o.usage.output_tokens,prompt_tokens:o.usage.input_tokens,total_tokens:o.usage.input_tokens+o.usage.output_tokens}};return new Response(JSON.stringify(s),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=(i,l)=>{if(i.startsWith("data: ")){let c=i.slice(6).trim();if(c){t?.debug({chunkStr:c},`${e} chunk:`);try{let u=JSON.parse(c);if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:u.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
204
210
|
|
|
205
|
-
`))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};
|
|
211
|
+
`))}else if(u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,function:{arguments:u.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
206
212
|
|
|
207
|
-
`))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};
|
|
213
|
+
`))}else if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){let p={choices:[{delta:{tool_calls:[{index:u.index||0,id:u.content_block.id,type:"function",function:{name:u.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
208
214
|
|
|
209
|
-
`))}else if(u.type==="message_delta"){let p={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};
|
|
215
|
+
`))}else if(u.type==="message_delta"){let p={choices:[{delta:{},finish_reason:u.delta?.stop_reason==="tool_use"?"tool_calls":u.delta?.stop_reason==="max_tokens"?"length":u.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
210
216
|
|
|
211
|
-
`))}else if(u.type==="message_stop")
|
|
217
|
+
`))}else if(u.type==="message_stop")l.enqueue(r.encode(`data: [DONE]
|
|
212
218
|
|
|
213
|
-
`));else{let p={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};
|
|
219
|
+
`));else{let p={choices:[{delta:{role:"assistant",content:u.content?.[0]?.text||""},finish_reason:u.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:u.id||"",model:u.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:u.usage?.output_tokens||0,prompt_tokens:u.usage?.input_tokens||0,total_tokens:(u.usage?.input_tokens||0)+(u.usage?.output_tokens||0)}};l.enqueue(r.encode(`data: ${JSON.stringify(p)}
|
|
214
220
|
|
|
215
|
-
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,
|
|
216
|
-
`);
|
|
221
|
+
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,c,u.message)}}}},a=new ReadableStream({async start(i){let l=n.body.getReader(),c="";try{for(;;){let{done:u,value:p}=await l.read();if(u){c&&s(c,i);break}c+=o.decode(p,{stream:!0});let d=c.split(`
|
|
222
|
+
`);c=d.pop()||"";for(let f of d)s(f,i)}}catch(u){i.error(u)}finally{i.close()}}});return new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers})}return n}var ka=w(()=>{"use strict"});async function Od(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
217
223
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
218
224
|
2. Run "gcloud auth application-default login"
|
|
219
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
220
|
-
`);for(let b of y)b.trim()&&
|
|
221
|
-
`))},f=(h
|
|
225
|
+
3. Use Google Cloud environment with default service account`)}}var Mn,Ta=w(()=>{"use strict";ka();Mn=class{name="vertex-claude";async transformRequestIn(e,t){let o=process.env.GOOGLE_CLOUD_PROJECT,r=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let i=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(i);l&&l.project_id&&(o=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Od();return{body:ya(e),config:{url:new URL(`/v1/projects/${o}/locations/${r}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${r}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return _a(e)}async transformResponseOut(e){return ba(e,this.name,this.logger)}}});var Ln,va=w(()=>{"use strict";Ln=class{name="cerebras";async transformRequestIn(e,t){let o=JSON.parse(JSON.stringify(e));return o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}}});var $n,xa=w(()=>{"use strict";$n=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Nn,Sa=w(()=>{"use strict";Nn=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Un,Ca=w(()=>{"use strict";Un=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let t={...e},o=Object.entries(this.options);for(let[r,s]of o)if(r in t)if(typeof t[r]=="object"&&typeof s=="object"&&!Array.isArray(t[r])&&!Array.isArray(s)&&t[r]!==null&&s!==null)t[r]=this.deepMergeObjects(t[r],s);else continue;else t[r]=this.cloneValue(s);return t}async transformResponseOut(e){return e}deepMergeObjects(e,t){let o={...e};for(let[r,s]of Object.entries(t))r in o&&typeof o[r]=="object"&&typeof s=="object"&&!Array.isArray(o[r])&&!Array.isArray(s)&&o[r]!==null&&s!==null?o[r]=this.deepMergeObjects(o[r],s):o[r]=this.cloneValue(s);return o}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>this.cloneValue(o));let t={};for(let[o,r]of Object.entries(e))t[o]=this.cloneValue(r);return t}}});import{v4 as Id}from"uuid";var Dn,Ra=w(()=>{"use strict";V();Dn=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(o=>{o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(o=>{o.cache_control&&delete o.cache_control,o.type==="image_url"&&(o.image_url.url.startsWith("http")||(o.image_url.url=`data:${o.media_type};base64,${o.image_url.url}`),delete o.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
|
|
226
|
+
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
227
|
+
`))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"&&m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
|
|
222
228
|
|
|
223
|
-
`)),_.choices?.[0]?.delta?.content&&!
|
|
229
|
+
`)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let T={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(T)}
|
|
224
230
|
|
|
225
|
-
`;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&
|
|
231
|
+
`;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let x={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let v=`data: ${JSON.stringify(x)}
|
|
226
232
|
|
|
227
|
-
`;m.enqueue(y.encode(v))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${
|
|
233
|
+
`;m.enqueue(y.encode(v))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${Id()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0),_.choices?.[0]?.delta?.tool_calls?.length&&h.hasTextContent()&&(typeof _.choices[0].index=="number"?_.choices[0].index+=1:_.choices[0].index=1);let k=`data: ${JSON.stringify(_)}
|
|
228
234
|
|
|
229
|
-
`;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(
|
|
230
|
-
`))}}else m.enqueue(y.encode(
|
|
231
|
-
`))};try{for(;;){let{done:
|
|
232
|
-
`);
|
|
233
|
-
`))}continue}let y=
|
|
234
|
-
`);
|
|
235
|
-
`))}}}catch(
|
|
235
|
+
`;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(g+`
|
|
236
|
+
`))}}else m.enqueue(y.encode(g+`
|
|
237
|
+
`))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
|
|
238
|
+
`);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
|
|
239
|
+
`))}continue}let y=l.split(`
|
|
240
|
+
`);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
|
|
241
|
+
`))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var mr,Md,Fn,wa=w(()=>{"use strict";V();mr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
236
242
|
|
|
237
243
|
Output format:
|
|
238
244
|
<reasoning_content>
|
|
239
245
|
Your detailed thinking process goes here
|
|
240
246
|
</reasoning_content>
|
|
241
|
-
Your final answer must follow after the closing tag above.`,
|
|
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:
|
|
247
|
+
Your final answer must follow after the closing tag above.`,Md=10,Fn=class{name="forcereasoning";async transformRequestIn(e){let t=0;e.messages.filter(r=>r.role==="assistant").reverse().forEach(r=>{r.thinking&&(r.thinking.content&&(!r.content||t<Md)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
|
|
248
|
+
${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:mr}):o.content=[{type:"text",text:mr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:mr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await j(e);if(r.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=r.choices[0]?.message.content.match(s);a&&a[1]&&(r.thinking={content:a[1]})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=0,s=new TextDecoder,a=new TextEncoder,i=new ReadableStream({async start(l){let c=e.body.getReader(),u="",p="SEARCHING",d="",f="",g=(h,m)=>{if(typeof m!="string"){h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&!h.choices[0].delta.content&&(h.choices[0].index=r,l.enqueue(a.encode(`data: ${JSON.stringify(h)}
|
|
243
249
|
|
|
244
|
-
`)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let x={...
|
|
250
|
+
`)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let x={...h.choices[0].delta,thinking:{content:_}};delete x.content;let v={...h,choices:[{...h.choices[0],delta:x,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
245
251
|
|
|
246
|
-
`))}let k={...
|
|
252
|
+
`))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
247
253
|
|
|
248
|
-
`)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...
|
|
254
|
+
`)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...h.choices[0].delta,thinking:{content:_}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
249
255
|
|
|
250
|
-
`))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...
|
|
256
|
+
`))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...h.choices[0].delta,content:_};k.thinking&&delete k.thinking;let T={...h,choices:[{...h.choices[0],delta:k}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
251
257
|
|
|
252
|
-
`)),f=""}r++,y=""}};try{for(;;){let{done:
|
|
253
|
-
`);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){
|
|
258
|
+
`)),f=""}r++,y=""}};try{for(;;){let{done:h,value:m}=await c.read();if(h)break;let y=s.decode(m,{stream:!0});u+=y;let b=u.split(`
|
|
259
|
+
`);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){l.enqueue(a.encode(_+`
|
|
254
260
|
|
|
255
|
-
`));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));
|
|
256
|
-
`))}else
|
|
257
|
-
`))}}}catch(
|
|
261
|
+
`));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(_+`
|
|
262
|
+
`))}else l.enqueue(a.encode(_+`
|
|
263
|
+
`))}}}catch(h){console.error("Stream error:",h),l.error(h)}finally{try{c.releaseLock()}catch(h){console.error("Error releasing reader lock:",h)}if(p==="REASONING"){let m={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(m)}
|
|
258
264
|
|
|
259
|
-
`))}
|
|
265
|
+
`))}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});var jn,Pa=w(()=>{"use strict";V();jn=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content))&&e.messages.forEach(o=>{if(o.role==="assistant"){let r=o.thinking?.content,s=o.thinking?.signature;r&&typeof r=="string"&&r.trim()&&(o.reasoning_content=r,s&&(o.reasoning_content_signature=s)),o.tool_calls&&o.tool_calls.length>0&&(o.reasoning_content||(o.reasoning_content="")),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){let t=e.headers.get("Content-Type");if(t?.includes("stream")){if(!e.body)return e;let o=new TextDecoder,r=new TextEncoder,s="",a="",i=new ReadableStream({async start(l){let c=e.body.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u){a.trim()&&l.enqueue(r.encode(a+`
|
|
260
266
|
`));break}let d=o.decode(p,{stream:!0});a+=d;let f=a.split(`
|
|
261
|
-
`);a=f.pop()||"";for(let
|
|
267
|
+
`);a=f.pop()||"";for(let g of f)if(g.trim())if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let h=JSON.parse(g.slice(6));if(h.choices?.[0]?.delta?.reasoning_content){s+=h.choices[0].delta.reasoning_content;let m={...h,choices:[{...h.choices[0],delta:{thinking:{content:h.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content,l.enqueue(r.encode(`data: ${JSON.stringify(m)}
|
|
262
268
|
|
|
263
|
-
`));continue}if(
|
|
269
|
+
`));continue}if(h.choices?.[0]?.delta?.content&&s&&!h.choices[0]?.delta?.reasoning_content){let m=Date.now().toString(),y={...h,choices:[{...h.choices[0],delta:{content:null,thinking:{content:s,signature:m}}}]};l.enqueue(r.encode(`data: ${JSON.stringify(y)}
|
|
264
270
|
|
|
265
|
-
`)),s=""}
|
|
271
|
+
`)),s=""}h.choices?.[0]?.delta?.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0&&l.enqueue(r.encode(`data: ${JSON.stringify(h)}
|
|
266
272
|
|
|
267
|
-
`))}catch{
|
|
268
|
-
`))}else
|
|
269
|
-
`))}}catch(u){
|
|
270
|
-
`);for(let b of y)b.trim()&&
|
|
271
|
-
`))},f=(h
|
|
273
|
+
`))}catch{l.enqueue(r.encode(g+`
|
|
274
|
+
`))}else l.enqueue(r.encode(g+`
|
|
275
|
+
`))}}catch(u){l.error(u)}finally{try{c.releaseLock()}catch{}l.close()}}});return new Response(i,{status:e.status,statusText:e.statusText,headers:{"Content-Type":t||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(t?.includes("application/json")){let o=await j(e);return o.choices?.[0]?.message?.reasoning_content&&(o.choices[0].message.thinking={content:o.choices[0].message.reasoning_content},delete o.choices[0].message.reasoning_content),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}}});import{v4 as Ea}from"uuid";var Hn,Aa=w(()=>{"use strict";V();je();Hn=class{constructor(e){this.options=e}static TransformerName="opencode";endPoint="/v1/chat/completions";resolveSessionId(e,t){let o=t?.req,r=o?.headers||{},s=a=>{let i=Object.keys(r).find(c=>c.toLowerCase()===a),l=i?r[i]:void 0;return typeof l=="string"&&l.trim()?l.trim():void 0};return s("x-opencode-session")||o?.clientContext?.stableSessionId||o?.sessionId||he(e.metadata?.user_id)||s("session_id")||Ea()}async transformRequestIn(e,t,o){let r=e.reasoning?.enabled||e.messages.some(s=>s.thinking?.content);return e.messages.forEach(s=>{if(Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)}),s.role==="assistant"){let a=s.thinking?.content,i=s.thinking?.signature;a&&typeof a=="string"&&a.trim()?(s.reasoning_content=a,i&&(s.reasoning_content_signature=i)):r&&s.tool_calls?.length&&!s.reasoning_content&&(s.reasoning_content=" "),s.thinking&&delete s.thinking}}),Object.assign(e,this.options||{}),{body:e,config:{headers:{"x-opencode-session":this.resolveSessionId(e,o)}}}}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await j(e);return t.choices?.[0]?.message?.reasoning_content&&(t.choices[0].message.thinking={content:t.choices[0].message.reasoning_content},delete t.choices[0].message.reasoning_content),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,o=new TextEncoder,r=!1,s="",a=!1,i=!1,l="",c=new ReadableStream({async start(u){let p=e.body.getReader(),d=(g,h,m)=>{let y=g.split(`
|
|
276
|
+
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
277
|
+
`))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let b=JSON.parse(g.slice(6));if(b.usage&&(b.choices[0].finish_reason=i?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:b.choices?.[0]?.error})}
|
|
272
278
|
|
|
273
|
-
`));return}b.choices?.[0]?.delta?.content&&!
|
|
279
|
+
`));return}b.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0);let _=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(_){h.appendReasoningContent(_);let P={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:_}}}]};P.choices?.[0]?.delta&&(delete P.choices[0].delta.reasoning,delete P.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(P)}
|
|
274
280
|
|
|
275
|
-
`));return}if(b.choices?.[0]?.delta?.content&&
|
|
281
|
+
`));return}if(b.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let P="ccr_think_signature",E=b.choices[0].delta.content,R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:P}}}]};R.choices?.[0]?.delta&&(delete R.choices[0].delta.reasoning,delete R.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(R)}
|
|
276
282
|
|
|
277
|
-
`));let
|
|
283
|
+
`));let A={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:E}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(A)}
|
|
278
284
|
|
|
279
|
-
`));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(
|
|
285
|
+
`));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(P=>{P.id=`call_${Ea()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,T=k&&Object.keys(k).length>0,x=b.choices?.[0]?.finish_reason,v=b.usage;(T||x||v)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
|
|
280
286
|
|
|
281
|
-
`))}catch{m.enqueue(y.encode(
|
|
282
|
-
`))}else m.enqueue(y.encode(
|
|
283
|
-
`))};try{for(;;){let{done:
|
|
284
|
-
`);
|
|
285
|
-
`))}continue}let y=
|
|
286
|
-
`);
|
|
287
|
-
`))}}}catch(
|
|
287
|
+
`))}catch{m.enqueue(y.encode(g+`
|
|
288
|
+
`))}else m.enqueue(y.encode(g+`
|
|
289
|
+
`))};try{for(;;){let{done:g,value:h}=await p.read();if(g){l.trim()&&d(l,u,o);break}if(!h||h.length===0)continue;let m;try{m=t.decode(h,{stream:!0})}catch(b){console.warn("Failed to decode chunk",b);continue}if(m.length===0)continue;if(l+=m,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let b=l.split(`
|
|
290
|
+
`);l=b.pop()||"";for(let _ of b)if(_.trim())try{f(_,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:k=>r=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",_,k),u.enqueue(o.encode(_+`
|
|
291
|
+
`))}continue}let y=l.split(`
|
|
292
|
+
`);l=y.pop()||"";for(let b of y)if(b.trim())try{f(b,{controller:u,encoder:o,hasTextContent:()=>r,setHasTextContent:_=>r=_,reasoningContent:()=>s,appendReasoningContent:_=>s+=_,isReasoningComplete:()=>a,setReasoningComplete:_=>a=_})}catch(_){console.error("Error processing line:",b,_),u.enqueue(o.encode(b+`
|
|
293
|
+
`))}}}catch(g){console.error("Stream error:",g),u.error(g)}finally{try{p.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}}});function $d(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim();if(!e)return;let t=e.toLowerCase();return["none","low","medium","high","max"].includes(t)?t:/^\d+$/.test(e)?parseInt(e,10):e}function Nd(n){let e="";try{e=new URL(String(n||"")).pathname.replace(/\/+$/,"")}catch{return"chat"}return e.endsWith("/messages")?"anthropic":e.endsWith("/responses")?"responses":"chat"}var Ld,zn,Oa=w(()=>{"use strict";Qe();Ld={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};zn=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=$d(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Nd(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=ye(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=Ld[o.toLowerCase()];return s?(r==="anthropic"?e.reasoning={enabled:!0,effort:s}:r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e):(r==="chat"?e.reasoning_effort=o:r==="responses"&&(e.reasoning={enabled:!0,effort:o}),e)}}});function Ia(n,e=!1){if(!n||typeof n!="object"||n.thinking)return!1;let t=n.reasoning,o=typeof t=="string"?t:t?.content;return typeof o=="string"&&o.length>0?(e&&typeof t=="object"?n.thinking={content:o}:(n.thinking=typeof t=="string"?{content:o}:{...t},delete n.reasoning),!0):typeof n.reasoning_content=="string"&&n.reasoning_content?(n.thinking={content:n.reasoning_content},!0):!1}var Bn,Ma=w(()=>{"use strict";Qe();V();Bn=class{static TransformerName="amd";name="amd";resolveEffort(e,t){if(!e)return;let o=(t??"").toLowerCase(),r=o.includes("glm"),s=!r&&o.includes("qwen"),a=!r&&!s&&o.includes("deepseek");if(e==="none")return a||o.split("/").pop()==="qwen3.8-flash-next"?"none":void 0;switch(e){case"minimal":return a?"minimal":"low";case"low":case"medium":return e;case"high":return s?"xhigh":"high";case"xhigh":case"max":return a?e:s?"xhigh":"high";default:return"medium"}}async transformRequestIn(e){let t=JSON.parse(JSON.stringify(e)),o=t.model,r=t.reasoning,s,a=r?.enabled===!1;r&&typeof r.effort=="string"?(s=r.effort===""?void 0:r.effort,a=a||r.effort==="none"):typeof r?.max_tokens=="number"?s=ye(r.max_tokens):r?.enabled===!0?s=t.reasoning_effort??"medium":(s=t.reasoning_effort,!a&&(t.enable_thinking===!1||t.thinking?.type==="disabled")&&(a=!0));let i=this.resolveEffort(a?"none":s,o);return i?t.reasoning_effort=i:delete t.reasoning_effort,delete t.reasoning,delete t.thinking,delete t.enable_thinking,t}async transformResponseOut(e){let t=e.headers.get("Content-Type")??"";if(t.includes("application/json")){if(!e.body)return e;let o=await pe(e);if(o){let a=new Headers(e.headers);if(o.isSSE&&a.set("Content-Type","text/event-stream"),e=new Response(o.body,{status:e.status,statusText:e.statusText,headers:a}),o.isSSE)return this.transformStream(e)}else{let a=await me(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await j(e);this.liftMessageReasoning(r);let s=new Headers(e.headers);return s.delete("content-length"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}return(t.includes("stream")||t.includes("event-stream"))&&e.body?this.transformStream(e):e}liftMessageReasoning(e){if(Array.isArray(e?.choices))for(let t of e.choices)Ia(t?.message)}transformStream(e){let t=new TextDecoder,o=new TextEncoder,r="",s=c=>{if(!c.startsWith("data:"))return c;let u=c.slice(5).trim();if(u==="[DONE]")return c;let p;try{p=JSON.parse(u)}catch{return c}let d=!1,f=Array.isArray(p?.choices)?p.choices:[];for(let g of f)Ia(g?.delta,!0)&&(d=!0);return d?`data: ${JSON.stringify(p)}`:c},a=(c,u=!1)=>{let p=/\r\n|\r|\n/g,d=0,f,g="";for(;(f=p.exec(r))!==null&&!(!u&&f[0]==="\r"&&p.lastIndex===r.length);)g+=s(r.slice(d,f.index))+f[0],d=p.lastIndex;r=r.slice(d),u&&(g+=s(r),r=""),g&&c.enqueue(o.encode(g))},i=e.body.pipeThrough(new TransformStream({transform(c,u){r+=t.decode(c,{stream:!0}),a(u)},flush(c){r+=t.decode(),a(c,!0)}})),l=new Headers(e.headers);return l.delete("content-length"),new Response(i,{status:e.status,statusText:e.statusText,headers:l})}}});var La,$a=w(()=>{oa();ra();sa();ia();aa();ca();la();ua();da();fa();ma();ga();ha();Ta();va();xa();Sa();Ca();Ra();Xo();wa();Pa();Aa();Oa();Ma();La={AnthropicTransformer:hn,GeminiTransformer:Tn,VertexGeminiTransformer:vn,VertexClaudeTransformer:Mn,DeepseekTransformer:xn,TooluseTransformer:Sn,OpenrouterTransformer:Cn,OpenAITransformer:Nn,MaxTokenTransformer:Rn,GroqTransformer:wn,CleancacheTransformer:Pn,EnhanceToolTransformer:En,ReasoningTransformer:An,SamplingTransformer:On,MaxCompletionTokens:In,CerebrasTransformer:Ln,StreamOptionsTransformer:$n,CustomParamsTransformer:Un,VercelTransformer:Dn,OpenAIResponsesTransformer:De,ForceReasoningTransformer:Fn,KimiTransformer:jn,OpenCodeTransformer:Hn,DefaultThinkingTransformer:zn,AmdTransformer:Bn}});var Ye,gr=w(()=>{"use strict";$a();Ye=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;preparePluginTransformer(e){if(typeof e.TransformerName=="string")return e;let t=new e;if(!t?.name)throw new Error("plugin transformer has no name");return t.logger=this.logger,t}registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=To(To.resolve(e.path));if(t){let o=new t(e.options);if(o&&typeof o=="object"&&(o.logger=this.logger),!o.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(o.name,o),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path})
|
|
288
294
|
error: ${t.message}
|
|
289
295
|
stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
290
|
-
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(
|
|
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,fr=w(()=>{"use strict";Oa();Ia();Ma();q();Xe=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new _t("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Wn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Kn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function La(n){if(!n||typeof n!="object"||Ud(n))return null;for(let t of Fd(n)){let o=$d(t);if(o)return o}return null}function $d(n){if(!n||typeof n!="object")return null;let e={},t=Gn(n,Id);if(t!==void 0){let a=Na(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Gn(n,Md);if(o!==void 0){let a=Na(o);e.usedBalance=a,e.totalBalance=100}let r=Gn(n,Ld);if(r!==void 0){let a=$a(r);a&&(e.resetTime=a)}let s=Gn(n,Nd);if(s!==void 0){let a=$a(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 Na(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Gn(n,e){for(let t of e){let o=F(n?.[t]);if(o!==void 0)return o}}function Fd(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 Ud(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 $a(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 Sr(n){let e=Rr(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Kd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Gd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Dd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?jd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Hd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?zd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Bd: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")?Wd:null:null}function Vd(n){let e=Rr(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Qd(n,e){let t=xr(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 xr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>xr(e)):Object.values(n).flatMap(e=>xr(e))}function Cr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Rr(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,mr,gr,hr,yr,_r,Id,Md,Ld,Nd,br,kr,Tr,vr,Dd,jd,Hd,zd,Bd,Jd,Wd,Kd,Gd,wr=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","Accept-Encoding":"identity",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}},mr=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}}},gr=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}},hr=class extends ie{async queryQuota(e,t,o){let r=Vd(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}},yr=class extends ie{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=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}}},_r=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=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}}};Id=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Md=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Ld=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Nd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];br=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=Cr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),c=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:c,signal:AbortSignal.timeout(o)};try{r&&(l.dispatcher=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 La(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=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 La(l)}catch{return null}}},kr=class extends ie{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Cr(e.quotaToken,"atp-auth-token")||Cr(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=Qd(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}}},Tr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=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}}},vr=class extends ie{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Rr(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}}},Dd=new mr,jd=new gr,Hd=new hr,zd=new yr,Bd=new _r,Jd=new br,Wd=new kr,Kd=new Tr,Gd=new vr});function Fa(n){return{[Yd]:n,[Xd]:Qt}}function Ee(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function qd(n){return n===!0||n==="true"||n===1||n==="1"}function ep(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 tp(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 np(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Pr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Ee(n))return{success:!1,skipped:!0,error:Er,latencyMs:r()};let s=tp(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 op(n,e,t,o){if(Ee(n))return{success:!1,skipped:!0,error:Er};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",...Fa("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 rp(n,e,t,o,r){if(Ee(n))return{success:!1,skipped:!0,error:Er};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Fa("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 Ua(n,e,t,o,r,s){return _e||(_e=new Vn(n,e,t,o,r,s)),_e}function bt(n,e,t,o,r,s){let a=Ua(n,e,t,o,r,s);return a.start(),a}function Ar(){_e&&_e.stop()}function Or(){_e&&(_e.stop(),_e=null)}var Yd,Xd,Zd,Er,Vn,_e,Qn=w(()=>{"use strict";se();xe();wr();De();Io();q();Yd="x-claude-code-router-source",Xd="x-claude-code-router-version";Zd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Er="Managed provider requires its plugin's authenticated model sync";Vn=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,a){this.config={...Zd,...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&&!Ee(s)&&!this.config.excludeProviders.includes(s.name)),t=j();if(e.length===0)return;let o=[];for(let s of e){let a=Sr(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){Zo(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`))}}})}),np(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Pr(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&&!Ee(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=>Pr(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&&Ee(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 rp(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&&!Ee(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=ep(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}`),op(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 Pr(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 Da=w(()=>{"use strict"});var Ir,kt,ja=w(()=>{"use strict";Ir=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 Ir});var ae,Mr=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,
|
|
296
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(La).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}}});import{get_encoding as Ud}from"tiktoken";var _t,Na=w(()=>{"use strict";_t=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Ud(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");let o=0,{messages:r,system:s,tools:a}=e;return Array.isArray(r)&&r.forEach(i=>{typeof i.content=="string"?o+=t.encode(i.content).length:Array.isArray(i.content)&&i.content.forEach(l=>{if(l.type==="text")o+=t.encode(l.text).length;else if(l.type==="tool_use")o+=t.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let c=l.content;if(Array.isArray(c))for(let u of c)u?.type!=="image"&&(o+=t.encode(u?.type==="text"?String(u.text??""):JSON.stringify(u)).length);else{let u=typeof c=="string"?c:JSON.stringify(c);o+=t.encode(u).length}}})}),typeof s=="string"?o+=t.encode(s).length:Array.isArray(s)&&s.forEach(i=>{i.type==="text"&&(typeof i.text=="string"?o+=t.encode(i.text).length:Array.isArray(i.text)&&i.text.forEach(l=>{o+=t.encode(l||"").length}))}),a&&a.forEach(i=>{i.description&&(o+=t.encode(i.name+i.description).length),i.input_schema&&(o+=t.encode(JSON.stringify(i.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let t=this.encoding;if(!t)throw new Error("Encoding not initialized");return Array.from(t.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}}});import{join as Jn}from"path";import{homedir as Dd}from"os";import{existsSync as hr,mkdirSync as Fd}from"fs";import{promises as Wn}from"fs";import{Tokenizer as jd}from"@huggingface/tokenizers";var Kn,Ua=w(()=>{"use strict";Kn=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,t,o={}){this.modelId=e,this.logger=t,this.options=o,this.cacheDir=o.cacheDir||Jn(Dd(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Jn(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Jn(e,"tokenizer.json"),tokenizerConfig:Jn(e,"tokenizer_config.json")}}ensureDir(e){hr(e)||Fd(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!hr(e.tokenizerJson)||!hr(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Wn.readFile(e.tokenizerJson,"utf-8"),Wn.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(t),tokenizerConfig:JSON.parse(o)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),t={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let o=new AbortController,r=setTimeout(()=>o.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(t.json,{signal:o.signal}),fetch(t.config,{signal:o.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[i,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Wn.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Wn.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:i,tokenizerConfig:l}}finally{clearTimeout(r)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let t=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new jd(t.tokenizerJson,t.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let t=this.extractTextFromRequest(e);return this.tokenizer.encode(t).ids.length}catch(t){throw this.logger?.error(`Error counting tokens: ${t.message}`),t}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let t=[],{messages:o,system:r,tools:s}=e;if(Array.isArray(o)){for(let a of o)if(typeof a.content=="string")t.push(a.content);else if(Array.isArray(a.content)){for(let i of a.content)if(i.type==="text"&&i.text)t.push(i.text);else if(i.type==="tool_use"&&i.input)t.push(JSON.stringify(i.input));else if(i.type==="tool_result")if(Array.isArray(i.content))for(let l of i.content)l?.type!=="image"&&t.push(l?.type==="text"?String(l.text??""):JSON.stringify(l));else t.push(typeof i.content=="string"?i.content:JSON.stringify(i.content))}}if(typeof r=="string")t.push(r);else if(Array.isArray(r)){for(let a of r)if(a.type==="text"){if(typeof a.text=="string")t.push(a.text);else if(Array.isArray(a.text))for(let i of a.text)i&&t.push(i)}}if(s)for(let a of s)a.name&&t.push(a.name),a.description&&t.push(a.description),a.input_schema&&t.push(JSON.stringify(a.input_schema));return t.join(" ")}}});var Gn,Da=w(()=>{"use strict";q();Gn=class{type="api";name;config;logger;options;constructor(e,t,o={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=t,this.options=o;try{let r=new URL(e.url);this.name=`api-${r.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let t=this.formatRequestBody(e),o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout||3e4),a={method:"POST",headers:o,body:JSON.stringify(t),signal:r.signal},i=this.options.resolveProxyUrl?.();i&&(a.dispatcher=G(i));let l=await fetch(this.config.url,a);if(clearTimeout(s),!l.ok)throw new Error(`API tokenizer request failed: ${l.status} ${l.statusText}`);let c=await l.json();return this.extractTokenCount(c)}catch(t){throw t.name==="AbortError"?new Error("API tokenizer request timed out"):t}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(t=>({role:t.role,content:this.extractTextFromMessage(t)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(t=>t.type==="text"&&t.text?t.text:t.type==="tool_use"&&t.input?JSON.stringify(t.input):t.type==="tool_result"?Array.isArray(t.content)?t.content.filter(o=>o?.type!=="image").map(o=>o?.type==="text"?String(o.text??""):JSON.stringify(o)).join(`
|
|
297
|
+
`):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Xe,yr=w(()=>{"use strict";Na();Ua();Da();q();Xe=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new _t("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e,t){let o=this.getCacheKey(e,t);if(this.tokenizers.has(o))return this.tokenizers.get(o);let r;try{switch(e.type){case"tiktoken":r=new _t(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Kn(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Gn(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return de(this.configService,s)}});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(o,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${o})`),r}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,t,o){let r=t?await this.getTokenizer(t,o):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,t){let r=(this.configService.get("providers")||[]).find(s=>s.name===e);if(r?.tokenizer)return r.tokenizer.models?.[t]?r.tokenizer.models[t]:r.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(t){this.logger?.error(`Error disposing tokenizer: ${t}`)}}),this.tokenizers.clear()}getCacheKey(e,t){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${t||"unscoped"}:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}getRawProvider(e){return(this.configService.get("providers")||[]).find(o=>o?.name===e)}}});function Fa(n){if(!n||typeof n!="object"||Gd(n))return null;for(let t of Kd(n)){let o=Wd(t);if(o)return o}return null}function Wd(n){if(!n||typeof n!="object")return null;let e={},t=Qn(n,Hd);if(t!==void 0){let a=ja(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Qn(n,zd);if(o!==void 0){let a=ja(o);e.usedBalance=a,e.totalBalance=100}let r=Qn(n,Bd);if(r!==void 0){let a=Ha(r);a&&(e.resetTime=a)}let s=Qn(n,Jd);if(s!==void 0){let a=Ha(s);a&&(e.resetTime7d=a,e.resetTime||(e.resetTime=a))}return e.usedDailyBalance===void 0&&e.limitDaily===void 0&&e.usedBalance===void 0&&e.totalBalance===void 0&&e.resetTime===void 0?null:e}function ja(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Qn(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function Kd(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function Gd(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function Ha(n){if(typeof n!="string"&&typeof n!="number")return;let e=n;if(typeof n=="number"&&n<1e12&&(e=n*1e3),typeof n=="string"){let o=Number(n.trim());Number.isFinite(o)&&o<1e12&&(e=o*1e3)}let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}function Er(n){let e=Ar(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?tp:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?np:e==="deepseek.com"||e.endsWith(".deepseek.com")?Qd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Vd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Yd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Xd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Zd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?qd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?ep:null:null}function op(n){let e=Ar(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function rp(n,e){let t=wr(n);if(t.length===0)return null;let o=String(e||"").split(":").map(s=>s.trim()).filter(Boolean);return t.find(s=>{let a=s?.codingPlanAppCredentialDTO||s?.appCredential||s,i=String(a?.apiKey||a?.api_key||"").trim();return i&&o.some(l=>l.includes(i)||i.includes(l))})||t[0]}function wr(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>wr(e)):Object.values(n).flatMap(e=>wr(e))}function Pr(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function Ar(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function U(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var se,_r,br,kr,Tr,vr,Hd,zd,Bd,Jd,xr,Sr,Cr,Rr,Qd,Vd,Yd,Xd,Zd,qd,ep,tp,np,Or=w(()=>{"use strict";q();se=class{async fetchJson(e,t,o,r,s){let a=s||t.apiKey;if(!a)return null;let i={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(o)};try{r&&(i.dispatcher=G(r));let l=await fetch(e,i);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},_r=class extends se{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(l=>U(l?.total_balance)!==void 0);if(!a)return null;let i=U(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},br=class extends se{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=U(s.limit),l=U(s.limit_remaining),c=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),l!==void 0&&(a.remainingBalance=l),c!==void 0&&(a.usedBalance=c),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},kr=class extends se{async queryQuota(e,t,o){let r=op(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},l=U(a.totalBalance),c=U(a.balance);return l!==void 0&&(i.totalBalance=l),c!==void 0&&(i.remainingBalance=c),l!==void 0&&c!==void 0&&(i.usedBalance=Math.max(0,l-c)),this.hasQuotaData(i)?i:null}},Tr=class extends se{async queryQuota(e,t,o){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let i=await a.json(),l=Array.isArray(i?.data?.limits)?i.data.limits:[],c=null,u=null,p=null;for(let f of l)f.type==="TOKENS_LIMIT"?f.unit===3?c=f:f.unit===6?u=f:c||(c=f):f.type==="TIME_LIMIT"&&(p=f);let d={};if(c){let f=U(c.currentValue),g=U(c.usage),h=U(c.remaining),m=U(c.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),g!==void 0?d.limitDaily=g:f!==void 0&&h!==void 0&&(d.limitDaily=f+h),c.nextResetTime&&(d.resetTime=new Date(c.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),g=U(u.usage),h=U(u.remaining),m=U(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),g!==void 0?d.totalBalance=g:f!==void 0&&h!==void 0&&(d.totalBalance=f+h),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=U(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=U(p.usage),g=U(p.currentValue),h=U(p.remaining);f!==void 0?d.limitDaily=f:g!==void 0&&h!==void 0&&(d.limitDaily=g+h)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},vr=class extends se{async queryQuota(e,t,o){if(!e.quotaToken)return null;let r={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(t)},s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{o&&(r.dispatcher=G(o));let i=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...r,body:a});if(!i.ok)return null;let c=(await i.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(c)||c.length===0)return null;let u=c[0]?.codingPlanQuotaInfo;if(!u)return null;let p={},d=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let g=U(u.perWeekUsedQuota),h=U(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),h!==void 0&&(p.totalBalance=h),this.hasQuotaData(p)?p:null}catch{return null}}};Hd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],zd=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Bd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Jd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];xr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken?.trim();if(!r)return null;let s=e.quotaSecToken?.trim();if(s){try{let a=await this.queryOfficialEndpoint(r,s,t,o);if(a)return a}catch{}return this.queryLegacyEndpoint(r,t,o)}return this.queryLegacyEndpoint(r,t,o)}async queryOfficialEndpoint(e,t,o,r){let s="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",a=Pr(e,"cna")||"",i=JSON.stringify({Api:s,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan#/efm/subscription/token-plan/personal",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN","X-Anonymous-Id":a}}}),l=new URLSearchParams({params:i,region:"cn-beijing",sec_token:t}).toString(),c={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing/?tab=plan"},body:l,signal:AbortSignal.timeout(o)};try{r&&(c.dispatcher=G(r));let u=await fetch(`https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=${encodeURIComponent(s)}&_v=undefined`,c);if(!u.ok)return null;let p=await u.json();return Fa(p)}catch{return null}}async queryLegacyEndpoint(e,t,o){let r="zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage",s=JSON.stringify({Api:r,V:"1.0",Data:{cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString(),i={method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Accept-Encoding":"identity",Cookie:e,"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/"},body:a,signal:AbortSignal.timeout(t)};try{o&&(i.dispatcher=G(o));let l=await fetch(`https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian&action=BroadScopeAspnGateway&api=${encodeURIComponent(r)}`,i);if(!l.ok)return null;let c=await l.json();return Fa(c)}catch{return null}}},Sr=class extends se{async queryQuota(e,t,o){if(!e.quotaToken)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://maas.xfyun.cn",Referer:"https://maas.xfyun.cn/packageSubscription",Authorization:(Pr(e.quotaToken,"atp-auth-token")||Pr(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://maas.xfyun.cn/api/v1/gpt-finetune/coding-plan/list?page=1&size=10",s);if(!a.ok)return null;let i=await a.json();if(i?.succeed===!1||i?.failed===!0)return null;let l=rp(i,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},p=U(c.rp5hUsage),d=U(c.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=U(c.rpwUsage),g=U(c.rpwLimit);return f!==void 0&&(u.usedBalance=f),g!==void 0&&(u.totalBalance=g),u.remainingBalance===void 0&&g!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,g-f)),this.hasQuotaData(u)?u:null}catch{return null}}},Cr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s={method:"GET",headers:{Accept:"application/json","Accept-Encoding":"identity",Authorization:`Bearer ${r.trim()}`},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=G(o));let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let i=await a.json(),l={},c=Array.isArray(i?.limits)?i.limits:[];if(c.length>0&&c[0]?.detail){let p=c[0].detail,d=U(p.limit),f=U(p.remaining),g=p.resetTime;d!==void 0&&f!==void 0&&(l.usedDailyBalance=Math.max(0,d-f),l.limitDaily=d),g&&(l.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let p=U(u.limit),d=U(u.remaining),f=U(u.used),g=u.resetTime;p!==void 0&&(l.totalBalance=p,f!==void 0?l.usedBalance=f:d!==void 0&&(l.usedBalance=Math.max(0,p-d),l.remainingBalance=d)),g&&(l.resetTime7d=new Date(g).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},Rr=class extends se{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=Ar(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let i=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let k of i)if(l=await this.fetchJson(k,e,t,o,r.trim()),l)break;if(!l)return null;if(l?.base_resp){let k=l.base_resp.status_code;if(k!==void 0&&k!==0)return null}let c=Array.isArray(l?.model_remains)?l.model_remains:[];if(c.length===0)return null;let u=c[0],p={},d=U(u.current_interval_total_count),f=U(u.current_interval_usage_count),g=U(u.current_interval_remaining_percent),h=U(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):g!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-g)),h&&(p.resetTime=new Date(h).toISOString());let m=U(u.current_weekly_total_count),y=U(u.current_weekly_usage_count),b=U(u.current_weekly_remaining_percent),_=U(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Qd=new _r,Vd=new br,Yd=new kr,Xd=new Tr,Zd=new vr,qd=new xr,ep=new Sr,tp=new Cr,np=new Rr});async function Vn(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=za.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<sp)return;let r=o??{fetchedAt:0};return r.pending=(async()=>{try{let s=await t.fetchQuota(e);s&<(n,s)}catch{}finally{r.fetchedAt=Date.now(),r.pending=void 0}})(),za.set(n,r),r.pending}var sp,Ba,za,Ir=w(()=>{"use strict";Ce();sp=6e4,Ba=2500,za=new Map});function Ja(n){return{[ip]:n,[ap]:Vt}}function _e(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function lp(n){return n===!0||n==="true"||n===1||n==="1"}function up(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function dp(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function pp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Mr(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(_e(n))return{success:!1,skipped:!0,error:Lr,latencyMs:r()};let s=dp(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=G(t));let i=await fetch(s,a);if(i.headers&&it(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let l=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${l.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",l=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:l?"timeout":"network"}}}async function fp(n,e,t,o){if(_e(n))return{success:!1,skipped:!0,error:Lr};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...Ja("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(l.dispatcher=G(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let c=await fetch(s,l);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function mp(n,e,t,o,r){if(_e(n))return{success:!1,skipped:!0,error:Lr};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...Ja("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let l={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(l.dispatcher=G(o)),r?.debug?.(`Sending independent ping to rate-limited model ${n.name} (${e})...`);let c=await fetch(s,l);if(c.ok)return{success:!0};let u=await c.text().catch(()=>"");return{success:!1,error:`HTTP ${c.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown ping error"}}}function Wa(n,e,t,o,r,s){return be||(be=new Yn(n,e,t,o,r,s)),be}function bt(n,e,t,o,r,s){let a=Wa(n,e,t,o,r,s);return a.start(),a}function $r(){be&&be.stop()}function Nr(){be&&(be.stop(),be=null)}var ip,ap,cp,Lr,Yn,be,Xn=w(()=>{"use strict";re();Se();Or();Ce();Ir();$o();q();ip="x-claude-code-router-source",ap="x-claude-code-router-version";cp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};Lr="Managed provider requires its plugin's authenticated model sync";Yn=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,a){this.config={...cp,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),l={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,l),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),l}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.managedProbeTimer=setInterval(()=>this.runManagedRecoveryProbe(),this.config.quotaProbeIntervalMinutes*60*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.managedProbeTimer&&(clearInterval(this.managedProbeTimer),this.managedProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!_e(s)&&!this.config.excludeProviders.includes(s.name)),t=H(),o=[];for(let s of e){let a=Er(s.baseUrl),i=Array.isArray(s.models)?s.models:[],l=this.resolveProxyUrl?.(s);if(!a){let c;try{c=new URL(s.baseUrl).hostname}catch{c=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(c?` (host: ${c})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,l).then(c=>{if(c){lt(s.name,c),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,p=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${c.usedDailyBalance}/${c.limitDaily})`:`Quota exhausted: 7d balance depleted (${c.usedBalance}/${c.totalBalance})`;for(let f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),pp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:Mr(s,this.config.probeTimeoutMs,l).then(c=>{this.recordProbe(s.name,c,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&_e(a)&&!this.config.excludeProviders.includes(a.name));for(let a of s){let i=this.resolveManagedRuntime(a);i&&typeof i.fetchQuota=="function"&&o.push({provider:a.name,models:Array.isArray(a.models)?a.models:[],type:"managed-plugin-quota",promise:Vn(a.name,a,i)})}}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=H(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!_e(r)&&!this.config.excludeProviders.includes(r.name));if(t.length===0)return;this.logger?.debug?.(`Running health probe for ${t.length} providers`);let o=await Promise.allSettled(t.map(r=>Mr(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let l=a.value;if(l.skipped)continue;if(this.recordProbe(s.name,l,"health"),l.success){let c=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),c++}c>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let c of i)e.recordFailure(s.name,c,l.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${l.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let l of i)e.recordFailure(s.name,l,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=H();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let l=o.get(s)??[];l.push(i),o.set(s,l)}for(let[r,s]of o){let a=this.getProviders().find(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let l=s[0],c=e.getState(r,l);!c||c.status!=="open"||c.rateLimitUntil&&Date.now()<c.rateLimitUntil||Date.now()-(c.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,l,s,e)||await this.probeManagedLiveness(r,i,a,l,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=this.config.probeTimeoutMs,l={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},c=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(l),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:c,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:c,requestBody:l,config:u,provider:o}):await c();if(p?.ok){for(let d of s)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=H(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),l=i.join(",");if(!a||!l)continue;let c=o.find(d=>d?.name===a);if(c&&_e(c))continue;let u=e.getState(a,l);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,l),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await mp(p,l,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,l);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!_e(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=up(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let l=i.wakeupTime||a,[c,u]=l.split(":"),p=parseInt(c,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,g=(p*60+d)*6e4-(o*60+r)*6e4,h=g>0&&g<=300*1e3;(f||h)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${l}`),fp(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?lp(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await Mr(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)H().recordSuccess(o.name,i);else for(let i of a)H().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},be=null});var Ka=w(()=>{"use strict"});var Ur,kt,Ga=w(()=>{"use strict";Ur=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},kt=new Ur});var ie,Dr=w(()=>{"use strict";ie=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
298
|
+
`);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var Ze,Fr=w(()=>{"use strict";Ze=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
293
299
|
`),e.id&&(o+=`id: ${e.id}
|
|
294
300
|
`),e.retry&&(o+=`retry: ${e.retry}
|
|
295
301
|
`),e.data&&(e.data.type==="done"?o+=`data: [DONE]
|
|
296
302
|
`:o+=`data: ${JSON.stringify(e.data)}
|
|
297
303
|
`),o+=`
|
|
298
|
-
`,t.enqueue(o)}})}}});var
|
|
304
|
+
`,t.enqueue(o)}})}}});var Zn,jr=w(()=>{"use strict";Zn=(n,e)=>{let t=n.getReader();return new ReadableStream({async start(o){try{for(;;){let{done:r,value:s}=await t.read();if(r){o.close();break}let a=await e(s,o);a!==void 0&&o.enqueue(a)}}catch(r){o.error(r)}finally{t.releaseLock()}}})}});var Hr=w(()=>{"use strict";Dr();Fr();jr()});var Qa=w(()=>{"use strict"});var Tt,zr=w(()=>{"use strict";Tt=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,t){let{format:o="text",timestamp:r=!0,prefix:s,metadata:a}=t||{},i="";if(r){let l=new Date().toISOString();i+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(i+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),o){case"json":i+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?i+=this.toMarkdown(e):i+=String(e);break;case"text":default:typeof e=="object"?i+=JSON.stringify(e,null,2):i+=String(e);break}return a&&Object.keys(a).length>0&&(i+=`
|
|
299
305
|
`+(this.config.colors?`${this.colors.dim}`:""),i+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(i+=this.colors.reset)),i}toMarkdown(e,t=0){let o=" ".repeat(t);return Array.isArray(e)?e.map(r=>typeof r=="object"?`${o}-
|
|
300
306
|
${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
|
|
301
307
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
|
|
302
308
|
${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
303
|
-
`):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var vt,Ur=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 Zn,opendir as ip,unlink as ap}from"node:fs/promises";import{join as Ba,resolve as Hr}from"node:path";import{tmpdir as cp}from"node:os";async function qn(n,e){let t=Hr(n),o=Xn.get(t),r,s=new Promise(a=>{r=a});Xn.set(t,s);try{return await o,await e()}finally{r(),Xn.get(t)===s&&Xn.delete(t)}}function Ja(n,e){return n.dev===e.dev&&n.ino===e.ino}async function za(n,e){try{let t=await Zn(n);return t.isDirectory()&&!t.isSymbolicLink()&&Ja(e,t)}catch{return!1}}function fp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Wa(n,e,t,o){let r=Hr(n);if(o?.aborted||Dr.has(r))return 0;Dr.add(r);let s=0;try{let a=await Zn(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await ip(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=Ba(r,u.name);try{let d=await Zn(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await qn(p,async()=>{if(o?.aborted||!await za(r,a))return!1;let h=await Zn(p);return!h.isFile()||h.isSymbolicLink()||!Ja(d,h)||h.mtimeMs!==d.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await ap(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await fp(),l=!o?.aborted&&await za(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Dr.delete(r)}return s}function Ka(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Wa(n,Date.now()-o,i=>pp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function mp(n,e){let t=Date.now()-lp;return Wa(n,t,o=>{let r=dp.exec(o);return r!==null&&Number(r[1])<t},e)}function zr(n,e,t){let o=jr.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,up),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},jr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),jr.delete(n)))}}function Ga(n=Ba(cp(),"claude-code-router")){return zr(`legacy:${Hr(n)}`,e=>mp(n,e),1e3)}var lp,up,dp,pp,Dr,Xn,jr,Br=w(()=>{"use strict";lp=3600*1e3,up=600*1e3,dp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,pp=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,Dr=new Set,Xn=new Map,jr=new Map});import{lstat as gp,mkdir as hp,open as yp,rename as _p,unlink as bp}from"node:fs/promises";import{randomUUID as kp}from"node:crypto";import{sanitizeTempFileKey as Tp}from"@wengine-ai/claude-code-router-shared";import{basename as vp,join as Jr,resolve as xp}from"node:path";import{tmpdir as Cp}from"node:os";var xt,Wr=w(()=>{"use strict";Br();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=xp(Jr(Cp(),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=zr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await hp(this.baseDir,{recursive:!0});let e=await gp(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}-${Tp(e)}${r}${o}`;if(vp(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 qn(a,async()=>{await this.ensureDir();let i=Jr(this.baseDir,`.ccr-tmp-${process.pid}-${kp()}.tmp`);return qn(i,async()=>{let c=!1;try{let l=await yp(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await _p(i,a),!0}finally{c&&await bp(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return Ka(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Kr,qe,Va=w(()=>{"use strict";Fr();Ur();Wr();Kr=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 Kr});var Gr=w(()=>{"use strict";Ha();Fr();Ur();Wr();Va()});import Sp from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Rp}from"@wengine-ai/claude-code-router-shared";function eo(){return{subdirectory:Rp,extension:"json",includeTimestamp:!1,prefix:"session"}}function Qa(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,wp);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 Ya(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,Vr,wp,to,Xa=w(()=>{"use strict";$r();Gr();je();Ct=new Map,Vr=new Map,wp=1,to={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:Sp(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:eo()}):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(Vr.has(u))return Vr.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 Vr.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=Qa(v.tokenCount,P,S),await Ya(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:Qa(g,y),stream:!1};await Ya(b,o,t.outputOptions,!0)}return c})})}});var Qr=w(()=>{"use strict";Da();ja();Xa();Gr()});import ne from"node:fs/promises";import Za from"json5";import Ae from"node:path";import{CONFIG_FILE as oe,HOME_DIR as no,PLUGINS_DIR as Pp}from"@wengine-ai/claude-code-router-shared";function qa(){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 Yr,Rt,oo,wt,X,ro,ue,Ep,Xr,Pt=w(()=>{"use strict";Yr=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(Yr);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Yr(o);return e}return n},Rt=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},oo=async()=>{await Rt(no),await Rt(Pp),await Rt(Ae.join(no,"logs"))},wt=async()=>{let n=await ne.readFile(oe,"utf-8");return Za.parse(n)},X=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=Za.parse(n);return Yr(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 oo();let e=await ro();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)}};ro=async()=>{qa();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=Ae.dirname(oe),o=Ae.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=Ae.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=>{qa(),await Rt(no),await Ep();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},Ep=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=Ae.join(no,"config-history");await Rt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ae.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(Ae.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},Xr=async()=>{let n=await X();return Object.assign(process.env,n),n}});function so(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(Zr(r,s))}return}if(Array.isArray(n)){for(let o of n)so(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))so(o,e,t)}}function ec(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(Zr(s,i))}return so(n?.Router,t,o),so(n?.fallback,t,o),o}function Et(n,e){try{let t=j();if(!t?.getAllStates||!t?.recover)return 0;let o=ec(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(Zr(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 io(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 Ap,Zr,At=w(()=>{"use strict";se();Ap="\0",Zr=(n,e)=>`${n}${Ap}${e}`});function Op(n){return/\[1m\]/i.test(n)?1e6:2e5}function Ip(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Mp(n,e=n){let t=Op(n),o=Ip(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 Lp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function qr(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Mp(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=Lp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var es=w(()=>{"use strict"});function Np(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var ao,ts=w(()=>{"use strict";ao=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Np(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 uc={};bo(uc,{append:()=>Nt,clear:()=>ss,close:()=>of,getOldestRecordTimestamp:()=>rf,query:()=>rs,querySummary:()=>$t,readTokenSpeedStats:()=>is});import{existsSync as oc,mkdirSync as $p,readFileSync as rc}from"fs";import{join as uo}from"path";import{tmpdir as Fp}from"os";import{openSqliteDatabase as Up}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Dp,sanitizeTempFileKey as jp,TOKEN_SPEED_TEMP_SUBDIRECTORY as Hp}from"@wengine-ai/claude-code-router-shared";function Kp(){oc(lo)||$p(lo,{recursive:!0})}function Lt(){if(ke)return ke;Kp();let n=Up(zp),e=n.db;n.driver==="node:sqlite"&&console.error(`[usage] better-sqlite3 unavailable, using built-in node:sqlite fallback. Reason: ${n.fallbackReason}`),e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("busy_timeout = 5000");let t=e.pragma("user_version",{simple:!0})||0;return t<1&&(Gp(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")),Qp(e),ac(e,!0),os=e.prepare(`
|
|
309
|
+
`):`${o}${e}`}async output(e,t={}){try{let o=this.formatData(e,t);switch(this.config.level||"log"){case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o);break;case"debug":console.debug(o);break;case"log":default:console.log(o);break}return!0}catch(o){return console.error("[ConsoleOutputHandler] Output failed:",o),!1}}}});var vt,Br=w(()=>{"use strict";vt=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let t=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${t}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,t){let{format:o="json",timestamp:r=!0,prefix:s,metadata:a}=t||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),s&&(i.prefix=s),a&&Object.keys(a).length>0&&(i.metadata=a),i}async sendRequest(e,t,o,r,s){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:t,headers:o,body:JSON.stringify(r),signal:a.signal});if(clearTimeout(i),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(i),l}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendWithRetry(e,t,o,r,s,a){let i=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,t,o,r,s)}catch(c){if(i=c,l===a.maxAttempts)break;let u=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${u}ms...`,c.message),await this.delay(u)}throw i}async output(e,t={}){let o=t.timeout||this.defaultTimeout;try{let r=this.buildHeaders(),s=this.buildBody(e,t),a=await this.sendWithRetry(this.config.url,this.config.method,r,s,o,this.config.retry);return!0}catch(r){let s=r instanceof Error?r.message:String(r);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{lstat as eo,opendir as hp,unlink as yp}from"node:fs/promises";import{join as Ya,resolve as Kr}from"node:path";import{tmpdir as _p}from"node:os";async function to(n,e){let t=Kr(n),o=qn.get(t),r,s=new Promise(a=>{r=a});qn.set(t,s);try{return await o,await e()}finally{r(),qn.get(t)===s&&qn.delete(t)}}function Xa(n,e){return n.dev===e.dev&&n.ino===e.ino}async function Va(n,e){try{let t=await eo(n);return t.isDirectory()&&!t.isSymbolicLink()&&Xa(e,t)}catch{return!1}}function xp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Za(n,e,t,o){let r=Kr(n);if(o?.aborted||Jr.has(r))return 0;Jr.add(r);let s=0;try{let a=await eo(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await hp(r,{bufferSize:32});try{let l=0,c=!0;for await(let u of i){if(o?.aborted||!c)break;try{if(!u.isFile()||u.isSymbolicLink()||!t(u.name))continue;let p=Ya(r,u.name);try{let d=await eo(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await to(p,async()=>{if(o?.aborted||!await Va(r,a))return!1;let g=await eo(p);return!g.isFile()||g.isSymbolicLink()||!Xa(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await yp(p),!0)})&&s++}catch{}}finally{++l%64===0&&(await xp(),c=!o?.aborted&&await Va(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{Jr.delete(r)}return s}function qa(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Za(n,Date.now()-o,i=>vp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function Sp(n,e){let t=Date.now()-bp;return Za(n,t,o=>{let r=Tp.exec(o);return r!==null&&Number(r[1])<t},e)}function Gr(n,e,t){let o=Wr.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},l=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,kp),a.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),a&&clearInterval(a)}},Wr.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Wr.delete(n)))}}function ec(n=Ya(_p(),"claude-code-router")){return Gr(`legacy:${Kr(n)}`,e=>Sp(n,e),1e3)}var bp,kp,Tp,vp,Jr,qn,Wr,Qr=w(()=>{"use strict";bp=3600*1e3,kp=600*1e3,Tp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,vp=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,Jr=new Set,qn=new Map,Wr=new Map});import{lstat as Cp,mkdir as Rp,open as wp,rename as Pp,unlink as Ep}from"node:fs/promises";import{randomUUID as Ap}from"node:crypto";import{sanitizeTempFileKey as Op}from"@wengine-ai/claude-code-router-shared";import{basename as Ip,join as Vr,resolve as Mp}from"node:path";import{tmpdir as Lp}from"node:os";var xt,Yr=w(()=>{"use strict";Qr();xt=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=Mp(Vr(Lp(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=Gr(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await Rp(this.baseDir,{recursive:!0});let e=await Cp(this.baseDir);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Unsafe temp output directory")}getFilePath(e){let t=this.config.prefix||"session",o=this.config.extension?`.${this.config.extension}`:"",r=this.config.includeTimestamp?`-${Date.now()}`:"",s=`${t}-${Op(e)}${r}${o}`;if(Ip(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return Vr(this.baseDir,s)}async output(e,t={}){try{let o=typeof t.metadata?.statsKey=="string"&&t.metadata.statsKey?t.metadata.statsKey:t.metadata?.sessionId;if(!o)return!1;let r=t.metadata?.sessionId??o,s=JSON.stringify({...e,timestamp:Date.now(),sessionId:r},null,2),a=this.getFilePath(o);return await to(a,async()=>{await this.ensureDir();let i=Vr(this.baseDir,`.ccr-tmp-${process.pid}-${Ap()}.tmp`);return to(i,async()=>{let l=!1;try{let c=await wp(i,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await Pp(i,a),!0}finally{l&&await Ep(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return qa(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Xr,qe,tc=w(()=>{"use strict";zr();Br();Yr();Xr=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new Tt(e.config);case"webhook":return new vt(e.config);case"temp-file":return new xt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let l=this.handlers.get(i);if(!l){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await l.output(t,r)?s.success.push(i):s.failed.push(i)}catch(c){console.error(`[OutputManager] Handler ${i} failed:`,c),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},qe=new Xr});var Zr=w(()=>{"use strict";Qa();zr();Br();Yr();tc()});import $p from"fastify-plugin";import{TOKEN_SPEED_TEMP_SUBDIRECTORY as Np}from"@wengine-ai/claude-code-router-shared";function no(){return{subdirectory:Np,extension:"json",includeTimestamp:!1,prefix:"session"}}function nc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,Up);return Math.round(n/o)}function Ct(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function oc(n,e,t,o=!1){let r=o?"[Token Speed Final]":"[Token Speed]",s={requestId:n.requestId.substring(0,8),sessionId:n.sessionId,stream:n.stream,tokenCount:n.tokenCount,tokensPerSecond:n.tokensPerSecond,timeToFirstToken:n.timeToFirstToken?`${n.timeToFirstToken}ms`:"N/A",duration:`${((n.lastTokenTime-n.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:r,metadata:{sessionId:n.sessionId,statsKey:n.statsKey},...t};for(let i of e)try{await qe.outputToType(i,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,l)}}var St,qr,Up,oo,rc=w(()=>{"use strict";Hr();Zr();je();St=new Map,qr=new Map,Up=1,oo={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:$p(async(n,e)=>{let t={reporter:["console","temp-file"],...e},o=Array.isArray(t.reporter)?t.reporter:[t.reporter];if(t.outputHandlers&&t.outputHandlers.length>0)qe.registerHandlers(t.outputHandlers);else{let a=[];for(let i of o)i==="console"?a.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?a.push({type:"temp-file",enabled:!0,config:no()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&qe.registerHandlers(a)}t.outputOptions&&qe.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let l=a.provider,c=a.model,u=`${l}:${c}`;if(qr.has(u))return qr.get(u);let p=i.getTokenizerConfigForModel(l,c);if(!p)return n.log?.debug(`No tokenizer config for ${l}:${c}, using fallback`),null;try{let d=await i.getTokenizer(p,l);return qr.set(u,d),n.log?.info(`Created tokenizer for ${l}:${c} - ${d.name}`),d}catch(d){return n.log?.warn(`Failed to create tokenizer for ${l}:${c}: ${d.message}`),null}},s=a=>{let i=new URL(`http://127.0.0.1${a}`).pathname;return i.endsWith("/v1/messages")||i.endsWith("/v1/responses")};n.addHook("onRequest",async a=>{s(a.url)&&(a.requestStartTime=performance.now())}),n.addHook("onSend",async(a,i,l)=>{let c=a.requestStartTime;if(!c)return;let u=a.id||Date.now().toString(),p=a.usageSessionId||u,d=a.sessionId;if(!d)try{d=he(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(l instanceof ReadableStream){St.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=l.tee(),_=async()=>{let k=null,T=async x=>{let v=St.get(u);if(!v)return;let P=v.firstTokenTime?v.firstTokenTime-v.startTime:0,R=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=nc(v.tokenCount,R,P),await oc(v,o,t.outputOptions,x).catch(A=>{n.log?.warn(`Failed to output streaming stats: ${A.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();for(k=setInterval(async()=>{St.get(u)&&await T(!1)},1e3);;){let{done:P,value:E}=await v.read();if(P)break;let R=E,A=St.get(u);if(!A)continue;let D=performance.now(),C=R.event||R.data?.type,O=R.event==="content_block_start"||R.event==="content_block_delta"||R.event==="text_block"||R.event==="content_block"||C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta";!A.firstTokenTime&&O&&(A.firstTokenTime=D,A.timeToFirstToken=Math.round(D-A.startTime));let S="";if(R.event==="content_block_delta"&&R.data?.delta){let I=R.data.delta.type;I==="text_delta"?S=R.data.delta.text||"":I==="input_json_delta"?S=R.data.delta.partial_json||"":I==="thinking_delta"&&(S=R.data.delta.thinking||"")}if((C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta")&&(S=typeof R.data?.delta=="string"?R.data.delta:""),S){let I=f&&f.encodeText?f.encodeText(S).length:Ct(S);A.tokenCount+=I,A.lastTokenTime=D}(R.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),St.delete(u))}}catch(x){k&&clearInterval(k),x.name!=="AbortError"&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${x.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let g=performance.now(),h=0,m=!1;if(l&&typeof l=="string")try{let y=JSON.parse(l);if(typeof y.usage?.output_tokens=="number")h=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?h=b.reduce((_,k)=>{if(k.type==="text"){let T=k.text||"";return _+(f.encodeText?f.encodeText(T).length:Ct(T))}return _},0):typeof b=="string"&&(h=f.encodeText?f.encodeText(b).length:Ct(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";h=Ct(_)}}}catch{}if(m){let y=g-c,b={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:g,tokenCount:h,tokensPerSecond:nc(h,y),stream:!1};await oc(b,o,t.outputOptions,!0)}return l})})}});var es=w(()=>{"use strict";Ka();Ga();rc();Zr()});import ne from"node:fs/promises";import sc from"json5";import Oe from"node:path";import{CONFIG_FILE as oe,HOME_DIR as ro,PLUGINS_DIR as Dp}from"@wengine-ai/claude-code-router-shared";function ic(){if(process.env.VITEST||process.env.CI)throw new Error("Config write attempted during test/CI. Set CCR_CONFIG_DIR to a temp dir to isolate.")}var ts,Rt,so,wt,X,io,ue,Fp,ns,Pt=w(()=>{"use strict";ts=n=>{if(typeof n=="string")return n.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,t,o)=>{let r=t||o;return process.env[r]||e});if(Array.isArray(n))return n.map(ts);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=ts(o);return e}return n},Rt=async n=>{try{await ne.access(n)}catch{await ne.mkdir(n,{recursive:!0})}},so=async()=>{await Rt(ro),await Rt(Dp),await Rt(Oe.join(ro,"logs"))},wt=async()=>{let n=await ne.readFile(oe,"utf-8");return sc.parse(n)},X=async()=>{try{let n=await ne.readFile(oe,"utf-8");try{let e=sc.parse(n);return ts(e)}catch(e){console.error(`Failed to parse config file at ${oe}`),console.error("Error details:",e.message),console.error("Please check your config file syntax."),process.exit(1)}}catch(n){if(n.code==="ENOENT")try{await so();let e=await io();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await ue(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${oe}`),console.error("Error details:",n.message),process.exit(1)}};io=async()=>{ic();try{if(await ne.access(oe).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${oe}.${n}.bak`;await ne.copyFile(oe,e);try{let t=Oe.dirname(oe),o=Oe.basename(oe),s=(await ne.readdir(t)).filter(a=>a.startsWith(o)&&a.endsWith(".bak")).sort().reverse();if(s.length>3)for(let a=3;a<s.length;a++){let i=Oe.join(t,s[a]);await ne.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},ue=async n=>{ic(),await Rt(ro),await Fp();let e=`${JSON.stringify(n,null,2)}`;await ne.writeFile(oe,e)},Fp=async()=>{if(!await ne.access(oe).then(()=>!0).catch(()=>!1))return;let e=Oe.join(ro,"config-history");await Rt(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Oe.join(e,`config-${t}.json`);await ne.copyFile(oe,o);try{let s=(await ne.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ne.unlink(Oe.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},ns=async()=>{let n=await X();return Object.assign(process.env,n),n}});function ao(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(os(r,s))}return}if(Array.isArray(n)){for(let o of n)ao(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))ao(o,e,t)}}function ac(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let i of a)i&&o.add(os(s,i))}return ao(n?.Router,t,o),ao(n?.fallback,t,o),o}function Et(n,e){try{let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=ac(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(os(a,i))||(t.recover(a,i),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function co(n,e){try{if(!n)return 0;let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var jp,os,At=w(()=>{"use strict";re();jp="\0",os=(n,e)=>`${n}${jp}${e}`});function Hp(n){return/\[1m\]/i.test(n)?1e6:2e5}function zp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function Bp(n,e=n){let t=Hp(n),o=zp(n);return{type:"model",id:n,display_name:e,created_at:"2024-01-01T00:00:00Z",context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o,capabilities:{context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o}}}function Jp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function rs(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,Bp(r,s))};o("ccr-opus","CCR Opus"),o("ccr-sonnet","CCR Sonnet"),o("ccr-haiku","CCR Haiku"),o("ccr-opus[1m]","CCR Opus 1M"),o("ccr-sonnet[1m]","CCR Sonnet 1M"),o("ccr-haiku[1m]","CCR Haiku 1M");for(let r of n.Providers||n.providers||[])if(!(!r?.name||!Array.isArray(r.models)))for(let s of r.models){if(typeof s!="string"||!s)continue;let a=Jp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var ss=w(()=>{"use strict"});function Wp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var lo,is=w(()=>{"use strict";lo=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Wp(e))return o();let s=n.Providers||n.providers||[];if(!s||s.length===0)return o();let a=n.APIKEY;if(!a){let u=[`http://127.0.0.1:${n.PORT||3456}`,`http://localhost:${n.PORT||3456}`];if(e.headers.origin&&!u.includes(e.headers.origin)){t.status(403).send("CORS not allowed for this origin");return}else t.header("Access-Control-Allow-Origin",`http://127.0.0.1:${n.PORT||3456}`),t.header("Access-Control-Allow-Origin",`http://localhost:${n.PORT||3456}`);return o()}let i=e.headers.authorization||e.headers["x-api-key"],l=Array.isArray(i)?i[0]:i||"";if(!l){t.log.warn({url:e.url,headers:Object.keys(e.headers)},"[AUTH] No auth header"),t.status(401).send("APIKEY is missing");return}let c="";if(l.startsWith("Bearer")?c=l.split(" ")[1]:c=l,c!==a){t.log.warn({url:e.url,gotPrefix:c.slice(0,10),gotSuffix:c.slice(-6),gotLen:c.length,expectedPrefix:a.slice(0,6),expectedSuffix:a.slice(-6),expectedLen:a.length},"[AUTH] Key mismatch"),t.status(401).send("Invalid API key");return}o()}});var yc={};vo(yc,{append:()=>$t,clear:()=>us,close:()=>mf,getOldestRecordTimestamp:()=>gf,query:()=>ls,querySummary:()=>Nt,readTokenSpeedStats:()=>ds});import{existsSync as uc,mkdirSync as Kp,readFileSync as dc}from"fs";import{join as fo}from"path";import{tmpdir as Gp}from"os";import{openSqliteDatabase as Qp}from"@wengine-ai/claude-code-router-shared";import{HOME_DIR as Vp,sanitizeTempFileKey as Yp,TOKEN_SPEED_TEMP_SUBDIRECTORY as Xp}from"@wengine-ai/claude-code-router-shared";function nf(){uc(po)||Kp(po,{recursive:!0})}function Lt(){if(Te)return Te;nf();let n=Qp(Zp),e=n.db;n.driver==="node:sqlite"&&console.error(`[usage] better-sqlite3 unavailable, using built-in node:sqlite fallback. Reason: ${n.fallbackReason}`),e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("busy_timeout = 5000");let t=e.pragma("user_version",{simple:!0})||0;return t<1&&(of(e),e.pragma("user_version = 1")),t<2&&(e.prepare("PRAGMA table_info(usage_records)").all().some(r=>r.name==="upstream_model")||e.exec("ALTER TABLE usage_records ADD COLUMN upstream_model TEXT"),e.pragma("user_version = 2")),t<3&&(e.exec("ALTER TABLE usage_records ADD COLUMN usage_estimated INTEGER NOT NULL DEFAULT 0"),e.pragma("user_version = 3")),sf(e),mc(e,!0),cs=e.prepare(`
|
|
304
310
|
INSERT INTO usage_records (
|
|
305
311
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
306
312
|
scenario_type, client_type,
|
|
@@ -314,7 +320,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
314
320
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
315
321
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
316
322
|
)
|
|
317
|
-
`),
|
|
323
|
+
`),Te=e,Te}function of(n){n.exec(`
|
|
318
324
|
CREATE TABLE IF NOT EXISTS usage_records (
|
|
319
325
|
id TEXT PRIMARY KEY,
|
|
320
326
|
timestamp TEXT NOT NULL,
|
|
@@ -351,12 +357,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
351
357
|
CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
|
|
352
358
|
CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
|
|
353
359
|
CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
|
|
354
|
-
`)}function
|
|
360
|
+
`)}function rf(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function Ot(n,e,t){n.prepare(`
|
|
355
361
|
INSERT INTO usage_meta (key, value)
|
|
356
362
|
VALUES (?, ?)
|
|
357
363
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
358
|
-
`).run(e,t)}function
|
|
359
|
-
`)){let
|
|
364
|
+
`).run(e,t)}function sf(n){if(rf(n,cc)||!uc(as))return;let e=cf(n,"INSERT OR IGNORE"),t=dc(as,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
|
|
365
|
+
`)){let l=i.trim();if(l)try{let c=JSON.parse(l);if(!af(c)){r++;continue}e.run(fc(mo(c))).changes>0?o++:s++}catch{r++}}Ot(n,cc,new Date().toISOString()),Ot(n,"legacy_usage_jsonl_migrated_path",as),Ot(n,"legacy_usage_jsonl_imported_count",String(o)),Ot(n,"legacy_usage_jsonl_skipped_count",String(r)),Ot(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function af(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.timestamp=="string"&&e.timestamp.length>0}function cf(n,e="INSERT"){return n.prepare(`
|
|
360
366
|
${e} INTO usage_records (
|
|
361
367
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
362
368
|
scenario_type, client_type,
|
|
@@ -370,11 +376,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
370
376
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
371
377
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
372
378
|
)
|
|
373
|
-
`)}function
|
|
374
|
-
SELECT ${t} AS key, ${
|
|
379
|
+
`)}function lf(n,e,t){if(n<=0||e==null||!Number.isFinite(e))return null;let o=t!=null&&Number.isFinite(t)?t:0,r=Math.max((e-o)/1e3,qp);return Math.round(n/r)}function mo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?Mt(n.ttft):null;return{...n,ttft:r,tokensPerSecond:lf(e,o,r)}}function ke(n){return typeof n=="string"?n:n==null?"":String(n)}function uo(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function It(n){let e=Number(n);return Number.isFinite(e)?e:0}function pc(n){return n==="success"?"success":"error"}function fc(n){let e=mo(n);return{id:ke(e.id),timestamp:ke(e.timestamp),session_id:ke(e.sessionId),provider:ke(e.provider),original_model:ke(e.originalModel),model:ke(e.model),upstream_model:uo(e.upstreamModel)??null,model_family:ke(e.modelFamily),scenario_type:ke(e.scenarioType),client_type:uo(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(It(e.inputTokens)),output_tokens:Math.trunc(It(e.outputTokens)),cache_read_input_tokens:Math.trunc(It(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(It(e.cacheCreationInputTokens)),ttft:Mt(e.ttft),tokens_per_second:Mt(e.tokensPerSecond),duration_ms:Math.trunc(It(e.durationMs)),status:pc(e.status),error_message:uo(e.errorMessage)??null,response_body:uo(e.responseBody)??null}}function uf(n){return mo({id:n.id,timestamp:n.timestamp,sessionId:n.session_id,provider:n.provider,originalModel:n.original_model,model:n.model,upstreamModel:n.upstream_model??void 0,modelFamily:n.model_family,scenarioType:n.scenario_type,clientType:n.client_type??void 0,stream:n.stream===1,...n.usage_estimated===1?{usageEstimated:!0}:{},inputTokens:n.input_tokens,outputTokens:n.output_tokens,cacheReadInputTokens:n.cache_read_input_tokens,cacheCreationInputTokens:n.cache_creation_input_tokens,ttft:n.ttft,tokensPerSecond:n.tokens_per_second,durationMs:n.duration_ms,status:pc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function df(){return new Date(Date.now()-ef*24*60*60*1e3).toISOString()}function mc(n,e=!1){let t=Date.now();!e&&t-lc<tf||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(df()),lc=t)}function gc(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function et(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
|
|
380
|
+
SELECT ${t} AS key, ${pf}
|
|
375
381
|
FROM usage_records ${r}
|
|
376
382
|
GROUP BY key
|
|
377
|
-
`).all(...e.params),a={};for(let i of s)i.key!=null&&(a[String(i.key)]={count:i.count,inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadInputTokens:i.cacheReadInputTokens,cacheCreationInputTokens:i.cacheCreationInputTokens});return a}function
|
|
383
|
+
`).all(...e.params),a={};for(let i of s)i.key!=null&&(a[String(i.key)]={count:i.count,inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadInputTokens:i.cacheReadInputTokens,cacheCreationInputTokens:i.cacheCreationInputTokens});return a}function hc(n,e){let t=gc(e),o=n.prepare(`
|
|
378
384
|
SELECT
|
|
379
385
|
COUNT(*) AS totalRequests,
|
|
380
386
|
COALESCE(SUM(usage_estimated), 0) AS estimatedCount,
|
|
@@ -386,14 +392,14 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
386
392
|
AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
|
|
387
393
|
AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
|
|
388
394
|
FROM usage_records ${t.sql}
|
|
389
|
-
`).get(...t.params);return{estimatedCount:o.estimatedCount,totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:et(n,t,"model"),byProvider:et(n,t,"provider"),byScenario:et(n,t,"scenario_type"),byFamily:et(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:et(n,t,"date(timestamp, 'localtime')"),byClient:et(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function
|
|
395
|
+
`).get(...t.params);return{estimatedCount:o.estimatedCount,totalRequests:o.totalRequests,successCount:o.successCount,errorCount:o.totalRequests-o.successCount,totalInputTokens:o.totalInputTokens,totalOutputTokens:o.totalOutputTokens,totalCacheReadInputTokens:o.totalCacheReadInputTokens,totalCacheCreationInputTokens:o.totalCacheCreationInputTokens,avgTtft:o.avgTtft!=null?Math.round(o.avgTtft):null,avgTokensPerSecond:o.avgTokensPerSecond!=null?Math.round(o.avgTokensPerSecond):null,byModel:et(n,t,"model"),byProvider:et(n,t,"provider"),byScenario:et(n,t,"scenario_type"),byFamily:et(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:et(n,t,"date(timestamp, 'localtime')"),byClient:et(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function $t(n){let e=Lt(),t=mo(n);cs.run(fc(t)),mc(e)}function ls(n){let e=Lt(),t=gc(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.min(Math.floor(n.pageSize),ff):50,s=(o-1)*r,a=e.prepare(`SELECT COUNT(*) AS count FROM usage_records ${t.sql}`).get(...t.params),i=e.prepare(`SELECT * FROM usage_records ${t.sql} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t.params,r,s),l=hc(e,n);return{records:i.map(uf),summary:l,total:a.count,page:o,pageSize:r}}function Nt(n,e,t){let o=Lt();return hc(o,{startTime:n,endTime:e,status:t})}function us(n){let e=Lt();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function mf(){Te&&(Te.pragma("wal_checkpoint(TRUNCATE)"),Te.close(),Te=null,cs=null)}function Mt(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function ds(n){let e=fo(Gp(),Xp,`session-${Yp(n)}.json`);try{let t=JSON.parse(dc(e,"utf-8"));return{ttft:Mt(t.timeToFirstToken),tokensPerSecond:Mt(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function gf(n,e,t){return Lt().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var po,Zp,as,qp,ef,tf,cc,Te,cs,lc,pf,ff,Ut=w(()=>{"use strict";po=fo(Vp,"data"),Zp=fo(po,"usage.sqlite"),as=fo(po,"usage.jsonl"),qp=1,ef=180,tf=3600*1e3,cc="legacy_usage_jsonl_migrated_at",Te=null,cs=null,lc=0;pf=`
|
|
390
396
|
COUNT(*) AS count,
|
|
391
397
|
COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
|
|
392
398
|
COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
|
|
393
399
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
|
|
394
400
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
|
|
395
|
-
`;nf=200});import{existsSync as sf}from"fs";import{homedir as af}from"os";import{join as cf}from"path";import{writeFile as lf}from"fs/promises";async function dc(){let n=af(),e=cf(n,".claude.json");if(!sf(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 lf(e,JSON.stringify(o,null,2))}}var pc=w(()=>{"use strict"});import{existsSync as uf,readdirSync as df,statSync as pf,unlinkSync as ff}from"fs";import{join as fc}from"path";import{HOME_DIR as mf}from"@wengine-ai/claude-code-router-shared";function gc(n=fc(mf,"logs")){try{if(!uf(n))return;let e=Date.now()-hf;for(let t of df(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=fc(n,t),r=pf(o);r.isFile()&&r.mtime.getTime()<e&&ff(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function hc(){mc||(mc=!0,gc(),setInterval(gc,yf).unref())}var gf,hf,yf,mc,yc=w(()=>{"use strict";gf=7,hf=gf*24*60*60*1e3,yf=1440*60*1e3,mc=!1});async function _c(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(to,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:eo()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var bc=w(()=>{"use strict";Qr()});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),Or();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 fo=w(()=>{"use strict";At();Qn();q()});import{constants as as,lstatSync as nt,realpathSync as Ut,openSync as _f,closeSync as bf,fstatSync as kf,readFileSync as kc}from"node:fs";import{dirname as Jb,join as ot,sep as Tf}from"node:path";import{pathToFileURL as vf}from"node:url";function vc(n){try{let e=JSON.parse(kc(ot(xf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function ls(n,e){if(!Tc(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+Tf)?null:r}catch{return null}}function cs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=ls(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=_f(r,as.O_RDONLY|as.O_NOFOLLOW|as.O_NONBLOCK);try{let i=kf(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||ls(n,e)!==o||Ut(r)!==r)throw new Error("plugin file changed while opening");return kc(a)}finally{bf(a)}}function Cf(n){let e=n?.configService,t=e?ws(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Ps(t)}async function xc(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Oo(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>wt(),writeConfig:i=>ue(i),reloadRuntime:async i=>tt(n.getServer(),i??await X(),t),getDirectDispatcher:To,getSubscriptionDispatcher:()=>Cf(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of vc(e)){let c;try{if(!Tc(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=ls(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let g=JSON.parse(cs(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,cs(e,i.name,"plugin.js");let d=await import(vf(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?cs(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 Cc(n,e=Oo()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return vc(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 Tc,xf,us=w(()=>{"use strict";Eo();Vt();fo();Pt();q();Tc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),xf=n=>ot(n,"plugins")});import{existsSync as Sc,readFileSync as Sf}from"node:fs";import{join as ds}from"node:path";import{NPM_SPEC_PATTERN as Rf,PLUGIN_NAME_PATTERN as Rc,PluginInstallError as wf,installPluginFromNpm as Pf,readPluginRecords as Ef}from"@wengine-ai/claude-code-router-shared";async function Of(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 If(n,e={}){let t=(e.registryBase??Af).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(wc.map(m=>Of(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(!_||!Rf.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>wc.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=Ef(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(!Rc.test(m))return null;try{let y=JSON.parse(Sf(ds(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||Sc(ds(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(!Rc.test(y)||!Sc(ds(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 Mf(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 Pc(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 Ec(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(!Pc(r,n,t))return o(s,403,"local_only");try{return await If(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(!Pc(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 Pf({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 wf){let u=Mf(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 wc,Af,Ac=w(()=>{"use strict";wc=["ccr-provider-plugin","claude-code-router-plugin"],Af="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Lf}from"@wengine-ai/claude-code-router-shared";import{join as ce,isAbsolute as Nf,normalize as $f,dirname as Ff}from"path";import{fileURLToPath as Uf}from"url";import Df from"@fastify/static";import{readdirSync as Oc,statSync as jf,readFileSync as Ic,writeFileSync as Hf,existsSync as fe,unlinkSync as Mc,rmSync as zf}from"fs";import{homedir as ps}from"os";import{getPresetDir as mo,readManifestFromDir as fs,manifestToPresetFile as Lc,saveManifest as Nc,isPresetInstalled as $c,extractPreset as Bf,HOME_DIR as ms,loadConfigFromManifest as Jf,downloadPresetToTemp as Wf,findMarketPresetByName as Kf,getMarketPresets as Gf,applyClientSelection as Vf,disableClient as Qf,enableClient as Yf,isClientId as Xf,listClientStatuses as Fc,restoreClient as Zf,listProjectConfigs as qf,readProjectConfigById as gs,readProjectConfig as em,writeProjectConfig as Uc,deleteProjectConfig as tm,getClaudeProjectId as nm,getProjectConfigPath as om,refreshCcrProjectTakeover as rm,refreshPiProjectTakeover as sm,refreshProjectTakeovers as im,syncGlobalProjectTakeovers as hs,getProjectTakeoverClients as ys,setProjectTakeover as _s,isProjectTakeoverClient as am}from"@wengine-ai/claude-code-router-shared";import cm from"@fastify/multipart";import lm from"adm-zip";function Dc(n){let e=j();return qr(n,(t,o)=>e.isAvailable(t,o))}function jc(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function um(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 Hc(n,e){let t=n.app;ct(),ut(),t.register(cm,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Dc(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=Dc(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:ln(l,p,u)}}),t.get("/api/config",async(i,c)=>await wt()),t.get("/api/transformers",async(i,c)=>{let l=t._server.transformerService.getAllTransformers();return{transformers:Array.from(l.entries()).map(([p,d])=>({name:p,endpoint:d.endPoint||null}))}}),t.post("/api/config",async(i,c)=>{let l=i.body,u=Rs(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(h=>`${h.key}: ${h.error}`).join("; "),proxyErrors:u};let p=await ro();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}Lf(l,d),n.pluginRegistry.applyConfigProtectors(l,d),await ue(l);let f;try{f=await hs(l),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"Config saved but some global project takeovers failed to sync")}catch(h){t.log?.warn?.(`Config saved but global project takeover sync failed: ${h?.message||h}`)}return tt(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,c)=>{try{let l=await X();return{clients:Fc(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=Vf(p,u);await ue(d.config);let f=await hs(d.config),h=jc(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(!Xf(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=l==="enable"?Yf(p,u):l==="restore"?Zf(p,u):Qf(p,u);await ue(p);let f=await hs(p),h=jc(t,f,`clients/${u}/${l}`);return{success:d.success&&h,result:d,results:[d],clients:Fc(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 qf();return{projects:await Promise.all(l.map(async p=>{let d=await ys(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"||!Nf(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=$f(l).replace(/[\\/]+$/,"")||l;if(await em(u)){c.status(409).send({error:"Project is already configured"});return}await Uc(u,{Router:{}});try{let f=await X();await _s(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await ys(u);return{id:nm(u),path:u,configPath:om(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 gs(l);if(!p){c.status(404).send({error:"Project config not found"});return}await Uc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await im(p.path,d):(await rm(p.path,d,u),await sm(p.path,d,u));let f=await ys(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(am);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 gs(l);if(!d){c.status(404).send({error:"Project config not found"});return}let f=await X(),h=await _s(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 gs(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await X();await _s(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await tm(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:Ff(Uf(import.meta.url)),s=fe(ce(r,"index.html"))?r:fe(ce(r,"..","index.html"))?ce(r,".."):ce(r,"..","dist");t.register(Df,{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(ps(),".claude-code-router","logs"),u=[];if(fe(l)){let p=Oc(l);for(let d of p)if(d.endsWith(".log")){let f=ce(l,d),h=jf(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(ps(),".claude-code-router","logs","app.log"),fe(u)?Ic(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(ps(),".claude-code-router","logs","app.log"),fe(u)&&Hf(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 So(c),{enabled:Bt()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return rs({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 ss(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&&io(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&&io(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=um(u),d=new Map(p.map(g=>[g.provider,g])),f=Ho();for(let g of p){let m=f.find(y=>y.provider===g.provider);m&&m.limit!=null&&!Zt(m.reset)&&(g.limit5h=m.limit,g.used5h=m.limit-(m.remaining??0),m.reset&&(g.reset5h=new Date(m.reset*1e3).toISOString()))}let h=qo();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);let y=Zt(typeof g.resetTime=="string"?Date.parse(g.resetTime)/1e3:void 0),b=Zt(typeof g.resetTime7d=="string"?Date.parse(g.resetTime7d)/1e3:void 0);typeof g.usedDailyBalance=="number"&&!y&&(m.used5h=g.usedDailyBalance,m.type5h="rateLimit"),typeof g.limitDaily=="number"&&!y&&(m.limit5h=g.limitDaily,m.type5h="rateLimit"),typeof g.resetTime=="string"&&!y&&(g.limitDaily!==void 0?m.reset5h=g.resetTime:m.reset7d=g.resetTime),typeof g.resetTime7d=="string"&&!b&&(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(ms,"presets");if(!fe(l))return{presets:[]};let p=Oc(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=Ic(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=mo(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}let p=await fs(u);return{...Lc(p),config:Jf(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=mo(l);if(!fe(p)){c.status(404).send({error:"Preset not found"});return}let f={...await fs(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await Nc(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=mo(l);if(!fe(u)){c.status(404).send({error:"Preset not found"});return}return zf(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 Gf()}}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 Kf(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 $c(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 Wf(g),y=await a(m);if(await $c(h)){Mc(m),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let b=mo(h);await Bf(m,b);let _=await fs(b);return _.repository=u.repo,u.url&&(_.source=u.url),await Nc(h,_),Mc(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 lm(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 Lc(u)}return t.get("/api/plugins",async()=>({plugins:Cc(ms,n.pluginRegistry)})),Ec(t,{configDir:ms,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 zc=w(()=>{"use strict";Re();xe();De();xe();q();st();se();At();fo();us();Ac();Pt();Ft();es()});function dm(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 Bc(n){return n?.Router?.image}function pm(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 fm(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 bs,go,ks,Jc,Wc=w(()=>{"use strict";Re();bs=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}},go=new bs;ks=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=dm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!pm(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&>(e.body.model)?!1:(fm(e.body.messages),s&&!!Bc(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=go.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=go.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:Bc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
401
|
+
`;ff=200});import{existsSync as hf}from"fs";import{homedir as yf}from"os";import{join as _f}from"path";import{writeFile as bf}from"fs/promises";async function _c(){let n=yf(),e=_f(n,".claude.json");if(!hf(e)){let o={numStartups:184,autoUpdaterStatus:"enabled",userID:Array.from({length:64},()=>Math.random().toString(16)[2]).join(""),hasCompletedOnboarding:!0,lastOnboardingVersion:"1.0.17",projects:{}};await bf(e,JSON.stringify(o,null,2))}}var bc=w(()=>{"use strict"});import{existsSync as kf,readdirSync as Tf,statSync as vf,unlinkSync as xf}from"fs";import{join as kc}from"path";import{HOME_DIR as Sf}from"@wengine-ai/claude-code-router-shared";function vc(n=kc(Sf,"logs")){try{if(!kf(n))return;let e=Date.now()-Rf;for(let t of Tf(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=kc(n,t),r=vf(o);r.isFile()&&r.mtime.getTime()<e&&xf(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function xc(){Tc||(Tc=!0,vc(),setInterval(vc,wf).unref())}var Cf,Rf,wf,Tc,Sc=w(()=>{"use strict";Cf=7,Rf=Cf*24*60*60*1e3,wf=1440*60*1e3,Tc=!1});async function Cc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":kt.registerPlugin(oo,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:no()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var Rc=w(()=>{"use strict";es()});function tt(n,e,t){if(n?.configService)try{n.configService.reload(),n.reloadProviders?n.reloadProviders(e):(n.configService.set("providers",e?.Providers??e?.providers??[]),n.providerService?.reload()),Et(e,t),Nr();let o={enabled:n.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:n.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:n.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(n.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:n.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:n.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};n.activeProbeService=bt(()=>n.providerService.getProviders(),o,r=>de(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var go=w(()=>{"use strict";At();Xn();q()});import{constants as ps,lstatSync as nt,realpathSync as Dt,openSync as Pf,closeSync as Ef,fstatSync as Af,readFileSync as wc}from"node:fs";import{dirname as nk,join as ot,sep as Of}from"node:path";import{pathToFileURL as If}from"node:url";function Ec(n){try{let e=JSON.parse(wc(ot(Mf(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function ms(n,e){if(!Pc(e))return null;try{let t=Dt(n),o=ot(t,"plugins"),r=ot(o,e);return nt(o).isSymbolicLink()||!nt(o).isDirectory()||nt(r).isSymbolicLink()||!nt(r).isDirectory()||Dt(o)!==o||Dt(r)!==r||!r.startsWith(o+Of)?null:r}catch{return null}}function fs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=ms(n,e);if(!o)throw new Error("unsafe plugin directory");let r=ot(o,t),s=nt(r);if(s.isSymbolicLink()||!s.isFile()||Dt(r)!==r)throw new Error("unsafe plugin file");let a=Pf(r,ps.O_RDONLY|ps.O_NOFOLLOW|ps.O_NONBLOCK);try{let i=Af(a),l=nt(r);if(!i.isFile()||l.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==l.dev||i.ino!==l.ino||ms(n,e)!==o||Dt(r)!==r)throw new Error("plugin file changed while opening");return wc(a)}finally{Ef(a)}}function Lf(n){let e=n?.configService,t=e?Is(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return Ms(t)}async function Ac(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??Lo(),r={configDir:e,readConfig:()=>X(),readRawConfig:()=>wt(),writeConfig:i=>ue(i),reloadRuntime:async i=>tt(n.getServer(),i??await X(),t),getDirectDispatcher:So,getSubscriptionDispatcher:()=>Lf(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of Ec(e)){let l;try{if(!Pc(i.name))throw new Error("invalid plugin install name");if(a.has(i.name))throw new Error(`duplicate plugin install record "${i.name}"`);if(a.add(i.name),i.enabled===!1){s.skipped.push({name:i.name,reason:"disabled"});continue}let c=ms(e,i.name);if(!c){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(fs(e,i.name,"plugin.json").toString("utf8"));if(!h||typeof h.name!="string"||typeof h.version!="string")throw new Error;u={name:h.name,version:h.version,coreApi:String(h.coreApi??"1"),description:h.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:h=>t.info(`[plugin:${u.name}] ${h}`),warn:h=>t.warn(`[plugin:${u.name}] ${h}`),error:h=>t.error(`[plugin:${u.name}] ${h}`)},r,c);l=p,fs(e,i.name,"plugin.js");let d=await import(If(ot(c,"plugin.js")).href),f=d?.activate??d?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(p.context);let g=p.cardPath?fs(e,i.name,p.cardPath):void 0;await p.commit(g,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(c){l?.abort(),s.failed.push({name:i.name,error:c?.message??String(c)}),t.warn(`plugin ${i.name} failed to load: ${c?.message??String(c)}`)}}return s}function Oc(n,e=Lo()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return Ec(n).map(o=>{let r=o.enabled!==!1?t.get(o.name):void 0;return r?{...r,enabled:!0}:{name:o.name,version:null,enabled:o.enabled!==!1,error:"plugin missing or failed to load \u2014 its providers are unavailable until it is reinstalled"}})}var Pc,Mf,gs=w(()=>{"use strict";Io();Qt();go();Pt();q();Pc=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Mf=n=>ot(n,"plugins")});import{existsSync as Ic,readFileSync as $f}from"node:fs";import{join as hs}from"node:path";import{NPM_SPEC_PATTERN as Nf,PLUGIN_NAME_PATTERN as Mc,PluginInstallError as Uf,installPluginFromNpm as Df,readPluginRecords as Ff}from"@wengine-ai/claude-code-router-shared";async function Hf(n,e,t){let o=`${n}/-/v1/search?text=${encodeURIComponent(`keywords:${e}`)}&size=100`,r=await fetch(o,{signal:AbortSignal.timeout(t),headers:{accept:"application/json"}});if(!r.ok)throw new Error(`registry_status_${r.status}`);let s=await r.json();return Array.isArray(s?.objects)?s.objects:[]}async function zf(n,e={}){let t=(e.registryBase??jf).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(Lc.map(m=>Hf(t,m,o))),s=new Map,a=!1;for(let m of r)if(m.status==="fulfilled"){a=!0;for(let y of m.value){let b=y?.package,_=typeof b?.name=="string"?b.name:"";if(!_||!Nf.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>Lc.includes(x)))continue;let T=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:T,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=Ff(n),l=new Map(i.map(m=>[m.name,m])),c=m=>{let y=m.indexOf("@",m.startsWith("@")?1:0);return y>0?m.slice(0,y):m},u=new Map(i.filter(m=>typeof m.source=="string"&&m.source!=="").map(m=>[c(m.source),m])),p=m=>{if(!Mc.test(m))return null;try{let y=JSON.parse($f(hs(n,"plugins",m,"plugin.json"),"utf8"));return typeof y?.version=="string"?y.version:null}catch{return null}},d=[...s.values()].sort((m,y)=>m.name.localeCompare(y.name)).map(m=>{let y=l.get(m.name)??u.get(m.name),b=y!==void 0||Ic(hs(n,"plugins",m.name)),_=b?p(y?y.name:m.name):null;return{...m,installed:b,installedVersion:_,...b&&_!==null&&_!==m.version?{updateAvailable:!0}:{}}}),f=new Set(d.map(m=>m.name)),g=new Set,h=new Map;for(let[m,y]of u)g.add(y.name),!f.has(m)&&h.set(m,y.name);for(let m of i)f.has(m.name)||g.has(m.name)||h.set(m.name,m.name);for(let[m,y]of h){if(!Mc.test(y)||!Ic(hs(n,"plugins",y)))continue;let b=p(y);b!==null&&d.push({name:m,description:"",version:b,installed:!0,installedVersion:b,localOnly:!0})}return d.sort((m,y)=>m.name.localeCompare(y.name)),{ok:!0,plugins:d}}function Bf(n){switch(n){case"invalid_spec":return 400;case"already_installed":case"plugins_json_corrupted":return 409;case"npm_pack_failed":case"npm_pack_timeout":return 502;case"archive_too_large":case"archive_too_many_files":case"unsafe_archive_member":case"extract_failed":case"invalid_manifest":return 422;default:return 500}}function $c(n,e,t){let o=n.ip||n.connection?.remoteAddress||"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1"))return!1;let s=e.server?.address?.(),a=typeof s?.port=="number"&&s.port>0?s.port:t,i=new Set([`127.0.0.1:${a}`,`localhost:${a}`,`[::1]:${a}`]),l=n.headers?.host;if(typeof l=="string"&&!i.has(l))return!1;let c=n.headers?.origin;if(c!==void 0&&c!==""){if(typeof c!="string")return!1;let u="";try{let p=new URL(c);if(!["http:","https:"].includes(p.protocol))return!1;u=p.host}catch{return!1}if(!i.has(u))return!1}return!0}function Nc(n,e){let t=e.configuredPort??3456,o=(r,s,a)=>r.status(s).send({ok:!1,error:a});n.get("/api/plugins/catalog",async(r,s)=>{if(!$c(r,n,t))return o(s,403,"local_only");try{return await zf(e.configDir,{registryBase:e.catalogRegistryBase??e.registry,timeoutMs:e.catalogTimeoutMs})}catch(a){return n.log?.warn?.(`plugin catalog failed: ${a?.code??a?.name??"error"}`),{ok:!0,plugins:[],warning:"registry_unavailable"}}}),n.post("/api/plugins/install",async(r,s)=>{if(!$c(r,n,t))return o(s,403,"local_only");let a=r.body??{},i=a.name??a.spec,l=a.force===!0;try{let c=await Df({spec:i,configDir:e.configDir,force:l,registry:e.registry,timeoutMs:e.npmTimeoutMs});return n.log?.info?.(`provider plugin installed via API: ${c.manifest.name}@${c.manifest.version} (restart to activate)`),{ok:!0,name:c.manifest.name,version:c.manifest.version,restartRequired:!0}}catch(c){if(c instanceof Uf){let u=Bf(c.code);return u===502?n.log?.warn?.(`plugin install failed: ${c.code}`):n.log?.warn?.(`plugin install rejected: ${c.code}: ${c.message}`),o(s,u,c.code)}return n.log?.error?.(`plugin install crashed: ${c?.message??c}`),o(s,500,"install_failed")}})}var Lc,jf,Uc=w(()=>{"use strict";Lc=["ccr-provider-plugin","claude-code-router-plugin"],jf="https://registry.npmjs.org"});import{ensureCcrSelfProvider as Jf}from"@wengine-ai/claude-code-router-shared";import{join as ae,isAbsolute as Wf,normalize as Kf,dirname as Gf}from"path";import{fileURLToPath as Qf}from"url";import Vf from"@fastify/static";import{readdirSync as Dc,statSync as Yf,readFileSync as Fc,writeFileSync as Xf,existsSync as fe,unlinkSync as jc,rmSync as Zf}from"fs";import{homedir as ys}from"os";import{getPresetDir as ho,readManifestFromDir as _s,manifestToPresetFile as Hc,saveManifest as zc,isPresetInstalled as Bc,extractPreset as qf,HOME_DIR as bs,loadConfigFromManifest as em,downloadPresetToTemp as tm,findMarketPresetByName as nm,getMarketPresets as om,applyClientSelection as rm,disableClient as sm,enableClient as im,isClientId as am,listClientStatuses as Jc,restoreClient as cm,listProjectConfigs as lm,readProjectConfigById as ks,readProjectConfig as um,writeProjectConfig as Wc,deleteProjectConfig as dm,getClaudeProjectId as pm,getProjectConfigPath as fm,refreshCcrProjectTakeover as mm,refreshPiProjectTakeover as gm,refreshProjectTakeovers as hm,syncGlobalProjectTakeovers as Ts,getProjectTakeoverClients as vs,setProjectTakeover as xs,isProjectTakeoverClient as ym}from"@wengine-ai/claude-code-router-shared";import _m from"@fastify/multipart";import bm from"adm-zip";function Kc(n){let e=H();return rs(n,(t,o)=>e.isAvailable(t,o))}function Gc(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function km(n){let e=new Date().toISOString(),t=new Date(Date.now()-300*60*1e3).toISOString(),o=new Date(Date.now()-10080*60*1e3).toISOString(),r=Nt(t,e),s=Nt(o,e),a=[],i=new Set;for(let l of n||[])l&&l.name&&i.add(l.name);for(let l of Object.keys(r.byProvider||{}))i.add(l);for(let l of Object.keys(s.byProvider||{}))i.add(l);for(let l of i){let c=r.byProvider[l]||{inputTokens:0,outputTokens:0},u=s.byProvider[l]||{inputTokens:0,outputTokens:0},p=(c.inputTokens||0)+(c.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),f,g,h=(n||[]).find(m=>m&&m.name===l);h&&h.quota&&(f=h.quota.limit5h,g=h.quota.limit7d),a.push({provider:l,used5h:p,used7d:d,limit5h:f,limit7d:g})}return a}async function Qc(n,e){let t=n.app;at(),ut(),t.register(_m,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=Kc(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,l)=>{let c=decodeURIComponent(i.params.modelId),u=Kc(e).find(p=>p.id===c);return u||(l.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${c}`}})}),t.post("/v1/messages/count_tokens",async(i,l)=>{let{messages:c,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[h,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${h}, model: ${m}`);let y=f.getTokenizerConfigForModel(h,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${h},${m}, using default tiktoken`);let b=await f.countTokens({messages:c,system:p,tools:u},y,h);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(h){i.log?.error(`Error using configured tokenizer: ${h.message}`),i.log?.error(h.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:ln(c,p,u)}}),t.get("/api/config",async(i,l)=>await wt()),t.get("/api/transformers",async(i,l)=>{let c=t._server.transformerService.getAllTransformers();return{transformers:Array.from(c.entries()).map(([p,d])=>({name:p,endpoint:d.endPoint||null}))}}),t.post("/api/config",async(i,l)=>{let c=i.body,u=Os(c||{});if(u.length>0)return l.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(g=>`${g.key}: ${g.error}`).join("; "),proxyErrors:u};let p=await io();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await X()}catch{}Jf(c,d),n.pluginRegistry.applyConfigProtectors(c,d),await ue(c);let f;try{f=await Ts(c),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}return tt(n,c,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,l)=>{try{let c=await X();return{clients:Jc(c)}}catch(c){console.error("Failed to get client integrations:",c),l.status(500).send({error:c.message||"Failed to get client integrations"})}}),t.post("/api/clients/apply",async(i,l)=>{try{let c=i.body,u=Array.isArray(c?.enabled)?c.enabled:[],p=await X(),d=rm(p,u);await ue(d.config);let f=await Ts(d.config),g=Gc(t,f,"clients/apply");return{...d,success:d.success&&g,projectTakeoverSync:f}}catch(c){console.error("Failed to apply client integrations:",c),l.status(500).send({error:c.message||"Failed to apply client integrations"})}});async function o(i,l,c){try{let{id:u}=i.params;if(!am(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let p=await X(),d=c==="enable"?im(p,u):c==="restore"?cm(p,u):sm(p,u);await ue(p);let f=await Ts(p),g=Gc(t,f,`clients/${u}/${c}`);return{success:d.success&&g,result:d,results:[d],clients:Jc(p),config:p,projectTakeoverSync:f}}catch(u){console.error(`Failed to ${c} client integration:`,u),l.status(500).send({error:u.message||`Failed to ${c} client integration`})}}t.post("/api/clients/:id/enable",async(i,l)=>o(i,l,"enable")),t.post("/api/clients/:id/disable",async(i,l)=>o(i,l,"disable")),t.post("/api/clients/:id/restore",async(i,l)=>o(i,l,"restore")),t.get("/api/projects",async(i,l)=>{try{let c=await lm();return{projects:await Promise.all(c.map(async p=>{let d=await vs(p.path);return{...p,ccrTakeoverClients:d,ccrTakeover:d.length>0}}))}}catch(c){console.error("Failed to list project configs:",c),l.status(500).send({error:c.message||"Failed to list project configs"})}}),t.post("/api/projects",async(i,l)=>{try{let{path:c}=i.body||{};if(!c||typeof c!="string"||!Wf(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=Kf(c).replace(/[\\/]+$/,"")||c;if(await um(u)){l.status(409).send({error:"Project is already configured"});return}await Wc(u,{Router:{}});try{let f=await X();await xs(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await vs(u);return{id:pm(u),path:u,configPath:fm(u),Router:{},ccrTakeoverClients:d,ccrTakeover:d.length>0}}catch(c){console.error("Failed to add project config:",c),l.status(500).send({error:c.message||"Failed to add project config"})}}),t.put("/api/projects/:id",async(i,l)=>{try{let{id:c}=i.params,{Router:u}=i.body||{};if(!u||typeof u!="object"){l.status(400).send({error:"Router must be an object"});return}let p=await ks(c);if(!p){l.status(404).send({error:"Project config not found"});return}await Wc(p.path,{Router:u});let d=await X();Object.keys(u).length===0?await hm(p.path,d):(await mm(p.path,d,u),await gm(p.path,d,u));let f=await vs(p.path);return{id:c,path:p.path,configPath:p.configPath,Router:u,ccrTakeoverClients:f,ccrTakeover:f.length>0}}catch(c){console.error("Failed to update project config:",c),l.status(500).send({error:c.message||"Failed to update project config"})}}),t.put("/api/projects/:id/takeover",async(i,l)=>{try{let{id:c}=i.params,u=i.body||{},p;if(Array.isArray(u.clients))p=u.clients.filter(ym);else if(typeof u.enabled=="boolean")p=u.enabled?["claudeCode"]:[];else{l.status(400).send({error:"clients (array) or enabled (boolean) is required"});return}let d=await ks(c);if(!d){l.status(404).send({error:"Project config not found"});return}let f=await X(),g=await xs(d.path,p,f);return{id:c,path:d.path,ccrTakeoverClients:g,ccrTakeover:g.length>0}}catch(c){console.error("Failed to update ccr takeover status:",c),l.status(500).send({error:c.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,l)=>{try{let{id:c}=i.params,u=await ks(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let p=await X();await xs(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await dm(u.path),{success:!0}}catch(c){console.error("Failed to delete project config:",c),l.status(500).send({error:c.message||"Failed to delete project config"})}});let r=typeof __dirname=="string"?__dirname:Gf(Qf(import.meta.url)),s=fe(ae(r,"index.html"))?r:fe(ae(r,"..","index.html"))?ae(r,".."):ae(r,"..","dist");t.register(Vf,{root:s,prefix:"/ui/",maxAge:"1h"}),t.get("/ui",async(i,l)=>l.redirect("/ui/")),t.get("/api/logs/files",async(i,l)=>{try{let c=ae(ys(),".claude-code-router","logs"),u=[];if(fe(c)){let p=Dc(c);for(let d of p)if(d.endsWith(".log")){let f=ae(c,d),g=Yf(f);u.push({name:d,path:f,size:g.size,lastModified:g.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(c){console.error("Failed to get log files:",c),l.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=ae(ys(),".claude-code-router","logs","app.log"),fe(u)?Fc(u,"utf8").split(`
|
|
402
|
+
`).filter(f=>f.trim()):[]}catch(c){console.error("Failed to get logs:",c),l.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,l)=>{try{let c=i.query.file,u;return c?u=c:u=ae(ys(),".claude-code-router","logs","app.log"),fe(u)&&Xf(u,"","utf8"),{success:!0,message:"Logs cleared successfully"}}catch(c){console.error("Failed to clear logs:",c),l.status(500).send({error:"Failed to clear logs"})}}),t.get("/api/debug-log",async()=>({enabled:Bt()})),t.put("/api/debug-log",async i=>{let{enabled:l}=i.body;return Po(l),{enabled:Bt()}}),t.get("/api/usage",async(i,l)=>{try{let c=i.query;return ls({startTime:c.startDate,endTime:c.endDate,model:c.model,provider:c.provider,scenario:c.scenario,clientType:c.clientType,sessionId:c.sessionId,status:c.status,page:c.page?parseInt(c.page,10):void 0,pageSize:c.pageSize?parseInt(c.pageSize,10):void 0})}catch(c){console.error("Failed to query usage:",c),l.status(500).send({error:"Failed to query usage"})}}),t.get("/api/usage/summary",async(i,l)=>{try{let c=i.query;return Nt(c.startDate,c.endDate,c.status)}catch(c){console.error("Failed to query usage summary:",c),l.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(i,l)=>{try{let c=i.query;return us(c.beforeDate),{success:!0,message:c.beforeDate?"Usage data cleared before "+c.beforeDate:"All usage data cleared"}}catch(c){console.error("Failed to clear usage:",c),l.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,l)=>{try{let u=H().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,lastSuccessTime:f.lastSuccessTime??null,lastError:f.lastError,rateLimitUntil:f.rateLimitUntil??null})),probes:d,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to get provider health:",c),l.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,l)=>{try{let{providerName:c}=i.body;if(!c)return l.status(400),{error:"providerName is required"};let p=t._server?.activeProbeService;if(!p?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let d=await p.probeProviderManually(c);return d.success&&co(c,i.log),{provider:c,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.error,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe provider:",c),l.status(500).send({error:c.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,l)=>{try{let c=t._server,u=c?.activeProbeService;if(!u?.probeProviderManually)return l.status(503),{error:"Active probe service is not available"};let p=(c?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let g=await u.probeProviderManually(f.name);return g.success&&co(f.name,i?.log),{provider:f.name,success:g.success,latencyMs:g.latencyMs,status:g.status,isSlow:g.isSlow,errorKind:g.errorKind??null,error:g.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to probe all providers:",c),l.status(500).send({error:c.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,l)=>{try{let u=(await X()).Providers||[],p=t._server?.pluginRegistry,d=t._server?.providerService;if(p&&d?.getProviders){let b=d.getProviders().filter(_=>_?.name&&_.enabled!==!1).map(_=>{let k=p.getManagedRuntimeFor(_);if(!(!k||typeof k.fetchQuota!="function"))return Vn(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,Ba).unref?.()});await Promise.race([Promise.all(b),_])}}let f=km(u),g=new Map(f.map(y=>[y.provider,y])),h=Jo();for(let y of f){let b=h.find(_=>_.provider===y.provider);b&&b.limit!=null&&!Zt(b.reset)&&(y.limit5h=b.limit,y.used5h=b.limit-(b.remaining??0),b.reset&&(y.reset5h=new Date(b.reset*1e3).toISOString()))}let m=tr();for(let y of m){let b=g.get(y.provider);b||(b={provider:y.provider,used5h:0,used7d:0},f.push(b),g.set(y.provider,b)),typeof y.totalBalance=="number"?(b.limit7d=y.totalBalance,b.type7d=y.currency?"balance":"rateLimit",y.currency&&(b.currency=y.currency),typeof y.usedBalance=="number"?b.used7d=y.usedBalance:typeof y.remainingBalance=="number"?b.used7d=Math.max(0,y.totalBalance-y.remainingBalance):(b.used7d=0,b.limit7d=y.totalBalance)):typeof y.usedBalance=="number"&&(b.used7d=y.usedBalance);let _=Zt(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=Zt(typeof y.resetTime7d=="string"?Date.parse(y.resetTime7d)/1e3:void 0);typeof y.usedDailyBalance=="number"&&!_&&(b.used5h=y.usedDailyBalance,b.type5h="rateLimit"),typeof y.limitDaily=="number"&&!_&&(b.limit5h=y.limitDaily,b.type5h="rateLimit"),typeof y.resetTime=="string"&&!_&&(y.limitDaily!==void 0?b.reset5h=y.resetTime:b.reset7d=y.resetTime),typeof y.resetTime7d=="string"&&!k&&(b.reset7d=y.resetTime7d)}return{quotas:f,timestamp:new Date().toISOString()}}catch(c){console.error("Failed to compute provider quota:",c),l.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,l)=>{try{let c=ae(bs,"presets");if(!fe(c))return{presets:[]};let p=Dc(c,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let g=ae(c,f);try{let h=ae(g,"manifest.json"),m=Fc(h,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:T,API_TIMEOUT_MS:x,PROXY_URL:v,PROXY_GLOBAL_ENABLED:P,LOG:E,LOG_LEVEL:R,StatusLine:A,NON_INTERACTIVE_MODE:D,...C}=y;d.push({id:f,name:C.name||f,version:C.version||"1.0.0",description:C.description,author:C.author,homepage:C.homepage,repository:C.repository,license:C.license,keywords:C.keywords,ccrVersion:C.ccrVersion,source:C.source,sourceType:C.sourceType,checksum:C.checksum,installed:!0})}catch(h){console.error(`Failed to read preset ${f}:`,h)}}return{presets:d}}catch(c){console.error("Failed to get presets:",c),l.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(i,l)=>{try{let{name:c}=i.params,u=ho(c);if(!fe(u)){l.status(404).send({error:"Preset not found"});return}let p=await _s(u);return{...Hc(p),config:em(p,u),userValues:p.userValues||{}}}catch(c){console.error("Failed to get preset:",c),l.status(500).send({error:c.message||"Failed to get preset"})}}),t.post("/api/presets/:name/apply",async(i,l)=>{try{let{name:c}=i.params,{secrets:u}=i.body,p=ho(c);if(!fe(p)){l.status(404).send({error:"Preset not found"});return}let f={...await _s(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await zc(c,f),{success:!0,message:"Preset applied successfully"}}catch(c){console.error("Failed to apply preset:",c),l.status(500).send({error:c.message||"Failed to apply preset"})}}),t.delete("/api/presets/:name",async(i,l)=>{try{let{name:c}=i.params,u=ho(c);if(!fe(u)){l.status(404).send({error:"Preset not found"});return}return Zf(u,{recursive:!0,force:!0}),{success:!0,message:"Preset deleted successfully"}}catch(c){console.error("Failed to delete preset:",c),l.status(500).send({error:c.message||"Failed to delete preset"})}}),t.get("/api/presets/market",async(i,l)=>{try{return{presets:await om()}}catch(c){console.error("Failed to get market presets:",c),l.status(500).send({error:c.message||"Failed to get market presets"})}}),t.post("/api/presets/install/github",async(i,l)=>{try{let{presetName:c}=i.body;if(!c){l.status(400).send({error:"Preset name is required"});return}let u=await nm(c);if(!u){l.status(400).send({error:"Preset not found in marketplace",message:`Preset '${c}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){l.status(400).send({error:"Invalid preset data",message:`Preset '${c}' does not have repository information`});return}let p=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!p){l.status(400).send({error:"Invalid GitHub repository URL"});return}let[,d,f]=p,g=u.name||c;if(await Bc(g)){l.status(409).send({error:"Preset already installed",message:`Preset '${g}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:g});return}let h=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await tm(h),y=await a(m);if(await Bc(g)){jc(m),l.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let b=ho(g);await qf(m,b);let _=await _s(b);return _.repository=u.repo,u.url&&(_.source=u.url),await zc(g,_),jc(m),{success:!0,presetName:g,preset:{...y.metadata,installed:!0}}}catch(c){console.error("Failed to install preset from GitHub:",c),l.status(500).send({error:c.message||"Failed to install preset from GitHub"})}});async function a(i){let l=new bm(i),c=l.getEntry("manifest.json");if(c||(c=l.getEntries().find(d=>d.entryName.includes("manifest.json"))||null),!c)throw new Error("Invalid preset file: manifest.json not found");let u=JSON.parse(c.getData().toString("utf-8"));return Hc(u)}return t.get("/api/plugins",async()=>({plugins:Oc(bs,n.pluginRegistry)})),Nc(t,{configDir:bs,configuredPort:Number(e.PORT)||3456,registry:typeof e.CCR_PLUGIN_NPM_REGISTRY=="string"&&/^https?:\/\//.test(e.CCR_PLUGIN_NPM_REGISTRY)?e.CCR_PLUGIN_NPM_REGISTRY:void 0}),t.get("/plugins/:name/:file",async(i,l)=>{let{name:c,file:u}=i.params,p=n.pluginRegistry.getPublicCard(c,u);return p?(l.header("Content-Type","application/javascript; charset=utf-8"),l.header("X-Content-Type-Options","nosniff"),l.header("Cache-Control","no-store"),l.send(p)):l.status(404).send({error:"plugin_not_found"})}),await n.pluginRegistry.registerAllRoutes(n.app??n),n}var Vc=w(()=>{"use strict";Pe();Se();Ce();Ir();Se();q();rt();re();At();go();gs();Uc();Pt();Ut();ss()});function Tm(n,e){let t=n?.Router,{family:o}=mt(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function Yc(n){return n?.Router?.image}function vm(n){return n.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(t=>t.type==="image"||t.type==="image_url"||Array.isArray(t?.content)&&t.content.some(o=>o.type==="image"||o.type==="image_url")))}function xm(n){let e=n[n.length-1];if(e?.role!=="user"||!Array.isArray(e.content))return;let t=[];e.content.filter(o=>o.type==="tool_result").forEach(o=>{if(!Array.isArray(o.content))return;let r=o.content.filter(s=>s.type==="image"?(t.push(s),!1):!0);r.length!==o.content.length&&(o.content=r.length>0?r:"read image successfully")}),e.content.push(...t)}var Ss,yo,Cs,Xc,Zc=w(()=>{"use strict";Pe();Ss=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},yo=new Ss;Cs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Tm(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!vm(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&>(e.body.model)?!1:(xm(e.body.messages),s&&!!Yc(t))}appendTools(){this.tools.set("analyzeImage",{name:"analyzeImage",description:"Analyse image or images by ID and extract information such as OCR text, objects, layout, colors, or safety signals.",input_schema:{type:"object",properties:{imageId:{type:"array",description:"an array of IDs to analyse",items:{type:"string"}},task:{type:"string",description:"Details of task to perform on the image.The more detailed, the better"},regions:{type:"array",description:"Optional regions of interest within the image",items:{type:"object",properties:{name:{type:"string",description:"Optional label for the region"},x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},w:{type:"number",description:"Width of the region"},h:{type:"number",description:"Height of the region"},units:{type:"string",enum:["px","pct"],description:"Units for coordinates and size"}},required:["x","y","w","h","units"]}}},required:["imageId","task"]},handler:async(e,t)=>{let o=[],r;if(e.imageId){if(Array.isArray(e.imageId))e.imageId.forEach(i=>{let l=yo.getImage(`${t.req.id}_Image#${i}`);l&&o.push({type:"image",source:l})});else{let i=yo.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(l=>l.type==="text"&&!l.text.includes("This is an image, if you need to view or analyze it, you need to extract the imageId"));o.push(...i)}Object.keys(e).length>0&&o.push({type:"text",text:JSON.stringify(e)});let a=await fetch(`http://127.0.0.1:${t.config.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":t.config.APIKEY,"content-type":"application/json"},body:JSON.stringify({model:Yc(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
397
403
|
When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
|
|
398
404
|
Do not ignore or deviate from the task.
|
|
399
405
|
Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(i=>i.json()).catch(i=>null);return!a||!a.content?"analyzeImage Error":a.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
|
|
@@ -406,5 +412,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
|
|
|
406
412
|
|
|
407
413
|
Do not attempt to describe or analyze the image directly yourself.
|
|
408
414
|
Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
|
|
409
|
-
Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")go.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:(go.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}})})}},Jc=new ks});var Ts,Kc,ho,Gc=w(()=>{"use strict";Wc();Ts=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}},Kc=new Ts;Kc.registerAgent(Jc);ho=Kc});import{EventEmitter as mm}from"node:events";import{performance as Vc}from"node:perf_hooks";import gm from"json5";function ym(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 Yc(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ce(n,e)}function vs(n){return n.usageSessionId||n.id}function yo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${vs(n)}`}function Dt(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Oe(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 _m(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?we(e.usage):e.response?.usage?we(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function bm(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();ao(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")){Yc(n,t);let r=yo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function km(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of ho.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 Xc(n){return{authClient:(e,t)=>bm(e,t,n),agent:(e,t)=>km(e,t,n)}}function Zc(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=Vc.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();ao(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Qc.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){Yc(t,e);let c=vs(t),l=yo(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,Yn(g,async(v,S)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let C=t.agents.find(P=>ho.getAgent(P)?.tools.get(v.data.content_block.name));if(C){m=ho.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=gm.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=we(k.usage),v=Pe(T,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Oe(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=we(k.response.usage),x=Y.get(l)||{},v=Pe(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Oe(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 _=we(b),k=Y.get(l)||{},T=Pe(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=_m(r);if(u?.usage&&Y.put(l,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(Qc.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{Go(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Go(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,hm)})])}finally{v&&clearTimeout(v)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=vs(t),a=s,i=t.sessionId||s,c=o.statusCode>=400,l=c?void 0:Y.get(yo(t)),u=is(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=Oe(t);ym(o.statusCode,d)?p.markRateLimited(t.provider||"",x,120,d):p.recordFailure(t.provider||"",x,d)}else{let x=Oe(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:Oe(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:Oe(t),upstreamModel:t.upstreamModel||Oe(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(Vc.now()-t.requestStartTime):0,status:y?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(yo(t))}catch(r){console.error("Usage tracking error:",r)}})}var hm,Qc,qc=w(()=>{"use strict";Je();on();tn();se();Mr();Lr();Nr();Ft();gn();Gc();ts();pn();hm=1500;Qc=new mm});var tl={};bo(tl,{createCcrServer:()=>wm});import{homedir as Tm}from"os";import{join as vm}from"path";import{createStream as xm}from"rotating-file-stream";import{CONFIG_FILE as Cm,HOME_DIR as el,listPresets as Sm,ensureCcrSelfProvider as Rm}from"@wengine-ai/claude-code-router-shared";async function wm(n={}){await dc(),await oo();let e=await Xr();Rm(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;Ga();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:(hc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:xm(l,{path:el,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await Sm(),d=new ol({jsonPath:Cm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:vm(Tm(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await xc({configDir:el,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 Hc(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)}},Zc(d,e),d.ccrPreHandlerCallbacks=Xc(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 _c(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 nl=w(()=>{"use strict";rl();pc();Pt();yc();Br();bc();zc();us();fo();qc();At();Ft();Je()});import Pm from"fastify";import Em from"@fastify/cors";function Am(n={}){let e=Pm({bodyLimit:52428800,...n});return e.setErrorHandler(Is),e.register(Em),e}async function Om(n={}){return(await Promise.resolve().then(()=>(nl(),tl))).createCcrServer(n)}var xs,ol,iv,rl=w(()=>{xo();zt();pn();rr();dr();fr();Re();on();Qn();se();xe();De();q();Je();pn();Vt();je();Je();Re();xo();rr();dr();fr();Qr();$r();se();xe();wr();De();se();Qn();st();q();Pt();gn();At();es();ts();Ft();xs=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=Am({...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 Ie(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 Ie({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),Ce(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 un(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&Y.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),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 Ki(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{Ar()}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 vo()})}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{Fo()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=bt(()=>this.providerService.getProviders(),t,o=>de(this.configService,o),this.app.log,o=>this.configService.get(o),o=>this.pluginRegistry?.getManagedRuntimeFor(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},ol=xs;iv=Om});rl();export{Vn as ActiveProbeService,Ie as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ge as ProviderService,ae as SSEParserTransform,Ze as SSESerializerTransform,Xe as TokenizerService,Ye as TransformerService,ao as apiKeyAuth,Ce as applyClientAdapter,ro as backupConfigFile,Ci as builtinClientAdapterRegistry,ln as calculateTokenCount,zu as clearClientAdapterCaches,io as clearProviderHealth,vo as closeProxyDispatchers,ec as collectReachableModelKeys,Om as createCcrServer,ol as default,Be as detectClientType,Li as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Ua as getActiveProbeService,qo as getAllQuotaResults,Ho as getAllRateLimitInfo,Ri as getClientAdapter,Ht as getConfiguredProxyUrl,j as getHealthStore,K as getProxyDispatcher,Sr as getQuotaAdapter,rn as getQuotaResult,Vl as getRateLimitInfo,Bt as getRuntimeDebugLog,iv as getServer,Xr as initConfig,oo as initDir,Fo as initProviderHealthPersistence,ut as initQuotaStorePersistence,ct as initRateLimitPersistence,Si as isClientType,Es as isGlobalProxyEnabled,qr as listAnthropicCompatibleModels,Pe as mergeUsageCapture,ge as normalizeSessionId,we as normalizeUsagePayload,kt as pluginManager,X as readConfigFile,wt as readConfigFileRaw,Et as reconcileHealthStore,Or as resetActiveProbeService,de as resolveProviderProxyUrl,Yn as rewriteStream,un as router,Fi as searchProjectBySession,Y as sessionUsageCache,So as setRuntimeDebugLog,bt as startActiveProbe,Ar as stopActiveProbe,Zo as storeQuotaResult,to as tokenSpeedPlugin,uc as usageStore,ue as writeConfigFile};
|
|
415
|
+
Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")yo.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],l=a.content.filter(u=>u.type!=="image"?!0:(yo.storeImage(`${e.id}_Image#${r}`,u.source),i.push(`[Image #${r}]`),r++,!1)),c=`${i.join("")}This is an image, if you need to view or analyze it, you need to extract the imageId`;a.content=l.length>0?[{type:"text",text:c},...l]:c}})})}},Xc=new Cs});var Rs,qc,_o,el=w(()=>{"use strict";Zc();Rs=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},qc=new Rs;qc.registerAgent(Xc);_o=qc});import{EventEmitter as Sm}from"node:events";import{performance as tl}from"node:perf_hooks";import Cm from"json5";function wm(n,e){return n===429||!!(e&&/rate[\s_]limit|too many|限流|频率限制|qps_limit|token_limit|quota exhausted|usage limit|limit reached/i.test(e))}function ol(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Re(n,e)}function ws(n){return n.usageSessionId||n.id}function bo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${ws(n)}`}function Ft(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function Ie(n){return n.body?.model?Array.isArray(n.body.model)?n.body.model.join(","):n.body.model:Array.isArray(n.model)?n.model.join(","):n.model||""}function Pm(n){if(!n)return;let e=n;if(Buffer.isBuffer(n)&&(e=n.toString("utf8")),typeof e=="string")try{e=JSON.parse(e)}catch{return}if(typeof e!="object")return;let t=e.usage?Ee(e.usage):e.response?.usage?Ee(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Em(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();lo(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o;try{o=new URL(`http://127.0.0.1${n.url}`)}catch{return}if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){ol(n,t);let r=bo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=Y.get(r))}}async function Am(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of _o.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function rl(n){return{authClient:(e,t)=>Em(e,t,n),agent:(e,t)=>Am(e,t,n)}}function sl(n,e){n.addHook("onRequest",async t=>{let o;try{o=new URL(`http://127.0.0.1${t.url}`)}catch{return}t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=tl.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname;if(!r)try{r=new URL(`http://127.0.0.1${t.url}`).pathname}catch{r=""}r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=l=>l?a(l):s();lo(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",nl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){ol(t,e);let l=ws(t),c=bo(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new ie),m,y=-1,b="",_="",k="",T=[],x=[];return s(null,Zn(h,async(v,P)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let E=t.agents.find(R=>_o.getAgent(R)?.tools.get(v.data.content_block.name));if(E){m=_o.getAgent(E),y=v.data.index,b=v.data.content_block.name,k=v.data.content_block.id;return}}if(y>-1&&v.data.index===y&&v.data?.delta?.type==="input_json_delta"){_+=v.data?.delta?.partial_json;return}if(y>-1&&v.data.index===y&&v.data?.type==="content_block_stop"){try{let E=Cm.parse(_);x.push({type:"tool_use",id:k,name:b,input:E});let R=await m?.tools.get(b)?.handler(E,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:R}),m=void 0,y=-1,b="",_="",k=""}catch(E){console.log(E)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:T});let E=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!E.ok)return;let A=E.body.pipeThrough(new ie).getReader();for(;;)try{let{value:D,done:C}=await A.read();if(C)break;let O=D;if(["message_start","message_stop"].includes(O.event))continue;if(!P.desiredSize)break;P.enqueue(O)}catch(D){if(D.name==="AbortError"||D.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw D}return}return v}catch(E){if(console.error("Unexpected error in stream processing:",E),E.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw E}}).pipeThrough(new Ze))}let[p,d]=r.tee(),f=async g=>{let m=g.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&Ft(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&Ft(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=Y.get(c)||{},x=Ee(k.usage),v=Ae(T,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:x,mergedUsage:v}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),Y.put(c,v)}if(k?.response?.usage){let T=Ee(k.response.usage),x=Y.get(c)||{},v=Ae(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:Ie(t),usageSessionId:l,capturedUsage:T,mergedUsage:v}),Y.put(c,v)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new ie).getReader();try{for(;;){let{done:g,value:h}=await f.read();if(g)break;let m=h.event,y=h.data;m==="message_start"&&y?.message?.model&&Ft(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&Ft(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ee(b),k=Y.get(c)||{},T=Ae(k,_,m==="message_start");Y.put(c,T)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{f.releaseLock()}})(),s(null,p)}let u=Pm(r);if(u?.usage&&Y.put(c,u.usage),u?.model&&(t.upstreamModel=u.model),typeof r=="object")return r.error?s(r.error,null):s(r,null)}if(typeof r=="object"&&r.error)return s(r.error,null);s(null,r)}),n.addHook("onSend",async(t,o,r)=>{if(nl.emit("onSend",t,o,r),o.statusCode>=400&&(t.pathname?.endsWith("/v1/messages")||t.pathname?.endsWith("/v1/responses")))try{typeof r=="string"?t.errorResponseBody=r:r&&typeof r=="object"&&(t.errorResponseBody=JSON.stringify(r))}catch{}return r}),n.addHook("onRequestAbort",async t=>{Yo(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Yo(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async v=>{if(!v)return;let P;try{await Promise.race([v,new Promise(E=>{P=setTimeout(E,Rm)})])}finally{P&&clearTimeout(P)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=ws(t),a=s,i=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:Y.get(bo(t)),u=ds(a),p=H(),d,f,g=t.sseError,h=g&&(g.type||g.code||g.message),m=c?.output_tokens&&c.output_tokens>0,y=t.contentDelivered===!0,b=l||h&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(g),f=JSON.stringify(g)),f=f||t.errorResponseBody;let v=Ie(t);wm(o.statusCode,d)?p.markRateLimited(t.provider||"",v,120,d):p.recordFailure(t.provider||"",v,d)}else{let v=Ie(t);p.recordSuccess(t.provider||"",v)}let _=c?.cache_read_input_tokens??0,T=c?.input_tokens||0||t.tokenCount||0;!c?.usage_estimated&&!_&&t.tokenCount&&c?.input_tokens&&c.input_tokens<t.tokenCount&&(_=t.tokenCount-c.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:c.input_tokens,impliedCache:_}));let x=b?0:c?.output_tokens||0;!b&&t.body?.stream&&T===0&&x===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:Ie(t),usageSessionId:i,tokenCount:t.tokenCount,cachedUsage:c,note:"Successful streaming request ended with zero usage. Check provider_stream_chunk usage_monitor and usage_capture_* logs."}),$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:i,provider:t.provider||"",originalModel:t.originalModel||t.body?.model||"",model:Ie(t),upstreamModel:t.upstreamModel||Ie(t)||void 0,...c?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Be(t),stream:t.body?.stream??!1,inputTokens:T,outputTokens:x,cacheReadInputTokens:_,cacheCreationInputTokens:c?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(tl.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&Y.delete(bo(t))}catch(r){console.error("Usage tracking error:",r)}})}var Rm,nl,il=w(()=>{"use strict";Je();on();tn();re();Dr();Fr();jr();Ut();gn();el();is();pn();Rm=1500;nl=new Sm});var cl={};vo(cl,{createCcrServer:()=>Um});import{homedir as Om}from"os";import{join as Im}from"path";import{createStream as Mm}from"rotating-file-stream";import{CONFIG_FILE as Lm,HOME_DIR as al,listPresets as $m,ensureCcrSelfProvider as Nm}from"@wengine-ai/claude-code-router-shared";async function Um(n={}){await _c(),await so();let e=await ns();Nm(e).changed&&(await ue(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;ec();let l=f=>(f>9?"":"0")+f,c=(f,g)=>{let h;f?typeof f=="number"?h=new Date(f):h=f:h=new Date;let m=h.getFullYear()+""+l(h.getMonth()+1),y=l(h.getDate()),b=l(h.getHours()),_=l(h.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${l(h.getSeconds())}${g?`_${g}`:""}.log`},u;n.logger!==void 0?u=n.logger:(xc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:Mm(c,{path:al,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await $m(),d=new ul({jsonPath:Lm,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:Im(Om(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await Ac({configDir:al,registry:d.pluginRegistry,getServer:()=>d,log:{info:y=>d.app?.log?.info?.(y),warn:y=>d.app?.log?.warn?.(y),error:y=>d.app?.log?.error?.(y)}});f.failed.length&&d.app?.log?.warn?.(`plugins failed to load: ${f.failed.map(y=>`${y.name} (${y.error})`).join("; ")}`),d.pluginRegistry.listLoadedPlugins().length&&d.app?.log?.info?.(`provider plugins active: ${d.pluginRegistry.listLoadedPlugins().map(y=>`${y.name}@${y.version}`).join(", ")}`),f.loaded.length&&tt(d,e,d.app.log),await Qc(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Be(y.req):"unknown";$t({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),sessionId:y.sessionId||"",provider:y.provider||"",originalModel:y.originalModel||"",model:y.model||"",modelFamily:y.modelFamily||"",scenarioType:y.scenarioType||"default",clientType:b,stream:y.stream??!1,inputTokens:y.inputTokens||0,outputTokens:0,cacheReadInputTokens:y.cacheReadInputTokens||0,cacheCreationInputTokens:y.cacheCreationInputTokens||0,ttft:null,tokensPerSecond:null,durationMs:0,status:"error",errorMessage:y.errorMessage,responseBody:void 0})}catch(b){console.error("Fallback usage tracking error:",b)}},sl(d,e),d.ccrPreHandlerCallbacks=rl(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,b)=>{if(y.status==="rejected"){let _=p[b],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await Cc(d,e),Et(e,d.app?.log);let h=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",h),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",h),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var ll=w(()=>{"use strict";dl();bc();Pt();Sc();Qr();Rc();Vc();gs();go();il();At();Ut();Je()});import Dm from"fastify";import Fm from"@fastify/cors";function jm(n={}){let e=Dm({bodyLimit:52428800,...n});return e.setErrorHandler(Us),e.register(Fm),e}async function Hm(n={}){return(await Promise.resolve().then(()=>(ll(),cl))).createCcrServer(n)}var Ps,ul,bv,dl=w(()=>{Ro();zt();pn();ir();gr();yr();Pe();on();Xn();re();Se();Ce();q();Je();pn();Qt();je();Je();Pe();Ro();ir();gr();yr();es();Hr();re();Se();Or();Ce();re();Xn();rt();q();Pt();gn();At();ss();is();Ut();Ps=class{app;pluginRegistry=new st;namespaceProviders=[];reloadProviders(e){let t=e?.Providers??e?.providers??[];this.configService.set("providers",t),this.providerService.reload();for(let o of this.namespaceProviders)o.providers.reload()}reloadNamespaceProviders(e,t){let o=this.namespaceProviders.find(r=>r.name===e);if(!o)throw new Error(`unknown namespace ${e}`);o.config.set("providers",t),o.providers.reload()}configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;readiness;mainNamespaceRegistered=!1;signalHandlersRegistered=!1;ccrPreHandlerCallbacks;constructor(e={}){let{initialConfig:t,jsonPath:o,envPath:r,useEnvFile:s,useJsonFile:a,useEnvironmentVariables:i,...l}=e;this.app=jm({...l,logger:l.logger??!0}),this.app._server=this,this.app.addHook("onClose",async()=>{this.pluginRegistry.dispose(),this.tokenizerService?.dispose()});let c={initialConfig:t};o!==void 0&&(c.jsonPath=o),r!==void 0&&(c.envPath=r),s!==void 0&&(c.useEnvFile=s),a!==void 0&&(c.useJsonFile=a),i!==void 0&&(c.useEnvironmentVariables=i),this.configService=new Me(c),this.transformerService=new Ye(this.configService,this.app.log),this.tokenizerService=new Xe(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ge(this.configService,this.transformerService,this.app.log)})()}async ready(){await this.readiness}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async registerNamespace(e,t){if(!e)throw new Error("name is required");if(await this.ready(),e==="/"&&this.mainNamespaceRegistered)return;let o=this.configService,r=this.transformerService,s=this.providerService,a=this.tokenizerService;if(e!=="/"){if(!t)throw new Error("options is required");o=new Me({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Ye(o,this.app.log),a=new Xe(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ge(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async l=>{l.decorate("pluginRegistry",this.pluginRegistry),l.decorate("configService",o),l.decorate("transformerService",r),l.decorate("providerService",s),l.decorate("tokenizerService",a),l.decorate("recordUsage",this.recordUsage||(()=>{})),l.addHook("preHandler",async(c,u)=>{let p=new URL(`http://127.0.0.1${c.url}`);c.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!c.body||typeof c.body!="object")return;let g=c.ccrHookOrder||=[];if(g.push("request-normalize"),f&&c.body.input&&!c.body.messages&&ht(c.body),c.body.stream===void 0&&(c.body.stream=!1),c.log.info({data:c.body,type:"request body"}),g.push("adapter"),!c.originalModel&&c.body.model&&(c.originalModel=c.body.model),Re(c,o.getAll()),g.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(c,u),u.sent))&&(g.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(c,u),u.sent)))){g.push("router"),c.body?.model&&await un(c,u,{configService:o,tokenizerService:a}),c.usageCacheKey&&Y.put(c.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),g.push("provider-model-normalize");try{let h=c.body;if(!h||!h.model)return u.code(400).send({error:"Missing model in request body"});let m=h.model.split(","),y=h.model;if(m.length>1){let[b,..._]=m;y=_.join(","),h.model=y,c.provider=b}c.model=y}catch(h){return c.log.error({error:h},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await Xi(l)};e==="/"?(await this.app.register(i),this.mainNamespaceRegistered=!0):await this.app.register(i,{prefix:e})}async start(){try{if(await this.ready(),await this.registerNamespace("/"),!this.signalHandlersRegistered){this.signalHandlersRegistered=!0;let t=async s=>{this.app.log.info(`Received ${s}, shutting down gracefully...`);try{$r()}catch{}await this.app.close(),process.exit(0)},o=()=>void t("SIGINT"),r=()=>void t("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",r),this.app.addHook("onClose",async()=>{process.off("SIGINT",o),process.off("SIGTERM",r),this.signalHandlersRegistered=!1;try{this.tokenizerService.dispose()}catch{}await Co()})}await this.app.ready();let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{at()}catch{}try{ut()}catch{}try{jo()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=bt(()=>this.providerService.getProviders(),t,o=>de(this.configService,o),this.app.log,o=>this.configService.get(o),o=>this.pluginRegistry?.getManagedRuntimeFor(o))}catch(t){this.app.log.warn?.(`Failed to start active probe service: ${t.message}`)}}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},ul=Ps;bv=Hm});dl();export{Yn as ActiveProbeService,Me as ConfigService,te as ProjectRoutingError,Xt as ProviderHealthStore,Ge as ProviderService,ie as SSEParserTransform,Ze as SSESerializerTransform,Xe as TokenizerService,Ye as TransformerService,lo as apiKeyAuth,Re as applyClientAdapter,io as backupConfigFile,Ei as builtinClientAdapterRegistry,ln as calculateTokenCount,Yu as clearClientAdapterCaches,co as clearProviderHealth,Co as closeProxyDispatchers,ac as collectReachableModelKeys,Hm as createCcrServer,ul as default,Be as detectClientType,Fi as diagnoseResolutionFailure,he as extractSessionIdFromUserId,Wa as getActiveProbeService,tr as getAllQuotaResults,Jo as getAllRateLimitInfo,Oi as getClientAdapter,Ht as getConfiguredProxyUrl,H as getHealthStore,G as getProxyDispatcher,Er as getQuotaAdapter,rn as getQuotaResult,nu as getRateLimitInfo,Bt as getRuntimeDebugLog,bv as getServer,ns as initConfig,so as initDir,jo as initProviderHealthPersistence,ut as initQuotaStorePersistence,at as initRateLimitPersistence,Ai as isClientType,Ls as isGlobalProxyEnabled,rs as listAnthropicCompatibleModels,Ae as mergeUsageCapture,ge as normalizeSessionId,Ee as normalizeUsagePayload,kt as pluginManager,X as readConfigFile,wt as readConfigFileRaw,Et as reconcileHealthStore,Nr as resetActiveProbeService,de as resolveProviderProxyUrl,Zn as rewriteStream,un as router,zi as searchProjectBySession,Y as sessionUsageCache,Po as setRuntimeDebugLog,bt as startActiveProbe,$r as stopActiveProbe,lt as storeQuotaResult,oo as tokenSpeedPlugin,yc as usageStore,ue as writeConfigFile};
|
|
410
416
|
//# sourceMappingURL=server.mjs.map
|