@wengine-ai/llms 2.3.2429 → 2.3.2431
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 -15
- package/dist/ccr/plugin-install-routes.d.ts +3 -4
- package/dist/cjs/server.cjs +162 -156
- package/dist/cjs/server.cjs.map +3 -3
- package/dist/esm/server.mjs +162 -156
- package/dist/esm/server.mjs.map +3 -3
- package/package.json +13 -11
package/dist/cjs/server.cjs
CHANGED
|
@@ -1,193 +1,199 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Ql=Object.create;var Tn=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var Yl=Object.getOwnPropertyNames;var Xl=Object.getPrototypeOf,Zl=Object.prototype.hasOwnProperty;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var xn=(n,e)=>{for(var t in e)Tn(n,t,{get:e[t],enumerable:!0})},ti=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yl(e))!Zl.call(n,r)&&r!==t&&Tn(n,r,{get:()=>e[r],enumerable:!(o=Vl(e,r))||o.enumerable});return n};var ee=(n,e,t)=>(t=n!=null?Ql(Xl(n)):{},ti(e||!n||!n.__esModule?Tn(t,"default",{value:n,enumerable:!0}):t,n)),ni=n=>ti(Tn({},"__esModule",{value:!0}),n);function eu(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(ql.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 si(n){let e=[];for(let t of[...oi,ri]){let o=n[t];if(o==null)continue;let r=eu(o);r.ok||e.push({key:t,error:r.error})}return e}function or(){return nr||(nr=new Cn.Agent({connect:{timeout:15e3}})),nr}function ii(n){let e=n.get(ri);return(typeof e=="string"?e.trim():"")||void 0}function ai(n){return n?X(n):or()}function Et(n){for(let e of oi){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function rr(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 he(n,e){let t=Et(n);if(t)return rr(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function X(n){let e=tu(n),t=Sn.get(e);if(t)return t;let o=new Cn.ProxyAgent(e);return Sn.set(e,o),o}async function Rn(){let n=Array.from(Sn.values());Sn.clear(),await Promise.allSettled(n.map(e=>e.close()))}function tu(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 Cn,oi,ri,ql,Sn,nr,ae=w(()=>{"use strict";Cn=require("undici"),oi=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],ri="SUBSCRIPTION_PROXY_URL",ql=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Sn=new Map});var At,sr,ci,li,ze,ir=w(()=>{"use strict";At=require("fs"),sr=require("path"),ci=require("dotenv"),li=ee(require("json5"),1);ae();ze=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:(0,sr.join)(process.cwd(),this.options.jsonPath);if((0,At.existsSync)(e))try{let t=(0,At.readFileSync)(e,"utf-8"),o=li.default.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:(0,sr.join)(process.cwd(),this.options.envPath);if((0,At.existsSync)(e))try{let t=(0,ci.config)({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 Et(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 V(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 ui(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 wn=w(()=>{"use strict"});function Pn(n){ar=n}function Ot(){return ar}function En(n){return ar||n.get("DEBUG_LOG")===!0}function fi(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?nt:{maxBodyLength:e.maxBodyLength??nt.maxBodyLength,maxStreamChunks:e.maxStreamChunks??nt.maxStreamChunks}}function An(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();nu.has(r)||ou.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function On(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function mi(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:An(t.headers),body:On(o,nt.maxBodyLength)})}function gi(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:An(t.headers),...t.body!==void 0?{body:On(t.body,nt.maxBodyLength)}:{}})}function di(n,e,t,o){let r=ru(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:On(o,nt.maxBodyLength)})}function ru(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:On(o,512)})}}if(e.length)return e.length===1?e[0]:e}function pi(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function hi(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:i,value:l}=await r.read();if(i)break;a+=l;let c=a.split(`
|
|
2
2
|
|
|
3
|
-
`);a=
|
|
4
|
-
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(nu.some(s=>r.includes(s))){e=!0;break}ru.some(s=>r.includes(s))&&(t=!0)}}return e||ou(n)?"content":t?"empty":"pending"}async function hi(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=c-Date.now(),p=Symbol("timeout"),d,f=o.read(),g=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),g===p)return l(ir(a)==="content"?"content":"pending",On(o,f));if(g.done){a+=r.decode();let m=ir(a);return l(m==="empty"?"empty":"pending",null)}if(!g.value)continue;s.push(g.value),i+=g.value.byteLength,a+=r.decode(g.value,{stream:!0});let h=ir(a);if(h==="content")return l("content",On(o));if(h==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(gi(a)||i>=e)return l("pending",On(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function On(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 yi(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var nu,ru,_i=P(()=>{"use strict";nu=["content_block_start","content_block_delta","content_block_stop"];ru=["message_stop","response.completed","response.incomplete","[DONE]"]});function su(n,e){return`${n.name}|${e?.name??""}`}function ar(n){return n.__ccrPluginRequestState??={budgets:new Map}}function ot(n,e,t){let o=ar(n),r=su(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function cr(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(ot(n,e,o).terminalError=t,!0)}var bi=P(()=>{"use strict"});var lr=P(()=>{"use strict"});function Ti(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 ki,Mt,iu,dr,In=P(()=>{"use strict";ki=ee(require("fastify"),1);lr();Mt=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let h of this.plugins.values()){for(let m of s.runtimes.keys())if(h.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(h.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(h=>[...s.transformers].map(([m,y])=>{if(h.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:h,name:m,value:h.preparePluginTransformer(y)}})),g=[];try{for(let h of f)g.push(h),h.service.registerTransformer(h.name,h.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(h){for(let m of g)m.service.removeTransformer(m.name);throw a="aborted",h}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:d??p}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=(0,ki.default)({logger:!1});try{for(let i of e){let c=i(s);c!==s&&await c}for(let i of this.plugins.values())for(let c of i.preparedRoutes)a.route(c);for(let i of r){let c=Array.isArray(i.method)?i.method:[i.method];for(let l of c)if(t.hasRoute({method:l,url:i.url,constraints:i.constraints}))throw new Error(`plugin route ${l} ${i.url} is already registered`);a.route(i)}return await a.ready(),r}finally{await a.close()}}async registerAllRoutes(e){this.assertOpen();for(let t of this.plugins.values())for(let o of t.preparedRoutes)e.route(o)}dispose(){if(!this.disposed){for(let e of this.transformerServices)for(let t of this.plugins.values())for(let o of t.transformers.keys())e.removeTransformer(o);this.plugins.clear(),this.transformerServices.clear(),this.disposed=!0}}assertOpen(){if(this.disposed)throw new Error("plugin host is disposed")}},iu=new Mt,dr=()=>iu});function vi(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 Be(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?au(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=Ti(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function au(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 xi=P(()=>{"use strict";In()});var Mn,pr=P(()=>{Mn="2.3.2428"});var Si={};vn(Si,{getFallbackPromotionStore:()=>rt,resetFallbackPromotionStore:()=>uu});function rt(n){return Je||(Je=new fr,n&&Je.configure(n)),Je}function uu(){Je&&(Je.clearAll(),Je=null)}var lu,fr,Je,Ln=P(()=>{"use strict";ue();lu=600*1e3,fr=class{promotions=new Map;enabled=!0;ttlMs=lu;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(!z().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(g=>g.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(g=>String(g).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},Je=null});function mu(n){try{if(!(0,Te.existsSync)(hr))return;let e=JSON.parse((0,Te.readFileSync)(hr,"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 Ri(n){try{let e=n.getAllStates();if(e.length===0)return;(0,Te.existsSync)(gr)||(0,Te.mkdirSync)(gr,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,Te.writeFileSync)(hr,JSON.stringify(t,null,2),"utf-8")}catch{}}function $n(){if(Ci)return;Ci=!0;let n=z();mu(n),fu=setInterval(()=>Ri(n),6e4),process.on("exit",()=>Ri(n))}function z(n){return mr||(mr=new Lt(n)),mr}var Te,yr,wi,du,pu,Lt,gr,hr,Ci,fu,mr,ue=P(()=>{"use strict";Te=require("fs"),yr=require("path"),wi=require("@wengine-ai/claude-code-router-shared"),du=120,pu={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Lt=class{states=new Map;config;probeTimer;constructor(e){this.config={...pu,...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}=(Ln(),Zs(Si));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??du)*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)}},gr=(0,yr.join)(wi.HOME_DIR,"runtime"),hr=(0,yr.join)(gr,"provider-health.json"),Ci=!1,fu=null;mr=null});function $t(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=_r(o,gu),s=_r(o,hu),a=_r(o,yu);(r||s||a)&&st.set(n,{provider:n,remaining:Ai(r),limit:Ai(s),reset:_u(a),capturedAt:Date.now()})}function Mi(n){return st.get(n)}function Nn(){return Array.from(st.values())}function Un(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function _r(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 _u(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=bu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function bu(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 ku(){try{if(!(0,ve.existsSync)(kr))return;let n=JSON.parse((0,ve.readFileSync)(kr,"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;st.set(t.provider,t)}}catch{}}function Oi(){try{if(st.size===0)return;(0,ve.existsSync)(br)||(0,ve.mkdirSync)(br,{recursive:!0}),(0,ve.writeFileSync)(kr,JSON.stringify(Array.from(st.values()),null,2),"utf-8")}catch{}}function it(){Pi||(Pi=!0,ku(),Ei=setInterval(Oi,6e4),Ei.unref?.(),process.on("exit",Oi))}var ve,Tr,Ii,br,kr,st,Pi,Ei,gu,hu,yu,We=P(()=>{"use strict";ve=require("fs"),Tr=require("path"),Ii=require("@wengine-ai/claude-code-router-shared"),br=(0,Tr.join)(Ii.HOME_DIR,"runtime"),kr=(0,Tr.join)(br,"rate-limit.json"),st=new Map,Pi=!1,Ei=null,gu=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],hu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],yu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Fn(){return vr||(vr=new Sr),vr}function Rr(){return xr||(xr=new Cr),xr}function Tu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function Li(n){let e=Tu(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 $i(n,e){let t=Fn(),o=n?.[Dn];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[Dn]=t.acquire(e)}function wr(n){let e=n?.[Dn];e&&Fn().release(e)}function Ni(n,e){let t=Li(n),o=n?.[Dn],r=t?Rr().get(t)!==void 0:!1;!o&&!r||(t&&Rr().bind(t,e),$i(n,e))}function vu(n,e,t){let o=Fn(),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 Ui(n,e,t){let o=Li(n),r=Rr(),s=Fn(),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=vu(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 $i(n,i),i}var Sr,Cr,vr,xr,Dn,jn=P(()=>{"use strict";Sr=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()}},Cr=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()}},vr=null,xr=null;Dn="__concurrencyLease"});async function H(n){let e=await n.text();return xu(e,n.status)}function xu(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 Di(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function Nt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function xe(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})),Nt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:Nt(s)}}async function Ee(n){try{let e=await n.text();if(Nt(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 oe=P(()=>{"use strict"});function Su(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 Hn(n){for(let e of Su(n))if(e.startsWith("response."))return!0;return!1}var at,Pr=P(()=>{"use strict";oe();at=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role==="system")return;if(Array.isArray(r.content)){let i=r.content.map(c=>this.normalizeRequestContent(c,r.role)).filter(c=>c!==null);i.length>0?r.content=i:delete r.content}if(r.role==="tool"){let i={...r};i.type="function_call_output",i.call_id=r.tool_call_id,i.output=r.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,t.push(i);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(i=>{t.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}let{thinking:s,...a}=r;r.role==="assistant"&&a.content===void 0||t.push(a)}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await xe(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 xe(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 Ee(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await H(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})),Hn(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}):Hn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",c,l,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let S=(x,I=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[{index:0,delta:x,finish_reason:I}]})}
|
|
3
|
+
`);a=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?di(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&&di(e,t,s,a.trim()),s++),pi(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),pi(e,t,s)}finally{r.releaseLock()}})()}var nu,ou,nt,ar,It=w(()=>{"use strict";nu=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),ou=/token|secret|credential|passwd|password/i,nt={maxBodyLength:4096,maxStreamChunks:100},ar=!1});function yi(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=X(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:An(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:su(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function su(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 _i=w(()=>{ae();It()});function au(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function bi(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function cr(n){if(bi(n))return"pending";let e=!1,t=!1;for(let o of n.split(`
|
|
4
|
+
`)){let r=o.trim();if(!(!r.startsWith("data:")&&!r.startsWith("event:"))){if(iu.some(s=>r.includes(s))){e=!0;break}cu.some(s=>r.includes(s))&&(t=!0)}}return e||au(n)?"content":t?"empty":"pending"}async function ki(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(cr(a)==="content"?"content":"pending",In(o,f));if(g.done){a+=r.decode();let m=cr(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=cr(a);if(h==="content")return c("content",In(o));if(h==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if(bi(a)||i>=e)return c("pending",In(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function In(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 vi(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 iu,cu,Ti=w(()=>{"use strict";iu=["content_block_start","content_block_delta","content_block_stop"];cu=["message_stop","response.completed","response.incomplete","[DONE]"]});function lu(n,e){return`${n.name}|${e?.name??""}`}function lr(n){return n.__ccrPluginRequestState??={budgets:new Map}}function ot(n,e,t){let o=lr(n),r=lu(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function ur(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(ot(n,e,o).terminalError=t,!0)}var xi=w(()=>{"use strict"});var dr=w(()=>{"use strict"});function Ci(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 Si,Mt,uu,fr,Mn=w(()=>{"use strict";Si=ee(require("fastify"),1);dr();Mt=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=(0,Si.default)({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")}},uu=new Mt,fr=()=>uu});function Ri(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 Be(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?du(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=Ci(n.name,i);return l.isRateLimit=i.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function du(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 wi=w(()=>{"use strict";Mn()});var Ln,mr=w(()=>{Ln="2.3.2431"});var Pi={};xn(Pi,{getFallbackPromotionStore:()=>rt,resetFallbackPromotionStore:()=>mu});function rt(n){return Je||(Je=new gr,n&&Je.configure(n)),Je}function mu(){Je&&(Je.clearAll(),Je=null)}var fu,gr,Je,$n=w(()=>{"use strict";ue();fu=600*1e3,gr=class{promotions=new Map;enabled=!0;ttlMs=fu;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(!z().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}},Je=null});function _u(n){try{if(!(0,ve.existsSync)(_r))return;let e=JSON.parse((0,ve.readFileSync)(_r,"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 Ai(n){try{let e=n.getAllStates();if(e.length===0)return;(0,ve.existsSync)(yr)||(0,ve.mkdirSync)(yr,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,ve.writeFileSync)(_r,JSON.stringify(t,null,2),"utf-8")}catch{}}function Nn(){if(Ei)return;Ei=!0;let n=z();_u(n),yu=setInterval(()=>Ai(n),6e4),process.on("exit",()=>Ai(n))}function z(n){return hr||(hr=new Lt(n)),hr}var ve,br,Oi,gu,hu,Lt,yr,_r,Ei,yu,hr,ue=w(()=>{"use strict";ve=require("fs"),br=require("path"),Oi=require("@wengine-ai/claude-code-router-shared"),gu=120,hu={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Lt=class{states=new Map;config;probeTimer;constructor(e){this.config={...hu,...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}=($n(),ni(Pi));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??gu)*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)}},yr=(0,br.join)(Oi.HOME_DIR,"runtime"),_r=(0,br.join)(yr,"provider-health.json"),Ei=!1,yu=null;hr=null});function $t(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=kr(o,bu),s=kr(o,ku),a=kr(o,vu);(r||s||a)&&st.set(n,{provider:n,remaining:Li(r),limit:Li(s),reset:Tu(a),capturedAt:Date.now()})}function Ui(n){return st.get(n)}function Un(){return Array.from(st.values())}function Dn(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function kr(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function Li(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Tu(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=xu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function xu(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(!(0,Te.existsSync)(Tr))return;let n=JSON.parse((0,Te.readFileSync)(Tr,"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;st.set(t.provider,t)}}catch{}}function $i(){try{if(st.size===0)return;(0,Te.existsSync)(vr)||(0,Te.mkdirSync)(vr,{recursive:!0}),(0,Te.writeFileSync)(Tr,JSON.stringify(Array.from(st.values()),null,2),"utf-8")}catch{}}function it(){Ii||(Ii=!0,Su(),Mi=setInterval($i,6e4),Mi.unref?.(),process.on("exit",$i))}var Te,xr,Ni,vr,Tr,st,Ii,Mi,bu,ku,vu,We=w(()=>{"use strict";Te=require("fs"),xr=require("path"),Ni=require("@wengine-ai/claude-code-router-shared"),vr=(0,xr.join)(Ni.HOME_DIR,"runtime"),Tr=(0,xr.join)(vr,"rate-limit.json"),st=new Map,Ii=!1,Mi=null,bu=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],ku=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],vu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function jn(){return Sr||(Sr=new Rr),Sr}function Pr(){return Cr||(Cr=new wr),Cr}function Cu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function Di(n){let e=Cu(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 Fi(n,e){let t=jn(),o=n?.[Fn];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[Fn]=t.acquire(e)}function Er(n){let e=n?.[Fn];e&&jn().release(e)}function ji(n,e){let t=Di(n),o=n?.[Fn],r=t?Pr().get(t)!==void 0:!1;!o&&!r||(t&&Pr().bind(t,e),Fi(n,e))}function Ru(n,e,t){let o=jn(),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 Hi(n,e,t){let o=Di(n),r=Pr(),s=jn(),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=Ru(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 Fi(n,i),i}var Rr,wr,Sr,Cr,Fn,Hn=w(()=>{"use strict";Rr=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()}},wr=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()}},Sr=null,Cr=null;Fn="__concurrencyLease"});async function H(n){let e=await n.text();return wu(e,n.status)}function wu(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 zi(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function Nt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function xe(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})),Nt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:Nt(s)}}async function Ee(n){try{let e=await n.text();if(Nt(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 oe=w(()=>{"use strict"});function Pu(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 zn(n){for(let e of Pu(n))if(e.startsWith("response."))return!0;return!1}var at,Ar=w(()=>{"use strict";oe();at=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 xe(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 xe(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 Ee(e);if(s.isSSE)return this.transformResponseOut(s.response,t);e=s.response}}if(o.includes("application/json")){let r=await H(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})),zn(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}):zn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",l,c,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(v){let x=(S,M=null)=>{v.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[{index:0,delta:S,finish_reason:M}]})}
|
|
5
5
|
|
|
6
|
-
`))},
|
|
6
|
+
`))},T=S=>{if(!S)return;let M=_.getCacheReadInputTokens(S),L=typeof S.input_tokens=="number"?S.input_tokens:void 0,U=_.getCacheCreationInputTokens(S);v.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[],usage:{prompt_tokens:L,completion_tokens:typeof S.output_tokens=="number"?S.output_tokens:void 0,total_tokens:S.total_tokens,prompt_tokens_details:{cached_tokens:M,cache_creation_tokens:U},cache_read_input_tokens:M,cache_creation_input_tokens:U}})}
|
|
7
7
|
|
|
8
|
-
`))},
|
|
8
|
+
`))},P=S=>{m||(m=!0,v.enqueue(r.encode(`data: ${JSON.stringify({error:{message:S,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
|
|
9
9
|
|
|
10
|
-
`)))},
|
|
10
|
+
`)))},A=S=>{y||(y=!0,T(u),x({},S))},R=()=>{b||(b=!0,v.enqueue(r.encode(`data: [DONE]
|
|
11
11
|
|
|
12
|
-
`)))},
|
|
12
|
+
`)))},O=(S,M)=>{let L=S?.call_id||S?.id||(M!==void 0?`idx_${M}`:void 0);if(!L)return h++;let U=f.get(L);if(U!==void 0)return U;let $=h++;return f.set(L,$),S?.call_id&&S?.id?(f.set(S.id,$),M!==void 0&&f.set(`idx_${M}`,$)):S?.id&&M!==void 0&&f.set(`idx_${M}`,$),$},F=S=>{let M=!1;for(let L of Array.isArray(S)?S:[])if(L?.type==="function_call"){d="tool";let U=O(L,void 0),$=L.call_id||L.id;$&&g.set(U,$),x({role:"assistant",tool_calls:[{index:U,id:$,type:"function",function:{name:L.name||"",arguments:typeof L.arguments=="string"?L.arguments:""}}]}),M=!0}else if(L?.type==="message")for(let U of Array.isArray(L.content)?L.content:[])U?.type==="output_text"&&typeof U.text=="string"&&U.text.trim().length>0&&(d="text",x({role:"assistant",content:U.text}),M=!0);return M},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 M=S.item;if(M?.type!=="function_call")return;d="tool";let L=O(M,S.output_index),U=M.call_id||M.id;U&&g.set(L,U),x({role:"assistant",tool_calls:[{index:L,id:U,type:"function",function:{name:M.name||"",arguments:""}}]});return}case"response.function_call_arguments.delta":{let M=O({id:S.item_id},S.output_index);d="tool";let L=g.get(M);x({tool_calls:[{index:M,...L?{id:L,type:"function"}:{},function:{arguments:typeof S.delta=="string"?S.delta:""}}]});return}case"response.output_text.annotation.added":{let M=S.annotation;if(!M)return;d="annotation",x({annotations:[{type:"url_citation",url_citation:{url:M.url||"",title:M.title||"",content:"",start_index:M.start_index||0,end_index:M.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 M=p!==S.item_id;p=S.item_id;let L={content:S.delta};M&&(L.role="assistant"),x(L);return}case"response.completed":{u=S.response?.usage;let M=Array.isArray(S.response?.output)?S.response.output:[],L=M.some(U=>U?.type==="function_call");if(d===""&&F(M),!L&&d===""){let U=String(S.response?.incomplete_details?.reason??"");P(M.length===0&&!U?"Upstream Responses stream completed with no output":`Upstream Responses stream produced no content (${U||"empty"})`);return}A(d==="tool"||L?"tool_calls":"stop");return}case"response.incomplete":{u=S.response?.usage;let M=String(S.response?.incomplete_details?.reason??"");d===""&&F(Array.isArray(S.response?.output)?S.response.output:[]);let L=M==="max_output_tokens"||M==="max_tokens";if(d===""){P(`Upstream Responses stream produced no content (${M||"incomplete"})`);return}A(L?"length":M==="content_filter"?"content_filter":"stop");return}case"response.failed":{let M=S.response?.error||S.error||void 0;P(M?.message||"Upstream Responses stream failed before completing");return}case"error":{P(S.error?.message||S.message||"Upstream Responses stream error");return}default:return}},I=e.getReader();(async()=>{try{for(;;){let{done:S,value:M}=await I.read();if(S)break;i+=o.decode(M,{stream:!0});let L=i.split(/\r?\n/);i=L.pop()||"";for(let U of L){let $=U.trim();if(!$||$.startsWith(":")||$.startsWith("event:")||!$.startsWith("data:"))continue;let j=$.slice(5).trim();if(!j)continue;if(j==="[DONE]"){R();continue}let G;try{G=JSON.parse(j)}catch{continue}C(G)}}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"):A(d==="tool"?"tool_calls":"stop")),m||R()}catch(S){console.error("Responses\u2192Chat stream error:",S);try{v.error(S)}catch{}return}finally{try{I.releaseLock()}catch{}}try{v.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:g}=await a.read();if(g||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),zn(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")||zn(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 H(e);return new Response(JSON.stringify(this.wrapChatInResponses(r)),{headers:{"Content-Type":"application/json"}})}catch{return e}}convertOpenAIChatStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i=0,l=!1,c=!1,u="",p=-1,d=[],f=(h,m)=>r.encode(`event: ${h}
|
|
13
13
|
data: ${JSON.stringify(m)}
|
|
14
14
|
|
|
15
|
-
`),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
|
|
16
|
-
`);y=
|
|
15
|
+
`),g=(h,m=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:h,model:s,output:m,usage:this.buildResponsesUsage()});return new ReadableStream({async start(h){try{let m=e.getReader(),y="",b=!1,_=k=>{if(!b){b=!0;for(let v of d)if(v.type==="function_call"){let x=d.indexOf(v);h.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:v.call_id||v.id,output_index:x,arguments:v.arguments||""})),v.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:v}))}for(let v of d)if(v.type==="message"){let x=d.indexOf(v);v.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:v}))}h.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:v}=await m.read();if(k)break;y+=o.decode(v,{stream:!0});let x=y.split(`
|
|
16
|
+
`);y=x.pop()||"";for(let T of x){let P=T.trim();if(!P||P.startsWith("event:")||!P.startsWith("data:"))continue;let A=P.slice(5).trim();if(A==="[DONE]"){_({}),h.enqueue(r.encode(`data: [DONE]
|
|
17
17
|
|
|
18
|
-
`));continue}let
|
|
19
|
-
data: ${JSON.stringify(
|
|
18
|
+
`));continue}let R;try{R=JSON.parse(A)}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 O=R.choices?.[0];if(!O)continue;let F=O.delta;if(F?.content){if(!c){c=!0;let C=i++,I={id:`${a}_msg`,type:"message",status:"in_progress",role:"assistant",content:[]};d.push(I),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:C,item:I}))}h.enqueue(f("response.output_text.delta",{type:"response.output_text.delta",item_id:`${a}_msg`,output_index:i-1,content_index:0,delta:F.content}))}if(Array.isArray(F?.tool_calls))for(let C of F.tool_calls){if(C.id){u=C.id,p=i++;let I={id:C.id,type:"function_call",status:"in_progress",call_id:C.id,name:C.function?.name||"",arguments:""};d.push(I),h.enqueue(f("response.output_item.added",{type:"response.output_item.added",output_index:p,item:I}))}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 I=d.find(S=>S.call_id===u);I&&(I.arguments+=C.function.arguments)}}O.finish_reason&&_(R)}}b||_({}),h.close()}catch(m){h.error(m)}}})}convertAnthropicStreamToResponsesAPI(e,t){let o=new TextDecoder,r=new TextEncoder,s=t?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,i="",l="",c=-1,u="",p="",d="",f=-1,g="",h="",m=-1,y=0,b=!1,_=!1,k=!1,v=!1,x=null,T=[],P=(I,S)=>r.encode(`event: ${I}
|
|
19
|
+
data: ${JSON.stringify(S)}
|
|
20
20
|
|
|
21
|
-
`),
|
|
22
|
-
`);
|
|
21
|
+
`),A=(I,S=[])=>({id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:I,model:s,output:S,usage:this.buildResponsesUsage()}),R=()=>{b||(b=!0,C.enqueue(P("response.created",{type:"response.created",response:A("in_progress")})),C.enqueue(P("response.in_progress",{type:"response.in_progress",response:A("in_progress")})))},O=(I,S)=>{C.enqueue(P("response.output_item.done",{type:"response.output_item.done",output_index:I,item:{...S,status:"completed"}}))},F=I=>{if(!v){if(v=!0,_){let S=T.find(M=>M.type==="message");S&&(S.content=[{type:"output_text",text:i}],S.status="completed")}for(let S of T)S.type==="function_call"&&(S.status="completed");return P("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:T,usage:I?{...this.buildResponsesUsage(I)}:this.buildResponsesUsage()}})}},C;return new ReadableStream({async start(I){C=I;try{let S=e.getReader(),M="";for(;;){let{done:U,value:$}=await S.read();if(U)break;M+=o.decode($,{stream:!0});let j=M.split(`
|
|
22
|
+
`);M=j.pop()||"";for(let G of j){let ge=G.trim();if(!ge||ge.startsWith("event:")||!ge.startsWith("data:"))continue;let K=ge.slice(5).trim();if(K==="[DONE]")continue;let W;try{W=JSON.parse(K)}catch{continue}if(W.type==="message_start"&&(a=W.message?.id||a,R()),W.type==="content_block_start"){let N=W.content_block;if(x=N?.type||null,N?.type==="tool_use"){u=N.id||"",p=N.name||"",d="",f=y++;let Q={id:u,type:"function_call",status:"in_progress",call_id:u,name:p,arguments:""};T.push(Q),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:f,item:Q}))}if(N?.type==="thinking"&&(g=N.thinking||"",!k)){k=!0,m=y++,h=`rs_${a}`;let Q={id:h,type:"reasoning",status:"in_progress",summary:[]};T.push(Q),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:m,item:Q}))}if(N?.type==="text"&&(i=N?.text||"",!_)){_=!0,c=y++,l=`${a}_msg`;let Q={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(Q),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:Q}))}}if(W.type==="content_block_delta"){let N=W.delta;if(N?.type==="text_delta"){if(!_){_=!0,c=y++,l=`${a}_msg`;let Q={id:l,type:"message",status:"in_progress",role:"assistant",content:[]};T.push(Q),C.enqueue(P("response.output_item.added",{type:"response.output_item.added",output_index:c,item:Q}))}i+=N.text||"",C.enqueue(P("response.output_text.delta",{type:"response.output_text.delta",item_id:l,output_index:c,content_index:0,delta:N.text||""}))}N?.type==="thinking_delta"&&(g+=N.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:N.thinking||""}))),N?.type==="input_json_delta"&&(d+=N.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:N.partial_json||""})))}if(W.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 N=T.find(Q=>Q.call_id===u);N&&(N.arguments=d,N.status="completed"),N&&O(f,N)}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 N=T.find(Q=>Q.type==="message");N&&(N.content=[{type:"output_text",text:i}],O(c,N))}if(x==="thinking"&&k){let N=T.find(Q=>Q.type==="reasoning");N&&(N.summary=[{type:"summary_text",text:g}],O(m,N))}x=null}if(W.type==="message_delta"){let N=F(W.usage);N&&C.enqueue(N)}if(W.type==="message_stop"){let N=F();N&&C.enqueue(N),C.enqueue(r.encode(`data: [DONE]
|
|
23
23
|
|
|
24
|
-
`))}}}E();let L=D();L&&C.enqueue(L),I="",C.close()}catch(x){C.error(x)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(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 Er,te,zn=P(()=>{"use strict";Er=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},te=new Er(100)});function lt(n,e){n&&ct.set(n,{...e,provider:n,capturedAt:Date.now()})}function Ut(n){let e=ct.get(n);return e?{...e}:void 0}function Bn(){return Array.from(ct.values()).map(n=>({...n}))}function Cu(){try{if(!(0,Se.existsSync)(Or))return;let n=JSON.parse((0,Se.readFileSync)(Or,"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;ct.set(t.provider,t)}}catch{}}function Hi(){try{if(ct.size===0)return;(0,Se.existsSync)(Ar)||(0,Se.mkdirSync)(Ar,{recursive:!0}),(0,Se.writeFileSync)(Or,JSON.stringify(Array.from(ct.values()),null,2),"utf-8")}catch{}}function ut(){Fi||(Fi=!0,Cu(),ji=setInterval(Hi,6e4),ji.unref?.(),process.on("exit",Hi))}var Se,Ir,zi,Ar,Or,ct,Fi,ji,Ke=P(()=>{"use strict";Se=require("fs"),Ir=require("path"),zi=require("@wengine-ai/claude-code-router-shared"),Ar=(0,Ir.join)(zi.HOME_DIR,"runtime"),Or=(0,Ir.join)(Ar,"quota-store.json"),ct=new Map,Fi=!1,ji=null});function Ce(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Ru.test(e)))return e}function Re(n){if(!n)return;if(typeof n=="object")return Ce(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=Ce(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return Ce(e.slice(o+t.length))}var Ru,dt=P(()=>{"use strict";Ru=/^[A-Za-z0-9_-]+$/});function Lu(){if(pt.size<=Bi)return;let n=[...pt.keys()].slice(0,pt.size-Bi);for(let e of n)pt.delete(e)}function $u(){if(ft.size<=Ji)return;let n=[...ft].slice(0,ft.size-Ji);for(let e of n)ft.delete(e)}function Nu(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 Uu(n,e){let t;try{t=(0,Ki.openSqliteDatabase)(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 Du(n,e){let t;try{t=await(0,Jn.readdir)(n)}catch{return null}for(let o of t)for(let r of e){let s=(0,ye.join)(n,o,`${r}.json`);if((0,Mr.existsSync)(s))try{let a=JSON.parse(await(0,Jn.readFile)(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Gi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=pt.get(e);if(t)return t;let o=async()=>{let r=Nu(e);if(r.length===0)return null;let s=(0,ye.join)(wu(),Pu),a=(0,ye.join)(s,Eu);if((0,Mr.existsSync)(a)){let i=Uu(a,r);if(i)return i}return Du((0,ye.join)(s,Au),r)};try{let r=await o();if(!r&&!ft.has(e)){ft.add(e),$u();for(let a=0;a<Ou&&!r;a++)await Mu(Iu),r=await o()}if(!r||!(0,ye.isAbsolute)(r))return null;let s=(0,ye.normalize)(r);return pt.set(e,s),Lu(),s}catch{return null}}var Mr,Jn,Wi,ye,Ki,wu,Pu,Eu,Au,Bi,Ji,Ou,Iu,pt,ft,Mu,Qi=P(()=>{"use strict";Mr=require("fs"),Jn=require("fs/promises"),Wi=require("os"),ye=require("path"),Ki=require("@wengine-ai/claude-code-router-shared"),wu=()=>process.env.CCR_ZCODE_DIR||(0,ye.join)((0,Wi.homedir)(),".zcode"),Pu="v2",Eu="tasks-index.sqlite",Au="sessions",Bi=500,Ji=500,Ou=3,Iu=50,pt=new Map,ft=new Set,Mu=n=>new Promise(e=>setTimeout(e,n))});function Zi(n){return typeof n=="string"&&n.length<=Fu}function ju(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Xi){let{value:t}=Wn(n,e);if(!Zi(t))continue;let o=Ce(t);if(o)return o}}function zu(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 Bu(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 Wn(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 Vi(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function Dt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Lr(n,e,t=!0){let o=Re(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Nr(n){return typeof n=="string"&&Hu.includes(n)}function Zu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Ge(n){if(Nr(n?.clientType))return n.clientType;let e=Bu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=zu(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(Wn(n,Kn.CCR_PROJECT_HEADER).present||Wn(n,"x-session-affinity").present)return"pi";if(Zu(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 Ur(n){return $r[n]}function qu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,Yi.randomUUID)();return n.__ccrRequestScopeId=e,e}function Ae(n,e={}){let t=Ge(n),o=Ur(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:qu(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,Vi(n,Kn.CCR_PROJECT_HEADER),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Xi)Vi(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function qi(){}var Yi,Kn,Xi,Fu,Hu,Ju,Wu,Ku,Gu,Qu,Vu,Yu,Xu,$r,mt=P(()=>{"use strict";Yi=require("node:crypto"),Kn=require("@wengine-ai/claude-code-router-shared");dt();Xi=["x-session-affinity","x-session-id","x-litellm-session-id"],Fu=256;Hu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Ju={type:"claude-code",createContext(n){return Lr(n,"claude-code")}},Wu={type:"zcode",createContext(n){return Lr(n,"zcode")}},Ku={type:"pi",createContext(n){let e=Wn(n,Kn.CCR_PROJECT_HEADER),t=ju(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||Re(n?.body?.metadata?.user_id),o=Zi(t)?t:void 0;return{...Dt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Gu={type:"qwen-code",createContext(n){return Lr(n,"qwen-code")}},Qu={type:"opencode",createContext(){return Dt("opencode")}},Vu={type:"codex",createContext(){return Dt("codex")}},Yu={type:"api",createContext(){return Dt("api")}},Xu={type:"unknown",createContext(){return Dt("unknown")}},$r={"claude-code":Ju,zcode:Wu,pi:Ku,"qwen-code":Gu,opencode:Qu,codex:Vu,api:Yu,unknown:Xu}});function ce(n,e,t,o){let r=Dr(e,t);if(r.code==="model_unhealthy"){let i=Z(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=ra[r.code]||502;throw new se(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function Vn(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 Ht(n){let e=Vn(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 nd(n,e){if(!e||!n)return null;let t=Vn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=Ht(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=Vn(r);if(a&&t.includes(a))return s}return null}function od(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function Gn(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 Dr(n,e){let t=Gn(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(!z().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=Ut(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 Z(n,e,t,o,r,s,a){let i=Gn(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=rt(),f=d.getPromotion(c,l,o,e);if(f){let g=Gn(f);if(g){let h=Ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=rt(),f=d.getPromotion(c,l,o,e);if(f){let g=Gn(f);if(g){let h=Ft(e,g.providerName,g.routeModel);if(h)return`${h.provider.name},${h.model}`}d.clear(c,l,o)}}if(!t&&!z().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=Ut(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 re(n,e,t,o,r,s){let a=[t?.[n],o?.[n]];for(let i of a)if(!(!Array.isArray(i)||i.length===0))for(let c of i){let l=Z(c,e,!1,n,void 0,void 0,s);if(l)return l}return null}function rd(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 zt(n){let e=Vn(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 sa(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,od(e))}function ia(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function sd(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??c??6e4,g=sa(e,r,d),h=n.modelFamily,m=ia(d,t,l),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||g>m)&&t.extendedContext){let k=Z(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?re("extendedContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let S=ce(n,t.extendedContext,o,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext",isFallback:!1}}n.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(g>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?Z(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?re("longContext",o,t.fallback,a,h,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${g}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let S=ce(n,t.longContext,o,"longContext");if(S)return{model:S,scenarioType:"longContext",isFallback:!1}}n.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(n.body.tools)&&n.body.tools.some(k=>k.type?.startsWith("web_search"))&&t.webSearch){let k=Z(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let T=i?re("webSearch",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,scenarioType:"webSearch",isFallback:!0};if(u){let S=ce(n,t.webSearch,o,"webSearch");if(S)return{model:S,scenarioType:"webSearch",isFallback:!1}}n.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(n.body.thinking?.type==="enabled"&&t.think){let k=Z(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let T=i?re("think",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,scenarioType:"think",isFallback:!0};if(u){let S=ce(n,t.think,o,"think");if(S)return{model:S,scenarioType:"think",isFallback:!1}}n.log.warn("Family: think model unavailable (fail pool), skipping")}if(t.default){let k=Z(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let T=i?re("default",o,t.fallback,a,h,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,scenarioType:"default",isFallback:!0};if(u){let S=ce(n,t.default,o,"default");if(S)return{model:S,scenarioType:"default",isFallback:!1}}n.log.warn("Family: default model unavailable (fail pool), skipping")}return null}function ud(){if(Qe.size<=ea)return;let n=[...Qe.keys()].slice(0,Qe.size-ea);for(let e of n)Qe.delete(e)}function dd(){if(gt.size<=ta)return;let n=[...gt].slice(0,gt.size-ta);for(let e of n)gt.delete(e)}var oa,Qn,Yn,ht,de,ra,se,_e,jt,td,id,Bt,Qe,ea,gt,ta,ad,cd,ld,na,Fr,Ve=P(()=>{"use strict";oa=require("tiktoken");zn();Qn=require("fs/promises"),Yn=require("fs/promises"),ht=require("path"),de=require("@wengine-ai/claude-code-router-shared");ue();Ke();Ln();jn();dt();Qi();mt();ra={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},se=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||ra[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};_e=(0,oa.get_encoding)("cl100k_base"),jt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=_e.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=_e.encode(s.text).length;else if(s.type==="tool_use")o+=_e.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+=_e.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=_e.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=_e.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=_e.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=_e.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=_e.encode(r.name+r.description).length),r.input_schema&&(o+=_e.encode(JSON.stringify(r.input_schema)).length)}),o},td=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 se(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Fr(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Gi(n.sessionId);s&&(0,de.isZcodeProjectTakeoverActive)(s)&&(r=(0,de.getClaudeProjectId)(s))}if(r){n.projectId=r;let s=(0,ht.join)(de.HOME_DIR,r,"config.json");if(!t&&n.sessionId){let a=(0,ht.join)(de.HOME_DIR,r,`${n.sessionId}.json`);try{let i=JSON.parse(await(0,Qn.readFile)(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await(0,Qn.readFile)(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||(0,de.getClaudeProjectId)(a.projectPath)!==o))throw new se(`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 se)throw a;if(t&&a?.code==="ENOENT")throw new se(`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 se(`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})}}}};id=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let C=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);C&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${C[1]}</CCR-SUBAGENT-MODEL>`,""),d=C[1])}let f=typeof n.body?.model=="string"?n.body.model:"",g=f.indexOf(",")>0,m=(g?f.slice(f.indexOf(",")+1).trim():f).replace(/\[1m\]$/i,"").toLowerCase(),y,b;if(!s&&m)for(let C of a){if(C?.enabled===!1||!Array.isArray(C?.models))continue;let O=C.models.find(x=>typeof x=="string"&&x.toLowerCase()===m);if(O){y=C,b=O;break}}let{family:_,extended:k,isCcrAlias:T}=Ht(n.body.model),S=i?.families?.[_||""];if(S&&i?.enableFamilyRouting&&!y){n.log.info(`Using model family routing for: ${_}${k?" (1M)":""}`),n.modelFamily=_,n.familyFallback=S.fallback;let C=sd(n,e,S,a,o,k,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(C)return{model:C.model,scenarioType:C.scenarioType}}if(g&&y&&b){let C=`${y.name},${b}`;n.body.model!==C&&(n.log.info(`Normalizing exact provider model ${n.body.model} to ${C}`),n.body.model=C)}if(n.body.model.includes(",")&&!s){let C=Z(n.body.model,a,!1,"default",c,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let O=c?re("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:nd(n.body.model,i?.models);if(v){let C=Z(v,a,!1,"modelMapping",c,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${v}`),{model:C,scenarioType:"modelMapping"};let O=c?re("modelMapping",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"modelMapping"};if(s){let x=ce(n,v,a,"modelMapping");if(x)return{model:x,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${v} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let w=n.clientContext,R=sa(e,o,w),E=ia(w,void 0,i?.extendedContextThreshold);if(R>E&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${R}, estimated: ${e}, threshold: ${E}`);let C=Z(i.extendedContext,a,!1,"extendedContext",c,p,s);if(C)return{model:C,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let O=c?re("extendedContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"extendedContext"};if(s){let x=ce(n,i.extendedContext,a,"extendedContext");if(x)return{model:x,scenarioType:"extendedContext"}}}let M=w?.longContextThreshold??i?.longContextThreshold??6e4;if(R>M&&i?.longContext){n.log.info(`Using long context model due to token count: ${R}, estimated: ${e}, threshold: ${M}`);let C=Z(i.longContext,a,!1,"longContext",c,p,s);if(C)return{model:C,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let O=c?re("longContext",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"longContext"};if(s){let x=ce(n,i.longContext,a,"longContext");if(x)return{model:x,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let C=Z(i.background,a,!1,"background",c,p,s);if(C)return{model:C,scenarioType:"background"};let O=c?re("background",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"background"};if(s){let x=ce(n,i.background,a,"background");if(x)return{model:x,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(C=>C.type?.startsWith("web_search"))&&i?.webSearch){let C=Z(i.webSearch,a,!1,"webSearch",c,p,s);if(C)return{model:C,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let O=c?re("webSearch",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"webSearch"};if(s){let x=ce(n,i.webSearch,a,"webSearch");if(x)return{model:x,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let C=Z(i.think,a,!1,"think",c,p,s);if(C)return{model:C,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let O=c?re("think",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"think"};if(s){let x=ce(n,i.think,a,"think");if(x)return{model:x,scenarioType:"think"}}}if(i?.default){let C=Z(i.default,a,!1,"default",c,p,s);if(C)return{model:C,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let O=c?re("default",a,void 0,u,void 0,s):null;if(O)return{model:O,scenarioType:"default"};let x=Z(i.default,a,!0,"default",c,p,s);if(x)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:x,scenarioType:"default"}}if(s){let C=ce(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Bt=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)&&Ae(n,o.getAll());let s=await td(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??te.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(0,Qn.readFile)(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=jt(p,d,f),n.tokenCount=b;let _,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!(0,ht.isAbsolute)(k)||!/\.(c|m)?js$/i.test(k))throw new Error(`CUSTOM_ROUTER_PATH must be an absolute .js/.cjs/.mjs path, got: ${String(k).slice(0,120)}`);let w=await import(k),R=typeof w=="function"?w:w?.default;if(typeof R!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await R(n,o.getAll(),{event:r})}catch(w){n.log.error(`failed to load custom router: ${w.message}`)}if(_)n.scenarioType="default";else{let w=await id(n,b,o,u,s,!!s);_=w.model,n.scenarioType=w.scenarioType}let{family:T}=Ht(n.originalModel||n.body.model),S=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[S?.image,a?.image].filter((w,R,E)=>!!w&&E.indexOf(w)===R);if(v.length>0&&rd(n)&&!zt(_))if(v.includes(_))n.scenarioType="image";else{let w=v.map(R=>Z(R,c,!1,"image",i,!l,l)).find(R=>!!R);if(w)n.log.info(`Using image model fallback for ${_}`),_=w,n.scenarioType="image";else{let R=i?re("image",c,S?.fallback,n.fallbackConfig,T||void 0,l):null;if(R)n.log.info(`Using image fallback model: ${R}`),_=R,n.scenarioType="image";else if(l){let E=ce(n,v[0],c,"image");E&&(_=E,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let w=n.scenarioType||"default",R=[...(n.familyFallback||{})[w]||[],...(n.fallbackConfig||{})[w]||[]];_=Ui(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:R,resolve:E=>Z(E,c,!1,w,i,!l,l),log:E=>n.log.info(E)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(h){if(h instanceof se)throw h;if(n.log.error(`Error in router middleware: ${h.message}`),l){let m=n.sessionId||n.clientContext?.stableSessionId;throw new se(`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"}},Qe=new Map,ea=1e3,gt=new Set,ta=1e3,ad=3,cd=50,ld=n=>new Promise(e=>setTimeout(e,n));na=async n=>{let e=await(0,Yn.opendir)(de.CLAUDE_PROJECTS_DIR),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=(0,ht.join)(de.CLAUDE_PROJECTS_DIR,s,`${n}.jsonl`);try{return(await(0,Yn.stat)(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Fr=async n=>{let e=Ce(n);if(!e)return null;if(Qe.has(e))return Qe.get(e)||null;try{let t=await na(e);if(!t&&!gt.has(e)){gt.add(e),dd();for(let o=0;o<ad&&!t;o++)await ld(cd),t=await na(e)}return t?(Qe.set(e,t),ud(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function Jt(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(`
|
|
24
|
+
`))}}}R();let L=F();L&&C.enqueue(L),M="",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 Or,te,Bn=w(()=>{"use strict";Or=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}values(){return Array.from(this.cache.values())}delete(e){return this.cache.delete(e)}},te=new Or(100)});function lt(n,e){n&&ct.set(n,{...e,provider:n,capturedAt:Date.now()})}function Ut(n){let e=ct.get(n);return e?{...e}:void 0}function Jn(){return Array.from(ct.values()).map(n=>({...n}))}function Eu(){try{if(!(0,Se.existsSync)(Mr))return;let n=JSON.parse((0,Se.readFileSync)(Mr,"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;ct.set(t.provider,t)}}catch{}}function Wi(){try{if(ct.size===0)return;(0,Se.existsSync)(Ir)||(0,Se.mkdirSync)(Ir,{recursive:!0}),(0,Se.writeFileSync)(Mr,JSON.stringify(Array.from(ct.values()),null,2),"utf-8")}catch{}}function ut(){Bi||(Bi=!0,Eu(),Ji=setInterval(Wi,6e4),Ji.unref?.(),process.on("exit",Wi))}var Se,Lr,Ki,Ir,Mr,ct,Bi,Ji,Ke=w(()=>{"use strict";Se=require("fs"),Lr=require("path"),Ki=require("@wengine-ai/claude-code-router-shared"),Ir=(0,Lr.join)(Ki.HOME_DIR,"runtime"),Mr=(0,Lr.join)(Ir,"quota-store.json"),ct=new Map,Bi=!1,Ji=null});function Ce(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Au.test(e)))return e}function Re(n){if(!n)return;if(typeof n=="object")return Ce(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=Ce(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return Ce(e.slice(o+t.length))}var Au,dt=w(()=>{"use strict";Au=/^[A-Za-z0-9_-]+$/});function Du(){if(pt.size<=Gi)return;let n=[...pt.keys()].slice(0,pt.size-Gi);for(let e of n)pt.delete(e)}function Fu(){if(ft.size<=Qi)return;let n=[...ft].slice(0,ft.size-Qi);for(let e of n)ft.delete(e)}function ju(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 Hu(n,e){let t;try{t=(0,Yi.openSqliteDatabase)(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 zu(n,e){let t;try{t=await(0,Wn.readdir)(n)}catch{return null}for(let o of t)for(let r of e){let s=(0,ye.join)(n,o,`${r}.json`);if((0,$r.existsSync)(s))try{let a=JSON.parse(await(0,Wn.readFile)(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Xi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=pt.get(e);if(t)return t;let o=async()=>{let r=ju(e);if(r.length===0)return null;let s=(0,ye.join)(Ou(),Iu),a=(0,ye.join)(s,Mu);if((0,$r.existsSync)(a)){let i=Hu(a,r);if(i)return i}return zu((0,ye.join)(s,Lu),r)};try{let r=await o();if(!r&&!ft.has(e)){ft.add(e),Fu();for(let a=0;a<$u&&!r;a++)await Uu(Nu),r=await o()}if(!r||!(0,ye.isAbsolute)(r))return null;let s=(0,ye.normalize)(r);return pt.set(e,s),Du(),s}catch{return null}}var $r,Wn,Vi,ye,Yi,Ou,Iu,Mu,Lu,Gi,Qi,$u,Nu,pt,ft,Uu,Zi=w(()=>{"use strict";$r=require("fs"),Wn=require("fs/promises"),Vi=require("os"),ye=require("path"),Yi=require("@wengine-ai/claude-code-router-shared"),Ou=()=>process.env.CCR_ZCODE_DIR||(0,ye.join)((0,Vi.homedir)(),".zcode"),Iu="v2",Mu="tasks-index.sqlite",Lu="sessions",Gi=500,Qi=500,$u=3,Nu=50,pt=new Map,ft=new Set,Uu=n=>new Promise(e=>setTimeout(e,n))});function na(n){return typeof n=="string"&&n.length<=Bu}function Ju(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of ta){let{value:t}=Kn(n,e);if(!na(t))continue;let o=Ce(t);if(o)return o}}function Ku(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 Gu(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 Kn(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 qi(n,e){if(!(!n?.headers||typeof n.headers!="object"))for(let t of Object.keys(n.headers))t.toLowerCase()===e&&delete n.headers[t]}function Dt(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Nr(n,e,t=!0){let o=Re(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Dr(n){return typeof n=="string"&&Wu.includes(n)}function nd(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Ge(n){if(Dr(n?.clientType))return n.clientType;let e=Gu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Ku(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(Kn(n,Gn.CCR_PROJECT_HEADER).present||Kn(n,"x-session-affinity").present)return"pi";if(nd(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 Fr(n){return Ur[n]}function od(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,ea.randomUUID)();return n.__ccrRequestScopeId=e,e}function Ae(n,e={}){let t=Ge(n),o=Fr(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:od(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,qi(n,Gn.CCR_PROJECT_HEADER),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of ta)qi(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function oa(){}var ea,Gn,ta,Bu,Wu,Qu,Vu,Yu,Xu,Zu,qu,ed,td,Ur,mt=w(()=>{"use strict";ea=require("node:crypto"),Gn=require("@wengine-ai/claude-code-router-shared");dt();ta=["x-session-affinity","x-session-id","x-litellm-session-id"],Bu=256;Wu=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Qu={type:"claude-code",createContext(n){return Nr(n,"claude-code")}},Vu={type:"zcode",createContext(n){return Nr(n,"zcode")}},Yu={type:"pi",createContext(n){let e=Kn(n,Gn.CCR_PROJECT_HEADER),t=Ju(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||Re(n?.body?.metadata?.user_id),o=na(t)?t:void 0;return{...Dt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Xu={type:"qwen-code",createContext(n){return Nr(n,"qwen-code")}},Zu={type:"opencode",createContext(){return Dt("opencode")}},qu={type:"codex",createContext(){return Dt("codex")}},ed={type:"api",createContext(){return Dt("api")}},td={type:"unknown",createContext(){return Dt("unknown")}},Ur={"claude-code":Qu,zcode:Vu,pi:Yu,"qwen-code":Xu,opencode:Zu,codex:qu,api:ed,unknown:td}});function ce(n,e,t,o){let r=jr(e,t);if(r.code==="model_unhealthy"){let i=Z(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=ca[r.code]||502;throw new se(`Project routing error (${o}): ${r.reason}. Project-level Router target: "${e}". Session: "${s||"unknown"}".`,{sessionId:s,configuredTarget:e,code:r.code,statusCode:a})}function Yn(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 Ht(n){let e=Yn(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 id(n,e){if(!e||!n)return null;let t=Yn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=Ht(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=Yn(r);if(a&&t.includes(a))return s}return null}function ad(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function Qn(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 jr(n,e){let t=Qn(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(!z().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=Ut(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 Z(n,e,t,o,r,s,a){let i=Qn(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=rt(),f=d.getPromotion(l,c,o,e);if(f){let g=Qn(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=rt(),f=d.getPromotion(l,c,o,e);if(f){let g=Qn(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&&!z().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=Ut(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 re(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=Z(l,e,!1,n,void 0,void 0,s);if(c)return c}return null}function cd(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 zt(n){let e=Yn(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 la(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,ad(e))}function ua(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function ld(n,e,t,o,r,s,a,i,l,c,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??l??6e4,g=la(e,r,d),h=n.modelFamily,m=ua(d,t,c),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||g>m)&&t.extendedContext){let k=Z(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let v=i?re("extendedContext",o,t.fallback,a,h,u):null;if(v)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${g}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:v,scenarioType:"extendedContext",isFallback:!0};if(u){let x=ce(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?Z(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${g}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let v=i?re("longContext",o,t.fallback,a,h,u):null;if(v)return n.log.info(`Family: using long context fallback model, tokens: ${g}, estimated: ${e}`),{model:v,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let x=ce(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=Z(t.webSearch,o,!1,"webSearch",i,p,u);if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let v=i?re("webSearch",o,t.fallback,a,h,u):null;if(v)return n.log.info("Family: using webSearch fallback model"),{model:v,scenarioType:"webSearch",isFallback:!0};if(u){let x=ce(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=Z(t.think,o,!1,"think",i,p,u);if(k)return{model:k,scenarioType:"think",isFallback:!1};let v=i?re("think",o,t.fallback,a,h,u):null;if(v)return n.log.info("Family: using think fallback model"),{model:v,scenarioType:"think",isFallback:!0};if(u){let x=ce(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=Z(t.default,o,!1,"default",i,p,u);if(k)return{model:k,scenarioType:"default",isFallback:!1};let v=i?re("default",o,t.fallback,a,h,u):null;if(v)return n.log.info("Family: using default fallback model"),{model:v,scenarioType:"default",isFallback:!0};if(u){let x=ce(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 md(){if(Qe.size<=ra)return;let n=[...Qe.keys()].slice(0,Qe.size-ra);for(let e of n)Qe.delete(e)}function gd(){if(gt.size<=sa)return;let n=[...gt].slice(0,gt.size-sa);for(let e of n)gt.delete(e)}var aa,Vn,Xn,ht,de,ca,se,_e,jt,sd,ud,Bt,Qe,ra,gt,sa,dd,pd,fd,ia,Hr,Ve=w(()=>{"use strict";aa=require("tiktoken");Bn();Vn=require("fs/promises"),Xn=require("fs/promises"),ht=require("path"),de=require("@wengine-ai/claude-code-router-shared");ue();Ke();$n();Hn();dt();Zi();mt();ca={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},se=class extends Error{statusCode;code;type;sessionId;configuredTarget;constructor(e,t){super(e),this.name="ProjectRoutingError",this.statusCode=t?.statusCode||ca[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};_e=(0,aa.get_encoding)("cl100k_base"),jt=(n,e,t)=>{let o=0;return Array.isArray(n)&&n.forEach(r=>{typeof r.content=="string"?o+=_e.encode(r.content).length:Array.isArray(r.content)&&r.content.forEach(s=>{if(s.type==="text")o+=_e.encode(s.text).length;else if(s.type==="tool_use")o+=_e.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+=_e.encode(i?.type==="text"?String(i.text??""):JSON.stringify(i)).length);else o+=_e.encode(typeof a=="string"?a:JSON.stringify(a)).length}})}),typeof e=="string"?o+=_e.encode(e).length:Array.isArray(e)&&e.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?o+=_e.encode(r.text).length:Array.isArray(r.text)&&r.text.forEach(s=>{o+=_e.encode(s||"").length}))}),t&&t.forEach(r=>{r.description&&(o+=_e.encode(r.name+r.description).length),r.input_schema&&(o+=_e.encode(JSON.stringify(r.input_schema)).length)}),o},sd=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 se(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await Hr(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Xi(n.sessionId);s&&(0,de.isZcodeProjectTakeoverActive)(s)&&(r=(0,de.getClaudeProjectId)(s))}if(r){n.projectId=r;let s=(0,ht.join)(de.HOME_DIR,r,"config.json");if(!t&&n.sessionId){let a=(0,ht.join)(de.HOME_DIR,r,`${n.sessionId}.json`);try{let i=JSON.parse(await(0,Vn.readFile)(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch(i){}}try{let a=JSON.parse(await(0,Vn.readFile)(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||(0,de.getClaudeProjectId)(a.projectPath)!==o))throw new se(`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 se)throw a;if(t&&a?.code==="ENOENT")throw new se(`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 se(`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})}}}};ud=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 I=C.models.find(S=>typeof S=="string"&&S.toLowerCase()===m);if(I){y=C,b=I;break}}let{family:_,extended:k,isCcrAlias:v}=Ht(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=ld(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=Z(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 I=l?re("default",a,void 0,u,void 0,s):null;if(I)return n.log.info(`Using fallback for explicit model: ${I}`),{model:I,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let T=v&&!i?.enableFamilyRouting?null:id(n.body.model,i?.models);if(T){let C=Z(T,a,!1,"modelMapping",l,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${T}`),{model:C,scenarioType:"modelMapping"};let I=l?re("modelMapping",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"modelMapping"};if(s){let S=ce(n,T,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${T} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let P=n.clientContext,A=la(e,o,P),R=ua(P,void 0,i?.extendedContextThreshold);if(A>R&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${A}, estimated: ${e}, threshold: ${R}`);let C=Z(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 I=l?re("extendedContext",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"extendedContext"};if(s){let S=ce(n,i.extendedContext,a,"extendedContext");if(S)return{model:S,scenarioType:"extendedContext"}}}let O=P?.longContextThreshold??i?.longContextThreshold??6e4;if(A>O&&i?.longContext){n.log.info(`Using long context model due to token count: ${A}, estimated: ${e}, threshold: ${O}`);let C=Z(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 I=l?re("longContext",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"longContext"};if(s){let S=ce(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=Z(i.background,a,!1,"background",l,p,s);if(C)return{model:C,scenarioType:"background"};let I=l?re("background",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"background"};if(s){let S=ce(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=Z(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 I=l?re("webSearch",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"webSearch"};if(s){let S=ce(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=Z(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 I=l?re("think",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"think"};if(s){let S=ce(n,i.think,a,"think");if(S)return{model:S,scenarioType:"think"}}}if(i?.default){let C=Z(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 I=l?re("default",a,void 0,u,void 0,s):null;if(I)return{model:I,scenarioType:"default"};let S=Z(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=ce(n,i?.default||n.body.model,a,"default");if(C)return{model:C,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Bt=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)&&Ae(n,o.getAll());let s=await sd(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??te.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(0,Vn.readFile)(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=jt(p,d,f),n.tokenCount=b;let _,k=c?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{if(typeof k!="string"||!(0,ht.isAbsolute)(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),A=typeof P=="function"?P:P?.default;if(typeof A!="function")throw new Error(`CUSTOM_ROUTER_PATH module does not export a function: ${k}`);_=await A(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 ud(n,b,o,u,s,!!s);_=P.model,n.scenarioType=P.scenarioType}let{family:v}=Ht(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&v?a.families?.[v]:void 0,T=[x?.image,a?.image].filter((P,A,R)=>!!P&&R.indexOf(P)===A);if(T.length>0&&cd(n)&&!zt(_))if(T.includes(_))n.scenarioType="image";else{let P=T.map(A=>Z(A,l,!1,"image",i,!c,c)).find(A=>!!A);if(P)n.log.info(`Using image model fallback for ${_}`),_=P,n.scenarioType="image";else{let A=i?re("image",l,x?.fallback,n.fallbackConfig,v||void 0,c):null;if(A)n.log.info(`Using image fallback model: ${A}`),_=A,n.scenarioType="image";else if(c){let R=ce(n,T[0],l,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${T.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let P=n.scenarioType||"default",A=[...(n.familyFallback||{})[P]||[],...(n.fallbackConfig||{})[P]||[]];_=Hi(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:A,resolve:R=>Z(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 se)throw h;if(n.log.error(`Error in router middleware: ${h.message}`),c){let m=n.sessionId||n.clientContext?.stableSessionId;throw new se(`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"}},Qe=new Map,ra=1e3,gt=new Set,sa=1e3,dd=3,pd=50,fd=n=>new Promise(e=>setTimeout(e,n));ia=async n=>{let e=await(0,Xn.opendir)(de.CLAUDE_PROJECTS_DIR),t=[];for await(let s of e)s.isDirectory()&&t.push(s.name);let o=t.map(async s=>{let a=(0,ht.join)(de.CLAUDE_PROJECTS_DIR,s,`${n}.jsonl`);try{return(await(0,Xn.stat)(a)).isFile()?s:null}catch{return null}}),r=await Promise.all(o);for(let s of r)if(s)return s;return null},Hr=async n=>{let e=Ce(n);if(!e)return null;if(Qe.has(e))return Qe.get(e)||null;try{let t=await ia(e);if(!t&&!gt.has(e)){gt.add(e),gd();for(let o=0;o<dd&&!t;o++)await fd(pd),t=await ia(e)}return t?(Qe.set(e,t),md(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function Jt(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
25
|
`):"";r&&e.push({role:"assistant",content:[{type:"text",text:`[reasoning]
|
|
26
|
-
${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
|
|
27
|
-
`).some(g=>g.startsWith("data:"))))break}if(
|
|
28
|
-
`).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=
|
|
29
|
-
`):""}async function aa(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})),gd(l,a?.req);for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];!i?.suppressDebugLog&&Pn(o.configService)&&ui(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>fi(c,n,{...e,headers:JSON.parse(JSON.stringify(l)),httpsProxy:i?void 0:he(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await Be(i,0,void 0,yt(n),vi(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!ot(a.req,i,t).refreshUsed){ot(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(g){throw i?await Be(i,u.status,void 0,yt(n)):g}if(i){let g=await Be(i,u.status,d,yt(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=V(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||Xn(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(Nt(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 Be(i,u.status,g,yt(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 Be(i,u.status,g,yt(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let b=Xn(g),_=V(`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 Be(i,u.status,void 0,yt(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=V(`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&&Pn(o.configService)){let f=await u.clone().text();di(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function fa(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 at().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function ma(n,e,t,o){n.ok||e.code(n.status);let r=Di(n);if(!r){let s=await xe(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 Ee(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&&Pn(o.configService)){let[s,a]=n.body.tee(),i=li(o.configService);return pi(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return H(n)}function Xn(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 yd(n){try{return new URL(n),!0}catch{return!1}}var pd,ga,Zn=P(()=>{"use strict";mi();Rn();_i();bi();xi();It();pr();ue();We();Ln();jn();Pr();oe();Ve();ae();pd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;ga=async n=>{n.get("/",async()=>({message:"LLMs API",version:Mn})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:z().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)=>ca(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 V("Provider name is required",400,"invalid_request");if(!s||!yd(s))throw V("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw V("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw V("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw V(`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 V("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 V("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 V("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 V("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ye,jr=P(()=>{"use strict";Ye=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 Oe,qn,ha,_d,ya,_t=P(()=>{"use strict";Oe=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",qn=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,ha=["low","medium","high"],_d={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"},ya=n=>{if(typeof n=="string")return _d[n.trim().toLowerCase()]}});var Hr,_a=P(()=>{Hr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function bd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ba(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let g=t[f],h=g?.text??JSON.stringify(g),m=d.get(h);if(m===void 0){d.set(h,f);continue}!t[m]?.cache_control&&g?.cache_control&&(t[m]=g),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let g=f.content;try{typeof f.content=="string"&&(g=JSON.parse(f.content))}catch{}g!=null&&typeof g!="object"&&typeof g!="string"&&(g=String(g));let h={type:"tool_result",tool_use_id:f.tool_call_id,content:g};f.cache_control&&(h.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(h):s.push({role:"user",content:[h]})}else if(f.role==="user"){let g=[];typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?g.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):g.push(m)});let h=s[s.length-1];h&&h.role==="user"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"user",content:g.length>0?g:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let g=[];f.content&&(typeof f.content=="string"?g.push({type:"text",text:f.content}):Array.isArray(f.content)&&g.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}g.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&g.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let h=s[s.length-1];h&&h.role==="assistant"&&Array.isArray(h.content)?h.content.push(...g):s.push({role:"assistant",content:g.length>0?g:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(g=>g?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},c=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let g=f.find(h=>h?.cache_control);if(g?.cache_control)return g.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},l=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(h=>h?.cache_control))return!1;let g=d.content.find(h=>h&&typeof h=="object"&&!h.cache_control);return g?(g.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,g=c(),h=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||h.push(m);for(let m of h){if(d<=0)break;l(f[m],g)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||qn(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:Oe(d);ha.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(`
|
|
26
|
+
${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 pa(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),lr(n);let s=kd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&Jt(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&hd.test(r.model)&&await Bt(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 V(`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&&Jt(r);let c={req:n,isCodexOnMessagesEndpoint:l,responseTargetFormat:ga(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await ma(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let v=JSON.stringify(k.content??"");y.has(v)||(y.add(v),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await ha(u,p,i,t,d,o,c);try{i?.baseUrl&&f?.headers&&$t(a,i.baseUrl,f.headers)}catch{}let g=await ya(u,f,i,o,d,c);g=await fa(r,g,i.name||a);let h=_a(g,e,r,t);try{let m=r.model||n.originalModel;a&&m&&z().recordSuccess(a,m)}catch{}return h}catch(c){if(c instanceof se)throw c;if(!ur(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await pa(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await yd(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function fa(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(`
|
|
27
|
+
`).some(g=>g.startsWith("data:"))))break}if(l+=a.decode(),i.length===0)throw s.releaseLock(),V(`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 V(`Provider ${t} returned error in SSE stream: ${d}`,400,"provider_response_error")}if(l.split(`
|
|
28
|
+
`).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=l.length<500?l:l.slice(0,500);throw V(`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 ki(u);if(p.verdict==="empty")throw V(`Provider ${t} returned an empty answer (200 with no content blocks)`,400,"provider_response_error");return new Response(vi(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function yd(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=z(),u=n.provider||"",p=n.body.model||"",d=new Set,f=r?.statusCode===429||r?.isRateLimit===!0||r?.rawBody&&Zn(r.rawBody)||r?.message&&Zn(r.message);if(u&&p&&(f?(c.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):c.recordFailure(u,p,r?.message),d.add(`${u},${p}`),t.recordUsage?.({provider:u,model:p,originalModel:n.originalModel||p,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let h=b=>{let[_,...k]=b.split(","),v=_?.trim(),x=k.join(",").trim();return!v||!x?null:{provider:v,model:x,key:`${v},${x}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(v=>v.type==="image"||v.type==="image_url"||Array.isArray(v?.content)&&v.content.some(x=>x.type==="image"||x.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=h(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let v=t.providerService.getProviders(),x=Ft(v,k.provider,k.model);if(!x){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let T=x.provider.name,P=x.model;if(!c.isAvailable(T,P,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let A=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(A&&ot(n,A,{name:T}).terminalError)continue;let R;for(let O=1;O<=2;O++)try{n.log.info(`Trying fallback model: ${T},${P}${O>1?" (retry)":""}`);let F={...n.body};F.model=P;let C={...n,provider:T,body:F},I=x.provider,S={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:ga(C,o,C.codexDetected===!0)},{requestBody:M,config:L,bypass:U}=await ma(F,I,o,n.headers,S),$=await ha(M,L,I,t,U,o,S);try{I?.baseUrl&&$?.headers&&$t(T,I.baseUrl,$.headers)}catch{}let j=await ya(M,$,I,o,U,S);return j=await fa(F,j,T),n.log.info(`Fallback model ${T},${P} succeeded`),c.recordSuccess(T,P),u&&p&&!n.strictProjectRouting&&(rt().promote(u,p,s,T,P),n.log.info(`Promoted fallback model ${T},${P} for ${u},${p}:${s}`),f?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(c.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=T,n.body=F,ji(n,`${T},${P}`),_a(j,e,F,t)}catch(F){if(R=F,ur(n,A,F,{name:T}))break;if(O===1){n.log.warn(`Fallback model ${T},${P} failed, retrying once: ${F.message}`);continue}}c.recordFailure(T,P,R?.message),n.log.warn(`Fallback model ${T},${P} failed after retry: ${R?.message}`),t.recordUsage?.({provider:T,model:P,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:R?.message||String(R),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function ma(n,e,t,o,r){if(typeof e.apiKey=="string"&&e.apiKey.startsWith("ccr-managed-")&&!r.pluginRegistry.getManagedRuntimeFor(e))throw V("Provider plugin missing or disabled; install and enable its provider plugin.",503,"plugin_missing");let s=r.pluginRegistry.getManagedRuntimeFor(e);if(s){let u=ot(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=_d(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 _d(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 bd(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 ga(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function kd(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 ha(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>da(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):da(n,e,t,o,r,s,a)}function yt(n){let e=n?.request?.systemInstruction?.parts??n?.systemInstruction?.parts;return Array.isArray(e)?e.map(t=>typeof t?.text=="string"?t.text:"").join(`
|
|
29
|
+
`):""}async function da(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})),bd(c,a?.req);for(let d in c)(c[d]==="undefined"||["authorization","Authorization"].includes(d)&&c[d]?.includes("undefined"))&&delete c[d];!i?.suppressDebugLog&&En(o.configService)&&mi(o.log,a.req.id,{url:String(l),headers:c,body:n});let u,p=()=>yi(l,n,{...e,headers:JSON.parse(JSON.stringify(c)),httpsProxy:i?void 0:he(o.configService,t)},a,i?void 0:o.log);try{u=await p()}catch(d){throw i?await Be(i,0,void 0,yt(n),Ri(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!ot(a.req,i,t).refreshUsed){ot(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 Be(i,u.status,void 0,yt(n)):g}if(i){let g=await Be(i,u.status,d,yt(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=V(`Error from provider(${t.name},${n.model}: ${u.status}): ${d}`,u.status,"provider_response_error");throw f.isRateLimit=u.status===429||Zn(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(Nt(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 Be(i,u.status,g,yt(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 Be(i,u.status,g,yt(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${g}`);let b=Zn(g),_=V(`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 Be(i,u.status,void 0,yt(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=V(`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&&En(o.configService)){let f=await u.clone().text();gi(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function ya(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 at().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function _a(n,e,t,o){n.ok||e.code(n.status);let r=zi(n);if(!r){let s=await xe(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 Ee(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&&En(o.configService)){let[s,a]=n.body.tee(),i=fi(o.configService);return hi(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return H(n)}function Zn(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 vd(n){try{return new URL(n),!0}catch{return!1}}var hd,ba,qn=w(()=>{"use strict";_i();wn();Ti();xi();wi();It();mr();ue();We();$n();Hn();Ar();oe();Ve();ae();hd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;ba=async n=>{n.get("/",async()=>({message:"LLMs API",version:Ln})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:z().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)=>pa(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 V("Provider name is required",400,"invalid_request");if(!s||!vd(s))throw V("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw V("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw V("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw V(`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 V("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 V("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 V("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 V("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ye,zr=w(()=>{"use strict";Ye=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 Oe,eo,ka,Td,va,_t=w(()=>{"use strict";Oe=n=>n>0?n<=1024?"low":n<=8192?"medium":n<=16384?"high":"max":"none",eo=n=>n==="none"?0:n==="low"?1024:n==="medium"?8192:n==="high"?16384:32768,ka=["low","medium","high"],Td={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"},va=n=>{if(typeof n=="string")return Td[n.trim().toLowerCase()]}});var Br,Ta=w(()=>{Br=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function xd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function xa(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||eo(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:Oe(d);ka.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(`
|
|
30
30
|
|
|
31
|
-
`)}return n.tools&&n.tools.length>0&&(p.tools=
|
|
31
|
+
`)}return n.tools&&n.tools.length>0&&(p.tools=xd(n.tools),n.tool_choice&&(n.tool_choice==="auto"?p.tool_choice={type:"auto"}:n.tool_choice==="any"||n.tool_choice==="required"?p.tool_choice={type:"any"}:typeof n.tool_choice=="string"?p.tool_choice={type:"tool",name:n.tool_choice}:typeof n.tool_choice=="object"&&n.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:n.tool_choice.function.name}))),p}var Sa=w(()=>{_t()});function Sd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function to(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 Ie(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:Sd(n),cache_creation_input_tokens:to(n)}}function Me(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 no=w(()=>{"use strict"});function Cd(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 Jr(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 oo,ro,Ca=w(()=>{"use strict";oo=require("uuid");_t();wn();oe();Ta();Sa();Ve();no();ro=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=zt(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(`
|
|
32
32
|
`);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(`
|
|
33
|
-
`),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"?
|
|
34
|
-
`));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(
|
|
35
|
-
data: ${JSON.stringify(
|
|
33
|
+
`),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"?Br(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"?Br(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(`
|
|
34
|
+
`));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=va(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=Cd(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=Oe(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=xa(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 xe(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 Ee(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 H(a),l=this.convertOpenAIResponseToAnthropic(i,t);return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e,t){return new ReadableStream({start:async r=>{let s=new TextEncoder,a=`msg_${Date.now()}`,i=null,l=String(t?.req?.body?.model??"unknown"),c=!1,u=!1,p=!1;t?.req&&(t.req.contentDelivered=!1);let d=()=>{t?.req&&(t.req.contentDelivered=!0)},f=new Map,g=new Map,h=0,m=0,y=0,b=!1,_=!1,k=0,v=-1,x=()=>{let R=k;return k++,R},T=R=>{if(!b)try{r.enqueue(R);let O=new TextDecoder().decode(R);this.logger.debug({reqId:t.req.id,data:O,type:"send data"})}catch(O){if(O instanceof TypeError&&O.message.includes("Controller is already closed"))b=!0;else throw this.logger.debug({reqId:t.req.id,error:O instanceof Error?O.message:String(O),type:"send data error"}),O}},P=()=>{if(!b)try{if(!c){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),r.close(),b=!0;return}if(v>=0){let O={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
|
|
35
|
+
data: ${JSON.stringify(O)}
|
|
36
36
|
|
|
37
|
-
`)),
|
|
37
|
+
`)),v=-1}if(i)T(s.encode(`event: message_delta
|
|
38
38
|
data: ${JSON.stringify(i)}
|
|
39
39
|
|
|
40
|
-
`)),i=null;else{let
|
|
41
|
-
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:
|
|
40
|
+
`)),i=null;else{let O=t?.req?.tokenCount||0;T(s.encode(`event: message_delta
|
|
41
|
+
data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:O,output_tokens:0,cache_read_input_tokens:0}})}
|
|
42
42
|
|
|
43
|
-
`))}let
|
|
44
|
-
data: ${JSON.stringify(
|
|
43
|
+
`))}let R={type:"message_stop"};T(s.encode(`event: message_stop
|
|
44
|
+
data: ${JSON.stringify(R)}
|
|
45
45
|
|
|
46
|
-
`)),r.close(),b=!0}catch(
|
|
47
|
-
`);
|
|
46
|
+
`)),r.close(),b=!0}catch(R){if(R instanceof TypeError&&R.message.includes("Controller is already closed"))b=!0;else throw R}},A=null;try{A=e.getReader();let R=new TextDecoder,O="";for(;!b;){let{done:F,value:C}=await A.read();if(F)break;O+=R.decode(C,{stream:!0});let I=O.split(`
|
|
47
|
+
`);O=I.pop()||"";for(let S of I){if(b)break;if(!S.startsWith("data:"))continue;let M=S.slice(5).trim();if(this.logger.debug({reqId:t.req.id,type:"recieved data",data:M}),M!=="[DONE]")try{let L=JSON.parse(M);if(h++,this.logger.debug({reqId:t.req.id,response:L,tppe:"Original Response"}),L.error){t?.req&&(t.req.sseError=L.error);let $={type:"error",message:{type:"api_error",message:JSON.stringify(L.error)}};T(s.encode(`event: error
|
|
48
48
|
data: ${JSON.stringify($)}
|
|
49
49
|
|
|
50
|
-
`));continue}if(
|
|
50
|
+
`));continue}if(l=L.model&&L.model!=="unknown"?L.model:l,!c&&!b&&!p){c=!0;let $=t?.req?.tokenCount||0,j={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:$,output_tokens:0}}};T(s.encode(`event: message_start
|
|
51
51
|
data: ${JSON.stringify(j)}
|
|
52
52
|
|
|
53
|
-
`))}let U=L.choices?.[0];if(L.usage){let $=L.usage?.prompt_tokens_details?.cached_tokens??L.usage?.prompt_cache_hit_tokens??0,G=(L.usage?.prompt_tokens||0)-$,ge=L.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:L.usage,mappedUsage:{input_tokens:G,output_tokens:ge,cache_read_input_tokens:$},choicesLength:Array.isArray(L.choices)?L.choices.length:void 0,finishReason:U?.finish_reason});let K={input_tokens:G,output_tokens:ge,cache_read_input_tokens:$,...
|
|
53
|
+
`))}let U=L.choices?.[0];if(L.usage){let $=L.usage?.prompt_tokens_details?.cached_tokens??L.usage?.prompt_cache_hit_tokens??0,G=(L.usage?.prompt_tokens||0)-$,ge=L.usage?.completion_tokens||0;this.logger?.info({debug_log:!0,reqId:t.req.id,phase:"anthropic_transformer_usage",providerUsage:L.usage,mappedUsage:{input_tokens:G,output_tokens:ge,cache_read_input_tokens:$},choicesLength:Array.isArray(L.choices)?L.choices.length:void 0,finishReason:U?.finish_reason});let K={input_tokens:G,output_tokens:ge,cache_read_input_tokens:$,...Jr(L.usage)?{cache_creation_input_tokens:to(L.usage)}:{},...L.usage.kiro_estimated===!0||L.usage.usage_estimated===!0?{usage_estimated:!0}:{}};if(!i)i={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{...K}};else{let W=i.usage||{};Jr(L.usage)||"cache_creation_input_tokens"in W?i.usage=Me(W,K,!1):i.usage={input_tokens:K.input_tokens||W.input_tokens||0,output_tokens:K.output_tokens||W.output_tokens||0,cache_read_input_tokens:K.cache_read_input_tokens||W.cache_read_input_tokens||0}}}if(!U)continue;if(U?.delta?.thinking&&!b&&!p&&!u){if(!_){let $=x();d();let j={type:"content_block_start",index:$,content_block:{type:"thinking",thinking:""}};T(s.encode(`event: content_block_start
|
|
54
54
|
data: ${JSON.stringify(j)}
|
|
55
55
|
|
|
56
|
-
`)),
|
|
56
|
+
`)),v=$,_=!0}if(U.delta.thinking.signature){let $={type:"content_block_delta",index:v,delta:{type:"signature_delta",signature:U.delta.thinking.signature}};T(s.encode(`event: content_block_delta
|
|
57
57
|
data: ${JSON.stringify($)}
|
|
58
58
|
|
|
59
|
-
`));let j={type:"content_block_stop",index:
|
|
59
|
+
`));let j={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
|
|
60
60
|
data: ${JSON.stringify(j)}
|
|
61
61
|
|
|
62
|
-
`)),
|
|
62
|
+
`)),v=-1}else if(U.delta.thinking.content){let $={type:"content_block_delta",index:v,delta:{type:"thinking_delta",thinking:U.delta.thinking.content||""}};T(s.encode(`event: content_block_delta
|
|
63
63
|
data: ${JSON.stringify($)}
|
|
64
64
|
|
|
65
|
-
`))}}if(U?.delta?.content&&!b&&!p){if(m++,
|
|
65
|
+
`))}}if(U?.delta?.content&&!b&&!p){if(m++,v>=0&&!u){let j={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
|
|
66
66
|
data: ${JSON.stringify(j)}
|
|
67
67
|
|
|
68
|
-
`)),
|
|
68
|
+
`)),v=-1}if(!u&&!p){u=!0;let $=x();d();let j={type:"content_block_start",index:$,content_block:{type:"text",text:""}};T(s.encode(`event: content_block_start
|
|
69
69
|
data: ${JSON.stringify(j)}
|
|
70
70
|
|
|
71
|
-
`)),
|
|
71
|
+
`)),v=$}if(!b&&!p){let $={type:"content_block_delta",index:v,delta:{type:"text_delta",text:U.delta.content}};T(s.encode(`event: content_block_delta
|
|
72
72
|
data: ${JSON.stringify($)}
|
|
73
73
|
|
|
74
|
-
`))}}if(U?.delta?.annotations?.length&&!b&&!p){if(
|
|
74
|
+
`))}}if(U?.delta?.annotations?.length&&!b&&!p){if(v>=0&&u){let $={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
|
|
75
75
|
data: ${JSON.stringify($)}
|
|
76
76
|
|
|
77
|
-
`)),
|
|
77
|
+
`)),v=-1,u=!1}U?.delta?.annotations.forEach($=>{let j=x();d();let G={type:"content_block_start",index:j,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${(0,oo.v4)()}`,content:[{type:"web_search_result",title:$.url_citation.title,url:$.url_citation.url}]}};T(s.encode(`event: content_block_start
|
|
78
78
|
data: ${JSON.stringify(G)}
|
|
79
79
|
|
|
80
|
-
`));let ge={type:"content_block_stop",index:j};
|
|
80
|
+
`));let ge={type:"content_block_stop",index:j};T(s.encode(`event: content_block_stop
|
|
81
81
|
data: ${JSON.stringify(ge)}
|
|
82
82
|
|
|
83
|
-
`)),
|
|
84
|
-
data: ${JSON.stringify(
|
|
83
|
+
`)),v=-1})}if(U?.delta?.tool_calls&&!b&&!p){y++;let $=new Set;for(let j of U.delta.tool_calls){if(b)break;let G=j.index??0;if($.has(G))continue;if($.add(G),!g.has(G)){if(v>=0){let Gl={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
|
|
84
|
+
data: ${JSON.stringify(Gl)}
|
|
85
85
|
|
|
86
|
-
`)),
|
|
86
|
+
`)),v=-1}let K=x();g.set(G,K);let W=j.id||`call_ccr_${G}`,N=j.function?.name||`tool_${G}`;d();let Q={type:"content_block_start",index:K,content_block:{type:"tool_use",id:W,name:N,input:{}}};T(s.encode(`event: content_block_start
|
|
87
87
|
data: ${JSON.stringify(Q)}
|
|
88
88
|
|
|
89
|
-
`)),
|
|
89
|
+
`)),v=K;let Kl={id:W,name:N,arguments:"",contentBlockIndex:K};f.set(G,Kl)}else if(j.id&&j.function?.name){let K=f.get(G);K.id.startsWith("call_")&&K.name.startsWith("tool_")&&(K.id=j.id,K.name=j.function.name)}if(j.function?.arguments&&!b&&!p){let K=g.get(G);if(K===void 0)continue;let W=f.get(G);W&&(W.arguments+=j.function.arguments);try{let N={type:"content_block_delta",index:K,delta:{type:"input_json_delta",partial_json:j.function.arguments}};T(s.encode(`event: content_block_delta
|
|
90
90
|
data: ${JSON.stringify(N)}
|
|
91
91
|
|
|
92
|
-
`))}catch{try{let N=j.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Q={type:"content_block_delta",index:K,delta:{type:"input_json_delta",partial_json:N}};
|
|
92
|
+
`))}catch{try{let N=j.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Q={type:"content_block_delta",index:K,delta:{type:"input_json_delta",partial_json:N}};T(s.encode(`event: content_block_delta
|
|
93
93
|
data: ${JSON.stringify(Q)}
|
|
94
94
|
|
|
95
|
-
`))}catch(N){console.error(N)}}}}}if(U?.finish_reason&&!b&&!p){if(m===0&&y===0&&console.error("Warning: No content in the stream response!"),
|
|
95
|
+
`))}catch(N){console.error(N)}}}}}if(U?.finish_reason&&!b&&!p){if(m===0&&y===0&&console.error("Warning: No content in the stream response!"),v>=0){let $={type:"content_block_stop",index:v};T(s.encode(`event: content_block_stop
|
|
96
96
|
data: ${JSON.stringify($)}
|
|
97
97
|
|
|
98
|
-
`)),
|
|
99
|
-
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:
|
|
98
|
+
`)),v=-1}if(!b){let j={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[U.finish_reason]||"end_turn";i?i.delta={...i.delta,stop_reason:j,stop_sequence:null}:i={type:"message_delta",delta:{stop_reason:j,stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}}}p=!0}}catch(L){this.logger?.error(`parseError: ${L.name} message: ${L.message} stack: ${L.stack} data: ${M}`)}}}P()}catch(R){if(!b)try{r.error(R)}catch(O){console.error(O)}}finally{if(A)try{A.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_${(0,oo.v4)()}`;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_${(0,oo.v4)().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:Jr(e.usage)?to(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 V(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}}});function Rd(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(bt).includes(o)?o:bt.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let o of t){let r=o.toUpperCase();e.anyOf.push({type:Object.values(bt).includes(r)?r:bt.TYPE_UNSPECIFIED})}}}function Wt(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)&&Rd(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(bt).includes(l)?l:bt.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=Wt(i);else if(o.includes(a)){let l=[];for(let c of i){if(c.type=="null"){e.nullable=!0;continue}l.push(Wt(c))}e[a]=l}else if(r.includes(a)){let l={};for(let[c,u]of Object.entries(i))l[c]=Wt(u);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=i}return e}function wd(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=Wt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Wt(e.response));return n}function io(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(wd({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 ao(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 so(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 Kr(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 Wr(n,e,t){let o=e?Kr(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:so(n.usageMetadata)}:{}}}async function co(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(`
|
|
99
|
+
`)||"",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:so(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(Wr(_,void 0,c))}
|
|
100
100
|
|
|
101
|
-
`))});let
|
|
101
|
+
`));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],v=!1,x=k.content?.parts||[];x.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let O={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(O)}
|
|
102
102
|
|
|
103
|
-
`))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{
|
|
103
|
+
`))});let T=x.find(R=>R.thoughtSignature)?.thoughtSignature;if(T&&!s){if(!i){let O={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(O)}
|
|
104
104
|
|
|
105
|
-
`))
|
|
105
|
+
`))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:T}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
106
106
|
|
|
107
|
-
`)),
|
|
108
|
-
`);if(!w&&s&&!a){let R={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
107
|
+
`)),s=!0,c++,l){let O={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(O)}
|
|
109
108
|
|
|
110
|
-
`)),a||(a=!0)}
|
|
109
|
+
`)),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||{})}})),A=x.filter(R=>R.text&&R.thought!==!0).map(R=>R.text).join(`
|
|
110
|
+
`);if(!A&&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)}
|
|
111
111
|
|
|
112
|
-
`)),
|
|
112
|
+
`)),a||(a=!0)}if(i&&A&&!s)if(_.modelVersion?.includes("3")){l+=A,_.usageMetadata&&y.enqueue(r.encode(`data: ${JSON.stringify(Wr(_,k,c))}
|
|
113
113
|
|
|
114
|
-
`))
|
|
114
|
+
`));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)}
|
|
115
115
|
|
|
116
|
-
`))
|
|
117
|
-
|
|
116
|
+
`)),s=!0}if(A){l||c++;let R={choices:[{delta:{role:"assistant",content:A},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:so(_.usageMetadata)},O=Kr(k);O&&(R.choices[0].delta.annotations=O),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
117
|
+
|
|
118
|
+
`)),v=!0,!a&&A&&(a=!0)}P.length>0&&(P.forEach(R=>{c++,u++;let O={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:so(_.usageMetadata)},F=Kr(k);F&&(O.choices[0].delta.annotations=F),y.enqueue(r.encode(`data: ${JSON.stringify(O)}
|
|
119
|
+
|
|
120
|
+
`)),v=!0}),!a&&A&&(a=!0)),!v&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&y.enqueue(r.encode(`data: ${JSON.stringify(Wr(_,k,c))}
|
|
121
|
+
|
|
122
|
+
`))}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(`
|
|
123
|
+
`);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 bt,Gr=w(()=>{"use strict";bt={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var lo,Ra=w(()=>{"use strict";Gr();lo=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:io(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=ao;async transformResponseOut(e){return co(e,this.name,this.logger)}}});async function Pd(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
118
124
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
119
125
|
2. Run "gcloud auth application-default login"
|
|
120
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
126
|
+
3. Use Google Cloud environment with default service account`)}}var uo,wa=w(()=>{"use strict";Gr();uo=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 Pd();return{body:io(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 ao(e)}async transformResponseOut(e){return co(e,this.name)}}});var po,Pa=w(()=>{"use strict";oe();po=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 H(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(`
|
|
121
127
|
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
122
128
|
`))},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)}
|
|
123
129
|
|
|
124
130
|
`;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(_)}
|
|
125
131
|
|
|
126
|
-
`;g.enqueue(h.encode(k));let
|
|
132
|
+
`;g.enqueue(h.encode(k));let v={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete v.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(v)}
|
|
127
133
|
|
|
128
|
-
`;g.enqueue(h.encode(
|
|
134
|
+
`;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)}
|
|
129
135
|
|
|
130
136
|
`;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
|
|
131
137
|
`))}else g.enqueue(h.encode(d+`
|
|
132
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
133
|
-
`);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:
|
|
134
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
138
|
+
`))};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(`
|
|
139
|
+
`);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+`
|
|
140
|
+
`))}}}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 fo,Ea=w(()=>{"use strict";oe();fo=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
|
|
135
141
|
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.
|
|
136
142
|
Examples:
|
|
137
143
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
138
|
-
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 H(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(
|
|
144
|
+
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 H(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(`
|
|
139
145
|
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
140
|
-
`))},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
|
|
146
|
+
`))},p=(d,f)=>{let{controller:g,encoder:h,exitToolIndex:m,setExitToolIndex:y,appendExitToolResponse:b}=f;if(d.startsWith("data: ")&&d.trim()!=="data: [DONE]")try{let _=JSON.parse(d.slice(6));if(_.choices[0]?.delta?.tool_calls?.length){let k=_.choices[0].delta.tool_calls[0];if(k.function?.name==="ExitTool"){y(k.index);return}else if(m()>-1&&k.index===m()&&k.function.arguments){b(k.function.arguments);try{let v=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:v.response||""}}];let x=`data: ${JSON.stringify(_)}
|
|
141
147
|
|
|
142
|
-
`;g.enqueue(h.encode(
|
|
148
|
+
`;g.enqueue(h.encode(x))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
|
|
143
149
|
|
|
144
150
|
`;g.enqueue(h.encode(k))}}catch{g.enqueue(h.encode(d+`
|
|
145
151
|
`))}else g.enqueue(h.encode(d+`
|
|
146
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
147
|
-
`);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:
|
|
148
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
152
|
+
`))};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(`
|
|
153
|
+
`);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+`
|
|
154
|
+
`))}}}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 Aa,mo,Oa=w(()=>{"use strict";oe();Aa=require("uuid"),mo=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 H(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(`
|
|
149
155
|
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
150
156
|
`))},f=(g,h)=>{let{controller:m,encoder:y}=h;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let b=g.slice(6);try{let _=JSON.parse(b);if(_.usage&&(this.logger?.debug({usage:_.usage,hasToolCall:i},"usage"),_.choices[0].finish_reason=i?"tool_calls":"stop"),_.choices?.[0]?.finish_reason==="error"){m.enqueue(y.encode(`data: ${JSON.stringify({error:_.choices?.[0].error})}
|
|
151
157
|
|
|
152
|
-
`));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
|
|
158
|
+
`));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 A={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:k}}}]};A.choices?.[0]?.delta&&(delete A.choices[0].delta.reasoning,delete A.choices[0].delta.reasoning_content);let R=`data: ${JSON.stringify(A)}
|
|
153
159
|
|
|
154
|
-
`;m.enqueue(y.encode(
|
|
160
|
+
`;m.enqueue(y.encode(R));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let A="ccr_think_signature",R=_.choices[0].delta.content,O={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:A}}}]};O.choices?.[0]?.delta&&delete O.choices[0].delta.reasoning;let F=`data: ${JSON.stringify(O)}
|
|
155
161
|
|
|
156
|
-
`;m.enqueue(y.encode(
|
|
162
|
+
`;m.enqueue(y.encode(F));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 I=`data: ${JSON.stringify(C)}
|
|
157
163
|
|
|
158
|
-
`;m.enqueue(y.encode(
|
|
164
|
+
`;m.enqueue(y.encode(I));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(A=>{A.id=`call_${(0,Aa.v4)()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let v=_.choices?.[0]?.delta,x=v&&Object.keys(v).length>0,T=_.choices?.[0]?.finish_reason,P=_.usage;if(x||T||P){let A=`data: ${JSON.stringify(_)}
|
|
159
165
|
|
|
160
|
-
`;m.enqueue(y.encode(
|
|
166
|
+
`;m.enqueue(y.encode(A))}}catch{m.enqueue(y.encode(g+`
|
|
161
167
|
`))}}else m.enqueue(y.encode(g+`
|
|
162
|
-
`))};try{for(;;){let{done:g,value:h}=await p.read();if(g){
|
|
163
|
-
`);
|
|
164
|
-
`))}continue}let y=
|
|
165
|
-
`);
|
|
166
|
-
`))}}}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(
|
|
168
|
+
`))};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(`
|
|
169
|
+
`);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(_+`
|
|
170
|
+
`))}continue}let y=l.split(`
|
|
171
|
+
`);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+`
|
|
172
|
+
`))}}}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 go,Ia=w(()=>{"use strict";go=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}}});var Ma,ho,La=w(()=>{"use strict";oe();Ma=require("uuid"),ho=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 H(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(`
|
|
167
173
|
`);for(let y of m)y.trim()&&g.enqueue(h.encode(y+`
|
|
168
|
-
`))},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_${(0,
|
|
174
|
+
`))},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_${(0,Ma.v4)()}`}),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)}
|
|
169
175
|
|
|
170
176
|
`;h.enqueue(m.encode(_))}catch{h.enqueue(m.encode(f+`
|
|
171
177
|
`))}}else h.enqueue(m.encode(f+`
|
|
172
|
-
`))};try{for(;;){let{done:f,value:g}=await u.read();if(f){i.trim()&&p(i,
|
|
173
|
-
`);i=y.pop()||"";for(let b of y)if(b.trim())try{d(b,{controller:
|
|
178
|
+
`))};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(`
|
|
179
|
+
`);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+`
|
|
174
180
|
`))}continue}let m=i.split(`
|
|
175
|
-
`);i=m.pop()||"";for(let y of m)if(y.trim())try{d(y,{controller:
|
|
176
|
-
`))}}}catch(f){console.error("Stream error:",f),
|
|
181
|
+
`);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+`
|
|
182
|
+
`))}}}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 yo,$a=w(()=>{"use strict";yo=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}}});function Qr(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=Na.default.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=(0,Ua.jsonrepair)(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 Na,Ua,Da=w(()=>{Na=ee(require("json5")),Ua=require("jsonrepair")});var _o,Fa=w(()=>{"use strict";Da();oe();_o=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await H(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=Qr(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(`
|
|
177
183
|
`);for(let k of _)k.trim()&&y.enqueue(b.encode(k+`
|
|
178
|
-
`))},g=(m,y,b)=>{let _="";try{_=
|
|
184
|
+
`))},g=(m,y,b)=>{let _="";try{_=Qr(r.arguments||"",this.logger)}catch(T){console.error(`${T.message} ${T.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},v={...m,choices:[{...m.choices[0],delta:k}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let x=`data: ${JSON.stringify(v)}
|
|
179
185
|
|
|
180
|
-
`;y.enqueue(b.encode(
|
|
186
|
+
`;y.enqueue(b.encode(x))},h=(m,y)=>{let{controller:b,encoder:_}=y;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.slice(6);try{let v=JSON.parse(k);if(v.choices?.[0]?.delta?.tool_calls?.length){let T=v.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:T.index,name:T.function?.name||"",id:T.id||"",arguments:T.function?.arguments||""},T.function?.arguments&&(T.function.arguments="");let P=`data: ${JSON.stringify(v)}
|
|
181
187
|
|
|
182
|
-
`;b.enqueue(_.encode(
|
|
188
|
+
`;b.enqueue(_.encode(P));return}else if(r.index===T.index){T.function?.arguments&&(r.arguments+=T.function.arguments);return}else{g(v,b,_),r={index:T.index,name:T.function?.name||"",id:T.id||"",arguments:T.function?.arguments||""};return}}if(v.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){g(v,b,_),r={};return}v.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let x=`data: ${JSON.stringify(v)}
|
|
183
189
|
|
|
184
|
-
`;b.enqueue(_.encode(
|
|
190
|
+
`;b.enqueue(_.encode(x))}catch{b.enqueue(_.encode(m+`
|
|
185
191
|
`))}}else b.enqueue(_.encode(m+`
|
|
186
|
-
`))};try{for(;;){let{done:m,value:y}=await d.read();if(m){
|
|
187
|
-
`);
|
|
188
|
-
`))}continue}let _=
|
|
189
|
-
`);
|
|
190
|
-
`))}}}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
|
+
`))};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(`
|
|
193
|
+
`);c=k.pop()||"";for(let v of k)if(v.trim())try{h(v,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>i,setReasoningComplete:x=>i=x})}catch(x){console.error("Error processing line:",v,x),p.enqueue(o.encode(v+`
|
|
194
|
+
`))}continue}let _=c.split(`
|
|
195
|
+
`);c=_.pop()||"";for(let k of _)if(k.trim())try{h(k,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>a,appendReasoningContent:v=>a+=v,isReasoningComplete:()=>i,setReasoningComplete:v=>i=v})}catch(v){console.error("Error processing line:",k,v),p.enqueue(o.encode(k+`
|
|
196
|
+
`))}}}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 bo,ja=w(()=>{"use strict";oe();_t();bo=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??eo(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 H(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(`
|
|
191
197
|
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
192
198
|
`))},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)}
|
|
193
199
|
|
|
@@ -197,109 +203,109 @@ Examples:
|
|
|
197
203
|
|
|
198
204
|
`;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
|
|
199
205
|
`))}else g.enqueue(h.encode(d+`
|
|
200
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
201
|
-
`);a=h.pop()||"";for(let m of h)if(m.trim())try{p(m,{controller:
|
|
202
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
206
|
+
`))};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(`
|
|
207
|
+
`);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+`
|
|
208
|
+
`))}}}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 ko,Ha=w(()=>{"use strict";ko=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 vo,za=w(()=>{"use strict";vo=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function Ba(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 Ja(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 Wa(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)}
|
|
203
209
|
|
|
204
|
-
`))}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)}};
|
|
210
|
+
`))}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)}
|
|
205
211
|
|
|
206
|
-
`))}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)}};
|
|
212
|
+
`))}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)}
|
|
207
213
|
|
|
208
|
-
`))}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)}};
|
|
214
|
+
`))}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)}
|
|
209
215
|
|
|
210
|
-
`))}else if(u.type==="message_stop")
|
|
216
|
+
`))}else if(u.type==="message_stop")l.enqueue(r.encode(`data: [DONE]
|
|
211
217
|
|
|
212
|
-
`));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)}};
|
|
218
|
+
`));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)}
|
|
213
219
|
|
|
214
|
-
`))}}catch(u){t?.error(`Error parsing ${e} stream chunk`,
|
|
215
|
-
`);
|
|
220
|
+
`))}}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(`
|
|
221
|
+
`);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 Ed(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
216
222
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
217
223
|
2. Run "gcloud auth application-default login"
|
|
218
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
224
|
+
3. Use Google Cloud environment with default service account`)}}var To,Ga=w(()=>{"use strict";Ka();To=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 Ed();return{body:Ba(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 Ja(e)}async transformResponseOut(e){return Wa(e,this.name,this.logger)}}});var xo,Qa=w(()=>{"use strict";xo=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 So,Va=w(()=>{"use strict";So=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var Co,Ya=w(()=>{"use strict";Co=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Ro,Xa=w(()=>{"use strict";Ro=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}}});var Za,wo,qa=w(()=>{"use strict";oe();Za=require("uuid"),wo=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 H(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(`
|
|
219
225
|
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
220
226
|
`))},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})}
|
|
221
227
|
|
|
222
|
-
`)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let
|
|
228
|
+
`)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let v={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};v.choices?.[0]?.delta&&delete v.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(v)}
|
|
223
229
|
|
|
224
|
-
`;m.enqueue(y.encode(
|
|
230
|
+
`;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let x={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,content:null,thinking:{content:h.reasoningContent(),signature:"ccr_think_signature"}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let T=`data: ${JSON.stringify(x)}
|
|
225
231
|
|
|
226
|
-
`;m.enqueue(y.encode(
|
|
232
|
+
`;m.enqueue(y.encode(T))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(v=>{v.id=`call_${(0,Za.v4)()}`}),_.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(_)}
|
|
227
233
|
|
|
228
234
|
`;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(g+`
|
|
229
235
|
`))}}else m.enqueue(y.encode(g+`
|
|
230
|
-
`))};try{for(;;){let{done:g,value:h}=await p.read();if(g){
|
|
231
|
-
`);
|
|
232
|
-
`))}continue}let y=
|
|
233
|
-
`);
|
|
234
|
-
`))}}}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(
|
|
236
|
+
`))};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(`
|
|
237
|
+
`);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(_+`
|
|
238
|
+
`))}continue}let y=l.split(`
|
|
239
|
+
`);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+`
|
|
240
|
+
`))}}}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 Vr,Ad,Po,ec=w(()=>{"use strict";oe();Vr=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
235
241
|
|
|
236
242
|
Output format:
|
|
237
243
|
<reasoning_content>
|
|
238
244
|
Your detailed thinking process goes here
|
|
239
245
|
</reasoning_content>
|
|
240
|
-
Your final answer must follow after the closing tag above.`,
|
|
241
|
-
${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:
|
|
246
|
+
Your final answer must follow after the closing tag above.`,Ad=10,Po=class{name="forcereasoning";async transformRequestIn(e){let t=0;e.messages.filter(r=>r.role==="assistant").reverse().forEach(r=>{r.thinking&&(r.thinking.content&&(!r.content||t<Ad)&&(t++,r.content=`<reasoning_content>${r.thinking.content}</reasoning_content>
|
|
247
|
+
${r.content}`),delete r.thinking)});let o=e.messages[e.messages.length-1];return o.role==="user"&&(Array.isArray(o.content)?o.content.push({type:"text",text:Vr}):o.content=[{type:"text",text:Vr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Vr}]}),e}async transformResponseOut(e){let t="<reasoning_content>",o="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let r=await H(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)}
|
|
242
248
|
|
|
243
|
-
`)));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
|
|
249
|
+
`)));return}let y=d+m;for(d="";y.length>0;)if(p==="SEARCHING"){let b=y.indexOf(t);if(b!==-1)y=y.substring(b+t.length),p="REASONING";else{for(let _=t.length-1;_>0;_--)if(y.endsWith(t.substring(0,_))){d=y.substring(y.length-_);break}y=""}}else if(p==="REASONING"){let b=y.indexOf(o);if(b!==-1){let _=y.substring(0,b);if(_.length>0){let x={...h.choices[0].delta,thinking:{content:_}};delete x.content;let T={...h,choices:[{...h.choices[0],delta:x,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
244
250
|
|
|
245
|
-
`))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let
|
|
251
|
+
`))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let v={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
246
252
|
|
|
247
|
-
`)),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
|
|
253
|
+
`)),r++,y=y.substring(b+o.length),p="FINAL"}else{let _=y;for(let k=o.length-1;k>0;k--)if(y.endsWith(o.substring(0,k))){d=y.substring(y.length-k),_=y.substring(0,y.length-k);break}if(_.length>0){let k={...h.choices[0].delta,thinking:{content:_}};delete k.content;let v={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
248
254
|
|
|
249
|
-
`))}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
|
|
255
|
+
`))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...h.choices[0].delta,content:_};k.thinking&&delete k.thinking;let v={...h,choices:[{...h.choices[0],delta:k}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
250
256
|
|
|
251
|
-
`)),f=""}r++,y=""}};try{for(;;){let{done:h,value:m}=await
|
|
252
|
-
`);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){
|
|
257
|
+
`)),f=""}r++,y=""}};try{for(;;){let{done:h,value:m}=await c.read();if(h)break;let y=s.decode(m,{stream:!0});u+=y;let b=u.split(`
|
|
258
|
+
`);u=b.pop()||"";for(let _ of b)if(_.trim()){if(_.trim()==="data: [DONE]"){l.enqueue(a.encode(_+`
|
|
253
259
|
|
|
254
|
-
`));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{
|
|
255
|
-
`))}else
|
|
256
|
-
`))}}}catch(h){console.error("Stream error:",h),
|
|
260
|
+
`));break}if(_.startsWith("data:"))try{let k=JSON.parse(_.slice(5));g(k,k.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(_+`
|
|
261
|
+
`))}else l.enqueue(a.encode(_+`
|
|
262
|
+
`))}}}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)}
|
|
257
263
|
|
|
258
|
-
`))}
|
|
264
|
+
`))}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 Eo,tc=w(()=>{"use strict";oe();Eo=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+`
|
|
259
265
|
`));break}let d=o.decode(p,{stream:!0});a+=d;let f=a.split(`
|
|
260
|
-
`);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,
|
|
266
|
+
`);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)}
|
|
261
267
|
|
|
262
|
-
`));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}}}]};
|
|
268
|
+
`));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)}
|
|
263
269
|
|
|
264
|
-
`)),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&&
|
|
270
|
+
`)),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)}
|
|
265
271
|
|
|
266
|
-
`))}catch{
|
|
267
|
-
`))}else
|
|
268
|
-
`))}}catch(u){
|
|
272
|
+
`))}catch{l.enqueue(r.encode(g+`
|
|
273
|
+
`))}else l.enqueue(r.encode(g+`
|
|
274
|
+
`))}}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 H(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}}});var Yr,Ao,nc=w(()=>{"use strict";oe();dt();Yr=require("uuid"),Ao=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||Re(e.metadata?.user_id)||s("session_id")||(0,Yr.v4)()}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 H(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(`
|
|
269
275
|
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
270
276
|
`))},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})}
|
|
271
277
|
|
|
272
|
-
`));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
|
|
278
|
+
`));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)}
|
|
273
279
|
|
|
274
|
-
`));return}if(b.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let
|
|
280
|
+
`));return}if(b.choices?.[0]?.delta?.content&&h.reasoningContent()&&!h.isReasoningComplete()){h.setReasoningComplete(!0);let P="ccr_think_signature",A=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)}
|
|
275
281
|
|
|
276
|
-
`));let
|
|
282
|
+
`));let O={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:A}}]};O.choices?.[0]?.delta&&(delete O.choices[0].delta.reasoning,delete O.choices[0].delta.reasoning_content),m.enqueue(y.encode(`data: ${JSON.stringify(O)}
|
|
277
283
|
|
|
278
|
-
`));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(
|
|
284
|
+
`));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_${(0,Yr.v4)()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,v=k&&Object.keys(k).length>0,x=b.choices?.[0]?.finish_reason,T=b.usage;(v||x||T)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
|
|
279
285
|
|
|
280
286
|
`))}catch{m.enqueue(y.encode(g+`
|
|
281
287
|
`))}else m.enqueue(y.encode(g+`
|
|
282
|
-
`))};try{for(;;){let{done:g,value:h}=await p.read();if(g){
|
|
283
|
-
`);
|
|
284
|
-
`))}continue}let y=
|
|
285
|
-
`);
|
|
286
|
-
`))}}}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(
|
|
288
|
+
`))};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(`
|
|
289
|
+
`);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(_+`
|
|
290
|
+
`))}continue}let y=l.split(`
|
|
291
|
+
`);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+`
|
|
292
|
+
`))}}}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 Id(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim();if(!e)return;let t=e.toLowerCase();return["none","low","medium","high","max"].includes(t)?t:/^\d+$/.test(e)?parseInt(e,10):e}function Md(n){let e="";try{e=new URL(String(n||"")).pathname.replace(/\/+$/,"")}catch{return"chat"}return e.endsWith("/messages")?"anthropic":e.endsWith("/responses")?"responses":"chat"}var Od,Oo,oc=w(()=>{"use strict";_t();Od={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Oo=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=Id(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Md(t?.baseUrl);if(typeof o=="number"){if(o<=0)return e;if(r==="anthropic")e.reasoning={enabled:!0,max_tokens:Math.max(1024,Math.floor(o))};else{let a=Oe(o);r==="chat"?e.reasoning_effort=a:e.reasoning={enabled:!0,effort:a}}return e}if(o==="low"||o==="medium"||o==="high"||o==="max")return r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e;let s=Od[o.toLowerCase()];return s?(r==="anthropic"?e.reasoning={enabled:!0,effort:s}:r==="chat"?e.reasoning_effort=o:e.reasoning={enabled:!0,effort:o},e):(r==="chat"?e.reasoning_effort=o:r==="responses"&&(e.reasoning={enabled:!0,effort:o}),e)}}});function rc(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 Io,sc=w(()=>{"use strict";_t();oe();Io=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=Oe(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 xe(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 Ee(e);if(e=a.response,a.isSSE)return this.transformStream(e)}let r=await H(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)rc(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)rc(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 ic,ac=w(()=>{Ca();Ra();wa();Pa();Ea();Oa();Ia();La();$a();Fa();ja();Ha();za();Ga();Qa();Va();Ya();Xa();qa();Ar();ec();tc();nc();oc();sc();ic={AnthropicTransformer:ro,GeminiTransformer:lo,VertexGeminiTransformer:uo,VertexClaudeTransformer:To,DeepseekTransformer:po,TooluseTransformer:fo,OpenrouterTransformer:mo,OpenAITransformer:Co,MaxTokenTransformer:go,GroqTransformer:ho,CleancacheTransformer:yo,EnhanceToolTransformer:_o,ReasoningTransformer:bo,SamplingTransformer:ko,MaxCompletionTokens:vo,CerebrasTransformer:xo,StreamOptionsTransformer:So,CustomParamsTransformer:Ro,VercelTransformer:wo,OpenAIResponsesTransformer:at,ForceReasoningTransformer:Po,KimiTransformer:Eo,OpenCodeTransformer:Ao,DefaultThinkingTransformer:Oo,AmdTransformer:Io}});var Xe,Xr=w(()=>{"use strict";ac();Xe=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;preparePluginTransformer(e){if(typeof e.TransformerName=="string")return e;let t=new e;if(!t?.name)throw new Error("plugin transformer has no name");return t.logger=this.logger,t}registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&t.endPoint&&e.push({name:o,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,o)=>{typeof t=="object"&&!t.endPoint&&e.push({name:o,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=require(require.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})
|
|
287
293
|
error: ${t.message}
|
|
288
294
|
stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
289
|
-
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(
|
|
290
|
-
`):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ze,Qr=P(()=>{"use strict";sc();cc();lc();ae();Ze=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new Kt("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 Kt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Oo(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Io(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return he(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 uc(n){if(!n||typeof n!="object"||Nd(n))return null;for(let t of $d(n)){let o=Ld(t);if(o)return o}return null}function Ld(n){if(!n||typeof n!="object")return null;let e={},t=Mo(n,Ad);if(t!==void 0){let a=dc(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Mo(n,Od);if(o!==void 0){let a=dc(o);e.usedBalance=a,e.totalBalance=100}let r=Mo(n,Id);if(r!==void 0){let a=pc(r);a&&(e.resetTime=a)}let s=Mo(n,Md);if(s!==void 0){let a=pc(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 dc(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Mo(n,e){for(let t of e){let o=F(n?.[t]);if(o!==void 0)return o}}function $d(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function Nd(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 pc(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 Lo(n){let e=is(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Jd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Wd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Ud:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Dd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Fd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?jd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Hd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?zd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Bd:null:null}function Kd(n){let e=is(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Gd(n,e){let t=rs(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 rs(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>rs(e)):Object.values(n).flatMap(e=>rs(e))}function ss(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function is(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 pe,Vr,Yr,Xr,Zr,qr,Ad,Od,Id,Md,es,ts,ns,os,Ud,Dd,Fd,jd,Hd,zd,Bd,Jd,Wd,as=P(()=>{"use strict";ae();pe=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=X(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}},Vr=class extends pe{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}}},Yr=class extends pe{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}},Xr=class extends pe{async queryQuota(e,t,o){let r=Kd(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}},Zr=class extends pe{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=X(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),g=F(l.usage),h=F(l.remaining),m=F(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),g!==void 0?d.limitDaily=g:f!==void 0&&h!==void 0&&(d.limitDaily=f+h),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=F(u.currentValue),g=F(u.usage),h=F(u.remaining),m=F(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=F(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=F(p.usage),g=F(p.currentValue),h=F(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}}},qr=class extends pe{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=X(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 g=F(u.perWeekUsedQuota),h=F(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),h!==void 0&&(p.totalBalance=h),this.hasQuotaData(p)?p:null}catch{return null}}};Ad=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Od=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Id=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Md=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];es=class extends pe{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=ss(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=X(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 uc(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=X(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 uc(l)}catch{return null}}},ts=class extends pe{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:(ss(e.quotaToken,"atp-auth-token")||ss(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=X(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=Gd(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),g=F(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),g!==void 0&&(u.totalBalance=g),u.remainingBalance===void 0&&g!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,g-f)),this.hasQuotaData(u)?u:null}catch{return null}}},ns=class extends pe{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=X(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),g=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),g&&(c.resetTime=new Date(g).toISOString())}let u=i?.usage;if(u){let p=F(u.limit),d=F(u.remaining),f=F(u.used),g=u.resetTime;p!==void 0&&(c.totalBalance=p,f!==void 0?c.usedBalance=f:d!==void 0&&(c.usedBalance=Math.max(0,p-d),c.remainingBalance=d)),g&&(c.resetTime7d=new Date(g).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},os=class extends pe{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=is(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),g=F(u.current_interval_remaining_percent),h=F(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=F(u.current_weekly_total_count),y=F(u.current_weekly_usage_count),b=F(u.current_weekly_remaining_percent),_=F(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Ud=new Vr,Dd=new Yr,Fd=new Xr,jd=new Zr,Hd=new qr,zd=new es,Bd=new ts,Jd=new ns,Wd=new os});async function $o(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=fc.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<Qd)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}})(),fc.set(n,r),r.pending}var Qd,mc,fc,cs=P(()=>{"use strict";Ke();Qd=6e4,mc=2500,fc=new Map});function gc(n){return{[Vd]:n,[Yd]:Mn}}function Le(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function Zd(n){return n===!0||n==="true"||n===1||n==="1"}function qd(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${o}`}function ep(n){try{let e=new URL(n),t=e.pathname;return t.endsWith("/v1/messages")?t=t.slice(0,-12):t.endsWith("/messages")?t=t.slice(0,-9):t.endsWith("/v1/chat/completions")?t=t.slice(0,-20):t.endsWith("/chat/completions")&&(t=t.slice(0,-17)),t.endsWith("/v1")||(t=t.endsWith("/")?`${t}v1`:`${t}/v1`),e.pathname=`${t}/models`,e.toString()}catch{return null}}function tp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function ls(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Le(n))return{success:!1,skipped:!0,error:us,latencyMs:r()};let s=ep(n.baseUrl);if(!s)return{success:!1,error:"Cannot derive models endpoint from baseUrl",errorKind:"network",latencyMs:r()};try{let a={method:"GET",headers:{Authorization:`Bearer ${n.apiKey}`},signal:AbortSignal.timeout(e)};t&&(a.dispatcher=X(t));let i=await fetch(s,a);if(i.headers&&$t(n.name,n.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers,latencyMs:r()};if(i.status===429)return{success:!1,error:`HTTP 429: ${(await i.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:i.headers,latencyMs:r(),errorKind:"http"};if(i.status>=400&&i.status<500)return{success:!0,headers:i.headers,latencyMs:r()};let c=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${c.slice(0,100)}`,headers:i.headers,latencyMs:r(),errorKind:"http"}}catch(a){let i=a?.message||a?.toString()||"Unknown probe error",c=a?.name==="TimeoutError"||a?.name==="AbortError"||a?.code===20||a?.code==="ABORT_ERR";return{success:!1,error:i,latencyMs:r(),errorKind:c?"timeout":"network"}}}async function np(n,e,t,o){if(Le(n))return{success:!1,skipped:!0,error:us};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",...gc("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=X(t)),o?.info(`Sending scheduled wake-up call to provider ${n.name} using model ${r}...`);let l=await fetch(s,c);if(l.ok)return{success:!0};let u=await l.text().catch(()=>"");return{success:!1,error:`HTTP ${l.status}: ${u.slice(0,200)||"Unknown error"}`}}catch(i){return{success:!1,error:i?.message||i?.toString()||"Unknown wake-up error"}}}async function op(n,e,t,o,r){if(Le(n))return{success:!1,skipped:!0,error:us};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...gc("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=X(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 ds(n,e,t,o,r,s){return $e||($e=new Vt(n,e,t,o,r,s)),$e}function Tt(n,e,t,o,r,s){let a=ds(n,e,t,o,r,s);return a.start(),a}function No(){$e&&$e.stop()}function Uo(){$e&&($e.stop(),$e=null)}var Vd,Yd,Xd,us,Vt,$e,Do=P(()=>{"use strict";ue();We();as();Ke();cs();pr();ae();Vd="x-claude-code-router-source",Yd="x-claude-code-router-version";Xd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};us="Managed provider requires its plugin's authenticated model sync";Vt=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;resolveProxyUrl;logger;getConfig;resolveManagedRuntime;managedProbeTimer;running=!1;probeTelemetry=new Map;constructor(e,t,o,r,s,a){this.config={...Xd,...t},this.getProviders=e,this.resolveProxyUrl=o,this.logger=r,this.getConfig=s,this.resolveManagedRuntime=a}recordProbe(e,t,o){let r=Date.now(),s=t.success&&t.latencyMs>this.config.slowThresholdMs,a;t.success?a=s?"slow":"healthy":a=t.errorKind==="timeout"?"timeout":"error";let i=this.probeTelemetry.get(e),c={provider:e,latencyMs:t.latencyMs,status:a,isSlow:s,errorKind:t.errorKind,errorMessage:t.error,lastProbeAt:r,lastSuccessAt:t.success?r:i?.lastSuccessAt,source:o};return this.probeTelemetry.set(e,c),s&&this.logger?.warn?.(`Slow network detected for provider ${e}: probe took ${t.latencyMs} ms (threshold ${this.config.slowThresholdMs} ms)`),c}getProbeTelemetry(){return Array.from(this.probeTelemetry.values()).map(e=>({...e}))}getProviderProbeTelemetry(e){let t=this.probeTelemetry.get(e);return t?{...t}:void 0}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3),this.managedProbeTimer=setInterval(()=>this.runManagedRecoveryProbe(),this.config.quotaProbeIntervalMinutes*60*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.managedProbeTimer&&(clearInterval(this.managedProbeTimer),this.managedProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!Le(s)&&!this.config.excludeProviders.includes(s.name)),t=z(),o=[];for(let s of e){let a=Lo(s.baseUrl),i=Array.isArray(s.models)?s.models:[],c=this.resolveProxyUrl?.(s);if(!a){let l;try{l=new URL(s.baseUrl).hostname}catch{l=void 0}this.logger?.debug?.(`No quota adapter for provider ${s.name}`+(l?` (host: ${l})`:"")+" \u2014 skipping quota probe")}a&&o.push({provider:s.name,models:i,type:"quota-adapter",promise:a.queryQuota(s,this.config.probeTimeoutMs,c).then(l=>{if(l){lt(s.name,l),this.logger?.debug?.(`Stored quota probe result for ${s.name}`);let u=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,p=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(u||p){let d=u?`Quota exhausted: 5h limit reached (${l.usedDailyBalance}/${l.limitDaily})`:`Quota exhausted: 7d balance depleted (${l.usedBalance}/${l.totalBalance})`;for(let f of i){if(t.getState(s.name,f)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${s.name} (${f}): already rate-limited with active cooldown`);continue}t.forceOpen(s.name,f,d)}this.logger?.warn?.(`${d} for ${s.name}, marked as unhealthy`)}else for(let d of i){let f=t.getState(s.name,d);f&&f.status==="open"&&f.lastError?.includes("Quota exhausted")&&(t.recover(s.name,d),this.logger?.info?.(`Quota recovered for ${s.name} (${d}), marked as healthy`))}}})}),tp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:ls(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(this.resolveManagedRuntime){let s=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&Le(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:$o(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=z(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Le(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=>ls(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=z();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=z(),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&&Le(l))continue;let u=e.getState(a,c);if(!u||!u.rateLimitUntil)continue;if(Date.now()>=u.rateLimitUntil){e.recover(a,c),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${s}`);continue}let p=o.find(d=>d?.name===a&&d.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${a} not found or disabled for rate-limit probe`);continue}try{let d=await op(p,c,r,this.resolveProxyUrl?.(p),this.logger);if(d.success)this.logger?.info?.(`Rate-limit probe succeeded for ${s}, recovering model`),e.recover(a,c);else if(d.error&&(d.error.includes("429")||d.error.toLowerCase().includes("rate limit")||d.error.toLowerCase().includes("rate_limit")||d.error.toLowerCase().includes("too many requests")||d.error.toLowerCase().includes("\u9650\u6D41"))){let f=Date.now();u.rateLimitUntil&&u.rateLimitUntil>f?u.rateLimitUntil+=120*1e3:u.rateLimitUntil=f+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${s} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${s} returned non-rate-limit error: ${d.error?.slice(0,100)}`)}catch(d){this.logger?.warn?.(`Rate-limit probe exception for ${s}: ${d?.message||d}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(i=>i?.name&&i.enabled!==!1&&!Le(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=qd(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),p=parseInt(l,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,g=(p*60+d)*6e4-(o*60+r)*6e4,h=g>0&&g<=300*1e3;(f||h)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),np(i,3e4,this.resolveProxyUrl?.(i),this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${i.name}`):this.logger?.error?.(`Failed to wake up provider ${i.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${i.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?Zd(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,t){return this.lastWakeupDate.get(e)===t?!0:(this.lastWakeupDate.set(e,t),!1)}async probeProviderManually(e){let o=this.getProviders().find(i=>i.name===e);if(!o)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} not found`};if(o.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),{success:!1,latencyMs:0,status:"error",isSlow:!1,error:`Provider ${e} is disabled`};let r=await ls(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)z().recordSuccess(o.name,i);else for(let i of a)z().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 hc=P(()=>{"use strict"});var ps,vt,yc=P(()=>{"use strict";ps=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},vt=new ps});var le,fs=P(()=>{"use strict";le=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
291
|
-
`);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var qe,
|
|
295
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(ic).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)}}});var cc,Kt,lc=w(()=>{"use strict";cc=require("tiktoken"),Kt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,cc.get_encoding)(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)}}});var Gt,uc,kt,Qt,dc,Mo,pc=w(()=>{"use strict";Gt=require("path"),uc=require("os"),kt=require("fs"),Qt=require("fs"),dc=require("@huggingface/tokenizers"),Mo=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||(0,Gt.join)((0,uc.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,Gt.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,Gt.join)(e,"tokenizer.json"),tokenizerConfig:(0,Gt.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,kt.existsSync)(e)||(0,kt.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,kt.existsSync)(e.tokenizerJson)||!(0,kt.existsSync)(e.tokenizerConfig))return null;let[t,o]=await Promise.all([Qt.promises.readFile(e.tokenizerJson,"utf-8"),Qt.promises.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([Qt.promises.writeFile(e.tokenizerJson,JSON.stringify(i,null,2)),Qt.promises.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 dc.Tokenizer(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 Lo,fc=w(()=>{"use strict";ae();Lo=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=X(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(`
|
|
296
|
+
`):typeof t.content=="string"?t.content:JSON.stringify(t.content):"").join(" "):""}extractConcatenatedText(e){let t=[];return e.messages&&e.messages.forEach(o=>{t.push(this.extractTextFromMessage(o))}),typeof e.system=="string"?t.push(e.system):Array.isArray(e.system)&&e.system.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?t.push(o.text):Array.isArray(o.text)&&o.text.forEach(r=>{r&&t.push(r)}))}),e.tools&&e.tools.forEach(o=>{o.name&&t.push(o.name),o.description&&t.push(o.description),o.input_schema&&t.push(JSON.stringify(o.input_schema))}),t.join(" ")}extractTokenCount(e){try{let t=this.config.responseField,o=t.split("."),r=e;for(let s of o){if(r==null)throw new Error(`Field path '${t}' not found in response`);r=r[s]}if(typeof r!="number")throw new Error(`Expected number at field path '${t}', got ${typeof r}`);return r}catch(t){throw this.logger?.error(`Failed to extract token count from API response: ${t.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${t.message}`)}}}});var Ze,Zr=w(()=>{"use strict";lc();pc();fc();ae();Ze=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new Kt("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 Kt(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Mo(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Lo(e,this.logger,{timeout:this.options.timeout,resolveProxyUrl:()=>{let s=t?this.getRawProvider(t):void 0;return he(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 mc(n){if(!n||typeof n!="object"||jd(n))return null;for(let t of Fd(n)){let o=Dd(t);if(o)return o}return null}function Dd(n){if(!n||typeof n!="object")return null;let e={},t=$o(n,Ld);if(t!==void 0){let a=gc(t);e.usedDailyBalance=a,e.limitDaily=100}let o=$o(n,$d);if(o!==void 0){let a=gc(o);e.usedBalance=a,e.totalBalance=100}let r=$o(n,Nd);if(r!==void 0){let a=hc(r);a&&(e.resetTime=a)}let s=$o(n,Ud);if(s!==void 0){let a=hc(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 gc(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function $o(n,e){for(let t of e){let o=D(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 jd(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function hc(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 No(n){let e=us(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Qd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Vd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Hd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?zd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Bd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Jd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Wd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Kd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Gd:null:null}function Yd(n){let e=us(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Xd(n,e){let t=cs(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 cs(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>cs(e)):Object.values(n).flatMap(e=>cs(e))}function ls(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function us(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function D(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var pe,qr,es,ts,ns,os,Ld,$d,Nd,Ud,rs,ss,is,as,Hd,zd,Bd,Jd,Wd,Kd,Gd,Qd,Vd,ds=w(()=>{"use strict";ae();pe=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=X(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}},qr=class extends pe{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=>D(l?.total_balance)!==void 0);if(!a)return null;let i=D(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},es=class extends pe{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=D(s.limit),l=D(s.limit_remaining),c=D(s.usage),u=D(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}},ts=class extends pe{async queryQuota(e,t,o){let r=Yd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},l=D(a.totalBalance),c=D(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}},ns=class extends pe{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=X(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=D(c.currentValue),g=D(c.usage),h=D(c.remaining),m=D(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=D(u.currentValue),g=D(u.usage),h=D(u.remaining),m=D(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),g!==void 0?d.totalBalance=g:f!==void 0&&h!==void 0&&(d.totalBalance=f+h),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=D(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=D(p.usage),g=D(p.currentValue),h=D(p.remaining);f!==void 0?d.limitDaily=f:g!==void 0&&h!==void 0&&(d.limitDaily=g+h)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},os=class extends pe{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=X(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=D(u.per5HourUsedQuota),f=D(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let g=D(u.perWeekUsedQuota),h=D(u.perWeekTotalQuota);return g!==void 0&&(p.usedBalance=g),h!==void 0&&(p.totalBalance=h),this.hasQuotaData(p)?p:null}catch{return null}}};Ld=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],$d=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],Nd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Ud=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];rs=class extends pe{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=ls(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=X(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 mc(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=X(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 mc(c)}catch{return null}}},ss=class extends pe{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:(ls(e.quotaToken,"atp-auth-token")||ls(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=X(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=Xd(i,e.apiKey),c=l?.codingPlanUsageDTO||l?.usage||l;if(!c||typeof c!="object")return null;let u={},p=D(c.rp5hUsage),d=D(c.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=D(c.rpwUsage),g=D(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}}},is=class extends pe{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=X(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=D(p.limit),f=D(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=D(u.limit),d=D(u.remaining),f=D(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}}},as=class extends pe{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=us(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=D(u.current_interval_total_count),f=D(u.current_interval_usage_count),g=D(u.current_interval_remaining_percent),h=D(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):g!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-g)),h&&(p.resetTime=new Date(h).toISOString());let m=D(u.current_weekly_total_count),y=D(u.current_weekly_usage_count),b=D(u.current_weekly_remaining_percent),_=D(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Hd=new qr,zd=new es,Bd=new ts,Jd=new ns,Wd=new os,Kd=new rs,Gd=new ss,Qd=new is,Vd=new as});async function Uo(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=yc.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<Zd)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}})(),yc.set(n,r),r.pending}var Zd,_c,yc,ps=w(()=>{"use strict";Ke();Zd=6e4,_c=2500,yc=new Map});function bc(n){return{[qd]:n,[ep]:Ln}}function Le(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function np(n){return n===!0||n==="true"||n===1||n==="1"}function op(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 rp(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 sp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function fs(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Le(n))return{success:!1,skipped:!0,error:ms,latencyMs:r()};let s=rp(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=X(t));let i=await fetch(s,a);if(i.headers&&$t(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 ip(n,e,t,o){if(Le(n))return{success:!1,skipped:!0,error:ms};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",...bc("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=X(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 ap(n,e,t,o,r){if(Le(n))return{success:!1,skipped:!0,error:ms};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...bc("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=X(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 gs(n,e,t,o,r,s){return $e||($e=new Vt(n,e,t,o,r,s)),$e}function vt(n,e,t,o,r,s){let a=gs(n,e,t,o,r,s);return a.start(),a}function Do(){$e&&$e.stop()}function Fo(){$e&&($e.stop(),$e=null)}var qd,ep,tp,ms,Vt,$e,jo=w(()=>{"use strict";ue();We();ds();Ke();ps();mr();ae();qd="x-claude-code-router-source",ep="x-claude-code-router-version";tp={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};ms="Managed provider requires its plugin's authenticated model sync";Vt=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={...tp,...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&&!Le(s)&&!this.config.excludeProviders.includes(s.name)),t=z(),o=[];for(let s of e){let a=No(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`))}}})}),sp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:fs(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&&Le(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:Uo(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=z(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Le(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=>fs(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=z();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=z(),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&&Le(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 ap(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&&!Le(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=op(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}`),ip(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?np(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 fs(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)z().recordSuccess(o.name,i);else for(let i of a)z().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 kc=w(()=>{"use strict"});var hs,Tt,vc=w(()=>{"use strict";hs=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()}},Tt=new hs});var le,ys=w(()=>{"use strict";le=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,t)=>{this.buffer+=e;let o=this.buffer.split(`
|
|
297
|
+
`);this.buffer=o.pop()||"";for(let r of o){let s=this.processLine(r);s&&t.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let t=[];this.processLine(this.buffer.trim(),t),t.forEach(o=>e.enqueue(o))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,t){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let o={...this.currentEvent};return this.currentEvent={},t?(t.push(o),null):o}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let o=e.slice(5).trim();if(o==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(o)}catch{this.currentEvent.data={raw:o,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}}});var qe,_s=w(()=>{"use strict";qe=class extends TransformStream{constructor(){super({transform:(e,t)=>{let o="";e.event&&(o+=`event: ${e.event}
|
|
292
298
|
`),e.id&&(o+=`id: ${e.id}
|
|
293
299
|
`),e.retry&&(o+=`retry: ${e.retry}
|
|
294
300
|
`),e.data&&(e.data.type==="done"?o+=`data: [DONE]
|
|
295
301
|
`:o+=`data: ${JSON.stringify(e.data)}
|
|
296
302
|
`),o+=`
|
|
297
|
-
`,t.enqueue(o)}})}}});var Yt,
|
|
303
|
+
`,t.enqueue(o)}})}}});var Yt,bs=w(()=>{"use strict";Yt=(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 ks=w(()=>{"use strict";ys();_s();bs()});var Tc=w(()=>{"use strict"});var Xt,vs=w(()=>{"use strict";Xt=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+=`
|
|
298
304
|
`+(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}-
|
|
299
305
|
${this.toMarkdown(r,t+1)}`:`${o}- ${r}`).join(`
|
|
300
306
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([r,s])=>typeof s=="object"&&s!==null?`${o}${r}:
|
|
301
307
|
${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
302
|
-
`):`${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 Zt,_s=P(()=>{"use strict";Zt=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}`)}}}});async function jo(n,e){let t=(0,et.resolve)(n),o=Fo.get(t),r,s=new Promise(a=>{r=a});Fo.set(t,s);try{return await o,await e()}finally{r(),Fo.get(t)===s&&Fo.delete(t)}}function Tc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function bc(n,e){try{let t=await(0,we.lstat)(n);return t.isDirectory()&&!t.isSymbolicLink()&&Tc(e,t)}catch{return!1}}function lp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function vc(n,e,t,o){let r=(0,et.resolve)(n);if(o?.aborted||bs.has(r))return 0;bs.add(r);let s=0;try{let a=await(0,we.lstat)(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await(0,we.opendir)(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=(0,et.join)(r,u.name);try{let d=await(0,we.lstat)(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await jo(p,async()=>{if(o?.aborted||!await bc(r,a))return!1;let g=await(0,we.lstat)(p);return!g.isFile()||g.isSymbolicLink()||!Tc(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await(0,we.unlink)(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await lp(),l=!o?.aborted&&await bc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{bs.delete(r)}return s}function xc(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return vc(n,Date.now()-o,i=>cp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function up(n,e){let t=Date.now()-sp;return vc(n,t,o=>{let r=ap.exec(o);return r!==null&&Number(r[1])<t},e)}function Ts(n,e,t){let o=ks.get(n);if(!o){let s=new AbortController,a,i=()=>{s.signal.aborted||Promise.resolve().then(()=>e(s.signal)).catch(()=>{})},c=setTimeout(()=>{s.signal.aborted||(i(),a=setInterval(i,ip),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},ks.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),ks.delete(n)))}}function Sc(n=(0,et.join)((0,kc.tmpdir)(),"claude-code-router")){return Ts(`legacy:${(0,et.resolve)(n)}`,e=>up(n,e),1e3)}var we,et,kc,sp,ip,ap,cp,bs,Fo,ks,vs=P(()=>{"use strict";we=require("node:fs/promises"),et=require("node:path"),kc=require("node:os"),sp=3600*1e3,ip=600*1e3,ap=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,cp=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,bs=new Set,Fo=new Map,ks=new Map});var be,Cc,Rc,Ne,wc,qt,xs=P(()=>{"use strict";be=require("node:fs/promises"),Cc=require("node:crypto"),Rc=require("@wengine-ai/claude-code-router-shared"),Ne=require("node:path"),wc=require("node:os");vs();qt=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=(0,Ne.resolve)((0,Ne.join)((0,wc.tmpdir)(),this.config.subdirectory)),Number.isFinite(this.config.retentionMs)&&this.config.retentionMs>0){let t=JSON.stringify([this.baseDir,this.config.prefix,this.config.extension,this.config.retentionMs]);this.stopSchedule=Ts(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await(0,be.mkdir)(this.baseDir,{recursive:!0});let e=await(0,be.lstat)(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}-${(0,Rc.sanitizeTempFileKey)(e)}${r}${o}`;if((0,Ne.basename)(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return(0,Ne.join)(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 jo(a,async()=>{await this.ensureDir();let i=(0,Ne.join)(this.baseDir,`.ccr-tmp-${process.pid}-${(0,Cc.randomUUID)()}.tmp`);return jo(i,async()=>{let c=!1;try{let l=await(0,be.open)(i,"wx");c=!0;try{await l.writeFile(s,"utf-8")}finally{await l.close()}return await(0,be.rename)(i,a),!0}finally{c&&await(0,be.unlink)(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return xc(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Ss,xt,Pc=P(()=>{"use strict";ys();_s();xs();Ss=class{handlers=new Map;defaultOptions={};registerHandler(e,t){this.handlers.set(e,t)}registerHandlers(e){for(let t of e)if(t.enabled!==!1)try{let o=this.createHandler(t),r=t.type+"_"+Date.now();this.registerHandler(r,o)}catch(o){console.error(`[OutputManager] Failed to register ${t.type} handler:`,o)}}createHandler(e){switch(e.type){case"console":return new Xt(e.config);case"webhook":return new Zt(e.config);case"temp-file":return new qt(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)}},xt=new Ss});var Cs=P(()=>{"use strict";_c();ys();_s();xs();Pc()});function Ho(){return{subdirectory:Ic.TOKEN_SPEED_TEMP_SUBDIRECTORY,extension:"json",includeTimestamp:!1,prefix:"session"}}function Ec(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,dp);return Math.round(n/o)}function tn(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Ac(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 xt.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var Oc,Ic,en,Rs,dp,nn,Mc=P(()=>{"use strict";Oc=ee(require("fastify-plugin"),1);hs();Cs();dt();Ic=require("@wengine-ai/claude-code-router-shared");en=new Map,Rs=new Map,dp=1,nn={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,Oc.default)(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)xt.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:Ho()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&xt.registerHandlers(a)}t.outputOptions&&xt.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(Rs.has(u))return Rs.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 Rs.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=Re(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(c instanceof ReadableStream){en.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=c.tee(),_=async()=>{let k=null,T=async S=>{let v=en.get(u);if(!v)return;let w=v.firstTokenTime?v.firstTokenTime-v.startTime:0,E=(S?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Ec(v.tokenCount,E,w),await Ac(v,o,t.outputOptions,S).catch(M=>{n.log?.warn(`Failed to output streaming stats: ${M.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new le).getReader();for(k=setInterval(async()=>{en.get(u)&&await T(!1)},1e3);;){let{done:w,value:R}=await v.read();if(w)break;let E=R,M=en.get(u);if(!M)continue;let D=performance.now(),C=E.event||E.data?.type,O=E.event==="content_block_start"||E.event==="content_block_delta"||E.event==="text_block"||E.event==="content_block"||C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta";!M.firstTokenTime&&O&&(M.firstTokenTime=D,M.timeToFirstToken=Math.round(D-M.startTime));let x="";if(E.event==="content_block_delta"&&E.data?.delta){let I=E.data.delta.type;I==="text_delta"?x=E.data.delta.text||"":I==="input_json_delta"?x=E.data.delta.partial_json||"":I==="thinking_delta"&&(x=E.data.delta.thinking||"")}if((C==="response.output_text.delta"||C==="response.function_call_arguments.delta"||C==="response.reasoning_summary_text.delta")&&(x=typeof E.data?.delta=="string"?E.data.delta:""),x){let I=f&&f.encodeText?f.encodeText(x).length:tn(x);M.tokenCount+=I,M.lastTokenTime=D}(E.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),en.delete(u))}}catch(S){k&&clearInterval(k),S.name!=="AbortError"&&S.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${S.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let g=performance.now(),h=0,m=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")h=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?h=b.reduce((_,k)=>{if(k.type==="text"){let T=k.text||"";return _+(f.encodeText?f.encodeText(T).length:tn(T))}return _},0):typeof b=="string"&&(h=f.encodeText?f.encodeText(b).length:tn(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";h=tn(_)}}}catch{}if(m){let y=g-l,b={requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:g,tokenCount:h,tokensPerSecond:Ec(h,y),stream:!1};await Ac(b,o,t.outputOptions,!0)}return c})})}});var ws=P(()=>{"use strict";hc();yc();Mc();Cs()});function Lc(){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 ie,Es,Ue,Y,Ps,on,rn,St,ne,sn,fe,pp,zo,an=P(()=>{"use strict";ie=ee(require("node:fs/promises"),1),Es=ee(require("json5"),1),Ue=ee(require("node:path"),1),Y=require("@wengine-ai/claude-code-router-shared"),Ps=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(Ps);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Ps(o);return e}return n},on=async n=>{try{await ie.default.access(n)}catch{await ie.default.mkdir(n,{recursive:!0})}},rn=async()=>{await on(Y.HOME_DIR),await on(Y.PLUGINS_DIR),await on(Ue.default.join(Y.HOME_DIR,"logs"))},St=async()=>{let n=await ie.default.readFile(Y.CONFIG_FILE,"utf-8");return Es.default.parse(n)},ne=async()=>{try{let n=await ie.default.readFile(Y.CONFIG_FILE,"utf-8");try{let e=Es.default.parse(n);return Ps(e)}catch(e){console.error(`Failed to parse config file at ${Y.CONFIG_FILE}`),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 rn();let e=await sn();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await fe(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${Y.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};sn=async()=>{Lc();try{if(await ie.default.access(Y.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${Y.CONFIG_FILE}.${n}.bak`;await ie.default.copyFile(Y.CONFIG_FILE,e);try{let t=Ue.default.dirname(Y.CONFIG_FILE),o=Ue.default.basename(Y.CONFIG_FILE),s=(await ie.default.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=Ue.default.join(t,s[a]);await ie.default.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},fe=async n=>{Lc(),await on(Y.HOME_DIR),await pp();let e=`${JSON.stringify(n,null,2)}`;await ie.default.writeFile(Y.CONFIG_FILE,e)},pp=async()=>{if(!await ie.default.access(Y.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=Ue.default.join(Y.HOME_DIR,"config-history");await on(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ue.default.join(e,`config-${t}.json`);await ie.default.copyFile(Y.CONFIG_FILE,o);try{let s=(await ie.default.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ie.default.unlink(Ue.default.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},zo=async()=>{let n=await ne();return Object.assign(process.env,n),n}});function Bo(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(As(r,s))}return}if(Array.isArray(n)){for(let o of n)Bo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))Bo(o,e,t)}}function Os(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(As(s,i))}return Bo(n?.Router,t,o),Bo(n?.fallback,t,o),o}function Ct(n,e){try{let t=z();if(!t?.getAllStates||!t?.recover)return 0;let o=Os(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(As(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 cn(n,e){try{if(!n)return 0;let t=z();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 fp,As,ln=P(()=>{"use strict";ue();fp="\0",As=(n,e)=>`${n}${fp}${e}`});function mp(n){return/\[1m\]/i.test(n)?1e6:2e5}function gp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function hp(n,e=n){let t=mp(n),o=gp(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 yp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Jo(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,hp(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=yp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var Is=P(()=>{"use strict"});function _p(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var un,Ms=P(()=>{"use strict";un=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||_p(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 Fs={};vn(Fs,{append:()=>hn,clear:()=>Us,close:()=>Lp,getOldestRecordTimestamp:()=>$p,query:()=>Ns,querySummary:()=>yn,readTokenSpeedStats:()=>Ds});function xp(){(0,je.existsSync)(Ko)||(0,je.mkdirSync)(Ko,{recursive:!0})}function gn(){if(Fe)return Fe;xp();let n=(0,Dc.openSqliteDatabase)(bp),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&&(Sp(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")),Rp(e),Hc(e,!0),$s=e.prepare(`
|
|
308
|
+
`):`${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 Zt,Ts=w(()=>{"use strict";Zt=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}`)}}}});async function zo(n,e){let t=(0,et.resolve)(n),o=Ho.get(t),r,s=new Promise(a=>{r=a});Ho.set(t,s);try{return await o,await e()}finally{r(),Ho.get(t)===s&&Ho.delete(t)}}function Cc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function xc(n,e){try{let t=await(0,we.lstat)(n);return t.isDirectory()&&!t.isSymbolicLink()&&Cc(e,t)}catch{return!1}}function fp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Rc(n,e,t,o){let r=(0,et.resolve)(n);if(o?.aborted||xs.has(r))return 0;xs.add(r);let s=0;try{let a=await(0,we.lstat)(r);if(!a.isDirectory()||a.isSymbolicLink()||o?.aborted)return 0;let i=await(0,we.opendir)(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=(0,et.join)(r,u.name);try{let d=await(0,we.lstat)(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await zo(p,async()=>{if(o?.aborted||!await xc(r,a))return!1;let g=await(0,we.lstat)(p);return!g.isFile()||g.isSymbolicLink()||!Cc(d,g)||g.mtimeMs!==d.mtimeMs||g.mtimeMs>=e||o?.aborted?!1:(await(0,we.unlink)(p),!0)})&&s++}catch{}}finally{++l%64===0&&(await fp(),c=!o?.aborted&&await xc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{xs.delete(r)}return s}function wc(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Rc(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 Rc(n,t,o=>{let r=dp.exec(o);return r!==null&&Number(r[1])<t},e)}function Cs(n,e,t){let o=Ss.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,up),a.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),a&&clearInterval(a)}},Ss.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),Ss.delete(n)))}}function Pc(n=(0,et.join)((0,Sc.tmpdir)(),"claude-code-router")){return Cs(`legacy:${(0,et.resolve)(n)}`,e=>mp(n,e),1e3)}var we,et,Sc,lp,up,dp,pp,xs,Ho,Ss,Rs=w(()=>{"use strict";we=require("node:fs/promises"),et=require("node:path"),Sc=require("node:os"),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$/,xs=new Set,Ho=new Map,Ss=new Map});var be,Ec,Ac,Ne,Oc,qt,ws=w(()=>{"use strict";be=require("node:fs/promises"),Ec=require("node:crypto"),Ac=require("@wengine-ai/claude-code-router-shared"),Ne=require("node:path"),Oc=require("node:os");Rs();qt=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=(0,Ne.resolve)((0,Ne.join)((0,Oc.tmpdir)(),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=Cs(`handler:${t}`,o=>this.pruneOldFiles(o),6e4)}}async ensureDir(){await(0,be.mkdir)(this.baseDir,{recursive:!0});let e=await(0,be.lstat)(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}-${(0,Ac.sanitizeTempFileKey)(e)}${r}${o}`;if((0,Ne.basename)(s)!==s||s.includes("\\"))throw new Error("Temp file configuration must not contain path separators");return(0,Ne.join)(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 zo(a,async()=>{await this.ensureDir();let i=(0,Ne.join)(this.baseDir,`.ccr-tmp-${process.pid}-${(0,Ec.randomUUID)()}.tmp`);return zo(i,async()=>{let l=!1;try{let c=await(0,be.open)(i,"wx");l=!0;try{await c.writeFile(s,"utf-8")}finally{await c.close()}return await(0,be.rename)(i,a),!0}finally{l&&await(0,be.unlink)(i).catch(()=>{})}})})}catch{return!1}}pruneOldFiles(e=this.controller.signal){return wc(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var Ps,xt,Ic=w(()=>{"use strict";vs();Ts();ws();Ps=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 Xt(e.config);case"webhook":return new Zt(e.config);case"temp-file":return new qt(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)}},xt=new Ps});var Es=w(()=>{"use strict";Tc();vs();Ts();ws();Ic()});function Bo(){return{subdirectory:Nc.TOKEN_SPEED_TEMP_SUBDIRECTORY,extension:"json",includeTimestamp:!1,prefix:"session"}}function Mc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,gp);return Math.round(n/o)}function tn(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Lc(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 xt.outputToType(i,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,l)}}var $c,Nc,en,As,gp,nn,Uc=w(()=>{"use strict";$c=ee(require("fastify-plugin"),1);ks();Es();dt();Nc=require("@wengine-ai/claude-code-router-shared");en=new Map,As=new Map,gp=1,nn={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,$c.default)(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)xt.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:Bo()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&xt.registerHandlers(a)}t.outputOptions&&xt.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(As.has(u))return As.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 As.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=Re(a.body?.metadata?.user_id)||p}catch{d=p}let f=await r(a);if(l instanceof ReadableStream){en.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:c,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=l.tee(),_=async()=>{let k=null,v=async x=>{let T=en.get(u);if(!T)return;let P=T.firstTokenTime?T.firstTokenTime-T.startTime:0,R=(x?T.lastTokenTime:performance.now())-T.startTime;T.tokensPerSecond=Mc(T.tokenCount,R,P),await Lc(T,o,t.outputOptions,x).catch(O=>{n.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let T=b.pipeThrough(new TextDecoderStream).pipeThrough(new le).getReader();for(k=setInterval(async()=>{en.get(u)&&await v(!1)},1e3);;){let{done:P,value:A}=await T.read();if(P)break;let R=A,O=en.get(u);if(!O)continue;let F=performance.now(),C=R.event||R.data?.type,I=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";!O.firstTokenTime&&I&&(O.firstTokenTime=F,O.timeToFirstToken=Math.round(F-O.startTime));let S="";if(R.event==="content_block_delta"&&R.data?.delta){let M=R.data.delta.type;M==="text_delta"?S=R.data.delta.text||"":M==="input_json_delta"?S=R.data.delta.partial_json||"":M==="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 M=f&&f.encodeText?f.encodeText(S).length:tn(S);O.tokenCount+=M,O.lastTokenTime=F}(R.event==="message_stop"||C==="response.completed"||C==="response.failed")&&(k&&(clearInterval(k),k=null),await v(!0),en.delete(u))}}catch(x){k&&clearInterval(k),x.name!=="AbortError"&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${x.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let g=performance.now(),h=0,m=!1;if(l&&typeof l=="string")try{let y=JSON.parse(l);if(typeof y.usage?.output_tokens=="number")h=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?h=b.reduce((_,k)=>{if(k.type==="text"){let v=k.text||"";return _+(f.encodeText?f.encodeText(v).length:tn(v))}return _},0):typeof b=="string"&&(h=f.encodeText?f.encodeText(b).length:tn(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";h=tn(_)}}}catch{}if(m){let y=g-c,b={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:g,tokenCount:h,tokensPerSecond:Mc(h,y),stream:!1};await Lc(b,o,t.outputOptions,!0)}return l})})}});var Os=w(()=>{"use strict";kc();vc();Uc();Es()});function Dc(){if(process.env.VITEST||process.env.CI)throw new Error("Config write attempted during test/CI. Set CCR_CONFIG_DIR to a temp dir to isolate.")}var ie,Ms,Ue,Y,Is,on,rn,St,ne,sn,fe,hp,Jo,an=w(()=>{"use strict";ie=ee(require("node:fs/promises"),1),Ms=ee(require("json5"),1),Ue=ee(require("node:path"),1),Y=require("@wengine-ai/claude-code-router-shared"),Is=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(Is);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Is(o);return e}return n},on=async n=>{try{await ie.default.access(n)}catch{await ie.default.mkdir(n,{recursive:!0})}},rn=async()=>{await on(Y.HOME_DIR),await on(Y.PLUGINS_DIR),await on(Ue.default.join(Y.HOME_DIR,"logs"))},St=async()=>{let n=await ie.default.readFile(Y.CONFIG_FILE,"utf-8");return Ms.default.parse(n)},ne=async()=>{try{let n=await ie.default.readFile(Y.CONFIG_FILE,"utf-8");try{let e=Ms.default.parse(n);return Is(e)}catch(e){console.error(`Failed to parse config file at ${Y.CONFIG_FILE}`),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 rn();let e=await sn();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await fe(t),console.log("Created minimal default configuration file at ~/.claude-code-router/config.json"),console.log("Please edit this file with your actual configuration."),t}catch(e){console.error("Failed to create default configuration:",e.message),process.exit(1)}else console.error(`Failed to read config file at ${Y.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};sn=async()=>{Dc();try{if(await ie.default.access(Y.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${Y.CONFIG_FILE}.${n}.bak`;await ie.default.copyFile(Y.CONFIG_FILE,e);try{let t=Ue.default.dirname(Y.CONFIG_FILE),o=Ue.default.basename(Y.CONFIG_FILE),s=(await ie.default.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=Ue.default.join(t,s[a]);await ie.default.unlink(i)}}catch(t){console.warn("Failed to clean up old backups:",t)}return e}}catch(n){console.error("Failed to backup config file:",n)}return null},fe=async n=>{Dc(),await on(Y.HOME_DIR),await hp();let e=`${JSON.stringify(n,null,2)}`;await ie.default.writeFile(Y.CONFIG_FILE,e)},hp=async()=>{if(!await ie.default.access(Y.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=Ue.default.join(Y.HOME_DIR,"config-history");await on(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=Ue.default.join(e,`config-${t}.json`);await ie.default.copyFile(Y.CONFIG_FILE,o);try{let s=(await ie.default.readdir(e)).filter(a=>a.startsWith("config-")&&a.endsWith(".json")).sort().reverse();if(s.length>50)for(let a of s.slice(50))await ie.default.unlink(Ue.default.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},Jo=async()=>{let n=await ne();return Object.assign(process.env,n),n}});function Wo(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(Ls(r,s))}return}if(Array.isArray(n)){for(let o of n)Wo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))Wo(o,e,t)}}function $s(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(Ls(s,i))}return Wo(n?.Router,t,o),Wo(n?.fallback,t,o),o}function Ct(n,e){try{let t=z();if(!t?.getAllStates||!t?.recover)return 0;let o=$s(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(Ls(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 cn(n,e){try{if(!n)return 0;let t=z();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 yp,Ls,ln=w(()=>{"use strict";ue();yp="\0",Ls=(n,e)=>`${n}${yp}${e}`});function _p(n){return/\[1m\]/i.test(n)?1e6:2e5}function bp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function kp(n,e=n){let t=_p(n),o=bp(n);return{type:"model",id:n,display_name:e,created_at:"2024-01-01T00:00:00Z",context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o,capabilities:{context_window:t,contextWindow:t,max_input_tokens:t,maxInputTokens:t,max_tokens:o,maxTokens:o,max_output_tokens:o,maxOutputTokens:o}}}function vp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Ko(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,kp(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=vp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var Ns=w(()=>{"use strict"});function Tp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var un,Us=w(()=>{"use strict";un=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||Tp(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 Bs={};xn(Bs,{append:()=>hn,clear:()=>Hs,close:()=>Dp,getOldestRecordTimestamp:()=>Fp,query:()=>js,querySummary:()=>yn,readTokenSpeedStats:()=>zs});function wp(){(0,je.existsSync)(Qo)||(0,je.mkdirSync)(Qo,{recursive:!0})}function gn(){if(Fe)return Fe;wp();let n=(0,zc.openSqliteDatabase)(xp),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&&(Pp(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")),Ap(e),Wc(e,!0),Fs=e.prepare(`
|
|
303
309
|
INSERT INTO usage_records (
|
|
304
310
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
305
311
|
scenario_type, client_type,
|
|
@@ -313,7 +319,7 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
313
319
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
314
320
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
315
321
|
)
|
|
316
|
-
`),Fe=e,Fe}function
|
|
322
|
+
`),Fe=e,Fe}function Pp(n){n.exec(`
|
|
317
323
|
CREATE TABLE IF NOT EXISTS usage_records (
|
|
318
324
|
id TEXT PRIMARY KEY,
|
|
319
325
|
timestamp TEXT NOT NULL,
|
|
@@ -350,12 +356,12 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
350
356
|
CREATE INDEX IF NOT EXISTS idx_usage_records_scenario_timestamp ON usage_records(scenario_type, timestamp);
|
|
351
357
|
CREATE INDEX IF NOT EXISTS idx_usage_records_client_timestamp ON usage_records(client_type, timestamp);
|
|
352
358
|
CREATE INDEX IF NOT EXISTS idx_usage_records_session_timestamp ON usage_records(session_id, timestamp);
|
|
353
|
-
`)}function
|
|
359
|
+
`)}function Ep(n,e){return n.prepare("SELECT value FROM usage_meta WHERE key = ?").get(e)?.value}function dn(n,e,t){n.prepare(`
|
|
354
360
|
INSERT INTO usage_meta (key, value)
|
|
355
361
|
VALUES (?, ?)
|
|
356
362
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
357
|
-
`).run(e,t)}function
|
|
358
|
-
`)){let
|
|
363
|
+
`).run(e,t)}function Ap(n){if(Ep(n,Fc)||!(0,je.existsSync)(Ds))return;let e=Ip(n,"INSERT OR IGNORE"),t=(0,je.readFileSync)(Ds,"utf-8"),o=0,r=0,s=0;n.transaction(()=>{for(let i of t.split(`
|
|
364
|
+
`)){let l=i.trim();if(l)try{let c=JSON.parse(l);if(!Op(c)){r++;continue}e.run(Jc(Vo(c))).changes>0?o++:s++}catch{r++}}dn(n,Fc,new Date().toISOString()),dn(n,"legacy_usage_jsonl_migrated_path",Ds),dn(n,"legacy_usage_jsonl_imported_count",String(o)),dn(n,"legacy_usage_jsonl_skipped_count",String(r)),dn(n,"legacy_usage_jsonl_duplicate_count",String(s))})()}function Op(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 Ip(n,e="INSERT"){return n.prepare(`
|
|
359
365
|
${e} INTO usage_records (
|
|
360
366
|
id, timestamp, session_id, provider, original_model, model, upstream_model, model_family,
|
|
361
367
|
scenario_type, client_type,
|
|
@@ -369,11 +375,11 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
369
375
|
@cache_read_input_tokens, @cache_creation_input_tokens, @ttft,
|
|
370
376
|
@tokens_per_second, @duration_ms, @status, @error_message, @response_body
|
|
371
377
|
)
|
|
372
|
-
`)}function
|
|
373
|
-
SELECT ${t} AS key, ${
|
|
378
|
+
`)}function Mp(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,Sp);return Math.round(n/r)}function Vo(n){let e=Number(n.outputTokens)||0,t=Number(n.durationMs),o=Number.isFinite(t)?t:null,r=n.stream?fn(n.ttft):null;return{...n,ttft:r,tokensPerSecond:Mp(e,o,r)}}function De(n){return typeof n=="string"?n:n==null?"":String(n)}function Go(n){if(n==null)return;let e=String(n);return e.length>0?e:void 0}function pn(n){let e=Number(n);return Number.isFinite(e)?e:0}function Bc(n){return n==="success"?"success":"error"}function Jc(n){let e=Vo(n);return{id:De(e.id),timestamp:De(e.timestamp),session_id:De(e.sessionId),provider:De(e.provider),original_model:De(e.originalModel),model:De(e.model),upstream_model:Go(e.upstreamModel)??null,model_family:De(e.modelFamily),scenario_type:De(e.scenarioType),client_type:Go(e.clientType)??null,stream:e.stream?1:0,usage_estimated:e.usageEstimated===!0?1:0,input_tokens:Math.trunc(pn(e.inputTokens)),output_tokens:Math.trunc(pn(e.outputTokens)),cache_read_input_tokens:Math.trunc(pn(e.cacheReadInputTokens)),cache_creation_input_tokens:Math.trunc(pn(e.cacheCreationInputTokens)),ttft:fn(e.ttft),tokens_per_second:fn(e.tokensPerSecond),duration_ms:Math.trunc(pn(e.durationMs)),status:Bc(e.status),error_message:Go(e.errorMessage)??null,response_body:Go(e.responseBody)??null}}function Lp(n){return Vo({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:Bc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function $p(){return new Date(Date.now()-Cp*24*60*60*1e3).toISOString()}function Wc(n,e=!1){let t=Date.now();!e&&t-jc<Rp||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run($p()),jc=t)}function Kc(n){let e=[],t=[];return n.startTime&&(e.push("timestamp >= ?"),t.push(n.startTime)),n.endTime&&(e.push("timestamp <= ?"),t.push(n.endTime)),n.model&&(e.push("model = ?"),t.push(n.model)),n.provider&&(e.push("provider = ?"),t.push(n.provider)),n.scenario&&(e.push("scenario_type = ?"),t.push(n.scenario)),n.clientType&&(n.clientType==="unknown"?(e.push("(client_type IS NULL OR client_type = '' OR client_type = ?)"),t.push(n.clientType)):(e.push("client_type = ?"),t.push(n.clientType))),n.sessionId&&(e.push("session_id = ?"),t.push(n.sessionId)),n.status&&(e.push("status = ?"),t.push(n.status)),{sql:e.length>0?`WHERE ${e.join(" AND ")}`:"",params:t}}function Rt(n,e,t,o=""){let r=o?e.sql?`${e.sql} AND ${o}`:`WHERE ${o}`:e.sql,s=n.prepare(`
|
|
379
|
+
SELECT ${t} AS key, ${Np}
|
|
374
380
|
FROM usage_records ${r}
|
|
375
381
|
GROUP BY key
|
|
376
|
-
`).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
|
|
382
|
+
`).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 Gc(n,e){let t=Kc(e),o=n.prepare(`
|
|
377
383
|
SELECT
|
|
378
384
|
COUNT(*) AS totalRequests,
|
|
379
385
|
COALESCE(SUM(usage_estimated), 0) AS estimatedCount,
|
|
@@ -385,14 +391,14 @@ ${this.toMarkdown(s,t+1)}`:`${o}${r}: ${s}`).join(`
|
|
|
385
391
|
AVG(CASE WHEN status = 'success' AND ttft IS NOT NULL THEN ttft END) AS avgTtft,
|
|
386
392
|
AVG(CASE WHEN status = 'success' AND tokens_per_second IS NOT NULL THEN tokens_per_second END) AS avgTokensPerSecond
|
|
387
393
|
FROM usage_records ${t.sql}
|
|
388
|
-
`).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:Rt(n,t,"model"),byProvider:Rt(n,t,"provider"),byScenario:Rt(n,t,"scenario_type"),byFamily:Rt(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:Rt(n,t,"date(timestamp, 'localtime')"),byClient:Rt(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function hn(n){let e=gn(),t=
|
|
394
|
+
`).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:Rt(n,t,"model"),byProvider:Rt(n,t,"provider"),byScenario:Rt(n,t,"scenario_type"),byFamily:Rt(n,t,"model_family || '/' || scenario_type","model_family IS NOT NULL AND model_family != ''"),byDay:Rt(n,t,"date(timestamp, 'localtime')"),byClient:Rt(n,t,"CASE WHEN client_type IS NULL OR client_type = '' THEN 'unknown' ELSE client_type END")}}function hn(n){let e=gn(),t=Vo(n);Fs.run(Jc(t)),Wc(e)}function js(n){let e=gn(),t=Kc(n),o=Number.isFinite(n.page)&&n.page>0?Math.floor(n.page):1,r=Number.isFinite(n.pageSize)&&n.pageSize>0?Math.min(Math.floor(n.pageSize),Up):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=Gc(e,n);return{records:i.map(Lp),summary:l,total:a.count,page:o,pageSize:r}}function yn(n,e,t){let o=gn();return Gc(o,{startTime:n,endTime:e,status:t})}function Hs(n){let e=gn();if(!n){e.prepare("DELETE FROM usage_records").run();return}e.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(n)}function Dp(){Fe&&(Fe.pragma("wal_checkpoint(TRUNCATE)"),Fe.close(),Fe=null,Fs=null)}function fn(n){if(n==null)return null;if(typeof n=="number")return n;let e=parseFloat(String(n));return isNaN(e)?null:e}function zs(n){let e=(0,mn.join)((0,Hc.tmpdir)(),wt.TOKEN_SPEED_TEMP_SUBDIRECTORY,`session-${(0,wt.sanitizeTempFileKey)(n)}.json`);try{let t=JSON.parse((0,je.readFileSync)(e,"utf-8"));return{ttft:fn(t.timeToFirstToken),tokensPerSecond:fn(t.tokensPerSecond)}}catch{return{ttft:null,tokensPerSecond:null}}}function Fp(n,e,t){return gn().prepare("SELECT MIN(timestamp) AS timestamp FROM usage_records WHERE provider = ? AND timestamp >= ? AND timestamp <= ?").get(n,e,t)?.timestamp??void 0}var je,mn,Hc,zc,wt,Qo,xp,Ds,Sp,Cp,Rp,Fc,Fe,Fs,jc,Np,Up,_n=w(()=>{"use strict";je=require("fs"),mn=require("path"),Hc=require("os"),zc=require("@wengine-ai/claude-code-router-shared"),wt=require("@wengine-ai/claude-code-router-shared"),Qo=(0,mn.join)(wt.HOME_DIR,"data"),xp=(0,mn.join)(Qo,"usage.sqlite"),Ds=(0,mn.join)(Qo,"usage.jsonl"),Sp=1,Cp=180,Rp=3600*1e3,Fc="legacy_usage_jsonl_migrated_at",Fe=null,Fs=null,jc=0;Np=`
|
|
389
395
|
COUNT(*) AS count,
|
|
390
396
|
COALESCE(SUM(CASE WHEN status = 'success' THEN input_tokens ELSE 0 END), 0) AS inputTokens,
|
|
391
397
|
COALESCE(SUM(CASE WHEN status = 'success' THEN output_tokens ELSE 0 END), 0) AS outputTokens,
|
|
392
398
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_read_input_tokens ELSE 0 END), 0) AS cacheReadInputTokens,
|
|
393
399
|
COALESCE(SUM(CASE WHEN status = 'success' THEN cache_creation_input_tokens ELSE 0 END), 0) AS cacheCreationInputTokens
|
|
394
|
-
`;Mp=200});async function Qc(){let n=(0,Wc.homedir)(),e=(0,Kc.join)(n,".claude.json");if(!(0,Jc.existsSync)(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(0,Gc.writeFile)(e,JSON.stringify(o,null,2))}}var Jc,Wc,Kc,Gc,Vc=P(()=>{"use strict";Jc=require("fs"),Wc=require("os"),Kc=require("path"),Gc=require("fs/promises")});function Xc(n=(0,js.join)(Zc.HOME_DIR,"logs")){try{if(!(0,He.existsSync)(n))return;let e=Date.now()-Up;for(let t of(0,He.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,js.join)(n,t),r=(0,He.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,He.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function qc(){Yc||(Yc=!0,Xc(),setInterval(Xc,Dp).unref())}var He,js,Zc,Np,Up,Dp,Yc,el=P(()=>{"use strict";He=require("fs"),js=require("path"),Zc=require("@wengine-ai/claude-code-router-shared"),Np=7,Up=Np*24*60*60*1e3,Dp=1440*60*1e3,Yc=!1});async function tl(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":vt.registerPlugin(nn,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:Ho()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await vt.enablePlugins(n)}var nl=P(()=>{"use strict";ws()});function Pt(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()),Ct(e,t),Uo();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=Tt(()=>n.providerService.getProviders(),o,r=>he(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var Qo=P(()=>{"use strict";ln();Do();ae()});function sl(n){try{let e=JSON.parse((0,B.readFileSync)((0,ke.join)(Fp(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function zs(n,e){if(!rl(e))return null;try{let t=(0,B.realpathSync)(n),o=(0,ke.join)(t,"plugins"),r=(0,ke.join)(o,e);return(0,B.lstatSync)(o).isSymbolicLink()||!(0,B.lstatSync)(o).isDirectory()||(0,B.lstatSync)(r).isSymbolicLink()||!(0,B.lstatSync)(r).isDirectory()||(0,B.realpathSync)(o)!==o||(0,B.realpathSync)(r)!==r||!r.startsWith(o+ke.sep)?null:r}catch{return null}}function Hs(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=zs(n,e);if(!o)throw new Error("unsafe plugin directory");let r=(0,ke.join)(o,t),s=(0,B.lstatSync)(r);if(s.isSymbolicLink()||!s.isFile()||(0,B.realpathSync)(r)!==r)throw new Error("unsafe plugin file");let a=(0,B.openSync)(r,B.constants.O_RDONLY|B.constants.O_NOFOLLOW|B.constants.O_NONBLOCK);try{let i=(0,B.fstatSync)(a),c=(0,B.lstatSync)(r);if(!i.isFile()||c.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==c.dev||i.ino!==c.ino||zs(n,e)!==o||(0,B.realpathSync)(r)!==r)throw new Error("plugin file changed while opening");return(0,B.readFileSync)(a)}finally{(0,B.closeSync)(a)}}function jp(n){let e=n?.configService,t=e?ni(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return oi(t)}async function il(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??dr(),r={configDir:e,readConfig:()=>ne(),readRawConfig:()=>St(),writeConfig:i=>fe(i),reloadRuntime:async i=>Pt(n.getServer(),i??await ne(),t),getDirectDispatcher:tr,getSubscriptionDispatcher:()=>jp(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of sl(e)){let c;try{if(!rl(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=zs(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(Hs(e,i.name,"plugin.json").toString("utf8"));if(!h||typeof h.name!="string"||typeof h.version!="string")throw new Error;u={name:h.name,version:h.version,coreApi:String(h.coreApi??"1"),description:h.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:h=>t.info(`[plugin:${u.name}] ${h}`),warn:h=>t.warn(`[plugin:${u.name}] ${h}`),error:h=>t.error(`[plugin:${u.name}] ${h}`)},r,l);c=p,Hs(e,i.name,"plugin.js");let d=await import((0,ol.pathToFileURL)((0,ke.join)(l,"plugin.js")).href),f=d?.activate??d?.default?.activate;if(typeof f!="function")throw new Error("entry exports no activate()");await f(p.context);let g=p.cardPath?Hs(e,i.name,p.cardPath):void 0;await p.commit(g,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function al(n,e=dr()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return sl(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 B,ke,ol,rl,Fp,Bs=P(()=>{"use strict";B=require("node:fs"),ke=require("node:path"),ol=require("node:url");lr();In();Qo();an();ae();rl=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Fp=n=>(0,ke.join)(n,"plugins")});async function zp(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 Bp(n,e={}){let t=(e.registryBase??Hp).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(cl.map(m=>zp(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(!_||!me.NPM_SPEC_PATTERN.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(S=>typeof S=="string"):[]).some(S=>cl.includes(S)))continue;let T=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:T,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=(0,me.readPluginRecords)(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(!me.PLUGIN_NAME_PATTERN.test(m))return null;try{let y=JSON.parse((0,bn.readFileSync)((0,Vo.join)(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||(0,bn.existsSync)((0,Vo.join)(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(!me.PLUGIN_NAME_PATTERN.test(y)||!(0,bn.existsSync)((0,Vo.join)(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 Jp(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 ll(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 ul(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(!ll(r,n,t))return o(s,403,"local_only");try{return await Bp(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(!ll(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(0,me.installPluginFromNpm)({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 me.PluginInstallError){let u=Jp(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 bn,Vo,me,cl,Hp,dl=P(()=>{"use strict";bn=require("node:fs"),Vo=require("node:path"),me=require("@wengine-ai/claude-code-router-shared"),cl=["ccr-provider-plugin","claude-code-router-plugin"],Hp="https://registry.npmjs.org"});function pl(n){let e=z();return Jo(n,(t,o)=>e.isAvailable(t,o))}function fl(n,e,t){return e.failed.length===0?!0:(n.log?.warn?.({source:t,projectTakeoverSync:e},"Client configuration changed but some project takeovers failed to sync"),!1)}function Wp(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=yn(t,e),s=yn(o,e),a=[],i=new Set;for(let c of n||[])c&&c.name&&i.add(c.name);for(let c of Object.keys(r.byProvider||{}))i.add(c);for(let c of Object.keys(s.byProvider||{}))i.add(c);for(let c of i){let l=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},p=(l.inputTokens||0)+(l.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),f,g,h=(n||[]).find(m=>m&&m.name===c);h&&h.quota&&(f=h.quota.limit5h,g=h.quota.limit7d),a.push({provider:c,used5h:p,used7d:d,limit5h:f,limit7d:g})}return a}async function bl(n,e){let t=n.app;it(),ut(),t.register(yl.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=pl(e);return{object:"list",data:i,first_id:i[0]?.id||null,last_id:i[i.length-1]?.id||null,has_more:!1}}),t.get("/v1/models/:modelId",async(i,c)=>{let l=decodeURIComponent(i.params.modelId),u=pl(e).find(p=>p.id===l);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${l}`}})}),t.post("/v1/messages/count_tokens",async(i,c)=>{let{messages:l,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[h,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${h}, model: ${m}`);let y=f.getTokenizerConfigForModel(h,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${h},${m}, using default tiktoken`);let b=await f.countTokens({messages:l,system:p,tools:u},y,h);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(h){i.log?.error(`Error using configured tokenizer: ${h.message}`),i.log?.error(h.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:jt(l,p,u)}}),t.get("/api/config",async(i,c)=>await St()),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=ti(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(g=>`${g.key}: ${g.error}`).join("; "),proxyErrors:u};let p=await sn();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await ne()}catch{}(0,ml.ensureCcrSelfProvider)(l,d),n.pluginRegistry.applyConfigProtectors(l,d),await fe(l);let f;try{f=await(0,A.syncGlobalProjectTakeovers)(l),f.failed.length>0&&t.log?.warn?.({projectTakeoverSync:f},"Config saved but some global project takeovers failed to sync")}catch(g){t.log?.warn?.(`Config saved but global project takeover sync failed: ${g?.message||g}`)}return Pt(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,c)=>{try{let l=await ne();return{clients:(0,A.listClientStatuses)(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 ne(),d=(0,A.applyClientSelection)(p,u);await fe(d.config);let f=await(0,A.syncGlobalProjectTakeovers)(d.config),g=fl(t,f,"clients/apply");return{...d,success:d.success&&g,projectTakeoverSync:f}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!(0,A.isClientId)(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await ne(),d=l==="enable"?(0,A.enableClient)(p,u):l==="restore"?(0,A.restoreClient)(p,u):(0,A.disableClient)(p,u);await fe(p);let f=await(0,A.syncGlobalProjectTakeovers)(p),g=fl(t,f,`clients/${u}/${l}`);return{success:d.success&&g,result:d,results:[d],clients:(0,A.listClientStatuses)(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(0,A.listProjectConfigs)();return{projects:await Promise.all(l.map(async p=>{let d=await(0,A.getProjectTakeoverClients)(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"||!(0,q.isAbsolute)(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,q.normalize)(l).replace(/[\\/]+$/,"")||l;if(await(0,A.readProjectConfig)(u)){c.status(409).send({error:"Project is already configured"});return}await(0,A.writeProjectConfig)(u,{Router:{}});try{let f=await ne();await(0,A.setProjectTakeover)(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await(0,A.getProjectTakeoverClients)(u);return{id:(0,A.getClaudeProjectId)(u),path:u,configPath:(0,A.getProjectConfigPath)(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(0,A.readProjectConfigById)(l);if(!p){c.status(404).send({error:"Project config not found"});return}await(0,A.writeProjectConfig)(p.path,{Router:u});let d=await ne();Object.keys(u).length===0?await(0,A.refreshProjectTakeovers)(p.path,d):(await(0,A.refreshCcrProjectTakeover)(p.path,d,u),await(0,A.refreshPiProjectTakeover)(p.path,d,u));let f=await(0,A.getProjectTakeoverClients)(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(A.isProjectTakeoverClient);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(0,A.readProjectConfigById)(l);if(!d){c.status(404).send({error:"Project config not found"});return}let f=await ne(),g=await(0,A.setProjectTakeover)(d.path,p,f);return{id:l,path:d.path,ccrTakeoverClients:g,ccrTakeover:g.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await(0,A.readProjectConfigById)(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await ne();await(0,A.setProjectTakeover)(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await(0,A.deleteProjectConfig)(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:(0,q.dirname)((0,gl.fileURLToPath)(void 0)),s=(0,J.existsSync)((0,q.join)(r,"index.html"))?r:(0,J.existsSync)((0,q.join)(r,"..","index.html"))?(0,q.join)(r,".."):(0,q.join)(r,"..","dist");t.register(hl.default,{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=(0,q.join)((0,Yo.homedir)(),".claude-code-router","logs"),u=[];if((0,J.existsSync)(l)){let p=(0,J.readdirSync)(l);for(let d of p)if(d.endsWith(".log")){let f=(0,q.join)(l,d),g=(0,J.statSync)(f);u.push({name:d,path:f,size:g.size,lastModified:g.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(l){console.error("Failed to get log files:",l),c.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=(0,q.join)((0,Yo.homedir)(),".claude-code-router","logs","app.log"),(0,J.existsSync)(u)?(0,J.readFileSync)(u,"utf8").split(`
|
|
395
|
-
`).filter(f=>f.trim()):[]}catch(l){console.error("Failed to get logs:",l),c.status(500).send({error:"Failed to get logs"})}}),t.delete("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=(0,q.join)((0,Yo.homedir)(),".claude-code-router","logs","app.log"),(0,J.existsSync)(u)&&(0,J.writeFileSync)(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:Ot()})),t.put("/api/debug-log",async i=>{let{enabled:c}=i.body;return wn(c),{enabled:Ot()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return Ns({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 yn(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 Us(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=z().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,lastSuccessTime:f.lastSuccessTime??null,lastError:f.lastError,rateLimitUntil:f.rateLimitUntil??null})),probes:d,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to get provider health:",l),c.status(500).send({error:"Failed to get provider health"})}}),t.post("/api/providers/probe",async(i,c)=>{try{let{providerName:l}=i.body;if(!l)return c.status(400),{error:"providerName is required"};let p=t._server?.activeProbeService;if(!p?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let d=await p.probeProviderManually(l);return d.success&&cn(l,i.log),{provider:l,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.error,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe provider:",l),c.status(500).send({error:l.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,c)=>{try{let l=t._server,u=l?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let p=(l?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let g=await u.probeProviderManually(f.name);return g.success&&cn(f.name,i?.log),{provider:f.name,success:g.success,latencyMs:g.latencyMs,status:g.status,isSlow:g.isSlow,errorKind:g.errorKind??null,error:g.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe all providers:",l),c.status(500).send({error:l.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,c)=>{try{let u=(await ne()).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 $o(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,mc).unref?.()});await Promise.race([Promise.all(b),_])}}let f=Wp(u),g=new Map(f.map(y=>[y.provider,y])),h=Nn();for(let y of f){let b=h.find(_=>_.provider===y.provider);b&&b.limit!=null&&!Un(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=Bn();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 _=Un(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=Un(typeof y.resetTime7d=="string"?Date.parse(y.resetTime7d)/1e3:void 0);typeof y.usedDailyBalance=="number"&&!_&&(b.used5h=y.usedDailyBalance,b.type5h="rateLimit"),typeof y.limitDaily=="number"&&!_&&(b.limit5h=y.limitDaily,b.type5h="rateLimit"),typeof y.resetTime=="string"&&!_&&(y.limitDaily!==void 0?b.reset5h=y.resetTime:b.reset7d=y.resetTime),typeof y.resetTime7d=="string"&&!k&&(b.reset7d=y.resetTime7d)}return{quotas:f,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=(0,q.join)(A.HOME_DIR,"presets");if(!(0,J.existsSync)(l))return{presets:[]};let p=(0,J.readdirSync)(l,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let g=(0,q.join)(l,f);try{let h=(0,q.join)(g,"manifest.json"),m=(0,J.readFileSync)(h,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:T,API_TIMEOUT_MS:S,PROXY_URL:v,PROXY_GLOBAL_ENABLED:w,LOG:R,LOG_LEVEL:E,StatusLine:M,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(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=(0,A.getPresetDir)(l);if(!(0,J.existsSync)(u)){c.status(404).send({error:"Preset not found"});return}let p=await(0,A.readManifestFromDir)(u);return{...(0,A.manifestToPresetFile)(p),config:(0,A.loadConfigFromManifest)(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=(0,A.getPresetDir)(l);if(!(0,J.existsSync)(p)){c.status(404).send({error:"Preset not found"});return}let f={...await(0,A.readManifestFromDir)(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await(0,A.saveManifest)(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=(0,A.getPresetDir)(l);if(!(0,J.existsSync)(u)){c.status(404).send({error:"Preset not found"});return}return(0,J.rmSync)(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(0,A.getMarketPresets)()}}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(0,A.findMarketPresetByName)(l);if(!u){c.status(400).send({error:"Preset not found in marketplace",message:`Preset '${l}' is not available in the official marketplace. Please check the available presets.`});return}if(!u.repo){c.status(400).send({error:"Invalid preset data",message:`Preset '${l}' does not have repository information`});return}let p=u.repo.match(/(?:github\.com[:/]|^)([^/]+)\/([^/\s#]+?)(?:\.git)?$/);if(!p){c.status(400).send({error:"Invalid GitHub repository URL"});return}let[,d,f]=p,g=u.name||l;if(await(0,A.isPresetInstalled)(g)){c.status(409).send({error:"Preset already installed",message:`Preset '${g}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:g});return}let h=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await(0,A.downloadPresetToTemp)(h),y=await a(m);if(await(0,A.isPresetInstalled)(g)){(0,J.unlinkSync)(m),c.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let b=(0,A.getPresetDir)(g);await(0,A.extractPreset)(m,b);let _=await(0,A.readManifestFromDir)(b);return _.repository=u.repo,u.url&&(_.source=u.url),await(0,A.saveManifest)(g,_),(0,J.unlinkSync)(m),{success:!0,presetName:g,preset:{...y.metadata,installed:!0}}}catch(l){console.error("Failed to install preset from GitHub:",l),c.status(500).send({error:l.message||"Failed to install preset from GitHub"})}});async function a(i){let c=new _l.default(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(0,A.manifestToPresetFile)(u)}return t.get("/api/plugins",async()=>({plugins:al(A.HOME_DIR,n.pluginRegistry)})),ul(t,{configDir:A.HOME_DIR,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 ml,q,gl,hl,J,Yo,A,yl,_l,kl=P(()=>{"use strict";Ve();We();Ke();cs();We();ae();It();ue();ln();Qo();Bs();dl();an();ml=require("@wengine-ai/claude-code-router-shared"),q=require("path"),gl=require("url"),hl=ee(require("@fastify/static"),1),J=require("fs"),Yo=require("os"),A=require("@wengine-ai/claude-code-router-shared"),yl=ee(require("@fastify/multipart"),1),_l=ee(require("adm-zip"),1);_n();Is()});function Kp(n,e){let t=n?.Router,{family:o}=Ht(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function Tl(n){return n?.Router?.image}function Gp(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 Qp(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 Js,Xo,Ws,vl,xl=P(()=>{"use strict";Ve();Js=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}},Xo=new Js;Ws=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Kp(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Gp(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&zt(e.body.model)?!1:(Qp(e.body.messages),s&&!!Tl(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=Xo.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=Xo.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:Tl(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
400
|
+
`;Up=200});async function Zc(){let n=(0,Vc.homedir)(),e=(0,Yc.join)(n,".claude.json");if(!(0,Qc.existsSync)(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(0,Xc.writeFile)(e,JSON.stringify(o,null,2))}}var Qc,Vc,Yc,Xc,qc=w(()=>{"use strict";Qc=require("fs"),Vc=require("os"),Yc=require("path"),Xc=require("fs/promises")});function tl(n=(0,Js.join)(nl.HOME_DIR,"logs")){try{if(!(0,He.existsSync)(n))return;let e=Date.now()-Hp;for(let t of(0,He.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,Js.join)(n,t),r=(0,He.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,He.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function ol(){el||(el=!0,tl(),setInterval(tl,zp).unref())}var He,Js,nl,jp,Hp,zp,el,rl=w(()=>{"use strict";He=require("fs"),Js=require("path"),nl=require("@wengine-ai/claude-code-router-shared"),jp=7,Hp=jp*24*60*60*1e3,zp=1440*60*1e3,el=!1});async function sl(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":Tt.registerPlugin(nn,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:Bo()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await Tt.enablePlugins(n)}var il=w(()=>{"use strict";Os()});function Pt(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()),Ct(e,t),Fo();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=vt(()=>n.providerService.getProviders(),o,r=>he(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var Yo=w(()=>{"use strict";ln();jo();ae()});function ll(n){try{let e=JSON.parse((0,B.readFileSync)((0,ke.join)(Bp(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function Ks(n,e){if(!cl(e))return null;try{let t=(0,B.realpathSync)(n),o=(0,ke.join)(t,"plugins"),r=(0,ke.join)(o,e);return(0,B.lstatSync)(o).isSymbolicLink()||!(0,B.lstatSync)(o).isDirectory()||(0,B.lstatSync)(r).isSymbolicLink()||!(0,B.lstatSync)(r).isDirectory()||(0,B.realpathSync)(o)!==o||(0,B.realpathSync)(r)!==r||!r.startsWith(o+ke.sep)?null:r}catch{return null}}function Ws(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=Ks(n,e);if(!o)throw new Error("unsafe plugin directory");let r=(0,ke.join)(o,t),s=(0,B.lstatSync)(r);if(s.isSymbolicLink()||!s.isFile()||(0,B.realpathSync)(r)!==r)throw new Error("unsafe plugin file");let a=(0,B.openSync)(r,B.constants.O_RDONLY|B.constants.O_NOFOLLOW|B.constants.O_NONBLOCK);try{let i=(0,B.fstatSync)(a),l=(0,B.lstatSync)(r);if(!i.isFile()||l.isSymbolicLink()||i.dev!==s.dev||i.ino!==s.ino||i.dev!==l.dev||i.ino!==l.ino||Ks(n,e)!==o||(0,B.realpathSync)(r)!==r)throw new Error("plugin file changed while opening");return(0,B.readFileSync)(a)}finally{(0,B.closeSync)(a)}}function Jp(n){let e=n?.configService,t=e?ii(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return ai(t)}async function ul(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??fr(),r={configDir:e,readConfig:()=>ne(),readRawConfig:()=>St(),writeConfig:i=>fe(i),reloadRuntime:async i=>Pt(n.getServer(),i??await ne(),t),getDirectDispatcher:or,getSubscriptionDispatcher:()=>Jp(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of ll(e)){let l;try{if(!cl(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=Ks(e,i.name);if(!c){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(Ws(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,Ws(e,i.name,"plugin.js");let d=await import((0,al.pathToFileURL)((0,ke.join)(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?Ws(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 dl(n,e=fr()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return ll(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 B,ke,al,cl,Bp,Gs=w(()=>{"use strict";B=require("node:fs"),ke=require("node:path"),al=require("node:url");dr();Mn();Yo();an();ae();cl=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Bp=n=>(0,ke.join)(n,"plugins")});async function Kp(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 Gp(n,e={}){let t=(e.registryBase??Wp).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(pl.map(m=>Kp(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(!_||!me.NPM_SPEC_PATTERN.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>pl.includes(x)))continue;let v=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:v,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=(0,me.readPluginRecords)(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(!me.PLUGIN_NAME_PATTERN.test(m))return null;try{let y=JSON.parse((0,kn.readFileSync)((0,Xo.join)(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||(0,kn.existsSync)((0,Xo.join)(n,"plugins",m.name)),_=b?p(y?y.name:m.name):null;return{...m,installed:b,installedVersion:_,...b&&_!==null&&(0,bn.valid)(_)&&(0,bn.valid)(m.version)&&(0,bn.gt)(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(!me.PLUGIN_NAME_PATTERN.test(y)||!(0,kn.existsSync)((0,Xo.join)(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 Qp(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 fl(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 ml(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(!fl(r,n,t))return o(s,403,"local_only");try{return await Gp(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(!fl(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(0,me.installPluginFromNpm)({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 me.PluginInstallError){let u=Qp(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 bn,kn,Xo,me,pl,Wp,gl=w(()=>{"use strict";bn=require("semver"),kn=require("node:fs"),Xo=require("node:path"),me=require("@wengine-ai/claude-code-router-shared"),pl=["ccr-provider-plugin","claude-code-router-plugin"],Wp="https://registry.npmjs.org"});function hl(n){let e=z();return Ko(n,(t,o)=>e.isAvailable(t,o))}function yl(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 Vp(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=yn(t,e),s=yn(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 xl(n,e){let t=n.app;it(),ut(),t.register(vl.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=hl(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=hl(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:jt(c,p,u)}}),t.get("/api/config",async(i,l)=>await St()),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=si(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 sn();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await ne()}catch{}(0,_l.ensureCcrSelfProvider)(c,d),n.pluginRegistry.applyConfigProtectors(c,d),await fe(c);let f;try{f=await(0,E.syncGlobalProjectTakeovers)(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 Pt(n,c,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,l)=>{try{let c=await ne();return{clients:(0,E.listClientStatuses)(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 ne(),d=(0,E.applyClientSelection)(p,u);await fe(d.config);let f=await(0,E.syncGlobalProjectTakeovers)(d.config),g=yl(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(!(0,E.isClientId)(u)){l.status(404).send({error:`Unknown client: ${u}`});return}let p=await ne(),d=c==="enable"?(0,E.enableClient)(p,u):c==="restore"?(0,E.restoreClient)(p,u):(0,E.disableClient)(p,u);await fe(p);let f=await(0,E.syncGlobalProjectTakeovers)(p),g=yl(t,f,`clients/${u}/${c}`);return{success:d.success&&g,result:d,results:[d],clients:(0,E.listClientStatuses)(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(0,E.listProjectConfigs)();return{projects:await Promise.all(c.map(async p=>{let d=await(0,E.getProjectTakeoverClients)(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"||!(0,q.isAbsolute)(c)){l.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,q.normalize)(c).replace(/[\\/]+$/,"")||c;if(await(0,E.readProjectConfig)(u)){l.status(409).send({error:"Project is already configured"});return}await(0,E.writeProjectConfig)(u,{Router:{}});try{let f=await ne();await(0,E.setProjectTakeover)(u,["claudeCode"],f)}catch(f){console.error("Failed to auto-enable ccr takeover for new project:",f)}let d=await(0,E.getProjectTakeoverClients)(u);return{id:(0,E.getClaudeProjectId)(u),path:u,configPath:(0,E.getProjectConfigPath)(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(0,E.readProjectConfigById)(c);if(!p){l.status(404).send({error:"Project config not found"});return}await(0,E.writeProjectConfig)(p.path,{Router:u});let d=await ne();Object.keys(u).length===0?await(0,E.refreshProjectTakeovers)(p.path,d):(await(0,E.refreshCcrProjectTakeover)(p.path,d,u),await(0,E.refreshPiProjectTakeover)(p.path,d,u));let f=await(0,E.getProjectTakeoverClients)(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(E.isProjectTakeoverClient);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(0,E.readProjectConfigById)(c);if(!d){l.status(404).send({error:"Project config not found"});return}let f=await ne(),g=await(0,E.setProjectTakeover)(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(0,E.readProjectConfigById)(c);if(!u){l.status(404).send({error:"Project config not found"});return}try{let p=await ne();await(0,E.setProjectTakeover)(u.path,[],p)}catch(p){console.error("Failed to remove ccr takeover while deleting project:",p)}return await(0,E.deleteProjectConfig)(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:(0,q.dirname)((0,bl.fileURLToPath)(void 0)),s=(0,J.existsSync)((0,q.join)(r,"index.html"))?r:(0,J.existsSync)((0,q.join)(r,"..","index.html"))?(0,q.join)(r,".."):(0,q.join)(r,"..","dist");t.register(kl.default,{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=(0,q.join)((0,Zo.homedir)(),".claude-code-router","logs"),u=[];if((0,J.existsSync)(c)){let p=(0,J.readdirSync)(c);for(let d of p)if(d.endsWith(".log")){let f=(0,q.join)(c,d),g=(0,J.statSync)(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=(0,q.join)((0,Zo.homedir)(),".claude-code-router","logs","app.log"),(0,J.existsSync)(u)?(0,J.readFileSync)(u,"utf8").split(`
|
|
401
|
+
`).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=(0,q.join)((0,Zo.homedir)(),".claude-code-router","logs","app.log"),(0,J.existsSync)(u)&&(0,J.writeFileSync)(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:Ot()})),t.put("/api/debug-log",async i=>{let{enabled:l}=i.body;return Pn(l),{enabled:Ot()}}),t.get("/api/usage",async(i,l)=>{try{let c=i.query;return js({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 yn(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 Hs(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=z().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&&cn(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&&cn(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 ne()).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 Uo(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,_c).unref?.()});await Promise.race([Promise.all(b),_])}}let f=Vp(u),g=new Map(f.map(y=>[y.provider,y])),h=Un();for(let y of f){let b=h.find(_=>_.provider===y.provider);b&&b.limit!=null&&!Dn(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=Jn();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 _=Dn(typeof y.resetTime=="string"?Date.parse(y.resetTime)/1e3:void 0),k=Dn(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=(0,q.join)(E.HOME_DIR,"presets");if(!(0,J.existsSync)(c))return{presets:[]};let p=(0,J.readdirSync)(c,{withFileTypes:!0}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).map(f=>f.name),d=[];for(let f of p){let g=(0,q.join)(c,f);try{let h=(0,q.join)(g,"manifest.json"),m=(0,J.readFileSync)(h,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:v,API_TIMEOUT_MS:x,PROXY_URL:T,PROXY_GLOBAL_ENABLED:P,LOG:A,LOG_LEVEL:R,StatusLine:O,NON_INTERACTIVE_MODE:F,...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=(0,E.getPresetDir)(c);if(!(0,J.existsSync)(u)){l.status(404).send({error:"Preset not found"});return}let p=await(0,E.readManifestFromDir)(u);return{...(0,E.manifestToPresetFile)(p),config:(0,E.loadConfigFromManifest)(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=(0,E.getPresetDir)(c);if(!(0,J.existsSync)(p)){l.status(404).send({error:"Preset not found"});return}let f={...await(0,E.readManifestFromDir)(p)};return u&&Object.keys(u).length>0&&(f.userValues={...f.userValues,...u}),await(0,E.saveManifest)(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=(0,E.getPresetDir)(c);if(!(0,J.existsSync)(u)){l.status(404).send({error:"Preset not found"});return}return(0,J.rmSync)(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(0,E.getMarketPresets)()}}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(0,E.findMarketPresetByName)(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(0,E.isPresetInstalled)(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(0,E.downloadPresetToTemp)(h),y=await a(m);if(await(0,E.isPresetInstalled)(g)){(0,J.unlinkSync)(m),l.status(409).send({error:"Preset already installed",message:`Preset '${g}' was installed while downloading. Please try again.`,presetName:g});return}let b=(0,E.getPresetDir)(g);await(0,E.extractPreset)(m,b);let _=await(0,E.readManifestFromDir)(b);return _.repository=u.repo,u.url&&(_.source=u.url),await(0,E.saveManifest)(g,_),(0,J.unlinkSync)(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 Tl.default(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(0,E.manifestToPresetFile)(u)}return t.get("/api/plugins",async()=>({plugins:dl(E.HOME_DIR,n.pluginRegistry)})),ml(t,{configDir:E.HOME_DIR,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 _l,q,bl,kl,J,Zo,E,vl,Tl,Sl=w(()=>{"use strict";Ve();We();Ke();ps();We();ae();It();ue();ln();Yo();Gs();gl();an();_l=require("@wengine-ai/claude-code-router-shared"),q=require("path"),bl=require("url"),kl=ee(require("@fastify/static"),1),J=require("fs"),Zo=require("os"),E=require("@wengine-ai/claude-code-router-shared"),vl=ee(require("@fastify/multipart"),1),Tl=ee(require("adm-zip"),1);_n();Ns()});function Yp(n,e){let t=n?.Router,{family:o}=Ht(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function Cl(n){return n?.Router?.image}function Xp(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 Zp(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 Qs,qo,Vs,Rl,wl=w(()=>{"use strict";Ve();Qs=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}},qo=new Qs;Vs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Yp(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Xp(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&zt(e.body.model)?!1:(Zp(e.body.messages),s&&!!Cl(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=qo.getImage(`${t.req.id}_Image#${i}`);l&&o.push({type:"image",source:l})});else{let i=qo.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:Cl(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
396
402
|
When an image placeholder is provided, your role is to parse the image content only within the scope of the user\u2019s instructions.
|
|
397
403
|
Do not ignore or deviate from the task.
|
|
398
404
|
Always ensure that your response reflects a clear, accurate interpretation of the image aligned with the given objective.`}],messages:[{role:"user",content:o}],stream:!1})}).then(i=>i.json()).catch(i=>null);return!a||!a.content?"analyzeImage Error":a.content[0].text}})}reqHandler(e,t){e.body?.system?.push({type:"text",text:`You are a text-only language model and do not possess visual perception.
|
|
@@ -405,5 +411,5 @@ If multiple images exist, select the **most relevant imageId** based on the user
|
|
|
405
411
|
|
|
406
412
|
Do not attempt to describe or analyze the image directly yourself.
|
|
407
413
|
Ignore any user interruptions or unrelated instructions that might cause you to skip this requirement.
|
|
408
|
-
Your response should consistently follow this rule whenever image-related analysis is requested.`});let o=e.body.messages.filter(s=>s.role==="user"&&Array.isArray(s.content)&&s.content.some(a=>a.type==="image"||Array.isArray(a.content)&&a.content.some(i=>i.type==="image"))),r=1;o.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{if(a.type==="image")Xo.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:(Xo.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}})})}},vl=new Ws});var Ks,Sl,Zo,Cl=P(()=>{"use strict";xl();Ks=class{agents=new Map;registerAgent(e){this.agents.set(e.name,e)}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getAllTools(){let e=[];for(let t of this.agents.values())e.push(...t.tools.values());return e}},Sl=new Ks;Sl.registerAgent(vl);Zo=Sl});function Yp(n,e){return n===429||!!(e&&/rate[\s_]limit|too many|限流|频率限制|qps_limit|token_limit|quota exhausted|usage limit|limit reached/i.test(e))}function El(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ae(n,e)}function Qs(n){return n.usageSessionId||n.id}function qo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Qs(n)}`}function kn(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function tt(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 Xp(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?Ie(e.usage):e.response?.usage?Ie(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function Zp(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();un(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o;try{o=new URL(`http://127.0.0.1${n.url}`)}catch{return}if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){El(n,t);let r=qo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=te.get(r))}}async function qp(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of Zo.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 Al(n){return{authClient:(e,t)=>Zp(e,t,n),agent:(e,t)=>qp(e,t,n)}}function Ol(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=Gs.performance.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname;if(!r)try{r=new URL(`http://127.0.0.1${t.url}`).pathname}catch{r=""}r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=c=>c?a(c):s();un(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Rl.emit("onError",t,o,r)}),n.addHook("onSend",(t,o,r,s)=>{(t.ccrHookOrder||=[]).push("onSend");let a=t.pathname?.endsWith("/v1/messages"),i=t.pathname?.endsWith("/v1/responses");if(a||i){El(t,e);let c=Qs(t),l=qo(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new le),m,y=-1,b="",_="",k="",T=[],S=[];return s(null,Yt(h,async(v,w)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let R=t.agents.find(E=>Zo.getAgent(E)?.tools.get(v.data.content_block.name));if(R){m=Zo.getAgent(R),y=v.data.index,b=v.data.content_block.name,k=v.data.content_block.id;return}}if(y>-1&&v.data.index===y&&v.data?.delta?.type==="input_json_delta"){_+=v.data?.delta?.partial_json;return}if(y>-1&&v.data.index===y&&v.data?.type==="content_block_stop"){try{let R=Pl.default.parse(_);S.push({type:"tool_use",id:k,name:b,input:R});let E=await m?.tools.get(b)?.handler(R,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:E}),m=void 0,y=-1,b="",_="",k=""}catch(R){console.log(R)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:S}),t.body.messages.push({role:"user",content:T});let R=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!R.ok)return;let M=R.body.pipeThrough(new le).getReader();for(;;)try{let{value:D,done:C}=await M.read();if(C)break;let O=D;if(["message_start","message_stop"].includes(O.event))continue;if(!w.desiredSize)break;w.enqueue(O)}catch(D){if(D.name==="AbortError"||D.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw D}return}return v}catch(R){if(console.error("Unexpected error in stream processing:",R),R.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw R}}).pipeThrough(new qe))}let[p,d]=r.tee(),f=async g=>{let m=g.pipeThrough(new TextDecoderStream).pipeThrough(new le).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&kn(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&kn(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&kn(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=te.get(l)||{},S=Ie(k.usage),v=Me(T,S,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:tt(t),usageSessionId:c,capturedUsage:S,mergedUsage:v}),(S?.cache_read_input_tokens||S?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:S?.cache_read_input_tokens,cache_creation:S?.cache_creation_input_tokens}),te.put(l,v)}if(k?.response?.usage){let T=Ie(k.response.usage),S=te.get(l)||{},v=Me(S,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:tt(t),usageSessionId:c,capturedUsage:T,mergedUsage:v}),te.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 le).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&&kn(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&kn(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ie(b),k=te.get(l)||{},T=Me(k,_,m==="message_start");te.put(l,T)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{f.releaseLock()}})(),s(null,p)}let u=Xp(r);if(u?.usage&&te.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(Rl.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=>{wr(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),wr(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async v=>{if(!v)return;let w;try{await Promise.race([v,new Promise(R=>{w=setTimeout(R,Vp)})])}finally{w&&clearTimeout(w)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=Qs(t),a=s,i=t.sessionId||s,c=o.statusCode>=400,l=c?void 0:te.get(qo(t)),u=Ds(a),p=z(),d,f,g=t.sseError,h=g&&(g.type||g.code||g.message),m=l?.output_tokens&&l.output_tokens>0,y=t.contentDelivered===!0,b=c||h&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(g),f=JSON.stringify(g)),f=f||t.errorResponseBody;let v=tt(t);Yp(o.statusCode,d)?p.markRateLimited(t.provider||"",v,120,d):p.recordFailure(t.provider||"",v,d)}else{let v=tt(t);p.recordSuccess(t.provider||"",v)}let _=l?.cache_read_input_tokens??0,T=l?.input_tokens||0||t.tokenCount||0;!l?.usage_estimated&&!_&&t.tokenCount&&l?.input_tokens&&l.input_tokens<t.tokenCount&&(_=t.tokenCount-l.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:l.input_tokens,impliedCache:_}));let S=b?0:l?.output_tokens||0;!b&&t.body?.stream&&T===0&&S===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:tt(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."}),hn({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:tt(t),upstreamModel:t.upstreamModel||tt(t)||void 0,...l?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Ge(t),stream:t.body?.stream??!1,inputTokens:T,outputTokens:S,cacheReadInputTokens:_,cacheCreationInputTokens:l?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Gs.performance.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&te.delete(qo(t))}catch(r){console.error("Usage tracking error:",r)}})}var wl,Gs,Pl,Vp,Rl,Il=P(()=>{"use strict";wl=require("node:events"),Gs=require("node:perf_hooks"),Pl=ee(require("json5"),1);mt();zn();jn();ue();fs();ms();gs();_n();to();Cl();Ms();Zn();Vp=1500;Rl=new wl.EventEmitter});var Nl={};vn(Nl,{createCcrServer:()=>ef});async function ef(n={}){await Qc(),await rn();let e=await zo();(0,Pe.ensureCcrSelfProvider)(e).changed&&(await fe(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;Sc();let c=f=>(f>9?"":"0")+f,l=(f,g)=>{let h;f?typeof f=="number"?h=new Date(f):h=f:h=new Date;let m=h.getFullYear()+""+c(h.getMonth()+1),y=c(h.getDate()),b=c(h.getHours()),_=c(h.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${c(h.getSeconds())}${g?`_${g}`:""}.log`},u;n.logger!==void 0?u=n.logger:(qc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:(0,$l.createStream)(l,{path:Pe.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await(0,Pe.listPresets)(),d=new Vs({jsonPath:Pe.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:(0,Ll.join)((0,Ml.homedir)(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await il({configDir:Pe.HOME_DIR,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&&Pt(d,e,d.app.log),await bl(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Ge(y.req):"unknown";hn({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)}},Ol(d,e),d.ccrPreHandlerCallbacks=Al(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 tl(d,e),Ct(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 Ml,Ll,$l,Pe,Ul=P(()=>{"use strict";Ml=require("os"),Ll=require("path");Dl();$l=require("rotating-file-stream"),Pe=require("@wengine-ai/claude-code-router-shared");Vc();an();el();vs();nl();kl();Bs();Qo();Il();ln();_n();mt()});var of={};vn(of,{ActiveProbeService:()=>Vt,ConfigService:()=>ze,ProjectRoutingError:()=>se,ProviderHealthStore:()=>Lt,ProviderService:()=>Ye,SSEParserTransform:()=>le,SSESerializerTransform:()=>qe,TokenizerService:()=>Ze,TransformerService:()=>Xe,apiKeyAuth:()=>un,applyClientAdapter:()=>Ae,backupConfigFile:()=>sn,builtinClientAdapterRegistry:()=>$r,calculateTokenCount:()=>jt,clearClientAdapterCaches:()=>qi,clearProviderHealth:()=>cn,closeProxyDispatchers:()=>Cn,collectReachableModelKeys:()=>Os,createCcrServer:()=>Hl,default:()=>Vs,detectClientType:()=>Ge,diagnoseResolutionFailure:()=>Dr,extractSessionIdFromUserId:()=>Re,getActiveProbeService:()=>ds,getAllQuotaResults:()=>Bn,getAllRateLimitInfo:()=>Nn,getClientAdapter:()=>Ur,getConfiguredProxyUrl:()=>Et,getHealthStore:()=>z,getProxyDispatcher:()=>X,getQuotaAdapter:()=>Lo,getQuotaResult:()=>Ut,getRateLimitInfo:()=>Mi,getRuntimeDebugLog:()=>Ot,getServer:()=>nf,initConfig:()=>zo,initDir:()=>rn,initProviderHealthPersistence:()=>$n,initQuotaStorePersistence:()=>ut,initRateLimitPersistence:()=>it,isClientType:()=>Nr,isGlobalProxyEnabled:()=>nr,listAnthropicCompatibleModels:()=>Jo,mergeUsageCapture:()=>Me,normalizeSessionId:()=>Ce,normalizeUsagePayload:()=>Ie,pluginManager:()=>vt,readConfigFile:()=>ne,readConfigFileRaw:()=>St,reconcileHealthStore:()=>Ct,resetActiveProbeService:()=>Uo,resolveProviderProxyUrl:()=>he,rewriteStream:()=>Yt,router:()=>Bt,searchProjectBySession:()=>Fr,sessionUsageCache:()=>te,setRuntimeDebugLog:()=>wn,startActiveProbe:()=>Tt,stopActiveProbe:()=>No,storeQuotaResult:()=>lt,tokenSpeedPlugin:()=>nn,usageStore:()=>Fs,writeConfigFile:()=>fe});module.exports=Zs(of);function tf(n={}){let e=(0,Fl.default)({bodyLimit:52428800,...n});return e.setErrorHandler(ii),e.register(jl.default),e}async function Hl(n={}){return(await Promise.resolve().then(()=>(Ul(),Nl))).createCcrServer(n)}var Fl,jl,Ys,Vs,nf,Dl=P(()=>{Fl=ee(require("fastify"),1),jl=ee(require("@fastify/cors"),1);rr();Rn();Zn();jr();Gr();Qr();Ve();zn();Do();ue();We();Ke();ae();mt();Zn();In();dt();mt();Ve();rr();jr();Gr();Qr();ws();hs();ue();We();as();Ke();ue();Do();It();ae();an();to();ln();Is();Ms();_n();Ys=class{app;pluginRegistry=new Mt;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=tf({...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 ze(l),this.transformerService=new Xe(this.configService,this.app.log),this.tokenizerService=new Ze(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ye(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 ze({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Xe(o,this.app.log),a=new Ze(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ye(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async c=>{c.decorate("pluginRegistry",this.pluginRegistry),c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,u)=>{let p=new URL(`http://127.0.0.1${l.url}`);l.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!l.body||typeof l.body!="object")return;let g=l.ccrHookOrder||=[];if(g.push("request-normalize"),f&&l.body.input&&!l.body.messages&&Jt(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),g.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),Ae(l,o.getAll()),g.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(g.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){g.push("router"),l.body?.model&&await Bt(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&te.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),g.push("provider-model-normalize");try{let h=l.body;if(!h||!h.model)return u.code(400).send({error:"Missing model in request body"});let m=h.model.split(","),y=h.model;if(m.length>1){let[b,..._]=m;y=_.join(","),h.model=y,l.provider=b}l.model=y}catch(h){return l.log.error({error:h},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await ga(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{No()}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 Cn()})}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{it()}catch{}try{ut()}catch{}try{$n()}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=Tt(()=>this.providerService.getProviders(),t,o=>he(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)}}},Vs=Ys;nf=Hl});Dl();0&&(module.exports={ActiveProbeService,ConfigService,ProjectRoutingError,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,apiKeyAuth,applyClientAdapter,backupConfigFile,builtinClientAdapterRegistry,calculateTokenCount,clearClientAdapterCaches,clearProviderHealth,closeProxyDispatchers,collectReachableModelKeys,createCcrServer,detectClientType,diagnoseResolutionFailure,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getClientAdapter,getConfiguredProxyUrl,getHealthStore,getProxyDispatcher,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,getServer,initConfig,initDir,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,isClientType,isGlobalProxyEnabled,listAnthropicCompatibleModels,mergeUsageCapture,normalizeSessionId,normalizeUsagePayload,pluginManager,readConfigFile,readConfigFileRaw,reconcileHealthStore,resetActiveProbeService,resolveProviderProxyUrl,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin,usageStore,writeConfigFile});
|
|
414
|
+
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")qo.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:(qo.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}})})}},Rl=new Vs});var Ys,Pl,er,El=w(()=>{"use strict";wl();Ys=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}},Pl=new Ys;Pl.registerAgent(Rl);er=Pl});function ef(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 Ml(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ae(n,e)}function Zs(n){return n.usageSessionId||n.id}function tr(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Zs(n)}`}function vn(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function tt(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 tf(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?Ie(e.usage):e.response?.usage?Ie(e.response.usage):void 0,o=e.model||e.response?.model;if(!(!t&&!o))return{usage:t,model:o}}async function nf(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();un(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")){Ml(n,t);let r=tr(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=te.get(r))}}async function of(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of er.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 Ll(n){return{authClient:(e,t)=>nf(e,t,n),agent:(e,t)=>of(e,t,n)}}function $l(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=Xs.performance.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();un(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",Al.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){Ml(t,e);let l=Zs(t),c=tr(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new le),m,y=-1,b="",_="",k="",v=[],x=[];return s(null,Yt(h,async(T,P)=>{try{if(T.event==="content_block_start"&&T?.data?.content_block?.name){let A=t.agents.find(R=>er.getAgent(R)?.tools.get(T.data.content_block.name));if(A){m=er.getAgent(A),y=T.data.index,b=T.data.content_block.name,k=T.data.content_block.id;return}}if(y>-1&&T.data.index===y&&T.data?.delta?.type==="input_json_delta"){_+=T.data?.delta?.partial_json;return}if(y>-1&&T.data.index===y&&T.data?.type==="content_block_stop"){try{let A=Il.default.parse(_);x.push({type:"tool_use",id:k,name:b,input:A});let R=await m?.tools.get(b)?.handler(A,{req:t,config:e});v.push({tool_use_id:k,type:"tool_result",content:R}),m=void 0,y=-1,b="",_="",k=""}catch(A){console.log(A)}return}if(T.event==="message_delta"&&v.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:v});let A=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!A.ok)return;let O=A.body.pipeThrough(new le).getReader();for(;;)try{let{value:F,done:C}=await O.read();if(C)break;let I=F;if(["message_start","message_stop"].includes(I.event))continue;if(!P.desiredSize)break;P.enqueue(I)}catch(F){if(F.name==="AbortError"||F.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();break}throw F}return}return T}catch(A){if(console.error("Unexpected error in stream processing:",A),A.code==="ERR_STREAM_PREMATURE_CLOSE"){g.abort();return}throw A}}).pipeThrough(new qe))}let[p,d]=r.tee(),f=async g=>{let m=g.pipeThrough(new TextDecoderStream).pipeThrough(new le).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&vn(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&vn(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&vn(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let v=te.get(c)||{},x=Ie(k.usage),T=Me(v,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:tt(t),usageSessionId:l,capturedUsage:x,mergedUsage:T}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),te.put(c,T)}if(k?.response?.usage){let v=Ie(k.response.usage),x=te.get(c)||{},T=Me(x,v,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:tt(t),usageSessionId:l,capturedUsage:v,mergedUsage:T}),te.put(c,T)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new le).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&&vn(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&vn(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ie(b),k=te.get(c)||{},v=Me(k,_,m==="message_start");te.put(c,v)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{f.releaseLock()}})(),s(null,p)}let u=tf(r);if(u?.usage&&te.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(Al.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=>{Er(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Er(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async T=>{if(!T)return;let P;try{await Promise.race([T,new Promise(A=>{P=setTimeout(A,qp)})])}finally{P&&clearTimeout(P)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=Zs(t),a=s,i=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:te.get(tr(t)),u=zs(a),p=z(),d,f,g=t.sseError,h=g&&(g.type||g.code||g.message),m=c?.output_tokens&&c.output_tokens>0,y=t.contentDelivered===!0,b=l||h&&!m&&!y;if(b){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,h&&(d=d||JSON.stringify(g),f=JSON.stringify(g)),f=f||t.errorResponseBody;let T=tt(t);ef(o.statusCode,d)?p.markRateLimited(t.provider||"",T,120,d):p.recordFailure(t.provider||"",T,d)}else{let T=tt(t);p.recordSuccess(t.provider||"",T)}let _=c?.cache_read_input_tokens??0,v=c?.input_tokens||0||t.tokenCount||0;!c?.usage_estimated&&!_&&t.tokenCount&&c?.input_tokens&&c.input_tokens<t.tokenCount&&(_=t.tokenCount-c.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:c.input_tokens,impliedCache:_}));let x=b?0:c?.output_tokens||0;!b&&t.body?.stream&&v===0&&x===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:tt(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."}),hn({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:tt(t),upstreamModel:t.upstreamModel||tt(t)||void 0,...c?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||Ge(t),stream:t.body?.stream??!1,inputTokens:v,outputTokens:x,cacheReadInputTokens:_,cacheCreationInputTokens:c?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Xs.performance.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&te.delete(tr(t))}catch(r){console.error("Usage tracking error:",r)}})}var Ol,Xs,Il,qp,Al,Nl=w(()=>{"use strict";Ol=require("node:events"),Xs=require("node:perf_hooks"),Il=ee(require("json5"),1);mt();Bn();Hn();ue();ys();_s();bs();_n();no();El();Us();qn();qp=1500;Al=new Ol.EventEmitter});var jl={};xn(jl,{createCcrServer:()=>rf});async function rf(n={}){await Zc(),await rn();let e=await Jo();(0,Pe.ensureCcrSelfProvider)(e).changed&&(await fe(e),console.log('\u2139\uFE0F Added the preset "ccr" provider pointing at this server (delete it in the UI to remove it for good).'));let o=e.Providers||e.providers||[],r=o&&o.length>0,s=e.HOST||"127.0.0.1";r?(s=e.HOST,e.APIKEY||(s="127.0.0.1")):(s="0.0.0.0",console.log("\u2139\uFE0F No providers configured. Listening on 0.0.0.0 without authentication."));let a=n.port??e.PORT??3456,i=process.env.SERVICE_PORT?parseInt(process.env.SERVICE_PORT):a;Pc();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:(ol(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:(0,Fl.createStream)(c,{path:Pe.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await(0,Pe.listPresets)(),d=new qs({jsonPath:Pe.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:(0,Dl.join)((0,Ul.homedir)(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await ul({configDir:Pe.HOME_DIR,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&&Pt(d,e,d.app.log),await xl(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||Ge(y.req):"unknown";hn({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)}},$l(d,e),d.ccrPreHandlerCallbacks=Ll(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 sl(d,e),Ct(e,d.app?.log);let h=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",h),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",h),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var Ul,Dl,Fl,Pe,Hl=w(()=>{"use strict";Ul=require("os"),Dl=require("path");zl();Fl=require("rotating-file-stream"),Pe=require("@wengine-ai/claude-code-router-shared");qc();an();rl();Rs();il();Sl();Gs();Yo();Nl();ln();_n();mt()});var cf={};xn(cf,{ActiveProbeService:()=>Vt,ConfigService:()=>ze,ProjectRoutingError:()=>se,ProviderHealthStore:()=>Lt,ProviderService:()=>Ye,SSEParserTransform:()=>le,SSESerializerTransform:()=>qe,TokenizerService:()=>Ze,TransformerService:()=>Xe,apiKeyAuth:()=>un,applyClientAdapter:()=>Ae,backupConfigFile:()=>sn,builtinClientAdapterRegistry:()=>Ur,calculateTokenCount:()=>jt,clearClientAdapterCaches:()=>oa,clearProviderHealth:()=>cn,closeProxyDispatchers:()=>Rn,collectReachableModelKeys:()=>$s,createCcrServer:()=>Wl,default:()=>qs,detectClientType:()=>Ge,diagnoseResolutionFailure:()=>jr,extractSessionIdFromUserId:()=>Re,getActiveProbeService:()=>gs,getAllQuotaResults:()=>Jn,getAllRateLimitInfo:()=>Un,getClientAdapter:()=>Fr,getConfiguredProxyUrl:()=>Et,getHealthStore:()=>z,getProxyDispatcher:()=>X,getQuotaAdapter:()=>No,getQuotaResult:()=>Ut,getRateLimitInfo:()=>Ui,getRuntimeDebugLog:()=>Ot,getServer:()=>af,initConfig:()=>Jo,initDir:()=>rn,initProviderHealthPersistence:()=>Nn,initQuotaStorePersistence:()=>ut,initRateLimitPersistence:()=>it,isClientType:()=>Dr,isGlobalProxyEnabled:()=>rr,listAnthropicCompatibleModels:()=>Ko,mergeUsageCapture:()=>Me,normalizeSessionId:()=>Ce,normalizeUsagePayload:()=>Ie,pluginManager:()=>Tt,readConfigFile:()=>ne,readConfigFileRaw:()=>St,reconcileHealthStore:()=>Ct,resetActiveProbeService:()=>Fo,resolveProviderProxyUrl:()=>he,rewriteStream:()=>Yt,router:()=>Bt,searchProjectBySession:()=>Hr,sessionUsageCache:()=>te,setRuntimeDebugLog:()=>Pn,startActiveProbe:()=>vt,stopActiveProbe:()=>Do,storeQuotaResult:()=>lt,tokenSpeedPlugin:()=>nn,usageStore:()=>Bs,writeConfigFile:()=>fe});module.exports=ni(cf);function sf(n={}){let e=(0,Bl.default)({bodyLimit:52428800,...n});return e.setErrorHandler(ui),e.register(Jl.default),e}async function Wl(n={}){return(await Promise.resolve().then(()=>(Hl(),jl))).createCcrServer(n)}var Bl,Jl,ei,qs,af,zl=w(()=>{Bl=ee(require("fastify"),1),Jl=ee(require("@fastify/cors"),1);ir();wn();qn();zr();Xr();Zr();Ve();Bn();jo();ue();We();Ke();ae();mt();qn();Mn();dt();mt();Ve();ir();zr();Xr();Zr();Os();ks();ue();We();ds();Ke();ue();jo();It();ae();an();no();ln();Ns();Us();_n();ei=class{app;pluginRegistry=new Mt;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=sf({...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 ze(c),this.transformerService=new Xe(this.configService,this.app.log),this.tokenizerService=new Ze(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ye(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 ze({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Xe(o,this.app.log),a=new Ze(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ye(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&&Jt(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),Ae(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 Bt(c,u,{configService:o,tokenizerService:a}),c.usageCacheKey&&te.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 ba(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{Do()}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 Rn()})}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{it()}catch{}try{ut()}catch{}try{Nn()}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=vt(()=>this.providerService.getProviders(),t,o=>he(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)}}},qs=ei;af=Wl});zl();0&&(module.exports={ActiveProbeService,ConfigService,ProjectRoutingError,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,apiKeyAuth,applyClientAdapter,backupConfigFile,builtinClientAdapterRegistry,calculateTokenCount,clearClientAdapterCaches,clearProviderHealth,closeProxyDispatchers,collectReachableModelKeys,createCcrServer,detectClientType,diagnoseResolutionFailure,extractSessionIdFromUserId,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getClientAdapter,getConfiguredProxyUrl,getHealthStore,getProxyDispatcher,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,getServer,initConfig,initDir,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,isClientType,isGlobalProxyEnabled,listAnthropicCompatibleModels,mergeUsageCapture,normalizeSessionId,normalizeUsagePayload,pluginManager,readConfigFile,readConfigFileRaw,reconcileHealthStore,resetActiveProbeService,resolveProviderProxyUrl,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin,usageStore,writeConfigFile});
|
|
409
415
|
//# sourceMappingURL=server.cjs.map
|