@wengine-ai/llms 2.3.236 → 2.3.237

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 CHANGED
@@ -93,6 +93,7 @@ npm install -g @wengine-ai/claude-code-router-next@latest && ccr restart
93
93
 
94
94
  | 版本 | 发布内容 |
95
95
  | --- | --- |
96
+ | **v2.3.237** | <ul><li>**更新操作显示进度并限制等待时间**: 点击“立即更新”后禁用弹窗按钮并显示“更新中…”状态,避免重复安装;前端请求与后端 `npm install -g` 均设置 5 分钟超时,后端输出缓冲提高到 4 MB,超时会显示可读错误而非永久挂起。</li><li>**精简 Claude 项目指引**: 删除可由 manifests、CLI help 和仓库结构直接推导的常驻说明,保留非显然的安全、发布与架构约束,减少每次会话的固定上下文开销。</li></ul> |
96
97
  | **v2.3.236** | <ul><li>**阿里云 Token Plan 用量查询(5h/7d 额度)**: 为 `*.maas.aliyuncs.com` 网关新增专用 `AliyunTokenPlanQuotaAdapter`,走 Token Plan 专用 BroadScope 用量接口并把 `per5HourPercentage`/`per1WeekPercentage` 映射为 5h/7d 百分比展示。</li><li>**`quota_sec_token` 配置项与官方网关 + legacy 回退**: provider 可选 `quota_sec_token` 与 UI 密码输入;配置后走官方 `bailian-cs.console.aliyun.com` 网关(对齐真实控制台请求,`_v=undefined`、动态 trace、不含 spm),失败安全降级到 `cs-data` cookie-only 端点。</li><li>**pi 扩展上下文触发统一为绝对阈值**: 移除 pi 的 `extendedContextRatio`,统一走 family → Router → 200000 的绝对阈值链。</li><li>**测试 HOME 隔离真正到达 vitest worker**: 修复 core/shared 测试套件此前落在真实 `~/.claude-code-router` 的隔离失效问题。</li></ul> |
97
98
  | **v2.3.235** | <ul><li>**修复 npm 全局安装静默失败**: 此前 `@wengine-ai/llms` 发布包把运行时 shared 依赖保留为 pnpm 的 `workspace:*` 协议,npm 在解析依赖树时无法识别并 exit 1。发布流程现在先发布同版本 `@wengine-ai/claude-code-router-shared`,再把 core 中所有 `workspace:` 范围转换为真实 npm version range 后发布,最后发布 CLI;shared/core/CLI 三个发布 manifest 都新增 `workspace:` 拦截校验,防止再次发布 npm 无法安装的包。</li></ul> |
98
99
  | **v2.3.234** | <ul><li>**修复全局 ContextWindow 变更不传递到已接管项目(auto-compact 窗口冻结)**: 项目在 v2.3.22 之前被接管、或经历 disable→enable 循环导致 `ccr-state.json` 缺失时,`CLAUDE_CODE_AUTO_COMPACT_WINDOW` 会停留在旧值(如 200000);旧守门把该旧值误判为用户手写值并永久保留,之后任何全局 `ContextWindow` 变更都不再生效,UI 重开关 takeover 也无效。现在 state 缺失时重新视为 CCR-managed,写入当前全局值并重建 state,被覆盖旧值记入 `previousAutoCompactWindow` 留痕;state 存在时仍保留用户手写值不被覆盖的原保证。</li></ul> |
