@wengine-ai/llms 2.3.2428 → 2.3.2430
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -14
- package/dist/cjs/server.cjs +216 -210
- package/dist/cjs/server.cjs.map +4 -4
- package/dist/esm/server.mjs +215 -209
- package/dist/esm/server.mjs.map +4 -4
- package/dist/index.html +16 -16
- package/dist/provider-plugins/types.d.ts +35 -0
- package/dist/services/plugin-quota.d.ts +44 -0
- package/dist/services/provider-health.d.ts +6 -0
- package/dist/services/quota-store.d.ts +2 -0
- package/dist/transformer/anthropic.transformer.d.ts +1 -1
- package/package.json +2 -2
package/dist/cjs/server.cjs
CHANGED
|
@@ -1,305 +1,311 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Gl=Object.create;var Tn=Object.defineProperty;var Ql=Object.getOwnPropertyDescriptor;var Vl=Object.getOwnPropertyNames;var Yl=Object.getPrototypeOf,Xl=Object.prototype.hasOwnProperty;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var vn=(n,e)=>{for(var t in e)Tn(n,t,{get:e[t],enumerable:!0})},ei=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vl(e))!Xl.call(n,r)&&r!==t&&Tn(n,r,{get:()=>e[r],enumerable:!(o=Ql(e,r))||o.enumerable});return n};var ee=(n,e,t)=>(t=n!=null?Gl(Yl(n)):{},ei(e||!n||!n.__esModule?Tn(t,"default",{value:n,enumerable:!0}):t,n)),ti=n=>ei(Tn({},"__esModule",{value:!0}),n);function ql(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Zl.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 ri(n){let e=[];for(let t of[...ni,oi]){let o=n[t];if(o==null)continue;let r=ql(o);r.ok||e.push({key:t,error:r.error})}return e}function nr(){return tr||(tr=new Sn.Agent({connect:{timeout:15e3}})),tr}function si(n){let e=n.get(oi);return(typeof e=="string"?e.trim():"")||void 0}function ii(n){return n?X(n):nr()}function Et(n){for(let e of ni){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function or(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 or(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function X(n){let e=eu(n),t=xn.get(e);if(t)return t;let o=new Sn.ProxyAgent(e);return xn.set(e,o),o}async function Cn(){let n=Array.from(xn.values());xn.clear(),await Promise.allSettled(n.map(e=>e.close()))}function eu(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 Sn,ni,oi,Zl,xn,tr,ae=w(()=>{"use strict";Sn=require("undici"),ni=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],oi="SUBSCRIPTION_PROXY_URL",Zl=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;xn=new Map});var At,rr,ai,ci,ze,sr=w(()=>{"use strict";At=require("fs"),rr=require("path"),ai=require("dotenv"),ci=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,rr.join)(process.cwd(),this.options.jsonPath);if((0,At.existsSync)(e))try{let t=(0,At.readFileSync)(e,"utf-8"),o=ci.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,rr.join)(process.cwd(),this.options.envPath);if((0,At.existsSync)(e))try{let t=(0,ai.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 li(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 Rn=w(()=>{"use strict"});function wn(n){ir=n}function Ot(){return ir}function Pn(n){return ir||n.get("DEBUG_LOG")===!0}function pi(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 En(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.toLowerCase();tu.has(r)||nu.test(r)&&!/^(?:x-|anthropic-)?ratelimit-/.test(r)?e[t]="***MASKED***":e[t]=o}return e}function An(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function fi(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:En(t.headers),body:An(o,nt.maxBodyLength)})}function mi(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:En(t.headers),...t.body!==void 0?{body:An(t.body,nt.maxBodyLength)}:{}})}function ui(n,e,t,o){let r=ou(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:An(o,nt.maxBodyLength)})}function ou(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:An(o,512)})}}if(e.length)return e.length===1?e[0]:e}function di(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function gi(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(Xl.some(s=>r.includes(s))){e=!0;break}ql.some(s=>r.includes(s))&&(t=!0)}}return e||Zl(n)?"content":t?"empty":"pending"}async function mi(n,e=65536,t=1e4){let o=n.getReader(),r=new TextDecoder,s=[],a="",i=0,c=Date.now()+t,l=(u,p)=>({verdict:u,chunks:s,bytes:i,rest:p});try{for(;;){let u=c-Date.now(),p=Symbol("timeout"),d,f=o.read(),h=u<=0?p:await Promise.race([f,new Promise(m=>{d=setTimeout(()=>m(p),u)})]);if(d&&clearTimeout(d),h===p)return l(sr(a)==="content"?"content":"pending",En(o,f));if(h.done){a+=r.decode();let m=sr(a);return l(m==="empty"?"empty":"pending",null)}if(!h.value)continue;s.push(h.value),i+=h.value.byteLength,a+=r.decode(h.value,{stream:!0});let g=sr(a);if(g==="content")return l("content",En(o));if(g==="empty")return await o.cancel().catch(()=>{}),l("empty",null);if(fi(a)||i>=e)return l("pending",En(o))}}catch(u){throw await o.cancel().catch(()=>{}),u}}function En(n,e){return new ReadableStream({start(t){let o=e,r=()=>{let s=o??n.read();o=void 0,s.then(({done:a,value:i})=>{a?t.close():(t.enqueue(i),r())}).catch(a=>t.error(a))};r()},cancel(t){return n.cancel(t)}})}function gi(n,e){let t=e?.getReader();return new ReadableStream({start(o){for(let s of n)o.enqueue(s);if(!t){o.close();return}let r=()=>{t.read().then(({done:s,value:a})=>{s?o.close():(o.enqueue(a),r())}).catch(s=>o.error(s))};r()},cancel(o){return t?.cancel(o)}})}var Xl,ql,hi=w(()=>{"use strict";Xl=["content_block_start","content_block_delta","content_block_stop"];ql=["message_stop","response.completed","response.incomplete","[DONE]"]});function eu(n,e){return`${n.name}|${e?.name??""}`}function ir(n){return n.__ccrPluginRequestState??={budgets:new Map}}function nt(n,e,t){let o=ir(n),r=eu(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function ar(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(nt(n,e,o).terminalError=t,!0)}var yi=w(()=>{"use strict"});var cr=w(()=>{"use strict"});function bi(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 _i,Ot,tu,ur,An=w(()=>{"use strict";_i=q(require("fastify"),1);cr();Ot=class{plugins=new Map;transformerServices=new Set;disposed=!1;revision=0;attachTransformerService(e){this.assertOpen();let t=[...this.plugins.values()].flatMap(r=>[...r.transformers].map(([s,a])=>{if(e.hasTransformer(s))throw new Error(`transformer "${s}" is already registered`);return[s,e.preparePluginTransformer(a)]})),o=[];try{for(let[r,s]of t)o.push(r),e.registerTransformer(r,s);this.transformerServices.add(e)}catch(r){for(let s of o)e.removeTransformer(s);throw r}}beginActivation(e,t,o,r){if(this.assertOpen(),this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);let s={manifest:{...e},directory:r,runtimes:new Map,transformers:new Map,protectors:[],routes:[],preparedRoutes:[]},a="staging",i,c=u=>{try{if(this.assertOpen(),a!=="staging")throw new Error("plugin activation is no longer open");u()}catch(p){throw i=p,p}};return{context:{manifest:s.manifest,log:t,host:o,registerTransformer:u=>c(()=>{let p=typeof u.TransformerName=="string"?u.TransformerName:new u().name;if(typeof p!="string"||!p)throw new Error("plugin transformer has no name");if(s.transformers.has(p))throw new Error(`transformer "${p}" is already registered`);s.transformers.set(p,u)}),registerManagedRuntime:u=>c(()=>{if(!u.name||typeof u.isManaged!="function"||typeof u.signRequest!="function")throw new Error("invalid managed runtime");if(s.runtimes.has(u.name))throw new Error(`managed runtime "${u.name}" is already registered`);s.runtimes.set(u.name,u)}),registerAdminRoutes:u=>c(()=>{s.routes.push(u)}),registerConfigProtector:u=>c(()=>{s.protectors.push(u)}),registerUiCard:u=>c(()=>{if(s.cardPath)throw new Error("plugin card is already registered");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(u.cardPath))throw new Error("card must be a single JavaScript file");s.cardPath=u.cardPath}),registerLocales:u=>c(()=>{s.locales=u})},commit:async(u,p)=>{this.assertOpen();let d=this.revision;if(s.routes.length){if(!p)throw new Error("plugin admin routes require a host app");s.preparedRoutes=await this.prepareRoutes(s.routes,p)}if(this.assertOpen(),this.revision!==d)throw new Error("plugin registry changed during activation; retry activation");if(a!=="staging")throw new Error("plugin activation is no longer open");if(i)throw i;if(this.plugins.has(e.name))throw new Error(`plugin "${e.name}" is already registered`);for(let g of this.plugins.values()){for(let m of s.runtimes.keys())if(g.runtimes.has(m))throw new Error(`managed runtime "${m}" is already registered`);for(let m of s.transformers.keys())if(g.transformers.has(m))throw new Error(`transformer "${m}" is already registered`)}let f=[...this.transformerServices].flatMap(g=>[...s.transformers].map(([m,y])=>{if(g.hasTransformer(m))throw new Error(`transformer "${m}" is already registered`);return{service:g,name:m,value:g.preparePluginTransformer(y)}})),h=[];try{for(let g of f)h.push(g),g.service.registerTransformer(g.name,g.value);s.card=u,this.plugins.set(e.name,s),this.revision++,a="committed"}catch(g){for(let m of h)m.service.removeTransformer(m.name);throw a="aborted",g}},get cardPath(){return s.cardPath},abort:()=>{a="aborted"}}}getManagedRuntimeFor(e){for(let t of this.plugins.values())for(let o of t.runtimes.values())try{if(o.isManaged(e))return o}catch{}}getRegisteredRuntimes(){return[...this.plugins.values()].flatMap(e=>[...e.runtimes.values()])}applyConfigProtectors(e,t){for(let o of this.plugins.values())for(let r of o.protectors)r(e,t)}listLoadedPlugins(){return[...this.plugins.values()].map(e=>({name:e.manifest.name,version:e.manifest.version,enabled:!0,...e.card?{cardUrl:`/plugins/${e.manifest.name}/${e.cardPath}`}:{},...e.locales?{locales:e.locales}:{}}))}getPublicCard(e,t){let o=this.plugins.get(e);return o?.cardPath===t&&o.card?Buffer.from(o.card):void 0}async prepareRoutes(e,t){let o=new Set(["get","post","put","patch","delete","head","options","all"]),r=[],s=new Proxy(t,{get:(i,c)=>{if(c==="route")return u=>(r.push(u),s);if(o.has(String(c)))return(u,p,d)=>(r.push({...typeof p=="function"?{}:p,method:c==="all"?["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]:String(c).toUpperCase(),url:u,handler:d??p}),s);let l=Reflect.get(i,c);return typeof l=="function"?()=>{throw new Error(`plugin route registration cannot call ${String(c)}`)}:l}}),a=(0,_i.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")}},tu=new Ot,ur=()=>tu});function ki(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 ze(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?nu(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=bi(n.name,i);return c.isRateLimit=i.httpStatus===429,c.upstreamStatus=e,r?.errorName&&(c.upstreamErrorName=r.errorName),c}function nu(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 Ti=w(()=>{"use strict";An()});var On,dr=w(()=>{On="2.3.2428"});var vi={};kn(vi,{getFallbackPromotionStore:()=>ot,resetFallbackPromotionStore:()=>su});function ot(n){return Be||(Be=new pr,n&&Be.configure(n)),Be}function su(){Be&&(Be.clearAll(),Be=null)}var ru,pr,Be,In=w(()=>{"use strict";de();ru=600*1e3,pr=class{promotions=new Map;enabled=!0;ttlMs=ru;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,t,o){return`${e},${t}:${o}`}promote(e,t,o,r,s,a){if(!this.enabled)return;let i=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(i,{promotedModel:c,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[c,...l]=a.promotedModel.split(","),u=l.join(",");if(!H().isAvailable(c,u))return this.promotions.delete(s),null;let d=r.find(h=>h.name.toLowerCase()===c.toLowerCase()),f=d?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return!d||!f||d.enabled===!1?(this.promotions.delete(s),null):`${d.name},${f}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},Be=null});function lu(n){try{if(!(0,Te.existsSync)(gr))return;let e=JSON.parse((0,Te.readFileSync)(gr,"utf-8"));if(!Array.isArray(e))return;let t=Date.now();for(let o of e){if(!o||!o.provider||!o.model)continue;let r=o.updatedAt||o.lastFailureTime||0;r&&t-r>1440*60*1e3||n.restore({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount??0,successCount:o.successCount??0,lastFailureTime:o.lastFailureTime??0,lastProbeTime:o.lastProbeTime??0,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil})}}catch{}}function Ci(n){try{let e=n.getAllStates();if(e.length===0)return;(0,Te.existsSync)(mr)||(0,Te.mkdirSync)(mr,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,Te.writeFileSync)(gr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Mn(){if(xi)return;xi=!0;let n=H();lu(n),cu=setInterval(()=>Ci(n),6e4),process.on("exit",()=>Ci(n))}function H(n){return fr||(fr=new It(n)),fr}var Te,hr,Si,iu,au,It,mr,gr,xi,cu,fr,de=w(()=>{"use strict";Te=require("fs"),hr=require("path"),Si=require("@wengine-ai/claude-code-router-shared"),iu=120,au={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},It=class{states=new Map;config;probeTimer;constructor(e){this.config={...au,...e}}getKey(e,t){return!e||!t?null:`${e},${t}`}recordSuccess(e,t){if(!this.config.enabled)return;let o=this.getKey(e,t);if(!o)return;let r=this.states.get(o);if(!r||(r.successCount++,r.rateLimitUntil&&r.rateLimitUntil>Date.now()))return;let s=!!r.rateLimitUntil;r.rateLimitUntil=void 0,r.status==="half-open"?r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o)):r.status==="open"&&(r.status="half-open",r.successCount=1,r.failureCount=0),s&&r.status==="half-open"&&r.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,t),this.states.delete(o))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(In(),Ys(vi));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??iu)*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)}},mr=(0,hr.join)(Si.HOME_DIR,"runtime"),gr=(0,hr.join)(mr,"provider-health.json"),xi=!1,cu=null;fr=null});function Mt(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=yr(o,uu),s=yr(o,du),a=yr(o,pu);(r||s||a)&&rt.set(n,{provider:n,remaining:Pi(r),limit:Pi(s),reset:fu(a),capturedAt:Date.now()})}function Oi(n){return rt.get(n)}function Ln(){return Array.from(rt.values())}function Nn(n,e=Date.now()){return typeof n=="number"&&n*1e3<=e}function yr(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function Pi(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function fu(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=mu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function mu(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 gu(){try{if(!(0,ve.existsSync)(br))return;let n=JSON.parse((0,ve.readFileSync)(br,"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;rt.set(t.provider,t)}}catch{}}function Ei(){try{if(rt.size===0)return;(0,ve.existsSync)(_r)||(0,ve.mkdirSync)(_r,{recursive:!0}),(0,ve.writeFileSync)(br,JSON.stringify(Array.from(rt.values()),null,2),"utf-8")}catch{}}function st(){Ri||(Ri=!0,gu(),wi=setInterval(Ei,6e4),wi.unref?.(),process.on("exit",Ei))}var ve,kr,Ai,_r,br,rt,Ri,wi,uu,du,pu,Je=w(()=>{"use strict";ve=require("fs"),kr=require("path"),Ai=require("@wengine-ai/claude-code-router-shared"),_r=(0,kr.join)(Ai.HOME_DIR,"runtime"),br=(0,kr.join)(_r,"rate-limit.json"),rt=new Map,Ri=!1,wi=null,uu=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],du=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],pu=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Fn(){return Tr||(Tr=new xr),Tr}function Sr(){return vr||(vr=new Cr),vr}function hu(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function Ii(n){let e=hu(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 Mi(n,e){let t=Fn(),o=n?.[$n];if(o&&!o.released){if(o.key===e)return;t.release(o)}n[$n]=t.acquire(e)}function Rr(n){let e=n?.[$n];e&&Fn().release(e)}function Li(n,e){let t=Ii(n),o=n?.[$n],r=t?Sr().get(t)!==void 0:!1;!o&&!r||(t&&Sr().bind(t,e),Mi(n,e))}function yu(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 Ni(n,e,t){let o=Ii(n),r=Sr(),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=yu(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 Mi(n,i),i}var xr,Cr,Tr,vr,$n,Un=w(()=>{"use strict";xr=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()}},Tr=null,vr=null;$n="__concurrencyLease"});async function j(n){let e=await n.text();return _u(e,n.status)}function _u(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 $i(n){return(n.headers.get("Content-Type")||"").includes("text/event-stream")}function Lt(n){return/^\s*(event:|data:|:\s*[A-Z])/m.test(n)||n.startsWith("data:")}async function 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})),Lt(s))||/^\s*[\[{]/.test(s))break}s+=r.decode()}finally{o.releaseLock()}return e.cancel().catch(()=>{}),{body:t,isSSE:Lt(s)}}async function Ee(n){try{let e=await n.text();if(Lt(e)){let o=new TextEncoder,r=new ReadableStream({start(s){s.enqueue(o.encode(e)),s.close()}});return{response:new Response(r,{status:n.status,statusText:n.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}),isSSE:!0}}return{response:new Response(e,{status:n.status,statusText:n.statusText,headers:n.headers}),isSSE:!1}}catch{return{response:n,isSSE:!1}}}var oe=w(()=>{"use strict"});function bu(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 Dn(n){for(let e of bu(n))if(e.startsWith("response."))return!0;return!1}var it,wr=w(()=>{"use strict";oe();it=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let t=e?.input_tokens??e?.prompt_tokens??0,o=e?.output_tokens??e?.completion_tokens??0,r=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:t,output_tokens:o,total_tokens:e?.total_tokens??t+o,input_tokens_details:{cached_tokens:r,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:r,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let t=[],o=e.messages.filter(r=>r.role==="system");if(o.length>0){let r=o[0];Array.isArray(r.content)?r.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),t.push({role:"system",content:a})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(a=>this.normalizeRequestContent(a,r.role)).filter(a=>a!==null);s.length>0?r.content=s:delete r.content}if(r.role==="tool"){let s={...r};s.type="function_call_output",s.call_id=r.tool_call_id,s.output=r.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,t.push(s);return}if(r.role==="assistant"&&Array.isArray(r.tool_calls)){r.tool_calls.forEach(s=>{t.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}t.push(r)}}),e.input=t,delete e.messages,Array.isArray(e.tools)){let r=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),r&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e,t){let o=e.headers.get("Content-Type")||"";if(!o.includes("text/event-stream")&&!o.includes("application/json")&&e.body){let r=await 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 j(e);if(r.object==="response"&&r.output){let s=this.convertResponseToChat(r);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(o.includes("text/event-stream")){if(!e.body)return e;let[r,s]=e.body.tee(),a=r.getReader(),i="",c=new TextDecoder;try{for(let u=0;u<8&&i.length<65536;u++){let{value:p,done:d}=await a.read();if(d||(p&&(i+=c.decode(p,{stream:!0})),Dn(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}):Dn(i)?this.getClientFormat(t)!=="responses"?this.buildResponsesToChatStream(s,t):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}normalizeRequestContent(e,t){let o={...e};if(delete o.cache_control,e.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){let r={type:t==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}getClientFormat(e){let t=e?.responseTargetFormat;return t==="responses"||t==="chat"||t==="anthropic"?t:"responses"}buildResponsesToChatStream(e,t){let o=new TextDecoder,r=new TextEncoder,s="chatcmpl-"+Date.now(),a=t?.provider?.models?.[0],i="",c,l,u,p,d="",f=new Map,h=new Map,g=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(R,E=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:l||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:c||a,choices:[{index:0,delta:R,finish_reason:E}]})}
|
|
3
|
+
`);a=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?ui(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&&ui(e,t,s,a.trim()),s++),di(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),di(e,t,s)}finally{r.releaseLock()}})()}var tu,nu,nt,ir,It=w(()=>{"use strict";tu=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),nu=/token|secret|credential|passwd|password/i,nt={maxBodyLength:4096,maxStreamChunks:100},ir=!1});function hi(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:En(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:ru(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),l)}function ru(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 yi=w(()=>{ae();It()});function iu(n){return n.includes('"delta"')?/"delta"\s*:\s*\{[^}]*"(content|tool_calls|reasoning_content|reasoning|function_call)"\s*:\s*("|\[|\{)/.test(n):!1}function _i(n){return/"type"\s*:\s*"response\.[A-Za-z0-9_.]+"/.test(n)||/(^|\n)\s*(event:\s*)?response\.[A-Za-z0-9_.]+/.test(n)}function ar(n){if(_i(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(su.some(s=>r.includes(s))){e=!0;break}au.some(s=>r.includes(s))&&(t=!0)}}return e||iu(n)?"content":t?"empty":"pending"}async function bi(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(ar(a)==="content"?"content":"pending",On(o,f));if(g.done){a+=r.decode();let m=ar(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=ar(a);if(h==="content")return c("content",On(o));if(h==="empty")return await o.cancel().catch(()=>{}),c("empty",null);if(_i(a)||i>=e)return c("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 ki(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 su,au,Ti=w(()=>{"use strict";su=["content_block_start","content_block_delta","content_block_stop"];au=["message_stop","response.completed","response.incomplete","[DONE]"]});function cu(n,e){return`${n.name}|${e?.name??""}`}function cr(n){return n.__ccrPluginRequestState??={budgets:new Map}}function ot(n,e,t){let o=cr(n),r=cu(e,t),s=o.budgets.get(r);return s||(s={refreshUsed:!1},o.budgets.set(r,s)),s}function lr(n,e,t,o){return!e||t?.nonRetryable!==!0?!1:(ot(n,e,o).terminalError=t,!0)}var vi=w(()=>{"use strict"});var ur=w(()=>{"use strict"});function Si(n,e){let t=new Error(e.message);return t.code=e.code,t.statusCode=e.httpStatus,e.cooldownMs&&(t.cooldownMs=e.cooldownMs),e.validationUrl&&(t.validationUrl=e.validationUrl),t.plugin=n,t.nonRetryable=!e.retryable,t.pluginClassified=!0,t}var xi,Mt,lu,pr,In=w(()=>{"use strict";xi=ee(require("fastify"),1);ur();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,xi.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")}},lu=new Mt,pr=()=>lu});function Ci(n){if(!n||typeof n!="object")return{};let e={},t;try{t=n?.name}catch{}typeof t=="string"&&/^[A-Za-z]{1,40}$/.test(t)&&(e.errorName=t);let o;try{o=n?.cause}catch{o=void 0}for(let r=0;o&&typeof o=="object"&&r<3;r++){try{let s=o.code;if(!e.causeCode&&typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(s)&&(e.causeCode=s),!e.causeDetail){let a=typeof o.address=="string"?o.address:"",i=typeof o.port=="number"&&Number.isInteger(o.port)&&o.port>0&&o.port<=65535?o.port:void 0;a&&/^[0-9A-Za-z.:%\[\]-]{1,60}$/.test(a)?e.causeDetail=i!==void 0?`${a}:${i}`:a:typeof o.hostname=="string"&&/^[0-9A-Za-z.-]{1,120}$/.test(o.hostname)&&(e.causeDetail=o.hostname)}}catch{}if(e.causeCode&&e.causeDetail)break;try{o=o?.cause}catch{break}}return e}async function 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?uu(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=Si(n.name,i);return l.isRateLimit=i.httpStatus===429,l.upstreamStatus=e,r?.errorName&&(l.upstreamErrorName=r.errorName),l}function uu(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 Ri=w(()=>{"use strict";In()});var Mn,fr=w(()=>{Mn="2.3.2430"});var wi={};vn(wi,{getFallbackPromotionStore:()=>rt,resetFallbackPromotionStore:()=>fu});function rt(n){return Je||(Je=new mr,n&&Je.configure(n)),Je}function fu(){Je&&(Je.clearAll(),Je=null)}var pu,mr,Je,Ln=w(()=>{"use strict";ue();pu=600*1e3,mr=class{promotions=new Map;enabled=!0;ttlMs=pu;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 yu(n){try{if(!(0,Te.existsSync)(yr))return;let e=JSON.parse((0,Te.readFileSync)(yr,"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 Ei(n){try{let e=n.getAllStates();if(e.length===0)return;(0,Te.existsSync)(hr)||(0,Te.mkdirSync)(hr,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,Te.writeFileSync)(yr,JSON.stringify(t,null,2),"utf-8")}catch{}}function $n(){if(Pi)return;Pi=!0;let n=z();yu(n),hu=setInterval(()=>Ei(n),6e4),process.on("exit",()=>Ei(n))}function z(n){return gr||(gr=new Lt(n)),gr}var Te,_r,Ai,mu,gu,Lt,hr,yr,Pi,hu,gr,ue=w(()=>{"use strict";Te=require("fs"),_r=require("path"),Ai=require("@wengine-ai/claude-code-router-shared"),mu=120,gu={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Lt=class{states=new Map;config;probeTimer;constructor(e){this.config={...gu,...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(),ti(wi));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??mu)*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)}},hr=(0,_r.join)(Ai.HOME_DIR,"runtime"),yr=(0,_r.join)(hr,"provider-health.json"),Pi=!1,hu=null;gr=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=br(o,_u),s=br(o,bu),a=br(o,ku);(r||s||a)&&st.set(n,{provider:n,remaining:Mi(r),limit:Mi(s),reset:Tu(a),capturedAt:Date.now()})}function Ni(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 br(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function Mi(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=vu(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function vu(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 xu(){try{if(!(0,ve.existsSync)(Tr))return;let n=JSON.parse((0,ve.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 Li(){try{if(st.size===0)return;(0,ve.existsSync)(kr)||(0,ve.mkdirSync)(kr,{recursive:!0}),(0,ve.writeFileSync)(Tr,JSON.stringify(Array.from(st.values()),null,2),"utf-8")}catch{}}function it(){Oi||(Oi=!0,xu(),Ii=setInterval(Li,6e4),Ii.unref?.(),process.on("exit",Li))}var ve,vr,$i,kr,Tr,st,Oi,Ii,_u,bu,ku,We=w(()=>{"use strict";ve=require("fs"),vr=require("path"),$i=require("@wengine-ai/claude-code-router-shared"),kr=(0,vr.join)($i.HOME_DIR,"runtime"),Tr=(0,vr.join)(kr,"rate-limit.json"),st=new Map,Oi=!1,Ii=null,_u=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],bu=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],ku=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});function Fn(){return xr||(xr=new Cr),xr}function wr(){return Sr||(Sr=new Rr),Sr}function Su(n){return n?.sessionId||n?.clientContext?.stableSessionId||void 0}function Ui(n){let e=Su(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 Di(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 Pr(n){let e=n?.[Dn];e&&Fn().release(e)}function Fi(n,e){let t=Ui(n),o=n?.[Dn],r=t?wr().get(t)!==void 0:!1;!o&&!r||(t&&wr().bind(t,e),Di(n,e))}function Cu(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 l=o.count(i);l<s&&(r=i,s=l)}return r}function ji(n,e,t){let o=Ui(n),r=wr(),s=Fn(),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=Cu(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 Di(n,i),i}var Cr,Rr,xr,Sr,Dn,jn=w(()=>{"use strict";Cr=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()}},Rr=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()}},xr=null,Sr=null;Dn="__concurrencyLease"});async function H(n){let e=await n.text();return Ru(e,n.status)}function Ru(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 Hi(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 wu(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 wu(n))if(e.startsWith("response."))return!0;return!1}var at,Er=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})),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="",l,c,u,p,d="",f=new Map,g=new Map,h=0,m=!1,y=!1,b=!1,_=this,k=new ReadableStream({start(T){let x=(S,M=null)=>{T.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[{index:0,delta:S,finish_reason:M}]})}
|
|
5
5
|
|
|
6
|
-
`))},v=
|
|
6
|
+
`))},v=S=>{if(!S)return;let M=_.getCacheReadInputTokens(S),L=typeof S.input_tokens=="number"?S.input_tokens:void 0,U=_.getCacheCreationInputTokens(S);T.enqueue(r.encode(`data: ${JSON.stringify({id:c||s,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l||a,choices:[],usage:{prompt_tokens: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
|
-
`))},S
|
|
8
|
+
`))},P=S=>{m||(m=!0,T.enqueue(r.encode(`data: ${JSON.stringify({error:{message:S,type:"upstream_error"},choices:[{index:0,delta:{},finish_reason:"error"}]})}
|
|
9
9
|
|
|
10
|
-
`)))},
|
|
10
|
+
`)))},A=S=>{y||(y=!0,v(u),x({},S))},R=()=>{b||(b=!0,T.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{T.error(S)}catch{}return}finally{try{I.releaseLock()}catch{}}try{T.close()}catch{}})()}});return new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[r,s]=e.body.tee(),a=r.getReader(),i="";try{for(let d=0;d<8&&i.length<65536;d++){let{value:f,done:g}=await a.read();if(g||(f&&(i+=new TextDecoder().decode(f,{stream:!0})),Hn(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")||Hn(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
|
-
`),
|
|
16
|
-
`);y=x.pop()||"";for(let v of x){let
|
|
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 T of d)if(T.type==="function_call"){let x=d.indexOf(T);h.enqueue(f("response.function_call_arguments.done",{type:"response.function_call_arguments.done",item_id:T.call_id||T.id,output_index:x,arguments:T.arguments||""})),T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}for(let T of d)if(T.type==="message"){let x=d.indexOf(T);T.status="completed",h.enqueue(f("response.output_item.done",{type:"response.output_item.done",output_index:x,item:T}))}h.enqueue(f("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:k?.model||s,output:d.slice(),usage:k?.usage?{...this.buildResponsesUsage(k.usage)}:this.buildResponsesUsage()}}))}};for(;;){let{done:k,value:T}=await m.read();if(k)break;y+=o.decode(T,{stream:!0});let x=y.split(`
|
|
16
|
+
`);y=x.pop()||"";for(let v of x){let P=v.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,T=!1,x=null,v=[],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(!T){if(T=!0,_){let S=v.find(M=>M.type==="message");S&&(S.content=[{type:"output_text",text:i}],S.status="completed")}for(let S of v)S.type==="function_call"&&(S.status="completed");return P("response.completed",{type:"response.completed",response:{id:a,object:"response",created_at:Math.floor(Date.now()/1e3),status:"completed",model:s,output:v,usage: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:""};v.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:[]};v.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:[]};v.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:[]};v.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=v.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=v.find(Q=>Q.type==="message");N&&(N.content=[{type:"output_text",text:i}],O(c,N))}if(x==="thinking"&&k){let N=v.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
|
-
`))}}}P();let M=$();M&&O.enqueue(M),E="",O.close()}catch(R){O.error(R)}}})}wrapChatInResponses(e){let t=e?.choices?.[0],o=[],r=[];if(t?.message?.content&&r.push({type:"output_text",text:t.message.content}),o.push({type:"message",role:"assistant",content:r}),Array.isArray(t?.message?.tool_calls))for(let s of t.message.tool_calls)o.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:o,usage:e.usage?{...this.buildResponsesUsage(e.usage)}:void 0}}convertResponseToChat(e){let t=e.output?.find(l=>l.type==="message"),o;t?.content?.length&&t?.content[0].annotations&&(o=t.content[0].annotations.map(l=>({type:"url_citation",url_citation:{url:l.url||"",title:l.title||"",content:"",start_index:l.start_index||0,end_index:l.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let r=null,s=null,a=null;if(t&&t.reasoning&&(a={content:t.reasoning}),t&&t.content){let l=[],u=[];if(t.content.forEach(p=>{if(p.type==="output_text")l.push(p.text||"");else if(p.type==="output_image"){let d=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});d&&u.push(d)}else if(p.type==="output_image_base64"){let d=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});d&&u.push(d)}}),u.length>0){let p=[];l.length>0&&p.push({type:"text",text:l.join("")}),p.push(...u),r=p}else r=l.join("")}let i=(e.output??[]).filter(l=>l.type==="function_call");return i.length>0&&(s=i.map(l=>({id:l.call_id||l.id,type:"function",function:{name:l.name,arguments:l.arguments}}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:r||null,tool_calls:s,thinking:a,annotations:o},logprobs:null,finish_reason:s?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_tokens:this.getCacheCreationInputTokens(e.usage)},cache_read_input_tokens:this.getCacheReadInputTokens(e.usage),cache_creation_input_tokens:this.getCacheCreationInputTokens(e.usage)}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}}});var Pr,ee,jn=w(()=>{"use strict";Pr=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)}},ee=new Pr(100)});function Hn(n,e){n&&at.set(n,{...e,provider:n,capturedAt:Date.now()})}function Nt(n){let e=at.get(n);return e?{...e}:void 0}function zn(){return Array.from(at.values()).map(n=>({...n}))}function ku(){try{if(!(0,Ce.existsSync)(Ar))return;let n=JSON.parse((0,Ce.readFileSync)(Ar,"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;at.set(t.provider,t)}}catch{}}function Di(){try{if(at.size===0)return;(0,Ce.existsSync)(Er)||(0,Ce.mkdirSync)(Er,{recursive:!0}),(0,Ce.writeFileSync)(Ar,JSON.stringify(Array.from(at.values()),null,2),"utf-8")}catch{}}function ct(){Fi||(Fi=!0,ku(),Ui=setInterval(Di,6e4),Ui.unref?.(),process.on("exit",Di))}var Ce,Or,ji,Er,Ar,at,Fi,Ui,lt=w(()=>{"use strict";Ce=require("fs"),Or=require("path"),ji=require("@wengine-ai/claude-code-router-shared"),Er=(0,Or.join)(ji.HOME_DIR,"runtime"),Ar=(0,Or.join)(Er,"quota-store.json"),at=new Map,Fi=!1,Ui=null});function Se(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Tu.test(e)))return e}function Re(n){if(!n)return;if(typeof n=="object")return Se(n.session_id??n.sessionId);if(typeof n!="string")return;let e=n.trim();if(!e)return;try{let r=JSON.parse(e),s=Se(r?.session_id??r?.sessionId);if(s)return s}catch{}let t="_session_",o=e.lastIndexOf(t);if(o!==-1)return Se(e.slice(o+t.length))}var Tu,ut=w(()=>{"use strict";Tu=/^[A-Za-z0-9_-]+$/});function Eu(){if(dt.size<=Hi)return;let n=[...dt.keys()].slice(0,dt.size-Hi);for(let e of n)dt.delete(e)}function Au(){if(pt.size<=zi)return;let n=[...pt].slice(0,pt.size-zi);for(let e of n)pt.delete(e)}function Ou(n){let e=n.trim();if(!e||e==="."||e===".."||/[/\\\0]/.test(e))return[];let t=e.replace(/^sess_/,"");return[...new Set([e,t,`sess_${t}`])].filter(Boolean)}function Iu(n,e){let t;try{t=(0,Ji.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 Mu(n,e){let t;try{t=await(0,Bn.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,Ir.existsSync)(s))try{let a=JSON.parse(await(0,Bn.readFile)(s,"utf8")),i=a?.meta?.workspacePath??a?.workspacePath;if(typeof i=="string"&&i.trim())return i.trim()}catch{}}return null}async function Wi(n){let e=typeof n=="string"?n.trim():"";if(!e)return null;let t=dt.get(e);if(t)return t;let o=async()=>{let r=Ou(e);if(r.length===0)return null;let s=(0,ye.join)(vu(),xu),a=(0,ye.join)(s,Cu);if((0,Ir.existsSync)(a)){let i=Iu(a,r);if(i)return i}return Mu((0,ye.join)(s,Su),r)};try{let r=await o();if(!r&&!pt.has(e)){pt.add(e),Au();for(let a=0;a<Ru&&!r;a++)await Pu(wu),r=await o()}if(!r||!(0,ye.isAbsolute)(r))return null;let s=(0,ye.normalize)(r);return dt.set(e,s),Eu(),s}catch{return null}}var Ir,Bn,Bi,ye,Ji,vu,xu,Cu,Su,Hi,zi,Ru,wu,dt,pt,Pu,Ki=w(()=>{"use strict";Ir=require("fs"),Bn=require("fs/promises"),Bi=require("os"),ye=require("path"),Ji=require("@wengine-ai/claude-code-router-shared"),vu=()=>process.env.CCR_ZCODE_DIR||(0,ye.join)((0,Bi.homedir)(),".zcode"),xu="v2",Cu="tasks-index.sqlite",Su="sessions",Hi=500,zi=500,Ru=3,wu=50,dt=new Map,pt=new Set,Pu=n=>new Promise(e=>setTimeout(e,n))});function Yi(n){return typeof n=="string"&&n.length<=Lu}function Nu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of Qi){let{value:t}=Jn(n,e);if(!Yi(t))continue;let o=Se(t);if(o)return o}}function Fu(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 Uu(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 Jn(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 Gi(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 $t(n,e=!0){return{clientType:n,usageScope:"request",supportsExplicitExtendedContext:e}}function Mr(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"&&$u.includes(n)}function Gu(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function We(n){if(Nr(n?.clientType))return n.clientType;let e=Uu(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Fu(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(Jn(n,Wn.CCR_PROJECT_HEADER).present||Jn(n,"x-session-affinity").present)return"pi";if(Gu(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 $r(n){return Lr[n]}function Vu(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,Vi.randomUUID)();return n.__ccrRequestScopeId=e,e}function Ae(n,e={}){let t=We(n),o=$r(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:Vu(n),s=o.usageScope==="session"?"session":"request";n.clientType=t,n.clientContext=o,o.stableSessionId?n.sessionId=o.stableSessionId:delete n.sessionId,o.projectHeaderPresent?n.projectId=o.projectId:delete n.projectId,Gi(n,Wn.CCR_PROJECT_HEADER),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of Qi)Gi(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function Xi(){}var Vi,Wn,Qi,Lu,$u,Du,ju,Hu,zu,Bu,Ju,Wu,Ku,Lr,ft=w(()=>{"use strict";Vi=require("node:crypto"),Wn=require("@wengine-ai/claude-code-router-shared");ut();Qi=["x-session-affinity","x-session-id","x-litellm-session-id"],Lu=256;$u=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Du={type:"claude-code",createContext(n){return Mr(n,"claude-code")}},ju={type:"zcode",createContext(n){return Mr(n,"zcode")}},Hu={type:"pi",createContext(n){let e=Jn(n,Wn.CCR_PROJECT_HEADER),t=Nu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||Re(n?.body?.metadata?.user_id),o=Yi(t)?t:void 0;return{...$t("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},zu={type:"qwen-code",createContext(n){return Mr(n,"qwen-code")}},Bu={type:"opencode",createContext(){return $t("opencode")}},Ju={type:"codex",createContext(){return $t("codex")}},Wu={type:"api",createContext(){return $t("api")}},Ku={type:"unknown",createContext(){return $t("unknown")}},Lr={"claude-code":Du,zcode:ju,pi:Hu,"qwen-code":zu,opencode:Bu,codex:Ju,api:Wu,unknown:Ku}});function ce(n,e,t,o){let r=Fr(e,t);if(r.code==="model_unhealthy"){let i=X(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=na[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 Qn(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 Dt(n){let e=Qn(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 Xu(n,e){if(!e||!n)return null;let t=Qn(n);if(e[n])return e[n];if(e[t])return e[t];let{family:o}=Dt(n);if(o&&e[o])return e[o];for(let[r,s]of Object.entries(e)){let a=Qn(r);if(a&&t.includes(a))return s}return null}function Zu(n){return n?(n.input_tokens||0)+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0):0}function Kn(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 Fr(n,e){let t=Kn(n);if(!t)return{reason:`invalid model format "${n}" (expected "provider,model")`,code:"invalid_model_format"};let{providerName:o,routeModel:r}=t,s=e.find(l=>l.name?.toLowerCase()===o.toLowerCase());if(!s)return{reason:`provider "${o}" not found`,code:"provider_not_found"};if(s.enabled===!1)return{reason:`provider "${o}" is disabled`,code:"provider_disabled"};let a=s.models?.find(l=>String(l).toLowerCase()===r.toLowerCase());if(!a)return{reason:`model "${r}" not found in provider "${o}"`,code:"model_not_found"};if(!H().isAvailable(s.name,String(a),s.apiKey?.startsWith("ccr-managed-")===!0||s.api_key?.startsWith("ccr-managed-")===!0))return{reason:`model "${r}" in provider "${o}" is temporarily unavailable (health fail-pool)`,code:"model_unhealthy"};let c=Nt(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 X(n,e,t,o,r,s,a){let i=Kn(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=ot(),f=d.getPromotion(c,l,o,e);if(f){let h=Kn(f);if(h){let g=Ft(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(c,l,o)}}return null}if(r===!0&&o&&!t&&s!==!1){let d=ot(),f=d.getPromotion(c,l,o,e);if(f){let h=Kn(f);if(h){let g=Ft(e,h.providerName,h.routeModel);if(g)return`${g.provider.name},${g.model}`}d.clear(c,l,o)}}if(!t&&!H().isAvailable(u.provider.name,u.model,u.provider.apiKey?.startsWith("ccr-managed-")===!0||u.provider.api_key?.startsWith("ccr-managed-")===!0))return null;let p=Nt(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=H(),i=[t?.[n],o?.[n]];for(let c of i)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let u=X(l,e,!1,n,void 0,void 0,s);if(u)return u}return null}function qu(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 jt(n){let e=Qn(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 oa(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,Zu(e))}function ra(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function ed(n,e,t,o,r,s,a,i,c,l,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??c??6e4,h=oa(e,r,d),g=n.modelFamily,m=ra(d,t,l),y=d?.supportsExplicitExtendedContext!==!1&&s===!0;if((y||h>m)&&t.extendedContext){let k=X(t.extendedContext,o,!1,"extendedContext",i,p,u);if(k)return n.log.info(`Family: using extended context model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let T=i?re("extendedContext",o,t.fallback,a,g,u):null;if(T)return n.log.info(`Family: using extended context fallback model (1M+), tokens: ${h}, estimated: ${e}, explicit: ${y}, threshold: ${m}`),{model:T,scenarioType:"extendedContext",isFallback:!0};if(u){let x=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(h>f&&(t.longContext||t.fallback?.longContext?.length||a?.longContext?.length)){let k=t.longContext?X(t.longContext,o,!1,"longContext",i,p,u):null;if(k)return n.log.info(`Family: using long context model, tokens: ${h}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let T=i?re("longContext",o,t.fallback,a,g,u):null;if(T)return n.log.info(`Family: using long context fallback model, tokens: ${h}, estimated: ${e}`),{model:T,scenarioType:"longContext",isFallback:!0};if(u&&t.longContext){let x=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=X(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,g,u):null;if(T)return n.log.info("Family: using webSearch fallback model"),{model:T,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=X(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,g,u):null;if(T)return n.log.info("Family: using think fallback model"),{model:T,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=X(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,g,u):null;if(T)return n.log.info("Family: using default fallback model"),{model:T,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 sd(){if(Ke.size<=Zi)return;let n=[...Ke.keys()].slice(0,Ke.size-Zi);for(let e of n)Ke.delete(e)}function id(){if(mt.size<=qi)return;let n=[...mt].slice(0,mt.size-qi);for(let e of n)mt.delete(e)}var ta,Gn,Yn,Vn,pe,na,se,_e,Ut,Yu,td,Ht,Ke,Zi,mt,qi,nd,od,rd,ea,Ur,Ge=w(()=>{"use strict";ta=require("tiktoken");jn();Gn=require("fs/promises"),Yn=require("fs/promises"),Vn=require("path"),pe=require("@wengine-ai/claude-code-router-shared");de();lt();In();Un();ut();Ki();ft();na={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||na[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};_e=(0,ta.get_encoding)("cl100k_base"),Ut=(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},Yu=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 Ur(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Wi(n.sessionId);s&&(0,pe.isZcodeProjectTakeoverActive)(s)&&(r=(0,pe.getClaudeProjectId)(s))}if(r){n.projectId=r;let s=(0,Vn.join)(pe.HOME_DIR,r,"config.json");if(!t&&n.sessionId){let a=(0,Vn.join)(pe.HOME_DIR,r,`${n.sessionId}.json`);try{let i=JSON.parse(await(0,Gn.readFile)(a,"utf8"));if(i&&i.Router&&Object.keys(i.Router).length>0)return i.Router}catch{}}try{let a=JSON.parse(await(0,Gn.readFile)(s,"utf8"));if(t&&(typeof a?.projectPath!="string"||(0,pe.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})}}}};td=async(n,e,t,o,r,s)=>{let a=t.get("providers")||[],i=r||t.get("Router"),c=i?.enableFallback===!0,l=c?i?.fallback:void 0,u=c&&!s?l||t.get("fallback"):l,p=!s,d=null;if(n.body?.system?.length>1&&n.body?.system[1]?.text?.includes("<CCR-SUBAGENT-MODEL>")){let v=n.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);v&&(n.body.system[1].text=n.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${v[1]}</CCR-SUBAGENT-MODEL>`,""),d=v[1])}let{family:f,extended:h,isCcrAlias:g}=Dt(n.body.model),m=i?.families?.[f||""];if(m&&i?.enableFamilyRouting){n.log.info(`Using model family routing for: ${f}${h?" (1M)":""}`),n.modelFamily=f,n.familyFallback=m.fallback;let v=ed(n,e,m,a,o,h,u,c,i?.longContextThreshold,i?.extendedContextThreshold,s,p);if(v)return{model:v.model,scenarioType:v.scenarioType}}if(n.body.model.includes(",")&&!s){let v=X(n.body.model,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Explicit model ${n.body.model} unavailable (fail pool), trying fallback`);let S=c?re("default",a,void 0,u,void 0,s):null;if(S)return n.log.info(`Using fallback for explicit model: ${S}`),{model:S,scenarioType:"default"};n.log.warn(`No fallback available for explicit model ${n.body.model}, continuing through routing logic`)}let y=g&&!i?.enableFamilyRouting?null:Xu(n.body.model,i?.models);if(y){let v=X(y,a,!1,"modelMapping",c,p,s);if(v)return n.log.info(`Using mapped model for ${n.body.model}: ${y}`),{model:v,scenarioType:"modelMapping"};let S=c?re("modelMapping",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"modelMapping"};if(s){let C=ce(n,y,a,"modelMapping");if(C)return{model:C,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${y} unavailable (fail pool), skipping`)}let b=n.clientContext,_=oa(e,o,b),k=ra(b,void 0,i?.extendedContextThreshold);if(_>k&&i?.extendedContext){n.log.info(`Using extended context (1M) model due to token count: ${_}, estimated: ${e}, threshold: ${k}`);let v=X(i.extendedContext,a,!1,"extendedContext",c,p,s);if(v)return{model:v,scenarioType:"extendedContext"};n.log.warn(`Extended context model ${i.extendedContext} unavailable (fail pool), trying fallback`);let S=c?re("extendedContext",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"extendedContext"};if(s){let C=ce(n,i.extendedContext,a,"extendedContext");if(C)return{model:C,scenarioType:"extendedContext"}}}let T=b?.longContextThreshold??i?.longContextThreshold??6e4;if(_>T&&i?.longContext){n.log.info(`Using long context model due to token count: ${_}, estimated: ${e}, threshold: ${T}`);let v=X(i.longContext,a,!1,"longContext",c,p,s);if(v)return{model:v,scenarioType:"longContext"};n.log.warn(`Long context model ${i.longContext} unavailable (fail pool), trying fallback`);let S=c?re("longContext",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"longContext"};if(s){let C=ce(n,i.longContext,a,"longContext");if(C)return{model:C,scenarioType:"longContext"}}}if(!s&&d)return n.subagentOverrideModel=d,{model:d,scenarioType:"default"};if(n.body.model?.includes("claude")&&n.body.model?.includes("haiku")&&i?.background){n.log.info(`Using background model for ${n.body.model}`);let v=X(i.background,a,!1,"background",c,p,s);if(v)return{model:v,scenarioType:"background"};let S=c?re("background",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"background"};if(s){let C=ce(n,i.background,a,"background");if(C)return{model:C,scenarioType:"background"}}n.log.warn(`Background model ${i.background} unavailable (fail pool), falling through`)}if(Array.isArray(n.body.tools)&&n.body.tools.some(v=>v.type?.startsWith("web_search"))&&i?.webSearch){let v=X(i.webSearch,a,!1,"webSearch",c,p,s);if(v)return{model:v,scenarioType:"webSearch"};n.log.warn(`WebSearch model ${i.webSearch} unavailable (fail pool), trying fallback`);let S=c?re("webSearch",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"webSearch"};if(s){let C=ce(n,i.webSearch,a,"webSearch");if(C)return{model:C,scenarioType:"webSearch"}}}if(n.body.thinking?.type==="enabled"&&i?.think){n.log.info(`Using think model for ${n.body.thinking}`);let v=X(i.think,a,!1,"think",c,p,s);if(v)return{model:v,scenarioType:"think"};n.log.warn(`Think model ${i.think} unavailable (fail pool), trying fallback`);let S=c?re("think",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"think"};if(s){let C=ce(n,i.think,a,"think");if(C)return{model:C,scenarioType:"think"}}}if(i?.default){let v=X(i.default,a,!1,"default",c,p,s);if(v)return{model:v,scenarioType:"default"};n.log.warn(`Default model ${i.default} unavailable (fail pool), trying fallback`);let S=c?re("default",a,void 0,u,void 0,s):null;if(S)return{model:S,scenarioType:"default"};let C=X(i.default,a,!0,"default",c,p,s);if(C)return n.log.warn(`No fallback available; retrying default model ${i.default} despite fail-pool state (strict=${s})`),{model:C,scenarioType:"default"}}if(s){let v=ce(n,i?.default||n.body.model,a,"default");if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Ht=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 Yu(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??ee.get(n.usageCacheKey):void 0,{messages:p,system:d=[],tools:f}=n.body,h=o.get("REWRITE_SYSTEM_PROMPT");if(h&&d.length>1&&d[1]?.text?.includes("<env>")){let g=await(0,Gn.readFile)(h,"utf-8");d[1].text=`${g}<env>${d[1].text.split("<env>").pop()}`}try{let[g,m]=n.body.model.split(","),y=t.tokenizerService?.getTokenizerConfigForModel(g,m),b;t.tokenizerService?b=(await t.tokenizerService.countTokens({messages:p,system:d,tools:f},y,g)).tokenCount:b=Ut(p,d,f),n.tokenCount=b;let _,k=l?void 0:o.get("CUSTOM_ROUTER_PATH");if(k)try{_=await require(k)(n,o.getAll(),{event:r})}catch(S){n.log.error(`failed to load custom router: ${S.message}`)}if(_)n.scenarioType="default";else{let S=await td(n,b,o,u,s,!!s);_=S.model,n.scenarioType=S.scenarioType}let{family:T}=Dt(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[x?.image,a?.image].filter((S,C,P)=>!!S&&P.indexOf(S)===C);if(v.length>0&&qu(n)&&!jt(_))if(v.includes(_))n.scenarioType="image";else{let S=v.map(C=>X(C,c,!1,"image",i,!l,l)).find(C=>!!C);if(S)n.log.info(`Using image model fallback for ${_}`),_=S,n.scenarioType="image";else{let C=i?re("image",c,x?.fallback,n.fallbackConfig,T||void 0,l):null;if(C)n.log.info(`Using image fallback model: ${C}`),_=C,n.scenarioType="image";else if(l){let P=ce(n,v[0],c,"image");P&&(_=P,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let S=n.scenarioType||"default",C=[...(n.familyFallback||{})[S]||[],...(n.fallbackConfig||{})[S]||[]];_=Ni(n,_,{threshold:Number(a?.concurrencyThreshold)||3,fallbackModels:C,resolve:P=>X(P,c,!1,S,i,!l,l),log:P=>n.log.info(P)})}typeof _=="string"&&_.trim()?n.body.model=_:(n.log.warn(`Router could not resolve a valid model for ${n.originalModel||n.body.model}; keeping original request model`),n.scenarioType=n.scenarioType||"default")}catch(g){if(g instanceof se)throw g;if(n.log.error(`Error in router middleware: ${g.message}`),l){let m=n.sessionId||n.clientContext?.stableSessionId;throw new se(`Project routing error: router failure in project mode. ${g.message}. Session: "${m||"unknown"}".`,{sessionId:m,configuredTarget:a?.default,code:"project_router_failure",statusCode:502})}n.body.model=a?.default,n.scenarioType="default"}},Ke=new Map,Zi=1e3,mt=new Set,qi=1e3,nd=3,od=50,rd=n=>new Promise(e=>setTimeout(e,n));ea=async n=>{let e=await(0,Yn.opendir)(pe.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,Vn.join)(pe.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},Ur=async n=>{let e=Se(n);if(!e)return null;if(Ke.has(e))return Ke.get(e)||null;try{let t=await ea(e);if(!t&&!mt.has(e)){mt.add(e),id();for(let o=0;o<nd&&!t;o++)await rd(od),t=await ea(e)}return t?(Ke.set(e,t),sd(),t):null}catch(t){return console.error("Error searching for project by session:",t),null}}});function zt(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 Ar,te,zn=w(()=>{"use strict";Ar=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 Ar(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 Pu(){try{if(!(0,Se.existsSync)(Ir))return;let n=JSON.parse((0,Se.readFileSync)(Ir,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>1440*60*1e3)continue;ct.set(t.provider,t)}}catch{}}function Ji(){try{if(ct.size===0)return;(0,Se.existsSync)(Or)||(0,Se.mkdirSync)(Or,{recursive:!0}),(0,Se.writeFileSync)(Ir,JSON.stringify(Array.from(ct.values()),null,2),"utf-8")}catch{}}function ut(){zi||(zi=!0,Pu(),Bi=setInterval(Ji,6e4),Bi.unref?.(),process.on("exit",Ji))}var Se,Mr,Wi,Or,Ir,ct,zi,Bi,Ke=w(()=>{"use strict";Se=require("fs"),Mr=require("path"),Wi=require("@wengine-ai/claude-code-router-shared"),Or=(0,Mr.join)(Wi.HOME_DIR,"runtime"),Ir=(0,Mr.join)(Or,"quota-store.json"),ct=new Map,zi=!1,Bi=null});function Ce(n){if(typeof n!="string")return;let e=n.trim();if(!(!e||!Eu.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 Eu,dt=w(()=>{"use strict";Eu=/^[A-Za-z0-9_-]+$/});function Uu(){if(pt.size<=Ki)return;let n=[...pt.keys()].slice(0,pt.size-Ki);for(let e of n)pt.delete(e)}function Du(){if(ft.size<=Gi)return;let n=[...ft].slice(0,ft.size-Gi);for(let e of n)ft.delete(e)}function Fu(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 ju(n,e){let t;try{t=(0,Vi.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 Hu(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,Lr.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 Yi(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=Fu(e);if(r.length===0)return null;let s=(0,ye.join)(Au(),Ou),a=(0,ye.join)(s,Iu);if((0,Lr.existsSync)(a)){let i=ju(a,r);if(i)return i}return Hu((0,ye.join)(s,Mu),r)};try{let r=await o();if(!r&&!ft.has(e)){ft.add(e),Du();for(let a=0;a<Lu&&!r;a++)await Nu($u),r=await o()}if(!r||!(0,ye.isAbsolute)(r))return null;let s=(0,ye.normalize)(r);return pt.set(e,s),Uu(),s}catch{return null}}var Lr,Jn,Qi,ye,Vi,Au,Ou,Iu,Mu,Ki,Gi,Lu,$u,pt,ft,Nu,Xi=w(()=>{"use strict";Lr=require("fs"),Jn=require("fs/promises"),Qi=require("os"),ye=require("path"),Vi=require("@wengine-ai/claude-code-router-shared"),Au=()=>process.env.CCR_ZCODE_DIR||(0,ye.join)((0,Qi.homedir)(),".zcode"),Ou="v2",Iu="tasks-index.sqlite",Mu="sessions",Ki=500,Gi=500,Lu=3,$u=50,pt=new Map,ft=new Set,Nu=n=>new Promise(e=>setTimeout(e,n))});function ta(n){return typeof n=="string"&&n.length<=zu}function Bu(n){if(!(!n?.headers||typeof n.headers!="object"))for(let e of ea){let{value:t}=Wn(n,e);if(!ta(t))continue;let o=Ce(t);if(o)return o}}function Wu(n){if(typeof n=="string")return n.slice(0,1e3);if(Array.isArray(n)){let e=n.find(t=>t&&typeof t.text=="string");return e?String(e.text).slice(0,1e3):""}return""}function Ku(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 Zi(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 $r(n,e,t=!0){let o=Re(n?.body?.metadata?.user_id);return{clientType:e,usageScope:o?"session":"request",stableSessionId:o,supportsExplicitExtendedContext:t}}function Ur(n){return typeof n=="string"&&Ju.includes(n)}function td(n,e){return/zcode/i.test(e)?!0:Object.keys(n).some(t=>t.toLowerCase().startsWith("x-zcode"))}function Ge(n){if(Ur(n?.clientType))return n.clientType;let e=Ku(n),t=n?.headers||{},o=typeof t["user-agent"]=="string"?t["user-agent"]:"",r=n?.body||{},s=Wu(r.system);if(/\bYou are Qwen Code\b/i.test(s)||/Qwen Code, an interactive CLI agent/i.test(s))return"qwen-code";if(/operating inside pi\b/i.test(s)||/a coding agent harness/i.test(s))return"pi";if(/\bYou are opencode\b/i.test(s))return"opencode";if(Wn(n,Kn.CCR_PROJECT_HEADER).present||Wn(n,"x-session-affinity").present)return"pi";if(td(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 Dr(n){return Nr[n]}function nd(n){if(typeof n?.__ccrRequestScopeId=="string"&&n.__ccrRequestScopeId)return n.__ccrRequestScopeId;let e=typeof n?.id=="string"&&n.id||(0,qi.randomUUID)();return n.__ccrRequestScopeId=e,e}function Ae(n,e={}){let t=Ge(n),o=Dr(t).createContext(n,e),r=o.usageScope==="session"&&o.stableSessionId?o.stableSessionId:nd(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,Zi(n,Kn.CCR_PROJECT_HEADER),t==="pi"&&o.stableSessionId&&(n.__ccrSessionAffinity=o.stableSessionId);for(let a of ea)Zi(n,a);return n.usageSessionId=r,n.usageCacheKey=`${t}:${s}:${r}`,o}function na(){}var qi,Kn,ea,zu,Ju,Gu,Qu,Vu,Yu,Xu,Zu,qu,ed,Nr,mt=w(()=>{"use strict";qi=require("node:crypto"),Kn=require("@wengine-ai/claude-code-router-shared");dt();ea=["x-session-affinity","x-session-id","x-litellm-session-id"],zu=256;Ju=["claude-code","zcode","pi","qwen-code","opencode","codex","api","unknown"];Gu={type:"claude-code",createContext(n){return $r(n,"claude-code")}},Qu={type:"zcode",createContext(n){return $r(n,"zcode")}},Vu={type:"pi",createContext(n){let e=Wn(n,Kn.CCR_PROJECT_HEADER),t=Bu(n)||(typeof n?.__ccrSessionAffinity=="string"?n.__ccrSessionAffinity:void 0)||Re(n?.body?.metadata?.user_id),o=ta(t)?t:void 0;return{...Dt("pi",!1),stableSessionId:o,projectId:e.value,projectHeaderPresent:e.present}}},Yu={type:"qwen-code",createContext(n){return $r(n,"qwen-code")}},Xu={type:"opencode",createContext(){return Dt("opencode")}},Zu={type:"codex",createContext(){return Dt("codex")}},qu={type:"api",createContext(){return Dt("api")}},ed={type:"unknown",createContext(){return Dt("unknown")}},Nr={"claude-code":Gu,zcode:Qu,pi:Vu,"qwen-code":Yu,opencode:Xu,codex:Zu,api:qu,unknown:ed}});function ce(n,e,t,o){let r=Fr(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=aa[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 sd(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 id(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 Fr(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(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=Gn(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=Gn(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=Gn(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 ad(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 ca(n,e,t){return t?.usageScope!=="session"?n:Math.max(n,id(e))}function la(n,e,t){return n?.extendedContextThreshold??e?.extendedContextThreshold??t??2e5}function cd(n,e,t,o,r,s,a,i,l,c,u,p){let d=n.clientContext,f=d?.longContextThreshold??t.longContextThreshold??l??6e4,g=ca(e,r,d),h=n.modelFamily,m=la(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 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 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 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 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 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 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 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 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 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 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 fd(){if(Qe.size<=oa)return;let n=[...Qe.keys()].slice(0,Qe.size-oa);for(let e of n)Qe.delete(e)}function md(){if(gt.size<=ra)return;let n=[...gt].slice(0,gt.size-ra);for(let e of n)gt.delete(e)}var ia,Qn,Yn,ht,de,aa,se,_e,jt,rd,ld,Bt,Qe,oa,gt,ra,ud,dd,pd,sa,jr,Ve=w(()=>{"use strict";ia=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();Xi();mt();aa={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||aa[t?.code||""]||502,this.code=t?.code||"project_routing_error",this.type="api_error",this.sessionId=t?.sessionId,this.configuredTarget=t?.configuredTarget}};_e=(0,ia.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},rd=async(n,e)=>{let t=n.clientContext?.projectHeaderPresent===!0,o=n.clientContext?.projectId;if(t&&(typeof o!="string"||o.length===0||o.length>1024||o==="."||o===".."||/[/\\\0]/.test(o)))throw new se(`Project routing error: invalid managed project id "${String(o)}".`,{configuredTarget:String(o),code:"invalid_project_id"});let r=t?o:n.sessionId?await jr(n.sessionId):null;if(!r&&!t&&n.clientType==="zcode"&&n.sessionId){let s=await Yi(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})}}}};ld=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:T}=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=cd(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 v=T&&!i?.enableFamilyRouting?null:sd(n.body.model,i?.models);if(v){let C=Z(v,a,!1,"modelMapping",l,p,s);if(C)return n.log.info(`Using mapped model for ${n.body.model}: ${v}`),{model:C,scenarioType:"modelMapping"};let 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,v,a,"modelMapping");if(S)return{model:S,scenarioType:"modelMapping"}}n.log.warn(`Mapped model ${v} unavailable (fail pool), skipping`)}if(y&&!g){let C=`${y.name},${b}`;return n.log.info(`Exact provider model ${f} routes to ${C}`),{model:C,scenarioType:"default"}}let P=n.clientContext,A=ca(e,o,P),R=la(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 rd(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,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=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 ld(n,b,o,u,s,!!s);_=P.model,n.scenarioType=P.scenarioType}let{family:T}=Ht(n.originalModel||n.body.model),x=a?.enableFamilyRouting&&T?a.families?.[T]:void 0,v=[x?.image,a?.image].filter((P,A,R)=>!!P&&R.indexOf(P)===A);if(v.length>0&&ad(n)&&!zt(_))if(v.includes(_))n.scenarioType="image";else{let P=v.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,T||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,v[0],l,"image");R&&(_=R,n.scenarioType="image")}else n.log.warn(`Image models ${v.join(", ")} unavailable (fail pool), keeping ${_}`),n.scenarioType="image"}}if(a?.enableConcurrencyPriority===!0&&!(n.originalModel||"").includes(",")&&!n.subagentOverrideModel&&typeof _=="string"&&_.trim()){let P=n.scenarioType||"default",A=[...(n.familyFallback||{})[P]||[],...(n.fallbackConfig||{})[P]||[]];_=ji(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,oa=1e3,gt=new Set,ra=1e3,ud=3,dd=50,pd=n=>new Promise(e=>setTimeout(e,n));sa=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},jr=async n=>{let e=Ce(n);if(!e)return null;if(Qe.has(e))return Qe.get(e)||null;try{let t=await sa(e);if(!t&&!gt.has(e)){gt.add(e),md();for(let o=0;o<ud&&!t;o++)await pd(dd),t=await sa(e)}return t?(Qe.set(e,t),fd(),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(
|
|
28
|
-
`).filter(d=>d.startsWith("data:")&&d.trim().length>5).length===0){s.releaseLock();let d=
|
|
29
|
-
`):""}async function sa(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})),ud(l,a?.req);for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];!i?.suppressDebugLog&&Rn(o.configService)&&ci(o.log,a.req.id,{url:String(c),headers:l,body:n});let u,p=()=>di(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 ze(i,0,void 0,gt(n),ki(d)):d}if(!u.ok&&i?.authRefresh&&u.status===401&&!nt(a.req,i,t).refreshUsed){nt(a.req,i,t).refreshUsed=!0;try{await i.authRefresh.forceRefresh(),l=await i.signRequest({headers:l,requestBody:n,provider:t}),u=await p()}catch{}u.status===401&&(a.req.__retryAttempted=!0)}if(!u.ok){let d;try{d=await u.text()}catch(h){throw i?await ze(i,u.status,void 0,gt(n)):h}if(i){let h=await ze(i,u.status,d,gt(n));throw o.log.error(`[provider_response_error] Plugin(${i.name}) status=${u.status} code=${h.code}`),h}o.log.error(`[provider_response_error] Error from provider(${t.name},${n.model}: ${u.status}): ${d}`);let f=K(`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 h="";try{if(h=await u.clone().text(),!h||h.trim()==="")throw new SyntaxError("Empty JSON body");if(Lt(h))return o.log.info(`[hidden-error-check] body is SSE mislabeled as ${d}, skipping JSON validation`),u;let m=JSON.parse(h);if(i?.isErrorEnvelope?.(m))throw await ze(i,u.status,h,gt(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 ze(i,u.status,h,gt(n));o.log.error(`[provider_response_error] Hidden error from provider(${t.name},${n.model}: ${u.status}): ${h}`);let b=Xn(h),_=K(`Error from provider(${t.name},${n.model}: ${u.status}): ${h}`,400,"provider_response_error");throw _.isRateLimit=b,_.rawBody=h,_}}catch(g){if(i)throw g?.pluginClassified===!0?g:await ze(i,u.status,void 0,gt(n));if(g instanceof SyntaxError){o.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${t.name},${n.model}: 200): "${h}"`);let m=K(`API returned an empty or malformed response (HTTP 200) from ${t.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw m.rawBody=h,m}throw g}}}if(!i?.suppressDebugLog&&!n.stream&&Rn(o.configService)){let f=await u.clone().text();li(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function da(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 it().transformResponseIn(a,{...s,provider:t})}catch(i){console.error("Failed to apply Responses API conversion for codex client:",i)}return a}async function pa(n,e,t,o){n.ok||e.code(n.status);let r=$i(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&&Rn(o.configService)){let[s,a]=n.body.tee(),i=ai(o.configService);return ui(s,o.log,e.request.id,i),e.send(a)}return e.send(n.body)}else return j(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 pd(n){try{return new URL(n),!0}catch{return!1}}var ad,fa,Zn=w(()=>{"use strict";pi();Cn();hi();yi();Ti();At();dr();de();Je();In();Un();wr();oe();Ge();ae();ad=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;fa=async n=>{n.get("/",async()=>({message:"LLMs API",version:On})),n.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),n.get("/providers/health",async()=>({states:H().getAllStates().map(r=>({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount,successCount:r.successCount,lastFailureTime:r.lastFailureTime,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=n.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&n.post(t.endPoint,async(o,r)=>ia(o,r,n,t));n.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,o)=>{let{name:r,baseUrl:s,apiKey:a,models:i}=t.body;if(!r?.trim())throw K("Provider name is required",400,"invalid_request");if(!s||!pd(s))throw K("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw K("API key is required",400,"invalid_request");if(!i||!Array.isArray(i)||i.length===0)throw K("At least one model is required",400,"invalid_request");if(n.providerService.getProvider(t.body.name))throw K(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return n.providerService.registerProvider(t.body)}),n.get("/providers",async()=>n.providerService.getProviders()),n.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let o=n.providerService.getProvider(t.params.id);if(!o)throw K("Provider not found",404,"provider_not_found");return o}),n.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},proxyEnabled:{type:"boolean"},enabled:{type:"boolean"}}}}},async(t,o)=>{let r=n.providerService.updateProvider(t.params.id,t.body);if(!r)throw K("Provider not found",404,"provider_not_found");return r}),n.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!n.providerService.deleteProvider(t.params.id))throw K("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),n.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,o)=>{if(!n.providerService.toggleProvider(t.params.id,t.body.enabled))throw K("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})}});var Ve,Dr=w(()=>{"use strict";Ve=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,ma,fd,ga,ht=w(()=>{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,ma=["low","medium","high"],fd={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"},ga=n=>{if(typeof n=="string")return fd[n.trim().toLowerCase()]}});var jr,ha=w(()=>{jr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function md(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ya(n){let e=[],t=[],o=d=>{if(typeof d=="string"){t.push({type:"text",text:d});return}Array.isArray(d)&&d.forEach(f=>{if(typeof f=="string"){t.push({type:"text",text:f});return}f&&typeof f=="object"&&f.type==="text"&&f.text&&t.push({...f})})},r=()=>{let d=new Map;for(let f=0;f<t.length;f++){let h=t[f],g=h?.text??JSON.stringify(h),m=d.get(g);if(m===void 0){d.set(g,f);continue}!t[m]?.cache_control&&h?.cache_control&&(t[m]=h),t.splice(f,1),f--}};n.messages.forEach(d=>{d.role==="system"?o(d.content):e.push(d)}),r();let s=[];for(let d=0;d<e.length;d++){let f=e[d];if(f.role==="tool"){let h=f.content;try{typeof f.content=="string"&&(h=JSON.parse(f.content))}catch{}h!=null&&typeof h!="object"&&typeof h!="string"&&(h=String(h));let g={type:"tool_result",tool_use_id:f.tool_call_id,content:h};f.cache_control&&(g.cache_control=f.cache_control);let m=s[s.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(g):s.push({role:"user",content:[g]})}else if(f.role==="user"){let h=[];typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&f.content.forEach(m=>{m&&typeof m=="object"&&m.type==="image_url"&&m.image_url?.url?h.push({type:"image",source:{type:"base64",media_type:m.media_type||"image/jpeg",data:m.image_url.url.split(",")[1]||m.image_url.url}}):h.push(m)});let g=s[s.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"user",content:h.length>0?h:[{type:"text",text:" "}]})}else if(f.role==="assistant"){let h=[];f.content&&(typeof f.content=="string"?h.push({type:"text",text:f.content}):Array.isArray(f.content)&&h.push(...f.content)),f.tool_calls&&f.tool_calls.length>0&&f.tool_calls.forEach(m=>{let y={};try{y=JSON.parse(m.function.arguments)}catch{y=m.function.arguments}h.push({type:"tool_use",id:m.id,name:m.function.name,input:y})}),f.thinking&&h.unshift({type:"thinking",thinking:f.thinking.content,signature:f.thinking.signature});let g=s[s.length-1];g&&g.role==="assistant"&&Array.isArray(g.content)?g.content.push(...h):s.push({role:"assistant",content:h.length>0?h:[{type:"text",text:" "}]})}}let a=()=>{let d=t.filter(f=>f?.cache_control).length;for(let f of s)Array.isArray(f.content)&&(d+=f.content.filter(h=>h?.cache_control).length);return d},i=d=>d&&typeof d=="object"?{...d}:{type:"ephemeral"},c=()=>{for(let d=s.length-1;d>=0;d--){let f=s[d]?.content;if(!Array.isArray(f))continue;let h=f.find(g=>g?.cache_control);if(h?.cache_control)return h.cache_control}for(let d=t.length-1;d>=0;d--)if(t[d]?.cache_control)return t[d].cache_control;return{type:"ephemeral"}},l=(d,f)=>{if(!Array.isArray(d?.content)||d.content.some(g=>g?.cache_control))return!1;let h=d.content.find(g=>g&&typeof g=="object"&&!g.cache_control);return h?(h.cache_control=i(f),!0):!1};(()=>{let d=4-a();if(d<=0||s.length===0)return;let f=s,h=c(),g=[];for(let m=f.length-1;m>=0;m--)f[m]?.role!=="user"||!Array.isArray(f[m].content)||g.push(m);for(let m of g){if(d<=0)break;l(f[m],h)&&d--}})();let p={messages:s,model:n.model,max_tokens:n.max_tokens||4096,temperature:n.temperature,stream:n.stream};if(n.reasoning?.enabled){let d=n.reasoning.max_tokens||qn(n.reasoning.effort||"medium"),f=Math.min(d,p.max_tokens-1024);f>=1024&&(p.thinking={type:"enabled",budget_tokens:f});let h=n.reasoning.effort&&n.reasoning.effort!=="none"?n.reasoning.effort:Oe(d);ma.includes(h)&&(p.output_config={...p.output_config||{},effort:h})}if(t.length>0){let d=t.some(f=>f?.cache_control);p.system=d?t:t.map(f=>f.text||"").join(`
|
|
30
|
-
|
|
31
|
-
`)}return n.tools&&n.tools.length>0&&(p.tools=
|
|
32
|
-
`);u?(
|
|
33
|
-
`),this.logger?.debug?.({type:"tool_image_omitted",model:String(e.model??""),count:
|
|
34
|
-
`));let u=i.content.filter(d=>d.type==="tool_use"&&d.id);u.length&&(
|
|
35
|
-
data: ${JSON.stringify(
|
|
36
|
-
|
|
37
|
-
`)),
|
|
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 da(n,e,t,o){let r=n.body;(n.ccrHookOrder||=[]).push("handler"),cr(n);let s=bd(n);n.codexDetected=s,o.endPoint==="/v1/responses"&&r?.input&&!r?.messages&&Jt(r),o.endPoint==="/v1/responses"&&!n.provider&&typeof r?.model=="string"&&gd.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:ma(n,o,s),pluginRegistry:t.pluginRegistry},{requestBody:u,config:p,bypass:d}=await fa(r,i,o,n.headers,c);if(u?.messages&&!d&&!n.isTargetAnthropic){let m=u.messages,y=new Set,b=[],_=[];for(let k of m){if(k?.role!=="system"){_.push(k);continue}let T=JSON.stringify(k.content??"");y.has(T)||(y.add(T),b.push(k))}b.length>0&&_.length>0&&(u.messages=[...b,..._])}let f=await ga(u,p,i,t,d,o,c);try{i?.baseUrl&&f?.headers&&$t(a,i.baseUrl,f.headers)}catch{}let g=await ha(u,f,i,o,d,c);g=await pa(r,g,i.name||a);let h=ya(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(!lr(n,t.pluginRegistry.getManagedRuntimeFor(i),c,i)&&!n.__retryAttempted){n.__retryAttempted=!0;try{return await da(n,e,t,o)}catch(d){if(n.__fallbackExhausted)throw d;c=d}}let p=await hd(n,e,t,o,c);if(p)return p;throw n.__fallbackExhausted=!0,c}}async function pa(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 bi(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(ki(p.chunks,p.rest),{headers:e.headers,status:e.status,statusText:e.statusText})}async function hd(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&&Xn(r.rawBody)||r?.message&&Xn(r.message);if(u&&p&&(f?(c.markRateLimited(u,p,120,r?.message),n.log.warn(`Primary model ${u},${p} rate-limited, will try fallbacks`)):c.recordFailure(u,p,r?.message),d.add(`${u},${p}`),t.recordUsage?.({provider:u,model:p,originalModel:n.originalModel||p,scenarioType:s,modelFamily:n.modelFamily,errorMessage:r?.message||String(r),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})),!(n.enableFallback??t.configService.get("Router")?.enableFallback===!0))return n.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let h=b=>{let[_,...k]=b.split(","),T=_?.trim(),x=k.join(",").trim();return!T||!x?null:{provider:T,model:x,key:`${T},${x}`}},m=[];if(i){let b=a?.[s];if(Array.isArray(b)&&b.length>0)m.push({name:`${i}/${s}`,models:b});else{let _=n.strictProjectRouting;n.log.warn(`No ${i} fallback configured for ${s}; ${_?"no project fallback available":"will try global fallback"}`)}}if(Array.isArray(l?.[s])&&l[s].length>0&&m.push({name:`global/${s}`,models:l[s]}),m.length===0&&s!=="image"&&n.body?.messages?.some(k=>k.role==="user"&&Array.isArray(k.content)&&k.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(x=>x.type==="image"||x.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(n.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),m.push({name:"global/image (auto-detected)",models:l.image})),m.length===0)return null;let y=m.reduce((b,_)=>b+_.models.length,0);n.log.warn(`Request failed for ${s}, trying ${y} fallback models across ${m.length} fallback stage(s)`);for(let b of m){n.log.info(`Trying ${b.name} fallback stage with ${b.models.length} models`);for(let _ of b.models){let k=h(_);if(!k){n.log.warn(`Fallback model '${_}' is invalid, skipping`);continue}if(d.has(k.key))continue;d.add(k.key);let T=t.providerService.getProviders(),x=Ft(T,k.provider,k.model);if(!x){n.log.warn(`Fallback model ${_} is not configured or provider is disabled, skipping`);continue}let v=x.provider.name,P=x.model;if(!c.isAvailable(v,P,x.provider.apiKey?.startsWith("ccr-managed-")===!0)){n.log.warn(`Fallback model ${_} unavailable (fail pool), skipping`);continue}let A=t.pluginRegistry.getManagedRuntimeFor(x.provider);if(A&&ot(n,A,{name:v}).terminalError)continue;let R;for(let O=1;O<=2;O++)try{n.log.info(`Trying fallback model: ${v},${P}${O>1?" (retry)":""}`);let F={...n.body};F.model=P;let C={...n,provider:v,body:F},I=x.provider,S={pluginRegistry:t.pluginRegistry,req:C,isCodexOnMessagesEndpoint:n.isCodexOnMessagesEndpoint||!1,responseTargetFormat:ma(C,o,C.codexDetected===!0)},{requestBody:M,config:L,bypass:U}=await fa(F,I,o,n.headers,S),$=await ga(M,L,I,t,U,o,S);try{I?.baseUrl&&$?.headers&&$t(v,I.baseUrl,$.headers)}catch{}let j=await ha(M,$,I,o,U,S);return j=await pa(F,j,v),n.log.info(`Fallback model ${v},${P} succeeded`),c.recordSuccess(v,P),u&&p&&!n.strictProjectRouting&&(rt().promote(u,p,s,v,P),n.log.info(`Promoted fallback model ${v},${P} for ${u},${p}:${s}`),f?n.log.info(`Rate-limited original model ${u},${p} already marked unavailable with cooldown`):(c.forceOpen(u,p,r?.message),n.log.info(`Marked original model ${u},${p} as unavailable`))),n.provider=v,n.body=F,Fi(n,`${v},${P}`),ya(j,e,F,t)}catch(F){if(R=F,lr(n,A,F,{name:v}))break;if(O===1){n.log.warn(`Fallback model ${v},${P} failed, retrying once: ${F.message}`);continue}}c.recordFailure(v,P,R?.message),n.log.warn(`Fallback model ${v},${P} failed after retry: ${R?.message}`),t.recordUsage?.({provider:v,model:P,originalModel:n.originalModel||p||n.body.model,scenarioType:s,modelFamily:n.modelFamily,errorMessage:R?.message||String(R),sessionId:n.sessionId||n.usageSessionId||n.id,stream:n.body.stream,inputTokens:n.tokenCount||0,req:n})}}return n.log.error(`All fallback models failed for ${s}`),null}async function fa(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=yd(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 yd(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 _d(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 ma(n,e,t){return n.codexDetected??t?"responses":e?.endPoint==="/v1/messages"?"anthropic":"chat"}function bd(n){if(n.clientType)return n.clientType==="codex";let e=n.headers||{},t=e["x-anthropic-billing-header"]||"";if(typeof t=="string"&&t.includes("cc_version="))return!1;let o=e["user-agent"]||"";if(typeof o=="string"&&/codex/i.test(o))return!0;let r=n.pathname||n.url||"";if(typeof r=="string"&&r.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=n.originalModel||n.body?.model||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function ga(n,e,t,o,r,s,a){let i=o.pluginRegistry.getManagedRuntimeFor(t);return i?.dispatchRequest?i.dispatchRequest({attempt:()=>ua(n,e,t,o,r,s,a),requestBody:n,config:e,provider:t,req:a?.req}):ua(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 ua(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})),_d(c,a?.req);for(let d in c)(c[d]==="undefined"||["authorization","Authorization"].includes(d)&&c[d]?.includes("undefined"))&&delete c[d];!i?.suppressDebugLog&&Pn(o.configService)&&fi(o.log,a.req.id,{url:String(l),headers:c,body:n});let u,p=()=>hi(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),Ci(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||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();mi(o.log,a.req.id,{status:u.status,headers:Object.fromEntries(Array.from(u.headers)),body:f})}return u}async function ha(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 ya(n,e,t,o){n.ok||e.code(n.status);let r=Hi(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=pi(o.configService);return gi(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 kd(n){try{return new URL(n),!0}catch{return!1}}var gd,_a,Zn=w(()=>{"use strict";yi();Rn();Ti();vi();Ri();It();fr();ue();We();Ln();jn();Er();oe();Ve();ae();gd=/^ccr-(opus|sonnet|haiku)(\[1m\])?$/i;_a=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)=>da(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||!kd(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,Hr=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,qn,ba,Td,ka,_t=w(()=>{"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,ba=["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"},ka=n=>{if(typeof n=="string")return Td[n.trim().toLowerCase()]}});var zr,Ta=w(()=>{zr=(n,e)=>(n.includes("base64")&&(n=n.split("base64").pop(),n.startsWith(",")&&(n=n.slice(1))),`data:${e};base64,${n}`)});function vd(n){return n.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function va(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||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);ba.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
|
+
|
|
31
|
+
`)}return n.tools&&n.tools.length>0&&(p.tools=vd(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 xa=w(()=>{_t()});function xd(n){return n?.cache_read_input_tokens??n?.input_tokens_details?.cached_tokens??n?.prompt_tokens_details?.cached_tokens??0}function eo(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:xd(n),cache_creation_input_tokens:eo(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 to=w(()=>{"use strict"});function Sd(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 Br(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 no,oo,Sa=w(()=>{"use strict";no=require("uuid");_t();Rn();oe();Ta();xa();Ve();to();oo=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
|
+
`);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"?zr(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"?zr(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=ka(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=Sd(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=va(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,T=-1,x=()=>{let R=k;return k++,R},v=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(T>=0){let O={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
35
|
+
data: ${JSON.stringify(O)}
|
|
36
|
+
|
|
37
|
+
`)),T=-1}if(i)v(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;v(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"};v(s.encode(`event: message_stop
|
|
44
|
+
data: ${JSON.stringify(R)}
|
|
45
45
|
|
|
46
|
-
`)),r.close(),
|
|
47
|
-
`);
|
|
48
|
-
data: ${JSON.stringify(
|
|
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)}};v(s.encode(`event: error
|
|
48
|
+
data: ${JSON.stringify($)}
|
|
49
49
|
|
|
50
|
-
`));continue}if(
|
|
51
|
-
data: ${JSON.stringify(
|
|
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}}};v(s.encode(`event: message_start
|
|
51
|
+
data: ${JSON.stringify(j)}
|
|
52
52
|
|
|
53
|
-
`))}let
|
|
54
|
-
data: ${JSON.stringify(
|
|
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:$,...Br(L.usage)?{cache_creation_input_tokens:eo(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||{};Br(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:""}};v(s.encode(`event: content_block_start
|
|
54
|
+
data: ${JSON.stringify(j)}
|
|
55
55
|
|
|
56
|
-
`)),
|
|
57
|
-
data: ${JSON.stringify(
|
|
56
|
+
`)),T=$,_=!0}if(U.delta.thinking.signature){let $={type:"content_block_delta",index:T,delta:{type:"signature_delta",signature:U.delta.thinking.signature}};v(s.encode(`event: content_block_delta
|
|
57
|
+
data: ${JSON.stringify($)}
|
|
58
58
|
|
|
59
|
-
`));let
|
|
60
|
-
data: ${JSON.stringify(
|
|
59
|
+
`));let j={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
60
|
+
data: ${JSON.stringify(j)}
|
|
61
61
|
|
|
62
|
-
`)),
|
|
63
|
-
data: ${JSON.stringify(
|
|
62
|
+
`)),T=-1}else if(U.delta.thinking.content){let $={type:"content_block_delta",index:T,delta:{type:"thinking_delta",thinking:U.delta.thinking.content||""}};v(s.encode(`event: content_block_delta
|
|
63
|
+
data: ${JSON.stringify($)}
|
|
64
64
|
|
|
65
|
-
`))}}if(
|
|
66
|
-
data: ${JSON.stringify(
|
|
65
|
+
`))}}if(U?.delta?.content&&!b&&!p){if(m++,T>=0&&!u){let j={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
66
|
+
data: ${JSON.stringify(j)}
|
|
67
67
|
|
|
68
|
-
`)),
|
|
69
|
-
data: ${JSON.stringify(
|
|
68
|
+
`)),T=-1}if(!u&&!p){u=!0;let $=x();d();let j={type:"content_block_start",index:$,content_block:{type:"text",text:""}};v(s.encode(`event: content_block_start
|
|
69
|
+
data: ${JSON.stringify(j)}
|
|
70
70
|
|
|
71
|
-
`)),
|
|
72
|
-
data: ${JSON.stringify(
|
|
71
|
+
`)),T=$}if(!b&&!p){let $={type:"content_block_delta",index:T,delta:{type:"text_delta",text:U.delta.content}};v(s.encode(`event: content_block_delta
|
|
72
|
+
data: ${JSON.stringify($)}
|
|
73
73
|
|
|
74
|
-
`))}}if(
|
|
75
|
-
data: ${JSON.stringify(
|
|
74
|
+
`))}}if(U?.delta?.annotations?.length&&!b&&!p){if(T>=0&&u){let $={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
75
|
+
data: ${JSON.stringify($)}
|
|
76
76
|
|
|
77
|
-
`)),
|
|
78
|
-
data: ${JSON.stringify(
|
|
77
|
+
`)),T=-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,no.v4)()}`,content:[{type:"web_search_result",title:$.url_citation.title,url:$.url_citation.url}]}};v(s.encode(`event: content_block_start
|
|
78
|
+
data: ${JSON.stringify(G)}
|
|
79
79
|
|
|
80
|
-
`));let
|
|
81
|
-
data: ${JSON.stringify(
|
|
80
|
+
`));let ge={type:"content_block_stop",index:j};v(s.encode(`event: content_block_stop
|
|
81
|
+
data: ${JSON.stringify(ge)}
|
|
82
82
|
|
|
83
|
-
`)),
|
|
84
|
-
data: ${JSON.stringify(
|
|
83
|
+
`)),T=-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(T>=0){let Kl={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
84
|
+
data: ${JSON.stringify(Kl)}
|
|
85
85
|
|
|
86
|
-
`)),
|
|
87
|
-
data: ${JSON.stringify(
|
|
86
|
+
`)),T=-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:{}}};v(s.encode(`event: content_block_start
|
|
87
|
+
data: ${JSON.stringify(Q)}
|
|
88
88
|
|
|
89
|
-
`)),
|
|
90
|
-
data: ${JSON.stringify(
|
|
89
|
+
`)),T=K;let Wl={id:W,name:N,arguments:"",contentBlockIndex:K};f.set(G,Wl)}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}};v(s.encode(`event: content_block_delta
|
|
90
|
+
data: ${JSON.stringify(N)}
|
|
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}};v(s.encode(`event: content_block_delta
|
|
93
|
+
data: ${JSON.stringify(Q)}
|
|
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!"),T>=0){let $={type:"content_block_stop",index:T};v(s.encode(`event: content_block_stop
|
|
96
|
+
data: ${JSON.stringify($)}
|
|
97
|
+
|
|
98
|
+
`)),T=-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,no.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,no.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:Br(e.usage)?eo(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 Cd(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)&&Cd(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 Rd(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 so(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(Rd({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 io(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 ro(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 Wr(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 Jr(n,e,t){let o=e?Wr(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:ro(n.usageMetadata)}:{}}}async function ao(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:ro(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(Jr(_,void 0,c))}
|
|
91
100
|
|
|
92
|
-
`))}
|
|
93
|
-
data: ${JSON.stringify(F)}
|
|
101
|
+
`));return}t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],T=!1,x=k.content?.parts||[];x.filter(R=>R.text&&R.thought===!0).forEach(R=>{i||(i=!0);let 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)}
|
|
94
102
|
|
|
95
|
-
`))}
|
|
96
|
-
data: ${JSON.stringify(I)}
|
|
103
|
+
`))});let v=x.find(R=>R.thoughtSignature)?.thoughtSignature;if(v&&!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)}
|
|
97
104
|
|
|
98
|
-
`))
|
|
99
|
-
`)||"",u={id:o.responseId,choices:[{finish_reason:o.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:l,role:"assistant",tool_calls:c.length>0?c:void 0,...s&&{thinking:{content:r||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:o.modelVersion,object:"chat.completion",usage:{completion_tokens:o.usageMetadata?.candidatesTokenCount||0,prompt_tokens:o.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:o.usageMetadata?.cachedContentTokenCount||0},total_tokens:o.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:o.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(u),{status:n.status,statusText:n.statusText,headers:n.headers})}else if(n.headers.get("Content-Type")?.includes("stream")){if(!n.body)return n;let o=new TextDecoder,r=new TextEncoder,s=!1,a=!1,i=!1,c="",l=0,u=-1,p=new ReadableStream({async start(d){let f=async(m,y)=>{if(m.startsWith("data: ")){let b=m.slice(6).trim();if(b){t?.debug({chunkStr:b},`${e} chunk:`);try{let _=JSON.parse(b);if(!_.candidates||!_.candidates[0]){t?.debug({chunkStr:b},"Invalid chunk structure");return}let k=_.candidates[0],T=k.content?.parts||[];T.filter(C=>C.text&&C.thought===!0).forEach(C=>{i||(i=!0);let P={choices:[{delta:{role:"assistant",content:null,thinking:{content:C.text}},finish_reason:null,index:l,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(P)}
|
|
105
|
+
`))}let R={choices:[{delta:{role:"assistant",content:null,thinking:{signature:v}},finish_reason:null,index:c,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
100
106
|
|
|
101
|
-
`))
|
|
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)}
|
|
102
108
|
|
|
103
|
-
`))}let
|
|
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)}
|
|
104
111
|
|
|
105
|
-
`)),
|
|
112
|
+
`)),a||(a=!0)}if(i&&A&&!s)if(_.modelVersion?.includes("3")){l+=A,_.usageMetadata&&y.enqueue(r.encode(`data: ${JSON.stringify(Jr(_,k,c))}
|
|
106
113
|
|
|
107
|
-
`))
|
|
108
|
-
`);if(!S&&s&&!a){let C={choices:[{delta:{role:"assistant",content:"(no content)"},index:l,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.responseId||"",model:_.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};y.enqueue(r.encode(`data: ${JSON.stringify(C)}
|
|
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)}
|
|
109
115
|
|
|
110
|
-
`)),
|
|
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:ro(_.usageMetadata)},O=Wr(k);O&&(R.choices[0].delta.annotations=O),y.enqueue(r.encode(`data: ${JSON.stringify(R)}
|
|
111
117
|
|
|
112
|
-
`)),
|
|
118
|
+
`)),T=!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:ro(_.usageMetadata)},F=Wr(k);F&&(O.choices[0].delta.annotations=F),y.enqueue(r.encode(`data: ${JSON.stringify(O)}
|
|
113
119
|
|
|
114
|
-
`)),!a&&
|
|
120
|
+
`)),T=!0}),!a&&A&&(a=!0)),!T&&(k.finishReason||_.usageMetadata||k?.groundingMetadata?.groundingChunks?.length)&&y.enqueue(r.encode(`data: ${JSON.stringify(Jr(_,k,c))}
|
|
115
121
|
|
|
116
|
-
`))}
|
|
117
|
-
`);
|
|
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,Kr=w(()=>{"use strict";bt={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"}});var co,Ca=w(()=>{"use strict";Kr();co=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:so(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=io;async transformResponseOut(e){return ao(e,this.name,this.logger)}}});async function wd(){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
|
|
121
|
-
`);for(let m of
|
|
122
|
-
`))},p=(d,f)=>{let{controller:
|
|
126
|
+
3. Use Google Cloud environment with default service account`)}}var lo,Ra=w(()=>{"use strict";Kr();lo=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 wd();return{body:so(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 io(e)}async transformResponseOut(e){return ao(e,this.name)}}});var uo,wa=w(()=>{"use strict";oe();uo=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(`
|
|
127
|
+
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
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
|
-
`;
|
|
132
|
+
`;g.enqueue(h.encode(k));let T={...m,choices:[{...m.choices[0],delta:{...m.choices[0].delta,content:b}}]};delete T.choices[0].delta.reasoning_content;let x=`data: ${JSON.stringify(T)}
|
|
127
133
|
|
|
128
|
-
`;
|
|
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
|
-
`;
|
|
131
|
-
`))}else
|
|
132
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
133
|
-
`);a=
|
|
134
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
136
|
+
`;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
|
|
137
|
+
`))}else g.enqueue(h.encode(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 po,Pa=w(()=>{"use strict";oe();po=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
|
|
139
|
-
`);for(let m of
|
|
140
|
-
`))},p=(d,f)=>{let{controller:
|
|
141
|
-
|
|
142
|
-
`;
|
|
143
|
-
|
|
144
|
-
`;
|
|
145
|
-
`))}else
|
|
146
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
147
|
-
`);a=
|
|
148
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
149
|
-
`);for(let b of y)b.trim()&&
|
|
150
|
-
`))},f=(h
|
|
151
|
-
|
|
152
|
-
`));return}_.choices?.[0]?.delta?.content&&!
|
|
153
|
-
|
|
154
|
-
`;m.enqueue(y.encode(
|
|
155
|
-
|
|
156
|
-
`;m.enqueue(y.encode(
|
|
157
|
-
|
|
158
|
-
`;m.enqueue(y.encode(
|
|
159
|
-
|
|
160
|
-
`;m.enqueue(y.encode(
|
|
161
|
-
`))}}else m.enqueue(y.encode(
|
|
162
|
-
`))};try{for(;;){let{done:
|
|
163
|
-
`);
|
|
164
|
-
`))}continue}let y=
|
|
165
|
-
`);
|
|
166
|
-
`))}}}catch(
|
|
167
|
-
`);for(let y of m)y.trim()&&
|
|
168
|
-
`))},d=(f,
|
|
169
|
-
|
|
170
|
-
`;
|
|
171
|
-
`))}}else
|
|
172
|
-
`))};try{for(;;){let{done:f,value:
|
|
173
|
-
`);i=y.pop()||"";for(let b of y)if(b.trim())try{d(b,{controller:
|
|
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(`
|
|
145
|
+
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
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 T=JSON.parse(f.exitToolResponse());_.choices=[{delta:{role:"assistant",content:T.response||""}}];let x=`data: ${JSON.stringify(_)}
|
|
147
|
+
|
|
148
|
+
`;g.enqueue(h.encode(x))}catch{}return}}if(_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let k=`data: ${JSON.stringify(_)}
|
|
149
|
+
|
|
150
|
+
`;g.enqueue(h.encode(k))}}catch{g.enqueue(h.encode(d+`
|
|
151
|
+
`))}else g.enqueue(h.encode(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 Ea,fo,Aa=w(()=>{"use strict";oe();Ea=require("uuid"),fo=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(`
|
|
155
|
+
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
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})}
|
|
157
|
+
|
|
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)}
|
|
159
|
+
|
|
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)}
|
|
161
|
+
|
|
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)}
|
|
163
|
+
|
|
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,Ea.v4)()}`}),_.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let T=_.choices?.[0]?.delta,x=T&&Object.keys(T).length>0,v=_.choices?.[0]?.finish_reason,P=_.usage;if(x||v||P){let A=`data: ${JSON.stringify(_)}
|
|
165
|
+
|
|
166
|
+
`;m.enqueue(y.encode(A))}}catch{m.enqueue(y.encode(g+`
|
|
167
|
+
`))}}else m.enqueue(y.encode(g+`
|
|
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 mo,Oa=w(()=>{"use strict";mo=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 Ia,go,Ma=w(()=>{"use strict";oe();Ia=require("uuid"),go=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(`
|
|
173
|
+
`);for(let y of m)y.trim()&&g.enqueue(h.encode(y+`
|
|
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,Ia.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)}
|
|
175
|
+
|
|
176
|
+
`;h.enqueue(m.encode(_))}catch{h.enqueue(m.encode(f+`
|
|
177
|
+
`))}}else h.enqueue(m.encode(f+`
|
|
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 ho,La=w(()=>{"use strict";ho=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 Gr(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=$a.default.parse(n);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(o)}catch(o){try{let r=(0,Na.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 $a,Na,Ua=w(()=>{$a=ee(require("json5")),Na=require("jsonrepair")});var yo,Da=w(()=>{"use strict";Ua();oe();yo=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=Gr(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
|
-
`))},
|
|
184
|
+
`))},g=(m,y,b)=>{let _="";try{_=Gr(r.arguments||"",this.logger)}catch(v){console.error(`${v.message} ${v.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(r)}`),_=r.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:r.name,arguments:_},id:r.id,index:r.index,type:"function"}]},T={...m,choices:[{...m.choices[0],delta:k}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let x=`data: ${JSON.stringify(T)}
|
|
179
185
|
|
|
180
|
-
`;y.enqueue(b.encode(x))},
|
|
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 T=JSON.parse(k);if(T.choices?.[0]?.delta?.tool_calls?.length){let v=T.choices[0].delta.tool_calls[0];if(typeof r.index>"u"){r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""},v.function?.arguments&&(v.function.arguments="");let P=`data: ${JSON.stringify(T)}
|
|
181
187
|
|
|
182
|
-
`;b.enqueue(_.encode(
|
|
188
|
+
`;b.enqueue(_.encode(P));return}else if(r.index===v.index){v.function?.arguments&&(r.arguments+=v.function.arguments);return}else{g(T,b,_),r={index:v.index,name:v.function?.name||"",id:v.id||"",arguments:v.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&r.index!==void 0){g(T,b,_),r={};return}T.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let x=`data: ${JSON.stringify(T)}
|
|
183
189
|
|
|
184
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
|
|
191
|
-
`);for(let m of
|
|
192
|
-
`))},p=(d,f)=>{let{controller:
|
|
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 T of k)if(T.trim())try{h(T,{controller:p,encoder:o,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>i,setReasoningComplete:x=>i=x})}catch(x){console.error("Error processing line:",T,x),p.enqueue(o.encode(T+`
|
|
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:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){console.error("Error processing line:",k,T),p.enqueue(o.encode(k+`
|
|
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 _o,Fa=w(()=>{"use strict";oe();_t();_o=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??qn(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(`
|
|
197
|
+
`);for(let m of h)m.trim()&&f.enqueue(g.encode(m+`
|
|
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
|
|
|
194
|
-
`;
|
|
200
|
+
`;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(_)}
|
|
195
201
|
|
|
196
|
-
`;
|
|
202
|
+
`;g.enqueue(h.encode(k))}if(m.choices?.[0]?.delta?.reasoning_content&&delete m.choices[0].delta.reasoning_content,m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0){f.isReasoningComplete()&&m.choices[0].index++;let y=`data: ${JSON.stringify(m)}
|
|
197
203
|
|
|
198
|
-
`;
|
|
199
|
-
`))}else
|
|
200
|
-
`))};try{for(;;){let{done:d,value:f}=await
|
|
201
|
-
`);a=
|
|
202
|
-
`))}}}catch(d){console.error("Stream error:",d),
|
|
204
|
+
`;g.enqueue(h.encode(y))}}catch{g.enqueue(h.encode(d+`
|
|
205
|
+
`))}else g.enqueue(h.encode(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 bo,ja=w(()=>{"use strict";bo=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 ko,Ha=w(()=>{"use strict";ko=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}}});function za(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 Ba(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 Ja(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 Wa=w(()=>{"use strict"});async function Pd(){try{let{GoogleAuth:n}=await import("google-auth-library");return(await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(n){throw console.error("Error getting access token:",n),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
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
|
|
219
|
-
`);for(let b of y)b.trim()&&
|
|
220
|
-
`))},f=(h
|
|
224
|
+
3. Use Google Cloud environment with default service account`)}}var To,Ka=w(()=>{"use strict";Wa();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 Pd();return{body:za(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 Ba(e)}async transformResponseOut(e){return Ja(e,this.name,this.logger)}}});var vo,Ga=w(()=>{"use strict";vo=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 xo,Qa=w(()=>{"use strict";xo=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}}});var So,Va=w(()=>{"use strict";So=class{name="OpenAI";endPoint="/v1/chat/completions"}});var Co,Ya=w(()=>{"use strict";Co=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 Xa,Ro,Za=w(()=>{"use strict";oe();Xa=require("uuid"),Ro=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(`
|
|
225
|
+
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
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&&!
|
|
228
|
+
`)),_.choices?.[0]?.delta?.content&&!h.hasTextContent()&&h.setHasTextContent(!0),_.choices?.[0]?.delta?.reasoning){h.appendReasoningContent(_.choices[0].delta.reasoning);let T={..._,choices:[{..._.choices?.[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let x=`data: ${JSON.stringify(T)}
|
|
223
229
|
|
|
224
|
-
`;m.enqueue(y.encode(x));return}if(_.choices?.[0]?.delta?.content&&
|
|
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 v=`data: ${JSON.stringify(x)}
|
|
225
231
|
|
|
226
|
-
`;m.enqueue(y.encode(v))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${(0,
|
|
232
|
+
`;m.enqueue(y.encode(v))}_.choices?.[0]?.delta?.reasoning&&delete _.choices[0].delta.reasoning,_.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(_.choices?.[0]?.delta?.tool_calls[0].id,10))&&_.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${(0,Xa.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
|
-
`;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(
|
|
229
|
-
`))}}else m.enqueue(y.encode(
|
|
230
|
-
`))};try{for(;;){let{done:
|
|
231
|
-
`);
|
|
232
|
-
`))}continue}let y=
|
|
233
|
-
`);
|
|
234
|
-
`))}}}catch(
|
|
234
|
+
`;m.enqueue(y.encode(k))}catch{m.enqueue(y.encode(g+`
|
|
235
|
+
`))}}else m.enqueue(y.encode(g+`
|
|
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 Qr,Ed,wo,qa=w(()=>{"use strict";oe();Qr=`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.`,Ed=10,wo=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<Ed)&&(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:Qr}):o.content=[{type:"text",text:Qr},{type:"text",text:o.content||""}]),o.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Qr}]}),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 x={...
|
|
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 v={...h,choices:[{...h.choices[0],delta:x,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(v)}
|
|
244
250
|
|
|
245
|
-
`))}let k={...
|
|
251
|
+
`))}let k={...h.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete k.content;let T={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
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={...
|
|
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 T={...h,choices:[{...h.choices[0],delta:k,index:r}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
248
254
|
|
|
249
|
-
`))}y=""}}else if(p==="FINAL"){if(y.length>0)if(/^\s*$/.test(y))f+=y;else{let _=f+y,k={...
|
|
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 T={...h,choices:[{...h.choices[0],delta:k}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
|
|
250
256
|
|
|
251
|
-
`)),f=""}r++,y=""}};try{for(;;){let{done:
|
|
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));
|
|
255
|
-
`))}else
|
|
256
|
-
`))}}}catch(
|
|
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 Po,ec=w(()=>{"use strict";oe();Po=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
|
|
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(
|
|
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=""}
|
|
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){
|
|
269
|
-
`);for(let b of y)b.trim()&&
|
|
270
|
-
`))},f=(h
|
|
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 Vr,Eo,tc=w(()=>{"use strict";oe();dt();Vr=require("uuid"),Eo=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,Vr.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(`
|
|
275
|
+
`);for(let b of y)b.trim()&&h.enqueue(m.encode(b+`
|
|
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&&!
|
|
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&&
|
|
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,Vr.v4)()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!i&&(i=!0);let k=b.choices?.[0]?.delta,T=k&&Object.keys(k).length>0,x=b.choices?.[0]?.finish_reason,v=b.usage;(T||x||v)&&m.enqueue(y.encode(`data: ${JSON.stringify(b)}
|
|
279
285
|
|
|
280
|
-
`))}catch{m.enqueue(y.encode(
|
|
281
|
-
`))}else m.enqueue(y.encode(
|
|
282
|
-
`))};try{for(;;){let{done:
|
|
283
|
-
`);
|
|
284
|
-
`))}continue}let y=
|
|
285
|
-
`);
|
|
286
|
-
`))}}}catch(
|
|
286
|
+
`))}catch{m.enqueue(y.encode(g+`
|
|
287
|
+
`))}else m.enqueue(y.encode(g+`
|
|
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 Od(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 Id(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 Ad,Ao,nc=w(()=>{"use strict";_t();Ad={min:"low",minimal:"low",light:"low",xhigh:"max",maximum:"max",ultra:"max",ultracode:"max"};Ao=class{constructor(e){this.options=e}static TransformerName="defaultthinking";async transformRequestIn(e,t){let o=Od(this.options?.level??this.options?.value);if(o===void 0||o==="none"||e.reasoning)return e;let r=Id(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=Ad[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 oc(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 Oo,rc=w(()=>{"use strict";_t();oe();Oo=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)oc(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)oc(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 sc,ic=w(()=>{Sa();Ca();Ra();wa();Pa();Aa();Oa();Ma();La();Da();Fa();ja();Ha();Ka();Ga();Qa();Va();Ya();Za();Er();qa();ec();tc();nc();rc();sc={AnthropicTransformer:oo,GeminiTransformer:co,VertexGeminiTransformer:lo,VertexClaudeTransformer:To,DeepseekTransformer:uo,TooluseTransformer:po,OpenrouterTransformer:fo,OpenAITransformer:So,MaxTokenTransformer:mo,GroqTransformer:go,CleancacheTransformer:ho,EnhanceToolTransformer:yo,ReasoningTransformer:_o,SamplingTransformer:bo,MaxCompletionTokens:ko,CerebrasTransformer:vo,StreamOptionsTransformer:xo,CustomParamsTransformer:Co,VercelTransformer:Ro,OpenAIResponsesTransformer:at,ForceReasoningTransformer:wo,KimiTransformer:Po,OpenCodeTransformer:Eo,DefaultThinkingTransformer:Ao,AmdTransformer:Oo}});var Xe,Yr=w(()=>{"use strict";ic();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 Ye,Gr=w(()=>{"use strict";oc();ic();ac();ae();Ye=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,t,o={}){this.configService=e,this.logger=t,this.options={timeout:o.timeout??3e4,...o}}async initialize(){try{this.fallbackTokenizer=new Jt("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 Jt(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 cc(n){if(!n||typeof n!="object"||Od(n))return null;for(let t of Ad(n)){let o=Ed(t);if(o)return o}return null}function Ed(n){if(!n||typeof n!="object")return null;let e={},t=Mo(n,Sd);if(t!==void 0){let a=lc(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Mo(n,Rd);if(o!==void 0){let a=lc(o);e.usedBalance=a,e.totalBalance=100}let r=Mo(n,wd);if(r!==void 0){let a=uc(r);a&&(e.resetTime=a)}let s=Mo(n,Pd);if(s!==void 0){let a=uc(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 lc(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Mo(n,e){for(let t of e){let o=U(n?.[t]);if(o!==void 0)return o}}function Ad(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 Od(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 uc(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=ss(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Dd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?jd:e==="deepseek.com"||e.endsWith(".deepseek.com")?Id:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Md:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?Ld:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Nd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?$d:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Fd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Ud:null:null}function Hd(n){let e=ss(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function zd(n,e){let t=os(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 os(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>os(e)):Object.values(n).flatMap(e=>os(e))}function rs(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function ss(n){try{return new URL(n).hostname.toLowerCase()}catch{return null}}function U(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string")return;let e=n.trim().replace(/,/g,"");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}var fe,Vr,Qr,Yr,Xr,Zr,Sd,Rd,wd,Pd,qr,es,ts,ns,Id,Md,Ld,Nd,$d,Fd,Ud,Dd,jd,is=w(()=>{"use strict";ae();fe=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=Y(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 fe{async queryQuota(e,t,o){let r=await this.fetchJson("https://api.deepseek.com/user/balance",e,t,o),a=(Array.isArray(r?.balance_infos)?r.balance_infos:[]).find(c=>U(c?.total_balance)!==void 0);if(!a)return null;let i=U(a.total_balance);return i===void 0?null:{totalBalance:i,currency:typeof a.currency=="string"?a.currency:void 0}}},Qr=class extends fe{async queryQuota(e,t,o){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,t,o))?.data;if(!s||typeof s!="object")return null;let a={},i=U(s.limit),c=U(s.limit_remaining),l=U(s.usage),u=U(s.usage_daily);return i!==void 0&&(a.totalBalance=i),c!==void 0&&(a.remainingBalance=c),l!==void 0&&(a.usedBalance=l),u!==void 0&&(a.usedDailyBalance=u),this.hasQuotaData(a)?a:null}},Yr=class extends fe{async queryQuota(e,t,o){let r=Hd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},c=U(a.totalBalance),l=U(a.balance);return c!==void 0&&(i.totalBalance=c),l!==void 0&&(i.remainingBalance=l),c!==void 0&&l!==void 0&&(i.usedBalance=Math.max(0,c-l)),this.hasQuotaData(i)?i:null}},Xr=class extends fe{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=Y(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=U(l.currentValue),h=U(l.usage),g=U(l.remaining),m=U(l.percentage);f!==void 0?d.usedDailyBalance=f:m!==void 0&&(d.usedDailyBalance=m,d.limitDaily=100),h!==void 0?d.limitDaily=h:f!==void 0&&g!==void 0&&(d.limitDaily=f+g),l.nextResetTime&&(d.resetTime=new Date(l.nextResetTime).toISOString())}if(u){let f=U(u.currentValue),h=U(u.usage),g=U(u.remaining),m=U(u.percentage);f!==void 0?d.usedBalance=f:m!==void 0&&(d.usedBalance=m,d.totalBalance=100),h!==void 0?d.totalBalance=h:f!==void 0&&g!==void 0&&(d.totalBalance=f+g),u.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(u.nextResetTime).toISOString())}if(p){if(d.usedDailyBalance===void 0){let f=U(p.currentValue);f!==void 0&&(d.usedDailyBalance=f)}if(d.limitDaily===void 0){let f=U(p.usage),h=U(p.currentValue),g=U(p.remaining);f!==void 0?d.limitDaily=f:h!==void 0&&g!==void 0&&(d.limitDaily=h+g)}p.nextResetTime&&!d.resetTime&&(d.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(d)?d:null}catch{return null}}},Zr=class extends fe{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=Y(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=U(u.per5HourUsedQuota),f=U(u.per5HourTotalQuota);d!==void 0&&(p.usedDailyBalance=d),f!==void 0&&(p.limitDaily=f);let h=U(u.perWeekUsedQuota),g=U(u.perWeekTotalQuota);return h!==void 0&&(p.usedBalance=h),g!==void 0&&(p.totalBalance=g),this.hasQuotaData(p)?p:null}catch{return null}}};Sd=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Rd=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],wd=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Pd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];qr=class extends fe{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=rs(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=Y(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 cc(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=Y(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 cc(l)}catch{return null}}},es=class extends fe{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:(rs(e.quotaToken,"atp-auth-token")||rs(e.quotaToken,"tenantToken")||e.quotaToken).trim(),Cookie:e.quotaToken},signal:AbortSignal.timeout(t)};try{o&&(s.dispatcher=Y(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=zd(i,e.apiKey),l=c?.codingPlanUsageDTO||c?.usage||c;if(!l||typeof l!="object")return null;let u={},p=U(l.rp5hUsage),d=U(l.rp5hLimit);p!==void 0&&(u.usedDailyBalance=p),d!==void 0&&(u.limitDaily=d);let f=U(l.rpwUsage),h=U(l.rpwLimit);return f!==void 0&&(u.usedBalance=f),h!==void 0&&(u.totalBalance=h),u.remainingBalance===void 0&&h!==void 0&&f!==void 0&&(u.remainingBalance=Math.max(0,h-f)),this.hasQuotaData(u)?u:null}catch{return null}}},ts=class extends fe{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=Y(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=U(p.limit),f=U(p.remaining),h=p.resetTime;d!==void 0&&f!==void 0&&(c.usedDailyBalance=Math.max(0,d-f),c.limitDaily=d),h&&(c.resetTime=new Date(h).toISOString())}let u=i?.usage;if(u){let p=U(u.limit),d=U(u.remaining),f=U(u.used),h=u.resetTime;p!==void 0&&(c.totalBalance=p,f!==void 0?c.usedBalance=f:d!==void 0&&(c.usedBalance=Math.max(0,p-d),c.remainingBalance=d)),h&&(c.resetTime7d=new Date(h).toISOString(),c.resetTime||(c.resetTime=c.resetTime7d))}return this.hasQuotaData(c)?c:null}catch{return null}}},ns=class extends fe{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=ss(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=U(u.current_interval_total_count),f=U(u.current_interval_usage_count),h=U(u.current_interval_remaining_percent),g=U(u.end_time);d!==void 0&&f!==void 0&&d>0?(p.usedDailyBalance=Math.max(0,d-f),p.limitDaily=d):h!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-h)),g&&(p.resetTime=new Date(g).toISOString());let m=U(u.current_weekly_total_count),y=U(u.current_weekly_usage_count),b=U(u.current_weekly_remaining_percent),_=U(u.weekly_end_time);return m!==void 0&&y!==void 0&&m>0?(p.usedBalance=Math.max(0,m-y),p.remainingBalance=y,p.totalBalance=m):b!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-b),p.remainingBalance=b),_&&!p.resetTime&&(p.resetTime=new Date(_).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},Id=new Vr,Md=new Qr,Ld=new Yr,Nd=new Xr,$d=new Zr,Fd=new qr,Ud=new es,Dd=new ts,jd=new ns});function dc(n){return{[Bd]:n,[Jd]:On}}function Xe(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function Kd(n){return n===!0||n==="true"||n===1||n==="1"}function Gd(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 Vd(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 Qd(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function as(n,e,t){let o=performance.now(),r=()=>Math.max(0,Math.round(performance.now()-o));if(Xe(n))return{success:!1,skipped:!0,error:cs,latencyMs:r()};let s=Vd(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=Y(t));let i=await fetch(s,a);if(i.headers&&Mt(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 Yd(n,e,t,o){if(Xe(n))return{success:!1,skipped:!0,error:cs};let r=n.wakeupModel||(Array.isArray(n.models)?n.models[0]:void 0);if(!r)return{success:!1,error:"No models configured for provider"};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||r.includes("claude");try{let i={"Content-Type":"application/json",...dc("scheduled-wakeup")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:r,messages:[{role:"user",content:"Wake up and acknowledge with a short greeting."}],max_tokens:10}),signal:AbortSignal.timeout(e)};t&&(c.dispatcher=Y(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 Xd(n,e,t,o,r){if(Xe(n))return{success:!1,skipped:!0,error:cs};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",...dc("rate-limit-probe")};a?(i["x-api-key"]=n.apiKey,i["anthropic-version"]="2023-06-01"):i.Authorization=`Bearer ${n.apiKey}`;let c={method:"POST",headers:i,body:JSON.stringify({model:e,messages:[{role:"user",content:"Hello, please reply briefly."}],max_tokens:10}),signal:AbortSignal.timeout(t)};o&&(c.dispatcher=Y(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 ls(n,e,t,o,r,s){return Le||(Le=new Gt(n,e,t,o,r,s)),Le}function bt(n,e,t,o,r,s){let a=ls(n,e,t,o,r,s);return a.start(),a}function No(){Le&&Le.stop()}function $o(){Le&&(Le.stop(),Le=null)}var Bd,Jd,Wd,cs,Gt,Le,Fo=w(()=>{"use strict";de();Je();is();lt();dr();ae();Bd="x-claude-code-router-source",Jd="x-claude-code-router-version";Wd={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};cs="Managed provider requires its plugin's authenticated model sync";Gt=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={...Wd,...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&&!Xe(s)&&!this.config.excludeProviders.includes(s.name)),t=H();if(e.length===0)return;let 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){Hn(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`))}}})}),Qd(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:as(s,this.config.probeTimeoutMs,c).then(l=>{this.recordProbe(s.name,l,"rate-limit-headers")})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let r=await Promise.allSettled(o.map(s=>s.promise));for(let s=0;s<o.length;s++){let a=r[s];if(a.status==="rejected"){let i=o[s];this.logger?.warn?.(`Quota probe failed for ${i.provider} (${i.type}): ${a.reason}`)}}}async runHealthProbe(){let e=H(),t=this.getProviders().filter(r=>r?.name&&r.enabled!==!1&&!Xe(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=>as(r,this.config.probeTimeoutMs,this.resolveProxyUrl?.(r))));for(let r=0;r<t.length;r++){let s=t[r],a=o[r],i=Array.isArray(s.models)?s.models:[];if(a.status==="fulfilled"){let c=a.value;if(c.skipped)continue;if(this.recordProbe(s.name,c,"health"),c.success){let l=0;for(let u of i){let p=e.getState(s.name,u);if(p&&p.status==="open"){let d=p.lastError?.includes("Quota exhausted"),f=p.rateLimitUntil||p.lastError&&(p.lastError.includes("429")||p.lastError.toLowerCase().includes("rate limit")||p.lastError.toLowerCase().includes("rate_limit")||p.lastError.toLowerCase().includes("too many requests")||p.lastError.toLowerCase().includes("\u9650\u6D41"));if(d){this.logger?.debug?.(`Skipping health probe recovery for ${s.name} (${u}) because quota is exhausted`);continue}if(f||p.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${s.name} (${u})`);continue}}e.recordSuccess(s.name,u),l++}l>0&&this.logger?.info?.(`Health probe succeeded for ${s.name}`)}else{for(let l of i)e.recordFailure(s.name,l,c.error);this.logger?.warn?.(`Health probe failed for ${s.name}: ${c.error}`)}}else{this.recordProbe(s.name,{success:!1,error:a.reason?.message||String(a.reason||"Probe error"),latencyMs:0,errorKind:"network"},"health");for(let c of i)e.recordFailure(s.name,c,a.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${s.name}: ${a.reason}`)}}}async runManagedRecoveryProbe(){let e=H();if(!this.resolveManagedRuntime)return;let t=e.getFailPoolModels();if(t.length===0)return;let o=new Map;for(let r of t){let[s,...a]=r.split(","),i=a.join(",");if(!s||!i)continue;let c=o.get(s)??[];c.push(i),o.set(s,c)}for(let[r,s]of o){let a=this.getProviders().find(p=>p?.name===r&&p.enabled!==!1);if(!a)continue;let i=this.resolveManagedRuntime(a);if(!i)continue;let c=s[0],l=e.getState(r,c);!l||l.status!=="open"||l.rateLimitUntil&&Date.now()<l.rateLimitUntil||Date.now()-(l.lastProbeTime??0)<this.config.quotaProbeIntervalMinutes*6e4||!await this.probeManagedAccountState(r,i,a,c,s,e)||await this.probeManagedLiveness(r,i,a,c,s,e)}}async probeManagedAccountState(e,t,o,r,s,a){try{if(typeof t.probeAccountState=="function"){let i=await t.probeAccountState();return i&&i.available===!1?(a.recordProbeAttempt?.(e,r),typeof i.parkedUntil=="number"&&i.parkedUntil>Date.now()&&a.markParkedUntil?.(e,r,i.parkedUntil),this.logger?.debug?.(`Managed probe: ${e} account parked (${i.reason??"unavailable"}), skipping liveness`),!1):!0}return typeof t.ensureUsable=="function"&&await t.ensureUsable(),!0}catch(i){return a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed probe: ${e} account unusable (${i?.code||i?.message||i}), skipping liveness`),!1}}async probeManagedLiveness(e,t,o,r,s,a){let i=this.config.probeTimeoutMs,c={model:r,max_tokens:1,messages:[{role:"user",content:"ping"}],stream:!1},l=async()=>{let p=o.baseUrl||o.api_base_url;return await fetch(p,{method:"POST",headers:{"content-type":"application/json",...o.apiKey?{authorization:`Bearer ${o.apiKey}`}:{}},body:JSON.stringify(c),signal:AbortSignal.timeout(i)})},u={TIMEOUT:i};try{this.logger?.debug?.(`Managed liveness probe for ${e} (${r})`);let p=typeof t.probeLiveness=="function"?await t.probeLiveness({attempt:l,model:r,provider:o,config:u}):typeof t.dispatchRequest=="function"?await t.dispatchRequest({attempt:l,requestBody:c,config:u,provider:o}):await l();if(p?.ok){for(let d of s)a.recover(e,d);this.logger?.info?.(`Managed liveness probe succeeded for ${e}, restored ${s.length} model(s)`)}else a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe failed for ${e}: HTTP ${p?.status}`)}catch(p){a.recordProbeAttempt?.(e,r),this.logger?.debug?.(`Managed liveness probe errored for ${e}: ${p?.message||p}`)}}async runRateLimitProbe(){let e=H(),t=e.getRateLimitedModels();if(t.length===0)return;let o=this.getProviders(),r=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${t.length} model(s)`);for(let s of t){let[a,...i]=s.split(","),c=i.join(",");if(!a||!c)continue;let l=o.find(d=>d?.name===a);if(l&&Xe(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 Xd(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&&!Xe(i)&&i.wakeupEnabled===!0);if(e.length===0)return;let t=new Date,o=t.getHours(),r=t.getMinutes(),s=Gd(t),a=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let i of e){let c=i.wakeupTime||a,[l,u]=c.split(":"),p=parseInt(l,10),d=parseInt(u,10);if(isNaN(p)||isNaN(d))continue;let f=o>p||o===p&&r>=d,h=(p*60+d)*6e4-(o*60+r)*6e4,g=h>0&&h<=300*1e3;(f||g)&&!this.hasWakeupFiredToday(i.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${i.name} at ${c}`),Yd(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?Kd(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 as(o,this.config.probeTimeoutMs,this.resolveProxyUrl?.(o));if(r.skipped)return{success:!1,skipped:!0,latencyMs:r.latencyMs,status:"skipped",isSlow:!1,error:r.error};let s=this.recordProbe(o.name,r,"manual"),a=Array.isArray(o.models)?o.models:[];if(r.success)for(let i of a)H().recordSuccess(o.name,i);else for(let i of a)H().recordFailure(o.name,i,r.error);return{success:r.success,latencyMs:r.latencyMs,status:s.status,isSlow:s.isSlow,errorKind:r.errorKind,error:r.error}}},Le=null});var pc=w(()=>{"use strict"});var us,kt,fc=w(()=>{"use strict";us=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,t={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:t.enabled!==!1,options:t})}async enablePlugin(e,t){let o=this.plugins.get(e),r=this.pluginInstances.get(e);if(!o||!r)throw new Error(`Plugin ${e} not found`);o.enabled&&await t.register(r.register,o.options)}async enablePlugins(e){for(let[t,o]of this.plugins)if(o.enabled)try{await this.enablePlugin(t,e)}catch(r){let s=r instanceof Error?r.message:String(r);e.log?.error(`Failed to enable plugin ${t}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,t){let o=this.plugins.get(e);o&&(o.enabled=t)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},kt=new us});var le,ds=w(()=>{"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
|
|
295
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(sc).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 ac,Kt,cc=w(()=>{"use strict";ac=require("tiktoken"),Kt=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,ac.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,lc,kt,Qt,uc,Io,dc=w(()=>{"use strict";Gt=require("path"),lc=require("os"),kt=require("fs"),Qt=require("fs"),uc=require("@huggingface/tokenizers"),Io=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,lc.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 uc.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 Mo,pc=w(()=>{"use strict";ae();Mo=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,Xr=w(()=>{"use strict";cc();dc();pc();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 Io(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Mo(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 fc(n){if(!n||typeof n!="object"||Fd(n))return null;for(let t of Dd(n)){let o=Ud(t);if(o)return o}return null}function Ud(n){if(!n||typeof n!="object")return null;let e={},t=Lo(n,Md);if(t!==void 0){let a=mc(t);e.usedDailyBalance=a,e.limitDaily=100}let o=Lo(n,Ld);if(o!==void 0){let a=mc(o);e.usedBalance=a,e.totalBalance=100}let r=Lo(n,$d);if(r!==void 0){let a=gc(r);a&&(e.resetTime=a)}let s=Lo(n,Nd);if(s!==void 0){let a=gc(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 mc(n){return!Number.isFinite(n)||n<=0?0:Math.round(n*1e4)/100}function Lo(n,e){for(let t of e){let o=D(n?.[t]);if(o!==void 0)return o}}function Dd(n){let e=[],t=new WeakSet,o=["data","Data","DataV2"],r=s=>{if(!(!s||typeof s!="object")&&!t.has(s)){t.add(s),e.push(s);for(let a of o)s[a]&&typeof s[a]=="object"&&r(s[a])}};return r(n),e}function Fd(n){let e=n?.data;return e&&typeof e=="object"&&(e.success===!1||e.errorCode||e.errorMsg)?String(e.errorCode||e.errorMsg||"gateway-error"):null}function gc(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 $o(n){let e=ls(n);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?Gd:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?Qd:e==="deepseek.com"||e.endsWith(".deepseek.com")?jd:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?Hd:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?zd:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?Bd:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?Jd:e==="maas.aliyuncs.com"||e.endsWith(".maas.aliyuncs.com")?Wd:e==="xf-yun.com"||e.endsWith(".xf-yun.com")||e==="xfyun.cn"||e.endsWith(".xfyun.cn")||e==="xfyun.com"||e.endsWith(".xfyun.com")?Kd:null:null}function Vd(n){let e=ls(n);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Yd(n,e){let t=as(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 as(n){return!n||typeof n!="object"?[]:!Array.isArray(n)&&n.codingPlanUsageDTO?[n]:Array.isArray(n)?n.flatMap(e=>as(e)):Object.values(n).flatMap(e=>as(e))}function cs(n,e){let t=n.match(new RegExp(`(?:^|;\\s*)${e}=([^;]+)`));return t?decodeURIComponent(t[1]):void 0}function ls(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,Zr,qr,es,ts,ns,Md,Ld,$d,Nd,os,rs,ss,is,jd,Hd,zd,Bd,Jd,Wd,Kd,Gd,Qd,us=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}},Zr=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}}},qr=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}},es=class extends pe{async queryQuota(e,t,o){let r=Vd(e.baseUrl),a=(await this.fetchJson(r,e,t,o))?.data;if(!a||typeof a!="object")return null;let i={},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}},ts=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}}},ns=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}}};Md=["per5HourPercentage","per5HourUsedPercentage","fiveHourPercentage"],Ld=["per1WeekPercentage","perWeekPercentage","per1WeekUsedPercentage"],$d=["per5HourResetTime","per5HourNextResetTime","fiveHourResetTime"],Nd=["per1WeekResetTime","per1WeekNextResetTime","perWeekResetTime"];os=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=cs(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 fc(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 fc(c)}catch{return null}}},rs=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:(cs(e.quotaToken,"atp-auth-token")||cs(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=Yd(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}}},ss=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}}},is=class extends pe{async queryQuota(e,t,o){let r=e.quotaToken||e.apiKey;if(!r)return null;let s=ls(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}}},jd=new Zr,Hd=new qr,zd=new es,Bd=new ts,Jd=new ns,Wd=new os,Kd=new rs,Gd=new ss,Qd=new is});async function No(n,e,t){if(!n||typeof t.fetchQuota!="function")return;let o=hc.get(n);if(o?.pending)return o.pending;if(o&&Date.now()-o.fetchedAt<Xd)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}})(),hc.set(n,r),r.pending}var Xd,yc,hc,ds=w(()=>{"use strict";Ke();Xd=6e4,yc=2500,hc=new Map});function _c(n){return{[Zd]:n,[qd]:Mn}}function Le(n){return typeof n.apiKey=="string"&&n.apiKey.startsWith("ccr-managed-")}function tp(n){return n===!0||n==="true"||n===1||n==="1"}function np(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 op(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 rp(n){try{let e=new URL(n).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function ps(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:fs,latencyMs:r()};let s=op(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 sp(n,e,t,o){if(Le(n))return{success:!1,skipped:!0,error:fs};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",..._c("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 ip(n,e,t,o,r){if(Le(n))return{success:!1,skipped:!0,error:fs};let s=n.baseUrl,a=n.baseUrl.includes("/messages")||e.includes("claude");try{let i={"Content-Type":"application/json",..._c("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 ms(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=ms(n,e,t,o,r,s);return a.start(),a}function Uo(){$e&&$e.stop()}function Do(){$e&&($e.stop(),$e=null)}var Zd,qd,ep,fs,Vt,$e,Fo=w(()=>{"use strict";ue();We();us();Ke();ds();fr();ae();Zd="x-claude-code-router-source",qd="x-claude-code-router-version";ep={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,slowThresholdMs:3e3,initialDelayMs:5e3,excludeProviders:[]};fs="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={...ep,...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=$o(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`))}}})}),rp(s.baseUrl)&&o.push({provider:s.name,models:i,type:"rate-limit-headers",promise:ps(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:No(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=>ps(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 ip(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=np(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}`),sp(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?tp(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 ps(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 bc=w(()=>{"use strict"});var gs,vt,kc=w(()=>{"use strict";gs=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 gs});var le,hs=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,ys=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
|
|
303
|
+
`,t.enqueue(o)}})}}});var Yt,_s=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 bs=w(()=>{"use strict";hs();ys();_s()});var Tc=w(()=>{"use strict"});var Xt,ks=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 Yt,hs=w(()=>{"use strict";Yt=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 Do(n,e){let t=(0,qe.resolve)(n),o=Uo.get(t),r,s=new Promise(a=>{r=a});Uo.set(t,s);try{return await o,await e()}finally{r(),Uo.get(t)===s&&Uo.delete(t)}}function yc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function gc(n,e){try{let t=await(0,we.lstat)(n);return t.isDirectory()&&!t.isSymbolicLink()&&yc(e,t)}catch{return!1}}function op(){return new Promise(n=>{setTimeout(n,10).unref()})}async function _c(n,e,t,o){let r=(0,qe.resolve)(n);if(o?.aborted||ys.has(r))return 0;ys.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,qe.join)(r,u.name);try{let d=await(0,we.lstat)(p);if(!d.isFile()||d.isSymbolicLink()||d.mtimeMs>=e)continue;await Do(p,async()=>{if(o?.aborted||!await gc(r,a))return!1;let h=await(0,we.lstat)(p);return!h.isFile()||h.isSymbolicLink()||!yc(d,h)||h.mtimeMs!==d.mtimeMs||h.mtimeMs>=e||o?.aborted?!1:(await(0,we.unlink)(p),!0)})&&s++}catch{}}finally{++c%64===0&&(await op(),l=!o?.aborted&&await gc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{ys.delete(r)}return s}function bc(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return _c(n,Date.now()-o,i=>np.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function rp(n,e){let t=Date.now()-qd;return _c(n,t,o=>{let r=tp.exec(o);return r!==null&&Number(r[1])<t},e)}function bs(n,e,t){let o=_s.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,ep),a.unref())},t);c.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(c),a&&clearInterval(a)}},_s.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),_s.delete(n)))}}function kc(n=(0,qe.join)((0,hc.tmpdir)(),"claude-code-router")){return bs(`legacy:${(0,qe.resolve)(n)}`,e=>rp(n,e),1e3)}var we,qe,hc,qd,ep,tp,np,ys,Uo,_s,ks=w(()=>{"use strict";we=require("node:fs/promises"),qe=require("node:path"),hc=require("node:os"),qd=3600*1e3,ep=600*1e3,tp=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,np=/^\.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$/,ys=new Set,Uo=new Map,_s=new Map});var be,Tc,vc,Ne,xc,Xt,Ts=w(()=>{"use strict";be=require("node:fs/promises"),Tc=require("node:crypto"),vc=require("@wengine-ai/claude-code-router-shared"),Ne=require("node:path"),xc=require("node:os");ks();Xt=class{type="temp-file";config;baseDir;controller=new AbortController;stopSchedule;constructor(e={}){if(this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",retentionMs:36e5,...e},this.baseDir=(0,Ne.resolve)((0,Ne.join)((0,xc.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=bs(`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,vc.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 Do(a,async()=>{await this.ensureDir();let i=(0,Ne.join)(this.baseDir,`.ccr-tmp-${process.pid}-${(0,Tc.randomUUID)()}.tmp`);return Do(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 bc(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var vs,Tt,Cc=w(()=>{"use strict";gs();hs();Ts();vs=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 Qt(e.config);case"webhook":return new Yt(e.config);case"temp-file":return new Xt(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,t){let o={...this.defaultOptions,...t},r={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,i])=>{try{await i.output(e,o)?r.success.push(a):r.failed.push(a)}catch(c){console.error(`[OutputManager] Handler ${a} failed:`,c),r.failed.push(a)}});return await Promise.all(s),r}async outputTo(e,t,o){let r={...this.defaultOptions,...o},s={success:[],failed:[]},a=e.map(async i=>{let c=this.handlers.get(i);if(!c){console.warn(`[OutputManager] Handler ${i} not found`),s.failed.push(i);return}try{await c.output(t,r)?s.success.push(i):s.failed.push(i)}catch(l){console.error(`[OutputManager] Handler ${i} failed:`,l),s.failed.push(i)}});return await Promise.all(a),s}async outputToType(e,t,o){let r=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(r,t,o)}},Tt=new vs});var xs=w(()=>{"use strict";mc();gs();hs();Ts();Cc()});function jo(){return{subdirectory:Pc.TOKEN_SPEED_TEMP_SUBDIRECTORY,extension:"json",includeTimestamp:!1,prefix:"session"}}function Sc(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,sp);return Math.round(n/o)}function qt(n){let e=(n.match(/[\u4e00-\u9fa5]/g)||[]).length,t=n.length-e;return Math.ceil(e/1.5+t/4)}async function Rc(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 Tt.outputToType(i,s,a)}catch(c){console.error(`[TokenSpeedPlugin] Failed to output to ${i}:`,c)}}var wc,Pc,Zt,Cs,sp,en,Ec=w(()=>{"use strict";wc=q(require("fastify-plugin"),1);ms();xs();ut();Pc=require("@wengine-ai/claude-code-router-shared");Zt=new Map,Cs=new Map,sp=1,en={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,wc.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)Tt.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:jo()}):i==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");a.length>0&&Tt.registerHandlers(a)}t.outputOptions&&Tt.setDefaultOptions(t.outputOptions);let r=async a=>{let i=n.tokenizerService;if(!i)return n.log?.warn("TokenizerService not available"),null;if(!a.provider||!a.model)return null;let c=a.provider,l=a.model,u=`${c}:${l}`;if(Cs.has(u))return Cs.get(u);let 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 Cs.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){Zt.set(u,{requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,stream:!0});let[y,b]=c.tee(),_=async()=>{let k=null,T=async x=>{let v=Zt.get(u);if(!v)return;let S=v.firstTokenTime?v.firstTokenTime-v.startTime:0,P=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Sc(v.tokenCount,P,S),await Rc(v,o,t.outputOptions,x).catch(N=>{n.log?.warn(`Failed to output streaming stats: ${N.message}`)})};try{let v=b.pipeThrough(new TextDecoderStream).pipeThrough(new le).getReader();for(k=setInterval(async()=>{Zt.get(u)&&await T(!1)},1e3);;){let{done:S,value:C}=await v.read();if(S)break;let P=C,N=Zt.get(u);if(!N)continue;let $=performance.now(),O=P.event||P.data?.type,D=P.event==="content_block_start"||P.event==="content_block_delta"||P.event==="text_block"||P.event==="content_block"||O==="response.output_text.delta"||O==="response.function_call_arguments.delta"||O==="response.reasoning_summary_text.delta";!N.firstTokenTime&&D&&(N.firstTokenTime=$,N.timeToFirstToken=Math.round($-N.startTime));let R="";if(P.event==="content_block_delta"&&P.data?.delta){let E=P.data.delta.type;E==="text_delta"?R=P.data.delta.text||"":E==="input_json_delta"?R=P.data.delta.partial_json||"":E==="thinking_delta"&&(R=P.data.delta.thinking||"")}if((O==="response.output_text.delta"||O==="response.function_call_arguments.delta"||O==="response.reasoning_summary_text.delta")&&(R=typeof P.data?.delta=="string"?P.data.delta:""),R){let E=f&&f.encodeText?f.encodeText(R).length:qt(R);N.tokenCount+=E,N.lastTokenTime=$}(P.event==="message_stop"||O==="response.completed"||O==="response.failed")&&(k&&(clearInterval(k),k=null),await T(!0),Zt.delete(u))}}catch(x){k&&clearInterval(k),x.name!=="AbortError"&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"&&n.log?.warn(`Error processing token stats: ${x.message}`)}};return a.tokenSpeedCapturePromise=_().catch(k=>{console.log(k),n.log?.warn(`Background stats processing failed: ${k.message}`)}),y}let h=performance.now(),g=0,m=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")g=y.usage.output_tokens,m=!0;else{let b=y.content??y.message?.content;if(b!==void 0)if(m=!0,f)Array.isArray(b)?g=b.reduce((_,k)=>{if(k.type==="text"){let T=k.text||"";return _+(f.encodeText?f.encodeText(T).length:qt(T))}return _},0):typeof b=="string"&&(g=f.encodeText?f.encodeText(b).length:qt(b));else{let _=Array.isArray(b)?b.map(k=>k.text).join(""):typeof b=="string"?b:"";g=qt(_)}}}catch{}if(m){let y=h-l,b={requestId:u,sessionId:d,statsKey:p,startTime:l,lastTokenTime:h,tokenCount:g,tokensPerSecond:Sc(g,y),stream:!1};await Rc(b,o,t.outputOptions,!0)}return c})})}});var Ss=w(()=>{"use strict";pc();fc();Ec();xs()});function Ac(){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,ws,$e,V,Rs,tn,nn,vt,te,on,me,ip,Ho,rn=w(()=>{"use strict";ie=q(require("node:fs/promises"),1),ws=q(require("json5"),1),$e=q(require("node:path"),1),V=require("@wengine-ai/claude-code-router-shared"),Rs=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(Rs);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Rs(o);return e}return n},tn=async n=>{try{await ie.default.access(n)}catch{await ie.default.mkdir(n,{recursive:!0})}},nn=async()=>{await tn(V.HOME_DIR),await tn(V.PLUGINS_DIR),await tn($e.default.join(V.HOME_DIR,"logs"))},vt=async()=>{let n=await ie.default.readFile(V.CONFIG_FILE,"utf-8");return ws.default.parse(n)},te=async()=>{try{let n=await ie.default.readFile(V.CONFIG_FILE,"utf-8");try{let e=ws.default.parse(n);return Rs(e)}catch(e){console.error(`Failed to parse config file at ${V.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 nn();let e=await on();e&&console.log(`Backed up existing configuration file to ${e}`);let t={PORT:3456,Providers:[],Router:{}};return await me(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 ${V.CONFIG_FILE}`),console.error("Error details:",n.message),process.exit(1)}};on=async()=>{Ac();try{if(await ie.default.access(V.CONFIG_FILE).then(()=>!0).catch(()=>!1)){let n=new Date().toISOString().replace(/[:.]/g,"-"),e=`${V.CONFIG_FILE}.${n}.bak`;await ie.default.copyFile(V.CONFIG_FILE,e);try{let t=$e.default.dirname(V.CONFIG_FILE),o=$e.default.basename(V.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=$e.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},me=async n=>{Ac(),await tn(V.HOME_DIR),await ip();let e=`${JSON.stringify(n,null,2)}`;await ie.default.writeFile(V.CONFIG_FILE,e)},ip=async()=>{if(!await ie.default.access(V.CONFIG_FILE).then(()=>!0).catch(()=>!1))return;let e=$e.default.join(V.HOME_DIR,"config-history");await tn(e);let t=new Date().toISOString().replace(/[:.]/g,"-"),o=$e.default.join(e,`config-${t}.json`);await ie.default.copyFile(V.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($e.default.join(e,a))}catch(r){console.warn("Failed to prune config-history:",r)}},Ho=async()=>{let n=await te();return Object.assign(process.env,n),n}});function zo(n,e,t){if(n){if(typeof n=="string"){let o=n.indexOf(",");if(o>0){let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&s&&e.has(r)&&t.add(Ps(r,s))}return}if(Array.isArray(n)){for(let o of n)zo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))zo(o,e,t)}}function Es(n){let e=n?.Providers||n?.providers||[],t=new Set,o=new Set;for(let r of e){let s=r?.name;if(!s)continue;t.add(s);let a=Array.isArray(r?.models)?r.models:[];for(let i of a)i&&o.add(Ps(s,i))}return zo(n?.Router,t,o),zo(n?.fallback,t,o),o}function xt(n,e){try{let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=Es(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(Ps(a,i))||(t.recover(a,i),r++)}return r>0&&e?.info?.(`[health-reconcile] Pruned ${r} orphaned provider-health entr${r===1?"y":"ies"}`),r}catch(t){return e?.warn?.(`[health-reconcile] Failed to reconcile health store: ${t?.message||t}`),0}}function sn(n,e){try{if(!n)return 0;let t=H();if(!t?.getAllStates||!t?.recover)return 0;let o=0;for(let r of t.getAllStates()||[])r?.provider===n&&r?.model&&(t.recover(n,r.model),o++);return o>0&&e?.info?.(`[health-reconcile] Cleared ${o} health entr${o===1?"y":"ies"} for probed provider ${n}`),o}catch(t){return e?.warn?.(`[health-reconcile] Failed to clear provider health for ${n}: ${t?.message||t}`),0}}var ap,Ps,an=w(()=>{"use strict";de();ap="\0",Ps=(n,e)=>`${n}${ap}${e}`});function cp(n){return/\[1m\]/i.test(n)?1e6:2e5}function lp(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function up(n,e=n){let t=cp(n),o=lp(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 dp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Bo(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,up(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=dp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var As=w(()=>{"use strict"});function pp(n){let e=n.ip||n.connection?.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}var cn,Os=w(()=>{"use strict";cn=n=>async(e,t,o)=>{if(["/","/health"].includes(e.url)||e.url.startsWith("/ui")||pp(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={};kn(Fs,{append:()=>mn,clear:()=>Ns,close:()=>Pp,getOldestRecordTimestamp:()=>Ep,query:()=>Ls,querySummary:()=>gn,readTokenSpeedStats:()=>$s});function yp(){(0,De.existsSync)(Wo)||(0,De.mkdirSync)(Wo,{recursive:!0})}function fn(){if(Ue)return Ue;yp();let n=(0,Lc.openSqliteDatabase)(fp),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&&(_p(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")),kp(e),Fc(e,!0),Ms=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 Ho(n,e){let t=(0,et.resolve)(n),o=jo.get(t),r,s=new Promise(a=>{r=a});jo.set(t,s);try{return await o,await e()}finally{r(),jo.get(t)===s&&jo.delete(t)}}function Sc(n,e){return n.dev===e.dev&&n.ino===e.ino}async function vc(n,e){try{let t=await(0,we.lstat)(n);return t.isDirectory()&&!t.isSymbolicLink()&&Sc(e,t)}catch{return!1}}function pp(){return new Promise(n=>{setTimeout(n,10).unref()})}async function Cc(n,e,t,o){let r=(0,et.resolve)(n);if(o?.aborted||vs.has(r))return 0;vs.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 Ho(p,async()=>{if(o?.aborted||!await vc(r,a))return!1;let g=await(0,we.lstat)(p);return!g.isFile()||g.isSymbolicLink()||!Sc(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 pp(),c=!o?.aborted&&await vc(r,a))}}}finally{await i.close().catch(()=>{})}}catch{}finally{vs.delete(r)}return s}function Rc(n,e,t,o,r){if(!Number.isFinite(o)||o<=0)return Promise.resolve(0);let s=`${e}-`,a=t?`.${t}`:"";return Cc(n,Date.now()-o,i=>dp.test(i)?!0:!i.endsWith(".tmp")&&i.startsWith(s)&&i.endsWith(a),r)}function fp(n,e){let t=Date.now()-cp;return Cc(n,t,o=>{let r=up.exec(o);return r!==null&&Number(r[1])<t},e)}function Ss(n,e,t){let o=xs.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,lp),a.unref())},t);l.unref(),o={users:0,stop:()=>{s.abort(),clearTimeout(l),a&&clearInterval(a)}},xs.set(n,o)}o.users++;let r=!1;return()=>{r||(r=!0,--o.users===0&&(o.stop(),xs.delete(n)))}}function wc(n=(0,et.join)((0,xc.tmpdir)(),"claude-code-router")){return Ss(`legacy:${(0,et.resolve)(n)}`,e=>fp(n,e),1e3)}var we,et,xc,cp,lp,up,dp,vs,jo,xs,Cs=w(()=>{"use strict";we=require("node:fs/promises"),et=require("node:path"),xc=require("node:os"),cp=3600*1e3,lp=600*1e3,up=/^session-[A-Za-z0-9_.-]+-(\d{13})\.json$/,dp=/^\.ccr-tmp-[1-9]\d*-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/,vs=new Set,jo=new Map,xs=new Map});var be,Pc,Ec,Ne,Ac,qt,Rs=w(()=>{"use strict";be=require("node:fs/promises"),Pc=require("node:crypto"),Ec=require("@wengine-ai/claude-code-router-shared"),Ne=require("node:path"),Ac=require("node:os");Cs();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,Ac.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=Ss(`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,Ec.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 Ho(a,async()=>{await this.ensureDir();let i=(0,Ne.join)(this.baseDir,`.ccr-tmp-${process.pid}-${(0,Pc.randomUUID)()}.tmp`);return Ho(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 Rc(this.baseDir,this.config.prefix||"session",this.config.extension||"",this.config.retentionMs,e)}dispose(){this.controller.abort(),this.stopSchedule?.()}getBaseDir(){return this.baseDir}}});var ws,xt,Oc=w(()=>{"use strict";ks();Ts();Rs();ws=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 ws});var Ps=w(()=>{"use strict";Tc();ks();Ts();Rs();Oc()});function zo(){return{subdirectory:$c.TOKEN_SPEED_TEMP_SUBDIRECTORY,extension:"json",includeTimestamp:!1,prefix:"session"}}function Ic(n,e,t=0){if(n<=0)return 0;let o=Math.max((e-t)/1e3,mp);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 Mc(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 Lc,$c,en,Es,mp,nn,Nc=w(()=>{"use strict";Lc=ee(require("fastify-plugin"),1);bs();Ps();dt();$c=require("@wengine-ai/claude-code-router-shared");en=new Map,Es=new Map,mp=1,nn={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,Lc.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:zo()}):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(Es.has(u))return Es.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 Es.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,T=async x=>{let v=en.get(u);if(!v)return;let P=v.firstTokenTime?v.firstTokenTime-v.startTime:0,R=(x?v.lastTokenTime:performance.now())-v.startTime;v.tokensPerSecond=Ic(v.tokenCount,R,P),await Mc(v,o,t.outputOptions,x).catch(O=>{n.log?.warn(`Failed to output streaming stats: ${O.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:P,value:A}=await v.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 T(!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 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-c,b={requestId:u,sessionId:d,statsKey:p,startTime:c,lastTokenTime:g,tokenCount:h,tokensPerSecond:Ic(h,y),stream:!1};await Mc(b,o,t.outputOptions,!0)}return l})})}});var As=w(()=>{"use strict";bc();kc();Nc();Ps()});function Uc(){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,Is,Ue,Y,Os,on,rn,St,ne,sn,fe,gp,Bo,an=w(()=>{"use strict";ie=ee(require("node:fs/promises"),1),Is=ee(require("json5"),1),Ue=ee(require("node:path"),1),Y=require("@wengine-ai/claude-code-router-shared"),Os=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(Os);if(n!==null&&typeof n=="object"){let e={};for(let[t,o]of Object.entries(n))e[t]=Os(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 Is.default.parse(n)},ne=async()=>{try{let n=await ie.default.readFile(Y.CONFIG_FILE,"utf-8");try{let e=Is.default.parse(n);return Os(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()=>{Uc();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=>{Uc(),await on(Y.HOME_DIR),await gp();let e=`${JSON.stringify(n,null,2)}`;await ie.default.writeFile(Y.CONFIG_FILE,e)},gp=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)}},Bo=async()=>{let n=await ne();return Object.assign(process.env,n),n}});function Jo(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(Ms(r,s))}return}if(Array.isArray(n)){for(let o of n)Jo(o,e,t);return}if(typeof n=="object")for(let o of Object.values(n))Jo(o,e,t)}}function Ls(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(Ms(s,i))}return Jo(n?.Router,t,o),Jo(n?.fallback,t,o),o}function Ct(n,e){try{let t=z();if(!t?.getAllStates||!t?.recover)return 0;let o=Ls(n),r=0;for(let s of t.getAllStates()||[]){let a=s?.provider,i=s?.model;!a||!i||o.has(Ms(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 hp,Ms,ln=w(()=>{"use strict";ue();hp="\0",Ms=(n,e)=>`${n}${hp}${e}`});function yp(n){return/\[1m\]/i.test(n)?1e6:2e5}function _p(n){let e=n.toLowerCase();return e.includes("haiku")||e.includes("mini")?8192:32e3}function bp(n,e=n){let t=yp(n),o=_p(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 kp(n,e,t){if(!n)return!1;try{return!n(e,t)}catch{return!1}}function Wo(n,e){let t=new Map,o=(r,s=r)=>{!r||t.has(r)||t.set(r,bp(r,s))};o("ccr-opus","CCR Opus"),o("ccr-sonnet","CCR Sonnet"),o("ccr-haiku","CCR Haiku"),o("ccr-opus[1m]","CCR Opus 1M"),o("ccr-sonnet[1m]","CCR Sonnet 1M"),o("ccr-haiku[1m]","CCR Haiku 1M");for(let r of n.Providers||n.providers||[])if(!(!r?.name||!Array.isArray(r.models)))for(let s of r.models){if(typeof s!="string"||!s)continue;let a=kp(e,r.name,s);a||o(s,s),a||o(`${r.name},${s}`,`${r.name}/${s}`)}return Array.from(t.values())}var $s=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,Ns=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 zs={};vn(zs,{append:()=>hn,clear:()=>js,close:()=>Up,getOldestRecordTimestamp:()=>Dp,query:()=>Fs,querySummary:()=>yn,readTokenSpeedStats:()=>Hs});function Rp(){(0,je.existsSync)(Go)||(0,je.mkdirSync)(Go,{recursive:!0})}function gn(){if(Fe)return Fe;Rp();let n=(0,Hc.openSqliteDatabase)(vp),e=n.db;n.driver==="node:sqlite"&&console.error(`[usage] better-sqlite3 unavailable, using built-in node:sqlite fallback. Reason: ${n.fallbackReason}`),e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("busy_timeout = 5000");let t=e.pragma("user_version",{simple:!0})||0;return t<1&&(wp(e),e.pragma("user_version = 1")),t<2&&(e.prepare("PRAGMA table_info(usage_records)").all().some(r=>r.name==="upstream_model")||e.exec("ALTER TABLE usage_records ADD COLUMN upstream_model TEXT"),e.pragma("user_version = 2")),t<3&&(e.exec("ALTER TABLE usage_records ADD COLUMN usage_estimated INTEGER NOT NULL DEFAULT 0"),e.pragma("user_version = 3")),Ep(e),Jc(e,!0),Ds=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
|
-
`),
|
|
322
|
+
`),Fe=e,Fe}function wp(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 Pp(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 Ep(n){if(Pp(n,Dc)||!(0,je.existsSync)(Us))return;let e=Op(n,"INSERT OR IGNORE"),t=(0,je.readFileSync)(Us,"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(!Ap(c)){r++;continue}e.run(Bc(Qo(c))).changes>0?o++:s++}catch{r++}}dn(n,Dc,new Date().toISOString()),dn(n,"legacy_usage_jsonl_migrated_path",Us),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 Ap(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 Op(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 Ip(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,xp);return Math.round(n/r)}function Qo(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:Ip(e,o,r)}}function De(n){return typeof n=="string"?n:n==null?"":String(n)}function Ko(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 zc(n){return n==="success"?"success":"error"}function Bc(n){let e=Qo(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:Ko(e.upstreamModel)??null,model_family:De(e.modelFamily),scenario_type:De(e.scenarioType),client_type:Ko(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:zc(e.status),error_message:Ko(e.errorMessage)??null,response_body:Ko(e.responseBody)??null}}function Mp(n){return Qo({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:zc(n.status),errorMessage:n.error_message??void 0,responseBody:n.response_body??void 0})}function Lp(){return new Date(Date.now()-Sp*24*60*60*1e3).toISOString()}function Jc(n,e=!1){let t=Date.now();!e&&t-Fc<Cp||(n.prepare("DELETE FROM usage_records WHERE timestamp < ?").run(Lp()),Fc=t)}function Wc(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, ${$p}
|
|
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 Kc(n,e){let t=Wc(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:
|
|
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=Qo(n);Ds.run(Bc(t)),Jc(e)}function Fs(n){let e=gn(),t=Wc(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),Np):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=Kc(e,n);return{records:i.map(Mp),summary:l,total:a.count,page:o,pageSize:r}}function yn(n,e,t){let o=gn();return Kc(o,{startTime:n,endTime:e,status:t})}function js(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 Up(){Fe&&(Fe.pragma("wal_checkpoint(TRUNCATE)"),Fe.close(),Fe=null,Ds=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 Hs(n){let e=(0,mn.join)((0,jc.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 Dp(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,jc,Hc,wt,Go,vp,Us,xp,Sp,Cp,Dc,Fe,Ds,Fc,$p,Np,_n=w(()=>{"use strict";je=require("fs"),mn=require("path"),jc=require("os"),Hc=require("@wengine-ai/claude-code-router-shared"),wt=require("@wengine-ai/claude-code-router-shared"),Go=(0,mn.join)(wt.HOME_DIR,"data"),vp=(0,mn.join)(Go,"usage.sqlite"),Us=(0,mn.join)(Go,"usage.jsonl"),xp=1,Sp=180,Cp=3600*1e3,Dc="legacy_usage_jsonl_migrated_at",Fe=null,Ds=null,Fc=0;$p=`
|
|
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
|
-
`;wp=200});async function Jc(){let n=(0,Hc.homedir)(),e=(0,zc.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,Bc.writeFile)(e,JSON.stringify(o,null,2))}}var jc,Hc,zc,Bc,Wc=w(()=>{"use strict";jc=require("fs"),Hc=require("os"),zc=require("path"),Bc=require("fs/promises")});function Gc(n=(0,Us.join)(Vc.HOME_DIR,"logs")){try{if(!(0,je.existsSync)(n))return;let e=Date.now()-Op;for(let t of(0,je.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,Us.join)(n,t),r=(0,je.statSync)(o);r.isFile()&&r.mtime.getTime()<e&&(0,je.unlinkSync)(o)}}catch(e){console.warn("Failed to prune old server log files:",e)}}function Qc(){Kc||(Kc=!0,Gc(),setInterval(Gc,Ip).unref())}var je,Us,Vc,Ap,Op,Ip,Kc,Yc=w(()=>{"use strict";je=require("fs"),Us=require("path"),Vc=require("@wengine-ai/claude-code-router-shared"),Ap=7,Op=Ap*24*60*60*1e3,Ip=1440*60*1e3,Kc=!1});async function Xc(n,e){let t=e.plugins||e.Plugins||[];for(let o of t){let{name:r,enabled:s=!1,options:a={}}=o;switch(r){case"token-speed":kt.registerPlugin(en,{enabled:s,outputHandlers:[{type:"temp-file",enabled:!0,config:jo()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await kt.enablePlugins(n)}var Zc=w(()=>{"use strict";Ss()});function Rt(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()),xt(e,t),$o();let o={enabled:n.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:n.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:n.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(n.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:n.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:n.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};n.activeProbeService=bt(()=>n.providerService.getProviders(),o,r=>he(n.configService,r),t,r=>n.configService.get(r))}catch(o){t.warn(`Config saved but runtime reload failed: ${o?.message||o}`)}}var Go=w(()=>{"use strict";an();Fo();ae()});function tl(n){try{let e=JSON.parse((0,B.readFileSync)((0,ke.join)(Mp(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function js(n,e){if(!el(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 Ds(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=js(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||js(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 Lp(n){let e=n?.configService,t=e?ei(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return ti(t)}async function nl(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??ur(),r={configDir:e,readConfig:()=>te(),readRawConfig:()=>vt(),writeConfig:i=>me(i),reloadRuntime:async i=>Rt(n.getServer(),i??await te(),t),getDirectDispatcher:er,getSubscriptionDispatcher:()=>Lp(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of tl(e)){let c;try{if(!el(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=js(e,i.name);if(!l){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let g=JSON.parse(Ds(e,i.name,"plugin.json").toString("utf8"));if(!g||typeof g.name!="string"||typeof g.version!="string")throw new Error;u={name:g.name,version:g.version,coreApi:String(g.coreApi??"1"),description:g.description}}catch{throw new Error("plugin.json missing or malformed")}if(u.name!==i.name)throw new Error("manifest name does not match install directory");if(u.coreApi.split(".")[0]!=="1".split(".")[0])throw new Error(`coreApi ${u.coreApi} incompatible with core ${"1"}`);let p=o.beginActivation(u,{info:g=>t.info(`[plugin:${u.name}] ${g}`),warn:g=>t.warn(`[plugin:${u.name}] ${g}`),error:g=>t.error(`[plugin:${u.name}] ${g}`)},r,l);c=p,Ds(e,i.name,"plugin.js");let d=await import((0,qc.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 h=p.cardPath?Ds(e,i.name,p.cardPath):void 0;await p.commit(h,n.getServer()?.app),s.loaded.push(u.name),t.info(`plugin loaded: ${u.name}@${u.version}`)}catch(l){c?.abort(),s.failed.push({name:i.name,error:l?.message??String(l)}),t.warn(`plugin ${i.name} failed to load: ${l?.message??String(l)}`)}}return s}function ol(n,e=ur()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return tl(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,qc,el,Mp,Hs=w(()=>{"use strict";B=require("node:fs"),ke=require("node:path"),qc=require("node:url");cr();An();Go();rn();ae();el=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),Mp=n=>(0,ke.join)(n,"plugins")});async function $p(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 Fp(n,e={}){let t=(e.registryBase??Np).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(rl.map(m=>$p(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(!_||!ge.NPM_SPEC_PATTERN.test(_)||!(Array.isArray(b?.keywords)?b.keywords.filter(x=>typeof x=="string"):[]).some(x=>rl.includes(x)))continue;let T=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:T,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=(0,ge.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(!ge.PLUGIN_NAME_PATTERN.test(m))return null;try{let y=JSON.parse((0,yn.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,yn.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)),h=new Set,g=new Map;for(let[m,y]of u)h.add(y.name),!f.has(m)&&g.set(m,y.name);for(let m of i)f.has(m.name)||h.has(m.name)||g.set(m.name,m.name);for(let[m,y]of g){if(!ge.PLUGIN_NAME_PATTERN.test(y)||!(0,yn.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 Up(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 sl(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 il(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(!sl(r,n,t))return o(s,403,"local_only");try{return await Fp(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(!sl(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,ge.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 ge.PluginInstallError){let u=Up(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 yn,Vo,ge,rl,Np,al=w(()=>{"use strict";yn=require("node:fs"),Vo=require("node:path"),ge=require("@wengine-ai/claude-code-router-shared"),rl=["ccr-provider-plugin","claude-code-router-plugin"],Np="https://registry.npmjs.org"});function cl(n){let e=H();return Bo(n,(t,o)=>e.isAvailable(t,o))}function ll(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 Dp(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=gn(t,e),s=gn(o,e),a=[],i=new Set;for(let c of n||[])c&&c.name&&i.add(c.name);for(let c of Object.keys(r.byProvider||{}))i.add(c);for(let c of Object.keys(s.byProvider||{}))i.add(c);for(let c of i){let l=r.byProvider[c]||{inputTokens:0,outputTokens:0},u=s.byProvider[c]||{inputTokens:0,outputTokens:0},p=(l.inputTokens||0)+(l.outputTokens||0),d=(u.inputTokens||0)+(u.outputTokens||0),f,h,g=(n||[]).find(m=>m&&m.name===c);g&&g.quota&&(f=g.quota.limit5h,h=g.quota.limit7d),a.push({provider:c,used5h:p,used7d:d,limit5h:f,limit7d:h})}return a}async function gl(n,e){let t=n.app;st(),ct(),t.register(fl.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=cl(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=cl(e).find(p=>p.id===l);return u||(c.status(404),{type:"error",error:{type:"not_found_error",message:`Model not found: ${l}`}})}),t.post("/v1/messages/count_tokens",async(i,c)=>{let{messages:l,tools:u,system:p,model:d}=i.body,f=t._server.tokenizerService;if(d&&d.includes(",")&&f)try{let[g,m]=d.split(",");i.log?.info(`Looking up tokenizer for provider: ${g}, model: ${m}`);let y=f.getTokenizerConfigForModel(g,m);y?i.log?.info(`Using tokenizer config: ${JSON.stringify(y)}`):i.log?.warn(`No tokenizer config found for ${g},${m}, using default tiktoken`);let b=await f.countTokens({messages:l,system:p,tools:u},y,g);return{input_tokens:b.tokenCount,tokenizer:b.tokenizerUsed}}catch(g){i.log?.error(`Error using configured tokenizer: ${g.message}`),i.log?.error(g.stack)}else d?d.includes(",")?f||i.log?.warn("TokenizerService not available, using default tiktoken"):i.log?.info(`Model "${d}" does not contain comma, using default tiktoken`):i.log?.info("No model specified, using default tiktoken");return{input_tokens:Ut(l,p,u)}}),t.get("/api/config",async(i,c)=>await vt()),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=qs(l||{});if(u.length>0)return c.status(400),{success:!1,error:"Invalid proxy URL",message:u.map(h=>`${h.key}: ${h.error}`).join("; "),proxyErrors:u};let p=await on();p&&console.log(`Backed up existing configuration file to ${p}`);let d=null;try{d=await te()}catch{}(0,ul.ensureCcrSelfProvider)(l,d),n.pluginRegistry.applyConfigProtectors(l,d),await me(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(h){t.log?.warn?.(`Config saved but global project takeover sync failed: ${h?.message||h}`)}return Rt(n,l,t.log),{success:!0,message:"Config saved successfully",projectTakeoverSync:f}}),t.get("/api/clients",async(i,c)=>{try{let l=await te();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 te(),d=(0,A.applyClientSelection)(p,u);await me(d.config);let f=await(0,A.syncGlobalProjectTakeovers)(d.config),h=ll(t,f,"clients/apply");return{...d,success:d.success&&h,projectTakeoverSync:f}}catch(l){console.error("Failed to apply client integrations:",l),c.status(500).send({error:l.message||"Failed to apply client integrations"})}});async function o(i,c,l){try{let{id:u}=i.params;if(!(0,A.isClientId)(u)){c.status(404).send({error:`Unknown client: ${u}`});return}let p=await te(),d=l==="enable"?(0,A.enableClient)(p,u):l==="restore"?(0,A.restoreClient)(p,u):(0,A.disableClient)(p,u);await me(p);let f=await(0,A.syncGlobalProjectTakeovers)(p),h=ll(t,f,`clients/${u}/${l}`);return{success:d.success&&h,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,Z.isAbsolute)(l)){c.status(400).send({error:"A valid absolute project path is required"});return}let u=(0,Z.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 te();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 te();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 te(),h=await(0,A.setProjectTakeover)(d.path,p,f);return{id:l,path:d.path,ccrTakeoverClients:h,ccrTakeover:h.length>0}}catch(l){console.error("Failed to update ccr takeover status:",l),c.status(500).send({error:l.message||"Failed to update ccr takeover status"})}}),t.delete("/api/projects/:id",async(i,c)=>{try{let{id:l}=i.params,u=await(0,A.readProjectConfigById)(l);if(!u){c.status(404).send({error:"Project config not found"});return}try{let p=await te();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,Z.dirname)((0,dl.fileURLToPath)(void 0)),s=(0,J.existsSync)((0,Z.join)(r,"index.html"))?r:(0,J.existsSync)((0,Z.join)(r,"..","index.html"))?(0,Z.join)(r,".."):(0,Z.join)(r,"..","dist");t.register(pl.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,Z.join)((0,Qo.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,Z.join)(l,d),h=(0,J.statSync)(f);u.push({name:d,path:f,size:h.size,lastModified:h.mtime.toISOString()})}u.sort((d,f)=>new Date(f.lastModified).getTime()-new Date(d.lastModified).getTime())}return u}catch(l){console.error("Failed to get log files:",l),c.status(500).send({error:"Failed to get log files"})}}),t.get("/api/logs",async(i,c)=>{try{let l=i.query.file,u;return l?u=l:u=(0,Z.join)((0,Qo.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,Z.join)((0,Qo.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:Et()})),t.put("/api/debug-log",async i=>{let{enabled:c}=i.body;return Sn(c),{enabled:Et()}}),t.get("/api/usage",async(i,c)=>{try{let l=i.query;return Ls({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 gn(l.startDate,l.endDate,l.status)}catch(l){console.error("Failed to query usage summary:",l),c.status(500).send({error:"Failed to query usage summary"})}}),t.delete("/api/usage",async(i,c)=>{try{let l=i.query;return Ns(l.beforeDate),{success:!0,message:l.beforeDate?"Usage data cleared before "+l.beforeDate:"All usage data cleared"}}catch(l){console.error("Failed to clear usage:",l),c.status(500).send({error:"Failed to clear usage data"})}}),t.get("/api/providers/health",async(i,c)=>{try{let u=H().getAllStates(),d=t._server?.activeProbeService?.getProbeTelemetry?.()||[];return{states:u.map(f=>({provider:f.provider,model:f.model,status:f.status,failureCount:f.failureCount,successCount:f.successCount,lastFailureTime:f.lastFailureTime,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&&sn(l,i.log),{provider:l,success:d.success,latencyMs:d.latencyMs,status:d.status,isSlow:d.isSlow,errorKind:d.errorKind??null,error:d.error,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe provider:",l),c.status(500).send({error:l.message||"Failed to probe provider"})}}),t.post("/api/providers/probe-all",async(i,c)=>{try{let l=t._server,u=l?.activeProbeService;if(!u?.probeProviderManually)return c.status(503),{error:"Active probe service is not available"};let p=(l?.providerService?.getProviders?.()||[]).filter(f=>f?.name&&f.enabled!==!1),d=await Promise.all(p.map(async f=>{let h=await u.probeProviderManually(f.name);return h.success&&sn(f.name,i?.log),{provider:f.name,success:h.success,latencyMs:h.latencyMs,status:h.status,isSlow:h.isSlow,errorKind:h.errorKind??null,error:h.error}}));return{results:d,successCount:d.filter(f=>f.success).length,total:d.length,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to probe all providers:",l),c.status(500).send({error:l.message||"Failed to probe all providers"})}}),t.get("/api/providers/quota",async(i,c)=>{try{let u=(await te()).Providers||[],p=Dp(u),d=new Map(p.map(g=>[g.provider,g])),f=Ln();for(let g of p){let m=f.find(y=>y.provider===g.provider);m&&m.limit!=null&&!Nn(m.reset)&&(g.limit5h=m.limit,g.used5h=m.limit-(m.remaining??0),m.reset&&(g.reset5h=new Date(m.reset*1e3).toISOString()))}let h=zn();for(let g of h){let m=d.get(g.provider);m||(m={provider:g.provider,used5h:0,used7d:0},p.push(m),d.set(g.provider,m)),typeof g.totalBalance=="number"?(m.limit7d=g.totalBalance,m.type7d=g.currency?"balance":"rateLimit",g.currency&&(m.currency=g.currency),typeof g.usedBalance=="number"?m.used7d=g.usedBalance:typeof g.remainingBalance=="number"?m.used7d=Math.max(0,g.totalBalance-g.remainingBalance):(m.used7d=0,m.limit7d=g.totalBalance)):typeof g.usedBalance=="number"&&(m.used7d=g.usedBalance);let y=Nn(typeof g.resetTime=="string"?Date.parse(g.resetTime)/1e3:void 0),b=Nn(typeof g.resetTime7d=="string"?Date.parse(g.resetTime7d)/1e3:void 0);typeof g.usedDailyBalance=="number"&&!y&&(m.used5h=g.usedDailyBalance,m.type5h="rateLimit"),typeof g.limitDaily=="number"&&!y&&(m.limit5h=g.limitDaily,m.type5h="rateLimit"),typeof g.resetTime=="string"&&!y&&(g.limitDaily!==void 0?m.reset5h=g.resetTime:m.reset7d=g.resetTime),typeof g.resetTime7d=="string"&&!b&&(m.reset7d=g.resetTime7d)}return{quotas:p,timestamp:new Date().toISOString()}}catch(l){console.error("Failed to compute provider quota:",l),c.status(500).send({error:"Failed to compute provider quota"})}}),t.get("/api/presets",async(i,c)=>{try{let l=(0,Z.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 h=(0,Z.join)(l,f);try{let g=(0,Z.join)(h,"manifest.json"),m=(0,J.readFileSync)(g,"utf-8"),y=JSON.parse(m),{Providers:b,Router:_,PORT:k,HOST:T,API_TIMEOUT_MS:x,PROXY_URL:v,PROXY_GLOBAL_ENABLED:S,LOG:C,LOG_LEVEL:P,StatusLine:N,NON_INTERACTIVE_MODE:$,...O}=y;d.push({id:f,name:O.name||f,version:O.version||"1.0.0",description:O.description,author:O.author,homepage:O.homepage,repository:O.repository,license:O.license,keywords:O.keywords,ccrVersion:O.ccrVersion,source:O.source,sourceType:O.sourceType,checksum:O.checksum,installed:!0})}catch(g){console.error(`Failed to read preset ${f}:`,g)}}return{presets:d}}catch(l){console.error("Failed to get presets:",l),c.status(500).send({error:"Failed to get presets"})}}),t.get("/api/presets/:name",async(i,c)=>{try{let{name:l}=i.params,u=(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,h=u.name||l;if(await(0,A.isPresetInstalled)(h)){c.status(409).send({error:"Preset already installed",message:`Preset '${h}' is already installed. To update or reconfigure, please delete it first using the delete button.`,presetName:h});return}let g=`https://github.com/${d}/${f}/archive/refs/heads/main.zip`,m=await(0,A.downloadPresetToTemp)(g),y=await a(m);if(await(0,A.isPresetInstalled)(h)){(0,J.unlinkSync)(m),c.status(409).send({error:"Preset already installed",message:`Preset '${h}' was installed while downloading. Please try again.`,presetName:h});return}let b=(0,A.getPresetDir)(h);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)(h,_),(0,J.unlinkSync)(m),{success:!0,presetName:h,preset:{...y.metadata,installed:!0}}}catch(l){console.error("Failed to install preset from GitHub:",l),c.status(500).send({error:l.message||"Failed to install preset from GitHub"})}});async function a(i){let c=new ml.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:ol(A.HOME_DIR,n.pluginRegistry)})),il(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 ul,Z,dl,pl,J,Qo,A,fl,ml,hl=w(()=>{"use strict";Ge();Je();lt();Je();ae();At();de();an();Go();Hs();al();rn();ul=require("@wengine-ai/claude-code-router-shared"),Z=require("path"),dl=require("url"),pl=q(require("@fastify/static"),1),J=require("fs"),Qo=require("os"),A=require("@wengine-ai/claude-code-router-shared"),fl=q(require("@fastify/multipart"),1),ml=q(require("adm-zip"),1);hn();As()});function jp(n,e){let t=n?.Router,{family:o}=Dt(e||"");if(t?.enableFamilyRouting&&o){let r=t.families?.[o]?.image;if(r)return r}return t?.image}function yl(n){return n?.Router?.image}function Hp(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 zs,Yo,Bs,_l,bl=w(()=>{"use strict";Ge();zs=class{cache=new Map;maxSize;ttl;constructor(e=100,t=300*1e3){this.maxSize=e,this.ttl=t}evictExpired(){let e=Date.now();for(let[t,o]of this.cache)e-o.timestamp>this.ttl&&this.cache.delete(t)}trim(){if(this.cache.size<=this.maxSize)return;let e=[...this.cache.keys()].slice(0,this.cache.size-this.maxSize);for(let t of e)this.cache.delete(t)}storeImage(e,t){this.hasImage(e)||(this.evictExpired(),this.cache.set(e,{source:t,timestamp:Date.now()}),this.trim())}getImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.source:null}hasImage(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),!1):!0:!1}clear(){this.cache.clear()}size(){return this.evictExpired(),this.cache.size}},Yo=new zs;Bs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=jp(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Hp(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&jt(e.body.model)?!1:(zp(e.body.messages),s&&!!yl(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=Yo.getImage(`${t.req.id}_Image#${i}`);c&&o.push({type:"image",source:c})});else{let i=Yo.getImage(`${t.req.id}_Image#${e.imageId}`);i&&o.push({type:"image",source:i})}r=e.imageId,delete e.imageId}let s=t.req.body.messages[t.req.body.messages.length-1];if(s.role==="user"&&Array.isArray(s.content)){let i=s.content.filter(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:yl(t.config),system:[{type:"text",text:`You must interpret and analyze images strictly according to the assigned task.
|
|
400
|
+
`;Np=200});async function Xc(){let n=(0,Qc.homedir)(),e=(0,Vc.join)(n,".claude.json");if(!(0,Gc.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,Yc.writeFile)(e,JSON.stringify(o,null,2))}}var Gc,Qc,Vc,Yc,Zc=w(()=>{"use strict";Gc=require("fs"),Qc=require("os"),Vc=require("path"),Yc=require("fs/promises")});function el(n=(0,Bs.join)(tl.HOME_DIR,"logs")){try{if(!(0,He.existsSync)(n))return;let e=Date.now()-jp;for(let t of(0,He.readdirSync)(n)){if(!/^ccr-.*\.log$/.test(t))continue;let o=(0,Bs.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 nl(){qc||(qc=!0,el(),setInterval(el,Hp).unref())}var He,Bs,tl,Fp,jp,Hp,qc,ol=w(()=>{"use strict";He=require("fs"),Bs=require("path"),tl=require("@wengine-ai/claude-code-router-shared"),Fp=7,jp=Fp*24*60*60*1e3,Hp=1440*60*1e3,qc=!1});async function rl(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:zo()}],...a});break;default:console.warn(`Unknown plugin: ${r}`);break}}await vt.enablePlugins(n)}var sl=w(()=>{"use strict";As()});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),Do();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 Vo=w(()=>{"use strict";ln();Fo();ae()});function cl(n){try{let e=JSON.parse((0,B.readFileSync)((0,ke.join)(zp(n),"plugins.json"),"utf8"));return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"):[]}catch{return[]}}function Ws(n,e){if(!al(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 Js(n,e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t))throw new Error("invalid plugin file");let o=Ws(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||Ws(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 Bp(n){let e=n?.configService,t=e?si(e):String(process.env.SUBSCRIPTION_PROXY_URL??"").trim()||void 0;return ii(t)}async function ll(n){let{configDir:e,log:t}=n,o=n.registry??n.getServer()?.pluginRegistry??pr(),r={configDir:e,readConfig:()=>ne(),readRawConfig:()=>St(),writeConfig:i=>fe(i),reloadRuntime:async i=>Pt(n.getServer(),i??await ne(),t),getDirectDispatcher:nr,getSubscriptionDispatcher:()=>Bp(n.getServer())},s={loaded:[],failed:[],skipped:[]},a=new Set;for(let i of cl(e)){let l;try{if(!al(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=Ws(e,i.name);if(!c){s.skipped.push({name:i.name,reason:"directory missing or unsafe"});continue}let u;try{let h=JSON.parse(Js(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,Js(e,i.name,"plugin.js");let d=await import((0,il.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?Js(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 ul(n,e=pr()){let t=new Map(e.listLoadedPlugins().map(o=>[o.name,o]));return cl(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,il,al,zp,Ks=w(()=>{"use strict";B=require("node:fs"),ke=require("node:path"),il=require("node:url");ur();In();Vo();an();ae();al=n=>/^[a-z0-9][a-z0-9-]*$/i.test(n),zp=n=>(0,ke.join)(n,"plugins")});async function Wp(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 Kp(n,e={}){let t=(e.registryBase??Jp).replace(/\/$/,""),o=e.timeoutMs??3e4,r=await Promise.allSettled(dl.map(m=>Wp(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=>dl.includes(x)))continue;let T=typeof b?.version=="string"?b.version:"";s.has(_)||s.set(_,{name:_,version:T,description:typeof b?.description=="string"?b.description:""})}}if(!a)return{ok:!0,plugins:[],warning:"registry_unavailable"};let i=(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,bn.readFileSync)((0,Yo.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,bn.existsSync)((0,Yo.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,Yo.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 Gp(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 pl(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 fl(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(!pl(r,n,t))return o(s,403,"local_only");try{return await Kp(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(!pl(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=Gp(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,Yo,me,dl,Jp,ml=w(()=>{"use strict";bn=require("node:fs"),Yo=require("node:path"),me=require("@wengine-ai/claude-code-router-shared"),dl=["ccr-provider-plugin","claude-code-router-plugin"],Jp="https://registry.npmjs.org"});function gl(n){let e=z();return Wo(n,(t,o)=>e.isAvailable(t,o))}function hl(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 Qp(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 vl(n,e){let t=n.app;it(),ut(),t.register(kl.default,{limits:{fileSize:50*1024*1024}}),t.get("/v1/models",async()=>{let i=gl(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=gl(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=ri(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,yl.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=hl(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=hl(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,_l.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(bl.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,Xo.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,Xo.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,Xo.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 wn(l),{enabled:Ot()}}),t.get("/api/usage",async(i,l)=>{try{let c=i.query;return Fs({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 js(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 No(_.name,_,k)}).filter(_=>!!_);if(b.length){let _=new Promise(k=>{setTimeout(k,yc).unref?.()});await Promise.race([Promise.all(b),_])}}let f=Qp(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(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:T,API_TIMEOUT_MS:x,PROXY_URL:v,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:ul(E.HOME_DIR,n.pluginRegistry)})),fl(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 yl,q,_l,bl,J,Xo,E,kl,Tl,xl=w(()=>{"use strict";Ve();We();Ke();ds();We();ae();It();ue();ln();Vo();Ks();ml();an();yl=require("@wengine-ai/claude-code-router-shared"),q=require("path"),_l=require("url"),bl=ee(require("@fastify/static"),1),J=require("fs"),Xo=require("os"),E=require("@wengine-ai/claude-code-router-shared"),kl=ee(require("@fastify/multipart"),1),Tl=ee(require("adm-zip"),1);_n();$s()});function Vp(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 Sl(n){return n?.Router?.image}function Yp(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 Xp(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 Gs,Zo,Qs,Cl,Rl=w(()=>{"use strict";Ve();Gs=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}},Zo=new Gs;Qs=class{name="image";tools;constructor(){this.tools=new Map,this.appendTools()}shouldHandle(e,t){let o=Vp(t,e.originalModel||e.body.model);if(!o||e.body.model===o||!Yp(e.body.messages))return!1;let s=t.forceUseImageAgent===!0;return!s&&zt(e.body.model)?!1:(Xp(e.body.messages),s&&!!Sl(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=Zo.getImage(`${t.req.id}_Image#${i}`);l&&o.push({type:"image",source:l})});else{let i=Zo.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:Sl(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")Yo.storeImage(`${e.id}_Image#${r}`,a.source),a.type="text",delete a.source,a.text=`[Image #${r}]This is an image, if you need to view or analyze it, you need to extract the imageId`,r++;else if(a.type==="text"&&a.text.includes("[Image #"))a.text=a.text.replace(/\[Image #\d+\]/g,"");else if(a.type==="tool_result"&&Array.isArray(a.content)&&a.content.some(i=>i.type==="image")){let i=[],c=a.content.filter(u=>u.type!=="image"?!0:(Yo.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}})})}},_l=new Bs});var Js,kl,Xo,Tl=w(()=>{"use strict";bl();Js=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}},kl=new Js;kl.registerAgent(_l);Xo=kl});function Jp(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 Sl(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ae(n,e)}function Ks(n){return n.usageSessionId||n.id}function Zo(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Ks(n)}`}function _n(n){return typeof n=="string"&&n.trim()!==""&&n!=="unknown"}function et(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 Wp(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 Kp(n,e,t){if(await new Promise((r,s)=>{let a=i=>i?s(i):r();cn(t)(n,e,a).then(()=>r(),s)}),e.sent)return;let o=new URL(`http://127.0.0.1${n.url}`);if(n.pathname=o.pathname,n.pathname.endsWith("/v1/messages")&&n.pathname!=="/v1/messages"&&(n.preset=n.pathname.replace("/v1/messages","").replace("/","")),n.pathname.endsWith("/v1/responses")&&n.pathname!=="/v1/responses"&&(n.preset=n.pathname.replace("/v1/responses","").replace("/","")),n.pathname.endsWith("/v1/messages")||n.pathname.endsWith("/v1/responses")){Sl(n,t);let r=Zo(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=ee.get(r))}}async function Gp(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of Xo.getAllAgents())r.shouldHandle(n,t)&&(o.push(r.name),r.reqHandler(n,t),r.tools.size&&(n.body?.tools?.length||(n.body.tools=[]),n.body.tools.unshift(...Array.from(r.tools.values()).map(s=>({name:s.name,description:s.description,input_schema:s.input_schema})))));o.length&&(n.agents=o)}function Rl(n){return{authClient:(e,t)=>Kp(e,t,n),agent:(e,t)=>Gp(e,t,n)}}function wl(n,e){n.addHook("onRequest",async t=>{let o=new URL(`http://127.0.0.1${t.url}`);t.pathname=o.pathname,(o.pathname.endsWith("/v1/messages")||o.pathname.endsWith("/v1/responses"))&&!t.requestStartTime&&(t.requestStartTime=Ws.performance.now())}),n.addHook("preHandler",async(t,o)=>{let r=t.pathname||new URL(`http://127.0.0.1${t.url}`).pathname;r.endsWith("/v1/messages")||r.endsWith("/v1/responses")||await new Promise((s,a)=>{let i=c=>c?a(c):s();cn(e)(t,o,i).then(()=>s(),a)})}),n.addHook("onError",async(t,o,r)=>{t.errorMessage=r?.message||r?.toString?.()||"Unknown error",vl.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){Sl(t,e);let c=Ks(t),l=Zo(t);if(r instanceof ReadableStream){if(a&&t.agents){let h=new AbortController,g=r.pipeThrough(new le),m,y=-1,b="",_="",k="",T=[],x=[];return s(null,Vt(g,async(v,S)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let C=t.agents.find(P=>Xo.getAgent(P)?.tools.get(v.data.content_block.name));if(C){m=Xo.getAgent(C),y=v.data.index,b=v.data.content_block.name,k=v.data.content_block.id;return}}if(y>-1&&v.data.index===y&&v.data?.delta?.type==="input_json_delta"){_+=v.data?.delta?.partial_json;return}if(y>-1&&v.data.index===y&&v.data?.type==="content_block_stop"){try{let C=Cl.default.parse(_);x.push({type:"tool_use",id:k,name:b,input:C});let P=await m?.tools.get(b)?.handler(C,{req:t,config:e});T.push({tool_use_id:k,type:"tool_result",content:P}),m=void 0,y=-1,b="",_="",k=""}catch(C){console.log(C)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:T});let C=await fetch(`http://127.0.0.1:${e.PORT||3456}/v1/messages`,{method:"POST",headers:{"x-api-key":e.APIKEY,"content-type":"application/json"},body:JSON.stringify(t.body)});if(!C.ok)return;let N=C.body.pipeThrough(new le).getReader();for(;;)try{let{value:$,done:O}=await N.read();if(O)break;let D=$;if(["message_start","message_stop"].includes(D.event))continue;if(!S.desiredSize)break;S.enqueue(D)}catch($){if($.name==="AbortError"||$.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();break}throw $}return}return v}catch(C){if(console.error("Unexpected error in stream processing:",C),C.code==="ERR_STREAM_PREMATURE_CLOSE"){h.abort();return}throw C}}).pipeThrough(new Ze))}let[p,d]=r.tee(),f=async h=>{let m=h.pipeThrough(new TextDecoderStream).pipeThrough(new le).getReader();try{for(;;){let{done:y,value:b}=await m.read();if(y)break;let _=b.event,k=b.data;if(_==="message_start"&&_n(k?.message?.model)&&(t.upstreamModel=k.message.model),!t.upstreamModel&&_n(k?.response?.model)&&(t.upstreamModel=k.response.model),_==="response.completed"&&_n(k?.response?.model)&&(t.upstreamModel=k.response.model),k?.usage){let T=ee.get(l)||{},x=Ie(k.usage),v=Me(T,x,_==="message_start");t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_anthropic_sse",event:_,provider:t.provider,model:et(t),usageSessionId:c,capturedUsage:x,mergedUsage:v}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),ee.put(l,v)}if(k?.response?.usage){let T=Ie(k.response.usage),x=ee.get(l)||{},v=Me(x,T,!1);t.log?.info?.({debug_log:!0,reqId:t.id,phase:"usage_capture_responses_sse",event:_,provider:t.provider,model:et(t),usageSessionId:c,capturedUsage:T,mergedUsage:v}),ee.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:h,value:g}=await f.read();if(h)break;let m=g.event,y=g.data;m==="message_start"&&y?.message?.model&&_n(y?.message?.model)&&(t.upstreamModel=y.message.model),m==="response.completed"&&y?.response?.model&&_n(y?.response?.model)&&(t.upstreamModel=y.response.model);let b=y?.usage??y?.response?.usage;if(b){let _=Ie(b),k=ee.get(l)||{},T=Me(k,_,m==="message_start");ee.put(l,T)}}}catch(h){h?.name!=="AbortError"&&h?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(h)})}finally{f.releaseLock()}})(),s(null,p)}let u=Wp(r);if(u?.usage&&ee.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(vl.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=>{Rr(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Rr(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async x=>{if(!x)return;let v;try{await Promise.race([x,new Promise(S=>{v=setTimeout(S,Bp)})])}finally{v&&clearTimeout(v)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=Ks(t),a=s,i=t.sessionId||s,c=o.statusCode>=400,l=c?void 0:ee.get(Zo(t)),u=$s(a),p=H(),d,f,h=t.sseError,g=h&&(h.type||h.code||h.message),m=l?.output_tokens&&l.output_tokens>0,y=c||g&&!m;if(y){d=t.errorMessage||o.errorMessage||t.error?.message||t.error?.toString?.()||void 0,g&&(d=d||JSON.stringify(h),f=JSON.stringify(h)),f=f||t.errorResponseBody;let x=et(t);Jp(o.statusCode,d)?p.markRateLimited(t.provider||"",x,120,d):p.recordFailure(t.provider||"",x,d)}else{let x=et(t);p.recordSuccess(t.provider||"",x)}let b=l?.cache_read_input_tokens??0,k=l?.input_tokens||0||t.tokenCount||0;!l?.usage_estimated&&!b&&t.tokenCount&&l?.input_tokens&&l.input_tokens<t.tokenCount&&(b=t.tokenCount-l.input_tokens,b&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:l.input_tokens,impliedCache:b}));let T=y?0:l?.output_tokens||0;!y&&t.body?.stream&&k===0&&T===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model:et(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."}),mn({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:et(t),upstreamModel:t.upstreamModel||et(t)||void 0,...l?.usage_estimated===!0?{usageEstimated:!0}:{},modelFamily:t.modelFamily||"",scenarioType:t.scenarioType||"default",clientType:t.clientType||We(t),stream:t.body?.stream??!1,inputTokens:k,outputTokens:T,cacheReadInputTokens:b,cacheCreationInputTokens:l?.cache_creation_input_tokens||0,ttft:y||!t.body?.stream?null:u.ttft,tokensPerSecond:y?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Ws.performance.now()-t.requestStartTime):0,status:y?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&ee.delete(Zo(t))}catch(r){console.error("Usage tracking error:",r)}})}var xl,Ws,Cl,Bp,vl,Pl=w(()=>{"use strict";xl=require("node:events"),Ws=require("node:perf_hooks"),Cl=q(require("json5"),1);ft();jn();Un();de();ds();ps();fs();hn();to();Tl();Os();Zn();Bp=1500;vl=new xl.EventEmitter});var Il={};kn(Il,{createCcrServer:()=>Vp});async function Vp(n={}){await Jc(),await nn();let e=await Ho();(0,Pe.ensureCcrSelfProvider)(e).changed&&(await me(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;kc();let c=f=>(f>9?"":"0")+f,l=(f,h)=>{let g;f?typeof f=="number"?g=new Date(f):g=f:g=new Date;let m=g.getFullYear()+""+c(g.getMonth()+1),y=c(g.getDate()),b=c(g.getHours()),_=c(g.getMinutes());return`./logs/ccr-${m}${y}${b}${_}${c(g.getSeconds())}${h?`_${h}`:""}.log`},u;n.logger!==void 0?u=n.logger:(Qc(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:(0,Ol.createStream)(l,{path:Pe.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await(0,Pe.listPresets)(),d=new Gs({jsonPath:Pe.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:(0,Al.join)((0,El.homedir)(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await nl({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&&Rt(d,e,d.app.log),await gl(d,e),d.recordUsage=y=>{try{let b=y.req?y.req.clientType||We(y.req):"unknown";mn({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)}},wl(d,e),d.ccrPreHandlerCallbacks=Rl(e),(await Promise.allSettled(p.map(async y=>await d.registerNamespace(`/preset/${y.name}`,y.config)))).forEach((y,b)=>{if(y.status==="rejected"){let _=p[b],k=y.reason instanceof Error?y.reason.message:String(y.reason);d.app?.log?.error?.(`Failed to register preset "${_?.name}": ${k}`)}}),await Xc(d,e),xt(e,d.app?.log);let g=y=>{d.app.log.error({err:y},"Uncaught exception")},m=(y,b)=>{d.app.log.error({reason:y,promise:b},"Unhandled rejection")};return process.on("uncaughtException",g),process.on("unhandledRejection",m),d.app.addHook("onClose",async()=>{process.off("uncaughtException",g),process.off("unhandledRejection",m)}),d}catch(f){throw d.pluginRegistry.dispose(),await d.app.close().catch(()=>{}),f}}var El,Al,Ol,Pe,Ml=w(()=>{"use strict";El=require("os"),Al=require("path");Ll();Ol=require("rotating-file-stream"),Pe=require("@wengine-ai/claude-code-router-shared");Wc();rn();Yc();ks();Zc();hl();Hs();Go();Pl();an();hn();ft()});var Xp={};kn(Xp,{ActiveProbeService:()=>Gt,ConfigService:()=>He,ProjectRoutingError:()=>se,ProviderHealthStore:()=>It,ProviderService:()=>Ve,SSEParserTransform:()=>le,SSESerializerTransform:()=>Ze,TokenizerService:()=>Ye,TransformerService:()=>Qe,apiKeyAuth:()=>cn,applyClientAdapter:()=>Ae,backupConfigFile:()=>on,builtinClientAdapterRegistry:()=>Lr,calculateTokenCount:()=>Ut,clearClientAdapterCaches:()=>Xi,clearProviderHealth:()=>sn,closeProxyDispatchers:()=>xn,collectReachableModelKeys:()=>Es,createCcrServer:()=>Fl,default:()=>Gs,detectClientType:()=>We,diagnoseResolutionFailure:()=>Fr,extractSessionIdFromUserId:()=>Re,getActiveProbeService:()=>ls,getAllQuotaResults:()=>zn,getAllRateLimitInfo:()=>Ln,getClientAdapter:()=>$r,getConfiguredProxyUrl:()=>wt,getHealthStore:()=>H,getProxyDispatcher:()=>Y,getQuotaAdapter:()=>Lo,getQuotaResult:()=>Nt,getRateLimitInfo:()=>Oi,getRuntimeDebugLog:()=>Et,getServer:()=>Yp,initConfig:()=>Ho,initDir:()=>nn,initProviderHealthPersistence:()=>Mn,initQuotaStorePersistence:()=>ct,initRateLimitPersistence:()=>st,isClientType:()=>Nr,isGlobalProxyEnabled:()=>tr,listAnthropicCompatibleModels:()=>Bo,mergeUsageCapture:()=>Me,normalizeSessionId:()=>Se,normalizeUsagePayload:()=>Ie,pluginManager:()=>kt,readConfigFile:()=>te,readConfigFileRaw:()=>vt,reconcileHealthStore:()=>xt,resetActiveProbeService:()=>$o,resolveProviderProxyUrl:()=>he,rewriteStream:()=>Vt,router:()=>Ht,searchProjectBySession:()=>Ur,sessionUsageCache:()=>ee,setRuntimeDebugLog:()=>Sn,startActiveProbe:()=>bt,stopActiveProbe:()=>No,storeQuotaResult:()=>Hn,tokenSpeedPlugin:()=>en,usageStore:()=>Fs,writeConfigFile:()=>me});module.exports=Ys(Xp);function Qp(n={}){let e=(0,Nl.default)({bodyLimit:52428800,...n});return e.setErrorHandler(ri),e.register($l.default),e}async function Fl(n={}){return(await Promise.resolve().then(()=>(Ml(),Il))).createCcrServer(n)}var Nl,$l,Vs,Gs,Yp,Ll=w(()=>{Nl=q(require("fastify"),1),$l=q(require("@fastify/cors"),1);or();Cn();Zn();Dr();Kr();Gr();Ge();jn();Fo();de();Je();lt();ae();ft();Zn();An();ut();ft();Ge();or();Dr();Kr();Gr();Ss();ms();de();Je();is();lt();de();Fo();At();ae();rn();to();an();As();Os();hn();Vs=class{app;pluginRegistry=new Ot;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=Qp({...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 He(l),this.transformerService=new Qe(this.configService,this.app.log),this.tokenizerService=new Ye(this.configService,this.app.log);let u=this.transformerService;this.readiness=(async()=>{await Promise.all([this.transformerService.initialize(),this.tokenizerService.initialize()]),this.pluginRegistry.attachTransformerService(u),this.providerService=new Ve(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 He({initialConfig:{...t,providers:t.Providers||t.providers}}),r=new Qe(o,this.app.log),a=new Ye(o,this.app.log),await Promise.all([r.initialize(),a.initialize()]),this.pluginRegistry.attachTransformerService(r),s=new Ve(o,r,this.app.log),this.namespaceProviders.push({name:e,config:o,providers:s})}let i=async c=>{c.decorate("pluginRegistry",this.pluginRegistry),c.decorate("configService",o),c.decorate("transformerService",r),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,u)=>{let p=new URL(`http://127.0.0.1${l.url}`);l.pathname=p.pathname;let d=p.pathname.endsWith("/v1/messages"),f=p.pathname.endsWith("/v1/responses");if(!d&&!f||!l.body||typeof l.body!="object")return;let h=l.ccrHookOrder||=[];if(h.push("request-normalize"),f&&l.body.input&&!l.body.messages&&zt(l.body),l.body.stream===void 0&&(l.body.stream=!1),l.log.info({data:l.body,type:"request body"}),h.push("adapter"),!l.originalModel&&l.body.model&&(l.originalModel=l.body.model),Ae(l,o.getAll()),h.push("auth-client"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.authClient(l,u),u.sent))&&(h.push("agent"),!(this.ccrPreHandlerCallbacks&&(await this.ccrPreHandlerCallbacks.agent(l,u),u.sent)))){h.push("router"),l.body?.model&&await Ht(l,u,{configService:o,tokenizerService:a}),l.usageCacheKey&&ee.put(l.usageCacheKey,{input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),h.push("provider-model-normalize");try{let g=l.body;if(!g||!g.model)return u.code(400).send({error:"Missing model in request body"});let m=g.model.split(","),y=g.model;if(m.length>1){let[b,..._]=m;y=_.join(","),g.model=y,l.provider=b}l.model=y}catch(g){return l.log.error({error:g},"Error in modelProviderMiddleware:"),u.code(500).send({error:"Internal server error"})}}}),await fa(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 xn()})}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{st()}catch{}try{ct()}catch{}try{Mn()}catch{}try{let t={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,slowThresholdMs:Number(this.configService.get("PROBE_SLOW_THRESHOLD_MS"))||3e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=bt(()=>this.providerService.getProviders(),t,o=>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)}}},Gs=Vs;Yp=Fl});Ll();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")Zo.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:(Zo.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}})})}},Cl=new Qs});var Vs,wl,qo,Pl=w(()=>{"use strict";Rl();Vs=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}},wl=new Vs;wl.registerAgent(Cl);qo=wl});function qp(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 Il(n,e){(!n.clientContext||!n.usageCacheKey||!n.usageSessionId)&&Ae(n,e)}function Xs(n){return n.usageSessionId||n.id}function er(n){return n.usageCacheKey||`${n.clientType||"unknown"}:request:${Xs(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 ef(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 tf(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")){Il(n,t);let r=er(n);n.clientContext?.usageScope==="session"&&(n.previousUsage=te.get(r))}}async function nf(n,e,t){if(!n.pathname?.endsWith("/v1/messages"))return;let o=[];for(let r of qo.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 Ml(n){return{authClient:(e,t)=>tf(e,t,n),agent:(e,t)=>nf(e,t,n)}}function Ll(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=Ys.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",El.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){Il(t,e);let l=Xs(t),c=er(t);if(r instanceof ReadableStream){if(a&&t.agents){let g=new AbortController,h=r.pipeThrough(new le),m,y=-1,b="",_="",k="",T=[],x=[];return s(null,Yt(h,async(v,P)=>{try{if(v.event==="content_block_start"&&v?.data?.content_block?.name){let A=t.agents.find(R=>qo.getAgent(R)?.tools.get(v.data.content_block.name));if(A){m=qo.getAgent(A),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 A=Ol.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});T.push({tool_use_id:k,type:"tool_result",content:R}),m=void 0,y=-1,b="",_="",k=""}catch(A){console.log(A)}return}if(v.event==="message_delta"&&T.length){t.body.messages.push({role:"assistant",content:x}),t.body.messages.push({role:"user",content:T});let 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 v}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"&&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(c)||{},x=Ie(k.usage),v=Me(T,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:v}),(x?.cache_read_input_tokens||x?.cache_creation_input_tokens)&&console.log("[Usage] Cache tokens:",{cache_read:x?.cache_read_input_tokens,cache_creation:x?.cache_creation_input_tokens}),te.put(c,v)}if(k?.response?.usage){let T=Ie(k.response.usage),x=te.get(c)||{},v=Me(x,T,!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:T,mergedUsage:v}),te.put(c,v)}}}catch(y){y.name==="AbortError"||y.code==="ERR_STREAM_PREMATURE_CLOSE"?console.error("Background read stream closed prematurely"):console.error("Error in background stream reading:",y)}finally{m.releaseLock()}};return t.usageCapturePromise=f(d),s(null,p)}if(r instanceof ReadableStream){let[p,d]=r.tee();return t.usageCapturePromise=(async()=>{let f=d.pipeThrough(new TextDecoderStream).pipeThrough(new 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(c)||{},T=Me(k,_,m==="message_start");te.put(c,T)}}}catch(g){g?.name!=="AbortError"&&g?.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn?.({phase:"usage_capture_plain_stream",err:String(g)})}finally{f.releaseLock()}})(),s(null,p)}let u=ef(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(El.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=>{Pr(t)}),n.addHook("onResponse",async(t,o)=>{if((t.ccrHookOrder||=[]).push("onResponse"),Pr(t),!(!t.pathname?.endsWith("/v1/messages")&&!t.pathname?.endsWith("/v1/responses")))try{let r=async v=>{if(!v)return;let P;try{await Promise.race([v,new Promise(A=>{P=setTimeout(A,Zp)})])}finally{P&&clearTimeout(P)}};await r(t.usageCapturePromise),await r(t.tokenSpeedCapturePromise);let s=Xs(t),a=s,i=t.sessionId||s,l=o.statusCode>=400,c=l?void 0:te.get(er(t)),u=Hs(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 v=tt(t);qp(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 _=c?.cache_read_input_tokens??0,T=c?.input_tokens||0||t.tokenCount||0;!c?.usage_estimated&&!_&&t.tokenCount&&c?.input_tokens&&c.input_tokens<t.tokenCount&&(_=t.tokenCount-c.input_tokens,_&&console.log("[Usage] Inferred cache tokens:",{tokenCount:t.tokenCount,netInput:c.input_tokens,impliedCache:_}));let x=b?0:c?.output_tokens||0;!b&&t.body?.stream&&T===0&&x===0&&t.log?.warn?.({debug_log:!0,reqId:t.id,phase:"usage_zero_stream",provider:t.provider,originalModel:t.originalModel||t.body?.model||"",model: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:T,outputTokens:x,cacheReadInputTokens:_,cacheCreationInputTokens:c?.cache_creation_input_tokens||0,ttft:b||!t.body?.stream?null:u.ttft,tokensPerSecond:b?null:u.tokensPerSecond,durationMs:t.requestStartTime?Math.round(Ys.performance.now()-t.requestStartTime):0,status:b?"error":"success",errorMessage:d,responseBody:f}),t.clientContext?.usageScope!=="session"&&te.delete(er(t))}catch(r){console.error("Usage tracking error:",r)}})}var Al,Ys,Ol,Zp,El,$l=w(()=>{"use strict";Al=require("node:events"),Ys=require("node:perf_hooks"),Ol=ee(require("json5"),1);mt();zn();jn();ue();hs();ys();_s();_n();to();Pl();Ns();Zn();Zp=1500;El=new Al.EventEmitter});var Fl={};vn(Fl,{createCcrServer:()=>of});async function of(n={}){await Xc(),await rn();let e=await Bo();(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;wc();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:(nl(),e.LOG!==!1?(e.LOG===void 0&&(e.LOG=!0),u={level:e.LOG_LEVEL||"error",stream:(0,Dl.createStream)(c,{path:Pe.HOME_DIR,interval:"1d",size:"50M",compress:!1})}):u=!1);let p=await(0,Pe.listPresets)(),d=new Zs({jsonPath:Pe.CONFIG_FILE,initialConfig:{providers:e.Providers||e.providers,HOST:s,PORT:i,LOG_FILE:(0,Ul.join)((0,Nl.homedir)(),".claude-code-router","claude-code-router.log")},logger:u});try{await d.ready();let f=await ll({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 vl(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)}},Ll(d,e),d.ccrPreHandlerCallbacks=Ml(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 rl(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 Nl,Ul,Dl,Pe,jl=w(()=>{"use strict";Nl=require("os"),Ul=require("path");Hl();Dl=require("rotating-file-stream"),Pe=require("@wengine-ai/claude-code-router-shared");Zc();an();ol();Cs();sl();xl();Ks();Vo();$l();ln();_n();mt()});var af={};vn(af,{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:()=>Nr,calculateTokenCount:()=>jt,clearClientAdapterCaches:()=>na,clearProviderHealth:()=>cn,closeProxyDispatchers:()=>Cn,collectReachableModelKeys:()=>Ls,createCcrServer:()=>Jl,default:()=>Zs,detectClientType:()=>Ge,diagnoseResolutionFailure:()=>Fr,extractSessionIdFromUserId:()=>Re,getActiveProbeService:()=>ms,getAllQuotaResults:()=>Bn,getAllRateLimitInfo:()=>Nn,getClientAdapter:()=>Dr,getConfiguredProxyUrl:()=>Et,getHealthStore:()=>z,getProxyDispatcher:()=>X,getQuotaAdapter:()=>$o,getQuotaResult:()=>Ut,getRateLimitInfo:()=>Ni,getRuntimeDebugLog:()=>Ot,getServer:()=>sf,initConfig:()=>Bo,initDir:()=>rn,initProviderHealthPersistence:()=>$n,initQuotaStorePersistence:()=>ut,initRateLimitPersistence:()=>it,isClientType:()=>Ur,isGlobalProxyEnabled:()=>or,listAnthropicCompatibleModels:()=>Wo,mergeUsageCapture:()=>Me,normalizeSessionId:()=>Ce,normalizeUsagePayload:()=>Ie,pluginManager:()=>vt,readConfigFile:()=>ne,readConfigFileRaw:()=>St,reconcileHealthStore:()=>Ct,resetActiveProbeService:()=>Do,resolveProviderProxyUrl:()=>he,rewriteStream:()=>Yt,router:()=>Bt,searchProjectBySession:()=>jr,sessionUsageCache:()=>te,setRuntimeDebugLog:()=>wn,startActiveProbe:()=>Tt,stopActiveProbe:()=>Uo,storeQuotaResult:()=>lt,tokenSpeedPlugin:()=>nn,usageStore:()=>zs,writeConfigFile:()=>fe});module.exports=ti(af);function rf(n={}){let e=(0,zl.default)({bodyLimit:52428800,...n});return e.setErrorHandler(li),e.register(Bl.default),e}async function Jl(n={}){return(await Promise.resolve().then(()=>(jl(),Fl))).createCcrServer(n)}var zl,Bl,qs,Zs,sf,Hl=w(()=>{zl=ee(require("fastify"),1),Bl=ee(require("@fastify/cors"),1);sr();Rn();Zn();Hr();Yr();Xr();Ve();zn();Fo();ue();We();Ke();ae();mt();Zn();In();dt();mt();Ve();sr();Hr();Yr();Xr();As();bs();ue();We();us();Ke();ue();Fo();It();ae();an();to();ln();$s();Ns();_n();qs=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=rf({...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 _a(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{Uo()}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)}}},Zs=qs;sf=Jl});Hl();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
|