dsh-cost-meter 1.8.5 → 1.8.6
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 +6 -6
- package/README.zh-CN.md +6 -6
- package/lib/client.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
Per-conversation cost · daily totals · OpenCode Go subscription quota display · budget with usage percentage · official account balance · custom provider balance · balance progress bar · history · peak/off-peak pricing hours display (peak hours UTC 01:00–04:00, 06:00–10:00; weekends and Chinese public holidays are off-peak all day, with separate labels) · pre-switch popup & system-notification alerts for peak/off-peak changes (position / lead time / alert type configurable) · one-click price sync from the official docs · Codex-style token usage heat grid · multi-vendor model pricing (built-in 90+ model price catalog with auto-matching) · mainstream Coding Plan quota queries & display (Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / Volcano Ark / Qwen / Xiaomi MiMo) plan/API dual-track billing (subscription quota vs pay-as-you-go money separated, per-1% & full-window token/equivalent-cost estimates with daily/weekly/monthly curves) · · quota strip above the input box (budget / Go / coding-plan usage in one row, toggleable)
|
|
10
10
|
|
|
11
|
-
[](https://github.com/Han-1413141/dsh-cost-meter)
|
|
12
12
|
|
|
13
|
-
**v1.8.
|
|
13
|
+
**v1.8.6** fixes transparent backgrounds in conversation cost details when using skins that style dialogs through `[role=dialog]`. See the [release notes](docs/release-notes/v1.8.6.md).
|
|
14
14
|
|
|
15
15
|
Desktop users: follow the [Desktop installation instructions](docs/install-troubleshooting.md#desktop-安装与更新) for the application's own CLI and `desktop` Profile.
|
|
16
16
|
|
|
@@ -320,22 +320,22 @@ On Node.js 20, use `npm install -g pnpm@10` instead. See [pnpm installation and
|
|
|
320
320
|
dsh plugin --profile web add dsh-cost-meter
|
|
321
321
|
```
|
|
322
322
|
|
|
323
|
-
**PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.8.
|
|
323
|
+
**PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.8.6`** — review the script before running):
|
|
324
324
|
|
|
325
325
|
```powershell
|
|
326
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.
|
|
326
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.6/install.ps1 | iex
|
|
327
327
|
```
|
|
328
328
|
|
|
329
329
|
**Or a plain command line** (the machine must already have pnpm and git; also pinned to the tag):
|
|
330
330
|
|
|
331
331
|
```sh
|
|
332
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.
|
|
332
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.6
|
|
333
333
|
```
|
|
334
334
|
|
|
335
335
|
Without git, use the GitHub tag archive:
|
|
336
336
|
|
|
337
337
|
```sh
|
|
338
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.
|
|
338
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.6.tar.gz
|
|
339
339
|
```
|
|
340
340
|
|
|
341
341
|
After installing, **restart** `dsh web` (plugin rows, the Typert manifest and the client bundle are all scanned at startup):
|
package/README.zh-CN.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
本会话费用 · 当日费用 · OpenCode Go 订阅额度显示 · 预算与已用百分比 · 官方账户余额 · 自定义 Provider 余额查询(可配任意 HTTP 端点) · 余额三段进度条 · 历史记录 · 峰谷计价时段显示(UTC 01:00–04:00、06:00–10:00 为峰时段;周末与中国法定假日全天按谷价,分别标注) · 峰/谷切换前弹窗与系统通知提醒(位置/提前量/提醒类型可配) · 官方价格一键同步 · 类 Codex Token 用量热图 · 多厂商多模型价格计费(内置 90+ 模型价格目录与自动匹配) · 主流 Coding Plan 额度查询与显示(Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / 火山方舟 / 千问 / 小米 MiMo 十一家,含 Volcano Ark AK/SK 签名与 MiMo 控制台 Cookie 查询) · Plan/API 双轨计费(订阅额度与按量金额分离统计,每 1% 额度与满窗的 token/等值金额估算及日/周/月曲线) · 输入框上方额度横条(预算/Go/Coding Plan 用量一条横排显示,可开关)
|
|
10
10
|
|
|
11
|
-
[](https://github.com/Han-1413141/dsh-cost-meter)
|
|
12
12
|
|
|
13
|
-
**v1.8.
|
|
13
|
+
**v1.8.6** 修复启用皮肤后单会话费用明细弹窗及内部控件背景透明的问题,使皮肤的 `[role=dialog]` 样式正常生效。详见[更新说明](docs/release-notes/v1.8.6.md)。
|
|
14
14
|
|
|
15
15
|
桌面端用户请按 [Desktop 安装说明](docs/install-troubleshooting.md#desktop-安装与更新),使用应用自带的 CLI 和 `desktop` Profile。
|
|
16
16
|
|
|
@@ -320,22 +320,22 @@ Node.js 20 请改用 `npm install -g pnpm@10`。版本要求见 [pnpm 官方安
|
|
|
320
320
|
dsh plugin --profile web add dsh-cost-meter
|
|
321
321
|
```
|
|
322
322
|
|
|
323
|
-
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.8.
|
|
323
|
+
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.8.6`**,建议先下载审阅再运行):
|
|
324
324
|
|
|
325
325
|
```powershell
|
|
326
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.
|
|
326
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.6/install.ps1 | iex
|
|
327
327
|
```
|
|
328
328
|
|
|
329
329
|
**或直接命令行**(机器上需已有 pnpm 与 git;同样固定到 tag):
|
|
330
330
|
|
|
331
331
|
```sh
|
|
332
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.
|
|
332
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.6
|
|
333
333
|
```
|
|
334
334
|
|
|
335
335
|
没有 git 时可用 GitHub tag 打包直链:
|
|
336
336
|
|
|
337
337
|
```sh
|
|
338
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.
|
|
338
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.6.tar.gz
|
|
339
339
|
```
|
|
340
340
|
|
|
341
341
|
安装后**重启** `dsh web`(插件行、Typert 清单与客户端 bundle 均在启动时扫描):
|
package/lib/client.js
CHANGED
|
@@ -3,4 +3,4 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:Ve=>{var Ft={exports:{
|
|
|
3
3
|
`),h=e(E,null,e("div",{className:"cm-mm-title"},n("codingPlanMinimaxTitle")),c.row,m.row,d?e("div",{className:"cm-mm-reset"},"5h · "+d):null),v=e(E,null,e("div",{className:"cm-bbox-rail cm-num"},c.text),e("div",{className:"cm-bbox-rail cm-num"},m.text));return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},g),side:"right",delayMs:300},e("div",{...u,className:"cm-bbox cm-mm"+(p==="ok"?"":" "+p)+(l===!1?" rail":"")+(i?" clickable"+(i.busy?" busy":""):""),...i?be(i.busy,i.run):{}},l===!1?v:h))}function Kn(t){const{state:s,wide:o,api:a}=t,n=s.codingPlans?.minimax,l=K(W(s.config?.locale)),i=Te(a?()=>a.refreshCodingPlan("minimax"):null);if(!n||n.status!=="ok")return null;const{five:r,seven:u}=_e(n.windows);return r==null&&u==null?null:e(Sa,{five:r,seven:u,fetchedAt:n.fetchedAt,t:l,wide:o,refresh:i,direction:se(s.config,"plan")})}const Yn="/plugins/dsh-openai-codex/auth/status",Vn=168*3600;function Jn(t){if(t===null||typeof t!="object"||t.status!=="signed-in")return null;const s=t.usage!==null&&typeof t.usage=="object"?t.usage.rateLimits:null;if(!Array.isArray(s))return null;const o=s.find(r=>r!==null&&typeof r=="object"&&r.id==="codex");if(!o||!Array.isArray(o.windows))return null;const a=o.windows.find(r=>r!==null&&typeof r=="object"&&Number(r.windowSeconds)===Vn);if(!a||typeof a.remainingPercent!="number"||!Number.isFinite(Number(a.remainingPercent)))return null;const n=Math.max(0,Math.min(100,Math.round((100-Number(a.remainingPercent))*10)/10)),l=Number(a.resetAt),i=Number.isFinite(l)&&l>0?new Date(l*1e3).toISOString():"";return{weekly:{percent:n,resetsAt:i}}}const $={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},$n=t=>($.listeners.push(t),()=>{$.listeners=$.listeners.filter(s=>s!==t)}),Zn=()=>{for(const t of $.listeners)try{t()}catch{}};async function Tt(t=!1,s=!1){if(!s)return;if($.inFlight!==null)return $.inFlight;if(!t&&$.fetchedAt>0&&Date.now()-$.fetchedAt<5*6e4)return;const o=(async()=>{try{const a=await fetch(Yn,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(a.ok){const l=Jn(await a.json().catch(()=>null));l!==null&&(n=l)}$.status=Object.keys(n).length>0?"ok":"unavailable",$.windows=n}catch{$.status="unavailable"}finally{$.fetchedAt=Date.now(),$.inFlight=null,Zn()}})();return $.inFlight=o,o}function Ot(t){const[s,o]=R(()=>({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt}));return X(()=>{if(!t)return;let a=!0;const n=()=>{a&&o({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt})},l=$n(n);return n(),Tt(!1,!0),()=>{a=!1,l()}},[t]),s}function Xn(t){const s=it(),{state:o,wide:a}=t,n=K(W(o.config?.locale)),l=o.config?.codexQuotaEnabled===!0&&o.config?.codexQuotaSidebar!==!1,i=Ot(l),r=Te(()=>Tt(!0,l));if(!l||i.status!=="ok")return null;const u=i.windows.weekly??null;if(u===null)return null;const d=se(o.config,"plan"),c=Ge(n("goShortWeekly"),u,d,n),m=[n("codexQuotaTitle"),lt(c.label,d,n),ze(u,n),i.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()}):null,...ye(n,r)].filter(Boolean).join(`
|
|
4
4
|
`),p=e(E,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),c.row),b=e("div",{className:"cm-bbox-rail cm-num"},c.label===null?"—":c.label+"%");return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},m),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(c.level==="ok"?"":" "+c.level)+(a===!1?" rail":"")+(r.busy?" busy":""),...be(r.busy,r.run)},a===!1?b:p))}function Dt(t,s){return t==="fiveHour"||t==="5h"?"5h":t==="weekly"||t==="week"||t==="7d"?t==="7d"?"7d":s("goShortWeekly"):t==="monthly"||t==="month"?s("goShortMonthly"):t==="daily"||t==="day"?s("goShortDaily"):t==="plan"?s("mimoWindowPlan"):t==="compensation"?s("mimoWindowCompensation"):t==="balance"?s("codingPlanWindowBalance"):String(t).replace(/_/g," ")}function es(t){const s=it(),{id:o,state:a,wide:n,api:l}=t,i=a.codingPlans?.[o],r=K(W(a.config?.locale)),u=Te(l?()=>l.refreshCodingPlan(o):null),d=Ee.find(f=>f.id===o);if(!d||!i||i.status!=="ok")return null;const c=i.windows!==null&&typeof i.windows=="object"?i.windows:{},m=Object.entries(c);if(m.length===0)return null;const p=f=>f!==null&&typeof f=="object"&&typeof f.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(f.percent)||0))):null,b=se(a.config,"plan"),g=m.map(([f,S])=>{const y=p(S);if(y===null)return e("div",{key:f,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof S?.text=="string"?S.text:"—"));const T=y>=100?"over":y>=80?"warn":"ok",A=pe(y,b);return e("div",{key:f,className:"cm-mm-row wide"+(T==="ok"?"":" "+T)},e("span",{className:"cm-bbox-label"},Dt(f,r)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:A.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},A.label===null?"—":A.label+"%"))}),h=m.map(([f,S])=>{const y=p(S),T=ze(S,r),A=y===null?typeof S?.text=="string"?S.text:"—":lt(pe(y,b).label,b,r);return Dt(f,r)+" "+A+(T?" · "+T:"")});i.fetchedAt>0&&h.push(r("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()})),h.push(...ye(r,u));const v=[r(d.labelKey),...h].join(`
|
|
5
5
|
`),N=m.map(([,f])=>p(f)).filter(f=>f!==null),C=N.some(f=>f>=100)?"over":N.some(f=>f>=80)?"warn":"ok",x=N.length>0?N.slice(0,2).map(f=>pe(f,b).label+"%").join(" "):typeof m[0][1]?.text=="string"?m[0][1].text:"—";return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},v),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(C==="ok"?"":" "+C)+(n===!1?" rail":"")+(u.busy?" busy":""),...be(u.busy,u.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},x):e(E,null,e("div",{className:"cm-mm-title"},r(d.labelKey)),...g)))}const Ca=t=>{try{return window.localStorage?.getItem?.("cm.gw."+t)??""}catch{return""}},ts=(t,s)=>{try{window.localStorage?.setItem?.("cm.gw."+t,s)}catch{}};function as(t){const s=it(),{source:o,snapshot:a,state:n,wide:l,api:i}=t,r=K(W(n.config?.locale)),[u,d]=R(()=>({source:o.id,id:Ca(o.id)})),c=Te(i?()=>i.refreshGatewayQuota(o.id):null),m=se(n.config,"plan"),p=a.accounts.length>1,b=u.source===o.id?u.id:Ca(o.id),g=a.accounts.findIndex(D=>D.id===b),h=g>=0?g:Math.max(0,a.accounts.findIndex(D=>D.windows.length>0||D.credits!=null)),v=a.accounts[h]??a.accounts[0],N=v?.label||v?.id||"",C=D=>p?(Jt[D.provider]??D.provider)+" · ":"",x=p&&v?[v]:a.accounts,f=[];for(const D of x){if(f.length>=4)break;for(const G of D.windows){if(f.length>=4)break;const B=C(D)+(G.label||G.id||r("gatewaySourceUnknown"));f.push({win:G,name:B,view:Ge(B,G,m,r)})}D.windows.length===0&&D.credits!=null&&f.push({win:null,name:C(D)+(D.credits.unit||"credits"),text:(D.credits.used??"—")+" / "+(D.credits.limit??"—")})}f.length===0&&f.push({name:r("gatewayQuotaEmpty"),text:"—"});const S=f.some(D=>D.view?.level==="over")?"over":f.some(D=>D.view?.level==="warn")?"warn":"ok",y=f.map(D=>{if(D.text!=null)return D.name+" "+D.text;const G=ze(D.win,r);return D.name+" "+lt(D.view.label,m,r)+(G?" · "+G:"")});a.fetchedAt>0&&y.push(r("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()})),y.push(...ye(r,c));const A=[p&&N?`${o.label||o.id} (${h+1}/${a.accounts.length} · ${N})`:o.label||o.id,...y].join(`
|
|
6
|
-
`),L=f.map((D,G)=>D.text!=null?e("div",{key:G,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},D.name),e("span",{className:"cm-mm-text cm-num"},D.text)):e(E,{key:G},D.view.row)),M=D=>{if(!D.key||D.key==="Enter"||D.key===" "){D.stopPropagation(),D.preventDefault?.();const G=a.accounts[(h+1)%a.accounts.length];ts(o.id,G.id),d({source:o.id,id:G.id})}},j=p?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:N||h+1}),onClick:M,onKeyDown:M,role:"button",tabIndex:0},`${h+1}/${a.accounts.length} ⇄`):null,k=p?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),j):e("div",{className:"cm-mm-title"},o.label||o.id),H=p&&N?e("div",{className:"cm-gw-sub"},N):null,de=e(E,null,k,H,...L),we=f.filter(D=>D.view).map(D=>D.view.label).filter(D=>D!==null),Se=we.length>0?we.slice(0,2).map(D=>D+"%").join(" "):f[0].text??"—",O=e("div",{className:"cm-bbox-rail cm-num"},Se);return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},A),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(S==="ok"?"":" "+S)+(l===!1?" rail":"")+(c.busy?" busy":""),...be(c.busy,c.run)},l===!1?e(E,null,O,j):de))}function ns(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],l=[];for(const i of s.gatewayQuotas?.sources??[]){if(i.enabled===!1||i.display!=="sidebar"&&i.display!=="both")continue;const r=n.find(u=>u.id===i.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||l.push(e(as,{source:i,snapshot:r,state:t,wide:o,api:a}))}return l}const ss={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function os(t){const s=t.useCost?t.useCost(g=>g):void 0;Ot(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=R(null),[n,l]=R({}),i=s?.state,r=t.api;if(!i)return null;const u=i.config,d=u.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(d.enabled!==!0)return null;const c=K(W(u?.locale)),m=[];if(d.budget!==!1){const g=u.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const h=Number(u.exchangeRate),N=(i.budgetUsed??(g.period==="day"?z(i.today,u):g.period==="all"?z(i.total,u):z(i.month,u)))*(Number.isFinite(h)&&h>0?h:1),C=Math.max(0,Number(g.amount)||0);if(C>0){const x=Math.min(999,N/C*100),f=x>=100?"over":x>=80?"warn":"ok";m.push({key:"budget",label:c("budgetShort"),level:f,tip:c("budgetOf",{period:c(Ie[g.period]??"periodMonth")})+" · "+c("usedOf",{used:ce(N,u),amount:ce(C,u)})+" · "+x.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(pe(Math.min(100,x),se(u,"budget")).width)}]})}}}if(d.go!==!1){const g=i.goQuota;if(u?.goQuota?.enabled!==!1&&g?.status==="ok"){const h=u.goQuota.main==="weekly"||u.goQuota.main==="monthly"?u.goQuota.main:"rolling",v=h==="rolling"?g.rolling:h==="weekly"?g.weekly:g.monthly;if(v!==null&&typeof v=="object"&&typeof v.percent=="number"){const N=Math.max(0,Math.min(100,Math.round(Number(v.percent)||0))),C=N>=100?"over":N>=80?"warn":"ok",x=typeof v.resetsAt=="string"&&v.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(v.resetsAt).toLocaleString()}):"";m.push({key:"go",label:"Go "+c(h==="rolling"?"goShortRolling":h==="weekly"?"goShortWeekly":"goShortMonthly"),level:C,tip:"Go: "+N+"%"+x,segs:[{name:"main",pct:Math.round(pe(N,se(u,"go")).width)}]})}}}if(d.plans!==!1)for(const g of Ee){const h=i.codingPlans?.[g.id];if(u.codingPlans?.[g.id]?.enabled!==!0||!h||h.status!=="ok")continue;const v=h.windows!==null&&typeof h.windows=="object"?h.windows:{},N=Object.entries(v);if(N.length===0)continue;const C=ss[g.id]??g.id,x=[],f=[];let S=0,y=0;for(const[T,A]of N){const L=Dt(T,c),M=typeof A?.resetsAt=="string"&&A.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(A.resetsAt).toLocaleString()}):"",j=A!==null&&typeof A=="object"&&typeof A.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(A.percent)||0))):null;if(f.push(L+" "+(j===null?typeof A?.text=="string"?A.text:"—":j+"%")+M),j===null){x.push({name:T,pct:null,text:typeof A?.text=="string"?A.text:"—"});continue}y>=2||(y+=1,x.push({name:T,pct:Math.round(pe(j,se(u,"plan")).width)}),S=Math.max(S,j>=100?2:j>=80?1:0))}h.fetchedAt>0&&f.push(c("goQuotaFetchedAt",{time:new Date(h.fetchedAt).toLocaleTimeString()})),x.length!==0&&m.push({key:g.id,label:C,level:["ok","warn","over"][S],tip:f.join("; "),segs:x})}const p=u.codexQuotaEnabled===!0&&$.status==="ok"?$.windows.weekly??null:null;if(p!==null&&typeof p.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(p.percent)||0))),h=typeof p.resetsAt=="string"&&p.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(p.resetsAt).toLocaleString()}):"";m.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+h,segs:[{name:"weekly",pct:Math.round(pe(g,se(u,"plan")).width)}]})}if(m.length===0)return null;const b=g=>{o!==null||!r||(a(g),l(h=>({...h,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?Tt(!0,u.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(h=>{l(v=>({...v,[g]:h?.message??String(h)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},m.map(g=>{const h=o===g.key,v=n[g.key],N=[e("span",{className:"cm-qlabel",key:"l"},g.label)];h?N.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((x,f)=>{f>0&&N.push(e("span",{className:"cm-qsep",key:"sep"+f,"aria-hidden":"true"})),x.pct===null?N.push(e("span",{className:"cm-qtext",key:x.name},x.text)):N.push(e("span",{className:"cm-qseg",key:x.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:x.pct+"%"}})),e("span",null,x.pct+"%")))});const C=[g.tip];return!h&&r&&C.push(c("clickToRefresh")),h&&C.push(c("refreshing")),v&&C.push("⚠ "+c("balanceRefreshFailed",{message:v})),e(Z,{key:g.key,label:C.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?be(h,()=>b(g.key)):{}},N))}))}const Aa="dsh-cost-meter:simple-guide-dismissed";function Bt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Aa)==="1"}catch{return!1}}function ls(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Pe(!1),[a,n]=R(!1),[l,i]=R(!1),[r,u]=R(!1),d=s?.state?.config;if(!d||r||Bt(d))return null;const c=K(W(d.locale)),m=()=>{u(!0);try{window.localStorage.setItem(Aa,"1")}catch{}},p=async b=>{if(!o.current){o.current=!0,n(!0),i(!1);try{if((await t.api.updateConfig({sidebarSimple:b,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==b)throw new Error;m()}catch{i(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),m())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:m},"×")),e("p",null,c("sidebarSimpleBody")),l?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>p(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>p(!0)},c("sidebarSimpleOn"))))}function is(t){const s=t.useCost?t.useCost(r=>r):void 0,o=Pe(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Bt(n)||n.quotaStrip?.promptSeen===!0)return null;const l=K(W(n?.locale)),i=r=>{if(o.current===!0)return;o.current=!0;const u=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...u,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":l("quotaStripGuideTitle")},e("h4",null,l("quotaStripGuideTitle")),e("p",null,l("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>i(!1)},l("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>i(!0)},l("quotaStripGuideOn"))))}const Ma="dsh-cost-meter:balance-click-hint-seen",rs=()=>{try{return window.localStorage.getItem(Ma)==="1"}catch{return!1}},cs=()=>{try{window.localStorage.setItem(Ma,"1")}catch{}};function ds(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Pe(!1),[a,n]=R(!1),[l]=R(rs),i=s?.state;if(!i)return null;const r=i.config,u=r.balance?.display==="sidebar"||r.balance?.display==="both",d=(r?.customBalances??[]).some(b=>b?.enabled===!0&&(b.display==="sidebar"||b.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Ee.some(b=>{const g=r.codingPlans?.[b.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||l||r.balance?.clickHintSeen===!0||!u&&!d&&!c||!Bt(r)||r.quotaStrip?.promptSeen!==!0)return null;const m=K(W(r?.locale)),p=()=>{o.current!==!0&&(n(!0),o.current=!0,cs(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":m("balanceClickGuideTitle")},e("h4",null,m("balanceClickGuideTitle")),e("p",null,m("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:p},m("balanceClickGuideOk"))))}function Rt(t,s,o){return s.sidebarTodayMetric==="tokens"?I(["input","output","cacheRead","cacheWrite","reasoning"].reduce((a,n)=>a+(Number(t?.[n])||0),0))+" "+o("tokensUnit"):Y(z(t,s),s)}function Lt(t){const{state:s,wide:o}=t,a=s.today,n=s.config,l=K(W(n?.locale)),i=Rt(a,n,l),r=n.budget??{enabled:!1,amount:100,period:"month"},u=Number(n.exchangeRate),c=(s.budgetUsed??(r.period==="day"?z(s.today,n):r.period==="all"?z(s.total,n):z(s.month,n)))*(Number.isFinite(u)&&u>0?u:1),m=Math.max(0,Number(r.amount)||0),p=m>0?Math.min(999,c/m*100):null,b=p===null?"ok":p>=100?"over":p>=80?"warn":"ok";if(r.enabled===!0){const v=z(a,n)*(Number.isFinite(u)&&u>0?u:1),N=m>0?Math.min(999,v/m*100):null,C=[l("budgetOf",{period:l(Ie[r.period]??"periodMonth")}),l("usedOf",{used:ce(c,n),amount:ce(m,n)})+" · "+(p===null?"—":p.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[n.sidebarTodayMetric==="tokens"?l("today")+" "+i:l("todayShare",{amount:i,pct:N===null?"—":N.toFixed(1)+"%"})],l("monthTotal",{month:Y(z(s.month,n),n),total:Y(z(s.total,n),n)})].join("; ");if(t.summary===!0)return e(Z,{label:C,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(b==="ok"?"":" "+b),tabIndex:0},e("span",null,l("todayBudget",{period:l(Ie[r.period]??"periodMonth")})),e("span",{className:"cm-num"},i+" / "+ce(m,n))));const x=xa(s,n,l);return e(Z,{label:C,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(b==="ok"?"":" "+b)+(o?"":" rail")},o?x.body:e("div",{className:"cm-bbox-rail cm-num"},x.rail)))}const g=[n.sidebarTodayMetric==="tokens"?l("todayTokensTitle"):l("todayCostTitle"),l("callsTokens",{calls:a.calls,input:I(a.input),cache:I(a.cacheRead+a.cacheWrite),output:I(a.output)}),l("monthCost",{amount:Y(z(s.month,n),n)}),l("totalCost",{amount:Y(z(s.total,n),n)})].join("; ");return e(Z,{label:g,side:"right",delayMs:300},e(E,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(E,null,l("today")," ",e("span",{className:"cm-num"},i)):e(tt,{size:16})),o?ot(s,n,l):null))}function us(t){const s=t.useCost?t.useCost(M=>M):void 0;Ot(s?.state?.config?.codexQuotaEnabled===!0&&s?.state?.config?.codexQuotaSidebar!==!1);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}ua(t,o);const a=s?.state,n=!!t.wide;if(!a)return null;const l=a.config,i=K(W(l?.locale)),r=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,d=Mt(a,l).length>0,c=r&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",m=d&&l.balance?.showProgressBar===!0,p=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",b=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[p]!==null,g=Ee.map(M=>M.id).filter(M=>{const j=l.codingPlans?.[M];if(j?.enabled!==!0||j.display!=="sidebar"&&j.display!=="both")return!1;const k=a.codingPlans?.[M];if(k?.status!=="ok")return!1;const H=k.windows!==null&&typeof k.windows=="object"?k.windows:{};return Object.keys(H).length>0}),h=g.length>0,v=ns(a,l,n,t.api),N=l.codexQuotaEnabled===!0&&l.codexQuotaSidebar!==!1&&$.status==="ok"&&$.windows.weekly!==null,C=(l.budget??{}).enabled===!0,x=l.sidebar!==!1&&l.hideTodayCost!==!0,f=l.sidebarModels?.enabled===!0;if(!f&&!r&&!d&&!b&&!h&&!N&&!C&&!x&&v.length===0)return null;const S=l.sidebarSimple===!0,y=!S&&n&&l.sidebarStyle==="compact",T=S&&n&&x&&C,A=[];T?A.push(e(Lt,{state:a,wide:n,summary:!0})):S&&n&&x&&A.push(e("div",{className:"cm-simple-summary"},e("span",null,i("today")),e("span",{className:"cm-num"},Rt(a.today,l,i)))),c?A.push(e(Bn,{state:a,wide:n,api:t.api})):r&&A.push(e(Dn,{state:a,wide:n,api:t.api})),m?A.push(e(Ln,{state:a,wide:n,api:t.api})):d&&A.push(e(qn,{state:a,wide:n,api:t.api}));const L=A.length;if(h&&A.push(...g.map(M=>M==="minimax"?e(Kn,{state:a,wide:n,api:t.api}):e(es,{id:M,state:a,wide:n,api:t.api}))),A.push(...v),N&&A.push(e(Xn,{state:a,wide:n,api:t.api})),b&&C&&n&&!S){const M=va(a,l,i),j=xa(a,l,i),k=M.level==="over"||j.level==="over"?"over":M.level==="warn"||j.level==="warn"?"warn":"ok";A.push(e("div",{className:"cm-bbox cm-bbox-pair"+(k==="ok"?"":" "+k)},e("div",{className:"cm-bbox-section"+(M.level==="ok"?"":" "+M.level)},M.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(j.level==="ok"?"":" "+j.level)},j.body)))}else b&&A.push(e(zn,{state:a,wide:n})),C&&!T&&A.push(e(Lt,{state:a,wide:n}));return!C&&x&&!(S&&n)&&A.push(e(Lt,{state:a,wide:n})),S&&n&&x&&A.push(ot(a,l,i)),n||A.push(_n(a,l,i)),f&&A.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?L:A.length,0,e(ms,{key:"models",state:a,wide:n})),e("div",{...S?{tabIndex:0,role:"region","aria-label":i("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(y?" compact":"")+(S?" simple":"")},...A)}const Et={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Pa="dsh-cost-meter:models-open";function Ta(t,s,o){return Ra(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:jt(a.key),cost:z(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function ms({state:t,wide:s}){const o={...Et,...t.config.sidebarModels},a=K(W(t.config.locale)),n=()=>{try{const N=o.remember?window.localStorage.getItem(Pa):null;if(N!==null)return N==="1"}catch{}return o.defaultOpen},[l,i]=R(n),[r,u]=R(o.period);X(()=>u(o.period),[o.period]),X(()=>i(n()),[o.defaultOpen,o.remember]);const d=Ta(t,r,a),c=d.reduce((N,C)=>N+C.cost,0),m=N=>Y(N,t.config),p=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+m(c)+" · "+a("modelsCount",{n:d.length}),b=o.summary==="top"&&d.length?d[0].label+" "+m(d[0].cost):p,g=o.summary==="top"&&d.length?e(E,null,e("span",{className:"cm-bal-label"},d[0].label),e("span",{className:"cm-bal-amt"},m(d[0].cost))):e("span",{className:"cm-bal-label"},b),h=()=>{i(!l);try{o.remember&&window.localStorage.setItem(Pa,l?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:b+" · "+p},s?g:e(tt,{size:16}));const v=d.slice(0,o.topN);return d.length>o.topN&&v.push(d.slice(o.topN).reduce((N,C)=>{for(const x of["cost","input","output","cacheRead","cacheWrite"])N[x]+=C[x];return N},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(l),title:p,onClick:h},e("span",{className:"cm-caret"+(l?" open":"")}),g),l?e(E,null,e("div",{className:"cm-buttons"},["today","history"].map(N=>e("button",{key:N,type:"button",className:"cm-mstats-tab"+(r===N?" active":""),"aria-pressed":r===N,onClick:()=>u(N)},a(N==="today"?"modelStatsToday":"modelStatsHistory")))),v.length?v.map(N=>e("div",{key:N.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:N.label},N.label),e("span",{className:"cm-num cm-bal-amt"},m(N.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?N.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?N.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+I(N.input)+" · "+a("modelStatsCache")+" "+I(N.cacheRead+N.cacheWrite)+" · "+a("modelStatsOutput")+" "+I(N.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function ps({draft:t,setDraft:s,t:o}){const a={...Et,...t?.sidebarModels},n=(i,r)=>{t&&s({...t,sidebarModels:{...a,[i]:r}})},l=(i,r)=>e("div",{className:"cm-field",key:i},e("label",null,o("models_"+i)),e("select",{className:"cm-input",value:a[i],onChange:u=>n(i,u.target.value)},r.map(([u,d])=>e("option",{key:u,value:u},o(d)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(i=>e("label",{key:i,className:"cm-check"},e("input",{type:"checkbox",checked:a[i],onChange:r=>n(i,r.target.checked)}),o("models_"+i))),l("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),l("summary",[["total","modelsTotal"],["top","modelsTop"]]),l("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(i=>e("div",{key:i,className:"cm-field"},e("label",null,o("models_"+i)),ae({value:a[i]},r=>n(i,Math.max(i==="topN"?1:10,Math.min(i==="topN"?10:60,Math.floor(r))))))))}function rt(t){return e("div",{className:"cm-card"},e("p",{className:"cm-card-title"},t.title),e("div",{className:"cm-card-value cm-num"},t.value),e("p",{className:"cm-card-sub"},t.sub))}function Oa(t){const[s,o]=R(null),[a,n]=R(""),[l,i]=R(0);return X(()=>{let r=!0;return n(""),t.api.loadStatistics().then(u=>{r&&o(()=>u)},u=>{r&&n(String(u.message??u))}),()=>{r=!1}},[t.api,l]),s?e(s,{...t,formatMoneyUsd:Y,formatTokens:I}):e("p",{role:a?"alert":"status"},a||"…",a?e("button",{className:"cm-btn",onClick:()=>i(r=>r+1)},"↻"):null)}function fs(t){const s=t.useCost?.(c=>c),o=s?.state,[a,n]=R(null),l=Be.useRef(null),i=o?.config[t.entryPosition==="header"?"hideSessionCostHeader":"hideSessionCostDock"]===!0,r=!i&&!!t.sessionId&&a===t.sessionId;if(X(()=>{r&&l.current?.showModal()},[r]),X(()=>{n(null)},[t.sessionId,i]),!t.sessionId||i)return null;const u=W(o?.config.locale)==="en",d=u?"Conversation cost details":"本会话费用明细";return e(E,null,e("button",{type:"button",className:"cm-btn cm-stat-entry cm-stat-"+(t.entryPosition||"dock"),title:d,"aria-label":d,"aria-haspopup":"dialog",onClick:()=>n(t.sessionId)},u?"Cost details":"费用明细"),r?e("dialog",{ref:l,"aria-label":d,onCancel:()=>n(null),style:{width:"min(1160px,94vw)",maxHeight:"90vh",padding:24,borderRadius:16,border:"1px solid var(--dsw-alias-border-l1)",color:"var(--dsw-alias-label-primary)",background:"var(--dsw-alias-bg-base,#fff)"}},e("button",{type:"button",className:"cm-btn",autoFocus:!0,"aria-label":u?"Close":"关闭",onClick:()=>n(null),style:{float:"right"}},"×"),o?e(Oa,{key:t.sessionId,state:o,api:t.api,sessionId:t.sessionId}):e("p",{role:s?.error?"alert":"status"},s?.error||(u?"Loading…":"加载中…"),e("button",{type:"button",className:"cm-btn",onClick:()=>t.api.reload()},u?"Retry":"重试"))):null)}function bs({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=d=>Y(z(d,a),a),l=d=>s("callsTokens",{calls:d.calls,input:I(d.input),cache:I(d.cacheRead+d.cacheWrite),output:I(d.output)}),i=(d,c)=>({calls:d.calls+c.calls,input:d.input+c.input,output:d.output+c.output,cacheRead:d.cacheRead+c.cacheRead,cacheWrite:d.cacheWrite+c.cacheWrite,cost:z(d,a)+c.cost,apiCost:z(d,a)+c.cost}),r=(d,c)=>e("tr",{key:d},e("td",null,d),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},I(c.input)),e("td",{className:"num"},I(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},I(c.output)),e("td",{className:"num"},n(c))),u=d=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,d)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((d,c)=>{const m=i(t[d],o.combined[d]);return e(rt,{key:d,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(m),sub:l(m)})})),...o.sources.map(d=>e("details",{key:d.source},e("summary",null,d.source+" · "+s("cardToday")+" "+n(d.today)+" · "+s("cardMonth")+" "+n(d.month)+" · "+l(d.today)),u(["today","month","total"].map((c,m)=>r(s(["cardToday","cardMonth","cardTotal"][m]),d[c]))),e("p",{className:"cm-note"},s("externalHistory")),u(d.history.map(c=>r(c.date,c))))))}const Le=(t,s,o)=>e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(t),onClick:s},e("span",{className:"cm-caret"+(t?" open":"")}),e("h3",{className:"cm-h"},o));function gs(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,l]=R(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(n,()=>l(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(hs,{state:s,api:o})):null)}function hs(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,l]=R(null),[i,r]=R({}),[u,d]=R(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const m=b=>{if(n===b){l(null);return}l(b),!(i[b]!==void 0||u.has(b))&&(d(g=>{const h=new Set(g);return h.add(b),h}),o.getDaySessions(b).then(g=>r(h=>({...h,[b]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[b]:"error"}))).finally(()=>d(g=>{const h=new Set(g);return h.delete(b),h})))},p=b=>b.map(g=>e("tr",{key:g.id},qt(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},I(g.input)),e("td",{className:"num"},I(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},I(g.output)),e("td",{className:"num"},Y(z(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(b=>{const g=e("tr",{key:b.date,className:"cm-row-click",onClick:()=>m(b.date)},e("td",null,(n===b.date?"▾ ":"▸ ")+b.date),e("td",{className:"num"},String(b.calls)),e("td",{className:"num"},I(b.input)),e("td",{className:"num"},I(b.cacheRead+b.cacheWrite)),e("td",{className:"num"},I(b.output)),e("td",{className:"num"},Y(z(b,s.config),s.config)));if(n!==b.date)return[g];const h=i[b.date],v=u.has(b.date)&&h===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):h==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(h)||h.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,p(h)));return[g,e("tr",{key:b.date+"-sessions"},e("td",{colSpan:6},v))]}))))}function ys(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,l]=R(!1),[i,r]=R(100),[u,d]=R("cost-desc"),[c,m]=R(null),[p,b]=R(!1),[g,h]=R(!1),v=Be.useRef(0),N=(S,y)=>{const[T,A]=y==="recent"?["recent","desc"]:y.split("-"),L=++v.current;b(!0),h(!1),o.getTopSessions(S,T,A).then(M=>{L===v.current&&m(Array.isArray(M?.sessions)?M.sessions:[])}).catch(()=>{L===v.current&&h(!0)}).finally(()=>{L===v.current&&b(!1)})},C=()=>{l(S=>{const y=!S;return y&&c===null&&!p&&N(i,u),y})},x=S=>{r(S),(n||c!==null)&&N(S,u)},f=S=>{d(S),(n||c!==null)&&N(i,S)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(n,C,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:u,onChange:S=>f(S.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(i),onChange:S=>x(Number(S.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),p?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(S=>e("tr",{key:S.date+":"+S.id},e("td",null,S.date),qt(S,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(S.calls)),e("td",{className:"num"},I(S.input)),e("td",{className:"num"},I((S.cacheRead??0)+(S.cacheWrite??0))),e("td",{className:"num"},I(S.output)),e("td",{className:"num"},Y(z(S,s.config),s.config)))))))):null)}function ks(t){const{state:s}=t,o=K(W(s.config?.locale)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(l=>e("tr",{key:l.id},qt(l,n,o),e("td",{className:"num"},String(l.calls)),e("td",{className:"num"},I(l.input)),e("td",{className:"num"},I(l.cacheRead+l.cacheWrite)),e("td",{className:"num"},I(l.output)),e("td",{className:"num"},Y(z(l,s.config),s.config)))))))}function qt(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",l=a.length>0?a:n,i=a.length>0?a+" · "+t.id:t.id;return e("td",{title:i},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},l),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const ws={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function xs(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=o?.budget??l.budget,r=Number(l.exchangeRate),d=(s.budgetUsed??(i.period==="day"?z(s.today,l):i.period==="all"?z(s.total,l):z(s.month,l)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(i.amount)||0),m=i.enabled&&c>0?Math.min(999,d/c*100):null,p=m===null?"ok":m>=100?"over":m>=80?"warn":"ok",b=(v,N)=>{o!==null&&a({...o,budget:{...o.budget??l.budget,[v]:N}})},g=i.period==="custom"?i.customStart+" → "+(i.customEnd??n("periodDay")):null,h=i.enabled&&m!==null?n("budgetStatus",{period:n(Ie[i.period]??"periodMonth"),amount:ce(c,l),used:ce(d,l),pct:m.toFixed(1)})+(p==="over"?n("overLimit"):p==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:i.enabled===!0,onChange:v=>b("enabled",v.target.checked)}),e("span",null,n("enableBudget")))),i.enabled?e(E,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(p==="ok"?"":p),style:{width:(m===null?0:Math.min(100,m))+"%"}})),e("div",{className:"cm-budget-line"+(p==="over"?" over":"")+" cm-num"},h),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ae({value:i.amount},v=>b("amount",v))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:i.period,onChange:v=>b("period",v.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),i.period==="custom"?e(E,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:i.customStart??"",onChange:v=>b("customStart",v.target.value===""?null:v.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:i.customEnd??"",onChange:v=>b("customEnd",v.target.value===""?null:v.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function vs(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=(c,m)=>{o!==null&&a({...o,[c]:m})},r=o===null?l:{...l,...o},u=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),m=Date.now();if(Number.isFinite(c)&&m<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const p=r.peakWindows??[],b=at(m,p,r.peakHolidays);return b===null?n("offPeakActive"):b.holiday===!0?n("holidayAllOffPeak"):b.weekend===!0?n("weekendAllOffPeak"):b.inPeak?n("peakActive"):n("offPeakActive")})(),d=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(W(r.locale)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:u}):n("noPeakWindows",{status:u});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>i("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>i("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>i("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>i("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const m=Number(c.target.value);Number.isInteger(m)&&m>=1&&m<=30&&i("peakAlertAhead",m)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>i("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>i("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{i("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?ot(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},d),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>i("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ae(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const l=Number(n);Number.isFinite(l)&&l>=0&&s(l)}})}function It(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:l,t:i}=t,r=Ze(o),u=p=>{const b={...Ze(p)};if(Array.isArray(p.rateHistory)){const g=p.rateHistory.filter(h=>Date.parse(h.before)<=Date.now());g.length>0?b.rateHistory=g:delete b.rateHistory}return b},d=(p,b,g)=>{if(g===null){if(a){const T=u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),A={...T[p]??{}};delete A[b];const L={...T};Object.keys(A).length>0?L[p]=A:delete L[p],l({...n,prices:{...n.prices,default:L}});return}const x={...n.prices.models},f=u(x[s]??{cacheHit:0,cacheMiss:0,output:0}),S={...f[p]??{}};delete S[b];const y={...f};Object.keys(S).length>0?y[p]=S:delete y[p],x[s]=y,l({...n,prices:{...n.prices,models:x}});return}const h=Math.max(0,g);if(a){let f={...u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(p==="base")f[b]=h;else{const S={...f[p]??{},[b]:h};f={...f,[p]:S}}l({...n,prices:{...n.prices,default:f}});return}const v={...n.prices.models},N=u(v[s]??{cacheHit:0,cacheMiss:0,output:0});let C={...N};if(p==="base")C[b]=h;else{const x={...N[p]??{},[b]:h};C={...N,[p]:x}}v[s]=C,l({...n,prices:{...n.prices,models:v}})},c=()=>{const p={...n.prices.models};delete p[s],l({...n,prices:{...n.prices,models:p}})},m=(p,b)=>{const g=b==="base"?r:r[b]??null,h=b==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:b},e("span",null,p),ae({value:g?.cacheHit??null,emptyMode:h},v=>d(b,"cacheHit",v)),ae({value:g?.cacheMiss??null,emptyMode:h},v=>d(b,"cacheMiss",v)),ae({value:g?.output??null,emptyMode:h},v=>d(b,"output",v)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(E,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},i("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},i("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},i("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatCached")),e("span",null,i("flatInput")),e("span",null,i("flatOutput"))),m(i("tierBase"),"base"),m(i("tierOffPeak"),"offPeak"),m(i("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},i("datedPriceNote")):null)}const Da={deepseek:"DeepSeek",openai:"OpenAI",anthropic:"Anthropic",google:"Google Gemini",moonshot:"Moonshot (Kimi)","z-ai":"Z.ai / 智谱",xai:"xAI",alibaba:"阿里云百炼",minimax:"MiniMax",tencent:"腾讯混元",xiaomi:"小米",upstage:"Upstage",nvidia:"NVIDIA",mistral:"Mistral",meta:"Meta",meituan:"美团 LongCat","opencode-go":"OpenCode Go"};function Ns(t,s,o="USD"){if(t=Ze(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");o==="CNY"&&t.cny&&(t=t.cny);const a=l=>(o==="CNY"?"¥":"$")+String(l),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function Ss(t){const{state:s,draft:o,setDraft:a,t:n}=t,[l,i]=R(!1),[r,u]=R({}),d=s.priceCatalog;if(d===null||typeof d!="object")return null;const c=o?.prices??s.config.prices,m=o?.priceTableDisplay??s.config.priceTableDisplay??{},p=(y,T)=>{const A=m[y+":"+T];return typeof A=="boolean"?A:y==="deepseek"},b=(y,T,A)=>{o!==null&&a({...o,priceTableDisplay:{...m,[y+":"+T]:A}})},g=(y,T)=>y==="deepseek"?c.models?.[T]!==void 0:c.providers?.[y]?.models?.[T]!==void 0,h=(y,T,A)=>{if(o===null)return;const L=JSON.parse(JSON.stringify(A));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[T]:L}}});return}const M={...o.prices.providers??{}},j=M[y]??{};M[y]={...j,models:{...j.models??{},[T]:L}},a({...o,prices:{...o.prices,providers:M}})},v=(y,T)=>{if(o===null)return;if(y==="deepseek"){const M={...o.prices.models};delete M[T],a({...o,prices:{...o.prices,models:M}});return}const A={...o.prices.providers??{}},L=A[y];if(L!==void 0&&L.models!==void 0){const M={...L.models};delete M[T],A[y]={...L,models:M},a({...o,prices:{...o.prices,providers:A}})}},N=Object.keys(d).sort((y,T)=>y==="deepseek"?-1:T==="deepseek"?1:y.localeCompare(T)),C=y=>Object.values(d[y]).reduce((T,A)=>T+Object.keys(A).length,0),x=new Set(Object.values(d.deepseek??{}).flatMap(y=>Object.keys(y))),f=Object.keys(c.models??{}).filter(y=>!x.has(y)).sort(),S=(y,T,A)=>{const L=g(y,T),M=p(y,T),j=L?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:M,onChange:k=>b(y,T,k.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(L&&!M&&o!==null){const k=y==="deepseek"?e(It,{key:T,modelId:T,entry:c.models[T],isDefault:!1,draft:o,setDraft:a,t:n}):e(Ea,{key:T,provider:y,modelId:T,entry:c.providers?.[y]?.models?.[T],draft:o,setDraft:a,t:n});return e("div",{key:T,className:"cm-catalog-mounted"},j,k)}return e("div",{key:T,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},T),e("span",{className:"cm-catalog-price"},Ns(A,n,y==="deepseek"||A?.cny?c.currency:"USD")),L?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,j,e("button",{className:"cm-btn small",disabled:!L&&A?.unpriced===!0,onClick:()=>L?v(y,T):h(y,T,A)},n(L?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>i(y=>!y)},n(l?"catalogCollapse":"catalogOpen"))),l?e(E,null,e("p",{className:"cm-note"},n("catalogNote")),N.map(y=>{const T=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>u(A=>({...A,[y]:!T}))},e("span",null,(T?"▾ ":"▸ ")+(Da[y]??y)+" · "+C(y))),T?e(E,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(d[y]).sort().map(A=>e("div",{key:A},e("div",{className:"cm-catalog-family"},A),Object.keys(d[y][A]).sort().map(L=>S(y,L,d[y][A][L])))),y==="deepseek"&&f.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),f.map(A=>S("deepseek",A,null))):null):null)})):null)}const Ba=t=>t==="zen"?"go":t,jt=t=>{const s=t.indexOf(":");return s<=0?t:Ba(t.slice(0,s).toLowerCase())+t.slice(s)};function Ra(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],l=d=>Number.isFinite(Number(d))&&Number(d)>0?Number(d):0,i=(d,c,m)=>{if(!m||typeof m!="object")return;const p=d[c]??(d[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)p[g]+=l(m[g]);const b=c.indexOf(":");p.apiCost+=l(m.apiCost??(Qe(b>0?c.slice(0,b):"deepseek",b>0?c.slice(b+1):c,s)==="plan"?0:m.cost))},r=d=>{if(!d||typeof d!="object")return{};if(d.byProviderModel&&Object.keys(d.byProviderModel).length)return d.byProviderModel;if(d.byModel&&Object.keys(d.byModel).length)return Object.fromEntries(Object.entries(d.byModel).map(([m,p])=>[m.includes(":")?m:"deepseek:"+m,p]));const c={};for(const m of Array.isArray(d.sessions)?d.sessions:[])if(!(!m||typeof m!="object"))if(m.byProviderModel&&Object.keys(m.byProviderModel).length)for(const[p,b]of Object.entries(m.byProviderModel))i(c,p,b);else i(c,(m.provider||"deepseek")+":"+(m.model||"unknown"),m);return Object.keys(c).length?c:n.some(m=>l(d[m])>0)?{"deepseek:legacy":d}:{}};return(d=>{const c={},m=p=>{for(const[b,g]of Object.entries(p??{}))i(c,b,g)};if(d==="today")m(r(t.today));else{const p=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const b of t.history??[]){const g=Date.parse(b.date+"T00:00:00Z");g<=p&&g>=p-76896e5&&m(r(b))}}return Object.entries(c).map(([p,b])=>{const g=p.indexOf(":"),h=(g>0?p.slice(0,g):"deepseek").toLowerCase(),v=g>0?p.slice(g+1):p,N=b.input+b.output+b.cacheRead+b.cacheWrite+b.reasoning,C=b.cacheRead+b.input;return{label:p==="deepseek:legacy"?o("modelStatsLegacy"):h==="deepseek"||h===""?v:Ba(h)+":"+v,key:p,...b,tokens:N,cls:Qe(h,v,s),hitRate:C>0?b.cacheRead/C:null,cacheUnreported:bn(b),blended:N>0&&b.cost>0?b.cost/N*1e6:null,perUsd:b.cost>0?N/b.cost:null}}).filter(p=>p.tokens>0||p.cost>0)})(a).sort((d,c)=>c.cost-d.cost||c.tokens-d.tokens)}function Cs(t){const{state:s,config:o,t:a,initialTab:n,draft:l,setDraft:i}=t,[r,u]=R(n==="history"?"history":"today"),[d,c]=R(!1),m=Ra(s,o,a,r),p=f=>(Math.max(0,Math.min(1,f))*100).toFixed(1)+"%",b=m.reduce((f,S)=>Math.max(f,S.cost),0),g=m.reduce((f,S)=>Math.max(f,S.tokens),0),h=m.reduce((f,S)=>Math.max(f,S.perUsd??0),0),v=(f,S)=>e("button",{className:"cm-mstats-tab"+(r===f?" active":""),onClick:()=>u(f)},S),N=f=>f.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,C=f=>e("select",{className:"cm-input",title:a("billingClassLabel"),value:o.planBilling?.models?.[f.key]??"auto",disabled:l===null,onChange:S=>{const y={...l.planBilling?.models??{}};S.target.value==="auto"?delete y[f.key]:y[f.key]=S.target.value,i({...l,planBilling:{...l.planBilling,models:y}})}},e("option",{value:"auto"},a("billingClassAuto")),e("option",{value:"plan"},a("billingClassPlan")),e("option",{value:"api"},a("billingClassApi"))),x=(f,S,y,T,A)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:f},f,A??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+y,style:{width:p(S)}})),e("span",{className:"cm-mstats-val"},T));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(d,()=>c(!d),a("modelStatsTitle"))),d?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},v("today",a("modelStatsToday")),v("history",a("modelStatsHistory"))),m.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(E,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),m.map(f=>e(E,{key:"c:"+f.label},x(f.label,b>0?f.cost/b:0,"cost",Y(f.cost,o),e(E,null,N(f),C(f),f.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...m].sort((f,S)=>S.tokens-f.tokens).map(f=>e("div",{className:"cm-mstats-row",key:"t:"+f.label},e("span",{className:"cm-mstats-name",title:f.label},f.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:p(g>0?f.input/g:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:p(g>0?(f.cacheRead+f.cacheWrite)/g:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:p(g>0?(f.output+f.reasoning)/g:0)}})),e("span",{className:"cm-mstats-val"},I(f.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...m].sort((f,S)=>(S.hitRate??-1)-(f.hitRate??-1)).map(f=>e(E,{key:"h:"+f.label},x(f.label,f.hitRate??0,"hit",f.cacheUnreported?a("modelStatsHitUnreported"):f.hitRate===null?"—":(f.hitRate*100).toFixed(1)+"%",f.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...m].sort((f,S)=>(S.perUsd??-1)-(f.perUsd??-1)).map(f=>e(E,{key:"v:"+f.label},x(f.label,h>0?(f.perUsd??0)/h:0,"value",f.perUsd===null?"—":I(f.perUsd)+" tok/$"+(f.blended!==null?" · "+a("modelStatsBlended",{price:"$"+f.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function As(t,s){return t==="fiveHour"?s==="en"?"5-hour":"5 小时":t==="weekly"?s==="en"?"This week":"本周":t==="monthly"?s==="en"?"This month":"本月":t==="daily"?s==="en"?"Today":"当日":t}function Ms(t,s){if(t==="go")return"OpenCode Go";const o=Ee.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const La=["fiveHour","weekly","monthly","daily"];function Ps(t,s){const o=new Map,a=n=>{const l=new Date(n),i=r=>String(r).padStart(2,"0");if(s==="monthly")return l.getFullYear()+"-"+i(l.getMonth()+1);if(s==="weekly"){const r=new Date(l.getFullYear(),l.getMonth(),l.getDate()-(l.getDay()+6)%7);return r.getFullYear()+"-"+i(r.getMonth()+1)+"-"+i(r.getDate())}return l.getFullYear()+"-"+i(l.getMonth()+1)+"-"+i(l.getDate())};for(const n of Object.values(t??{}))for(const l of n??[]){if(l===null||typeof l!="object"||!(l.tokens>0)&&!(l.cost>0))continue;const i=a(Number(l.t1)||Number(l.t0)),r=o.get(i)??{key:i,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(l.tokens)||0,r.cost+=Number(l.cost)||0,r.pct+=Number(l.pct)||0,r.intervals+=1,o.set(i,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,l)=>n.key<l.key?-1:n.key>l.key?1:0)}function Ts(t){const{state:s,config:o,t:a}=t,[n,l]=R(!1),[i,r]=R("daily"),u=W(o?.locale),d=s?.planStats,c=d!=null&&typeof d.providers=="object"?d.providers:{},m=Object.keys(c).sort(),p=y=>Y(Number(y)||0,o??s?.config),b=y=>y.method==="none"||y.per1Tokens===null?"—":I(y.per1Tokens)+" tok · "+p(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":I(y.fullTokens)+" tok · "+p(y.fullCost),h=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),v=y=>{let T=h(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(T=a("planStatsMethodSampleAt",{method:T,time:new Date(Number(y.sampleAt)).toLocaleString(u==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(T+=" · "+a("planStatsConfidenceLow")),T},N=([y,T,A])=>e("tr",{key:T+":"+y},e("td",null,As(y,u)),e("td",{className:"num"},Math.round(A.percent*10)/10+"%"),e("td",{className:"num"},I(A.localTokens)+" tok · "+p(A.localCost)),e("td",{className:"num"},b(A)),e("td",{className:"num"},g(A)),e("td",{className:"num cm-plan-reset"},A.resetsAt.length>0?a("planStatsResets",{time:new Date(A.resetsAt).toLocaleString(u==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},v(A))),C=n?m.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,T])=>({winKey:y,list:T})):[],x=Ps(Object.fromEntries(C.map(y=>[y.winKey,y.list])),i),f=x.reduce((y,T)=>Math.max(y,T.fullTokens??0),0),S=(y,T)=>e("button",{key:y,className:"cm-mstats-tab"+(i===y?" active":""),onClick:()=>r(y)},T);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(n,()=>l(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},m.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(E,null,m.map(y=>{const T=c[y]?.windows??{},A=[...La.filter(L=>T[L]!==void 0).map(L=>[L,y,T[L]]),...Object.keys(T).filter(L=>!La.includes(L)).map(L=>[L,y,T[L]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},Ms(y,a),e("span",{className:"cm-plan-updated"},(()=>{const L=Number(c[y]?.generatedAt)||Number(d?.generatedAt)||0;return L>0?new Date(L).toLocaleTimeString(u==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,A.map(N))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},S("daily",a("planStatsDaily")),S("weekly",a("planStatsWeekly")),S("monthly",a("planStatsMonthly"))),x.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(E,null,[...x].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(f>0?(y.fullTokens??0)/f*100:0).toFixed(1)+"%"}})),e(Z,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":I(y.fullTokens),per1:y.per1Tokens===null?"—":I(y.per1Tokens),tokens:I(y.tokens),cost:p(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":I(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Ea(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:l,t:i}=t,r=m=>{const p={...n.prices.providers??{}},b=p[s]??{};p[s]={...b,models:m},l({...n,prices:{...n.prices,providers:p}})},u=(m,p)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}};b[o]={...b[o]??{},[m]:Math.max(0,p)},r(b)},d=(m,p)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}},g=b[o]??{};b[o]={...g,cny:{...g.cny,[m]:Math.max(0,p)}},r(b)},c=()=>{if(n===null)return;const m={...(n.prices.providers??{})[s]?.models??{}};delete m[o],r(m)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(E,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},i("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:c},i("unmountBtn")))),a?.unpriced===!0?null:e(E,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatInput")),e("span",null,i("flatCached")),e("span",null,i("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ae({value:a?.input??null,emptyMode:"ignore"},m=>u("input",m)),ae({value:a?.cachedInput??null,emptyMode:"ignore"},m=>u("cachedInput",m)),ae({value:a?.output??null,emptyMode:"ignore"},m=>u("output",m))),a?.cny?e("div",{className:"cm-price-row"},e("span",null,"CNY"),ae({value:a.cny.cacheMiss,emptyMode:"ignore"},m=>d("cacheMiss",m)),ae({value:a.cny.cacheHit,emptyMode:"ignore"},m=>d("cacheHit",m)),ae({value:a.cny.output,emptyMode:"ignore"},m=>d("output",m))):null))}const Ke=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Ut=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function Os(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r,u]=Ye(a,()=>o.refreshBalance()),d=s.balance,c=s.config,m=s.reconcile,p=(n?.balance??c.balance??{}).reconcile!==!1,b=v=>{n===null||typeof l!="function"||l({...n,balance:{...n.balance??c.balance??{},reconcile:v.target.checked}})},g=v=>Ne(v,c,d?.currency),h=d.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:g(d.totalBalance),granted:g(d.grantedBalance),toppedUp:g(d.toppedUpBalance),time:d.fetchedAt>0?new Date(d.fetchedAt).toLocaleTimeString():"—"}))):d.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:d.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:u,disabled:i},a(i?"refreshing":"refreshBalance"))),h,e("label",null,a("balanceApiKey")),e(De,{target:"balance",configured:d.keyConfigured,source:d.keySource,t:a,api:o,placeholder:"sk-…"}),e("p",{className:"cm-hint"},a("balanceKeyHint")),m!==void 0&&m.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+m.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:p,onChange:b}),a("reconcileLabel")),Ut(r))}function ct(t){const{name:s,enabled:o,saved:a,busy:n,open:l,statusNode:i,configNode:r,errorMsg:u,onToggle:d,onRefresh:c,onRemove:m,onToggleOpen:p,t:b}=t,g=r!=null;return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":b("enable")+": "+s,checked:o===!0,onChange:h=>d(h.target.checked)})),e("div",{className:"cm-quota-name"},g?Le(l===!0,p,s):e("h3",{className:"cm-h"},s)),m?e("button",{className:"cm-btn small",onClick:m},b("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:c,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?b("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?b("quotaRefreshReady"):b("refresh")},b(n===!0?"refreshing":"refresh"))),i,g&&l===!0?e("div",{className:"cm-collapse-body"},r):null,u!=null?e("div",{className:"cm-msg "+u.kind},u.text):null)}function Ye(t,s){const[o,a]=R(!1),[n,l]=R(null),i=Pe(!1);return[o,n,async()=>{if(!i.current){i.current=!0,a(!0),l(null);try{const u=await s();l({kind:u.ok?"ok":"err",text:u.message})}catch(u){l({kind:"err",text:t("syncFailed",{message:u?.message??String(u)})})}finally{i.current=!1,a(!1)}}}]}const Ds=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},qa=(t,s,o,a,n,l=s)=>{if(typeof o?.percent!="number")return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const i=Math.max(0,Math.min(100,Number(o.percent)||0)),r=pe(i,a),u=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),u?e("span",{className:"cm-go-reset"},u):null)};function Bs(t){const{state:s,api:o,t:a,entry:n,index:l,canRemove:i,onPatch:r,onRemove:u}=t,d=n.adapter==="aliyun",[c,m]=R(!1),p=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[b,g]=R(p),[h,v]=R(()=>(n.allowedHosts??[]).join(", ")),[N,C]=R({}),x=Pe(!1),f=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(B=>B.index===l)??null,T=n.enabled===!0,A=()=>{m(B=>!B)};X(()=>{c&&!x.current&&(g(p()),v((n.allowedHosts??[]).join(", ")),C({})),x.current=c},[c]);const L=(B,V)=>r({[B]:V}),M=(B,V)=>r({request:{...n.request??{},[B]:V}}),j=d?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(B=>typeof B=="string"?[...B.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(V=>V[1]):[]))],k=(B,V)=>{g(w=>({...w,[B]:V}));try{const w=B==="body",q=w&&!V.trim()?void 0:JSON.parse(V);if(!w&&(q===null||typeof q!="object"||Array.isArray(q)))throw new Error("invalid");if(B==="headers"&&Object.values(q).some(Q=>typeof Q!="string"))throw new Error("invalid");C(Q=>({...Q,[B]:""})),B==="extract"?L(B,q):M(B,w?q===void 0?void 0:V:q)}catch{C(w=>({...w,[B]:a("customBalanceInvalidJson")}))}},H=(B,V,w,q)=>!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(V)),q&&e("span",{className:"cm-hint"},a(q)),e("textarea",{className:"cm-input",rows:w,value:b[B],onChange:Q=>k(B,Q.target.value)}),N[B]?e("span",{className:"cm-hint err"},N[B]):null),de=B=>{v(B);const V=B.split(/[\s,;]+/).map(w=>w.trim()).filter(w=>w.length>0);L("allowedHosts",V)},[we,Se,O]=Ye(a,()=>(f.customBalances??[])[l]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(l)),D=y!==null&&y.status==="ok"?e(E,null,f.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(St,{segments:Nt(s,f,y,n),direction:se(f,"balance")}),e("div",{className:"cm-bal-line"},At(y,f,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:We(y.remaining,f,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),G=e(E,null,e("p",{className:"cm-note"},a(d?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:Fe(f,y,n)!=="USD",onChange:B=>L("convertToDisplayCurrency",B.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([B,V])=>e("div",{key:B,className:"cm-field"},e("label",null,a(V)),e("input",{className:"cm-input",value:n[B]??"",onChange:w=>L(B,w.target.value)}))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:B=>L("unit",B.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:B=>L("display",B.target.value)},...Ke(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ae({value:n.refreshMinutes??15},B=>L("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(B)))))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:B=>M("method",B.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:B=>M("url",B.target.value)})),H("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&H("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),j.length>0?e(E,null,!d&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),j.map(B=>e(De,{key:"cb-var-"+B,target:"customVar:"+B,configured:(s.customVarStatus?.[B]?.configured??!1)===!0,source:s.customVarStatus?.[B]?.source??"",t:a,api:o,placeholder:"{{"+B+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:h,placeholder:"api.example.com, relay.example.org",onChange:B=>de(B.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),H("extract","customBalanceExtract",8)));return e(ct,{name:`#${l+1} · `+(Ct(n,W(f?.locale))||a("customBalanceTitle")),enabled:T,saved:JSON.stringify(n)===JSON.stringify(f.customBalances?.[l])?f.customBalances[l]:null,busy:we,open:c,statusNode:D,configNode:G,errorMsg:Se,onToggle:B=>L("enabled",B),onRefresh:O,onRemove:i?u:null,onToggleOpen:A,t:a})}function Ia({config:t,draft:s,setDraft:o,t:a,api:n}){const l=s?.goQuota??t.goQuota,i=(r,u)=>{s&&o({...s,goQuota:{...l,[r]:u}})};return e(E,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,u])=>e("div",{key:r,className:"cm-field"},e("label",null,a(u)),e("select",{className:"cm-input",value:l[r],onChange:d=>i(r,d.target.value)},r==="display"?Ke(a):["rolling","weekly","monthly"].map((d,c)=>e("option",{key:d,value:d},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ae({value:l.refreshMinutes},r=>i("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function Rs(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r]=R(!1),u=s.goQuota,d=s.config,c=n?.goQuota?.enabled??d.goQuota?.enabled??!0,m=(f,S)=>{n!==null&&l({...n,goQuota:{...n.goQuota??d.goQuota,[f]:S}})},[p,b,g]=Ye(a,()=>o.refreshGoQuota()),h=d.goQuota?.main==="weekly"||d.goQuota?.main==="monthly"?d.goQuota.main:"rolling",v=[h,...["rolling","weekly","monthly"].filter(f=>f!==h)],N=f=>f==="rolling"?"goWindowRolling":f==="weekly"?"goWindowWeekly":"goWindowMonthly",C=f=>f==="rolling"?u.rolling:f==="weekly"?u.weekly:u.monthly,x=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},v.map(f=>qa(a,a(N(f)),C(f),se(d,"go"),f===h)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||a("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(ct,{name:a("goQuotaTitle"),enabled:c,saved:d.goQuota,busy:p,open:i,statusNode:x,errorMsg:b,configNode:e(Ia,{config:d,draft:n,setDraft:l,t:a,api:o}),onToggleOpen:()=>r(f=>!f),onToggle:f=>m("enabled",f),onRefresh:g,t:a})}const Ls=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Es(t){const{state:s,api:o,t:a,draft:n,setDraft:l,index:i}=t,r=s.config,d=(n??r).gatewayQuotas?.sources??[],c=d[i]??{},p=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(M=>M.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},b=Ls(c,s.customVarStatus),[g,h]=R(!1),[v,N,C]=Ye(a,()=>o.refreshGatewayQuota(c.id)),x=M=>{n!==null&&l({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:M}})},f=M=>x(d.map((j,k)=>k===i?{...j,...M}:j)),S=(M,j,k)=>e("div",{className:"cm-field"},e("label",null,M),e("input",{className:"cm-input",value:j??"",onChange:k})),y=(M,j)=>{const k=Ge(M?.label||M?.id||a("gatewaySourceUnknown"),M,se(r,"plan"),a);return e(E,{key:M?.id||j},k.row,M?.resetsAt?e("div",{className:"cm-note"},ze(M,a)):null)},T=(M,j)=>e("div",{key:M.id||j,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(M.used??"—")+" / "+(M.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(M.remaining??"—")+" remaining")),A=M=>M==null?null:e(E,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(M.used??"—")+" / "+(M.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(M.remaining??"—")+" remaining")),(M.packages??[]).map(T)),L=(M,j)=>e("div",{key:M.id||j,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Jt[M.provider]??M.provider??a("gatewaySourceUnknown"))+" · "+(M.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},M.status)),M.plan?e("div",{className:"cm-note"},M.plan):null,M.windows.length>0?e("div",{className:"cm-go-list"},M.windows.map(y)):null,A(M.credits),M.message?e("div",{className:"cm-note"},M.message):null);return e(ct,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(M=>M.id===c.id),busy:v,open:g,errorMsg:N,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(p.status??a("gatewaySourceUnknown"))+(p.serverVersion?" · "+p.serverVersion:"")+(p.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(p.fetchedAt).toLocaleTimeString()}):"")+(p.message?" · "+p.message:"")),configNode:e(E,null,e("div",{className:"cm-grid"},S(a("gatewaySourceLabel"),c.label,M=>f({label:M.target.value})),S(a("gatewaySourceBaseURL"),c.baseURL,M=>f({baseURL:M.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:M=>f({display:M.target.value})},...Ke(a))),S(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),M=>f({allowedHosts:M.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:M=>f({antigravityOnlyGemini:M.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),b?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+b,configured:s.customVarStatus?.[b]?.configured===!0,source:s.customVarStatus?.[b]?.source??"",t:a,api:o,placeholder:b})):null,p.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+p.unsupportedProviders.join(", ")):null,p.accounts.length>0?p.accounts.map(L):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:M=>f({enabled:M}),onRefresh:C,onRemove:()=>x(d.filter((M,j)=>j!==i)),onToggleOpen:()=>h(M=>!M),t:a})}const Ee=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function qs(t){const{state:s,api:o,t:a,draft:n,setDraft:l,planId:i,labelKey:r}=t,u=s.config,d=s.codingPlans??{},c=n?.codingPlans?.[i]??u.codingPlans?.[i]??{},m=d[i]??{status:"off",message:"",fetchedAt:0,windows:{}},p=c.enabled===!0,[b,g]=R(!1),[h,v,N]=Ye(a,()=>o.refreshCodingPlan(i)),C=(O,D)=>{if(n===null)return;const G=n.codingPlans??u.codingPlans??{};l({...n,codingPlans:{...G,[i]:{...G[i]??{},[O]:D}}})},[x,f]=R(""),[S,y]=R({}),T=O=>O?.rates!==null&&typeof O?.rates=="object"&&!Array.isArray(O.rates)?O.rates:{},A=["input","cachedInput","output"],L=O=>S[O]??T(c)[O]??{},M=O=>A.every(D=>Number.isFinite(Number(O[D]))&&Number(O[D])>0),j=(O,D,G)=>{if(n===null)return;const B={...L(O),[D]:String(G)};y(Q=>({...Q,[O]:B}));const V=A.every(Q=>String(B[Q]??"").trim()==="");if(!V&&!M(B))return;const w=n.codingPlans??u.codingPlans??{},q={...(w.qwen??{}).rates??{}};V?delete q[O]:q[O]=Object.fromEntries(A.map(Q=>[Q,Number(B[Q])])),l({...n,codingPlans:{...w,qwen:{...w.qwen??{},rates:q}}})},k=O=>{n!==null&&y(D=>({...D,[O]:D[O]??T(c)[O]??{}}))},H=O=>{if(n===null)return;y(B=>{const V={...B};return delete V[O],V});const D=n.codingPlans??u.codingPlans??{},G={...(D.qwen??{}).rates??{}};delete G[O],l({...n,codingPlans:{...D,qwen:{...D.qwen??{},rates:G}}})},de=m.windows!==null&&typeof m.windows=="object"?m.windows:{},we=p===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):m.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(de).length>0?i==="minimax"&&(_e(de).five!=null||_e(de).seven!=null)?e(Sa,{five:_e(de).five,seven:_e(de).seven,fetchedAt:m.fetchedAt,t:a,wide:!0,direction:se(u,"plan")}):Object.entries(de).map(([O,D])=>qa(a,O.replace(/_/g," "),D,se(u,"plan"),!1,O)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:m.fetchedAt>0?new Date(m.fetchedAt).toLocaleTimeString():"—"}))):m.status==="error"?e("div",{className:"cm-bal-line err"},m.message||a("unknownError")):m.status==="off"&&m.message?e("p",{className:"cm-note"},m.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),Se=e(E,null,i==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:O=>C("baseUrl",O.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,i==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:O=>C("quotaSource",O.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:i==="minimax"?"both":"settings",onChange:O=>C("display",O.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),i!=="scnet"&&(i!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ae({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},O=>{C("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(O))))})):null,i==="scnet"||i==="qwen"&&(c.quotaSource??"local")==="local"?e(E,null,e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:i==="qwen"?5e5:24e4,onChange:O=>{const D=Number(O.target.value);Number.isFinite(D)&&D>0&&C("planCredits",Math.floor(D))}})),e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:O=>C("planStart",O.target.value)})),i==="qwen"?e(E,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(T(c)),...Object.keys(S)])].sort().map(O=>e("div",{key:O,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},O),A.map(D=>e("input",{key:D,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:L(O)[D]??"",placeholder:a("qwenRate_"+D),"aria-label":O+" · "+a("qwenRate_"+D),onChange:G=>{const B=G.target.value;j(O,D,B)}})),e("button",{className:"cm-btn small",onClick:()=>H(O)},a("overrideRemove")),O in S&&!M(L(O))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:x,onChange:O=>f(O.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const O=x.trim();O.length!==0&&(k(O),f(""))},disabled:x.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(i==="qwen"?"qwenLocalNote":"scnetLocalNote"))):i==="qwen"?null:i==="volcengine"?e(E,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(E,null,e("div",{className:"cm-field"},e("label",null,i==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+i,configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:i==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(ct,{name:a(r),enabled:p,saved:u.codingPlans?.[i],busy:h,open:b,errorMsg:v,statusNode:we,configNode:Se,onToggle:O=>C("enabled",O),onRefresh:N,onToggleOpen:()=>g(O=>!O),t:a})}function Is(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,i=s.config,r=n??i,u=r.codingPlans??{},d=r.gatewayQuotas?.sources??[],c=n?.customBalances??i.customBalances??[],m=x=>{n!==null&&l({...n,customBalances:x,...x.length===0?{customBalance:{...i.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},p=Pe({next:0,keys:[]}).current;for(;p.keys.length<c.length;)p.keys.push(p.next++);p.keys.length=c.length;const b=x=>{p.keys.splice(x,1),m(c.filter((f,S)=>S!==x))},g=(x,f)=>m(c.map((S,y)=>y===x?{...S,...f}:S)),h=(x="custom")=>{c.length>=8||m([...c,{...x==="aliyun"?{adapter:x}:{},enabled:!1,label:x==="aliyun"?"千问 / 阿里云":"",labelEn:x==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:x==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:x==="aliyun"?"https://business.aliyuncs.com/":"",method:x==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},v=()=>{d.length>=4||n===null||l({...n,gatewayQuotas:{...n.gatewayQuotas??i.gatewayQuotas??{},sources:[...d,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:gt,allowedHosts:[],allowInsecureHttp:!1}]}})},N=[...d.map((x,f)=>({kind:"gateway",key:"gw-"+(x.id??f),index:f,enabled:x.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Ee.map(x=>({kind:"plan",key:"plan-"+x.id,planId:x.id,labelKey:x.labelKey,enabled:u[x.id]?.enabled===!0})),...c.map((x,f)=>({kind:"custom",key:"cb-"+p.keys[f],index:f,enabled:x.enabled===!0}))],C=x=>x.kind==="plan"?e(qs,{key:x.key,planId:x.planId,labelKey:x.labelKey,state:s,api:o,t:a,draft:n,setDraft:l}):x.kind==="go"?e(Rs,{key:x.key,state:s,api:o,t:a,draft:n,setDraft:l}):x.kind==="gateway"?e(Es,{key:x.key,index:x.index,state:s,api:o,t:a,draft:n,setDraft:l}):e(Bs,{key:x.key,state:s,api:o,t:a,entry:c[x.index],index:x.index,canRemove:!0,onPatch:f=>g(x.index,f),onRemove:()=>b(x.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ds(N).map(C)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:v,disabled:d.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>h(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>h("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const js=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ja=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function Ht(t){const s=t.useCost?t.useCost(f=>f):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=W(a?.locale),l=t.t??K(n),i=Array.isArray(o.history)?o.history:[];if(i.length===0)return e("div",null,e("h3",{className:"cm-h"},l("usageTitle")),e("p",{className:"cm-empty"},l("usageEmpty")));const r=o.meta?.dayKey??"",u=new Map(i.map(f=>[f.date,f])),d=f=>{const S=y=>String(y).padStart(2,"0");return f.getFullYear()+"-"+S(f.getMonth()+1)+"-"+S(f.getDate())},c=new Date;c.setHours(0,0,0,0);const m=new Date(c);m.setDate(m.getDate()+(6-(c.getDay()+6)%7));const p=26,b=[],g=[];let h=-1;for(let f=p-1;f>=0;f-=1){for(let y=0;y<7;y+=1){const T=new Date(m);T.setDate(T.getDate()-(f*7+(6-y)));const A=u.get(d(T));b.push(A!==void 0?{day:A,tokens:ja(A)}:{day:{date:d(T)},tokens:0})}const S=new Date(m);S.setDate(S.getDate()-(f*7+6)),g.push(S.getMonth()!==h?n==="en"?js[S.getMonth()]:String(S.getMonth()+1)+"月":""),h=S.getMonth()}const v=Math.max(...b.map(f=>f.tokens),1),N=f=>{const S=f/v;return S<.25?1:S<.5?2:S<.75?3:4},C=f=>{const{day:S,tokens:y}=f,T="cm-ug-cell"+(y>0?" l"+N(y):"")+(S.date===r?" today":""),A=l("usageDay",{date:S.date,tokens:I(y),input:I(S.input??0),cache:I((S.cacheRead??0)+(S.cacheWrite??0)),output:I(S.output??0),calls:S.calls??0,cost:Y(z(S,a),a)});return e(Z,{key:S.date,label:A,side:"top",delayMs:200},e("div",{className:T}))},x=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},l("usageTitle")),e("div",{className:"cm-ug-total"},l("usageTotal",{tokens:I(ja(x)),input:I(x.input??0),cache:I((x.cacheRead??0)+(x.cacheWrite??0)),output:I(x.output??0),calls:x.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+p+",1fr)"}},b.map(C)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+p+",1fr)"}},g.map((f,S)=>e("span",{key:"m"+String(S),className:"cm-ug-monthc"},f))))}function Us(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.api,a=s?.state??null,[n,l]=R(null),[i,r]=R(null),[u,d]=R(!1),[c,m]=R(!1),[p,b]=R(!1),[g,h]=R(""),[v,N]=R(!1),[C,x]=R(!1),[f,S]=R("overview"),[y,T]=R({status:"idle",at:0,error:null}),A=Be.useRef(null),L=Be.useRef(null),M=Be.useRef(null);X(()=>{if(a!==null){const w=JSON.stringify(a.config);l(q=>{const Q=q!==null&&JSON.stringify(q)!==A.current;return Q||(L.current=a.config,M.current=a.config),Q?q:JSON.parse(w)}),A.current=w}},[a]),X(()=>{n!==null&&M.current===null&&L.current!==null&&(M.current=L.current)},[n]),X(()=>{if(n===null||o===void 0)return;const w=JSON.stringify(n);if(w===A.current)return;T(Q=>Q.status==="saving"?Q:{...Q,status:"saving"});const q=setTimeout(()=>{const Q={},ue=M.current??L.current;if(ue!==null&&typeof ue=="object")for(const J of Object.keys(n))JSON.stringify(n[J])!==JSON.stringify(ue[J])&&(Q[J]=n[J]);if(Object.keys(Q).length===0){A.current=w,T({status:"saved",at:Date.now(),error:null});return}o.updateConfig(Q).then(()=>{A.current=w,ue!==null&&typeof ue=="object"&&(M.current={...ue,...Q}),T({status:"saved",at:Date.now(),error:null})},J=>{T({status:"error",at:0,error:J?.message??String(J)})})},600);return()=>{clearTimeout(q)}},[n,o]),X(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:k("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const j=W((n??a?.config)?.locale),k=K(j);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?k("readingLedger"):k("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},k("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},k("refresh")));const H=a.config,de=async()=>{if(!v){N(!0),r(null);try{const w=await o.fetchPrices();if(r({kind:w.ok?"ok":"err",text:w.message}),w.ok&&w.state&&typeof w.state.config=="object"){const q=JSON.stringify(w.state.config);l(JSON.parse(q)),A.current=q}}catch(w){r({kind:"err",text:k("syncFailed",{message:w?.message??String(w)})})}finally{N(!1),d(!1)}}},we=async()=>{if(!v){N(!0);try{await o.resetHistory(),r({kind:"ok",text:k("historyCleared")})}catch(w){r({kind:"err",text:k("clearFailed",{message:w?.message??String(w)})})}finally{N(!1),m(!1)}}},Se=async()=>{if(!v){N(!0),r(null);try{const w=await o.importLegacyHistory();r({kind:"ok",text:w.message})}catch(w){r({kind:"err",text:k("legacyImportFailed",{message:w?.message??String(w)})})}finally{N(!1),b(!1)}}},O=(w,q)=>{n!==null&&l({...n,[w]:q})},D=()=>{if(n===null)return;const w=g.trim().toLowerCase();if(w.length===0||!/^[a-z0-9_.-]+$/.test(w)||n?.prices.models[w]!==void 0)return;const q={...n.prices.models,[w]:{cacheHit:0,cacheMiss:0,output:0}};l({...n,prices:{...n.prices,models:q}}),h("")},G=n===null?[]:Object.keys(n.prices.models).filter(w=>{const Q=(n?.priceTableDisplay??H.priceTableDisplay??{})["deepseek:"+w];return typeof Q=="boolean"?Q:!0}).map(w=>e(It,{key:w,modelId:w,entry:n.prices.models[w]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:l,t:k})),B=[["overview",k("tabOverview")],["statistics",j==="en"?"Cost statistics":"计费统计"],["quotas",k("tabQuotas")],["usage",k("tabUsage")],["pricing",k("tabPricing")],["display",k("tabDisplay")]],V=y.status==="saving"?e("span",{className:"cm-hint"},k("saving")):y.status==="error"?e("span",{className:"cm-msg err"},k("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?k("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):k("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},B.map(([w,q])=>e("button",{key:w,type:"button",role:"tab","aria-selected":String(f===w),className:"cm-tab"+(f===w?" active":""),onClick:()=>S(w)},q))),V),Ut(i),f==="statistics"?e(Oa,{state:a,api:o}):null,f==="overview"?e(E,{key:"overview"},e("div",{className:"cm-cards"},H.hideTodayCost===!0?null:e(rt,{title:k("cardToday"),value:Y(z(a.today,H),H),sub:k("callsTokens",{calls:a.today.calls,input:I(a.today.input),cache:I(a.today.cacheRead+a.today.cacheWrite),output:I(a.today.output)})}),e(rt,{title:k("cardMonth"),value:Y(z(a.month,H),H),sub:k("callsTokens",{calls:a.month.calls,input:I(a.month.input),cache:I(a.month.cacheRead+a.month.cacheWrite),output:I(a.month.output)})}),e(rt,{title:k("cardTotal"),value:Y(z(a.total,H),H),sub:k("cardTotalSub",{calls:a.total.calls})})),e(bs,{state:a,t:k}),e("p",{className:"cm-note",key:"cards-footnote"},k("cardsFootnote")),(()=>{const w=wn(a);return w!==null?e("p",{className:"cm-note",key:"tz-hint"},k("timezoneHint",{host:w.hostLabel,browser:w.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:k("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??H).showTotalWithPlan===!0,onChange:w=>{const q=n??H;q!=null&&l({...q,showTotalWithPlan:w.target.checked})}}),e("span",null,k("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},k("todaySessions")),e(ks,{state:a,t:k})),e(xs,{state:a,draft:n,setDraft:l,t:k}),(H.balance?.display==="settings"||H.balance?.display==="both")&&H.hideOfficialBalance!==!0?e(Os,{state:a,api:o,t:k,draft:n,setDraft:l}):null):null,f==="quotas"?e(Is,{key:"quotas",state:a,api:o,t:k,draft:n,setDraft:l}):null,f==="usage"?e(E,{key:"usage"},!Je||(H.usage?.position??"cost")==="cost"?e(Ht,{state:a,t:k,locale:j}):null,e(Cs,{state:a,config:n??H,t:k,draft:n,setDraft:l}),e(Ts,{state:a,config:n??H,t:k}),e(gs,{state:a,api:o}),e(ys,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},k("historyDataTitle")),e("div",{className:"cm-buttons"},p?e(E,null,e("span",{className:"cm-hint"},k("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:Se,disabled:v},k("apply")),e("button",{className:"cm-btn",onClick:()=>b(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>b(!0),disabled:v},k("importLegacy")),c?e(E,null,e("span",{className:"cm-hint"},k("confirmReset")),e("button",{className:"cm-btn danger",onClick:we,disabled:v},k("confirmClear")),e("button",{className:"cm-btn",onClick:()=>m(!1)},k("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>m(!0),disabled:v},k("clearAllHistory"))),e("p",{className:"cm-note"},k("legacyImportNote")))):null,f==="display"?e(E,{key:"display"},e(ps,{draft:n,setDraft:l,t:k}),a?.secretMigration?.pending?.length>0?e(vn,{pending:a.secretMigration.pending,t:k}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,k("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:w=>O("locale",w.target.value)},e("option",{value:"auto"},k("localeAuto")),e("option",{value:"zh"},k("localeZh")),e("option",{value:"en"},k("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},k("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},k("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled","codexQuotaSidebar"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:q=>O(w,q.target.checked)}),e("span",null,k(w)))),Je?e("div",{className:"cm-field"},e("label",null,k("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:w=>{n!==null&&l({...n,usage:{...n.usage??{position:"cost"},position:w.target.value}})}},e("option",{value:"cost"},k("usagePositionCost")),e("option",{value:"general"},k("usagePositionGeneral")),e("option",{value:"section"},k("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,k("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:w=>O("position",w.target.value)},e("option",{value:"dock"},k("positionDock")),e("option",{value:"header"},k("positionHeader")),e("option",{value:"off"},k("off")))),e("div",{className:"cm-field"},e("label",null,k("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:w=>O("sidebar",w.target.value==="on")},e("option",{value:"on"},k("sidebarOn")),e("option",{value:"off"},k("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:w=>O("showSessionId",w.target.checked)}),e("span",null,k("showSessionIdLabel"))),...["hideSessionCostHeader","hideSessionCostDock","hideTurnCost"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:q=>O(w,q.target.checked)}),e("span",null,k(w)))),e("div",{className:"cm-grid-group"},k("groupMoney")),e("div",{className:"cm-field"},e("label",null,k("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:w=>{const q=ws[w.target.value];q!==void 0&&n!==null&&l({...n,currency:w.target.value,...q})}},e("option",{value:"CNY"},k("currencyCny")),e("option",{value:"USD"},k("currencyUsd")),e("option",{value:"EUR"},k("currencyEur")))),e("div",{className:"cm-field"},e("label",null,k("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:w=>O("symbol",w.target.value)})),e("div",{className:"cm-field"},e("label",null,k("rateLabel")),ae({value:n?.exchangeRate??1,emptyMode:"ignore"},w=>O("exchangeRate",w))),e("div",{className:"cm-field"},e("label",null,k("decimalsLabel")),ae({value:n?.decimals??2},w=>O("decimals",Math.min(10,Math.floor(w))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:w=>O("hideOfficialBalance",w.target.checked)}),e("span",null,k("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:w=>O("hideTodayCost",w.target.checked)}),e("span",null,k("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},k("groupSidebar")),e("div",{className:"cm-field"},e("label",null,k("sidebarTodayMetric")),e("select",{className:"cm-input",value:n?.sidebarTodayMetric??"cost",onChange:w=>O("sidebarTodayMetric",w.target.value)},e("option",{value:"cost"},k("sidebarTodayCost")),e("option",{value:"tokens"},k("sidebarTodayTokens")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:w=>{n&&l({...n,sidebarSimple:w.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,k("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,k("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:w=>O("sidebarStyle",w.target.value)},e("option",{value:"standard"},k("sidebarStyleStandard")),e("option",{value:"compact"},k("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,k("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:w.target.value}})}},...Ke(k))),e("div",{className:"cm-field"},e("label",null,k("refreshIntervalLabel")),ae({value:n?.balance?.refreshMinutes??5},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:w.target.checked}})}}),e("span",null,k("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,k("balanceBudgetCapLabel")),ae({value:n?.balance?.budgetCap??""},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:w>0?w:null}})}),e("span",{className:"cm-hint"},k("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,k("barDirectionsTitle")),["balance","budget","go","plan"].map(w=>e("div",{className:"cm-dir-row",key:w},e("span",{className:"cm-dir-label"},k("barDirection_"+w)),e("select",{className:"cm-input",value:n?.barDirections?.[w]??(w==="balance"?"remaining":"used"),onChange:q=>{if(n===null)return;const Q={balance:"remaining",budget:"used",go:"used",plan:"used"};l({...n,barDirections:{...n.barDirections??Q,[w]:q.target.value}})}},e("option",{value:"remaining"},k("barDirectionRemaining")),e("option",{value:"used"},k("barDirectionUsed"))))),e("span",{className:"cm-hint"},k("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,k("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??H.customBalance?.display??"both",onChange:w=>{n!==null&&l({...n,customBalance:{...n.customBalance??H.customBalance??{},display:w.target.value}})}},...Ke(k))),e("div",{className:"cm-field"},e("label",null,k("customBalanceRefreshInterval")),ae({value:n?.customBalance?.refreshMinutes??H.customBalance?.refreshMinutes??15},w=>{n!==null&&l({...n,customBalance:{...n.customBalance??H.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e(Ia,{config:H,draft:n,setDraft:l,t:k,api:o}),e("div",{className:"cm-grid-group"},k("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:w=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:w.target.checked,promptSeen:!0}})}}),e("span",null,k("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([w,q])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[w]!==!1,onChange:Q=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip,[w]:Q.target.checked}})}}),e("span",null,k(q)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("quotaStripNote"))),e("div",{className:"cm-grid-group"},k("groupCorner")),e("div",{className:"cm-field"},e("label",null,k("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:w=>{n!==null&&l({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:w.target.checked}})}}),e("span",null,k("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([w,q])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[w]!==!1,onChange:Q=>{n!==null&&l({...n,corner:{...n.corner,[w]:Q.target.checked}})}}),e("span",null,k(q)))):null),e("div",{className:"cm-grid-group"},k("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:w=>{n!==null&&l({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:w.target.checked}})}}),e("span",null,k("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:w=>{n!==null&&l({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:w.target.checked}})}}),e("span",null,k("budgetDetailLabel"))))),e("p",{className:"cm-note"},k("badgeNote")))):null,f==="pricing"?e(E,{key:"pricing"},e(vs,{state:a,draft:n,setDraft:l,t:k}),e("div",null,Le(C,()=>x(!C),k("priceTableTitle")),C?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},k("priceTableNote")),e("p",{className:"cm-hint"},k("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},k("deepseekMountedHeader")),G,e(It,{key:"__default__",modelId:k("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:l,t:k}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:k("newModelPlaceholder"),value:g,onChange:w=>h(w.target.value)}),e("button",{className:"cm-btn small",onClick:D,disabled:g.trim().length===0},k("addModel"))),(()=>{const w=n?.priceTableDisplay??H.priceTableDisplay??{},q=n?.prices?.providers??{},Q=J=>Object.keys(q[J]?.models??{}).filter(P=>w[J+":"+P]===!0),ue=Object.keys(q).filter(J=>Q(J).length>0).sort((J,P)=>J.localeCompare(P));return ue.length===0?null:ue.map(J=>e("div",{key:J},e("div",{className:"cm-catalog-vendor"},(Da[J]??J)+" · "+k("mountedSuffix")),Q(J).sort().map(P=>e(Ea,{key:J+":"+P,provider:J,modelId:P,entry:q[J].models[P],draft:n,setDraft:l,t:k}))))})()):null),(()=>{const w=n?.priceOverrides??H.priceOverrides??{},q=n?.priceMatchDismissed??H.priceMatchDismissed??[],Q=n?.prices??H.prices,ue=a.today.byProviderModel??{},J={prices:Q,priceMatch:n?.priceMatch??H.priceMatch},P=Object.keys(ue).filter(U=>{if(q.includes(U)||w[U]!==void 0)return!1;const _=U.indexOf(":"),me=(_>0?U.slice(0,_):"deepseek").toLowerCase(),Qt=_>0?U.slice(_+1):U;return kt(me,Qt,J).matched!==!0}),F=[...new Set([...P,...Object.keys(w)])].filter(U=>!q.includes(U)),ee=a.month?.byProviderModel??{},oe=Object.keys(ee).filter(U=>{if(q.includes(U)||w[U]!==void 0)return!1;const _=U.indexOf(":"),me=(_>0?U.slice(0,_):"deepseek").toLowerCase(),Qt=_>0?U.slice(_+1):U;return kt(me,Qt,J).matched===!0}).sort(),qe=[{value:"__local__",label:k("overrideTargetLocal")},{value:"deepseek:__default__",label:k("overrideTargetDefault")},...Object.keys(Q.models??{}).map(U=>({value:"deepseek:"+U,label:"DeepSeek · "+U})),...Object.entries(Q.providers??{}).flatMap(([U,_])=>Object.keys(_?.models??{}).map(me=>({value:U+":"+me,label:U+" · "+me})))],Ce=(U,_)=>{if(n===null)return;const me={...n.priceOverrides??{}};_===""?delete me[U]:me[U]=_,l({...n,priceOverrides:me})},xe=U=>{if(n===null)return;const _={...n.priceOverrides??{}};delete _[U],l({...n,priceOverrides:_,priceMatchDismissed:[...new Set([...q,U])]})};return e("div",null,e("h3",{className:"cm-h"},k("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:U=>O("priceMatch",U.target.value)},e("option",{value:"auto"},k("priceMatchAuto")),e("option",{value:"exact"},k("priceMatchExact")))),e("p",{className:"cm-note"},k("priceMatchNote")),F.length>0?e(E,null,e("h3",{className:"cm-h"},k("unmatchedTitle")),e("p",{className:"cm-hint"},k("unmatchedHint")),F.map(U=>e("div",{key:U,className:"cm-match-row"},e("span",null,jt(U)),e("select",{className:"cm-input",value:w[U]??"",onChange:_=>Ce(U,_.target.value)},e("option",{value:""},"—"),qe.map(_=>e("option",{key:_.value,value:_.value},_.label))),e("button",{className:"cm-btn small",title:k("removePriceMatchHint"),onClick:()=>xe(U)},k("overrideRemove"))))):e("p",{className:"cm-hint"},k("overrideNone")),q.length>0?e("button",{className:"cm-btn small",onClick:()=>O("priceMatchDismissed",[])},k("restorePriceMatches",{count:q.length})):null,oe.length>0?e(E,null,e("h3",{className:"cm-h"},k("matchedTitle")),e("p",{className:"cm-hint"},k("matchedHint")),oe.map(U=>e("div",{key:U,className:"cm-match-row"},e("span",null,jt(U)),e("select",{className:"cm-input",value:"",onChange:_=>{_.target.value!==""&&Ce(U,_.target.value)}},e("option",{value:""},k("matchedKeepAuto")),qe.map(_=>e("option",{key:_.value,value:_.value},_.label)))))):null)})(),e(Ss,{state:a,draft:n,setDraft:l,t:k}),e("div",null,e("h3",{className:"cm-h"},k("dataSync")),(n??H).currency==="CNY"&&(n??H).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},k("pricingCnyHint",{rate:(n??H).exchangeRate}),(n??H).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:v,onClick:()=>O("pricingCurrency","CNY")},k("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,k("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:w=>O("pricingCurrency",w.target.value)},e("option",{value:"USD"},k("pricingCurrencyUsd")),e("option",{value:"CNY"},k("pricingCurrencyCny"))),e("p",{className:"cm-note"},k("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},u?e(E,null,e("span",{className:"cm-hint"},k("confirmFetch")),e("button",{className:"cm-btn",onClick:de,disabled:v},k("apply")),e("button",{className:"cm-btn",onClick:()=>d(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>d(!0),disabled:v},k("syncFromDocs"))),e("p",{className:"cm-note"},k("lastSync",{time:H.fetchedAt!==null?new Date(H.fetchedAt).toLocaleString():k("neverSynced")})+k("source",{source:H.priceSource==="official"?k("sourceOfficial"):k("sourceBundled")})),e("p",{className:"cm-note"},k("syncScopeNote")))):null)}const Hs=["remote"];async function Qs(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(on);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=xn({status:"loading",error:null,state:null}),l=()=>K(W(n.getSnapshot().state?.config?.locale)),i=async(P,F)=>{const ee=await a[P](...F??[]);if(ee===null||typeof ee!="object"||ee.ok!==!0)throw new Error(ee?.error?.message??l()("rpcFailed",{method:P}));return ee.value};let r=Date.now(),u=!1,d=!0,c=1;const m=async()=>{if(!d||u)return;u=!0,r=Date.now();const P=n.getSnapshot();P.state===null&&n.set({...P,status:"loading"});try{const F=await i("getState");if(!d)return;c=1,n.set({status:"ready",error:null,state:F})}catch(F){if(!d)return;P.state===null&&(r=Date.now()),c=Math.min(c*2,60),n.set({status:"error",error:F?.message??String(F),state:P.state})}finally{u=!1}};t.effect(()=>t.on("connection/reset",()=>{m()}),"cost-meter: reconnect reload");const p=setInterval(()=>{const P=n.getSnapshot().state,F=P?.config.sidebarModels,ee=P?F?.enabled||F?.dock?F.refreshSeconds:60:c;!document.hidden&&Date.now()-r>=(ee||60)*1e3&&m()},1e3);t.effect(()=>()=>{d=!1,clearInterval(p)},"cost-meter: poll timer");const b=()=>{document.visibilityState==="visible"&&m()};document.addEventListener("visibilitychange",b),t.effect(()=>()=>{document.removeEventListener("visibilitychange",b)},"cost-meter: visibility reload");const g=async(P,F="rpcSyncFailed",ee=!1)=>{const oe=await P;if(oe===null||typeof oe!="object"||oe.ok!==!0)throw new Error(oe?.error?.message??(ee?oe?.value?.message:void 0)??l()(F));return oe.value.state!==void 0&&n.set({status:"ready",error:null,state:oe.value.state}),oe.value};let h=null;const v={loadStatistics:()=>(h||(h=(typeof Ve.async=="function"?Ve.async("./client.statistics.js").then(P=>P.mount(t)):Promise.reject(new Error(l()("statisticsUpgrade")))).catch(P=>{throw h=null,P})),h),reload:m,updateConfig:async P=>{const F=await i("updateConfig",[P]);return n.set({status:"ready",error:null,state:F}),F},fetchPrices:async()=>g(a.fetchPrices()),resetHistory:async()=>{const P=await i("resetHistory");return n.set({status:"ready",error:null,state:P}),P},importLegacyHistory:async()=>{const P=await a.importLegacyHistory();if(P===null||typeof P!="object"||P.ok!==!0)throw new Error(P?.error?.message??P?.value?.message??l()("legacyImportFailed",{message:"RPC failed"}));return P.value.state!==void 0&&n.set({status:"ready",error:null,state:P.value.state}),P.value},getDaySessions:async P=>i("getDaySessions",[P]),getSessionCost:async P=>i("getSessionCost",[P]),getTurnCost:async(P,F,ee)=>i("getTurnCost",[P,F,ee]),getTopSessions:async(P,F,ee)=>i("getTopSessions",[P,F,ee]),refreshBalance:async()=>g(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>g(a.refreshGoQuota()),refreshGatewayQuota:async(P=null)=>g(P==null?a.refreshGatewayQuota():a.refreshGatewayQuota(P)),refreshCustomBalance:async(P=null)=>g(P==null?a.refreshCustomBalance():a.refreshCustomBalance(P)),refreshCodingPlan:async P=>g(a.refreshCodingPlan(P)),setCredential:async(P,F)=>g(a.setCredential(P,F),"rpcSyncFailed",!0),clearCredential:async P=>g(a.clearCredential(P),"rpcSyncFailed",!0)};m();const N=t.get("slots");if(N===void 0)return;const C=()=>({hooks:{cost:n},api:v});for(const[P,F]of[["header","conversation.session.header.actions"],["dock","conversation.composer.dock"]])N.inject(F,()=>N.register({name:F,id:"cost-meter-statistics",order:1,inject:()=>({...C(),entryPosition:P})},fs));N.inject("conversation.chat.turnTail",()=>N.register({name:"conversation.chat.turnTail",id:"cost-meter-turn",order:10,inject:C},Sn));const x=()=>({gen:0,dispose:null}),f=(P,F,ee,oe,qe=!0)=>{P.dispose!==null&&(P.dispose(),P.dispose=null),P.gen+=1;const Ce=P.gen;qe&&N.inject(F,()=>{if(P.gen!==Ce)return;const xe=typeof ee=="function"?ee():N.register(ee,oe);if(P.gen!==Ce){xe();return}return P.dispose=xe,()=>{P.dispose===xe&&(P.dispose=null),xe()}})},S=x(),y=P=>{const F=P==="header"?"conversation.session.header.actions":"conversation.composer.dock";f(S,F,P==="header"?{name:F,id:"cost-meter",order:-5,inject:C}:{name:F,id:"cost-meter",order:5,inject:C},P==="header"?Cn:An,P!=="off")},T=x(),A=P=>{f(T,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:C},us,P)},L=x(),M=P=>{f(L,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:C},jn,P)};N.inject("conversation.input.dock",()=>N.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:C},os)),N.inject("sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:C},ls)),N.inject("sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:C},is)),N.inject("sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:C},ds));const j=x(),k=P=>{f(j,"sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:C},Un),null,P)};window.cmPeakAlertPreview=P=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(Pt,{detail:{kind:P==="offpeak"?"offpeak":"peak"}}))};const H=x(),de=P=>{f(H,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:P==="en"?Oe.en.sectionLabel:Oe.zh.sectionLabel,inject:C},Us,!0)},we=x(),Se=P=>{f(we,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:C},Ht,P)},O=x(),D=(P,F)=>{f(O,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:F==="en"?Oe.en.usageSectionLabel:Oe.zh.usageSectionLabel,inject:C},Ht,P)};let G=null,B=null,V=null,w=null,q=null,Q=null;const ue=()=>{const P=n.getSnapshot().state,F=P?.config?.position??"dock",ee=P?.config?.sidebar!==!1&&P?.config?.hideTodayCost!==!0,oe=P?.config?.balance?.display??"both",qe=(oe==="sidebar"||oe==="both")&&P?.config?.hideOfficialBalance!==!0,Ce=ee||qe||P?.config?.codexQuotaEnabled===!0||P?.config?.sidebarModels?.enabled===!0,xe=P?.config?.corner?.enabled===!0||P?.config?.sidebarModels?.dock===!0,U=W(P?.config?.locale),_=P?.config?.usage?.position??"cost";F!==G&&(y(F),G=F),Ce!==B&&(A(Ce),B=Ce),xe!==V&&(M(xe),V=xe);const me=P?.config?.peakEnabled===!0;me!==Q&&(k(me),Q=me),U!==w&&(de(U),w=U),_!==q?(Je&&(Se(_==="general"),D(_==="section",U)),q=_):Je&&_==="section"&&U!==w&&D(!0,U)};ue();const J=n.subscribe(ue);return()=>{J()}}return dt.apply=Qs,dt.inject=Hs,Ft.exports}});
|
|
6
|
+
`),L=f.map((D,G)=>D.text!=null?e("div",{key:G,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},D.name),e("span",{className:"cm-mm-text cm-num"},D.text)):e(E,{key:G},D.view.row)),M=D=>{if(!D.key||D.key==="Enter"||D.key===" "){D.stopPropagation(),D.preventDefault?.();const G=a.accounts[(h+1)%a.accounts.length];ts(o.id,G.id),d({source:o.id,id:G.id})}},j=p?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:N||h+1}),onClick:M,onKeyDown:M,role:"button",tabIndex:0},`${h+1}/${a.accounts.length} ⇄`):null,k=p?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),j):e("div",{className:"cm-mm-title"},o.label||o.id),H=p&&N?e("div",{className:"cm-gw-sub"},N):null,de=e(E,null,k,H,...L),we=f.filter(D=>D.view).map(D=>D.view.label).filter(D=>D!==null),Se=we.length>0?we.slice(0,2).map(D=>D+"%").join(" "):f[0].text??"—",O=e("div",{className:"cm-bbox-rail cm-num"},Se);return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},A),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(S==="ok"?"":" "+S)+(l===!1?" rail":"")+(c.busy?" busy":""),...be(c.busy,c.run)},l===!1?e(E,null,O,j):de))}function ns(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],l=[];for(const i of s.gatewayQuotas?.sources??[]){if(i.enabled===!1||i.display!=="sidebar"&&i.display!=="both")continue;const r=n.find(u=>u.id===i.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||l.push(e(as,{source:i,snapshot:r,state:t,wide:o,api:a}))}return l}const ss={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function os(t){const s=t.useCost?t.useCost(g=>g):void 0;Ot(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=R(null),[n,l]=R({}),i=s?.state,r=t.api;if(!i)return null;const u=i.config,d=u.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(d.enabled!==!0)return null;const c=K(W(u?.locale)),m=[];if(d.budget!==!1){const g=u.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const h=Number(u.exchangeRate),N=(i.budgetUsed??(g.period==="day"?z(i.today,u):g.period==="all"?z(i.total,u):z(i.month,u)))*(Number.isFinite(h)&&h>0?h:1),C=Math.max(0,Number(g.amount)||0);if(C>0){const x=Math.min(999,N/C*100),f=x>=100?"over":x>=80?"warn":"ok";m.push({key:"budget",label:c("budgetShort"),level:f,tip:c("budgetOf",{period:c(Ie[g.period]??"periodMonth")})+" · "+c("usedOf",{used:ce(N,u),amount:ce(C,u)})+" · "+x.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(pe(Math.min(100,x),se(u,"budget")).width)}]})}}}if(d.go!==!1){const g=i.goQuota;if(u?.goQuota?.enabled!==!1&&g?.status==="ok"){const h=u.goQuota.main==="weekly"||u.goQuota.main==="monthly"?u.goQuota.main:"rolling",v=h==="rolling"?g.rolling:h==="weekly"?g.weekly:g.monthly;if(v!==null&&typeof v=="object"&&typeof v.percent=="number"){const N=Math.max(0,Math.min(100,Math.round(Number(v.percent)||0))),C=N>=100?"over":N>=80?"warn":"ok",x=typeof v.resetsAt=="string"&&v.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(v.resetsAt).toLocaleString()}):"";m.push({key:"go",label:"Go "+c(h==="rolling"?"goShortRolling":h==="weekly"?"goShortWeekly":"goShortMonthly"),level:C,tip:"Go: "+N+"%"+x,segs:[{name:"main",pct:Math.round(pe(N,se(u,"go")).width)}]})}}}if(d.plans!==!1)for(const g of Ee){const h=i.codingPlans?.[g.id];if(u.codingPlans?.[g.id]?.enabled!==!0||!h||h.status!=="ok")continue;const v=h.windows!==null&&typeof h.windows=="object"?h.windows:{},N=Object.entries(v);if(N.length===0)continue;const C=ss[g.id]??g.id,x=[],f=[];let S=0,y=0;for(const[T,A]of N){const L=Dt(T,c),M=typeof A?.resetsAt=="string"&&A.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(A.resetsAt).toLocaleString()}):"",j=A!==null&&typeof A=="object"&&typeof A.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(A.percent)||0))):null;if(f.push(L+" "+(j===null?typeof A?.text=="string"?A.text:"—":j+"%")+M),j===null){x.push({name:T,pct:null,text:typeof A?.text=="string"?A.text:"—"});continue}y>=2||(y+=1,x.push({name:T,pct:Math.round(pe(j,se(u,"plan")).width)}),S=Math.max(S,j>=100?2:j>=80?1:0))}h.fetchedAt>0&&f.push(c("goQuotaFetchedAt",{time:new Date(h.fetchedAt).toLocaleTimeString()})),x.length!==0&&m.push({key:g.id,label:C,level:["ok","warn","over"][S],tip:f.join("; "),segs:x})}const p=u.codexQuotaEnabled===!0&&$.status==="ok"?$.windows.weekly??null:null;if(p!==null&&typeof p.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(p.percent)||0))),h=typeof p.resetsAt=="string"&&p.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(p.resetsAt).toLocaleString()}):"";m.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+h,segs:[{name:"weekly",pct:Math.round(pe(g,se(u,"plan")).width)}]})}if(m.length===0)return null;const b=g=>{o!==null||!r||(a(g),l(h=>({...h,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?Tt(!0,u.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(h=>{l(v=>({...v,[g]:h?.message??String(h)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},m.map(g=>{const h=o===g.key,v=n[g.key],N=[e("span",{className:"cm-qlabel",key:"l"},g.label)];h?N.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((x,f)=>{f>0&&N.push(e("span",{className:"cm-qsep",key:"sep"+f,"aria-hidden":"true"})),x.pct===null?N.push(e("span",{className:"cm-qtext",key:x.name},x.text)):N.push(e("span",{className:"cm-qseg",key:x.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:x.pct+"%"}})),e("span",null,x.pct+"%")))});const C=[g.tip];return!h&&r&&C.push(c("clickToRefresh")),h&&C.push(c("refreshing")),v&&C.push("⚠ "+c("balanceRefreshFailed",{message:v})),e(Z,{key:g.key,label:C.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?be(h,()=>b(g.key)):{}},N))}))}const Aa="dsh-cost-meter:simple-guide-dismissed";function Bt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Aa)==="1"}catch{return!1}}function ls(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Pe(!1),[a,n]=R(!1),[l,i]=R(!1),[r,u]=R(!1),d=s?.state?.config;if(!d||r||Bt(d))return null;const c=K(W(d.locale)),m=()=>{u(!0);try{window.localStorage.setItem(Aa,"1")}catch{}},p=async b=>{if(!o.current){o.current=!0,n(!0),i(!1);try{if((await t.api.updateConfig({sidebarSimple:b,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==b)throw new Error;m()}catch{i(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),m())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:m},"×")),e("p",null,c("sidebarSimpleBody")),l?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>p(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>p(!0)},c("sidebarSimpleOn"))))}function is(t){const s=t.useCost?t.useCost(r=>r):void 0,o=Pe(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Bt(n)||n.quotaStrip?.promptSeen===!0)return null;const l=K(W(n?.locale)),i=r=>{if(o.current===!0)return;o.current=!0;const u=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...u,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":l("quotaStripGuideTitle")},e("h4",null,l("quotaStripGuideTitle")),e("p",null,l("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>i(!1)},l("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>i(!0)},l("quotaStripGuideOn"))))}const Ma="dsh-cost-meter:balance-click-hint-seen",rs=()=>{try{return window.localStorage.getItem(Ma)==="1"}catch{return!1}},cs=()=>{try{window.localStorage.setItem(Ma,"1")}catch{}};function ds(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Pe(!1),[a,n]=R(!1),[l]=R(rs),i=s?.state;if(!i)return null;const r=i.config,u=r.balance?.display==="sidebar"||r.balance?.display==="both",d=(r?.customBalances??[]).some(b=>b?.enabled===!0&&(b.display==="sidebar"||b.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Ee.some(b=>{const g=r.codingPlans?.[b.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||l||r.balance?.clickHintSeen===!0||!u&&!d&&!c||!Bt(r)||r.quotaStrip?.promptSeen!==!0)return null;const m=K(W(r?.locale)),p=()=>{o.current!==!0&&(n(!0),o.current=!0,cs(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":m("balanceClickGuideTitle")},e("h4",null,m("balanceClickGuideTitle")),e("p",null,m("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:p},m("balanceClickGuideOk"))))}function Rt(t,s,o){return s.sidebarTodayMetric==="tokens"?I(["input","output","cacheRead","cacheWrite","reasoning"].reduce((a,n)=>a+(Number(t?.[n])||0),0))+" "+o("tokensUnit"):Y(z(t,s),s)}function Lt(t){const{state:s,wide:o}=t,a=s.today,n=s.config,l=K(W(n?.locale)),i=Rt(a,n,l),r=n.budget??{enabled:!1,amount:100,period:"month"},u=Number(n.exchangeRate),c=(s.budgetUsed??(r.period==="day"?z(s.today,n):r.period==="all"?z(s.total,n):z(s.month,n)))*(Number.isFinite(u)&&u>0?u:1),m=Math.max(0,Number(r.amount)||0),p=m>0?Math.min(999,c/m*100):null,b=p===null?"ok":p>=100?"over":p>=80?"warn":"ok";if(r.enabled===!0){const v=z(a,n)*(Number.isFinite(u)&&u>0?u:1),N=m>0?Math.min(999,v/m*100):null,C=[l("budgetOf",{period:l(Ie[r.period]??"periodMonth")}),l("usedOf",{used:ce(c,n),amount:ce(m,n)})+" · "+(p===null?"—":p.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[n.sidebarTodayMetric==="tokens"?l("today")+" "+i:l("todayShare",{amount:i,pct:N===null?"—":N.toFixed(1)+"%"})],l("monthTotal",{month:Y(z(s.month,n),n),total:Y(z(s.total,n),n)})].join("; ");if(t.summary===!0)return e(Z,{label:C,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(b==="ok"?"":" "+b),tabIndex:0},e("span",null,l("todayBudget",{period:l(Ie[r.period]??"periodMonth")})),e("span",{className:"cm-num"},i+" / "+ce(m,n))));const x=xa(s,n,l);return e(Z,{label:C,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(b==="ok"?"":" "+b)+(o?"":" rail")},o?x.body:e("div",{className:"cm-bbox-rail cm-num"},x.rail)))}const g=[n.sidebarTodayMetric==="tokens"?l("todayTokensTitle"):l("todayCostTitle"),l("callsTokens",{calls:a.calls,input:I(a.input),cache:I(a.cacheRead+a.cacheWrite),output:I(a.output)}),l("monthCost",{amount:Y(z(s.month,n),n)}),l("totalCost",{amount:Y(z(s.total,n),n)})].join("; ");return e(Z,{label:g,side:"right",delayMs:300},e(E,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(E,null,l("today")," ",e("span",{className:"cm-num"},i)):e(tt,{size:16})),o?ot(s,n,l):null))}function us(t){const s=t.useCost?t.useCost(M=>M):void 0;Ot(s?.state?.config?.codexQuotaEnabled===!0&&s?.state?.config?.codexQuotaSidebar!==!1);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}ua(t,o);const a=s?.state,n=!!t.wide;if(!a)return null;const l=a.config,i=K(W(l?.locale)),r=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,d=Mt(a,l).length>0,c=r&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",m=d&&l.balance?.showProgressBar===!0,p=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",b=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[p]!==null,g=Ee.map(M=>M.id).filter(M=>{const j=l.codingPlans?.[M];if(j?.enabled!==!0||j.display!=="sidebar"&&j.display!=="both")return!1;const k=a.codingPlans?.[M];if(k?.status!=="ok")return!1;const H=k.windows!==null&&typeof k.windows=="object"?k.windows:{};return Object.keys(H).length>0}),h=g.length>0,v=ns(a,l,n,t.api),N=l.codexQuotaEnabled===!0&&l.codexQuotaSidebar!==!1&&$.status==="ok"&&$.windows.weekly!==null,C=(l.budget??{}).enabled===!0,x=l.sidebar!==!1&&l.hideTodayCost!==!0,f=l.sidebarModels?.enabled===!0;if(!f&&!r&&!d&&!b&&!h&&!N&&!C&&!x&&v.length===0)return null;const S=l.sidebarSimple===!0,y=!S&&n&&l.sidebarStyle==="compact",T=S&&n&&x&&C,A=[];T?A.push(e(Lt,{state:a,wide:n,summary:!0})):S&&n&&x&&A.push(e("div",{className:"cm-simple-summary"},e("span",null,i("today")),e("span",{className:"cm-num"},Rt(a.today,l,i)))),c?A.push(e(Bn,{state:a,wide:n,api:t.api})):r&&A.push(e(Dn,{state:a,wide:n,api:t.api})),m?A.push(e(Ln,{state:a,wide:n,api:t.api})):d&&A.push(e(qn,{state:a,wide:n,api:t.api}));const L=A.length;if(h&&A.push(...g.map(M=>M==="minimax"?e(Kn,{state:a,wide:n,api:t.api}):e(es,{id:M,state:a,wide:n,api:t.api}))),A.push(...v),N&&A.push(e(Xn,{state:a,wide:n,api:t.api})),b&&C&&n&&!S){const M=va(a,l,i),j=xa(a,l,i),k=M.level==="over"||j.level==="over"?"over":M.level==="warn"||j.level==="warn"?"warn":"ok";A.push(e("div",{className:"cm-bbox cm-bbox-pair"+(k==="ok"?"":" "+k)},e("div",{className:"cm-bbox-section"+(M.level==="ok"?"":" "+M.level)},M.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(j.level==="ok"?"":" "+j.level)},j.body)))}else b&&A.push(e(zn,{state:a,wide:n})),C&&!T&&A.push(e(Lt,{state:a,wide:n}));return!C&&x&&!(S&&n)&&A.push(e(Lt,{state:a,wide:n})),S&&n&&x&&A.push(ot(a,l,i)),n||A.push(_n(a,l,i)),f&&A.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?L:A.length,0,e(ms,{key:"models",state:a,wide:n})),e("div",{...S?{tabIndex:0,role:"region","aria-label":i("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(y?" compact":"")+(S?" simple":"")},...A)}const Et={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Pa="dsh-cost-meter:models-open";function Ta(t,s,o){return Ra(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:jt(a.key),cost:z(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function ms({state:t,wide:s}){const o={...Et,...t.config.sidebarModels},a=K(W(t.config.locale)),n=()=>{try{const N=o.remember?window.localStorage.getItem(Pa):null;if(N!==null)return N==="1"}catch{}return o.defaultOpen},[l,i]=R(n),[r,u]=R(o.period);X(()=>u(o.period),[o.period]),X(()=>i(n()),[o.defaultOpen,o.remember]);const d=Ta(t,r,a),c=d.reduce((N,C)=>N+C.cost,0),m=N=>Y(N,t.config),p=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+m(c)+" · "+a("modelsCount",{n:d.length}),b=o.summary==="top"&&d.length?d[0].label+" "+m(d[0].cost):p,g=o.summary==="top"&&d.length?e(E,null,e("span",{className:"cm-bal-label"},d[0].label),e("span",{className:"cm-bal-amt"},m(d[0].cost))):e("span",{className:"cm-bal-label"},b),h=()=>{i(!l);try{o.remember&&window.localStorage.setItem(Pa,l?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:b+" · "+p},s?g:e(tt,{size:16}));const v=d.slice(0,o.topN);return d.length>o.topN&&v.push(d.slice(o.topN).reduce((N,C)=>{for(const x of["cost","input","output","cacheRead","cacheWrite"])N[x]+=C[x];return N},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(l),title:p,onClick:h},e("span",{className:"cm-caret"+(l?" open":"")}),g),l?e(E,null,e("div",{className:"cm-buttons"},["today","history"].map(N=>e("button",{key:N,type:"button",className:"cm-mstats-tab"+(r===N?" active":""),"aria-pressed":r===N,onClick:()=>u(N)},a(N==="today"?"modelStatsToday":"modelStatsHistory")))),v.length?v.map(N=>e("div",{key:N.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:N.label},N.label),e("span",{className:"cm-num cm-bal-amt"},m(N.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?N.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?N.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+I(N.input)+" · "+a("modelStatsCache")+" "+I(N.cacheRead+N.cacheWrite)+" · "+a("modelStatsOutput")+" "+I(N.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function ps({draft:t,setDraft:s,t:o}){const a={...Et,...t?.sidebarModels},n=(i,r)=>{t&&s({...t,sidebarModels:{...a,[i]:r}})},l=(i,r)=>e("div",{className:"cm-field",key:i},e("label",null,o("models_"+i)),e("select",{className:"cm-input",value:a[i],onChange:u=>n(i,u.target.value)},r.map(([u,d])=>e("option",{key:u,value:u},o(d)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(i=>e("label",{key:i,className:"cm-check"},e("input",{type:"checkbox",checked:a[i],onChange:r=>n(i,r.target.checked)}),o("models_"+i))),l("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),l("summary",[["total","modelsTotal"],["top","modelsTop"]]),l("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(i=>e("div",{key:i,className:"cm-field"},e("label",null,o("models_"+i)),ae({value:a[i]},r=>n(i,Math.max(i==="topN"?1:10,Math.min(i==="topN"?10:60,Math.floor(r))))))))}function rt(t){return e("div",{className:"cm-card"},e("p",{className:"cm-card-title"},t.title),e("div",{className:"cm-card-value cm-num"},t.value),e("p",{className:"cm-card-sub"},t.sub))}function Oa(t){const[s,o]=R(null),[a,n]=R(""),[l,i]=R(0);return X(()=>{let r=!0;return n(""),t.api.loadStatistics().then(u=>{r&&o(()=>u)},u=>{r&&n(String(u.message??u))}),()=>{r=!1}},[t.api,l]),s?e(s,{...t,formatMoneyUsd:Y,formatTokens:I}):e("p",{role:a?"alert":"status"},a||"…",a?e("button",{className:"cm-btn",onClick:()=>i(r=>r+1)},"↻"):null)}function fs(t){const s=t.useCost?.(c=>c),o=s?.state,[a,n]=R(null),l=Be.useRef(null),i=o?.config[t.entryPosition==="header"?"hideSessionCostHeader":"hideSessionCostDock"]===!0,r=!i&&!!t.sessionId&&a===t.sessionId;if(X(()=>{r&&l.current?.showModal()},[r]),X(()=>{n(null)},[t.sessionId,i]),!t.sessionId||i)return null;const u=W(o?.config.locale)==="en",d=u?"Conversation cost details":"本会话费用明细";return e(E,null,e("button",{type:"button",className:"cm-btn cm-stat-entry cm-stat-"+(t.entryPosition||"dock"),title:d,"aria-label":d,"aria-haspopup":"dialog",onClick:()=>n(t.sessionId)},u?"Cost details":"费用明细"),r?e("dialog",{ref:l,role:"dialog","aria-label":d,onCancel:()=>n(null),style:{width:"min(1160px,94vw)",maxHeight:"90vh",padding:24,borderRadius:16,border:"1px solid var(--dsw-alias-border-l1)",color:"var(--dsw-alias-label-primary)",background:"var(--dsw-alias-bg-base,#fff)"}},e("button",{type:"button",className:"cm-btn",autoFocus:!0,"aria-label":u?"Close":"关闭",onClick:()=>n(null),style:{float:"right"}},"×"),o?e(Oa,{key:t.sessionId,state:o,api:t.api,sessionId:t.sessionId}):e("p",{role:s?.error?"alert":"status"},s?.error||(u?"Loading…":"加载中…"),e("button",{type:"button",className:"cm-btn",onClick:()=>t.api.reload()},u?"Retry":"重试"))):null)}function bs({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=d=>Y(z(d,a),a),l=d=>s("callsTokens",{calls:d.calls,input:I(d.input),cache:I(d.cacheRead+d.cacheWrite),output:I(d.output)}),i=(d,c)=>({calls:d.calls+c.calls,input:d.input+c.input,output:d.output+c.output,cacheRead:d.cacheRead+c.cacheRead,cacheWrite:d.cacheWrite+c.cacheWrite,cost:z(d,a)+c.cost,apiCost:z(d,a)+c.cost}),r=(d,c)=>e("tr",{key:d},e("td",null,d),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},I(c.input)),e("td",{className:"num"},I(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},I(c.output)),e("td",{className:"num"},n(c))),u=d=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,d)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((d,c)=>{const m=i(t[d],o.combined[d]);return e(rt,{key:d,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(m),sub:l(m)})})),...o.sources.map(d=>e("details",{key:d.source},e("summary",null,d.source+" · "+s("cardToday")+" "+n(d.today)+" · "+s("cardMonth")+" "+n(d.month)+" · "+l(d.today)),u(["today","month","total"].map((c,m)=>r(s(["cardToday","cardMonth","cardTotal"][m]),d[c]))),e("p",{className:"cm-note"},s("externalHistory")),u(d.history.map(c=>r(c.date,c))))))}const Le=(t,s,o)=>e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(t),onClick:s},e("span",{className:"cm-caret"+(t?" open":"")}),e("h3",{className:"cm-h"},o));function gs(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,l]=R(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(n,()=>l(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(hs,{state:s,api:o})):null)}function hs(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,l]=R(null),[i,r]=R({}),[u,d]=R(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const m=b=>{if(n===b){l(null);return}l(b),!(i[b]!==void 0||u.has(b))&&(d(g=>{const h=new Set(g);return h.add(b),h}),o.getDaySessions(b).then(g=>r(h=>({...h,[b]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[b]:"error"}))).finally(()=>d(g=>{const h=new Set(g);return h.delete(b),h})))},p=b=>b.map(g=>e("tr",{key:g.id},qt(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},I(g.input)),e("td",{className:"num"},I(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},I(g.output)),e("td",{className:"num"},Y(z(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(b=>{const g=e("tr",{key:b.date,className:"cm-row-click",onClick:()=>m(b.date)},e("td",null,(n===b.date?"▾ ":"▸ ")+b.date),e("td",{className:"num"},String(b.calls)),e("td",{className:"num"},I(b.input)),e("td",{className:"num"},I(b.cacheRead+b.cacheWrite)),e("td",{className:"num"},I(b.output)),e("td",{className:"num"},Y(z(b,s.config),s.config)));if(n!==b.date)return[g];const h=i[b.date],v=u.has(b.date)&&h===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):h==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(h)||h.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,p(h)));return[g,e("tr",{key:b.date+"-sessions"},e("td",{colSpan:6},v))]}))))}function ys(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,l]=R(!1),[i,r]=R(100),[u,d]=R("cost-desc"),[c,m]=R(null),[p,b]=R(!1),[g,h]=R(!1),v=Be.useRef(0),N=(S,y)=>{const[T,A]=y==="recent"?["recent","desc"]:y.split("-"),L=++v.current;b(!0),h(!1),o.getTopSessions(S,T,A).then(M=>{L===v.current&&m(Array.isArray(M?.sessions)?M.sessions:[])}).catch(()=>{L===v.current&&h(!0)}).finally(()=>{L===v.current&&b(!1)})},C=()=>{l(S=>{const y=!S;return y&&c===null&&!p&&N(i,u),y})},x=S=>{r(S),(n||c!==null)&&N(S,u)},f=S=>{d(S),(n||c!==null)&&N(i,S)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(n,C,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:u,onChange:S=>f(S.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(i),onChange:S=>x(Number(S.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),p?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(S=>e("tr",{key:S.date+":"+S.id},e("td",null,S.date),qt(S,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(S.calls)),e("td",{className:"num"},I(S.input)),e("td",{className:"num"},I((S.cacheRead??0)+(S.cacheWrite??0))),e("td",{className:"num"},I(S.output)),e("td",{className:"num"},Y(z(S,s.config),s.config)))))))):null)}function ks(t){const{state:s}=t,o=K(W(s.config?.locale)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(l=>e("tr",{key:l.id},qt(l,n,o),e("td",{className:"num"},String(l.calls)),e("td",{className:"num"},I(l.input)),e("td",{className:"num"},I(l.cacheRead+l.cacheWrite)),e("td",{className:"num"},I(l.output)),e("td",{className:"num"},Y(z(l,s.config),s.config)))))))}function qt(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",l=a.length>0?a:n,i=a.length>0?a+" · "+t.id:t.id;return e("td",{title:i},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},l),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const ws={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function xs(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=o?.budget??l.budget,r=Number(l.exchangeRate),d=(s.budgetUsed??(i.period==="day"?z(s.today,l):i.period==="all"?z(s.total,l):z(s.month,l)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(i.amount)||0),m=i.enabled&&c>0?Math.min(999,d/c*100):null,p=m===null?"ok":m>=100?"over":m>=80?"warn":"ok",b=(v,N)=>{o!==null&&a({...o,budget:{...o.budget??l.budget,[v]:N}})},g=i.period==="custom"?i.customStart+" → "+(i.customEnd??n("periodDay")):null,h=i.enabled&&m!==null?n("budgetStatus",{period:n(Ie[i.period]??"periodMonth"),amount:ce(c,l),used:ce(d,l),pct:m.toFixed(1)})+(p==="over"?n("overLimit"):p==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:i.enabled===!0,onChange:v=>b("enabled",v.target.checked)}),e("span",null,n("enableBudget")))),i.enabled?e(E,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(p==="ok"?"":p),style:{width:(m===null?0:Math.min(100,m))+"%"}})),e("div",{className:"cm-budget-line"+(p==="over"?" over":"")+" cm-num"},h),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ae({value:i.amount},v=>b("amount",v))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:i.period,onChange:v=>b("period",v.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),i.period==="custom"?e(E,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:i.customStart??"",onChange:v=>b("customStart",v.target.value===""?null:v.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:i.customEnd??"",onChange:v=>b("customEnd",v.target.value===""?null:v.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function vs(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=(c,m)=>{o!==null&&a({...o,[c]:m})},r=o===null?l:{...l,...o},u=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),m=Date.now();if(Number.isFinite(c)&&m<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const p=r.peakWindows??[],b=at(m,p,r.peakHolidays);return b===null?n("offPeakActive"):b.holiday===!0?n("holidayAllOffPeak"):b.weekend===!0?n("weekendAllOffPeak"):b.inPeak?n("peakActive"):n("offPeakActive")})(),d=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(W(r.locale)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:u}):n("noPeakWindows",{status:u});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>i("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>i("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>i("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>i("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const m=Number(c.target.value);Number.isInteger(m)&&m>=1&&m<=30&&i("peakAlertAhead",m)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>i("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>i("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{i("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?ot(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},d),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>i("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ae(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const l=Number(n);Number.isFinite(l)&&l>=0&&s(l)}})}function It(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:l,t:i}=t,r=Ze(o),u=p=>{const b={...Ze(p)};if(Array.isArray(p.rateHistory)){const g=p.rateHistory.filter(h=>Date.parse(h.before)<=Date.now());g.length>0?b.rateHistory=g:delete b.rateHistory}return b},d=(p,b,g)=>{if(g===null){if(a){const T=u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),A={...T[p]??{}};delete A[b];const L={...T};Object.keys(A).length>0?L[p]=A:delete L[p],l({...n,prices:{...n.prices,default:L}});return}const x={...n.prices.models},f=u(x[s]??{cacheHit:0,cacheMiss:0,output:0}),S={...f[p]??{}};delete S[b];const y={...f};Object.keys(S).length>0?y[p]=S:delete y[p],x[s]=y,l({...n,prices:{...n.prices,models:x}});return}const h=Math.max(0,g);if(a){let f={...u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(p==="base")f[b]=h;else{const S={...f[p]??{},[b]:h};f={...f,[p]:S}}l({...n,prices:{...n.prices,default:f}});return}const v={...n.prices.models},N=u(v[s]??{cacheHit:0,cacheMiss:0,output:0});let C={...N};if(p==="base")C[b]=h;else{const x={...N[p]??{},[b]:h};C={...N,[p]:x}}v[s]=C,l({...n,prices:{...n.prices,models:v}})},c=()=>{const p={...n.prices.models};delete p[s],l({...n,prices:{...n.prices,models:p}})},m=(p,b)=>{const g=b==="base"?r:r[b]??null,h=b==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:b},e("span",null,p),ae({value:g?.cacheHit??null,emptyMode:h},v=>d(b,"cacheHit",v)),ae({value:g?.cacheMiss??null,emptyMode:h},v=>d(b,"cacheMiss",v)),ae({value:g?.output??null,emptyMode:h},v=>d(b,"output",v)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(E,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},i("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},i("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},i("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatCached")),e("span",null,i("flatInput")),e("span",null,i("flatOutput"))),m(i("tierBase"),"base"),m(i("tierOffPeak"),"offPeak"),m(i("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},i("datedPriceNote")):null)}const Da={deepseek:"DeepSeek",openai:"OpenAI",anthropic:"Anthropic",google:"Google Gemini",moonshot:"Moonshot (Kimi)","z-ai":"Z.ai / 智谱",xai:"xAI",alibaba:"阿里云百炼",minimax:"MiniMax",tencent:"腾讯混元",xiaomi:"小米",upstage:"Upstage",nvidia:"NVIDIA",mistral:"Mistral",meta:"Meta",meituan:"美团 LongCat","opencode-go":"OpenCode Go"};function Ns(t,s,o="USD"){if(t=Ze(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");o==="CNY"&&t.cny&&(t=t.cny);const a=l=>(o==="CNY"?"¥":"$")+String(l),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function Ss(t){const{state:s,draft:o,setDraft:a,t:n}=t,[l,i]=R(!1),[r,u]=R({}),d=s.priceCatalog;if(d===null||typeof d!="object")return null;const c=o?.prices??s.config.prices,m=o?.priceTableDisplay??s.config.priceTableDisplay??{},p=(y,T)=>{const A=m[y+":"+T];return typeof A=="boolean"?A:y==="deepseek"},b=(y,T,A)=>{o!==null&&a({...o,priceTableDisplay:{...m,[y+":"+T]:A}})},g=(y,T)=>y==="deepseek"?c.models?.[T]!==void 0:c.providers?.[y]?.models?.[T]!==void 0,h=(y,T,A)=>{if(o===null)return;const L=JSON.parse(JSON.stringify(A));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[T]:L}}});return}const M={...o.prices.providers??{}},j=M[y]??{};M[y]={...j,models:{...j.models??{},[T]:L}},a({...o,prices:{...o.prices,providers:M}})},v=(y,T)=>{if(o===null)return;if(y==="deepseek"){const M={...o.prices.models};delete M[T],a({...o,prices:{...o.prices,models:M}});return}const A={...o.prices.providers??{}},L=A[y];if(L!==void 0&&L.models!==void 0){const M={...L.models};delete M[T],A[y]={...L,models:M},a({...o,prices:{...o.prices,providers:A}})}},N=Object.keys(d).sort((y,T)=>y==="deepseek"?-1:T==="deepseek"?1:y.localeCompare(T)),C=y=>Object.values(d[y]).reduce((T,A)=>T+Object.keys(A).length,0),x=new Set(Object.values(d.deepseek??{}).flatMap(y=>Object.keys(y))),f=Object.keys(c.models??{}).filter(y=>!x.has(y)).sort(),S=(y,T,A)=>{const L=g(y,T),M=p(y,T),j=L?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:M,onChange:k=>b(y,T,k.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(L&&!M&&o!==null){const k=y==="deepseek"?e(It,{key:T,modelId:T,entry:c.models[T],isDefault:!1,draft:o,setDraft:a,t:n}):e(Ea,{key:T,provider:y,modelId:T,entry:c.providers?.[y]?.models?.[T],draft:o,setDraft:a,t:n});return e("div",{key:T,className:"cm-catalog-mounted"},j,k)}return e("div",{key:T,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},T),e("span",{className:"cm-catalog-price"},Ns(A,n,y==="deepseek"||A?.cny?c.currency:"USD")),L?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,j,e("button",{className:"cm-btn small",disabled:!L&&A?.unpriced===!0,onClick:()=>L?v(y,T):h(y,T,A)},n(L?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>i(y=>!y)},n(l?"catalogCollapse":"catalogOpen"))),l?e(E,null,e("p",{className:"cm-note"},n("catalogNote")),N.map(y=>{const T=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>u(A=>({...A,[y]:!T}))},e("span",null,(T?"▾ ":"▸ ")+(Da[y]??y)+" · "+C(y))),T?e(E,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(d[y]).sort().map(A=>e("div",{key:A},e("div",{className:"cm-catalog-family"},A),Object.keys(d[y][A]).sort().map(L=>S(y,L,d[y][A][L])))),y==="deepseek"&&f.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),f.map(A=>S("deepseek",A,null))):null):null)})):null)}const Ba=t=>t==="zen"?"go":t,jt=t=>{const s=t.indexOf(":");return s<=0?t:Ba(t.slice(0,s).toLowerCase())+t.slice(s)};function Ra(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],l=d=>Number.isFinite(Number(d))&&Number(d)>0?Number(d):0,i=(d,c,m)=>{if(!m||typeof m!="object")return;const p=d[c]??(d[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)p[g]+=l(m[g]);const b=c.indexOf(":");p.apiCost+=l(m.apiCost??(Qe(b>0?c.slice(0,b):"deepseek",b>0?c.slice(b+1):c,s)==="plan"?0:m.cost))},r=d=>{if(!d||typeof d!="object")return{};if(d.byProviderModel&&Object.keys(d.byProviderModel).length)return d.byProviderModel;if(d.byModel&&Object.keys(d.byModel).length)return Object.fromEntries(Object.entries(d.byModel).map(([m,p])=>[m.includes(":")?m:"deepseek:"+m,p]));const c={};for(const m of Array.isArray(d.sessions)?d.sessions:[])if(!(!m||typeof m!="object"))if(m.byProviderModel&&Object.keys(m.byProviderModel).length)for(const[p,b]of Object.entries(m.byProviderModel))i(c,p,b);else i(c,(m.provider||"deepseek")+":"+(m.model||"unknown"),m);return Object.keys(c).length?c:n.some(m=>l(d[m])>0)?{"deepseek:legacy":d}:{}};return(d=>{const c={},m=p=>{for(const[b,g]of Object.entries(p??{}))i(c,b,g)};if(d==="today")m(r(t.today));else{const p=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const b of t.history??[]){const g=Date.parse(b.date+"T00:00:00Z");g<=p&&g>=p-76896e5&&m(r(b))}}return Object.entries(c).map(([p,b])=>{const g=p.indexOf(":"),h=(g>0?p.slice(0,g):"deepseek").toLowerCase(),v=g>0?p.slice(g+1):p,N=b.input+b.output+b.cacheRead+b.cacheWrite+b.reasoning,C=b.cacheRead+b.input;return{label:p==="deepseek:legacy"?o("modelStatsLegacy"):h==="deepseek"||h===""?v:Ba(h)+":"+v,key:p,...b,tokens:N,cls:Qe(h,v,s),hitRate:C>0?b.cacheRead/C:null,cacheUnreported:bn(b),blended:N>0&&b.cost>0?b.cost/N*1e6:null,perUsd:b.cost>0?N/b.cost:null}}).filter(p=>p.tokens>0||p.cost>0)})(a).sort((d,c)=>c.cost-d.cost||c.tokens-d.tokens)}function Cs(t){const{state:s,config:o,t:a,initialTab:n,draft:l,setDraft:i}=t,[r,u]=R(n==="history"?"history":"today"),[d,c]=R(!1),m=Ra(s,o,a,r),p=f=>(Math.max(0,Math.min(1,f))*100).toFixed(1)+"%",b=m.reduce((f,S)=>Math.max(f,S.cost),0),g=m.reduce((f,S)=>Math.max(f,S.tokens),0),h=m.reduce((f,S)=>Math.max(f,S.perUsd??0),0),v=(f,S)=>e("button",{className:"cm-mstats-tab"+(r===f?" active":""),onClick:()=>u(f)},S),N=f=>f.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,C=f=>e("select",{className:"cm-input",title:a("billingClassLabel"),value:o.planBilling?.models?.[f.key]??"auto",disabled:l===null,onChange:S=>{const y={...l.planBilling?.models??{}};S.target.value==="auto"?delete y[f.key]:y[f.key]=S.target.value,i({...l,planBilling:{...l.planBilling,models:y}})}},e("option",{value:"auto"},a("billingClassAuto")),e("option",{value:"plan"},a("billingClassPlan")),e("option",{value:"api"},a("billingClassApi"))),x=(f,S,y,T,A)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:f},f,A??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+y,style:{width:p(S)}})),e("span",{className:"cm-mstats-val"},T));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(d,()=>c(!d),a("modelStatsTitle"))),d?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},v("today",a("modelStatsToday")),v("history",a("modelStatsHistory"))),m.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(E,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),m.map(f=>e(E,{key:"c:"+f.label},x(f.label,b>0?f.cost/b:0,"cost",Y(f.cost,o),e(E,null,N(f),C(f),f.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...m].sort((f,S)=>S.tokens-f.tokens).map(f=>e("div",{className:"cm-mstats-row",key:"t:"+f.label},e("span",{className:"cm-mstats-name",title:f.label},f.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:p(g>0?f.input/g:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:p(g>0?(f.cacheRead+f.cacheWrite)/g:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:p(g>0?(f.output+f.reasoning)/g:0)}})),e("span",{className:"cm-mstats-val"},I(f.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...m].sort((f,S)=>(S.hitRate??-1)-(f.hitRate??-1)).map(f=>e(E,{key:"h:"+f.label},x(f.label,f.hitRate??0,"hit",f.cacheUnreported?a("modelStatsHitUnreported"):f.hitRate===null?"—":(f.hitRate*100).toFixed(1)+"%",f.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...m].sort((f,S)=>(S.perUsd??-1)-(f.perUsd??-1)).map(f=>e(E,{key:"v:"+f.label},x(f.label,h>0?(f.perUsd??0)/h:0,"value",f.perUsd===null?"—":I(f.perUsd)+" tok/$"+(f.blended!==null?" · "+a("modelStatsBlended",{price:"$"+f.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function As(t,s){return t==="fiveHour"?s==="en"?"5-hour":"5 小时":t==="weekly"?s==="en"?"This week":"本周":t==="monthly"?s==="en"?"This month":"本月":t==="daily"?s==="en"?"Today":"当日":t}function Ms(t,s){if(t==="go")return"OpenCode Go";const o=Ee.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const La=["fiveHour","weekly","monthly","daily"];function Ps(t,s){const o=new Map,a=n=>{const l=new Date(n),i=r=>String(r).padStart(2,"0");if(s==="monthly")return l.getFullYear()+"-"+i(l.getMonth()+1);if(s==="weekly"){const r=new Date(l.getFullYear(),l.getMonth(),l.getDate()-(l.getDay()+6)%7);return r.getFullYear()+"-"+i(r.getMonth()+1)+"-"+i(r.getDate())}return l.getFullYear()+"-"+i(l.getMonth()+1)+"-"+i(l.getDate())};for(const n of Object.values(t??{}))for(const l of n??[]){if(l===null||typeof l!="object"||!(l.tokens>0)&&!(l.cost>0))continue;const i=a(Number(l.t1)||Number(l.t0)),r=o.get(i)??{key:i,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(l.tokens)||0,r.cost+=Number(l.cost)||0,r.pct+=Number(l.pct)||0,r.intervals+=1,o.set(i,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,l)=>n.key<l.key?-1:n.key>l.key?1:0)}function Ts(t){const{state:s,config:o,t:a}=t,[n,l]=R(!1),[i,r]=R("daily"),u=W(o?.locale),d=s?.planStats,c=d!=null&&typeof d.providers=="object"?d.providers:{},m=Object.keys(c).sort(),p=y=>Y(Number(y)||0,o??s?.config),b=y=>y.method==="none"||y.per1Tokens===null?"—":I(y.per1Tokens)+" tok · "+p(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":I(y.fullTokens)+" tok · "+p(y.fullCost),h=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),v=y=>{let T=h(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(T=a("planStatsMethodSampleAt",{method:T,time:new Date(Number(y.sampleAt)).toLocaleString(u==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(T+=" · "+a("planStatsConfidenceLow")),T},N=([y,T,A])=>e("tr",{key:T+":"+y},e("td",null,As(y,u)),e("td",{className:"num"},Math.round(A.percent*10)/10+"%"),e("td",{className:"num"},I(A.localTokens)+" tok · "+p(A.localCost)),e("td",{className:"num"},b(A)),e("td",{className:"num"},g(A)),e("td",{className:"num cm-plan-reset"},A.resetsAt.length>0?a("planStatsResets",{time:new Date(A.resetsAt).toLocaleString(u==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},v(A))),C=n?m.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,T])=>({winKey:y,list:T})):[],x=Ps(Object.fromEntries(C.map(y=>[y.winKey,y.list])),i),f=x.reduce((y,T)=>Math.max(y,T.fullTokens??0),0),S=(y,T)=>e("button",{key:y,className:"cm-mstats-tab"+(i===y?" active":""),onClick:()=>r(y)},T);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Le(n,()=>l(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},m.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(E,null,m.map(y=>{const T=c[y]?.windows??{},A=[...La.filter(L=>T[L]!==void 0).map(L=>[L,y,T[L]]),...Object.keys(T).filter(L=>!La.includes(L)).map(L=>[L,y,T[L]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},Ms(y,a),e("span",{className:"cm-plan-updated"},(()=>{const L=Number(c[y]?.generatedAt)||Number(d?.generatedAt)||0;return L>0?new Date(L).toLocaleTimeString(u==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,A.map(N))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},S("daily",a("planStatsDaily")),S("weekly",a("planStatsWeekly")),S("monthly",a("planStatsMonthly"))),x.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(E,null,[...x].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(f>0?(y.fullTokens??0)/f*100:0).toFixed(1)+"%"}})),e(Z,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":I(y.fullTokens),per1:y.per1Tokens===null?"—":I(y.per1Tokens),tokens:I(y.tokens),cost:p(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":I(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Ea(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:l,t:i}=t,r=m=>{const p={...n.prices.providers??{}},b=p[s]??{};p[s]={...b,models:m},l({...n,prices:{...n.prices,providers:p}})},u=(m,p)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}};b[o]={...b[o]??{},[m]:Math.max(0,p)},r(b)},d=(m,p)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}},g=b[o]??{};b[o]={...g,cny:{...g.cny,[m]:Math.max(0,p)}},r(b)},c=()=>{if(n===null)return;const m={...(n.prices.providers??{})[s]?.models??{}};delete m[o],r(m)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(E,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},i("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:c},i("unmountBtn")))),a?.unpriced===!0?null:e(E,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatInput")),e("span",null,i("flatCached")),e("span",null,i("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ae({value:a?.input??null,emptyMode:"ignore"},m=>u("input",m)),ae({value:a?.cachedInput??null,emptyMode:"ignore"},m=>u("cachedInput",m)),ae({value:a?.output??null,emptyMode:"ignore"},m=>u("output",m))),a?.cny?e("div",{className:"cm-price-row"},e("span",null,"CNY"),ae({value:a.cny.cacheMiss,emptyMode:"ignore"},m=>d("cacheMiss",m)),ae({value:a.cny.cacheHit,emptyMode:"ignore"},m=>d("cacheHit",m)),ae({value:a.cny.output,emptyMode:"ignore"},m=>d("output",m))):null))}const Ke=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Ut=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function Os(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r,u]=Ye(a,()=>o.refreshBalance()),d=s.balance,c=s.config,m=s.reconcile,p=(n?.balance??c.balance??{}).reconcile!==!1,b=v=>{n===null||typeof l!="function"||l({...n,balance:{...n.balance??c.balance??{},reconcile:v.target.checked}})},g=v=>Ne(v,c,d?.currency),h=d.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:g(d.totalBalance),granted:g(d.grantedBalance),toppedUp:g(d.toppedUpBalance),time:d.fetchedAt>0?new Date(d.fetchedAt).toLocaleTimeString():"—"}))):d.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:d.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:u,disabled:i},a(i?"refreshing":"refreshBalance"))),h,e("label",null,a("balanceApiKey")),e(De,{target:"balance",configured:d.keyConfigured,source:d.keySource,t:a,api:o,placeholder:"sk-…"}),e("p",{className:"cm-hint"},a("balanceKeyHint")),m!==void 0&&m.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+m.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:p,onChange:b}),a("reconcileLabel")),Ut(r))}function ct(t){const{name:s,enabled:o,saved:a,busy:n,open:l,statusNode:i,configNode:r,errorMsg:u,onToggle:d,onRefresh:c,onRemove:m,onToggleOpen:p,t:b}=t,g=r!=null;return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":b("enable")+": "+s,checked:o===!0,onChange:h=>d(h.target.checked)})),e("div",{className:"cm-quota-name"},g?Le(l===!0,p,s):e("h3",{className:"cm-h"},s)),m?e("button",{className:"cm-btn small",onClick:m},b("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:c,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?b("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?b("quotaRefreshReady"):b("refresh")},b(n===!0?"refreshing":"refresh"))),i,g&&l===!0?e("div",{className:"cm-collapse-body"},r):null,u!=null?e("div",{className:"cm-msg "+u.kind},u.text):null)}function Ye(t,s){const[o,a]=R(!1),[n,l]=R(null),i=Pe(!1);return[o,n,async()=>{if(!i.current){i.current=!0,a(!0),l(null);try{const u=await s();l({kind:u.ok?"ok":"err",text:u.message})}catch(u){l({kind:"err",text:t("syncFailed",{message:u?.message??String(u)})})}finally{i.current=!1,a(!1)}}}]}const Ds=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},qa=(t,s,o,a,n,l=s)=>{if(typeof o?.percent!="number")return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const i=Math.max(0,Math.min(100,Number(o.percent)||0)),r=pe(i,a),u=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),u?e("span",{className:"cm-go-reset"},u):null)};function Bs(t){const{state:s,api:o,t:a,entry:n,index:l,canRemove:i,onPatch:r,onRemove:u}=t,d=n.adapter==="aliyun",[c,m]=R(!1),p=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[b,g]=R(p),[h,v]=R(()=>(n.allowedHosts??[]).join(", ")),[N,C]=R({}),x=Pe(!1),f=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(B=>B.index===l)??null,T=n.enabled===!0,A=()=>{m(B=>!B)};X(()=>{c&&!x.current&&(g(p()),v((n.allowedHosts??[]).join(", ")),C({})),x.current=c},[c]);const L=(B,V)=>r({[B]:V}),M=(B,V)=>r({request:{...n.request??{},[B]:V}}),j=d?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(B=>typeof B=="string"?[...B.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(V=>V[1]):[]))],k=(B,V)=>{g(w=>({...w,[B]:V}));try{const w=B==="body",q=w&&!V.trim()?void 0:JSON.parse(V);if(!w&&(q===null||typeof q!="object"||Array.isArray(q)))throw new Error("invalid");if(B==="headers"&&Object.values(q).some(Q=>typeof Q!="string"))throw new Error("invalid");C(Q=>({...Q,[B]:""})),B==="extract"?L(B,q):M(B,w?q===void 0?void 0:V:q)}catch{C(w=>({...w,[B]:a("customBalanceInvalidJson")}))}},H=(B,V,w,q)=>!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(V)),q&&e("span",{className:"cm-hint"},a(q)),e("textarea",{className:"cm-input",rows:w,value:b[B],onChange:Q=>k(B,Q.target.value)}),N[B]?e("span",{className:"cm-hint err"},N[B]):null),de=B=>{v(B);const V=B.split(/[\s,;]+/).map(w=>w.trim()).filter(w=>w.length>0);L("allowedHosts",V)},[we,Se,O]=Ye(a,()=>(f.customBalances??[])[l]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(l)),D=y!==null&&y.status==="ok"?e(E,null,f.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(St,{segments:Nt(s,f,y,n),direction:se(f,"balance")}),e("div",{className:"cm-bal-line"},At(y,f,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:We(y.remaining,f,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),G=e(E,null,e("p",{className:"cm-note"},a(d?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:Fe(f,y,n)!=="USD",onChange:B=>L("convertToDisplayCurrency",B.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([B,V])=>e("div",{key:B,className:"cm-field"},e("label",null,a(V)),e("input",{className:"cm-input",value:n[B]??"",onChange:w=>L(B,w.target.value)}))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:B=>L("unit",B.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:B=>L("display",B.target.value)},...Ke(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ae({value:n.refreshMinutes??15},B=>L("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(B)))))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:B=>M("method",B.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:B=>M("url",B.target.value)})),H("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&H("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),j.length>0?e(E,null,!d&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),j.map(B=>e(De,{key:"cb-var-"+B,target:"customVar:"+B,configured:(s.customVarStatus?.[B]?.configured??!1)===!0,source:s.customVarStatus?.[B]?.source??"",t:a,api:o,placeholder:"{{"+B+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:h,placeholder:"api.example.com, relay.example.org",onChange:B=>de(B.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),H("extract","customBalanceExtract",8)));return e(ct,{name:`#${l+1} · `+(Ct(n,W(f?.locale))||a("customBalanceTitle")),enabled:T,saved:JSON.stringify(n)===JSON.stringify(f.customBalances?.[l])?f.customBalances[l]:null,busy:we,open:c,statusNode:D,configNode:G,errorMsg:Se,onToggle:B=>L("enabled",B),onRefresh:O,onRemove:i?u:null,onToggleOpen:A,t:a})}function Ia({config:t,draft:s,setDraft:o,t:a,api:n}){const l=s?.goQuota??t.goQuota,i=(r,u)=>{s&&o({...s,goQuota:{...l,[r]:u}})};return e(E,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,u])=>e("div",{key:r,className:"cm-field"},e("label",null,a(u)),e("select",{className:"cm-input",value:l[r],onChange:d=>i(r,d.target.value)},r==="display"?Ke(a):["rolling","weekly","monthly"].map((d,c)=>e("option",{key:d,value:d},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ae({value:l.refreshMinutes},r=>i("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function Rs(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r]=R(!1),u=s.goQuota,d=s.config,c=n?.goQuota?.enabled??d.goQuota?.enabled??!0,m=(f,S)=>{n!==null&&l({...n,goQuota:{...n.goQuota??d.goQuota,[f]:S}})},[p,b,g]=Ye(a,()=>o.refreshGoQuota()),h=d.goQuota?.main==="weekly"||d.goQuota?.main==="monthly"?d.goQuota.main:"rolling",v=[h,...["rolling","weekly","monthly"].filter(f=>f!==h)],N=f=>f==="rolling"?"goWindowRolling":f==="weekly"?"goWindowWeekly":"goWindowMonthly",C=f=>f==="rolling"?u.rolling:f==="weekly"?u.weekly:u.monthly,x=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},v.map(f=>qa(a,a(N(f)),C(f),se(d,"go"),f===h)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||a("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(ct,{name:a("goQuotaTitle"),enabled:c,saved:d.goQuota,busy:p,open:i,statusNode:x,errorMsg:b,configNode:e(Ia,{config:d,draft:n,setDraft:l,t:a,api:o}),onToggleOpen:()=>r(f=>!f),onToggle:f=>m("enabled",f),onRefresh:g,t:a})}const Ls=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Es(t){const{state:s,api:o,t:a,draft:n,setDraft:l,index:i}=t,r=s.config,d=(n??r).gatewayQuotas?.sources??[],c=d[i]??{},p=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(M=>M.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},b=Ls(c,s.customVarStatus),[g,h]=R(!1),[v,N,C]=Ye(a,()=>o.refreshGatewayQuota(c.id)),x=M=>{n!==null&&l({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:M}})},f=M=>x(d.map((j,k)=>k===i?{...j,...M}:j)),S=(M,j,k)=>e("div",{className:"cm-field"},e("label",null,M),e("input",{className:"cm-input",value:j??"",onChange:k})),y=(M,j)=>{const k=Ge(M?.label||M?.id||a("gatewaySourceUnknown"),M,se(r,"plan"),a);return e(E,{key:M?.id||j},k.row,M?.resetsAt?e("div",{className:"cm-note"},ze(M,a)):null)},T=(M,j)=>e("div",{key:M.id||j,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(M.used??"—")+" / "+(M.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(M.remaining??"—")+" remaining")),A=M=>M==null?null:e(E,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(M.used??"—")+" / "+(M.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(M.remaining??"—")+" remaining")),(M.packages??[]).map(T)),L=(M,j)=>e("div",{key:M.id||j,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Jt[M.provider]??M.provider??a("gatewaySourceUnknown"))+" · "+(M.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},M.status)),M.plan?e("div",{className:"cm-note"},M.plan):null,M.windows.length>0?e("div",{className:"cm-go-list"},M.windows.map(y)):null,A(M.credits),M.message?e("div",{className:"cm-note"},M.message):null);return e(ct,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(M=>M.id===c.id),busy:v,open:g,errorMsg:N,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(p.status??a("gatewaySourceUnknown"))+(p.serverVersion?" · "+p.serverVersion:"")+(p.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(p.fetchedAt).toLocaleTimeString()}):"")+(p.message?" · "+p.message:"")),configNode:e(E,null,e("div",{className:"cm-grid"},S(a("gatewaySourceLabel"),c.label,M=>f({label:M.target.value})),S(a("gatewaySourceBaseURL"),c.baseURL,M=>f({baseURL:M.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:M=>f({display:M.target.value})},...Ke(a))),S(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),M=>f({allowedHosts:M.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:M=>f({antigravityOnlyGemini:M.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),b?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+b,configured:s.customVarStatus?.[b]?.configured===!0,source:s.customVarStatus?.[b]?.source??"",t:a,api:o,placeholder:b})):null,p.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+p.unsupportedProviders.join(", ")):null,p.accounts.length>0?p.accounts.map(L):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:M=>f({enabled:M}),onRefresh:C,onRemove:()=>x(d.filter((M,j)=>j!==i)),onToggleOpen:()=>h(M=>!M),t:a})}const Ee=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function qs(t){const{state:s,api:o,t:a,draft:n,setDraft:l,planId:i,labelKey:r}=t,u=s.config,d=s.codingPlans??{},c=n?.codingPlans?.[i]??u.codingPlans?.[i]??{},m=d[i]??{status:"off",message:"",fetchedAt:0,windows:{}},p=c.enabled===!0,[b,g]=R(!1),[h,v,N]=Ye(a,()=>o.refreshCodingPlan(i)),C=(O,D)=>{if(n===null)return;const G=n.codingPlans??u.codingPlans??{};l({...n,codingPlans:{...G,[i]:{...G[i]??{},[O]:D}}})},[x,f]=R(""),[S,y]=R({}),T=O=>O?.rates!==null&&typeof O?.rates=="object"&&!Array.isArray(O.rates)?O.rates:{},A=["input","cachedInput","output"],L=O=>S[O]??T(c)[O]??{},M=O=>A.every(D=>Number.isFinite(Number(O[D]))&&Number(O[D])>0),j=(O,D,G)=>{if(n===null)return;const B={...L(O),[D]:String(G)};y(Q=>({...Q,[O]:B}));const V=A.every(Q=>String(B[Q]??"").trim()==="");if(!V&&!M(B))return;const w=n.codingPlans??u.codingPlans??{},q={...(w.qwen??{}).rates??{}};V?delete q[O]:q[O]=Object.fromEntries(A.map(Q=>[Q,Number(B[Q])])),l({...n,codingPlans:{...w,qwen:{...w.qwen??{},rates:q}}})},k=O=>{n!==null&&y(D=>({...D,[O]:D[O]??T(c)[O]??{}}))},H=O=>{if(n===null)return;y(B=>{const V={...B};return delete V[O],V});const D=n.codingPlans??u.codingPlans??{},G={...(D.qwen??{}).rates??{}};delete G[O],l({...n,codingPlans:{...D,qwen:{...D.qwen??{},rates:G}}})},de=m.windows!==null&&typeof m.windows=="object"?m.windows:{},we=p===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):m.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(de).length>0?i==="minimax"&&(_e(de).five!=null||_e(de).seven!=null)?e(Sa,{five:_e(de).five,seven:_e(de).seven,fetchedAt:m.fetchedAt,t:a,wide:!0,direction:se(u,"plan")}):Object.entries(de).map(([O,D])=>qa(a,O.replace(/_/g," "),D,se(u,"plan"),!1,O)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:m.fetchedAt>0?new Date(m.fetchedAt).toLocaleTimeString():"—"}))):m.status==="error"?e("div",{className:"cm-bal-line err"},m.message||a("unknownError")):m.status==="off"&&m.message?e("p",{className:"cm-note"},m.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),Se=e(E,null,i==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:O=>C("baseUrl",O.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,i==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:O=>C("quotaSource",O.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:i==="minimax"?"both":"settings",onChange:O=>C("display",O.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),i!=="scnet"&&(i!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ae({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},O=>{C("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(O))))})):null,i==="scnet"||i==="qwen"&&(c.quotaSource??"local")==="local"?e(E,null,e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:i==="qwen"?5e5:24e4,onChange:O=>{const D=Number(O.target.value);Number.isFinite(D)&&D>0&&C("planCredits",Math.floor(D))}})),e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:O=>C("planStart",O.target.value)})),i==="qwen"?e(E,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(T(c)),...Object.keys(S)])].sort().map(O=>e("div",{key:O,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},O),A.map(D=>e("input",{key:D,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:L(O)[D]??"",placeholder:a("qwenRate_"+D),"aria-label":O+" · "+a("qwenRate_"+D),onChange:G=>{const B=G.target.value;j(O,D,B)}})),e("button",{className:"cm-btn small",onClick:()=>H(O)},a("overrideRemove")),O in S&&!M(L(O))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:x,onChange:O=>f(O.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const O=x.trim();O.length!==0&&(k(O),f(""))},disabled:x.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(i==="qwen"?"qwenLocalNote":"scnetLocalNote"))):i==="qwen"?null:i==="volcengine"?e(E,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(E,null,e("div",{className:"cm-field"},e("label",null,i==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+i,configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:i==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(ct,{name:a(r),enabled:p,saved:u.codingPlans?.[i],busy:h,open:b,errorMsg:v,statusNode:we,configNode:Se,onToggle:O=>C("enabled",O),onRefresh:N,onToggleOpen:()=>g(O=>!O),t:a})}function Is(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,i=s.config,r=n??i,u=r.codingPlans??{},d=r.gatewayQuotas?.sources??[],c=n?.customBalances??i.customBalances??[],m=x=>{n!==null&&l({...n,customBalances:x,...x.length===0?{customBalance:{...i.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},p=Pe({next:0,keys:[]}).current;for(;p.keys.length<c.length;)p.keys.push(p.next++);p.keys.length=c.length;const b=x=>{p.keys.splice(x,1),m(c.filter((f,S)=>S!==x))},g=(x,f)=>m(c.map((S,y)=>y===x?{...S,...f}:S)),h=(x="custom")=>{c.length>=8||m([...c,{...x==="aliyun"?{adapter:x}:{},enabled:!1,label:x==="aliyun"?"千问 / 阿里云":"",labelEn:x==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:x==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:x==="aliyun"?"https://business.aliyuncs.com/":"",method:x==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},v=()=>{d.length>=4||n===null||l({...n,gatewayQuotas:{...n.gatewayQuotas??i.gatewayQuotas??{},sources:[...d,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:gt,allowedHosts:[],allowInsecureHttp:!1}]}})},N=[...d.map((x,f)=>({kind:"gateway",key:"gw-"+(x.id??f),index:f,enabled:x.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Ee.map(x=>({kind:"plan",key:"plan-"+x.id,planId:x.id,labelKey:x.labelKey,enabled:u[x.id]?.enabled===!0})),...c.map((x,f)=>({kind:"custom",key:"cb-"+p.keys[f],index:f,enabled:x.enabled===!0}))],C=x=>x.kind==="plan"?e(qs,{key:x.key,planId:x.planId,labelKey:x.labelKey,state:s,api:o,t:a,draft:n,setDraft:l}):x.kind==="go"?e(Rs,{key:x.key,state:s,api:o,t:a,draft:n,setDraft:l}):x.kind==="gateway"?e(Es,{key:x.key,index:x.index,state:s,api:o,t:a,draft:n,setDraft:l}):e(Bs,{key:x.key,state:s,api:o,t:a,entry:c[x.index],index:x.index,canRemove:!0,onPatch:f=>g(x.index,f),onRemove:()=>b(x.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ds(N).map(C)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:v,disabled:d.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>h(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>h("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const js=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ja=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function Ht(t){const s=t.useCost?t.useCost(f=>f):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=W(a?.locale),l=t.t??K(n),i=Array.isArray(o.history)?o.history:[];if(i.length===0)return e("div",null,e("h3",{className:"cm-h"},l("usageTitle")),e("p",{className:"cm-empty"},l("usageEmpty")));const r=o.meta?.dayKey??"",u=new Map(i.map(f=>[f.date,f])),d=f=>{const S=y=>String(y).padStart(2,"0");return f.getFullYear()+"-"+S(f.getMonth()+1)+"-"+S(f.getDate())},c=new Date;c.setHours(0,0,0,0);const m=new Date(c);m.setDate(m.getDate()+(6-(c.getDay()+6)%7));const p=26,b=[],g=[];let h=-1;for(let f=p-1;f>=0;f-=1){for(let y=0;y<7;y+=1){const T=new Date(m);T.setDate(T.getDate()-(f*7+(6-y)));const A=u.get(d(T));b.push(A!==void 0?{day:A,tokens:ja(A)}:{day:{date:d(T)},tokens:0})}const S=new Date(m);S.setDate(S.getDate()-(f*7+6)),g.push(S.getMonth()!==h?n==="en"?js[S.getMonth()]:String(S.getMonth()+1)+"月":""),h=S.getMonth()}const v=Math.max(...b.map(f=>f.tokens),1),N=f=>{const S=f/v;return S<.25?1:S<.5?2:S<.75?3:4},C=f=>{const{day:S,tokens:y}=f,T="cm-ug-cell"+(y>0?" l"+N(y):"")+(S.date===r?" today":""),A=l("usageDay",{date:S.date,tokens:I(y),input:I(S.input??0),cache:I((S.cacheRead??0)+(S.cacheWrite??0)),output:I(S.output??0),calls:S.calls??0,cost:Y(z(S,a),a)});return e(Z,{key:S.date,label:A,side:"top",delayMs:200},e("div",{className:T}))},x=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},l("usageTitle")),e("div",{className:"cm-ug-total"},l("usageTotal",{tokens:I(ja(x)),input:I(x.input??0),cache:I((x.cacheRead??0)+(x.cacheWrite??0)),output:I(x.output??0),calls:x.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+p+",1fr)"}},b.map(C)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+p+",1fr)"}},g.map((f,S)=>e("span",{key:"m"+String(S),className:"cm-ug-monthc"},f))))}function Us(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.api,a=s?.state??null,[n,l]=R(null),[i,r]=R(null),[u,d]=R(!1),[c,m]=R(!1),[p,b]=R(!1),[g,h]=R(""),[v,N]=R(!1),[C,x]=R(!1),[f,S]=R("overview"),[y,T]=R({status:"idle",at:0,error:null}),A=Be.useRef(null),L=Be.useRef(null),M=Be.useRef(null);X(()=>{if(a!==null){const w=JSON.stringify(a.config);l(q=>{const Q=q!==null&&JSON.stringify(q)!==A.current;return Q||(L.current=a.config,M.current=a.config),Q?q:JSON.parse(w)}),A.current=w}},[a]),X(()=>{n!==null&&M.current===null&&L.current!==null&&(M.current=L.current)},[n]),X(()=>{if(n===null||o===void 0)return;const w=JSON.stringify(n);if(w===A.current)return;T(Q=>Q.status==="saving"?Q:{...Q,status:"saving"});const q=setTimeout(()=>{const Q={},ue=M.current??L.current;if(ue!==null&&typeof ue=="object")for(const J of Object.keys(n))JSON.stringify(n[J])!==JSON.stringify(ue[J])&&(Q[J]=n[J]);if(Object.keys(Q).length===0){A.current=w,T({status:"saved",at:Date.now(),error:null});return}o.updateConfig(Q).then(()=>{A.current=w,ue!==null&&typeof ue=="object"&&(M.current={...ue,...Q}),T({status:"saved",at:Date.now(),error:null})},J=>{T({status:"error",at:0,error:J?.message??String(J)})})},600);return()=>{clearTimeout(q)}},[n,o]),X(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:k("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const j=W((n??a?.config)?.locale),k=K(j);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?k("readingLedger"):k("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},k("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},k("refresh")));const H=a.config,de=async()=>{if(!v){N(!0),r(null);try{const w=await o.fetchPrices();if(r({kind:w.ok?"ok":"err",text:w.message}),w.ok&&w.state&&typeof w.state.config=="object"){const q=JSON.stringify(w.state.config);l(JSON.parse(q)),A.current=q}}catch(w){r({kind:"err",text:k("syncFailed",{message:w?.message??String(w)})})}finally{N(!1),d(!1)}}},we=async()=>{if(!v){N(!0);try{await o.resetHistory(),r({kind:"ok",text:k("historyCleared")})}catch(w){r({kind:"err",text:k("clearFailed",{message:w?.message??String(w)})})}finally{N(!1),m(!1)}}},Se=async()=>{if(!v){N(!0),r(null);try{const w=await o.importLegacyHistory();r({kind:"ok",text:w.message})}catch(w){r({kind:"err",text:k("legacyImportFailed",{message:w?.message??String(w)})})}finally{N(!1),b(!1)}}},O=(w,q)=>{n!==null&&l({...n,[w]:q})},D=()=>{if(n===null)return;const w=g.trim().toLowerCase();if(w.length===0||!/^[a-z0-9_.-]+$/.test(w)||n?.prices.models[w]!==void 0)return;const q={...n.prices.models,[w]:{cacheHit:0,cacheMiss:0,output:0}};l({...n,prices:{...n.prices,models:q}}),h("")},G=n===null?[]:Object.keys(n.prices.models).filter(w=>{const Q=(n?.priceTableDisplay??H.priceTableDisplay??{})["deepseek:"+w];return typeof Q=="boolean"?Q:!0}).map(w=>e(It,{key:w,modelId:w,entry:n.prices.models[w]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:l,t:k})),B=[["overview",k("tabOverview")],["statistics",j==="en"?"Cost statistics":"计费统计"],["quotas",k("tabQuotas")],["usage",k("tabUsage")],["pricing",k("tabPricing")],["display",k("tabDisplay")]],V=y.status==="saving"?e("span",{className:"cm-hint"},k("saving")):y.status==="error"?e("span",{className:"cm-msg err"},k("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?k("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):k("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},B.map(([w,q])=>e("button",{key:w,type:"button",role:"tab","aria-selected":String(f===w),className:"cm-tab"+(f===w?" active":""),onClick:()=>S(w)},q))),V),Ut(i),f==="statistics"?e(Oa,{state:a,api:o}):null,f==="overview"?e(E,{key:"overview"},e("div",{className:"cm-cards"},H.hideTodayCost===!0?null:e(rt,{title:k("cardToday"),value:Y(z(a.today,H),H),sub:k("callsTokens",{calls:a.today.calls,input:I(a.today.input),cache:I(a.today.cacheRead+a.today.cacheWrite),output:I(a.today.output)})}),e(rt,{title:k("cardMonth"),value:Y(z(a.month,H),H),sub:k("callsTokens",{calls:a.month.calls,input:I(a.month.input),cache:I(a.month.cacheRead+a.month.cacheWrite),output:I(a.month.output)})}),e(rt,{title:k("cardTotal"),value:Y(z(a.total,H),H),sub:k("cardTotalSub",{calls:a.total.calls})})),e(bs,{state:a,t:k}),e("p",{className:"cm-note",key:"cards-footnote"},k("cardsFootnote")),(()=>{const w=wn(a);return w!==null?e("p",{className:"cm-note",key:"tz-hint"},k("timezoneHint",{host:w.hostLabel,browser:w.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:k("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??H).showTotalWithPlan===!0,onChange:w=>{const q=n??H;q!=null&&l({...q,showTotalWithPlan:w.target.checked})}}),e("span",null,k("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},k("todaySessions")),e(ks,{state:a,t:k})),e(xs,{state:a,draft:n,setDraft:l,t:k}),(H.balance?.display==="settings"||H.balance?.display==="both")&&H.hideOfficialBalance!==!0?e(Os,{state:a,api:o,t:k,draft:n,setDraft:l}):null):null,f==="quotas"?e(Is,{key:"quotas",state:a,api:o,t:k,draft:n,setDraft:l}):null,f==="usage"?e(E,{key:"usage"},!Je||(H.usage?.position??"cost")==="cost"?e(Ht,{state:a,t:k,locale:j}):null,e(Cs,{state:a,config:n??H,t:k,draft:n,setDraft:l}),e(Ts,{state:a,config:n??H,t:k}),e(gs,{state:a,api:o}),e(ys,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},k("historyDataTitle")),e("div",{className:"cm-buttons"},p?e(E,null,e("span",{className:"cm-hint"},k("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:Se,disabled:v},k("apply")),e("button",{className:"cm-btn",onClick:()=>b(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>b(!0),disabled:v},k("importLegacy")),c?e(E,null,e("span",{className:"cm-hint"},k("confirmReset")),e("button",{className:"cm-btn danger",onClick:we,disabled:v},k("confirmClear")),e("button",{className:"cm-btn",onClick:()=>m(!1)},k("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>m(!0),disabled:v},k("clearAllHistory"))),e("p",{className:"cm-note"},k("legacyImportNote")))):null,f==="display"?e(E,{key:"display"},e(ps,{draft:n,setDraft:l,t:k}),a?.secretMigration?.pending?.length>0?e(vn,{pending:a.secretMigration.pending,t:k}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,k("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:w=>O("locale",w.target.value)},e("option",{value:"auto"},k("localeAuto")),e("option",{value:"zh"},k("localeZh")),e("option",{value:"en"},k("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},k("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},k("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled","codexQuotaSidebar"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:q=>O(w,q.target.checked)}),e("span",null,k(w)))),Je?e("div",{className:"cm-field"},e("label",null,k("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:w=>{n!==null&&l({...n,usage:{...n.usage??{position:"cost"},position:w.target.value}})}},e("option",{value:"cost"},k("usagePositionCost")),e("option",{value:"general"},k("usagePositionGeneral")),e("option",{value:"section"},k("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,k("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:w=>O("position",w.target.value)},e("option",{value:"dock"},k("positionDock")),e("option",{value:"header"},k("positionHeader")),e("option",{value:"off"},k("off")))),e("div",{className:"cm-field"},e("label",null,k("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:w=>O("sidebar",w.target.value==="on")},e("option",{value:"on"},k("sidebarOn")),e("option",{value:"off"},k("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:w=>O("showSessionId",w.target.checked)}),e("span",null,k("showSessionIdLabel"))),...["hideSessionCostHeader","hideSessionCostDock","hideTurnCost"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:q=>O(w,q.target.checked)}),e("span",null,k(w)))),e("div",{className:"cm-grid-group"},k("groupMoney")),e("div",{className:"cm-field"},e("label",null,k("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:w=>{const q=ws[w.target.value];q!==void 0&&n!==null&&l({...n,currency:w.target.value,...q})}},e("option",{value:"CNY"},k("currencyCny")),e("option",{value:"USD"},k("currencyUsd")),e("option",{value:"EUR"},k("currencyEur")))),e("div",{className:"cm-field"},e("label",null,k("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:w=>O("symbol",w.target.value)})),e("div",{className:"cm-field"},e("label",null,k("rateLabel")),ae({value:n?.exchangeRate??1,emptyMode:"ignore"},w=>O("exchangeRate",w))),e("div",{className:"cm-field"},e("label",null,k("decimalsLabel")),ae({value:n?.decimals??2},w=>O("decimals",Math.min(10,Math.floor(w))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:w=>O("hideOfficialBalance",w.target.checked)}),e("span",null,k("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:w=>O("hideTodayCost",w.target.checked)}),e("span",null,k("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},k("groupSidebar")),e("div",{className:"cm-field"},e("label",null,k("sidebarTodayMetric")),e("select",{className:"cm-input",value:n?.sidebarTodayMetric??"cost",onChange:w=>O("sidebarTodayMetric",w.target.value)},e("option",{value:"cost"},k("sidebarTodayCost")),e("option",{value:"tokens"},k("sidebarTodayTokens")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:w=>{n&&l({...n,sidebarSimple:w.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,k("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,k("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:w=>O("sidebarStyle",w.target.value)},e("option",{value:"standard"},k("sidebarStyleStandard")),e("option",{value:"compact"},k("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,k("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:w.target.value}})}},...Ke(k))),e("div",{className:"cm-field"},e("label",null,k("refreshIntervalLabel")),ae({value:n?.balance?.refreshMinutes??5},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:w.target.checked}})}}),e("span",null,k("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,k("balanceBudgetCapLabel")),ae({value:n?.balance?.budgetCap??""},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:w>0?w:null}})}),e("span",{className:"cm-hint"},k("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,k("barDirectionsTitle")),["balance","budget","go","plan"].map(w=>e("div",{className:"cm-dir-row",key:w},e("span",{className:"cm-dir-label"},k("barDirection_"+w)),e("select",{className:"cm-input",value:n?.barDirections?.[w]??(w==="balance"?"remaining":"used"),onChange:q=>{if(n===null)return;const Q={balance:"remaining",budget:"used",go:"used",plan:"used"};l({...n,barDirections:{...n.barDirections??Q,[w]:q.target.value}})}},e("option",{value:"remaining"},k("barDirectionRemaining")),e("option",{value:"used"},k("barDirectionUsed"))))),e("span",{className:"cm-hint"},k("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,k("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??H.customBalance?.display??"both",onChange:w=>{n!==null&&l({...n,customBalance:{...n.customBalance??H.customBalance??{},display:w.target.value}})}},...Ke(k))),e("div",{className:"cm-field"},e("label",null,k("customBalanceRefreshInterval")),ae({value:n?.customBalance?.refreshMinutes??H.customBalance?.refreshMinutes??15},w=>{n!==null&&l({...n,customBalance:{...n.customBalance??H.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e(Ia,{config:H,draft:n,setDraft:l,t:k,api:o}),e("div",{className:"cm-grid-group"},k("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:w=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:w.target.checked,promptSeen:!0}})}}),e("span",null,k("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([w,q])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[w]!==!1,onChange:Q=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip,[w]:Q.target.checked}})}}),e("span",null,k(q)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("quotaStripNote"))),e("div",{className:"cm-grid-group"},k("groupCorner")),e("div",{className:"cm-field"},e("label",null,k("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:w=>{n!==null&&l({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:w.target.checked}})}}),e("span",null,k("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([w,q])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[w]!==!1,onChange:Q=>{n!==null&&l({...n,corner:{...n.corner,[w]:Q.target.checked}})}}),e("span",null,k(q)))):null),e("div",{className:"cm-grid-group"},k("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:w=>{n!==null&&l({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:w.target.checked}})}}),e("span",null,k("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:w=>{n!==null&&l({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:w.target.checked}})}}),e("span",null,k("budgetDetailLabel"))))),e("p",{className:"cm-note"},k("badgeNote")))):null,f==="pricing"?e(E,{key:"pricing"},e(vs,{state:a,draft:n,setDraft:l,t:k}),e("div",null,Le(C,()=>x(!C),k("priceTableTitle")),C?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},k("priceTableNote")),e("p",{className:"cm-hint"},k("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},k("deepseekMountedHeader")),G,e(It,{key:"__default__",modelId:k("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:l,t:k}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:k("newModelPlaceholder"),value:g,onChange:w=>h(w.target.value)}),e("button",{className:"cm-btn small",onClick:D,disabled:g.trim().length===0},k("addModel"))),(()=>{const w=n?.priceTableDisplay??H.priceTableDisplay??{},q=n?.prices?.providers??{},Q=J=>Object.keys(q[J]?.models??{}).filter(P=>w[J+":"+P]===!0),ue=Object.keys(q).filter(J=>Q(J).length>0).sort((J,P)=>J.localeCompare(P));return ue.length===0?null:ue.map(J=>e("div",{key:J},e("div",{className:"cm-catalog-vendor"},(Da[J]??J)+" · "+k("mountedSuffix")),Q(J).sort().map(P=>e(Ea,{key:J+":"+P,provider:J,modelId:P,entry:q[J].models[P],draft:n,setDraft:l,t:k}))))})()):null),(()=>{const w=n?.priceOverrides??H.priceOverrides??{},q=n?.priceMatchDismissed??H.priceMatchDismissed??[],Q=n?.prices??H.prices,ue=a.today.byProviderModel??{},J={prices:Q,priceMatch:n?.priceMatch??H.priceMatch},P=Object.keys(ue).filter(U=>{if(q.includes(U)||w[U]!==void 0)return!1;const _=U.indexOf(":"),me=(_>0?U.slice(0,_):"deepseek").toLowerCase(),Qt=_>0?U.slice(_+1):U;return kt(me,Qt,J).matched!==!0}),F=[...new Set([...P,...Object.keys(w)])].filter(U=>!q.includes(U)),ee=a.month?.byProviderModel??{},oe=Object.keys(ee).filter(U=>{if(q.includes(U)||w[U]!==void 0)return!1;const _=U.indexOf(":"),me=(_>0?U.slice(0,_):"deepseek").toLowerCase(),Qt=_>0?U.slice(_+1):U;return kt(me,Qt,J).matched===!0}).sort(),qe=[{value:"__local__",label:k("overrideTargetLocal")},{value:"deepseek:__default__",label:k("overrideTargetDefault")},...Object.keys(Q.models??{}).map(U=>({value:"deepseek:"+U,label:"DeepSeek · "+U})),...Object.entries(Q.providers??{}).flatMap(([U,_])=>Object.keys(_?.models??{}).map(me=>({value:U+":"+me,label:U+" · "+me})))],Ce=(U,_)=>{if(n===null)return;const me={...n.priceOverrides??{}};_===""?delete me[U]:me[U]=_,l({...n,priceOverrides:me})},xe=U=>{if(n===null)return;const _={...n.priceOverrides??{}};delete _[U],l({...n,priceOverrides:_,priceMatchDismissed:[...new Set([...q,U])]})};return e("div",null,e("h3",{className:"cm-h"},k("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:U=>O("priceMatch",U.target.value)},e("option",{value:"auto"},k("priceMatchAuto")),e("option",{value:"exact"},k("priceMatchExact")))),e("p",{className:"cm-note"},k("priceMatchNote")),F.length>0?e(E,null,e("h3",{className:"cm-h"},k("unmatchedTitle")),e("p",{className:"cm-hint"},k("unmatchedHint")),F.map(U=>e("div",{key:U,className:"cm-match-row"},e("span",null,jt(U)),e("select",{className:"cm-input",value:w[U]??"",onChange:_=>Ce(U,_.target.value)},e("option",{value:""},"—"),qe.map(_=>e("option",{key:_.value,value:_.value},_.label))),e("button",{className:"cm-btn small",title:k("removePriceMatchHint"),onClick:()=>xe(U)},k("overrideRemove"))))):e("p",{className:"cm-hint"},k("overrideNone")),q.length>0?e("button",{className:"cm-btn small",onClick:()=>O("priceMatchDismissed",[])},k("restorePriceMatches",{count:q.length})):null,oe.length>0?e(E,null,e("h3",{className:"cm-h"},k("matchedTitle")),e("p",{className:"cm-hint"},k("matchedHint")),oe.map(U=>e("div",{key:U,className:"cm-match-row"},e("span",null,jt(U)),e("select",{className:"cm-input",value:"",onChange:_=>{_.target.value!==""&&Ce(U,_.target.value)}},e("option",{value:""},k("matchedKeepAuto")),qe.map(_=>e("option",{key:_.value,value:_.value},_.label)))))):null)})(),e(Ss,{state:a,draft:n,setDraft:l,t:k}),e("div",null,e("h3",{className:"cm-h"},k("dataSync")),(n??H).currency==="CNY"&&(n??H).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},k("pricingCnyHint",{rate:(n??H).exchangeRate}),(n??H).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:v,onClick:()=>O("pricingCurrency","CNY")},k("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,k("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:w=>O("pricingCurrency",w.target.value)},e("option",{value:"USD"},k("pricingCurrencyUsd")),e("option",{value:"CNY"},k("pricingCurrencyCny"))),e("p",{className:"cm-note"},k("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},u?e(E,null,e("span",{className:"cm-hint"},k("confirmFetch")),e("button",{className:"cm-btn",onClick:de,disabled:v},k("apply")),e("button",{className:"cm-btn",onClick:()=>d(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>d(!0),disabled:v},k("syncFromDocs"))),e("p",{className:"cm-note"},k("lastSync",{time:H.fetchedAt!==null?new Date(H.fetchedAt).toLocaleString():k("neverSynced")})+k("source",{source:H.priceSource==="official"?k("sourceOfficial"):k("sourceBundled")})),e("p",{className:"cm-note"},k("syncScopeNote")))):null)}const Hs=["remote"];async function Qs(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(on);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=xn({status:"loading",error:null,state:null}),l=()=>K(W(n.getSnapshot().state?.config?.locale)),i=async(P,F)=>{const ee=await a[P](...F??[]);if(ee===null||typeof ee!="object"||ee.ok!==!0)throw new Error(ee?.error?.message??l()("rpcFailed",{method:P}));return ee.value};let r=Date.now(),u=!1,d=!0,c=1;const m=async()=>{if(!d||u)return;u=!0,r=Date.now();const P=n.getSnapshot();P.state===null&&n.set({...P,status:"loading"});try{const F=await i("getState");if(!d)return;c=1,n.set({status:"ready",error:null,state:F})}catch(F){if(!d)return;P.state===null&&(r=Date.now()),c=Math.min(c*2,60),n.set({status:"error",error:F?.message??String(F),state:P.state})}finally{u=!1}};t.effect(()=>t.on("connection/reset",()=>{m()}),"cost-meter: reconnect reload");const p=setInterval(()=>{const P=n.getSnapshot().state,F=P?.config.sidebarModels,ee=P?F?.enabled||F?.dock?F.refreshSeconds:60:c;!document.hidden&&Date.now()-r>=(ee||60)*1e3&&m()},1e3);t.effect(()=>()=>{d=!1,clearInterval(p)},"cost-meter: poll timer");const b=()=>{document.visibilityState==="visible"&&m()};document.addEventListener("visibilitychange",b),t.effect(()=>()=>{document.removeEventListener("visibilitychange",b)},"cost-meter: visibility reload");const g=async(P,F="rpcSyncFailed",ee=!1)=>{const oe=await P;if(oe===null||typeof oe!="object"||oe.ok!==!0)throw new Error(oe?.error?.message??(ee?oe?.value?.message:void 0)??l()(F));return oe.value.state!==void 0&&n.set({status:"ready",error:null,state:oe.value.state}),oe.value};let h=null;const v={loadStatistics:()=>(h||(h=(typeof Ve.async=="function"?Ve.async("./client.statistics.js").then(P=>P.mount(t)):Promise.reject(new Error(l()("statisticsUpgrade")))).catch(P=>{throw h=null,P})),h),reload:m,updateConfig:async P=>{const F=await i("updateConfig",[P]);return n.set({status:"ready",error:null,state:F}),F},fetchPrices:async()=>g(a.fetchPrices()),resetHistory:async()=>{const P=await i("resetHistory");return n.set({status:"ready",error:null,state:P}),P},importLegacyHistory:async()=>{const P=await a.importLegacyHistory();if(P===null||typeof P!="object"||P.ok!==!0)throw new Error(P?.error?.message??P?.value?.message??l()("legacyImportFailed",{message:"RPC failed"}));return P.value.state!==void 0&&n.set({status:"ready",error:null,state:P.value.state}),P.value},getDaySessions:async P=>i("getDaySessions",[P]),getSessionCost:async P=>i("getSessionCost",[P]),getTurnCost:async(P,F,ee)=>i("getTurnCost",[P,F,ee]),getTopSessions:async(P,F,ee)=>i("getTopSessions",[P,F,ee]),refreshBalance:async()=>g(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>g(a.refreshGoQuota()),refreshGatewayQuota:async(P=null)=>g(P==null?a.refreshGatewayQuota():a.refreshGatewayQuota(P)),refreshCustomBalance:async(P=null)=>g(P==null?a.refreshCustomBalance():a.refreshCustomBalance(P)),refreshCodingPlan:async P=>g(a.refreshCodingPlan(P)),setCredential:async(P,F)=>g(a.setCredential(P,F),"rpcSyncFailed",!0),clearCredential:async P=>g(a.clearCredential(P),"rpcSyncFailed",!0)};m();const N=t.get("slots");if(N===void 0)return;const C=()=>({hooks:{cost:n},api:v});for(const[P,F]of[["header","conversation.session.header.actions"],["dock","conversation.composer.dock"]])N.inject(F,()=>N.register({name:F,id:"cost-meter-statistics",order:1,inject:()=>({...C(),entryPosition:P})},fs));N.inject("conversation.chat.turnTail",()=>N.register({name:"conversation.chat.turnTail",id:"cost-meter-turn",order:10,inject:C},Sn));const x=()=>({gen:0,dispose:null}),f=(P,F,ee,oe,qe=!0)=>{P.dispose!==null&&(P.dispose(),P.dispose=null),P.gen+=1;const Ce=P.gen;qe&&N.inject(F,()=>{if(P.gen!==Ce)return;const xe=typeof ee=="function"?ee():N.register(ee,oe);if(P.gen!==Ce){xe();return}return P.dispose=xe,()=>{P.dispose===xe&&(P.dispose=null),xe()}})},S=x(),y=P=>{const F=P==="header"?"conversation.session.header.actions":"conversation.composer.dock";f(S,F,P==="header"?{name:F,id:"cost-meter",order:-5,inject:C}:{name:F,id:"cost-meter",order:5,inject:C},P==="header"?Cn:An,P!=="off")},T=x(),A=P=>{f(T,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:C},us,P)},L=x(),M=P=>{f(L,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:C},jn,P)};N.inject("conversation.input.dock",()=>N.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:C},os)),N.inject("sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:C},ls)),N.inject("sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:C},is)),N.inject("sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:C},ds));const j=x(),k=P=>{f(j,"sidebar.footer.action",()=>N.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:C},Un),null,P)};window.cmPeakAlertPreview=P=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(Pt,{detail:{kind:P==="offpeak"?"offpeak":"peak"}}))};const H=x(),de=P=>{f(H,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:P==="en"?Oe.en.sectionLabel:Oe.zh.sectionLabel,inject:C},Us,!0)},we=x(),Se=P=>{f(we,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:C},Ht,P)},O=x(),D=(P,F)=>{f(O,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:F==="en"?Oe.en.usageSectionLabel:Oe.zh.usageSectionLabel,inject:C},Ht,P)};let G=null,B=null,V=null,w=null,q=null,Q=null;const ue=()=>{const P=n.getSnapshot().state,F=P?.config?.position??"dock",ee=P?.config?.sidebar!==!1&&P?.config?.hideTodayCost!==!0,oe=P?.config?.balance?.display??"both",qe=(oe==="sidebar"||oe==="both")&&P?.config?.hideOfficialBalance!==!0,Ce=ee||qe||P?.config?.codexQuotaEnabled===!0||P?.config?.sidebarModels?.enabled===!0,xe=P?.config?.corner?.enabled===!0||P?.config?.sidebarModels?.dock===!0,U=W(P?.config?.locale),_=P?.config?.usage?.position??"cost";F!==G&&(y(F),G=F),Ce!==B&&(A(Ce),B=Ce),xe!==V&&(M(xe),V=xe);const me=P?.config?.peakEnabled===!0;me!==Q&&(k(me),Q=me),U!==w&&(de(U),w=U),_!==q?(Je&&(Se(_==="general"),D(_==="section",U)),q=_):Je&&_==="section"&&U!==w&&D(!0,U)};ue();const J=n.subscribe(ue);return()=>{J()}}return dt.apply=Qs,dt.inject=Hs,Ft.exports}});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cost-meter",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.6",
|
|
4
4
|
"description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 90+ 模型价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(11 家,含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 90+ model catalog with auto-matching), Coding Plan quota queries & display for 11 vendors (incl. Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|