@wengine-ai/llms 2.3.232 → 2.3.234

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,8 @@ npm install -g @wengine-ai/claude-code-router-next@latest && ccr restart
93
93
 
94
94
  | 版本 | 发布内容 |
95
95
  | --- | --- |
96
+ | **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> |
97
+ | **v2.3.233** | <ul><li>**修复「立即更新」点击失败(404)**: UI `ApiClient` 的 `baseUrl` 已是 `/api`,但 `performUpdate()` 又传入 `/api/update/perform` 导致实际请求变成 `/api/api/update/perform`;现改为 `/update/perform`,更新请求重新落到服务端 `/api/update/perform`。</li><li>**修复更新弹窗永远显示「暂无更新日志」**: `checkForUpdates` 此前 `changelog` 恒为空字符串。现在检测到新版本时,优先从已发布 npm 包对应版本 README 的 changelog 表提取摘要,取不到再 fallback 到 GitHub `CHANGELOG.md` 对应版本段,两级都失败才回退兜底文案,网络错误不影响版本检查。</li></ul> |
96
98
  | **v2.3.232** | <ul><li>**严格项目级路由成为权威边界**: 项目配置非空 `Router` 后,目标缺失、格式错误、被禁用、不健康或额度耗尽不再静默回落到全局,而是返回稳定错误码;项目内显式 fallback 仍可用,同时关闭全局 Router/custom router、全局 fallback、客户端与 subagent model override 等项目外逃逸路径。</li><li>**Provider 级代理策略**: 新增顶层 `PROXY_GLOBAL_ENABLED` 与 provider 级 `proxy_enabled`;全局关闭时仅显式标记的 provider 使用共享 `PROXY_URL`,其余直连,未配置或开启时保持全部走代理的旧行为。推理、fallback、健康探测、额度查询、wakeup、provider API tokenizer 等出站请求统一遵循该策略。</li><li>**代理安全校验与 UI 控制**: 保存配置前仅允许 `http://`、`https://`、空值或环境变量占位符,非法协议/畸形 URL 逐项报错且不覆盖原配置;设置页新增「全局生效」开关、provider 卡片新增独立代理开关,并提示仅使用可信代理。ProxyAgent 改为按 URL 缓存复用,关闭时释放,日志自动脱敏代理凭据。</li><li>**per-client adapters 与 pi 上下文路由**: runtime 下沉到 core 并用 adapter 统一 Claude Code、Codex、pi、qwen-code、opencode 的差异;pi 新增 `extendedContextRatio`(默认 80%),不再生成/消费 `[1m]` 后缀,longContext 改用绝对阈值链。</li><li>**修复严格路由、客户端识别与用量回归**: 畸形项目 target 不再逃逸全局;Codex Responses 请求不再被误判为 Claude Code;修复非流式 `upstreamModel` 丢失、失败请求串用上一请求 tokens、`response.completed` 将 usage merge base 归零、项目路由失败清除会话用量基线等问题。</li><li>**修复 runtime 生命周期与错误处理**: `createCcrServer({ port })` 正确采用传入端口,401/403 认证不再挂起,provider/transformer/tokenizer 初始化完成后才监听,preset 注册失败不再静默吞掉。</li></ul> |
97
99
  | **v2.3.231** | <ul><li>**项目级接管默认仅接管 Claude Code**: 此前打开项目「CCR 接管」默认接管全部客户端(Claude Code、pi、qwen-code、opencode),会把 `.pi/settings.json`、`.qwen/settings.json`、`opencode.json` 等配置写进项目目录(opencode 首次运行还会自行生成 `AGENTS.md`),污染项目根目录;现在所有默认路径(主开关、多选清空、legacy `enabled: true`)都只接管 Claude Code,其余客户端在多选中显式勾选才接管。</li><li>**修复「检查更新」永远提示已是最新(双重 bug)**: 后端 `checkForUpdates`/`performUpdate` 硬编码了已从 npm unpublish 的旧包名 `claude-code-router-next`,`npm view` 404 被 catch 静默吞掉、恒返回「无更新」,「立即更新」也因同样的错包名安装失败,现改为从 `package.json` 动态读取包名(`@wengine-ai/claude-code-router-next`),今后改包名不会再失效;另外前端更新弹窗条件要求 `changelog` 非空而后端该字段恒为空串,即使有新版本也不弹窗,现去掉该强制判断(弹窗内已有「暂无更新日志」兜底文案)。</li><li>**发布确认点闸门(release gate)**: `scripts/release.sh` 新增 `validate_release_docs`,发布前(含 dry-run)强制校验:6 个 `package.json` 版本一致、`CHANGELOG.md` 有该版本的非空段落、两份 README 表格有该版本行、版本号严格大于 npm 已发布 latest(逐段数字比较,registry 不可达时警告跳过);任一不满足即中止发布。</li><li>**版本号策略:多位 patch 日常小迭代**: 自本版本起日常小迭代在 patch 段追加一位数字(`2.3.23` → `2.3.231` → `2.3.232`),避免每日发布推高主版本数字;patch 按数字比较,用过 `2.3.23x` 后下一个功能版本是 `2.3.240`(`2.3.24` 会被闸门当降级拦截)或直接升 `2.4.0`。</li></ul> |
