@wengine-ai/llms 2.3.2391 → 2.3.2392
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 +1 -1
- package/dist/cjs/server.cjs +1 -1
- package/dist/cjs/server.cjs.map +2 -2
- package/dist/esm/server.mjs +1 -1
- package/dist/esm/server.mjs.map +2 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -93,7 +93,7 @@ npm install -g @wengine-ai/claude-code-router-next@latest && ccr restart
|
|
|
93
93
|
|
|
94
94
|
| 版本 | 发布内容 |
|
|
95
95
|
| --- | --- |
|
|
96
|
-
| **v2.3.
|
|
96
|
+
| **v2.3.2392** | <ul><li>**用量按日统计按本地时区分组**: `byDay` 此前取 UTC 日期,本地 0:00–8:00 的请求(UTC 仍是昨天)被归到前一天——表现为「过了零点后昨天的消耗还在涨、今天的偏少」;改用 `date(timestamp,'localtime')` 按进程时区分组,历史记录无需迁移即自动重新归类。</li></ul> |
|
|
97
97
|
| **v2.3.239** | <ul><li>**供应商慢网探测与黄色 ⚠️ 告警**: 后台对每个供应商的 `/models` 可达性探测现在记录延迟,超过 `PROBE_SLOW_THRESHOLD_MS`(默认 3000ms)在 provider 卡片显示黄色 ⚠️;`GET /api/providers/health` 追加 `probes`,手动探测返回 latency/status/isSlow。慢但成功不开熔断,仅作 UI 提示。</li><li>**用量汇总改 SQL 聚合,UI 不再随机卡顿**: `/api/providers/quota`、`/api/usage` 的 summary 此前 `SELECT *` 全量物化 + JS 聚合阻塞 event loop,是 health/quota 随机卡顿的共享根因;改为 SQL `COUNT/SUM/AVG/GROUP BY`,语义不变。</li><li>**UI 刷新循环重做,杜绝请求重叠**: Providers health/quota 改 60s 自调度 single-flight;Usage 改 30s 串行队列(上一个未返回下一个顺延);`/api/clients` 仅 mount 刷新(操作后复用响应、不再 visibility 补拉);页面隐藏时暂停。</li><li>**Image 路由根因修复**: image agent 此前在路由前改写 `req.body.model`,导致用量记录丢失客户端真实模型(如 ccr-opus)并绕过 family image 路由;现按客户端原始模型识别 family 路由图片。同时修复 `promoteToolResultImages` 把所有数组型 tool_result 内容替换为占位符、丢失文本/结构化内容的问题。</li><li>**移除已弃用的 Codex 多账号管理**: 删除账号列表、切换、后台自动维护及对应 API/CLI/UI;Codex 仍作为普通 provider/client 完整支持(检测、`/v1/responses`、transformer、takeover、用量归属),历史账号文件与 `~/.codex/auth.json` 保持不动。</li><li>**路由优先级:模型族优先于 explicit `provider,model`**: 开启 family routing 时请求先走模型族映射,命中即用;family 未命中才解析客户端显式指定,最后落默认路由。</li></ul> |
|
|
98
98
|
| **v2.3.238** | <ul><li>**更新成功后服务自动重启**: 修复 `performUpdate` 跑完 `npm install -g` 只返回“请手动重启”、从不真正重启的问题;现在成功后复用 `/api/restart` 的自重启模式自动重启服务,前端轮询 `checkForUpdates` 返回 `hasUpdate:false` 后自动刷新页面加载新前端。</li><li>**更新请求并发锁**: 新增模块级 `updateInProgress` 守卫,刷新页面丢失 UI 状态后再次点击“立即更新”不会再触发第二次 `npm install -g`。</li><li>**超时文案补全包名**: `app.update_timeout` 改为“手动执行 `npm install -g @wengine-ai/claude-code-router-next@latest`”,照抄即可成功。</li></ul> |
|
|
99
99
|
| **v2.3.237** | <ul><li>**更新操作显示进度并限制等待时间**: 点击“立即更新”后禁用弹窗按钮并显示“更新中…”状态,避免重复安装;前端请求与后端 `npm install -g` 均设置 5 分钟超时,后端输出缓冲提高到 4 MB,超时会显示可读错误而非永久挂起。</li><li>**精简 Claude 项目指引**: 删除可由 manifests、CLI help 和仓库结构直接推导的常驻说明,保留非显然的安全、发布与架构约束,减少每次会话的固定上下文开销。</li></ul> |
|
package/dist/cjs/server.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";var Pa=Object.create;var Wt=Object.defineProperty;var Ea=Object.getOwnPropertyDescriptor;var Oa=Object.getOwnPropertyNames;var Aa=Object.getPrototypeOf,Ia=Object.prototype.hasOwnProperty;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var Gt=(n,e)=>{for(var t in e)Wt(n,t,{get:e[t],enumerable:!0})},Mr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Oa(e))!Ia.call(n,r)&&r!==t&&Wt(n,r,{get:()=>e[r],enumerable:!(o=Ea(e,r))||o.enumerable});return n};var Y=(n,e,t)=>(t=n!=null?Pa(Aa(n)):{},Mr(e||!n||!n.__esModule?Wt(t,"default",{value:n,enumerable:!0}):t,n)),$r=n=>Mr(Wt({},"__esModule",{value:!0}),n);function $a(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(Ma.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 Dr(n){let e=[];for(let t of Lr){let o=n[t];if(o==null)continue;let r=$a(o);r.ok||e.push({key:t,error:r.error})}return e}function st(n){for(let e of Lr){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function ao(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 le(n,e){let t=st(n);if(t)return ao(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function Q(n){let e=Na(n),t=Kt.get(e);if(t)return t;let o=new Nr.ProxyAgent(e);return Kt.set(e,o),o}async function Qt(){let n=Array.from(Kt.values());Kt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function Na(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 Nr,Lr,Ma,Kt,se=w(()=>{"use strict";Nr=require("undici"),Lr=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],Ma=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Kt=new Map});var it,co,Fr,Ur,ve,lo=w(()=>{"use strict";it=require("fs"),co=require("path"),Fr=require("dotenv"),Ur=Y(require("json5"),1);se();ve=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,co.join)(process.cwd(),this.options.jsonPath);if((0,it.existsSync)(e))try{let t=(0,it.readFileSync)(e,"utf-8"),o=Ur.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,co.join)(process.cwd(),this.options.envPath);if((0,it.existsSync)(e))try{let t=(0,Fr.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 st(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 G(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 jr(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 Vt=w(()=>{"use strict"});function Yt(n){uo=n}function at(){return uo}function Xt(n){return uo||n.get("DEBUG_LOG")===!0}function Br(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Le:{maxBodyLength:e.maxBodyLength??Le.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Le.maxStreamChunks}}function qt(n){let e={};for(let[t,o]of Object.entries(n))La.has(t.toLowerCase())?e[t]="***MASKED***":e[t]=o;return e}function Zt(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Jr(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:qt(t.headers),body:Zt(o,Le.maxBodyLength)})}function Wr(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:qt(t.headers),...t.body!==void 0?{body:Zt(t.body,Le.maxBodyLength)}:{}})}function Hr(n,e,t,o){let r=Da(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:Zt(o,Le.maxBodyLength)})}function Da(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:Zt(o,512)})}}if(e.length)return e.length===1?e[0]:e}function zr(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function Gr(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let i="";for(;;){let{done:l,value:a}=await r.read();if(l)break;i+=a;let c=i.split(`
|
|
2
2
|
|
|
3
|
-
`);i=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Hr(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++)}i.trim()&&(s<o.maxStreamChunks&&Hr(e,t,s,i.trim()),s++),zr(e,t,s)}catch(i){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,i),zr(e,t,s)}finally{r.releaseLock()}})()}var La,Le,uo,ct=w(()=>{"use strict";La=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Le={maxBodyLength:4096,maxStreamChunks:100},uo=!1});function Kr(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 i,l=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),l.addEventListener("abort",u),i=c.signal}else i=l;let a={method:"POST",headers:s,body:JSON.stringify(e),signal:i};return t.httpsProxy&&(a.dispatcher=Q(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:qt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Fa(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),a)}function Fa(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 Qr=w(()=>{se();ct()});var en,po=w(()=>{en="2.3.239"});var Vr={};Gt(Vr,{getFallbackPromotionStore:()=>De,resetFallbackPromotionStore:()=>Ha});function De(n){return xe||(xe=new fo,n&&xe.configure(n)),xe}function Ha(){xe&&(xe.clearAll(),xe=null)}var ja,fo,xe,tn=w(()=>{"use strict";ie();ja=600*1e3,fo=class{promotions=new Map;enabled=!0;ttlMs=ja;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,i){if(!this.enabled)return;let l=this.getKey(e,t,o),a=`${r},${s}`;this.promotions.set(l,{promotedModel:a,timestamp:Date.now(),ttlMs:i??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),i=this.promotions.get(s);if(!i)return null;if(Date.now()-i.timestamp>=i.ttlMs)return this.promotions.delete(s),null;let[a,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(a,u))return this.promotions.delete(s),null;let g=r.find(y=>y.name.toLowerCase()===a.toLowerCase()),m=g?.models?.find(y=>String(y).toLowerCase()===u.toLowerCase());return!g||!m||g.enabled===!1?(this.promotions.delete(s),null):`${g.name},${m}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});function Wa(n){try{if(!(0,pe.existsSync)(ho))return;let e=JSON.parse((0,pe.readFileSync)(ho,"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 Xr(n){try{let e=n.getAllStates();if(e.length===0)return;(0,pe.existsSync)(go)||(0,pe.mkdirSync)(go,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,pe.writeFileSync)(ho,JSON.stringify(t,null,2),"utf-8")}catch{}}function nn(){if(Yr)return;Yr=!0;let n=U();Wa(n),Ja=setInterval(()=>Xr(n),6e4),process.on("exit",()=>Xr(n))}function U(n){return mo||(mo=new lt(n)),mo}var pe,yo,qr,za,Ba,lt,go,ho,Yr,Ja,mo,ie=w(()=>{"use strict";pe=require("fs"),yo=require("path"),qr=require("@wengine-ai/claude-code-router-shared"),za=120,Ba={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},lt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ba,...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);r&&(r.successCount++,!r.rateLimitUntil&&(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)))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(tn(),$r(Vr));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){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let r=this.getState(e,t);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.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}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 i=this.states.get(s);i?(i.status="open",i.lastFailureTime=Date.now(),i.lastError=r||"rate-limited",i.lastProbeTime=0):(i={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,i));let l=(o??za)*1e3;i.rateLimitUntil=Date.now()+l}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)}},go=(0,yo.join)(qr.HOME_DIR,"runtime"),ho=(0,yo.join)(go,"provider-health.json"),Yr=!1,Ja=null;mo=null});function ut(n,e,t){let o=l=>{if(t instanceof Headers)return t.get(l);let a=Object.keys(t).find(c=>c.toLowerCase()===l);return a?t[a]:null},r=_o(o,Ga),s=_o(o,Ka),i=_o(o,Qa);(r||s||i)&&Fe.set(n,{provider:n,remaining:ts(r),limit:ts(s),reset:Va(i),capturedAt:Date.now()})}function rs(n){return Fe.get(n)}function on(){return Array.from(Fe.values())}function _o(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ts(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Va(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=Ya(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Ya(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]),i=r[2].toLowerCase();if(Number.isFinite(s))switch(i){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 Xa(){try{if(!(0,fe.existsSync)(bo))return;let n=JSON.parse((0,fe.readFileSync)(bo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Fe.set(t.provider,t)}}catch{}}function ns(){try{if(Fe.size===0)return;(0,fe.existsSync)(ko)||(0,fe.mkdirSync)(ko,{recursive:!0}),(0,fe.writeFileSync)(bo,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function Ue(){Zr||(Zr=!0,Xa(),es=setInterval(ns,6e4),es.unref?.(),process.on("exit",ns))}var fe,To,os,ko,bo,Fe,Zr,es,Ga,Ka,Qa,je=w(()=>{"use strict";fe=require("fs"),To=require("path"),os=require("@wengine-ai/claude-code-router-shared"),ko=(0,To.join)(os.HOME_DIR,"runtime"),bo=(0,To.join)(ko,"rate-limit.json"),Fe=new Map,Zr=!1,es=null,Ga=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Ka=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Qa=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var He,Co=w(()=>{"use strict";He=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 i="";typeof s=="string"?i=s:s&&typeof s=="object"&&"text"in s&&(i=s.text),t.push({role:"system",content:i})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(i=>this.normalizeRequestContent(i,r.role)).filter(i=>i!==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){let t=e.headers.get("Content-Type")||"";if(t.includes("application/json")){let o=await e.json();if(o.object==="response"&&o.output){let r=this.convertResponseToChat(o);return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return o.type==="message"&&Array.isArray(o.content)?new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let[o,r]=e.body.tee(),s=o.getReader(),i="";try{let{value:f,done:_}=await s.read();!_&&f&&(i=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let c=this.prependToStream(i,r),u=new TextDecoder,d=new TextEncoder,g="",m=!1,y=this,p=new ReadableStream({async start(f){let _=c.getReader(),k=-1,h="",b=T=>(T!==h&&(k++,h=T),k);try{for(;;){let{done:T,value:x}=await _.read();if(T){m||f.enqueue(d.encode(`data: [DONE]
|
|
3
|
+
`);i=c.pop()||"";for(let u of c)u.trim()&&(s<o.maxStreamChunks?Hr(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++)}i.trim()&&(s<o.maxStreamChunks&&Hr(e,t,s,i.trim()),s++),zr(e,t,s)}catch(i){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,i),zr(e,t,s)}finally{r.releaseLock()}})()}var La,Le,uo,ct=w(()=>{"use strict";La=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Le={maxBodyLength:4096,maxStreamChunks:100},uo=!1});function Kr(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 i,l=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let c=new AbortController,u=()=>c.abort();t.signal.addEventListener("abort",u),l.addEventListener("abort",u),i=c.signal}else i=l;let a={method:"POST",headers:s,body:JSON.stringify(e),signal:i};return t.httpsProxy&&(a.dispatcher=Q(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:qt(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:Fa(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),a)}function Fa(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 Qr=w(()=>{se();ct()});var en,po=w(()=>{en="2.3.2392"});var Vr={};Gt(Vr,{getFallbackPromotionStore:()=>De,resetFallbackPromotionStore:()=>Ha});function De(n){return xe||(xe=new fo,n&&xe.configure(n)),xe}function Ha(){xe&&(xe.clearAll(),xe=null)}var ja,fo,xe,tn=w(()=>{"use strict";ie();ja=600*1e3,fo=class{promotions=new Map;enabled=!0;ttlMs=ja;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,i){if(!this.enabled)return;let l=this.getKey(e,t,o),a=`${r},${s}`;this.promotions.set(l,{promotedModel:a,timestamp:Date.now(),ttlMs:i??this.ttlMs})}getPromotion(e,t,o,r){if(!this.enabled)return null;let s=this.getKey(e,t,o),i=this.promotions.get(s);if(!i)return null;if(Date.now()-i.timestamp>=i.ttlMs)return this.promotions.delete(s),null;let[a,...c]=i.promotedModel.split(","),u=c.join(",");if(!U().isAvailable(a,u))return this.promotions.delete(s),null;let g=r.find(y=>y.name.toLowerCase()===a.toLowerCase()),m=g?.models?.find(y=>String(y).toLowerCase()===u.toLowerCase());return!g||!m||g.enabled===!1?(this.promotions.delete(s),null):`${g.name},${m}`}clear(e,t,o){let r=this.getKey(e,t,o);this.promotions.delete(r)}clearByPrimary(e,t){let o=`${e},${t}:`,r=0;for(let s of this.promotions.keys())s.startsWith(o)&&(this.promotions.delete(s),r++);return r}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[t,o]of this.promotions)e-o.timestamp>=o.ttlMs&&this.promotions.delete(t)}getAllPromotions(){let e=Date.now(),t=[];for(let[o,r]of this.promotions){let s=r.ttlMs-(e-r.timestamp);s>0&&t.push({key:o,promotedModel:r.promotedModel,remainingMs:s})}return t}},xe=null});function Wa(n){try{if(!(0,pe.existsSync)(ho))return;let e=JSON.parse((0,pe.readFileSync)(ho,"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 Xr(n){try{let e=n.getAllStates();if(e.length===0)return;(0,pe.existsSync)(go)||(0,pe.mkdirSync)(go,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,pe.writeFileSync)(ho,JSON.stringify(t,null,2),"utf-8")}catch{}}function nn(){if(Yr)return;Yr=!0;let n=U();Wa(n),Ja=setInterval(()=>Xr(n),6e4),process.on("exit",()=>Xr(n))}function U(n){return mo||(mo=new lt(n)),mo}var pe,yo,qr,za,Ba,lt,go,ho,Yr,Ja,mo,ie=w(()=>{"use strict";pe=require("fs"),yo=require("path"),qr=require("@wengine-ai/claude-code-router-shared"),za=120,Ba={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},lt=class{states=new Map;config;probeTimer;constructor(e){this.config={...Ba,...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);r&&(r.successCount++,!r.rateLimitUntil&&(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)))}clearPromotionsForPrimary(e,t){try{let{getFallbackPromotionStore:o}=(tn(),$r(Vr));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){if(!this.config.enabled)return!0;if(!this.getKey(e,t))return!1;let r=this.getState(e,t);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.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}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 i=this.states.get(s);i?(i.status="open",i.lastFailureTime=Date.now(),i.lastError=r||"rate-limited",i.lastProbeTime=0):(i={provider:e,model:t,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r||"rate-limited"},this.states.set(s,i));let l=(o??za)*1e3;i.rateLimitUntil=Date.now()+l}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)}},go=(0,yo.join)(qr.HOME_DIR,"runtime"),ho=(0,yo.join)(go,"provider-health.json"),Yr=!1,Ja=null;mo=null});function ut(n,e,t){let o=l=>{if(t instanceof Headers)return t.get(l);let a=Object.keys(t).find(c=>c.toLowerCase()===l);return a?t[a]:null},r=_o(o,Ga),s=_o(o,Ka),i=_o(o,Qa);(r||s||i)&&Fe.set(n,{provider:n,remaining:ts(r),limit:ts(s),reset:Va(i),capturedAt:Date.now()})}function rs(n){return Fe.get(n)}function on(){return Array.from(Fe.values())}function _o(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function ts(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Va(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=Ya(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function Ya(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]),i=r[2].toLowerCase();if(Number.isFinite(s))switch(i){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 Xa(){try{if(!(0,fe.existsSync)(bo))return;let n=JSON.parse((0,fe.readFileSync)(bo,"utf-8"));if(!Array.isArray(n))return;let e=Date.now();for(let t of n)if(t&&t.provider){if(t.capturedAt&&e-t.capturedAt>3600*1e3)continue;Fe.set(t.provider,t)}}catch{}}function ns(){try{if(Fe.size===0)return;(0,fe.existsSync)(ko)||(0,fe.mkdirSync)(ko,{recursive:!0}),(0,fe.writeFileSync)(bo,JSON.stringify(Array.from(Fe.values()),null,2),"utf-8")}catch{}}function Ue(){Zr||(Zr=!0,Xa(),es=setInterval(ns,6e4),es.unref?.(),process.on("exit",ns))}var fe,To,os,ko,bo,Fe,Zr,es,Ga,Ka,Qa,je=w(()=>{"use strict";fe=require("fs"),To=require("path"),os=require("@wengine-ai/claude-code-router-shared"),ko=(0,To.join)(os.HOME_DIR,"runtime"),bo=(0,To.join)(ko,"rate-limit.json"),Fe=new Map,Zr=!1,es=null,Ga=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Ka=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Qa=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var He,Co=w(()=>{"use strict";He=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 i="";typeof s=="string"?i=s:s&&typeof s=="object"&&"text"in s&&(i=s.text),t.push({role:"system",content:i})}):e.instructions=r.content}if(e.messages.forEach(r=>{if(r.role!=="system"){if(Array.isArray(r.content)){let s=r.content.map(i=>this.normalizeRequestContent(i,r.role)).filter(i=>i!==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){let t=e.headers.get("Content-Type")||"";if(t.includes("application/json")){let o=await e.json();if(o.object==="response"&&o.output){let r=this.convertResponseToChat(o);return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}return o.type==="message"&&Array.isArray(o.content)?new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(t.includes("text/event-stream")){if(!e.body)return e;let[o,r]=e.body.tee(),s=o.getReader(),i="";try{let{value:f,done:_}=await s.read();!_&&f&&(i=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),i.includes("message_start")||i.includes("content_block_start")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(i.includes("response.created")||i.includes("response.output_text.delta")||i.includes("response.in_progress")||i.includes("response.output_item.added")){let f=this.prependToStream(i,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let c=this.prependToStream(i,r),u=new TextDecoder,d=new TextEncoder,g="",m=!1,y=this,p=new ReadableStream({async start(f){let _=c.getReader(),k=-1,h="",b=T=>(T!==h&&(k++,h=T),k);try{for(;;){let{done:T,value:x}=await _.read();if(T){m||f.enqueue(d.encode(`data: [DONE]
|
|
4
4
|
|
|
5
5
|
`));break}let v=u.decode(x,{stream:!0});g+=v;let S=g.split(/\r?\n/);g=S.pop()||"";for(let C of S)if(C.trim())try{if(C.startsWith("event: "))continue;if(C.startsWith("data: ")){let P=C.slice(5).trim();if(P==="[DONE]"){m=!0,f.enqueue(d.encode(`data: [DONE]
|
|
6
6
|
|