@@ -102,7 +103,6 @@ npm install -g @wengine-ai/claude-code-router-next@latest && ccr restart
102
103
  | **v2.3.23** | <ul><li>**修复状态栏 token 速率虚高(撞到 999 上限)**: `ccr statusline` 的 token 速率常显示几百、极端撞到 999 上限,与「用量统计」的几十 t/s 对不上。根因是 token-speed 插件流式过程中每秒上报的是「最近 1 秒到达的 token 数」滑动窗口值,而 SSE delta 常成批到达(同一时间戳)使瞬时计数虚高;现改为与用量统计同一套解码平均公式(`输出 token ÷ (总耗时 − TTFT)`)上报,速率随流式收敛到最终值、与用量统计一致,并移除失效的滑动窗口记账。</li><li>**状态栏默认改为无图标表格风格**: 默认主题不再带装饰图标,模块之间改用细竖线 `│` 分隔,呈简洁表格样式,默认模块顺序为「模型 │ 工作目录 │ git 分支 │ 上下文进度条 │ token 速率 │ 会话总 token」。动机是歧义宽度的 emoji 图标(如闪电 `⚡` U+26A1)会让 Claude Code 误算状态栏显示宽度、在双击等重绘时产生数字重影/位移;改用定宽字符或不带图标可避免。图标仍支持在 UI 中自定义。</li><li>**修复 UI 状态栏图标无法删除 + 旧圆圈模块迁移**: 切换所选模块时图标搜索框(`IconSearchInput`)不随 `value` 同步、与模块真实图标脱节导致看似删不掉,现已在 `value` 变化时同步;同时加载配置时把旧 `contextCircle` 模块迁移为 `contextBar`,配置弹窗显示长条进度条而非旧圆圈图标。</li><li>**`build:ui` 构建后同步产物到 CLI/根 dist**: `pnpm build:ui` 现会把 `index.html` 同步到 `packages/cli/dist` 与根 `dist`,使单独运行 `build:ui` 也能更新本地运行中的 ccr 实际读取的包。</li></ul> |
103
104
  | **v2.3.22** | <ul><li>**状态栏按用户配置的压缩阈值显示上下文上限**: `ccr statusline` 优先用 `CLAUDE_CODE_AUTO_COMPACT_WINDOW`(CCR 从顶层 `ContextWindow` 写入)作为上下文上限与百分比分母,未设才回退到 Claude Code 的窗口值,使状态栏与实际 auto-compact 触发点对齐,不再固定显示 1M/200k。</li><li>**接管保留用户手写的 auto-compact 自定义值**: CCR 接管 Claude Code 时不再无条件用 `ContextWindow` 覆盖 `CLAUDE_CODE_AUTO_COMPACT_WINDOW`,改用状态文件(`~/.claude-code-router/client-state.json` 全局、`<project-id>/ccr-state.json` 项目级)区分 CCR 写入值(可随 `ContextWindow` 更新)与用户手写值(保留);卸载只清自己写的、保留用户的;状态缺失时保守保留,绝不误覆盖。</li><li>**UI 上下文窗口与扩展上下文配合提示**: 顶层 `ContextWindow` > 200000 但未启用对应模型家族「扩展上下文 (1M)」(模型名带 `[1m]`)时显示红色警告,并在两处配置补充配合说明——否则 Claude Code 会将其封顶至 200000。</li><li>**修复状态栏百分比按 1M 计算与偶发闪 0%**: statusline 子进程不一定继承项目级 settings 的环境变量,导致项目里设的 `CLAUDE_CODE_AUTO_COMPACT_WINDOW` 被漏读而按 1M 计算,现在依次从 `process.env`→项目 `settings.local.json`→全局 `settings.json` 读取;另 `current_usage` 在请求进行中/刚 auto-compact 后会暂态为空使百分比偶发闪 0%,现回退到 transcript 最近一条 assistant 消息的上下文用量保持稳定。</li><li>**修复项目接管 disable→enable 循环冻结窗口与 disable 残留**: 项目级 `ccr-state.json` 在 disable 后丢失、再 enable 时不重建,导致 CCR 无法识别自己写入的窗口——既会让 `ContextWindow` 变更无法刷新生效,也会在关闭接管时把 `CLAUDE_CODE_AUTO_COMPACT_WINDOW` 当用户值残留。现在状态缺失时按「值等于当前 `ContextWindow`」兜底识别 CCR-managed,enable 重建状态、disable 清残留,真正的用户手写值仍保留。</li></ul> |