98
100
  | **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> |
@@ -101,8 +103,6 @@ npm install -g @wengine-ai/claude-code-router-next@latest && ccr restart
101
103
  | **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> |
102
104
  | **v2.3.19** | <ul><li>**新增 OpenCode (opencode.ai) Transformer**: 为暴露 OpenAI 兼容 `/v1/chat/completions`、底层由 GLM/智谱驱动的 OpenCode 类 provider 新增专用 transformer,显式声明 `endPoint` 避免误触 bypass 把 Anthropic 格式工具发给 OpenAI 兼容接口;同时清理 GLM 不识别的 `cache_control`/`image_url`/`media_type`,转换 `reasoning_content` 为 thinking 格式,并把纯数字 `tool_call` ID 替换为 UUID。在 provider `transformer` 中配置 `"opencode"` 启用。</li><li>**设置页代理地址与 API 密钥输入框禁用浏览器自动填充**: 弹窗版与整页版设置的「代理地址」「API 密钥」此前会被 Chrome 用已保存表单数据/密码自动填充覆盖真实值;现在通过 `Input` 的 `disableAutofill` 提供随机 `name`、初始 `readOnly` 至首次聚焦解除、`autoComplete="off"` 及密码管理器忽略标记三重防护,并配合隐藏 honeypot 字段。</li></ul> |
103
105
  | **v2.3.18** | <ul><li>**模型族长上下文阈值继承主路由配置**: `ccr-opus`/`ccr-sonnet`/`ccr-haiku` 的 family routing 未配置族级阈值时会继承 `Router.longContextThreshold`,避免主路由设为 100k 时约 70k token 请求仍误进 `<family>/longContext`。</li><li>**fallback 候选模型也执行 Double-Check 重试**: 每个 fallback 候选第一次 `fetch failed`/空 SSE/隐藏错误后会先对同一候选重试一次,第二次仍失败才切到下一个,降低智谱等接口短暂不稳定导致的过早切换;同时修正失败记录的 `originalModel` 显示。</li><li>**全局配置保存后同步项目级 CCR 接管字段**: 跟随全局 Router 且已开启 CCR Takeover 的项目,在保存全局配置或切回使用全局配置时自动刷新 `.claude/settings.local.json` 中的模型族别名、auto-compact、状态栏与代理字段。</li><li>**默认降低日志量并保留最近 7 天**: 服务器日志默认级别从 `debug` 调整为 `error`,只在显式配置 `LOG_LEVEL=info/debug/trace` 时输出详细日志,并自动清理超过 7 天的 `ccr-*.log`。</li></ul> |
104
- | **v2.3.17** | <ul><li>**修复 fallback 触发时所有备用模型报 Invalid URL**: 主模型限流(如智谱套餐)触发 fallback 后,此前所有备用模型都报 `Invalid URL`;根因是 fallback 用了原始 `ConfigProvider[]`(无 `baseUrl`)而非已注册的 `LLMProvider[]`,改为 `providerService.getProviders()`。</li><li>**修复 fireworks 托管上游用量统计全 0**: fireworks 流式把真实 usage 放在 `finish_reason` 之后的 `choices:[]` 空 chunk 里,此前 `finish_reason` 块用 null usage 覆盖了已 merge 的真实值、且 `break` 丢弃了后续 usage chunk,导致 `input` 有值但 `output`/缓存命中为 0;现改为 finish 后继续读取、只设 stop_reason 不碰 usage、`break` 改 `hasFinished=true`,并修复下游三层用量捕获与 `??` 对 0 不 fallback 的问题。</li><li>**忽略已删除模型的残留路由,防止健康池污染**: 从 provider 配置删除模型后,路由与 fallback 中残留的 `provider,model` 仍被当作有效候选反复失败污染健康池;现在对无法匹配的候选直接返回 `null` 并在请求前校验,`ProviderHealthStore` 统一拦截空 provider/model 防畸形 key 污染,同时抽取 `findProviderModel` 共用函数。</li></ul> |
105
- | **v2.3.16** | <ul><li>**修复 system 消息顺序兼容 DeepSeek/vLLM**: OpenAI 兼容提供商(DeepSeek V4、GLM、vLLM)要求 `[system, user, assistant]` 顺序,此前 system 排在 user/assistant 之后会导致输出乱码;现在将 system 消息前置并去重。</li><li>**接管时去除 Attribution 动态头以提升缓存命中**: CCR 接管 Claude Code 时默认写入 `CLAUDE_CODE_ATTRIBUTION_HEADER=0`,去掉系统提示词开头随请求变化的 attribution 头(客户端版本 + prompt fingerprint),稳定上游 prompt 缓存前缀;可在设置页或 `disableAttributionHeader: false` 关闭。</li><li>**设置页布局紧凑化**: 「日志级别」下拉从独占整行移入两列网格,与「API 密钥」并排显示,减少纵向留白。</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 Za=Object.create;var Yt=Object.defineProperty;var ec=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var nc=Object.getPrototypeOf,oc=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var qt=(n,e)=>{for(var t in e)Yt(n,t,{get:e[t],enumerable:!0})},Wr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of tc(e))!oc.call(n,r)&&r!==t&&Yt(n,r,{get:()=>e[r],enumerable:!(o=ec(e,r))||o.enumerable});return n};var K=(n,e,t)=>(t=n!=null?Za(nc(n)):{},Wr(e||!n||!n.__esModule?Yt(t,"default",{value:n,enumerable:!0}):t,n)),Gr=n=>Wr(Yt({},"__esModule",{value:!0}),n);function sc(n){if(n==null)return{ok:!0};let e=String(n).trim();if(!e)return{ok:!0};if(rc.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 Kr(n){let e=[];for(let t of Qr){let o=n[t];if(o==null)continue;let r=sc(o);r.ok||e.push({key:t,error:r.error})}return e}function ct(n){for(let e of Qr){let t=n.get(e);if(t==null)continue;let o=String(t).trim();if(o)return o}}function yo(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=ct(n);if(t)return yo(n.get("PROXY_GLOBAL_ENABLED"))||e?.proxyEnabled===!0||e?.proxy_enabled===!0?t:void 0}function Y(n){let e=ic(n),t=Zt.get(e);if(t)return t;let o=new Vr.ProxyAgent(e);return Zt.set(e,o),o}async function en(){let n=Array.from(Zt.values());Zt.clear(),await Promise.allSettled(n.map(e=>e.close()))}function ic(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 Vr,Qr,rc,Zt,ie=P(()=>{"use strict";Vr=require("undici"),Qr=["HTTPS_PROXY","https_proxy","httpsProxy","PROXY_URL"],rc=/\$\{[^}]+\}|\$[A-Z_][A-Z0-9_]*/;Zt=new Map});var lt,_o,Xr,Yr,we,ko=P(()=>{"use strict";lt=require("fs"),_o=require("path"),Xr=require("dotenv"),Yr=K(require("json5"),1);ie();we=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,_o.join)(process.cwd(),this.options.jsonPath);if((0,lt.existsSync)(e))try{let t=(0,lt.readFileSync)(e,"utf-8"),o=Yr.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,_o.join)(process.cwd(),this.options.envPath);if((0,lt.existsSync)(e))try{let t=(0,Xr.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 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 qr(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 tn=P(()=>{"use strict"});function nn(n){bo=n}function ut(){return bo}function on(n){return bo||n.get("DEBUG_LOG")===!0}function ts(n){let e=n.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Fe:{maxBodyLength:e.maxBodyLength??Fe.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Fe.maxStreamChunks}}function rn(n){let e={};for(let[t,o]of Object.entries(n))ac.has(t.toLowerCase())?e[t]="***MASKED***":e[t]=o;return e}function sn(n,e){return n.length<=e?n:n.slice(0,e)+`...[truncated, total ${n.length} bytes]`}function ns(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:rn(t.headers),body:sn(o,Fe.maxBodyLength)})}function os(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_response",status:t.status,headers:rn(t.headers),...t.body!==void 0?{body:sn(t.body,Fe.maxBodyLength)}:{}})}function Zr(n,e,t,o){let r=cc(o);n.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:t,...r?{usage_monitor:r}:{},data:sn(o,Fe.maxBodyLength)})}function cc(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:sn(o,512)})}}if(e.length)return e.length===1?e[0]:e}function es(n,e,t){n.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:t})}function rs(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?Zr(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&&Zr(e,t,s,a.trim()),s++),es(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),es(e,t,s)}finally{r.releaseLock()}})()}var ac,Fe,bo,dt=P(()=>{"use strict";ac=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Fe={maxBodyLength:4096,maxStreamChunks:100},bo=!1});function ss(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=Y(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:rn(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:lc(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function lc(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 is=P(()=>{ie();dt()});var an,xo=P(()=>{an="2.3.232"});var as={};qt(as,{getFallbackPromotionStore:()=>Ue,resetFallbackPromotionStore:()=>pc});function Ue(n){return Se||(Se=new Co,n&&Se.configure(n)),Se}function pc(){Se&&(Se.clearAll(),Se=null)}var dc,Co,Se,cn=P(()=>{"use strict";ae();dc=600*1e3,Co=class{promotions=new Map;enabled=!0;ttlMs=dc;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}},Se=null});function hc(n){try{if(!(0,ge.existsSync)(Ro))return;let e=JSON.parse((0,ge.readFileSync)(Ro,"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 ls(n){try{let e=n.getAllStates();if(e.length===0)return;(0,ge.existsSync)(vo)||(0,ge.mkdirSync)(vo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,ge.writeFileSync)(Ro,JSON.stringify(t,null,2),"utf-8")}catch{}}function ln(){if(cs)return;cs=!0;let n=D();hc(n),gc=setInterval(()=>ls(n),6e4),process.on("exit",()=>ls(n))}function D(n){return To||(To=new pt(n)),To}var ge,wo,us,fc,mc,pt,vo,Ro,cs,gc,To,ae=P(()=>{"use strict";ge=require("fs"),wo=require("path"),us=require("@wengine-ai/claude-code-router-shared"),fc=120,mc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},pt=class{states=new Map;config;probeTimer;constructor(e){this.config={...mc,...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}=(cn(),Gr(as));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??fc)*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)}},vo=(0,wo.join)(us.HOME_DIR,"runtime"),Ro=(0,wo.join)(vo,"provider-health.json"),cs=!1,gc=null;To=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=So(o,yc),s=So(o,_c),a=So(o,kc);(r||s||a)&&De.set(n,{provider:n,remaining:fs(r),limit:fs(s),reset:bc(a),capturedAt:Date.now()})}function hs(n){return De.get(n)}function un(){return Array.from(De.values())}function So(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function fs(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function bc(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=xc(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function xc(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 Cc(){try{if(!(0,he.existsSync)(Ao))return;let n=JSON.parse((0,he.readFileSync)(Ao,"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;De.set(t.provider,t)}}catch{}}function ms(){try{if(De.size===0)return;(0,he.existsSync)(Po)||(0,he.mkdirSync)(Po,{recursive:!0}),(0,he.writeFileSync)(Ao,JSON.stringify(Array.from(De.values()),null,2),"utf-8")}catch{}}function je(){ds||(ds=!0,Cc(),ps=setInterval(ms,6e4),ps.unref?.(),process.on("exit",ms))}var he,Oo,gs,Po,Ao,De,ds,ps,yc,_c,kc,ze=P(()=>{"use strict";he=require("fs"),Oo=require("path"),gs=require("@wengine-ai/claude-code-router-shared"),Po=(0,Oo.join)(gs.HOME_DIR,"runtime"),Ao=(0,Oo.join)(Po,"rate-limit.json"),De=new Map,ds=!1,ps=null,yc=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],_c=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],kc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var He,Eo=P(()=>{"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 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?Zr(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&&Zr(e,t,s,a.trim()),s++),es(e,t,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${t}:`,a),es(e,t,s)}finally{r.releaseLock()}})()}var ac,Fe,bo,dt=P(()=>{"use strict";ac=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Fe={maxBodyLength:4096,maxStreamChunks:100},bo=!1});function ss(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=Y(t.httpsProxy)),r?.debug({reqId:o.req.id,method:"POST",headers:rn(Object.fromEntries(s.entries())),requestUrl:typeof n=="string"?n:n.toString(),useProxy:lc(t.httpsProxy)},"final request"),fetch(typeof n=="string"?n:n.toString(),c)}function lc(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 is=P(()=>{ie();dt()});var an,xo=P(()=>{an="2.3.234"});var as={};qt(as,{getFallbackPromotionStore:()=>Ue,resetFallbackPromotionStore:()=>pc});function Ue(n){return Se||(Se=new Co,n&&Se.configure(n)),Se}function pc(){Se&&(Se.clearAll(),Se=null)}var dc,Co,Se,cn=P(()=>{"use strict";ae();dc=600*1e3,Co=class{promotions=new Map;enabled=!0;ttlMs=dc;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}},Se=null});function hc(n){try{if(!(0,ge.existsSync)(Ro))return;let e=JSON.parse((0,ge.readFileSync)(Ro,"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 ls(n){try{let e=n.getAllStates();if(e.length===0)return;(0,ge.existsSync)(vo)||(0,ge.mkdirSync)(vo,{recursive:!0});let t=e.map(o=>({...o,updatedAt:Date.now()}));(0,ge.writeFileSync)(Ro,JSON.stringify(t,null,2),"utf-8")}catch{}}function ln(){if(cs)return;cs=!0;let n=D();hc(n),gc=setInterval(()=>ls(n),6e4),process.on("exit",()=>ls(n))}function D(n){return To||(To=new pt(n)),To}var ge,wo,us,fc,mc,pt,vo,Ro,cs,gc,To,ae=P(()=>{"use strict";ge=require("fs"),wo=require("path"),us=require("@wengine-ai/claude-code-router-shared"),fc=120,mc={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},pt=class{states=new Map;config;probeTimer;constructor(e){this.config={...mc,...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}=(cn(),Gr(as));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??fc)*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)}},vo=(0,wo.join)(us.HOME_DIR,"runtime"),Ro=(0,wo.join)(vo,"provider-health.json"),cs=!1,gc=null;To=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=So(o,yc),s=So(o,_c),a=So(o,kc);(r||s||a)&&De.set(n,{provider:n,remaining:fs(r),limit:fs(s),reset:bc(a),capturedAt:Date.now()})}function hs(n){return De.get(n)}function un(){return Array.from(De.values())}function So(n,e){for(let t of e){let o=n(t);if(o)return o}return null}function fs(n){if(!n)return null;let e=Number(n.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function bc(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=xc(e);return r===null?null:Math.floor((Date.now()+r)/1e3)}function xc(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 Cc(){try{if(!(0,he.existsSync)(Ao))return;let n=JSON.parse((0,he.readFileSync)(Ao,"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;De.set(t.provider,t)}}catch{}}function ms(){try{if(De.size===0)return;(0,he.existsSync)(Po)||(0,he.mkdirSync)(Po,{recursive:!0}),(0,he.writeFileSync)(Ao,JSON.stringify(Array.from(De.values()),null,2),"utf-8")}catch{}}function je(){ds||(ds=!0,Cc(),ps=setInterval(ms,6e4),ps.unref?.(),process.on("exit",ms))}var he,Oo,gs,Po,Ao,De,ds,ps,yc,_c,kc,ze=P(()=>{"use strict";he=require("fs"),Oo=require("path"),gs=require("@wengine-ai/claude-code-router-shared"),Po=(0,Oo.join)(gs.HOME_DIR,"runtime"),Ao=(0,Oo.join)(Po,"rate-limit.json"),De=new Map,ds=!1,ps=null,yc=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],_c=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],kc=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"]});var He,Eo=P(()=>{"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 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