104
105
  | **v2.3.21** | <ul><li>**新增 pi (earendil-works) 客户端接管**: 新增 pi 作为第三个接管目标(与 Claude Code、Codex 并列),pi 使用 Anthropic `/v1/messages` 协议直连无需 transformer;接管会在 `~/.pi/agent` 写入 `models.json`(注册指向 ccr 代理的 `ccr` provider,暴露 `ccr-opus`/`ccr-sonnet`/`ccr-haiku` 族别名)与 `settings.json`(默认 provider/model 指向 ccr),并备份原文件,仅做配置注入不含账号管理;用量统计也会把 pi 识别为独立客户端(pi 与 Claude Code 共用 `ccr-*` 别名,靠 pi system prompt 特征 + Anthropic SDK 请求头区分)。</li><li>**项目级接管支持多客户端多选**: 「项目级配置」页「CCR 接管」从只接管 Claude Code 改为客户端多选下拉(Claude Code + pi + qwen-code + opencode),不选默认接管全部;pi 项目级接管在项目目录写 `.pi/settings.json` 指向全局 ccr provider 并在 `trust.json` 信任该目录,接管状态从各客户端项目级配置文件实时推导、自动兼容既有项目(Codex 配置全局-only 不纳入)。</li><li>**新增 qwen-code (Alibaba) 客户端接管**: 新增 qwen-code(`@qwen-code/qwen-code`)作为第四个接管目标,走 Anthropic `/v1/messages` 直连;接管在 `~/.qwen/settings.json`(用户级)/ `<项目>/.qwen/settings.json`(项目级)写入指向 ccr 的 `modelProviders.anthropic`(暴露 ccr-opus/sonnet/haiku)、备份原文件,项目级还在 `trustedFolders.json` 信任该目录。用量统计区分 qwen-code:qwen 经代理时会伪装成 Claude Code 的 `claude-cli` UA,故改用 qwen system prompt 特征(`You are Qwen Code`)正向识别、Claude Code 用 `cc_version`/`metadata.user_id` 强信号识别。</li><li>**新增 opencode (opencode.ai) 客户端接管**: 新增 opencode 作为第五个接管目标,走 Anthropic `/v1/messages` 直连;接管在 `~/.config/opencode/opencode.json`(全局)/ `<项目>/opencode.json`(项目级)注入一个 `@ai-sdk/anthropic` 的 `provider.ccr`(baseURL=`…/v1`、apiKey 内联、暴露 ccr-opus/sonnet/haiku)并设 `model: ccr/ccr-opus`,备份原文件,无需 trust。用量统计区分 opencode:其请求带 `opencode/…` UA 且不伪装,直接按 UA 识别。</li></ul> |
105
- | **v2.3.20** | <ul><li>**清理改名/删除模型后残留的僵尸熔断记录**: 从 provider 的 `models` 重命名/删除模型后(如 `ollama,glm-5.2` → `ollama,glm-5.2:cloud`),旧名字在 `provider-health.json` 中的熔断记录会成为僵尸,UI 上该供应商一直显示 `Failed`,且因状态持久化落盘 `ccr restart` 与点刷新都清不掉(probe 成功只 `recover` 当前配置的模型名)。现在新增 `health-reconcile`:服务启动、保存配置、probe 成功时分别按当前配置对账清理残留记录;「可路由」集合同时取自各 provider `models` 与 Router/fallback 引用,避免误删 `models` 为空但仅靠 Router 路由的模型(如 `阿里云 Coding Plan,glm-5`)健康状态。新增 7 个单元测试。</li></ul> |
106
106
 
107
107
  > 仅保留最近 10 个版本,更早版本的发布摘要见 [CHANGELOG-archive.md](./CHANGELOG-archive.md),完整详细变更记录见 [CHANGELOG.md](./CHANGELOG.md)。
108
108
 
@@ -1,6 +1,6 @@
1
1
  "use strict";var Xa=Object.create;var Xt=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var qa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,ec=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var Yt=(n,e)=>{for(var t in e)Xt(n,t,{get:e[t],enumerable:!0})},Hr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qa(e))!ec.call(n,r)&&r!==t&&Xt(n,r,{get:()=>e[r],enumerable:!(o=Ya(e,r))||o.enumerable});return n};var Y=(n,e,t)=>(t=n!=null?Xa(Za(n)):{},Hr(e||!n||!n.__esModule?Xt(t,"default",{value:n,enumerable:!0}):t,n)),Jr=n=>Hr(Xt({},"__esModule",{value:!0}),n);function nc(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(tc.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 Gr(n){let e=[];for(let t of Wr){let o=n[t];if(o==null)continue;let r=nc(o);r.ok||e.push({key:t,error:r.error})}return e}function ct(n){for(let e of Wr){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function go(n){if(n==null||n==="")return!0;if(typeof n=="string"){let e=n.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:!!e}return n===!1||n===0?!1:n===!0||n===1?!0:!!n}function de(n,e){let t=ct(n);if(t)return go(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function K(n){let e=oc(n),t=qt.get(e);if(t)return t;let o=new Br.ProxyAgent(e);return qt.set(e,o),o}async function Zt(){let n=Array.from(qt.values());qt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function oc(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 Br,Wr,tc,qt,ae=P(()=>{"use strict";Br=require("undici"),Wr=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],tc=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;qt=new Map});var lt,ho,Vr,Qr,Se,yo=P(()=>{"use strict";lt=require("fs"),ho=require("path"),Vr=require("dotenv"),Qr=Y(require("json5"),1);ae();Se=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,ho.join)(process.cwd(),this.options.jsonPath);if((0,lt.existsSync)(e))try{let t=(0,lt.readFileSync)(e,"utf-8"),o=Qr.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,ho.join)(process.cwd(),this.options.envPath);if((0,lt.existsSync)(e))try{let t=(0,Vr.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 ct(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 Kr(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 en=P(()=>{"use strict"});function tn(n){_o=n}function ut(){return _o}function nn(n){return _o||n.get("DEBUG_LOG")===!0}function qr(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Ue:{maxBodyLength:e.maxBodyLength??Ue.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Ue.maxStreamChunks}}function on(n){let e={};for(let[t,o]of Object.entries(n))rc.has(t.toLowerCase())?e[t]="***MASKED***":e[t]=o;return e}function rn(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function Zr(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:on(t.headers),body:rn(o,Ue.maxBodyLength)})}function es(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:on(t.headers),...t.body!==void 0?{body:rn(t.body,Ue.maxBodyLength)}:{}})}function Xr(n,e,t,o){let r=sc(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:rn(o,Ue.maxBodyLength)})}function sc(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:rn(o,512)})}}if(e.length)return e.length===1?e[0]:e}function Yr(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function ts(n,e,t,o){(async()=>{let r=n.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:l,value:c}=await r.read();if(l)break;a+=c;let i=a.split(`
2
2
 
3
- `);a=i.pop()||"";for(let u of i)u.trim()&&(s<o.maxStreamChunks?Xr(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&&Xr(e,t,s,a.trim()),s++),Yr(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Yr(e,t,s)}finally{r.releaseLock()}})()}var rc,Ue,_o,dt=P(()=>{"use strict";rc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Ue={maxBodyLength:4096,maxStreamChunks:100},_o=!1});function ns(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([i,u])=>{u&&s.set(i,u)});let a,l=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let i=new AbortController,u=()=>i.abort();t.signal.addEventListener("abort",u),l.addEventListener("abort",u),a=i.signal}else a=l;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return t.httpsProxy&&(c.dispatcher=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:on(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:ic(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function ic(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 os=P(()=>{ae();dt()});var sn,ko=P(()=>{sn="2.3.236"});var rs={};Yt(rs,{getFallbackPromotionStore:()=>De,resetFallbackPromotionStore:()=>lc});function De(n){return Pe||(Pe=new bo,n&&Pe.configure(n)),Pe}function lc(){Pe&&(Pe.clearAll(),Pe=null)}var cc,bo,Pe,an=P(()=>{"use strict";ce();cc=600*1e3,bo=class{promotions=new Map;enabled=!0;ttlMs=cc;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 l=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(l,{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,...i]=a.promotedModel.split(","),u=i.join(",");if(!D().isAvailable(c,u))return this.promotions.delete(s),null;let m=r.find(y=>y.name.toLowerCase()===c.toLowerCase()),g=m?.models?.find(y=>String(y).toLowerCase()===u.toLowerCase());return!m||!g||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${g}`}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}},Pe=null});function fc(n){try{if(!(0,ge.existsSync)(To))return;let e=JSON.parse((0,ge.readFileSync)(To,"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 is(n){try{let e=n.getAllStates();if(e.length===0)return;(0,ge.existsSync)(Co)||(0,ge.mkdirSync)(Co,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,ge.writeFileSync)(To,JSON.stringify(t,null,2),"utf-8")}catch{}}function cn(){if(ss)return;ss=!0;let n=D();fc(n),pc=setInterval(()=>is(n),6e4),process.on("exit",()=>is(n))}function D(n){return xo||(xo=new pt(n)),xo}var ge,vo,as,uc,dc,pt,Co,To,ss,pc,xo,ce=P(()=>{"use strict";ge=require("fs"),vo=require("path"),as=require("@wengine-ai/claude-code-router-shared"),uc=120,dc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},pt=class{states=new Map;config;probeTimer;constructor(e){this.config={...dc,...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}=(an(),Jr(rs));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 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 l=(o??uc)*1e3;a.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)}},Co=(0,vo.join)(as.HOME_DIR,"runtime"),To=(0,vo.join)(Co,"provider-health.json"),ss=!1,pc=null;xo=null});function ft(n,e,t){let o=l=>{if(t instanceof Headers)return t.get(l);let c=Object.keys(t).find(i=>i.toLowerCase()===l);return c?t[c]:null},r=Ro(o,mc),s=Ro(o,gc),a=Ro(o,hc);(r||s||a)&&je.set(n,{provider:n,remaining:us(r),limit:us(s),reset:yc(a),capturedAt:Date.now()})}function fs(n){return je.get(n)}function ln(){return Array.from(je.values())}function Ro(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function us(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function yc(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=_c(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function _c(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 kc(){try{if(!(0,he.existsSync)(So))return;let n=JSON.parse((0,he.readFileSync)(So,"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;je.set(t.provider,t)}}catch{}}function ds(){try{if(je.size===0)return;(0,he.existsSync)(wo)||(0,he.mkdirSync)(wo,{recursive:!0}),(0,he.writeFileSync)(So,JSON.stringify(Array.from(je.values()),null,2),"utf-8")}catch{}}function ze(){cs||(cs=!0,kc(),ls=setInterval(ds,6e4),ls.unref?.(),process.on("exit",ds))}var he,Po,ps,wo,So,je,cs,ls,mc,gc,hc,He=P(()=>{"use strict";he=require("fs"),Po=require("path"),ps=require("@wengine-ai/claude-code-router-shared"),wo=(0,Po.join)(ps.HOME_DIR,"runtime"),So=(0,Po.join)(wo,"rate-limit.json"),je=new Map,cs=!1,ls=null,mc=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],gc=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],hc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var Je,Ao=P(()=>{"use strict";Je=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){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(),a="";try{let{value:f,done:_}=await s.read();!_&&f&&(a=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let f=this.prependToStream(a,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let f=this.prependToStream(a,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let i=this.prependToStream(a,r),u=new TextDecoder,d=new TextEncoder,m="",g=!1,y=this,p=new ReadableStream({async start(f){let _=i.getReader(),k=-1,h="",b=x=>(x!==h&&(k++,h=x),k);try{for(;;){let{done:x,value:v}=await _.read();if(x){g||f.enqueue(d.encode(`data: [DONE]
3
+ `);a=i.pop()||"";for(let u of i)u.trim()&&(s<o.maxStreamChunks?Xr(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&&Xr(e,t,s,a.trim()),s++),Yr(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),Yr(e,t,s)}finally{r.releaseLock()}})()}var rc,Ue,_o,dt=P(()=>{"use strict";rc=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Ue={maxBodyLength:4096,maxStreamChunks:100},_o=!1});function ns(n,e,t,o,r){let s=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([i,u])=>{u&&s.set(i,u)});let a,l=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let i=new AbortController,u=()=>i.abort();t.signal.addEventListener("abort",u),l.addEventListener("abort",u),a=i.signal}else a=l;let c={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return t.httpsProxy&&(c.dispatcher=K(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:on(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:ic(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function ic(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 os=P(()=>{ae();dt()});var sn,ko=P(()=>{sn="2.3.237"});var rs={};Yt(rs,{getFallbackPromotionStore:()=>De,resetFallbackPromotionStore:()=>lc});function De(n){return Pe||(Pe=new bo,n&&Pe.configure(n)),Pe}function lc(){Pe&&(Pe.clearAll(),Pe=null)}var cc,bo,Pe,an=P(()=>{"use strict";ce();cc=600*1e3,bo=class{promotions=new Map;enabled=!0;ttlMs=cc;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 l=this.getKey(e,t,o),c=`${r},${s}`;this.promotions.set(l,{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,...i]=a.promotedModel.split(","),u=i.join(",");if(!D().isAvailable(c,u))return this.promotions.delete(s),null;let m=r.find(y=>y.name.toLowerCase()===c.toLowerCase()),g=m?.models?.find(y=>String(y).toLowerCase()===u.toLowerCase());return!m||!g||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${g}`}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}},Pe=null});function fc(n){try{if(!(0,ge.existsSync)(To))return;let e=JSON.parse((0,ge.readFileSync)(To,"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 is(n){try{let e=n.getAllStates();if(e.length===0)return;(0,ge.existsSync)(Co)||(0,ge.mkdirSync)(Co,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,ge.writeFileSync)(To,JSON.stringify(t,null,2),"utf-8")}catch{}}function cn(){if(ss)return;ss=!0;let n=D();fc(n),pc=setInterval(()=>is(n),6e4),process.on("exit",()=>is(n))}function D(n){return xo||(xo=new pt(n)),xo}var ge,vo,as,uc,dc,pt,Co,To,ss,pc,xo,ce=P(()=>{"use strict";ge=require("fs"),vo=require("path"),as=require("@wengine-ai/claude-code-router-shared"),uc=120,dc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},pt=class{states=new Map;config;probeTimer;constructor(e){this.config={...dc,...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}=(an(),Jr(rs));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 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 l=(o??uc)*1e3;a.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)}},Co=(0,vo.join)(as.HOME_DIR,"runtime"),To=(0,vo.join)(Co,"provider-health.json"),ss=!1,pc=null;xo=null});function ft(n,e,t){let o=l=>{if(t instanceof Headers)return t.get(l);let c=Object.keys(t).find(i=>i.toLowerCase()===l);return c?t[c]:null},r=Ro(o,mc),s=Ro(o,gc),a=Ro(o,hc);(r||s||a)&&je.set(n,{provider:n,remaining:us(r),limit:us(s),reset:yc(a),capturedAt:Date.now()})}function fs(n){return je.get(n)}function ln(){return Array.from(je.values())}function Ro(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function us(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function yc(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=_c(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function _c(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 kc(){try{if(!(0,he.existsSync)(So))return;let n=JSON.parse((0,he.readFileSync)(So,"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;je.set(t.provider,t)}}catch{}}function ds(){try{if(je.size===0)return;(0,he.existsSync)(wo)||(0,he.mkdirSync)(wo,{recursive:!0}),(0,he.writeFileSync)(So,JSON.stringify(Array.from(je.values()),null,2),"utf-8")}catch{}}function ze(){cs||(cs=!0,kc(),ls=setInterval(ds,6e4),ls.unref?.(),process.on("exit",ds))}var he,Po,ps,wo,So,je,cs,ls,mc,gc,hc,He=P(()=>{"use strict";he=require("fs"),Po=require("path"),ps=require("@wengine-ai/claude-code-router-shared"),wo=(0,Po.join)(ps.HOME_DIR,"runtime"),So=(0,Po.join)(wo,"rate-limit.json"),je=new Map,cs=!1,ls=null,mc=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],gc=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],hc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var Je,Ao=P(()=>{"use strict";Je=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){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(),a="";try{let{value:f,done:_}=await s.read();!_&&f&&(a=new TextDecoder().decode(f))}finally{s.releaseLock()}if(o.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let f=this.prependToStream(a,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let f=this.prependToStream(a,r);return new Response(f,{status:e.status,statusText:e.statusText,headers:e.headers})}let i=this.prependToStream(a,r),u=new TextDecoder,d=new TextEncoder,m="",g=!1,y=this,p=new ReadableStream({async start(f){let _=i.getReader(),k=-1,h="",b=x=>(x!==h&&(k++,h=x),k);try{for(;;){let{done:x,value:v}=await _.read();if(x){g||f.enqueue(d.encode(`data: [DONE]
4
4
 
5
5
  `));break}let C=u.decode(v,{stream:!0});m+=C;let R=m.split(/\r?\n/);m=R.pop()||"";for(let T of R)if(T.trim())try{if(T.startsWith("event: "))continue;if(T.startsWith("data: ")){let O=T.slice(5).trim();if(O==="[DONE]"){g=!0,f.enqueue(d.encode(`data: [DONE]
6
6