dsh-cost-meter 1.9.40 → 1.9.41
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 +8 -8
- package/README.zh-CN.md +8 -8
- package/docs/ledger-lock-recovery.md +12 -0
- package/docs/update-notes-1.9.41.md +29 -0
- package/lib/client.js +1 -1
- package/lib/ledger-persistence.js +43 -7
- package/lib/ledger-writer-worker.js +1 -1
- package/lib/store.js +27 -2
- package/package.json +3 -2
package/lib/client.js
CHANGED
|
@@ -4,4 +4,4 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:ve=>{var Ca={exports:{
|
|
|
4
4
|
`),x=a(E,null,a("div",{className:"cm-mm-title"},s("codingPlanMinimaxTitle")),u.row,b.row,c?a("div",{className:"cm-mm-reset"},"5h · "+c):null),h=a(E,null,a("div",{className:"cm-bbox-rail cm-num"},u.text),a("div",{className:"cm-bbox-rail cm-num"},b.text));return a(J,{portal:!0,label:a("span",{style:{whiteSpace:"pre-line"}},m),side:"right",delayMs:300},a("div",{...d,"data-cm-display":"plan","data-cm-plan":"minimax",className:"cm-bbox cm-mm"+(g==="ok"?"":" "+g)+(l===!1?" rail":"")+(r?" clickable"+(r.busy?" busy":""):""),...r?ke(r.busy,r.run):{}},l===!1?h:x))}function rs(e){const{state:t,wide:o,api:n}=e,s=t.codingPlans?.minimax,l=z(H(t.config)),r=Be(n?()=>n.refreshCodingPlan("minimax"):null);if(!s||s.status!=="ok")return null;const{five:i,seven:d}=na(s.windows);return i==null&&d==null?null:a(oa,{five:i,seven:d,fetchedAt:s.fetchedAt,t:l,wide:o,refresh:r,direction:ie(t.config,"plan")})}const is="/plugins/dsh-openai-codex/auth/status",cs={18e3:"five",604800:"weekly"};function gn(e){if(!Array.isArray(e))return null;const t=e.find(n=>n!==null&&typeof n=="object"&&n.id==="codex");if(!t||!Array.isArray(t.windows))return null;const o={};for(const n of t.windows){const s=n!==null&&typeof n=="object"?cs[Number(n.windowSeconds)]:null;if(!s||typeof n.remainingPercent!="number"||!Number.isFinite(Number(n.remainingPercent)))continue;const l=Number(n.resetAt??n.resetsAt);o[s]={percent:Math.max(0,Math.min(100,Math.round((100-Number(n.remainingPercent))*10)/10)),resetsAt:Number.isFinite(l)&&l>0?new Date(l*1e3).toISOString():""}}return o}function us(e){return e===null||typeof e!="object"||e.status!=="signed-in"?null:gn(e.usage?.rateLimits)}async function sa(e){const t=AbortSignal.timeout(8e3);let o;const n=new Promise((s,l)=>{o=()=>l(t.reason),t.addEventListener("abort",o,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>e(t)),n])}finally{t.removeEventListener("abort",o)}}async function ds(e){try{const t=await sa(o=>U.rpc?.call("/api","codex-subscription/usage",{force:e},o));return t?.ok?gn(t.value?.rateLimits):null}catch{return null}}const U={source:"auto",listeners:[]},la=(e,t=null,o=null)=>Object.assign(U,{rpc:e,readPiAi:t,readChatgptSub:o,request:null,inFlight:null,fetchedAt:0,status:"idle",windows:{},message:""});la(null);const ra=()=>{const{rpc:e,readPiAi:t,readChatgptSub:o,request:n,inFlight:s,listeners:l,...r}=U;return r},ps=e=>(U.listeners.push(e),()=>{U.listeners=U.listeners.filter(t=>t!==e)}),vt=()=>{for(const e of U.listeners)try{e()}catch{}};async function At(e=!1,t=!1,o="auto"){if(!t)return;if(U.inFlight!==null&&U.source===o)return U.inFlight;if(!e&&U.source===o&&U.fetchedAt>0&&Date.now()-U.fetchedAt<(U.status==="ok"?5:1)*6e4)return;const n={};U.request=n,U.source!==o&&Object.assign(U,{status:"idle",windows:{},fetchedAt:0,source:o}),vt();const s=Promise.resolve().then(async()=>{let l={},r="";try{if((o==="auto"||o==="subscription")&&(l=await ds(e)??{}),Object.keys(l).length===0&&(o==="auto"||o==="pi-ai"))try{const i=await sa(()=>U.readPiAi?.());i?.ok===!0&&i.value?.status==="ok"?l=i.value.windows:i?.ok===!0&&i.value?.status==="error"&&(r=i.value.message)}catch{}if(Object.keys(l).length===0&&(o==="auto"||o==="chatgpt-sub"))try{const i=await sa(()=>ve.async("./client.codex.js").then(d=>d.readChatgptSubQuota(U.readChatgptSub)));i?.status==="ok"?l=i.windows:i?.status==="error"&&(r=i.message)}catch{}if(Object.keys(l).length===0&&(o==="auto"||o==="chatgpt"))try{l=await(await ve.async("./client.codex.js")).readChatgptQuota(e)??{}}catch{}if(Object.keys(l).length===0&&(o==="auto"||o==="connect")){const i=await fetch(is,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});i.ok&&(l=us(await i.json().catch(()=>null))??{})}}catch{}finally{if(U.request!==n)return;U.status=Object.keys(l).length>0?"ok":"unavailable",U.windows=l,U.message=Object.keys(l).length?"":r,U.fetchedAt=Date.now(),U.inFlight=null,vt()}});return U.inFlight=s,s}function Pt(e,t="auto"){const[o,n]=O(ra);return V(()=>{if(!e)return;let s=!0;const l=()=>{s&&n(ra())},r=ps(l);l(),At(!1,!0,t);const i=setInterval(()=>{At(!1,!0,t)},6e4);return()=>{s=!1,clearInterval(i),r()}},[e,t,U.rpc]),o.source===t?o:{status:"idle",windows:{},fetchedAt:0}}function ms(e){const t=Ct(),{state:o,wide:n}=e,s=z(H(o.config)),l=o.config?.codexQuotaEnabled===!0&&o.config?.codexQuotaSidebar!==!1,r=o.config?.codexQuotaSource??"auto",i=Pt(l&&!e.preview,r),d=e.preview?o.displayPreviewCodex??(U.source===r?U:{status:"idle"}):i,c=Be(e.preview?null:l?()=>At(!0,l,r):()=>e.api.updateConfig({codexQuotaEnabled:!0,codexQuotaSidebar:!0}));if(!l&&(o.config?.codexQuotaSidebar===!1||o.codexCompat?.enabled!==!0))return null;if(!l)return a("div",{"data-cm-display":"codex",className:"cm-bbox cm-mm clickable"+(n===!1?" rail":""),...ke(c.busy,c.run)},c.err||(n===!1?"Codex":s("codexQuotaEnable")));if(d.status!=="ok")return a("div",{"data-cm-display":"codex",className:"cm-bbox cm-mm clickable"+(n===!1?" rail":""),title:d.message||s("codexQuotaUnavailable"),...ke(c.busy,c.run)},a("div",{className:"cm-mm-title"},n===!1?"Codex":s("codexQuotaTitle")),a("span",{className:"cm-hint"},n===!1?"—":d.status==="idle"||c.busy?s("refreshing"):d.message||s("codexQuotaUnavailable")));const u=[["five","codexQuotaFive","5h"],["weekly","codexQuotaWeek","7d"]].flatMap(([x,h,C])=>{const N=d.windows[x];if(!N)return[];const y=lt(C,N,"remaining",s,!0),p=new Date(typeof N.resetsAt=="string"?N.resetsAt:NaN),k=Number.isFinite(p.getTime())?s("codexQuotaReset",{time:p.toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})}):"";return[{...y,key:x,short:C,name:s(h),reset:k,win:N}]});if(!u.length)return null;const b=u.some(x=>x.pct>=100)?"over":u.some(x=>x.pct>=80)?"warn":"ok",g=[s("codexQuotaTitle"),...u.map(x=>x.name+" · "+x.text+(x.reset?" · "+st(x.win,s):"")),d.fetchedAt>0?s("goQuotaFetchedAt",{time:new Date(d.fetchedAt).toLocaleTimeString()}):null,...Pe(s,c)].filter(Boolean).join(`
|
|
5
5
|
`),f=a(E,null,a("div",{className:"cm-bbox-head cm-codex-head"},a("div",{className:"cm-mm-title"},s("codexQuotaTitle")),a("div",{className:"cm-codex-resets"},...u.filter(x=>x.reset).map(x=>a("span",{key:x.key,className:"cm-mm-reset"},(u.length>1?x.short+" · ":"")+x.reset)))),...u.map(x=>x.row)),m=a(E,null,...u.map(x=>a("div",{className:"cm-bbox-rail cm-num"},x.text)));return a(J,{portal:!0,label:a("span",{style:{whiteSpace:"pre-line"}},g),side:"right",delayMs:300},a("div",{...t,"data-cm-display":"codex",className:"cm-bbox cm-mm clickable"+(b==="ok"?"":" "+b)+(n===!1?" rail":"")+(c.busy?" busy":""),...ke(c.busy,c.run)},n===!1?m:f))}function We(e,t){return e.startsWith("core_")?"Core · "+We(e.slice(5),t):e==="fiveHour"||e==="5h"?"5h":e==="weekly"||e==="week"||e==="7d"?e==="7d"?"7d":t("goShortWeekly"):e==="monthly"||e==="month"?t("goShortMonthly"):e==="daily"||e==="day"?t("goShortDaily"):e==="plan"?t("mimoWindowPlan"):e==="compensation"?t("mimoWindowCompensation"):e==="balance"?t("codingPlanWindowBalance"):String(e).replace(/_/g," ")}function Mt(e,t){const o=n=>{const s=n.replace(/^core_/,"").toLowerCase().replace(/[^a-z0-9]/g,"");return/^(fivehour|five|5h|rolling|session)$/.test(s)?0:/^(daily|day|1d)$/.test(s)?1:/^(weekly|week|7d|sevenday)$/.test(s)?2:/^(monthly|month|30d)$/.test(s)?3:4};return Object.entries(e??{}).filter(([n])=>t!=="volcengine"||[0,2,3].includes(o(n))).sort((n,s)=>o(n[0])-o(s[0]))}function fs(e){const t=Ct(),{id:o,state:n,wide:s,api:l}=e,r=n.codingPlans?.[o],i=z(H(n.config)),d=Be(l?()=>l.refreshCodingPlan(o):null),c=De.find(k=>k.id===o);if(!c||!r||r.status!=="ok")return null;const u=r.windows!==null&&typeof r.windows=="object"?r.windows:{},b=Mt(u,o);if(b.length===0)return null;const g=k=>k!==null&&typeof k=="object"&&typeof k.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(k.percent)||0))):null,f=ie(n.config,"plan"),m=(o==="workbuddy"||o==="opendesign")&&u.balance?.text?i("codingPlanWindowBalance")+": "+u.balance.text:null,x=(m?b.filter(([k])=>k!=="balance"):b).map(([k,w])=>{const v=g(w);if(v===null)return a("div",{key:k,className:"cm-mm-row wide"},a("span",{className:"cm-mm-text"},typeof w?.text=="string"?w.text:"—"));const R=v>=100?"over":v>=80?"warn":"ok",j=we(v,f);return a("div",{key:k,className:"cm-mm-row wide"+(R==="ok"?"":" "+R)},a("span",{className:"cm-bbox-label"},We(k,i)),a("div",{className:"cm-bbox-bar"},a("div",{className:"cm-bbox-fill",style:{width:j.width+"%"}})),a("span",{className:"cm-bbox-pct cm-num"},j.label===null?"—":j.label+"%"))}),h=b.map(([k,w])=>{const v=g(w),R=st(w,i),j=v===null?typeof w?.text=="string"?w.text:"—":Oe(we(v,f).label,f,i);return We(k,i)+" "+j+(R?" · "+R:"")});r.fetchedAt>0&&h.push(i("goQuotaFetchedAt",{time:new Date(r.fetchedAt).toLocaleTimeString()})),r.message&&h.push(r.message),h.push(...Pe(i,d));const C=[i(c.labelKey),...h].join(`
|
|
6
6
|
`),N=b.map(([,k])=>g(k)).filter(k=>k!==null),y=N.some(k=>k>=100)?"over":N.some(k=>k>=80)?"warn":"ok",p=N.length>0?N.slice(0,2).map(k=>we(k,f).label+"%").join(" "):typeof b[0][1]?.text=="string"?b[0][1].text:"—";return a(J,{portal:!0,label:a("span",{style:{whiteSpace:"pre-line"}},C),side:"right",delayMs:300},a("div",{...t,"data-cm-display":"plan","data-cm-plan":o,className:"cm-bbox cm-mm clickable"+(y==="ok"?"":" "+y)+(s===!1?" rail":"")+(d.busy?" busy":""),...ke(d.busy,d.run)},s===!1?a("div",{className:"cm-bbox-rail cm-num"},p):a(E,null,a("div",{className:m?"cm-mm-title cm-mm-row wide":"cm-mm-title"},i(c.labelKey),m&&a("span",{className:"cm-mm-text"},m)),...x)))}const yn=e=>{try{return window.localStorage?.getItem?.("cm.gw."+e)??""}catch{return""}},bs=(e,t)=>{try{window.localStorage?.setItem?.("cm.gw."+e,t)}catch{}};function gs(e){const t=Ct(),{source:o,snapshot:n,state:s,wide:l,api:r}=e,i=z(H(s.config)),[d,c]=O(()=>({source:o.id,id:yn(o.id)})),u=Be(r?()=>r.refreshGatewayQuota(o.id):null),b=ie(s.config,"plan"),g=n.accounts.length>1,f=d.source===o.id?d.id:yn(o.id),m=n.accounts.findIndex(T=>T.id===f),x=m>=0?m:Math.max(0,n.accounts.findIndex(T=>T.windows.length>0||T.credits!=null)),h=n.accounts[x]??n.accounts[0],C=h?.label||h?.id||"",N=T=>g?(La[T.provider]??T.provider)+" · ":"",y=g&&h?[h]:n.accounts,p=[];for(const T of y){if(p.length>=4)break;for(const le of T.windows){if(p.length>=4)break;const Le=N(T)+(le.label||le.id||i("gatewaySourceUnknown"));p.push({win:le,name:Le,view:lt(Le,le,b,i)})}T.windows.length===0&&T.credits!=null&&p.push({win:null,name:N(T)+(T.credits.unit||"credits"),text:(T.credits.used??"—")+" / "+(T.credits.limit??"—")})}p.length===0&&p.push({name:i("gatewayQuotaEmpty"),text:"—"});const k=p.some(T=>T.view?.level==="over")?"over":p.some(T=>T.view?.level==="warn")?"warn":"ok",w=p.map(T=>{if(T.text!=null)return T.name+" "+T.text;const le=st(T.win,i);return T.name+" "+Oe(T.view.label,b,i)+(le?" · "+le:"")});n.fetchedAt>0&&w.push(i("goQuotaFetchedAt",{time:new Date(n.fetchedAt).toLocaleTimeString()})),w.push(...Pe(i,u));const R=[g&&C?`${o.label||o.id} (${x+1}/${n.accounts.length} · ${C})`:o.label||o.id,...w].join(`
|
|
7
|
-
`),j=p.map((T,le)=>T.text!=null?a("div",{key:le,className:"cm-mm-row wide"},a("span",{className:"cm-bbox-label"},T.name),a("span",{className:"cm-mm-text cm-num"},T.text)):a(E,{key:le},T.view.row)),A=T=>{if(!T.key||T.key==="Enter"||T.key===" "){T.stopPropagation(),T.preventDefault?.();const le=n.accounts[(x+1)%n.accounts.length];bs(o.id,le.id),c({source:o.id,id:le.id})}},B=g?a("span",{className:"cm-gw-switcher","aria-label":i("gatewaySwitchAccount",{account:C||x+1}),onClick:A,onKeyDown:A,role:"button",tabIndex:0},`${x+1}/${n.accounts.length} ⇄`):null,F=g?a("div",{className:"cm-bbox-head"},a("div",{className:"cm-mm-title"},o.label||o.id),B):a("div",{className:"cm-mm-title"},o.label||o.id),G=g&&C?a("div",{className:"cm-gw-sub"},C):null,ae=a(E,null,F,G,...j),K=p.filter(T=>T.view).map(T=>T.view.label).filter(T=>T!==null),$=K.length>0?K.slice(0,2).map(T=>T+"%").join(" "):p[0].text??"—",M=a("div",{className:"cm-bbox-rail cm-num"},$);return a(J,{portal:!0,label:a("span",{style:{whiteSpace:"pre-line"}},R),side:"right",delayMs:300},a("div",{...t,"data-cm-display":"gateway","data-cm-source":o.id,className:"cm-bbox cm-mm clickable"+(k==="ok"?"":" "+k)+(l===!1?" rail":"")+(u.busy?" busy":""),...ke(u.busy,u.run)},l===!1?a(E,null,M,B):ae))}function ys(e,t,o,n){const s=Array.isArray(e.gatewayQuotas)?e.gatewayQuotas:[],l=[];for(const r of t.gatewayQuotas?.sources??[]){if(r.enabled===!1||r.display!=="sidebar"&&r.display!=="both")continue;const i=s.find(d=>d.id===r.id);!i||i.status!=="ok"&&i.status!=="partial"&&i.status!=="stale"||i.accounts.length===0||l.push(a(gs,{key:"gateway:"+r.id,source:r,snapshot:i,state:e,wide:o,api:n}))}return l}const hs={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",clinepass:"CP",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo",factory:"Factory",opendesign:"OpenDesign"};function hn(e,t,o){return e?.enabled!==!0?!1:typeof e.showInComposer=="boolean"?e.showInComposer:e.display!=="off"&&t?.enabled===!0&&t[o]!==!1}function ia(e,t,o){const n=e?.display??"settings";return(typeof e?.showInComposer=="boolean"?e.showInComposer:n!=="off"&&t?.enabled===!0&&t[o]!==!1)?{off:"composer",both:"all"}[n]??n+"-composer":n}function ca(e){const t={composer:"off","sidebar-composer":"sidebar","settings-composer":"settings",all:"both"}[e];return{display:t??e,showInComposer:t!==void 0}}function ua(e){return[["sidebar","balanceSidebar"],["settings","balanceSettings"],["both","quotaSidebarSettings"],["composer","quotaComposer"],["sidebar-composer","quotaSidebarComposer"],["settings-composer","quotaSettingsComposer"],["all","quotaAllPositions"],["off","off"]].map(([t,o])=>a("option",{key:t,value:t},e(o)))}function ks(e){const t=e.useCost?e.useCost(N=>N):void 0,o=t?.state?.config;Pt(o?.codexQuotaEnabled===!0&&o.codexQuotaStrip!==!1&&o.quotaStrip?.enabled===!0,o?.codexQuotaSource);const[n,s]=O(null),[l,r]=O({}),i=t?.state,d=e.api;if(!i)return null;const c=i.config,u=c.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(u.enabled!==!0&&c.goQuota?.showInComposer!==!0&&!Object.values(c.codingPlans??{}).some(N=>N.enabled===!0&&N.showInComposer===!0))return null;const b=z(H(c)),g=[];if(u.enabled===!0&&u.budget!==!1){const N=c.budget??{enabled:!1,amount:100,period:"month"};if(N.enabled===!0){const y=Number(c.exchangeRate),k=(i.budgetUsed??(N.period==="day"?Q(i.today,c):N.period==="all"?Q(i.total,c):Q(i.month,c)))*(Number.isFinite(y)&&y>0?y:1),w=Math.max(0,Number(N.amount)||0);if(w>0){const v=Math.min(999,k/w*100),R=v>=100?"over":v>=80?"warn":"ok";g.push({key:"budget",label:b("budgetShort"),level:R,tip:b("budgetOf",{period:b(Ye[N.period]??"periodMonth")})+" · "+b("usedOf",{used:de(k,c),amount:de(w,c)})+" · "+v.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(we(Math.min(100,v),ie(c,"budget")).width)}]})}}}if(hn(c.goQuota,u,"go")){const N=i.goQuota;if(c?.goQuota?.enabled!==!1&&N?.status==="ok"){const y=c.goQuota.main==="weekly"||c.goQuota.main==="monthly"?c.goQuota.main:"rolling",p=y==="rolling"?N.rolling:y==="weekly"?N.weekly:N.monthly;if(p!==null&&typeof p=="object"&&typeof p.percent=="number"){const k=Math.max(0,Math.min(100,Math.round(Number(p.percent)||0))),w=k>=100?"over":k>=80?"warn":"ok",v=typeof p.resetsAt=="string"&&p.resetsAt.length>0?" · "+b("goResetAt",{time:new Date(p.resetsAt).toLocaleString()}):"";g.push({key:"go",label:"Go "+b(y==="rolling"?"goShortRolling":y==="weekly"?"goShortWeekly":"goShortMonthly"),level:w,tip:fn(N,c,b),segs:[{name:"main",pct:Math.round(we(k,ie(c,"go")).width)}]})}}}for(const N of De){const y=i.codingPlans?.[N.id];if(!hn(c.codingPlans?.[N.id],u,"plans")||!y||y.status!=="ok")continue;const p=y.windows!==null&&typeof y.windows=="object"?y.windows:{},k=Mt(p,N.id),w=N.id==="factory"?[k.filter(([v])=>!v.startsWith("core_")),k.filter(([v])=>v.startsWith("core_"))]:[k];for(const[v,R]of w.entries()){if(R.length===0)continue;const j=hs[N.id]??N.id,A=[],B=[];y.message&&B.push(y.message);let F=0,G=0;for(const[ae,K]of R){const $=We(ae,b),M=typeof K?.resetsAt=="string"&&K.resetsAt.length>0?" · "+b("goResetAt",{time:new Date(K.resetsAt).toLocaleString()}):"",T=K!==null&&typeof K=="object"&&typeof K.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(K.percent)||0))):null;if(B.push($+" "+(T===null?typeof K?.text=="string"?K.text:"—":T+"%")+M),T===null){A.push({name:ae,pct:null,text:typeof K?.text=="string"?K.text:"—"});continue}G>=(N.id==="factory"?3:2)||(G+=1,A.push({name:ae,pct:Math.round(we(T,ie(c,"plan")).width)}),F=Math.max(F,T>=100?2:T>=80?1:0))}y.fetchedAt>0&&B.push(b("goQuotaFetchedAt",{time:new Date(y.fetchedAt).toLocaleTimeString()})),A.length!==0&&g.push({key:N.id+(v?":core":""),label:j+(N.id==="factory"?v?" Core":" Standard":""),level:["ok","warn","over"][F],tip:B.join("; "),segs:A})}}const f=u.enabled===!0&&c.codexQuotaEnabled===!0&&c.codexQuotaStrip!==!1&&U.source===(c.codexQuotaSource??"auto")&&U.status==="ok"?U.windows:{},m=f.five??null,x=f.weekly??null,h=N=>Math.max(0,Math.min(100,Math.round(Number(N.percent)||0)));if(m!==null||x!==null){const N=m===null?null:h(m),y=x===null?null:h(x),p=Math.max(N??0,y??0);g.push({key:"codex",label:"Codex",level:p>=100?"over":p>=80?"warn":"ok",tip:b("codexQuotaTitle")+": "+[N===null?null:"5h "+Oe(100-N,"remaining",b),y===null?null:b("codingPlanRemain7d")+" "+Oe(100-y,"remaining",b)].filter(Boolean).join(" · "),segs:[N===null?null:{name:"5h",pct:100-N},y===null?null:{name:"weekly",pct:100-y}].filter(Boolean)})}if(g.length===0)return null;const C=N=>{n!==null||!d||(s(N),r(y=>({...y,[N]:null})),Promise.resolve().then(()=>N==="budget"?d.reload():N==="go"?d.refreshGoQuota():N==="codex"?At(!0,c.codexQuotaEnabled===!0,c.codexQuotaSource):N==="factory:core"?d.refreshCodingPlan("factory"):d.refreshCodingPlan(N)).catch(y=>{r(p=>({...p,[N]:y?.message??String(y)}))}).finally(()=>s(null)))};return a("div",{className:"cm-qstrip"},g.map(N=>{const y=n===N.key,p=l[N.key],k=[a("span",{className:"cm-qlabel",key:"l"},N.label)];y?k.push(a("span",{className:"cm-qtext",key:"busy"},b("refreshing"))):N.segs.forEach((v,R)=>{R>0&&k.push(a("span",{className:"cm-qsep",key:"sep"+R,"aria-hidden":"true"})),v.pct===null?k.push(a("span",{className:"cm-qtext",key:v.name},v.text)):k.push(a("span",{className:"cm-qseg",key:v.name},a("span",{className:"cm-qbar"},a("span",{className:"cm-qfill",style:{width:v.pct+"%"}})),a("span",null,N.key==="codex"?(N.segs.length>1?(v.name==="5h"?"5h":b("goShortWeekly"))+" ":"")+Oe(v.pct,"remaining",b):v.pct+"%")))});const w=[N.tip];return!y&&d&&w.push(b("clickToRefresh")),y&&w.push(b("refreshing")),p&&w.push("⚠ "+b("balanceRefreshFailed",{message:p})),a(J,{portal:!0,key:N.key,label:w.join("; "),side:"bottom",delayMs:400},a("span",{className:"cm-qchip"+(d?" action":"")+(N.level==="ok"?"":" "+N.level),...d?ke(y,()=>C(N.key)):{}},k))}))}const rt="dsh-cost-meter:simple-guide-dismissed";function da(e){if(e?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(rt)==="1"}catch{return!1}}function xs(e){const t=e.useCost?e.useCost(m=>m):void 0,o=fe(!1),[n,s]=O(!1),[l,r]=O(!1),[i,d]=O(!1),c=t?.state?.config,u=!!c&&!i&&!da(c);if(V(()=>{const m=()=>d(!0);return window.addEventListener?.(rt,m),()=>window.removeEventListener?.(rt,m)},[]),!u)return null;const b=z(H(c)),g=()=>{d(!0);try{window.localStorage.setItem(rt,"1")}catch{}window.dispatchEvent?.(new Event(rt))},f=async m=>{if(!o.current){o.current=!0,s(!0),r(!1);try{if((await e.api.updateConfig({sidebarSimple:m,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==m)throw new Error;g()}catch{r(!0)}finally{o.current=!1,s(!1)}}};return a(dn,{actions:{close:g,keep:()=>f(!1),enable:()=>f(!0)},className:"cm-qguide",role:"dialog","aria-label":b("sidebarSimpleTitle"),"aria-busy":n,onKeyDown:m=>{m.key==="Escape"&&(m.stopPropagation(),g())}},a("div",{className:"cm-bbox-head"},a("h4",null,b("sidebarSimpleTitle")),a("button",{type:"button",className:"cm-btn small","aria-label":b("closeGuide"),"data-cm-action":"close",onClick:g},"×")),a("p",null,b("sidebarSimpleBody")),l?a("p",{role:"alert"},b("sidebarSimpleError")):null,a("div",{className:"cm-buttons"},a("button",{type:"button",className:"cm-btn small","data-cm-action":"keep",disabled:n,onClick:()=>f(!1)},b("sidebarSimpleOff")),a("button",{type:"button",className:"cm-btn small primary","data-cm-action":"enable",disabled:n,onClick:()=>f(!0)},b("sidebarSimpleOn"))))}function ws(e){const t=e.useCost?e.useCost(i=>i):void 0,o=fe(!1),n=t?.state;if(!n)return null;const s=n.config;if(!da(s)||s.quotaStrip?.promptSeen===!0)return null;const l=z(H(s)),r=i=>{if(o.current===!0)return;o.current=!0;const d=s.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};e.api.updateConfig({quotaStrip:{...d,enabled:i,promptSeen:!0}}).catch(()=>{o.current=!1})};return a("div",{className:"cm-qguide",role:"dialog","aria-label":l("quotaStripGuideTitle")},a("h4",null,l("quotaStripGuideTitle")),a("p",null,l("quotaStripGuideBody")),a("div",{className:"cm-buttons"},a("button",{type:"button",className:"cm-btn small",onClick:()=>r(!1)},l("quotaStripGuideOff")),a("button",{type:"button",className:"cm-btn small primary",onClick:()=>r(!0)},l("quotaStripGuideOn"))))}const kn="dsh-cost-meter:balance-click-hint-seen",Ns=()=>{try{return window.localStorage.getItem(kn)==="1"}catch{return!1}},Ss=()=>{try{window.localStorage.setItem(kn,"1")}catch{}};function Cs(e){const t=e.useCost?e.useCost(f=>f):void 0,o=fe(!1),[n,s]=O(!1),[l]=O(Ns),r=t?.state;if(!r)return null;const i=r.config,d=i.balance?.display==="sidebar"||i.balance?.display==="both",c=(i?.customBalances??[]).some(f=>f?.enabled===!0&&(f.display==="sidebar"||f.display==="both"))||i.customBalance?.enabled===!0&&(i.customBalance?.display==="sidebar"||i.customBalance?.display==="both"),u=De.some(f=>{const m=i.codingPlans?.[f.id];return m?.enabled===!0&&(m.display==="sidebar"||m.display==="both")});if(n||l||i.balance?.clickHintSeen===!0||!d&&!c&&!u||!da(i)||i.quotaStrip?.promptSeen!==!0)return null;const b=z(H(i)),g=()=>{o.current!==!0&&(s(!0),o.current=!0,Ss(),e.api.updateConfig({balance:{...i.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,s(!1)}))};return a("div",{className:"cm-qguide",role:"dialog","aria-label":b("balanceClickGuideTitle")},a("h4",null,b("balanceClickGuideTitle")),a("p",null,b("balanceClickGuideBody")),a("div",{className:"cm-buttons"},a("button",{type:"button",className:"cm-btn small primary",onClick:g},b("balanceClickGuideOk"))))}function xn(e,t,o){const n=t.sidebarTodayMetric??"cost";return a("span",{className:"cm-today-values","data-both":n==="both"},n!=="tokens"?a("span",{"data-cm-today":"cost"},W(Q(e,t),t)):null,n!=="cost"?a("span",{"data-cm-today":"tokens"},L(["input","output","cacheRead","cacheWrite"].reduce((s,l)=>s+(Number(e?.[l])||0),0))+" "+o("tokensUnit")):null)}function Tt(e){const{state:t,wide:o}=e,n=t.today,s=t.config,l=z(H(s)),r=xn(n,s,l),i=s.budget??{enabled:!1,amount:100,period:"month"},d=Number(s.exchangeRate),u=(t.budgetUsed??(i.period==="day"?Q(t.today,s):i.period==="all"?Q(t.total,s):Q(t.month,s)))*(Number.isFinite(d)&&d>0?d:1),b=Math.max(0,Number(i.amount)||0),g=b>0?Math.min(999,u/b*100):null,f=g===null?"ok":g>=100?"over":g>=80?"warn":"ok";if(i.enabled===!0&&s.hideBudget!==!0&&e.todayOnly!==!0){const x=[l("budgetOf",{period:l(Ye[i.period]??"periodMonth")}),l("usedOf",{used:de(u,s),amount:de(b,s)})+" · "+(g===null?"—":g.toFixed(1)+"%"),l("monthTotal",{month:W(Q(t.month,s),s),total:W(Q(t.total,s),s)})].join("; ");if(e.summary===!0)return a(J,{portal:!0,label:x,side:"right",delayMs:300},a("div",{"data-cm-display":"budget",className:"cm-simple-summary"+(f==="ok"?"":" "+f),tabIndex:0},a("span",null,l("budgetOf",{period:l(Ye[i.period]??"periodMonth")})),a("span",{className:"cm-num"},de(u,s)+" / "+de(b,s))));const h=ns(t,s,l);return a(J,{portal:!0,label:x,side:"right",delayMs:300},a("div",{"data-cm-display":"budget",className:"cm-bbox"+(f==="ok"?"":" "+f)+(o?"":" rail")},o?h.body:a("div",{className:"cm-bbox-rail cm-num"},h.rail)))}const m=[s.sidebarTodayMetric==="tokens"?l("todayTokensTitle"):l("todayCostTitle"),l("callsTokens",{calls:n.calls,input:L(n.input),cache:L(n.cacheRead+n.cacheWrite),output:L(n.output)}),l("monthCost",{amount:W(Q(t.month,s),s)}),l("totalCost",{amount:W(Q(t.total,s),s)})].join("; ");return a(J,{portal:!0,label:m,side:"right",delayMs:300},a("div",{"data-cm-display":"today",className:"cm-foot"+(o?"":" cm-foot-rail")},o?a(E,null,a("span",null,l("today")),a("span",{className:"cm-num cm-bal-amt"},r)):a(Nt,{size:16})))}function vs(e){const t=e.useCost?e.useCost(l=>l):void 0;Pt(t?.state?.config?.codexQuotaEnabled===!0&&t?.state?.config?.codexQuotaSidebar!==!1,t?.state?.config?.codexQuotaSource);let o;if(e.useProjection)try{o=e.useProjection("costUsage")}catch{o=void 0}Za(e,o);const n=t?.state,s=n?{...n,config:aa(n,o?.provider)}:null;return s?Rt(s,!!e.wide,e.api):null}function Rt(e,t,o,n=!1){const s=aa(e),l=z(H(s)),r=(s.balance?.display==="sidebar"||s.balance?.display==="both")&&s.hideOfficialBalance!==!0,d=St(e,s).length>0,c=r&&s.balance?.showProgressBar===!0&&e.balance?.status==="ok",u=d&&s.balance?.showProgressBar===!0,b=s.goQuota?.main==="weekly"||s.goQuota?.main==="monthly"?s.goQuota.main:"rolling",g=s.goQuota?.enabled!==!1&&(s.goQuota?.display==="sidebar"||s.goQuota?.display==="both")&&e.goQuota?.status==="ok"&&e.goQuota?.[b]!==null,f=De.map(A=>A.id).filter(A=>{const B=s.codingPlans?.[A];if(B?.enabled!==!0||B.display!=="sidebar"&&B.display!=="both")return!1;const F=e.codingPlans?.[A];if(F?.status!=="ok")return!1;const G=F.windows!==null&&typeof F.windows=="object"?F.windows:{};return Object.keys(G).length>0}),m=f.length>0,x=ys(e,s,t,o),h=s.codexQuotaSidebar!==!1&&(s.codexQuotaEnabled===!0||e.codexCompat?.enabled===!0),C=(s.budget??{}).enabled===!0&&s.hideBudget!==!0,N=s.sidebar!==!1&&s.hideTodayCost!==!0,y=_e(s,Date.now())!==null,p=s.sidebarModels?.enabled===!0;if(!p&&!r&&!d&&!g&&!m&&!h&&!C&&!N&&!y&&x.length===0)return null;const k=s.sidebarSimple===!0,w=!k&&t&&s.sidebarStyle==="compact",v=[];k&&t&&N&&!s.sidebarTodayBalanceInline&&v.push(a("div",{key:"today","data-cm-display":"today",className:"cm-simple-summary"},a("span",null,l("today")),a("span",{className:"cm-num"},xn(e.today,s,l)))),c?v.push(a(Fo,{key:"balance",state:e,wide:t,api:o})):r&&v.push(a(Uo,{key:"balance",state:e,wide:t,api:o})),u?v.push(a(Wo,{key:"customBalance",state:e,wide:t,api:o})):d&&v.push(a(Ko,{key:"customBalance",state:e,wide:t,api:o}));const R=v.length;m&&v.push(...f.map(A=>A==="minimax"?a(rs,{key:"plan:"+A,state:e,wide:t,api:o}):a(fs,{key:"plan:"+A,id:A,state:e,wide:t,api:o}))),v.push(...x),h&&v.push(a(ms,{key:"codex",state:e,wide:t,api:o,preview:n})),g&&v.push(a(ss,{key:"go",state:e,wide:t})),C&&v.push(a(Tt,{key:"budget",state:e,wide:t,summary:k&&t})),N&&(!(k&&t)||s.sidebarTodayBalanceInline)&&v.push(a(Tt,{key:"today",state:e,wide:t,todayOnly:!0})),y&&v.push(a(E,{key:"peak"},t?mn(e,s.sidebarStyle==="summary"&&!s.sidebarSimple?{...s,peakProgressVariant:"summary"}:s,l):as(e,s,l))),p&&v.splice(s.sidebarModels.position==="first"?0:s.sidebarModels.position==="afterBalance"?R:v.length,0,a(As,{key:"models",state:e,wide:t,preview:n}));const j=s.sidebarOrder?.length?s.sidebarOrder:s.sidebarStyle==="summary"&&!k?["today","balance","peak"]:[];if(j.length){const A=B=>{const F=j.indexOf(B.key);return F<0?999:F};v.sort((B,F)=>A(B)-A(F))}return a("div",{...k?{tabIndex:0,role:"region","aria-label":l("sidebarSimple")}:{},className:"cm-footer-stack"+(s.sidebarTodayBalanceInline?" same-line":"")+(t?"":" rail")+(w?" compact":"")+(k?" simple":s.sidebarStyle==="summary"&&t?" summary":"")},...v)}const wn={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Nn="dsh-cost-meter:models-open";function Sn(e,t,o){return Pn(e,e.config,o,t).map(n=>({...n,label:e.modelLabels?.[n.key]??(n.key==="deepseek:legacy"?n.label:ut(n.key)),cost:Q(n,e.config)})).sort((n,s)=>s.cost-n.cost||s.tokens-n.tokens||n.key.localeCompare(s.key))}function As({state:e,wide:t,preview:o=!1}){const n={...wn,...e.config.sidebarModels},s=z(H(e.config)),l=()=>{try{const y=n.remember?window.localStorage.getItem(Nn):null;if(y!==null)return y==="1"}catch{}return n.defaultOpen},[r,i]=O(l),[d,c]=O(n.period);V(()=>c(n.period),[n.period]);const u=fe(n.defaultOpen);V(()=>{i(o&&u.current!==n.defaultOpen?n.defaultOpen:l()),u.current=n.defaultOpen},[n.defaultOpen,n.remember]);const b=Sn(e,d,s),g=b.reduce((y,p)=>y+p.cost,0),f=y=>W(y,e.config),m=s(d==="history"?"modelStatsHistory":"modelStatsToday")+" "+f(g)+" · "+s("modelsCount",{n:b.length}),x=n.summary==="top"&&b.length?b[0].label+" "+f(b[0].cost):m,h=a(E,null,a("span",{className:"cm-bal-label"},n.summary==="top"&&b.length?b[0].label:s(d==="history"?"modelStatsHistory":"modelStatsToday")),a("span",{className:"cm-bal-amt cm-num"},n.summary==="top"&&b.length?f(b[0].cost):f(g)+" · "+s("modelsCount",{n:b.length}))),C=()=>{i(!r);try{n.remember&&!o&&window.localStorage.setItem(Nn,r?"0":"1")}catch{}};if(!t||e.config.sidebarSimple)return a("div",{"data-cm-display":"models",className:"cm-foot cm-num"+(t?"":" cm-foot-rail"),title:x+" · "+m},t?h:a(Nt,{size:16}));const N=b.slice(0,n.topN);return b.length>n.topN&&N.push(b.slice(n.topN).reduce((y,p)=>{for(const k of["cost","input","output","cacheRead","cacheWrite"])y[k]+=p[k];return y},{key:"other",label:s("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),a("div",{"data-cm-display":"models",className:"cm-bbox cm-model-costs"},a("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(r),title:m,onClick:C},a("span",{className:"cm-caret"+(r?" open":"")}),h),r?a(E,null,a("div",{className:"cm-buttons"},["today","history"].map(y=>a("button",{key:y,type:"button",className:"cm-mstats-tab"+(d===y?" active":""),"aria-pressed":d===y,onClick:()=>c(y)},s(y==="today"?"modelStatsToday":"modelStatsHistory")))),N.length?N.map(y=>a("div",{key:y.key},a("div",{className:"cm-bbox-head"},a("span",{className:"cm-bal-label",title:y.label},y.label),a("span",{className:"cm-num cm-bal-amt"},f(y.cost))),n.shares?a("div",{className:"cm-bbox-bar",title:(g>0?y.cost/g*100:0).toFixed(1)+"%"},a("div",{className:"cm-bbox-fill",style:{width:(g>0?y.cost/g*100:0)+"%"}})):null,n.tokens?a("div",{className:"cm-mstats-note"},s("modelStatsInput")+" "+L(y.input)+" · "+s("modelStatsCache")+" "+L(y.cacheRead+y.cacheWrite)+" · "+s("modelStatsOutput")+" "+L(y.output)):null)):a("span",{className:"cm-note"},s("modelStatsEmpty"))):null)}function it(e){return a("div",{className:"cm-card"},a("p",{className:"cm-card-title"},e.title),a("div",{className:"cm-card-value cm-num"},e.value),a("p",{className:"cm-card-sub"},e.sub))}const pa=new WeakMap,ma=(e,t)=>e?.().then(o=>(pa.set(e,o),o.prefetch?.(t))).catch(()=>{});function Cn({state:e}){const t=e?.billionContext;return!t||!(t.unresolved>0||["needs_update","changed","bridge_missing"].includes(t.compatibility))?null:a("p",{className:"cm-note","data-billing-accuracy":"billion-context"},H(e.config)==="en"?"Some billion-context usage records are incomplete; cost totals may differ from the provider bill.":"billion-context 部分用量记录不完整,费用统计可能存在偏差。")}function be(e){const t=e.load??e.api.loadStatistics,[o,n]=O(()=>pa.get(t)??null),[s,l]=O(""),[r,i]=O(0);return V(()=>{let d=!0;if(l(""),typeof t=="function")return t().then(c=>{pa.set(t,c),d&&n(()=>c)},c=>{d&&l(String(c.message??c))}),()=>{d=!1}},[e.api,e.load,r]),o?a(o,{...e,formatMoneyUsd:W,formatTokens:L,resolveLocale:H}):e.quiet?null:a("div",{className:s?"":"cm-loading",role:s?"alert":"status","aria-label":H(e.state?.config)==="en"?"Loading":"正在读取"},s||a(E,null,a("i"),a("i"),a("i")),s?a("button",{className:"cm-btn",onClick:()=>i(d=>d+1)},"↻"):null)}const Ps="cm-stat-dialog";function Ms(e){const t=e.useCost?.(u=>u),o=t?.state,[n,s]=O(null),l=Ae.useRef(null),r=o?.config[e.entryPosition==="header"?"hideSessionCostHeader":"hideSessionCostDock"]===!0,i=!r&&!!e.sessionId&&n===e.sessionId;if(V(()=>{i&&l.current?.showModal()},[i]),V(()=>{s(null)},[e.sessionId,r]),!e.sessionId||r)return null;const d=H(o?.config)==="en",c=d?"Conversation cost details":"本会话费用明细";return a(E,null,a("button",{type:"button",className:"cm-btn cm-stat-entry cm-stat-"+(e.entryPosition||"dock"),title:c,"aria-label":c,"aria-haspopup":"dialog",onMouseEnter:()=>ma(e.api.loadStatistics,{state:o,sessionId:e.sessionId}),onFocus:()=>ma(e.api.loadStatistics,{state:o,sessionId:e.sessionId}),onClick:()=>s(e.sessionId)},d?"Cost details":"费用明细"),i?a("dialog",{ref:l,role:"dialog",className:Ps,"aria-label":c,onCancel:()=>s(null)},a("header",{className:"cm-stat-dialog-head"},a("strong",null,c),a("button",{type:"button",className:"cm-btn",autoFocus:!0,"aria-label":d?"Close":"关闭",onClick:()=>s(null)},"×")),a("div",{className:"cm-stat-dialog-body"},o?a(be,{key:e.sessionId,state:o,api:e.api,sessionId:e.sessionId}):a("p",{role:t?.error?"alert":"status"},t?.error||(d?"Loading…":"加载中…"),a("button",{type:"button",className:"cm-btn",onClick:()=>e.api.reload()},d?"Retry":"重试")))):null)}function Ts({state:e,t}){const o=e.externalUsage;if(!o)return null;const n=e.config,s=c=>W(Q(c,n),n),l=c=>t("callsTokens",{calls:c.calls,input:L(c.input),cache:L(c.cacheRead+c.cacheWrite),output:L(c.output)}),r=(c,u)=>({calls:c.calls+u.calls,input:c.input+u.input,output:c.output+u.output,cacheRead:c.cacheRead+u.cacheRead,cacheWrite:c.cacheWrite+u.cacheWrite,cost:Q(c,n)+u.cost,apiCost:Q(c,n)+u.cost}),i=(c,u)=>a("tr",{key:c},a("td",null,c),a("td",{className:"num"},String(u.calls)),a("td",{className:"num"},L(u.input)),a("td",{className:"num"},L(u.cacheRead+u.cacheWrite)),a("td",{className:"num"},L(u.output)),a("td",{className:"num"},s(u))),d=c=>a("div",{className:"cm-scroll"},a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,t("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(u=>a("th",{className:"num"},t(u))))),a("tbody",null,c)));return a("section",{className:"cm-budget"},a("h3",{className:"cm-h"},t("externalUsage")),o.stale?a("p",{className:"cm-note"},t("externalStale")):null,a("div",{className:"cm-cards"},["today","month","total"].map((c,u)=>{const b=r(e[c],o.combined[c]);return a(it,{key:c,title:t("combinedUsage")+" · "+t(["cardToday","cardMonth","cardTotal"][u]),value:s(b),sub:l(b)})})),...o.sources.map(c=>a("details",{key:c.source},a("summary",null,c.source+" · "+t("cardToday")+" "+s(c.today)+" · "+t("cardMonth")+" "+s(c.month)+" · "+l(c.today)),d(["today","month","total"].map((u,b)=>i(t(["cardToday","cardMonth","cardTotal"][b]),c[u]))),a("p",{className:"cm-note"},t("externalHistory")),d(c.history.map(u=>i(u.date,u))))))}const ct=(e,t,o)=>a("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(e),onClick:t},a("span",{className:"cm-caret"+(e?" open":"")}),a("h3",{className:"cm-h"},o));function Rs(e){const{state:t,api:o}=e,n=z(H(t.config)),[s,l]=O(!1);return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(s,()=>l(!s),n("history"))),s?a("div",{className:"cm-collapse-body"},a(Bs,{state:t,api:o})):null)}function Bs(e){const{state:t,api:o}=e,n=z(H(t.config)),[s,l]=O(null),[r,i]=O({}),[d,c]=O(()=>new Set),u=t.history??[];if(u.length===0)return a("p",{className:"cm-empty"},n("noHistory"));const b=f=>{if(s===f){l(null);return}l(f),!(r[f]!==void 0||d.has(f))&&(c(m=>{const x=new Set(m);return x.add(f),x}),o.getDaySessions(f).then(m=>i(x=>({...x,[f]:Array.isArray(m?.sessions)?m.sessions:[]}))).catch(()=>i(m=>({...m,[f]:"error"}))).finally(()=>c(m=>{const x=new Set(m);return x.delete(f),x})))},g=f=>f.map(m=>a("tr",{key:m.id},fa(m,t.config?.showSessionId===!0,n),a("td",{className:"num"},String(m.calls)),a("td",{className:"num"},L(m.input)),a("td",{className:"num"},L(m.cacheRead+m.cacheWrite)),a("td",{className:"num"},L(m.output)),a("td",{className:"num"},W(Q(m,t.config),t.config))));return a("div",{className:"cm-scroll"},a("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},n("historyExpandHint")),a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("colDate")),a("th",{className:"num"},n("colCalls")),a("th",{className:"num"},n("colInTok")),a("th",{className:"num"},n("colCacheTok")),a("th",{className:"num"},n("colOutTok")),a("th",{className:"num"},n("colCost")))),a("tbody",null,u.flatMap(f=>{const m=a("tr",{key:f.date,className:"cm-row-click",onClick:()=>b(f.date)},a("td",null,(s===f.date?"▾ ":"▸ ")+f.date),a("td",{className:"num"},String(f.calls)),a("td",{className:"num"},L(f.input)),a("td",{className:"num"},L(f.cacheRead+f.cacheWrite)),a("td",{className:"num"},L(f.output)),a("td",{className:"num"},W(Q(f,t.config),t.config)));if(s!==f.date)return[m];const x=r[f.date],h=d.has(f.date)&&x===void 0?a("p",{className:"cm-empty"},n("historySessionsLoading")):x==="error"?a("p",{className:"cm-empty"},n("historySessionsError")):!Array.isArray(x)||x.length===0?a("p",{className:"cm-empty"},n("historyNoSessions")):a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("colSession")),a("th",{className:"num"},n("colCalls")),a("th",{className:"num"},n("colInTok")),a("th",{className:"num"},n("colCacheTok")),a("th",{className:"num"},n("colOutTok")),a("th",{className:"num"},n("colCost")))),a("tbody",null,g(x)));return[m,a("tr",{key:f.date+"-sessions"},a("td",{colSpan:6},h))]}))))}function Os(e){const{state:t,api:o}=e,n=z(H(t.config)),[s,l]=O(!1),[r,i]=O(100),[d,c]=O("cost-desc"),[u,b]=O(null),[g,f]=O(!1),[m,x]=O(!1),h=Ae.useRef(0),C=(k,w)=>{const[v,R]=w==="recent"?["recent","desc"]:w.split("-"),j=++h.current;f(!0),x(!1),o.getTopSessions(k,v,R).then(A=>{j===h.current&&b(Array.isArray(A?.sessions)?A.sessions:[])}).catch(()=>{j===h.current&&x(!0)}).finally(()=>{j===h.current&&f(!1)})},N=()=>{l(k=>{const w=!k;return w&&u===null&&!g&&C(r,d),w})},y=k=>{i(k),(s||u!==null)&&C(k,d)},p=k=>{c(k),(s||u!==null)&&C(r,k)};return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(s,N,n("sessionRankTitle"))),s?a("div",{className:"cm-collapse-body"},a("p",{className:"cm-hint"},n("sessionRankHint")),a("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},a("div",{className:"cm-field"},a("label",null,n("sessionRankSort")),a("select",{className:"cm-input",value:d,onChange:k=>p(k.target.value)},a("option",{value:"cost-desc"},n("sessionSortCostDesc")),a("option",{value:"cost-asc"},n("sessionSortCostAsc")),a("option",{value:"time-desc"},n("sessionSortTimeDesc")),a("option",{value:"time-asc"},n("sessionSortTimeAsc")),a("option",{value:"recent"},n("sessionSortRecent")))),a("div",{className:"cm-field"},a("label",null,n("sessionRankLimit")),a("select",{className:"cm-input",value:String(r),onChange:k=>y(Number(k.target.value))},a("option",{value:"50"},"50"),a("option",{value:"100"},"100"),a("option",{value:"200"},"200")))),g?a("p",{className:"cm-empty"},n("sessionRankLoading")):m?a("p",{className:"cm-empty"},n("sessionRankError")):u===null||u.length===0?a("p",{className:"cm-empty"},n("sessionRankEmpty")):a("div",{className:"cm-scroll"},a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("colDate")),a("th",null,n("colSession")),a("th",{className:"num"},n("colCalls")),a("th",{className:"num"},n("colInTok")),a("th",{className:"num"},n("colCacheTok")),a("th",{className:"num"},n("colOutTok")),a("th",{className:"num"},n("colCost")))),a("tbody",null,u.map(k=>a("tr",{key:k.date+":"+k.id},a("td",null,k.date),fa(k,t.config?.showSessionId===!0,n),a("td",{className:"num"},String(k.calls)),a("td",{className:"num"},L(k.input)),a("td",{className:"num"},L((k.cacheRead??0)+(k.cacheWrite??0))),a("td",{className:"num"},L(k.output)),a("td",{className:"num"},W(Q(k,t.config),t.config)))))))):null)}function vn(e){const{state:t}=e,o=z(H(t.config)),n=t.today.sessions??[];if(n.length===0)return a("p",{className:"cm-empty"},o("noSessionsToday"));const s=t.config?.showSessionId===!0;return a("div",{className:"cm-scroll"},a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,o("colSession")),a("th",{className:"num"},o("colCalls")),a("th",{className:"num"},o("colInTok")),a("th",{className:"num"},o("colCacheTok")),a("th",{className:"num"},o("colOutTok")),a("th",{className:"num"},o("colCost")))),a("tbody",null,n.map(l=>a("tr",{key:l.id},fa(l,s,o),a("td",{className:"num"},String(l.calls)),a("td",{className:"num"},L(l.input)),a("td",{className:"num"},L(l.cacheRead+l.cacheWrite)),a("td",{className:"num"},L(l.output)),a("td",{className:"num"},W(Q(l,t.config),t.config)))))))}function fa(e,t,o){const n=typeof e.title=="string"?e.title.trim():"",s=String(e.id).slice(0,14)+"…",l=n.length>0?n:s,r=n.length>0?n+" · "+e.id:e.id;return a("td",{title:r},a("div",{className:"cm-sess-title"+(n.length===0?" cm-sess-id":"")},l),t&&n.length>0?a("div",{className:"cm-sess-id"},s):null)}const Ds={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function Ls(e){const{state:t,draft:o,setDraft:n,t:s}=e,l=t.config,r=o?.budget??l.budget,i=Number(l.exchangeRate),c=(t.budgetUsed??(r.period==="day"?Q(t.today,l):r.period==="all"?Q(t.total,l):Q(t.month,l)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(r.amount)||0),b=r.enabled&&u>0?Math.min(999,c/u*100):null,g=b===null?"ok":b>=100?"over":b>=80?"warn":"ok",f=(h,C)=>{o!==null&&n({...o,budget:{...o.budget??l.budget,[h]:C}})},m=r.period==="custom"?r.customStart+" → "+(r.customEnd??s("periodDay")):null,x=r.enabled&&b!==null?s("budgetStatus",{period:s(Ye[r.period]??"periodMonth"),amount:de(u,l),used:de(c,l),pct:b.toFixed(1)})+(g==="over"?s("overLimit"):g==="warn"?s("nearLimit"):""):null;return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},a("h3",{className:"cm-h"},s("budget")),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:r.enabled===!0,onChange:h=>f("enabled",h.target.checked)}),a("span",null,s("enableBudget")))),r.enabled?a(E,null,a("div",{className:"cm-budget-bar"},a("div",{className:"cm-budget-fill "+(g==="ok"?"":g),style:{width:(b===null?0:Math.min(100,b))+"%"}})),a("div",{className:"cm-budget-line"+(g==="over"?" over":"")+" cm-num"},x),a("div",{className:"cm-budget-controls"},a("div",{className:"cm-field"},a("label",null,s("budgetAmountLabel")),Ge({value:r.amount},h=>f("amount",h))),a("div",{className:"cm-field"},a("label",null,s("budgetPeriodLabel")),a("select",{className:"cm-input",value:r.period,onChange:h=>f("period",h.target.value)},a("option",{value:"day"},s("periodDay")),a("option",{value:"month"},s("periodMonth")),a("option",{value:"all"},s("periodAll")),a("option",{value:"custom"},s("periodCustomRange")))),r.period==="custom"?a(E,null,a("div",{className:"cm-field"},a("label",null,s("startDate")),a("input",{className:"cm-input",type:"date",value:r.customStart??"",onChange:h=>f("customStart",h.target.value===""?null:h.target.value)})),a("div",{className:"cm-field"},a("label",null,s("endDate")),a("input",{className:"cm-input",type:"date",value:r.customEnd??"",onChange:h=>f("customEnd",h.target.value===""?null:h.target.value)}))):null),m!==null?a("p",{className:"cm-hint"},s("rangeText",{range:m})):null):a("p",{className:"cm-note"},s("budgetDisabledNote")))}function Es(e){const{state:t,draft:o,setDraft:n,t:s}=e,l=t.config,r=(u,b)=>{o!==null&&n({...o,[u]:b})},i=o===null?l:{...l,...o},d=(()=>{if(i.peakEnabled!==!0)return s("peakOff");const u=Date.parse(i.peakEffectiveAt||""),b=Date.now();if(Number.isFinite(u)&&b<u)return s("peakNotEffective",{time:new Date(u).toLocaleString()});const g=i.peakWindows??[],f=ta(b,g,i.peakHolidays);return f===null?s("offPeakActive"):f.holiday===!0?s("holidayAllOffPeak"):f.weekend===!0?s("weekendAllOffPeak"):f.inPeak?s("peakActive"):s("offPeakActive")})(),c=(i.peakWindows?.length??0)>0?s("peakSummary",{windows:i.peakWindows.map(u=>u.start+":00-"+u.end+":00").join(H(i)==="zh"?"、":", "),time:i.peakEffectiveAt||s("unknown"),status:d}):s("noPeakWindows",{status:d});return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},a("h3",{className:"cm-h"},s("peakPanelTitle")),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:u=>r("peakEnabled",u.target.checked)}),a("span",null,s("peakEnabledLabel")))),a("div",{className:"cm-grid"},a("div",{className:"cm-field"},a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:u=>r("peakNotice",u.target.checked)}),a("span",null,s("peakNoticeLabel")))),a("div",{className:"cm-field"},a("label",null,s("peakStyleLabel")),a("select",{className:"cm-input",value:o?.peakStyle??"compact",onChange:u=>r("peakStyle",u.target.value)},a("option",{value:"progress"},H(o)==="en"?"Time progress":"时间进度条"),a("option",{value:"compact"},s("peakStyleCompact")),a("option",{value:"classic"},s("peakStyleClassic"))))),a("div",{className:"cm-grid"},a("div",{className:"cm-field"},a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:u=>r("peakAlertEnabled",u.target.checked)}),a("span",null,s("peakAlertLabel")))),a("div",{className:"cm-field"},a("label",null,s("peakAlertAheadLabel")),a("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:u=>{const b=Number(u.target.value);Number.isInteger(b)&&b>=1&&b<=30&&r("peakAlertAhead",b)}})),a("div",{className:"cm-field"},a("label",null,s("peakAlertTargetLabel")),a("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:u=>r("peakAlertTarget",u.target.value)},a("option",{value:"both"},s("peakAlertTargetBoth")),a("option",{value:"peak"},s("peakAlertTargetPeak")),a("option",{value:"offpeak"},s("peakAlertTargetOffPeak"))))),a("div",{className:"cm-grid"},a("div",{className:"cm-field"},a("label",null,s("peakAlertPositionLabel")),a("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:u=>r("peakAlertPosition",u.target.value)},a("option",{value:"corner"},s("peakAlertPositionCorner")),a("option",{value:"center"},s("peakAlertPositionCenter")))),a("div",{className:"cm-field"},a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:u=>{r("peakAlertWebNotify",u.target.checked),u.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),a("span",null,s("peakAlertWebNotifyLabel"))),a("p",{className:"cm-hint"},s("peakAlertWebNotifyHint")))),a("div",{className:"cm-field"},a("label",null,s("peakAlertPreviewLabel")),a("div",{className:"cm-row"},a("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},s("peakAlertPreviewPeak")),a("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},s("peakAlertPreviewOffPeak")))),a("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?mn(t,i,s):a("p",{className:"cm-hint"},s("peakNoticeHiddenHint"))),a("p",{className:"cm-hint"},c),a("div",{className:"cm-field"},a("label",null,s("peakHolidaysLabel")),a("input",{className:"cm-input",defaultValue:(i.peakHolidays??[]).join(", "),onBlur:u=>r("peakHolidays",u.target.value.split(/[,,\s]+/).filter(Boolean))})),a("p",{className:"cm-hint"},s("weekendRuleNote")))}function Ge(e,t){const o=e.value;return a("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",placeholder:e.placeholder,title:e.title,"aria-label":e.label,value:typeof o=="number"?String(o):"",onChange:n=>{const s=n.target.value;if(s===""){if(e.emptyMode==="clear"){t(null);return}if(e.emptyMode==="ignore")return;t(0);return}const l=Number(s);Number.isFinite(l)&&l>=0&&t(l)}})}function An({value:e,entry:t,path:o,emptyMode:n,placeholder:s,label:l,title:r,t:i,onCommit:d}){const c=yt(t,o),u=e==null?"":String(e)+(t.multiplier!==void 0||t.separateMultipliers?" × "+c:""),[b,g]=O(u),[f,m]=O(!1),x=fe(!1);V(()=>{x.current||g(u)},[u]);const h=()=>{if(!x.current)return;const C=b.trim().split(/\s*[×*xX]\s*/),N=/^[+]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;if(b.trim()===""){x.current=!1,m(!1),n==="clear"?d(null):g(u);return}if(C.length>2||!C.every(y=>N.test(y)&&Number.isFinite(Number(y)))||!Number.isFinite(Number(C[0])*(C.length===2?Number(C[1]):c))){m(!0);return}x.current=!1,m(!1),g(String(Number(C[0]))+(t.multiplier!==void 0||t.separateMultipliers||C.length===2?" × "+(C.length===2?Number(C[1]):c):"")),d(Number(C[0]),C.length===2?Number(C[1]):void 0)};return a("input",{className:"cm-input narrow",type:"text",value:b,placeholder:s,"aria-label":l,"aria-invalid":f,title:f?i("priceMultiplyInvalid"):[r,i(t.separateMultipliers?"priceMultiplySingle":"priceMultiplyAll"),e==null?"":"= "+Number((e*c).toPrecision(12))].filter(Boolean).join(" · "),onChange:C=>{x.current=!0,g(C.target.value),m(!1)},onBlur:h,onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),h()),C.key==="Escape"&&(C.stopPropagation(),x.current=!1,m(!1),g(u))}})}function Bt(e,t,o){o!==void 0&&(e.separateMultipliers?e.multipliers={...e.multipliers,[t]:o}:e.multiplier=o)}function ba(e,t,o,n,s,l,r,i=0){const d=n==="cacheWrite",c=t?.[n]??(n==="cacheMiss"?t?.input:n==="cacheHit"?t?.cachedInput:void 0)??null,u=l({cacheHit:"flatCached",cacheMiss:"flatInput",cacheWrite:"flatCacheWrite",output:"flatOutput"}[n]);return a("label",{className:"cm-price-cell"},a("span",{className:"cm-price-cell-label"},u),a(An,{entry:e,value:c,path:o+"."+n,t:l,emptyMode:d||!["base","cny"].includes(o)?"clear":"ignore",placeholder:d?String(t?.cacheHit??t?.cachedInput??t?.cacheMiss??t?.input??i):void 0,label:s+" · "+u,title:d?l("cacheWriteFallback"):void 0,onCommit:r}))}function ga(e,t,o){return a("div",{className:"cm-price-multiplier"},a("label",null,a("input",{type:"checkbox",checked:e.separateMultipliers===!0,onChange:n=>o(n.target.checked)}),t("priceMultiplySeparate")),a("span",{title:t(e.separateMultipliers?"priceMultiplySingle":"priceMultiplyAll")},t("priceMultiplyHint")))}function Is(e){const{modelId:t,entry:o,isDefault:n,draft:s,setDraft:l,t:r}=e,i=Ze(o),d=f=>{const m={...Ze(f)};if(Array.isArray(f.rateHistory)){const x=f.rateHistory.filter(h=>Date.parse(h.before)<=Date.now());x.length>0?m.rateHistory=x:delete m.rateHistory}return m},c=f=>{const m=n?{...s.prices,default:f}:{...s.prices,models:{...s.prices.models,[t]:f}};l({...s,prices:m})},u=(f,m,x,h)=>{const C=n?s.prices.default:s.prices.models[t],N=d(C??{cacheHit:0,cacheMiss:0,output:0}),y=f==="base"?N:{...N[f]??(x===null?{}:Qe(N))};x===null?delete y[m]:y[m]=Math.max(0,x),f!=="base"&&(Object.keys(y).length?N[f]=y:delete N[f]),Bt(N,f+"."+m,h),c(N)},b=()=>{const f={...s.prices.models};delete f[t],l({...s,prices:{...s.prices,models:f}})},g=(f,m)=>{const x=m==="base"?i:i[m]??null;return a("div",{className:"cm-price-row",key:m},a("span",null,f),...["cacheMiss","cacheHit","cacheWrite","output"].map(h=>a(E,{key:h},ba(i,x,m,h,f,r,(C,N)=>u(m,h,C,N),i.cacheHit))))};return a("div",{className:"cm-price-card"},a("div",{className:"cm-price-head"},a("span",{className:"cm-price-name"},t),a("span",{className:"cm-price-unit"},s.prices.currency??"USD"),a(E,null,i?.legacy===!0?a("span",{className:"cm-price-legacy"},r("legacyModel")):null,n?a("span",{className:"cm-price-legacy"},r("defaultFallback")):null,n?null:a("button",{className:"cm-btn small danger",onClick:b},r("remove")))),a("div",{className:"cm-price-row cm-price-columns"},a("span",null,""),a("span",null,r("flatInput")),a("span",null,r("flatCached")),a("span",null,r("flatCacheWrite")),a("span",null,r("flatOutput"))),g(r("tierBase"),"base"),g(r("tierOffPeak"),"offPeak"),g(r("tierPeak"),"peak"),ga(i,r,f=>c({...o,separateMultipliers:f,multipliers:{}})),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?a("p",{className:"cm-note"},r("datedPriceNote")):null)}const js={deepseek:"DeepSeek",stepfun:"StepFun",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"},Hs=e=>e==="zen"?"go":e,ut=e=>e.replace(/^zen:/i,"go:").replace(/^(deepseek(?:-official|-account)?):deepseek-(?:v4(?:\.1)?-)?flash(?:-vision-exp)?$/i,"$1:DeepSeek V4.1 Flash");function Pn(e,t,o,n){const s=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],l=c=>Number.isFinite(Number(c))&&Number(c)>0?Number(c):0,r=(c,u,b)=>{if(!b||typeof b!="object")return;const g=c[u]??(c[u]=Object.fromEntries([...s,"apiCost"].map(m=>[m,0])));for(const m of s)g[m]+=l(b[m]);for(const m of bt)Number.isFinite(b[m])&&(g[m]=(g[m]??0)+b[m]);const f=u.indexOf(":");g.apiCost+=l(b.apiCost??(et(f>0?u.slice(0,f):"deepseek",f>0?u.slice(f+1):u,t)==="plan"?0:b.cost))},i=c=>{if(!c||typeof c!="object")return{};if(c.byProviderModel&&Object.keys(c.byProviderModel).length)return c.byProviderModel;if(c.byModel&&Object.keys(c.byModel).length)return Object.fromEntries(Object.entries(c.byModel).map(([b,g])=>[b.includes(":")?b:"deepseek:"+b,g]));const u={};for(const b of Array.isArray(c.sessions)?c.sessions:[])if(!(!b||typeof b!="object"))if(b.byProviderModel&&Object.keys(b.byProviderModel).length)for(const[g,f]of Object.entries(b.byProviderModel))r(u,g,f);else r(u,(b.provider||"deepseek")+":"+(b.model||"unknown"),b);return Object.keys(u).length?u:s.some(b=>l(c[b])>0)?{"deepseek:legacy":c}:{}};return(c=>{const u={},b=g=>{for(const[f,m]of Object.entries(g??{}))r(u,f,m)};if(c==="today")b(i(e.today));else{const g=Date.parse((e.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const f of e.history??[]){const m=Date.parse(f.date+"T00:00:00Z");m<=g&&m>=g-76896e5&&b(i(f))}}return Object.entries(u).map(([g,f])=>{const m=g.indexOf(":"),x=(m>0?g.slice(0,m):"deepseek").toLowerCase(),h=m>0?g.slice(m+1):g,C=f.input+f.output+f.cacheRead+f.cacheWrite+f.reasoning,N=f.cacheRead+f.input;return{label:e.modelLabels?.[g]??(g==="deepseek:legacy"?o("modelStatsLegacy"):x==="deepseek"||x===""?h:Hs(x)+":"+h),key:g,...f,tokens:C,cls:et(x,h,t),hitRate:N>0?f.cacheRead/N:null,cacheUnreported:wo(f),blended:C>0&&f.cost>0?f.cost/C*1e6:null,perUsd:f.cost>0?C/f.cost:null}}).filter(g=>(g.tokens>0||g.cost>0)&&t.modelStatistics?.[g.key]?.[c==="today"?"today":"summary"]!==!1)})(n).sort((c,u)=>u.cost-c.cost||u.tokens-c.tokens)}function Qs(e){const{state:t,config:o,t:n,initialTab:s,draft:l,setDraft:r}=e,[i,d]=O(s==="history"?"history":"today"),[c,u]=O(!1),b=Pn(t,o,n,i),g=p=>(Math.max(0,Math.min(1,p))*100).toFixed(1)+"%",f=b.reduce((p,k)=>Math.max(p,k.cost),0),m=b.reduce((p,k)=>Math.max(p,k.tokens),0),x=b.reduce((p,k)=>Math.max(p,k.perUsd??0),0),h=(p,k)=>a("button",{className:"cm-mstats-tab"+(i===p?" active":""),onClick:()=>d(p)},k),C=p=>p.cls==="plan"?a("span",{className:"cm-plan-tag",title:n("billingClassLabel")+" · "+(ya(za(p.provider,o,p.model),n)||n("billingClassPlan"))},n("billingClassPlan")):null,N=p=>a("select",{className:"cm-input",title:n("billingClassLabel"),value:o.planBilling?.models?.[p.key]==="plan"&&o.planBilling?.modelPlans?.[p.key]?"plan:"+o.planBilling.modelPlans[p.key]:o.planBilling?.models?.[p.key]??"auto",disabled:l===null,onChange:k=>{const w={...l.planBilling?.models??{}},v={...l.planBilling?.modelPlans??{}},R=k.target.value;delete v[p.key],R.startsWith("plan:")?(w[p.key]="plan",v[p.key]=R.slice(5)):R==="auto"?delete w[p.key]:w[p.key]=R,r({...l,planBilling:{...l.planBilling,models:w,modelPlans:v}})}},a("option",{value:"auto"},n("billingClassAuto")),a("option",{value:"plan"},n("billingClassPlan")),a("option",{value:"api"},n("billingClassApi")),Ue.map(k=>a("option",{key:k,value:"plan:"+k},n("billingClassPlan")+" · "+ya(k,n)))),y=(p,k,w,v,R)=>a("div",{className:"cm-mstats-row"},R?a("div",{className:"cm-mstats-label"},a("span",{className:"cm-mstats-name",title:p},p),R):a("span",{className:"cm-mstats-name",title:p},p),a("div",{className:"cm-mstats-barbg"},a("div",{className:"cm-mstats-bar "+w,style:{width:g(k)}})),a("span",{className:"cm-mstats-val"},v));return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(c,()=>u(!c),n("modelStatsTitle"))),c?a("div",{className:"cm-collapse-body"},a("div",{className:"cm-mstats-tabs"},h("today",n("modelStatsToday")),h("history",n("modelStatsHistory"))),b.length===0?a("p",{className:"cm-note"},n("modelStatsEmpty")):a(E,null,a("div",{className:"cm-mstats-h"},n("modelStatsCostH")),b.map(p=>a(E,{key:"c:"+p.label},y(p.label,f>0?p.cost/f:0,"cost",W(p.cost,o),a(E,null,C(p),N(p),p.cacheUnreported?a("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null)))),a("div",{className:"cm-mstats-h"},n("modelStatsTokensH")),a("div",{className:"cm-mstats-legend"},a("span",null,a("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),n("modelStatsInput")),a("span",null,a("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),n("modelStatsCache")),a("span",null,a("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),n("modelStatsOutput"))),[...b].sort((p,k)=>k.tokens-p.tokens).map(p=>a("div",{className:"cm-mstats-row",key:"t:"+p.label},a("span",{className:"cm-mstats-name",title:p.label},p.label),a("div",{className:"cm-mstats-barbg"},a("div",{className:"cm-mstats-seg in",style:{width:g(m>0?p.input/m:0)}}),a("div",{className:"cm-mstats-seg cache",style:{width:g(m>0?(p.cacheRead+p.cacheWrite)/m:0)}}),a("div",{className:"cm-mstats-seg out",style:{width:g(m>0?(p.output+p.reasoning)/m:0)}})),a("span",{className:"cm-mstats-val"},L(p.tokens)))),a("div",{className:"cm-mstats-h"},n("modelStatsHitH")),[...b].sort((p,k)=>(k.hitRate??-1)-(p.hitRate??-1)).map(p=>a(E,{key:"h:"+p.label},y(p.label,p.hitRate??0,"hit",p.cacheUnreported?n("modelStatsHitUnreported"):p.hitRate===null?"—":(p.hitRate*100).toFixed(1)+"%",p.cacheUnreported?a("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null))),a("div",{className:"cm-mstats-h"},n("modelStatsValueH")),[...b].sort((p,k)=>(k.perUsd??-1)-(p.perUsd??-1)).map(p=>a(E,{key:"v:"+p.label},y(p.label,x>0?(p.perUsd??0)/x:0,"value",p.perUsd===null?"—":L(p.perUsd)+" tok/$"+(p.blended!==null?" · "+n("modelStatsBlended",{price:"$"+p.blended.toFixed(2)}):"")))),a("p",{className:"cm-mstats-note"},n("modelStatsNote")))):null)}function qs(e,t){return e==="fiveHour"?t==="en"?"5-hour":"5 小时":e==="weekly"?t==="en"?"This week":"本周":e==="monthly"?t==="en"?"This month":"本月":e==="daily"?t==="en"?"Today":"当日":e}function ya(e,t){if(e==="go")return"OpenCode Go / Go Plus";const o={codex:"Codex / ChatGPT","volcengine-agent":"Volcengine Agent Plan","tencent-coding":"Tencent Coding Plan","tencent-token":"Tencent Token Plan","baidu-coding":"Baidu Qianfan Coding Plan"};if(o[e])return o[e];const n=De.find(s=>s.id===e);return n!==void 0?t(n.labelKey):e}const Mn=["fiveHour","weekly","monthly","daily"];function Us(e,t){const o=new Map,n=s=>{const l=new Date(s),r=i=>String(i).padStart(2,"0");if(t==="monthly")return l.getFullYear()+"-"+r(l.getMonth()+1);if(t==="weekly"){const i=new Date(l.getFullYear(),l.getMonth(),l.getDate()-(l.getDay()+6)%7);return i.getFullYear()+"-"+r(i.getMonth()+1)+"-"+r(i.getDate())}return l.getFullYear()+"-"+r(l.getMonth()+1)+"-"+r(l.getDate())};for(const s of Object.values(e??{}))for(const l of s??[]){if(l===null||typeof l!="object"||!(l.tokens>0)&&!(l.cost>0))continue;const r=n(Number(l.t1)||Number(l.t0)),i=o.get(r)??{key:r,tokens:0,cost:0,pct:0,intervals:0};i.tokens+=Number(l.tokens)||0,i.cost+=Number(l.cost)||0,i.pct+=Number(l.pct)||0,i.intervals+=1,o.set(r,i)}return[...o.values()].map(s=>({...s,per1Tokens:s.pct>0?s.tokens/s.pct:null,fullTokens:s.pct>0?s.tokens/s.pct*100:null})).sort((s,l)=>s.key<l.key?-1:s.key>l.key?1:0)}function Fs(e){const{state:t,config:o,t:n}=e,[s,l]=O(!1),[r,i]=O("daily"),d=H(o),c=t?.planStats,u=c!=null&&typeof c.providers=="object"?c.providers:{},b=Object.keys(u).sort(),g=w=>W(Number(w)||0,o??t?.config),f=w=>w.method==="none"||w.per1Tokens===null?"—":L(w.per1Tokens)+" tok · "+g(w.per1Cost),m=w=>w.method==="none"||w.fullTokens===null?"—":L(w.fullTokens)+" tok · "+g(w.fullCost),x=w=>w.method==="sample"?n("planStatsMethodSample"):w.method==="live"?n("planStatsMethodLive"):n("planStatsMethodNone"),h=w=>{let v=x(w);return w.method==="sample"&&Number(w.sampleAt)>0&&(v=n("planStatsMethodSampleAt",{method:v,time:new Date(Number(w.sampleAt)).toLocaleString(d==="en"?"en-US":"zh-CN")})),(w.method==="sample"||w.method==="live")&&w.confidence==="low"&&(v+=" · "+n("planStatsConfidenceLow")),v},C=([w,v,R])=>a("tr",{key:v+":"+w},a("td",null,qs(w,d)),a("td",{className:"num"},Math.round(R.percent*10)/10+"%"),a("td",{className:"num"},L(R.localTokens)+" tok · "+g(R.localCost)),a("td",{className:"num"},f(R)),a("td",{className:"num"},m(R)),a("td",{className:"num cm-plan-reset"},R.resetsAt.length>0?n("planStatsResets",{time:new Date(R.resetsAt).toLocaleString(d==="en"?"en-US":"zh-CN")}):"—"),a("td",{className:"cm-plan-method"},h(R))),N=s?b.flatMap(w=>Object.entries(u[w]?.intervals??{})).map(([w,v])=>({winKey:w,list:v})):[],y=Us(Object.fromEntries(N.map(w=>[w.winKey,w.list])),r),p=y.reduce((w,v)=>Math.max(w,v.fullTokens??0),0),k=(w,v)=>a("button",{key:w,className:"cm-mstats-tab"+(r===w?" active":""),onClick:()=>i(w)},v);return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(s,()=>l(!s),n("planStatsTitle"))),s?a("div",{className:"cm-collapse-body"},b.length===0?a("p",{className:"cm-empty"},n("planStatsEmpty")):a(E,null,b.map(w=>{const v=u[w]?.windows??{},R=[...Mn.filter(j=>v[j]!==void 0).map(j=>[j,w,v[j]]),...Object.keys(v).filter(j=>!Mn.includes(j)).map(j=>[j,w,v[j]])];return a("div",{key:w,className:"cm-plan-provider"},a("div",{className:"cm-plan-provider-name"},ya(w,n),a("span",{className:"cm-plan-updated"},(()=>{const j=Number(u[w]?.generatedAt)||Number(c?.generatedAt)||0;return j>0?new Date(j).toLocaleTimeString(d==="en"?"en-US":"zh-CN"):""})())),a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("planStatsWindow")),a("th",{className:"num"},n("planStatsPercent")),a("th",null,n("planStatsLocal")),a("th",null,n("planStatsPer1")),a("th",null,n("planStatsFull")),a("th",null,""),a("th",null,""))),a("tbody",null,R.map(C))))}),a("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},n("planStatsCurveTitle")),a("div",{className:"cm-mstats-tabs"},k("daily",n("planStatsDaily")),k("weekly",n("planStatsWeekly")),k("monthly",n("planStatsMonthly"))),y.length===0?a("p",{className:"cm-note"},n("planStatsCurveEmpty")):a(E,null,[...y].reverse().map(w=>a("div",{className:"cm-mstats-row",key:w.key},a("span",{className:"cm-mstats-name"},w.key),a("div",{className:"cm-mstats-barbg"},a("div",{className:"cm-mstats-bar value",style:{width:(p>0?(w.fullTokens??0)/p*100:0).toFixed(1)+"%"}})),a(J,{label:n("planStatsBarTip",{date:w.key,full:w.fullTokens===null?"—":L(w.fullTokens),per1:w.per1Tokens===null?"—":L(w.per1Tokens),tokens:L(w.tokens),cost:g(w.cost),intervals:w.intervals}),side:"top",delayMs:200},a("span",{className:"cm-mstats-val"},w.fullTokens===null?"—":L(w.fullTokens)))))),a("p",{className:"cm-note"},n("planStatsNote")))):null)}function _s(e){const{provider:t,modelId:o,entry:n,draft:s,setDraft:l,t:r,api:i,lockedIds:d,releaseDisabled:c}=e,u=Array.isArray(d)&&d.includes(o),[b,g]=O(!1),[f,m]=O(""),x=async()=>{if(!(b||c)){g(!0),m("");try{await i.releasePriceLock(o)}catch(p){m(String(p.message??p))}finally{g(!1)}}},h=p=>{const k={...s.prices.providers??{}},w=k[t]??{};k[t]={...w,models:p},l({...s,prices:{...s.prices,providers:k}})},C=(p,k,w)=>{if(s===null)return;const v={...(s.prices.providers??{})[t]?.models??{}};v[o]={...v[o]??{},[p]:Math.max(0,k)},k===null&&delete v[o][p],p==="input"&&delete v[o].cacheMiss,p==="cachedInput"&&(delete v[o].cacheHit,delete v[o].cacheRead),Bt(v[o],"base."+({input:"cacheMiss",cachedInput:"cacheHit"}[p]??p),w),h(v)},N=(p,k,w)=>{if(s===null)return;const v={...(s.prices.providers??{})[t]?.models??{}},R=v[o]??{};v[o]={...R,cny:{...R.cny,[p]:Math.max(0,k)}},k===null&&delete v[o].cny[p],Bt(v[o],"cny."+p,w),h(v)},y=()=>{if(s===null)return;const p={...(s.prices.providers??{})[t]?.models??{}};delete p[o],h(p)};return a("div",{className:"cm-price-card"},a("div",{className:"cm-price-head"},a("span",{className:"cm-price-name"},o),a("span",{className:"cm-price-unit"},n.cny?"USD / CNY":"USD"),a(E,null,n?.unpriced===!0?a("span",{className:"cm-price-legacy"},r("catalogUnpriced")):null,u?a("span",{className:"cm-price-locked",title:r("priceLockHint")},r("priceLockBadge")):null,u&&typeof i?.releasePriceLock=="function"?a("button",{className:"cm-btn small",disabled:b||c,onClick:x},r("priceLockRelease")):null,a("button",{className:"cm-btn small danger",onClick:y},r("unmountBtn")))),f?a("p",{className:"cm-err",role:"alert"},f):null,n?.unpriced===!0?null:a(E,null,a("div",{className:"cm-price-row cm-price-columns"},a("span",null,""),a("span",null,r("flatInput")),a("span",null,r("flatCached")),a("span",null,r("flatCacheWrite")),a("span",null,r("flatOutput"))),a("div",{className:"cm-price-row"},a("span",null,"USD"),...["cacheMiss","cacheHit","cacheWrite","output"].map(p=>a(E,{key:p},ba(n,n,"base",p,"USD",r,(k,w)=>C({cacheMiss:"input",cacheHit:"cachedInput"}[p]??p,k,w))))),n?.cny?a("div",{className:"cm-price-row"},a("span",null,"CNY"),...["cacheMiss","cacheHit","cacheWrite","output"].map(p=>a(E,{key:p},ba(n,n.cny,"cny",p,"CNY",r,(k,w)=>N(p,k,w))))):null,ga(n,r,p=>h({...s.prices.providers[t].models,[o]:{...n,separateMultipliers:p,multipliers:{}}}))))}const ha=e=>[a("option",{key:"sidebar",value:"sidebar"},e("balanceSidebar")),a("option",{key:"settings",value:"settings"},e("balanceSettings")),a("option",{key:"both",value:"both"},e("balanceBoth")),a("option",{key:"off",value:"off"},e("off"))],ka=e=>e!=null?a("div",{className:"cm-msg "+e.kind},e.text):null;function Ws(e){const{state:t,api:o,t:n,draft:s,setDraft:l}=e,[r,i,d]=dt(n,()=>o.refreshBalance()),c=t.balance,u=t.config,b=t.reconcile,g=(s?.balance??u.balance??{}).reconcile!==!1,f=h=>{s===null||typeof l!="function"||l({...s,balance:{...s.balance??u.balance??{},reconcile:h.target.checked}})},m=h=>je(h,u,c?.currency),x=c.status==="ok"?a("div",{className:"cm-bal-line"},a("span",null,n("balanceLine",{total:m(c.totalBalance),granted:m(c.grantedBalance),toppedUp:m(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?a("div",{className:"cm-bal-line err"},n("balanceQueryFailedHint",{message:c.message||n("unknownError")})):a("div",{className:"cm-bal-line"},n("balanceNotQueried"));return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},a("h3",{className:"cm-h"},n("accountBalance")),a("button",{className:"cm-btn small",onClick:d,disabled:r},n(r?"refreshing":"refreshBalance"))),x,a("label",null,n("balanceApiKey")),a(tt,{target:"balance",configured:c.keyConfigured,source:c.keySource,t:n,api:o,placeholder:"sk-…"}),a("p",{className:"cm-hint"},n("balanceKeyHint")),b!==void 0&&b.ok===!1?a("div",{className:"cm-bal-line warn"},"⚠ "+b.message):null,a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:g,onChange:f}),n("reconcileLabel")),ka(i))}function Ot(e){const t=fe(null);V(()=>{e.targeted&&(t.current?.scrollIntoView({block:"start"}),t.current?.focus({preventScroll:!0}))},[e.targeted]);const{name:o,enabled:n,saved:s,busy:l,open:r,statusNode:i,configNode:d,errorMsg:c,onToggle:u,onRefresh:b,onLogin:g,loginRequired:f,onRemove:m,onToggleOpen:x,t:h}=e,C=d!=null,N=f?g:b,y=h(l===!0?f?"loggingIn":"refreshing":f?"loginCodingPlan":"refresh");return a("div",{ref:t,"data-quota-plan":e.planId,tabIndex:e.targeted?-1:void 0,className:"cm-budget cm-quota-card"},a("div",{className:"cm-budget-head"},a("label",{className:"cm-check"},a("input",{type:"checkbox","aria-label":h("enable")+": "+o,checked:n===!0,onChange:p=>u(p.target.checked)})),a("div",{className:"cm-quota-name"},C?ct(r===!0,x,o):a("h3",{className:"cm-h"},o)),m?a("button",{className:"cm-btn small",onClick:m},h("quotaRemove")):null,a("button",{className:"cm-btn small",onClick:N,disabled:l===!0||n!==!0||s?.enabled!==!0||s.display==="off"&&s.showInComposer!==!0,title:n!==!0?h("quotaEnableFirst"):s?.enabled!==!0||s.display==="off"&&s.showInComposer!==!0?h("quotaRefreshReady"):h(f?"loginCodingPlan":"refresh")},y)),i,C&&r===!0?a("div",{className:"cm-collapse-body"},d):null,c!=null?a("div",{className:"cm-msg "+c.kind},c.text):null)}function dt(e,t){const[o,n]=O(!1),[s,l]=O(null),r=fe(!1);return[o,s,async()=>{if(!r.current){r.current=!0,n(!0),l(null);try{const d=await t();l({kind:d.ok?"ok":"err",text:d.message})}catch(d){l({kind:"err",text:e("syncFailed",{message:d?.message??String(d)})})}finally{r.current=!1,n(!1)}}}]}const Gs=e=>{const t=e.filter(n=>n.enabled===!0),o=e.filter(n=>n.enabled!==!0);return[...t,...o]},xa=(e,t,o,n,s,l=t)=>{if(typeof o?.percent!="number")return a("div",{key:l,className:"cm-go-row"+(s?" main":"")},a("span",{className:"cm-go-label"},t),a("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const r=Math.max(0,Math.min(100,Number(o.percent)||0)),i=we(r,n),d=typeof o.resetsAt=="string"&&o.resetsAt.length>0?e("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return a("div",{key:l,className:"cm-go-row"+(s?" main":"")},a("span",{className:"cm-go-label"},t),a("div",{className:"cm-go-bar"},a("div",{className:"cm-go-fill",style:{width:i.width+"%"}})),a("span",{className:"cm-go-num"},i.label===null?"—":e("goQuotaPercent",{percent:String(Math.round(i.label))})),d?a("span",{className:"cm-go-reset"},d):null)};function Ks(e){const{state:t,api:o,t:n,entry:s,index:l,canRemove:r,onPatch:i,onRemove:d}=e,c=s.adapter==="aliyun",u=s.adapter==="tokenrhythm",b=c||u,[g,f]=O(!1),m=()=>({headers:JSON.stringify(s.request?.headers??{},null,2),extract:JSON.stringify(s.extract??{},null,2),body:typeof s.request?.body=="string"?s.request.body:JSON.stringify(s.request?.body,null,2)??""}),[x,h]=O(m),[C,N]=O(()=>(s.allowedHosts??[]).join(", ")),[y,p]=O({}),k=fe(!1),w=t.config,R=(Array.isArray(t.customBalances)?t.customBalances:[]).find(D=>D.index===l)??null,j=s.enabled===!0,A=()=>{f(D=>!D)};V(()=>{g&&!k.current&&(h(m()),N((s.allowedHosts??[]).join(", ")),p({})),k.current=g},[g]);const B=(D,ne)=>i({[D]:ne}),F=(D,ne)=>i({request:{...s.request??{},[D]:ne}}),G=c?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:u?["TOKENRHYTHM_COOKIE"]:[...new Set(Object.values(s.request?.headers??{}).flatMap(D=>typeof D=="string"?[...D.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(ne=>ne[1]):[]))],ae=(D,ne)=>{h(oe=>({...oe,[D]:ne}));try{const oe=D==="body",ge=oe&&!ne.trim()?void 0:JSON.parse(ne);if(!oe&&(ge===null||typeof ge!="object"||Array.isArray(ge)))throw new Error("invalid");if(D==="headers"&&Object.values(ge).some(P=>typeof P!="string"))throw new Error("invalid");p(P=>({...P,[D]:""})),D==="extract"?B(D,ge):F(D,oe?ge===void 0?void 0:ne:ge)}catch{p(oe=>({...oe,[D]:n("customBalanceInvalidJson")}))}},K=(D,ne,oe,ge)=>!b&&a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,n(ne)),ge&&a("span",{className:"cm-hint"},n(ge)),a("textarea",{className:"cm-input",rows:oe,value:x[D],onChange:P=>ae(D,P.target.value)}),y[D]?a("span",{className:"cm-hint err"},y[D]):null),$=D=>{N(D);const ne=D.split(/[\s,;]+/).map(oe=>oe.trim()).filter(oe=>oe.length>0);B("allowedHosts",ne)},[M,T,le]=dt(n,()=>(w.customBalances??[])[l]?.enabled!==!0?Promise.resolve({ok:!1,message:n("quotaEnableFirst")}):o.refreshCustomBalance(l)),Le=R!==null&&R.status==="ok"?a(E,null,w.balance?.showProgressBar===!0&&!u?a("div",{className:"cm-budget",style:{marginTop:"8px"}},a(Jt,{segments:$t(t,w,R,s),direction:ie(w,"balance")}),a("div",{className:"cm-bal-line"},ea(R,w,n,t,s))):a("div",{className:"cm-bal-line"},n("customBalanceRemaining",{amount:Fe(R.remaining,w,R,s)}))):R!==null&&R.status==="error"?a("div",{className:"cm-bal-line err"},R.message||n("unknownError")):a("div",{className:"cm-bal-line"},R?.message||n("balanceNotQueried")),pt=a(E,null,a("p",{className:"cm-note"},n(u?"tokenRhythmBalanceNote":c?"aliyunBalanceNote":"customBalanceConfigNote")),!u&&a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:s.convertToDisplayCurrency===!0,disabled:at(w,R,s)!=="USD",onChange:D=>B("convertToDisplayCurrency",D.target.checked)}),n("customBalanceConvert")),!u&&a("p",{className:"cm-note"},n("customBalanceConvertNote")),a("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([D,ne])=>a("div",{key:D,className:"cm-field"},a("label",null,n(ne)),a("input",{className:"cm-input",value:s[D]??"",onChange:oe=>B(D,oe.target.value)}))),!b&&a("div",{className:"cm-field"},a("label",null,n("customBalanceUnitLabel")),a("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(s.unit)?s.unit:"USD",onChange:D=>B("unit",D.target.value)},a("option",{value:"USD"},"USD ($)"),a("option",{value:"CNY"},"CNY (¥)"),a("option",{value:"EUR"},"EUR (€)"),a("option",{value:"CREDITS"},"CREDITS"))),a("div",{className:"cm-field"},a("label",null,n("customBalanceDisplayLabel")),a("select",{className:"cm-input",value:s.display??"both",onChange:D=>B("display",D.target.value)},...ha(n))),a("div",{className:"cm-field"},a("label",null,n("customBalanceRefreshInterval")),Ge({value:s.refreshMinutes??15},D=>B("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D)))))),!b&&a("div",{className:"cm-field"},a("label",null,n("customBalanceMethod")),a("select",{className:"cm-input",value:s.request?.method??"GET",onChange:D=>F("method",D.target.value)},a("option",{value:"GET"},"GET"),a("option",{value:"POST"},"POST"))),!b&&a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,n("customBalanceUrl")),a("input",{className:"cm-input",value:s.request?.url??"",placeholder:"/plugins/dsh-workbuddy-connect/status",onChange:D=>F("url",D.target.value)}),a("span",{className:"cm-hint"},n("customBalanceUrlHint"))),K("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((s.request?.method??"GET").toUpperCase())&&K("body","customBalanceBody",5,"customBalanceBodyNote"),a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,u?"Token Rhythm Cookie":n("customBalanceCredentialsTitle")),G.length>0?a(E,null,!b&&a("span",{className:"cm-hint"},n("customBalanceCredentialsHint")),G.map(D=>a(tt,{key:"cb-var-"+D,target:"customVar:"+D,configured:(t.customVarStatus?.[D]?.configured??!1)===!0,source:t.customVarStatus?.[D]?.source??"",t:n,api:o,placeholder:u?"tr_session=…":"{{"+D+"}}"}))):a("span",{className:"cm-hint"},n("customBalanceNoPlaceholders"))),!b&&a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,n("customBalanceAllowedHosts")),a("input",{className:"cm-input",value:C,placeholder:"api.example.com, relay.example.org",onChange:D=>$(D.target.value)}),a("span",{className:"cm-hint"},n("customBalanceAllowedHostsHint"))),!b&&a("label",{className:"cm-check",style:{gridColumn:"1 / -1"}},a("input",{type:"checkbox",checked:s.allowInsecureHttp===!0,onChange:D=>B("allowInsecureHttp",D.target.checked)}),n("customBalanceHttp")),K("extract","customBalanceExtract",8)));return a(Ot,{name:`#${l+1} · `+(Xt(s,H(w))||n("customBalanceTitle")),enabled:j,saved:JSON.stringify(s)===JSON.stringify(w.customBalances?.[l])?w.customBalances[l]:null,busy:M,open:g,statusNode:Le,configNode:pt,errorMsg:T,onToggle:D=>B("enabled",D),onRefresh:le,onRemove:r?d:null,onToggleOpen:A,t:n})}function zs({config:e,draft:t,setDraft:o,t:n,api:s}){const l=t?.goQuota??e.goQuota,r=(i,d)=>{t&&o({...t,goQuota:{...l,[i]:d}})};return a(E,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([i,d])=>a("div",{key:i,className:"cm-field"},a("label",null,n(d)),a("select",{className:"cm-input",value:i==="display"?ia(l,(t??e).quotaStrip,"go"):l[i],onChange:c=>i==="display"?t&&o({...t,goQuota:{...l,...ca(c.target.value)}}):r(i,c.target.value)},i==="display"?ua(n):["rolling","weekly","monthly"].map((c,u)=>a("option",{key:c,value:c},n(["goWindowRolling","goWindowWeekly","goWindowMonthly"][u])))))),a("div",{className:"cm-field"},a("label",null,n("goQuotaRefreshIntervalLabel")),Ge({value:l.refreshMinutes},i=>r("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(i)))))),a("label",null,n("goQuotaKeyLabel")),a(tt,{target:"goQuota",configured:e.goQuota?.keyConfigured===!0,source:e.goQuota?.keySource,t:n,api:s,placeholder:"sk-…"}))}function Ys(e){const{state:t,api:o,t:n,draft:s,setDraft:l}=e,[r,i]=O(!1),d=t.goQuota,c=t.config,u=s?.goQuota?.enabled??c.goQuota?.enabled??!0,b=(p,k)=>{s!==null&&l({...s,goQuota:{...s.goQuota??c.goQuota,[p]:k}})},[g,f,m]=dt(n,()=>o.refreshGoQuota()),x=c.goQuota?.main==="weekly"||c.goQuota?.main==="monthly"?c.goQuota.main:"rolling",h=[x,...["rolling","weekly","monthly"].filter(p=>p!==x)],C=p=>p==="rolling"?"goWindowRolling":p==="weekly"?"goWindowWeekly":"goWindowMonthly",N=p=>p==="rolling"?d.rolling:p==="weekly"?d.weekly:d.monthly,y=u===!1?a("p",{className:"cm-note"},n("goQuotaDisabledNote")):d.status==="ok"?a("div",{className:"cm-go-list"},h.map(p=>xa(n,n(C(p)),N(p),ie(c,"go"),p===x)),a("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:d.fetchedAt>0?new Date(d.fetchedAt).toLocaleTimeString():"—"}))):d.status==="error"?a("div",{className:"cm-bal-line err"},d.message||n("unknownError")):d.status==="off"&&d.message?a("p",{className:"cm-note"},d.message):a("div",{className:"cm-bal-line"},n("goQuotaNotQueried"));return a(Ot,{name:n("goQuotaTitle"),enabled:u,saved:c.goQuota,busy:g,open:r,statusNode:y,errorMsg:f,configNode:a(zs,{config:c,draft:s,setDraft:l,t:n,api:o}),onToggleOpen:()=>i(p=>!p),onToggle:p=>b("enabled",p),onRefresh:m,t:n})}const Vs=(e,t)=>{if(typeof e?.keyVar=="string"&&e.keyVar.length>0)return e.keyVar;const n="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(e?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(t??{}).find(s=>s===n||s.startsWith(n+"_"))??n};function $s(e){const{state:t,api:o,t:n,draft:s,setDraft:l,index:r}=e,i=t.config,c=(s??i).gatewayQuotas?.sources??[],u=c[r]??{},g=(Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[]).find(A=>A.id===u.id)??{id:u.id,status:"off",accounts:[],unsupportedProviders:[]},f=Vs(u,t.customVarStatus),[m,x]=O(!1),[h,C,N]=dt(n,()=>o.refreshGatewayQuota(u.id)),y=A=>{s!==null&&l({...s,gatewayQuotas:{...s.gatewayQuotas??i.gatewayQuotas??{},sources:A}})},p=A=>y(c.map((B,F)=>F===r?{...B,...A}:B)),k=(A,B,F)=>a("div",{className:"cm-field"},a("label",null,A),a("input",{className:"cm-input","aria-label":A,value:B??"",onChange:F})),w=(A,B)=>{const F=lt(A?.label||A?.id||n("gatewaySourceUnknown"),A,ie(i,"plan"),n);return a(E,{key:A?.id||B},F.row,A?.resetsAt?a("div",{className:"cm-note"},st(A,n)):null)},v=(A,B)=>a("div",{key:A.id||B,className:"cm-mm-row wide"},a("span",{className:"cm-bbox-label"},A.label||"package"),a("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),a("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),R=A=>A==null?null:a(E,null,a("div",{className:"cm-mm-row wide"},a("span",{className:"cm-bbox-label"},A.unit||"credits"),a("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),a("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),(A.packages??[]).map(v)),j=(A,B)=>a("div",{key:A.id||B,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},a("div",{className:"cm-budget-head"},a("strong",null,(La[A.provider]??A.provider??n("gatewaySourceUnknown"))+" · "+(A.label||n("gatewaySourceUnknown"))),a("span",{className:"cm-hint"},A.status)),A.plan?a("div",{className:"cm-note"},A.plan):null,A.windows.length>0?a("div",{className:"cm-go-list"},A.windows.map(w)):null,R(A.credits),A.message?a("div",{className:"cm-note"},A.message):null);return a(Ot,{name:u.label||u.id||n("gatewayQuotaTitle"),enabled:u.enabled===!0,saved:i.gatewayQuotas?.sources?.find(A=>A.id===u.id),busy:h,open:m,errorMsg:C,statusNode:a("div",{className:"cm-note"},n("gatewaySourceStatus")+": "+(g.status??n("gatewaySourceUnknown"))+(g.serverVersion?" · "+g.serverVersion:"")+(g.fetchedAt>0?" · "+n("gatewaySourceFetchedAt",{time:new Date(g.fetchedAt).toLocaleTimeString()}):"")+(g.message?" · "+g.message:"")),configNode:a(E,null,a("div",{className:"cm-grid"},k(n("gatewaySourceLabel"),u.label,A=>p({label:A.target.value})),k(n("gatewaySourceBaseURL"),u.baseURL,A=>p({baseURL:A.target.value})),a("div",{className:"cm-field"},a("label",null,n("gatewaySourceDisplay")),a("select",{className:"cm-input",value:u.display??"both",onChange:A=>p({display:A.target.value})},...ha(n))),a("div",{className:"cm-field"},a("label",null,n("gatewaySourceRefreshInterval")),Ge({value:u.refreshMinutes??15},A=>p({refreshMinutes:Math.min(1440,Math.max(1,Math.floor(A)))}))),k(n("gatewaySourceAllowlist"),(u.allowedHosts??[]).join(", "),A=>p({allowedHosts:A.target.value.split(/[\s,;]+/).filter(Boolean)})),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:u.allowInsecureHttp===!0,onChange:A=>p({allowInsecureHttp:A.target.checked})}),a("span",null,n("customBalanceHttp"))),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:u.antigravityOnlyGemini===!0,onChange:A=>p({antigravityOnlyGemini:A.target.checked})}),a("span",null,n("gatewayOnlyGemini")))),f?a("div",{className:"cm-field"},a("label",null,n("gatewaySourceCredential")),a(tt,{target:"customVar:"+f,configured:t.customVarStatus?.[f]?.configured===!0,source:t.customVarStatus?.[f]?.source??"",t:n,api:o,placeholder:f})):null,g.unsupportedProviders.length>0?a("div",{className:"cm-note"},n("gatewaySourceUnsupported")+": "+g.unsupportedProviders.join(", ")):null,g.accounts.length>0?g.accounts.map(j):a("div",{className:"cm-bal-line"},n("gatewaySourceNoAccounts"))),onToggle:A=>p({enabled:A}),onRefresh:N,onRemove:()=>y(c.filter((A,B)=>B!==r)),onToggleOpen:()=>x(A=>!A),t:n})}const De=[{id:"opendesign",labelKey:"codingPlanOpendesign"},{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:"clinepass",labelKey:"codingPlanClinepass"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"},{id:"workbuddy",labelKey:"wbT"},{id:"factory",labelKey:"codingPlanFactory"}];let Tn;function Js(){return Tn??=ve.async("./client.plan-settings.js").then(e=>e.mount({useQuotaRefresh:dt,miniMaxWindowsOf:na,MiniMaxPlanCard:oa,barDirectionOf:ie,quotaWindowRow:xa,codingPlanWindowLabel:We,codingPlanWindowEntries:Mt,numInput:Ge,CredentialField:tt,QuotaCard:Ot,resolveLocale:H,formatMoneyUsd:W,quotaPlacementValue:ia,quotaPlacementPatch:ca,quotaPlacementOptions:ua})).catch(e=>{throw Tn=null,e})}function Zs(e){return a(be,{...e,load:Js})}function Xs(e){const{state:t,api:o,t:n,draft:s,setDraft:l}=e,r=t.config,i=s??r,d=i.codingPlans??{},c=i.gatewayQuotas?.sources??[],u=s?.customBalances??r.customBalances??[],b=y=>{s!==null&&l({...s,customBalances:y,...y.length===0?{customBalance:{...r.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},g=fe({next:0,keys:[]}).current;for(;g.keys.length<u.length;)g.keys.push(g.next++);g.keys.length=u.length;const f=y=>{g.keys.splice(y,1),b(u.filter((p,k)=>k!==y))},m=(y,p)=>b(u.map((k,w)=>w===y?{...k,...p}:k)),x=(y="custom")=>{if(!(u.length>=8)){if(y==="workbuddy2api"){b([...u,{enabled:!1,label:"WorkBuddy2API 积分",labelEn:"WorkBuddy2API credits",display:"both",unit:"CREDITS",refreshMinutes:15,request:{url:"http://127.0.0.1:8790/api/credits/expiry?package_limit=1",method:"GET",headers:{"X-Admin-Token":"{{WORKBUDDY2API_ADMIN_TOKEN}}"}},extract:{remaining:"summary.available_remaining"},allowedHosts:["127.0.0.1:8790"],allowInsecureHttp:!1}]);return}b([...u,{...y!=="custom"?{adapter:y}:{},enabled:!1,label:y==="tokenrhythm"?"Token Rhythm":y==="aliyun"?"千问 / 阿里云":"",labelEn:y==="tokenrhythm"?"Token Rhythm":y==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:y!=="custom"?"CNY":"USD",refreshMinutes:15,request:{url:y==="tokenrhythm"?"https://tokenrhythm.studio/api/wallet/summary":y==="aliyun"?"https://business.aliyuncs.com/":"",method:y==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])}},h=()=>{c.length>=4||s===null||l({...s,gatewayQuotas:{...s.gatewayQuotas??r.gatewayQuotas??{},sources:[...c,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:Ut,allowedHosts:[],allowInsecureHttp:!1}]}})},C=[...c.map((y,p)=>({kind:"gateway",key:"gw-"+(y.id??p),index:p,enabled:y.enabled===!0})),{kind:"go",key:"go",enabled:i.goQuota?.enabled!==!1},...De.map(y=>({kind:"plan",key:"plan-"+y.id,planId:y.id,labelKey:y.labelKey,enabled:d[y.id]?.enabled===!0})),...u.map((y,p)=>({kind:"custom",key:"cb-"+g.keys[p],index:p,enabled:y.enabled===!0}))],N=y=>y.kind==="plan"?a(Zs,{key:y.key,planId:y.planId,labelKey:y.labelKey,targeted:y.planId===e.targetPlan,state:t,api:o,t:n,draft:s,setDraft:l}):y.kind==="go"?a(Ys,{key:y.key,state:t,api:o,t:n,draft:s,setDraft:l}):y.kind==="gateway"?a($s,{key:y.key,index:y.index,state:t,api:o,t:n,draft:s,setDraft:l}):a(Ks,{key:y.key,state:t,api:o,t:n,entry:u[y.index],index:y.index,canRemove:!0,onPatch:p=>m(y.index,p),onRemove:()=>f(y.index)});return a("div",null,a("p",{className:"cm-note"},n("quotaSectionNote")),a("div",{className:"cm-quota-list"},Gs(C).map(N)),a("div",{className:"cm-buttons"},a("button",{className:"cm-btn small",onClick:h,disabled:c.length>=4},n("gatewaySourceAdd")),a("button",{className:"cm-btn small",onClick:()=>x(),disabled:u.length>=8},n("customBalanceAdd")),a("button",{className:"cm-btn small",onClick:()=>x("aliyun"),disabled:u.length>=8},n("aliyunBalanceAdd")),a("button",{className:"cm-btn small",onClick:()=>x("tokenrhythm"),disabled:u.length>=8},n("tokenRhythmBalanceAdd")),a("button",{className:"cm-btn small",onClick:()=>x("workbuddy2api"),disabled:u.length>=8},n("workBuddyBalanceAdd")),a("p",{className:"cm-note"},n("workBuddyBalanceNote"))))}const el=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Rn=e=>(e.input??0)+(e.output??0)+(e.cacheRead??0)+(e.cacheWrite??0);function Dt(e){const t=e.useCost?e.useCost(p=>p):void 0,o=e.state??t?.state;if(!o)return null;const n=o.config,s=H(n),l=e.t??z(s),r=Array.isArray(o.history)?o.history:[];if(r.length===0)return a("div",null,a("h3",{className:"cm-h"},l("usageTitle")),a("p",{className:"cm-empty"},l("usageEmpty")));const i=o.meta?.dayKey??"",d=new Map(r.map(p=>[p.date,p])),c=p=>{const k=w=>String(w).padStart(2,"0");return p.getFullYear()+"-"+k(p.getMonth()+1)+"-"+k(p.getDate())},u=new Date;u.setHours(0,0,0,0);const b=new Date(u);b.setDate(b.getDate()+(6-(u.getDay()+6)%7));const g=26,f=[],m=[];let x=-1;for(let p=g-1;p>=0;p-=1){for(let w=0;w<7;w+=1){const v=new Date(b);v.setDate(v.getDate()-(p*7+(6-w)));const R=d.get(c(v));f.push(R!==void 0?{day:R,tokens:Rn(R)}:{day:{date:c(v)},tokens:0})}const k=new Date(b);k.setDate(k.getDate()-(p*7+6)),m.push(k.getMonth()!==x?s==="en"?el[k.getMonth()]:String(k.getMonth()+1)+"月":""),x=k.getMonth()}const h=Math.max(...f.map(p=>p.tokens),1),C=p=>{const k=p/h;return k<.25?1:k<.5?2:k<.75?3:4},N=p=>{const{day:k,tokens:w}=p,v="cm-ug-cell"+(w>0?" l"+C(w):"")+(k.date===i?" today":""),R=l("usageDay",{date:k.date,tokens:L(w),input:L(k.input??0),cache:L((k.cacheRead??0)+(k.cacheWrite??0)),output:L(k.output??0),calls:k.calls??0,cost:W(Q(k,n),n)});return a(J,{key:k.date,label:R,side:"top",delayMs:200},a("div",{className:v}))},y=o.total;return a("div",{className:"cm-ug"},a("h3",{className:"cm-h"},l("usageTitle")),a("div",{className:"cm-ug-total"},l("usageTotal",{tokens:L(Rn(y)),input:L(y.input??0),cache:L((y.cacheRead??0)+(y.cacheWrite??0)),output:L(y.output??0),calls:y.calls??0})),a("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+g+",1fr)"}},f.map(N)),a("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+g+",1fr)"}},m.map((p,k)=>a("span",{key:"m"+String(k),className:"cm-ug-monthc"},p))))}function Bn(e){return e.ready?a(be,{...e,load:e.api.loadCodex,quiet:e.view==="prompt"}):null}function tl(e){const t=e.useCost?.(n=>n),o=t?.state;return a(Bn,{...e,state:o,view:"prompt",ready:o?.codexCompat?.enabled===!0&&o?.codexCompat?.promptDue,locale:t?.locale})}const al=!1;function nl(e){const t=e.useCost?.(o=>o);return a(be,{state:t?.state,snapshot:t,api:e.api,load:e.api.loadSettingsOverview,helpers:{makeT:z,Card:it,BillingAccuracyNote:Cn,displayCostOf:Q,quotaWindowRow:xa,codingPlanWindowLabel:We,formatBalanceMoney:je,formatCustomBalanceMoney:Fe,CODING_PLAN_ROWS:De,UsagePanel:Dt,TodaySessions:vn,BudgetBoxContent:Tt,useCodexQuota:Pt,codingPlanWindowEntries:Mt}})}function On(e){const t=e.useCost?e.useCost(P=>P):void 0,o=e.api,n=t?.state??null,[s,l]=O(null),[r,i]=O(null),[d,c]=O(!1),[u,b]=O(!1),[g,f]=O(!1),[m,x]=O(!1),[h,C]=O("models"),[N,y]=O("overview"),p=n?.codexCompat?.installed===!0&&n?.codexCompat?.enabled===!0,k=N==="export"?"statistics":N==="codex"&&!p?"overview":N;V(()=>{p||y(P=>P==="codex"?"overview":P)},[p]);const[w,v]=O(null),[R,j]=O({status:"idle",at:0,error:null}),A=Ae.useRef(null),B=Ae.useRef(null),F=Ae.useRef(null),G=Ae.useRef(Promise.resolve()),ae=Ae.useRef(0),K=Ae.useRef(null);V(()=>()=>{K.current?.()},[]),V(()=>{if(n!==null){const P=JSON.stringify(n.config);l(_=>{const ye=_!==null&&JSON.stringify(_)!==A.current;return ye||(B.current=n.config,F.current=n.config),ye?{..._,activeLocale:n.config.activeLocale}:JSON.parse(P)}),A.current=P}},[n]),V(()=>{s!==null&&F.current===null&&B.current!==null&&(F.current=B.current)},[s]),V(()=>{const P=++ae.current;if(s===null||o===void 0)return;const _=JSON.stringify(s);if(_===A.current){K.current=null;return}j(ce=>ce.status==="saving"?ce:{...ce,status:"saving"});const ye=()=>{G.current=G.current.catch(()=>{}).then(async()=>{if(P!==ae.current)return;const ce={},pe=F.current??B.current;if(pe!==null&&typeof pe=="object")for(const re of Object.keys(s))re==="activeLocale"||s[re]===pe[re]||JSON.stringify(s[re])!==JSON.stringify(pe[re])&&(ce[re]=s[re]);if(Object.keys(ce).length===0){A.current=_,j({status:"saved",at:Date.now(),error:null});return}try{await o.updateConfig(ce),A.current=_,pe!==null&&typeof pe=="object"&&(F.current={...pe,...ce}),P===ae.current&&j({status:"saved",at:Date.now(),error:null})}catch(re){P===ae.current&&j({status:"error",at:0,error:re?.message??String(re)})}})};K.current=ye;const xe=setTimeout(ye,120);return()=>{clearTimeout(xe)}},[s,o]),V(()=>{n!==null&&t?.status==="error"&&t.error&&i({kind:"err",text:M("ledgerReadFailed",{message:t.error})})},[t?.status,t?.error]);const $=H({...s??n?.config,activeLocale:t?.locale}),M=z($);if(t===void 0||n===null)return a("div",{className:"cm-section"},a("p",{className:"cm-empty"},t?.status==="loading"?M("readingLedger"):M("ledgerUnavailable")),t?.error&&a("p",{className:"cm-err",role:"alert"},M("ledgerReadFailed",{message:t.error})),a("button",{className:"cm-btn",disabled:t?.status==="loading"||!o?.reload,onClick:o?.reload},M("refresh")));const T=n.config,le=async()=>{if(!m){x(!0),i(null);try{const P=await o.fetchPrices();if(i({kind:P.ok?"ok":"err",text:P.message}),P.ok&&P.state&&typeof P.state.config=="object"){const _=JSON.stringify(P.state.config);l(JSON.parse(_)),A.current=_}}catch(P){i({kind:"err",text:M("syncFailed",{message:P?.message??String(P)})})}finally{x(!1),c(!1)}}},Le=async()=>{if(!m){x(!0);try{await o.resetHistory(),i({kind:"ok",text:M("historyCleared")})}catch(P){i({kind:"err",text:M("clearFailed",{message:P?.message??String(P)})})}finally{x(!1),b(!1)}}},pt=async()=>{if(!m){x(!0),i(null);try{const P=await o.importLegacyHistory();i({kind:"ok",text:P.message})}catch(P){i({kind:"err",text:M("legacyImportFailed",{message:P?.message??String(P)})})}finally{x(!1),f(!1)}}},D=(P,_)=>{s!==null&&l({...s,[P]:_})},ne=[["overview",M("tabOverview")],["statistics",$==="en"?"Cost statistics":"计费统计"],["quotas",M("tabQuotas")],["usage",M("tabUsage")],["pricing",M("tabPricing")],...p?[["codex","Codex"]]:[],["display",M("tabDisplay")]],oe=P=>ma({statistics:o.loadStatistics,pricing:o.loadOpenRouter,codex:o.loadCodex}[P],{state:n}),ge=R.status==="saving"?a("span",{className:"cm-hint"},M("saving")):R.status==="error"?a("span",{className:"cm-msg err"},M("autoSaveFailed",{message:R.error??""})):a("span",{className:"cm-hint"},R.status==="saved"?M("autoSavedAt",{time:new Date(R.at).toLocaleTimeString()}):M("autoSaveHint"));return a("div",{className:"cm-section"},a("div",{className:"cm-tabs-row"},a("div",{className:"cm-tabs",role:"tablist"},ne.map(([P,_])=>a("button",{key:P,type:"button",role:"tab","aria-selected":String(k===P),className:"cm-tab"+(k===P?" active":""),onMouseEnter:()=>oe(P),onFocus:()=>oe(P),onClick:()=>y(P)},_))),ge),a(be,{state:n,api:o,load:o.loadCommunity,locale:$,quiet:!0}),ka(r),k==="statistics"?a(be,{state:n,api:o,autoExport:N==="export"}):null,k==="overview"?a(E,{key:"overview"},a("div",{className:"cm-overview-grid"},a("div",{className:"cm-cards",style:{"--cm-overview-count":T.hideTodayCost===!0?2:3}},T.hideTodayCost===!0?null:a(it,{title:M("cardToday"),value:W(Q(n.today,T),T),sub:M("callsTokens",{calls:n.today.calls,input:L(n.today.input),cache:L(n.today.cacheRead+n.today.cacheWrite),output:L(n.today.output)})}),a(it,{title:M("cardMonth"),value:W(Q(n.month,T),T),sub:M("callsTokens",{calls:n.month.calls,input:L(n.month.input),cache:L(n.month.cacheRead+n.month.cacheWrite),output:L(n.month.output)})}),a(it,{title:M("cardTotal"),value:W(Q(n.total,T),T),sub:M("cardTotalSub",{calls:n.total.calls})}))),a(Ts,{state:n,t:M}),a("p",{className:"cm-note",key:"cards-footnote"},M("cardsFootnote")),a(Cn,{state:n}),(()=>{const P=To(n);return P!==null?a("p",{className:"cm-note",key:"tz-hint"},M("timezoneHint",{host:P.hostLabel,browser:P.browserLabel})):null})(),a("label",{className:"cm-cards-toggle",title:M("cardsTogglePlanTotalHint")},a("input",{type:"checkbox",checked:(s??T).showTotalWithPlan===!0,onChange:P=>{const _=s??T;_!=null&&l({..._,showTotalWithPlan:P.target.checked})}}),a("span",null,M("cardsTogglePlanTotal"))),a("div",null,a("button",{className:"cm-btn",onClick:()=>y("export")},$==="en"?"Export cost records":"导出费用记录"),a("h3",{className:"cm-h"},M("todaySessions")),a(vn,{state:n,t:M})),a(Ls,{state:n,draft:s,setDraft:l,t:M}),(T.balance?.display==="settings"||T.balance?.display==="both")&&T.hideOfficialBalance!==!0?a(Ws,{state:n,api:o,t:M,draft:s,setDraft:l}):null):null,k==="quotas"?a(Xs,{key:"quotas",state:n,api:o,t:M,draft:s,setDraft:l,targetPlan:w}):null,k==="usage"?a(E,{key:"usage"},!ft||(T.usage?.position??"cost")==="cost"?a(Dt,{state:n,t:M,locale:$}):null,a(Qs,{state:n,config:s??T,t:M,draft:s,setDraft:l}),a(Fs,{state:n,config:s??T,t:M}),a(Rs,{state:n,api:o}),a(Os,{state:n,api:o}),a(be,{state:n,api:o,load:o.loadBillingStorage,draft:s,setDraft:l,locale:$,disabled:R.status==="saving"||(s??T).billingStorageRetentionDays!==T.billingStorageRetentionDays}),a("div",null,a("h3",{className:"cm-h"},M("historyDataTitle")),a("div",{className:"cm-buttons"},g?a(E,null,a("span",{className:"cm-hint"},M("confirmImportLegacy")),a("button",{className:"cm-btn",onClick:pt,disabled:m},M("apply")),a("button",{className:"cm-btn",onClick:()=>f(!1)},M("cancel"))):a("button",{className:"cm-btn",onClick:()=>f(!0),disabled:m},M("importLegacy")),u?a(E,null,a("span",{className:"cm-hint"},M("confirmReset")),a("button",{className:"cm-btn danger",onClick:Le,disabled:m},M("confirmClear")),a("button",{className:"cm-btn",onClick:()=>b(!1)},M("cancel"))):a("button",{className:"cm-btn danger",onClick:()=>b(!0),disabled:m},M("clearAllHistory"))),a("p",{className:"cm-note"},M("legacyImportNote")))):null,k==="codex"?a(Bn,{key:"codex",state:n,api:o,t:M,locale:$,view:"panel",ready:p}):null,k==="display"?a(E,{key:"display"},n?.secretMigration?.pending?.length>0?a(Bo,{pending:n.secretMigration.pending,t:M}):null,a(be,{state:{...n,displayPreviewCodex:U.source===(n.config.codexQuotaSource??"auto")?ra():{status:"idle",windows:{}}},api:o,load:o.loadDisplay,draft:s,setDraft:l,t:M,locale:$,numInput:Ge,displayOptions:ha,quotaPlacementValue:ia,quotaPlacementPatch:ca,quotaPlacementOptions:ua,CURRENCY_PRESETS:Ds,USAGE_POSITION_SWITCHABLE:ft,formatMoneyUsd:W,planOptions:De.map(P=>[P.id,M(P.labelKey)]),onNavigate:(P,_)=>{v(_),y(P)},renderSidebar:(P,_=n)=>Rt({..._,config:P},!0,void 0,!0),renderCorner:P=>a(cn,{useCost:()=>({state:P})}),renderStyleSample:(P,_=n,ye=!0)=>{if(!ye)return Rt({..._,config:P},!0,void 0,!0);const xe=P.sidebarSimple===!0,ce={...P,peakNotice:!1,hideBudget:!1,hideTodayCost:!1,budget:{...P.budget,enabled:!0,amount:Number(P.budget?.amount)>0?P.budget.amount:100}},pe={..._,config:ce},re=na(_.codingPlans?.minimax?.windows??{});return a("div",{className:"cm-footer-stack"+(xe?" simple":P.sidebarStyle==="compact"?" compact":"")},a(Tt,{state:pe,wide:!0,summary:xe}),a(oa,{five:re.five??{percent:24},seven:re.seven??{percent:18},fetchedAt:0,t:M,wide:!0,direction:ie(P,"plan")}))}})):null,k==="pricing"?a("div",{key:"pricing",className:"cm-pricing-page"},a("div",{className:"cm-pricing-heading"},a("div",null,a("h3",{className:"cm-h"},$==="en"?"Pricing":"价格设置"),a("p",{className:"cm-note"},$==="en"?"New prices apply to future calls. Historical costs keep their original rates.":"价格修改用于后续调用,历史费用沿用原价格。")),a("span",{className:"cm-pricing-unit"},$==="en"?"Per 1M tokens":"每百万 Token")),a("div",{className:"cm-pricing-nav",role:"tablist","aria-label":$==="en"?"Pricing sections":"价格分区"},[["models","模型定价","Model pricing"],["catalog","参考价格表","Price tables"],["tools","同步与规则","Sync & rules"]].map(([P,_,ye])=>a("button",{key:P,id:"cm-pricing-"+P,type:"button",role:"tab","aria-selected":h===P,"aria-controls":"cm-pricing-panel",tabIndex:h===P?0:-1,className:"cm-pricing-nav-item"+(h===P?" active":""),onClick:()=>C(P),onKeyDown:xe=>{const ce=["models","catalog","tools"],pe=xe.key==="ArrowRight"?1:xe.key==="ArrowLeft"?-1:0;if(pe){xe.preventDefault();const re=ce[(ce.indexOf(P)+pe+3)%3];C(re),xe.currentTarget.parentElement.querySelector("#cm-pricing-"+re)?.focus()}}},$==="en"?ye:_))),a("div",{id:"cm-pricing-panel",className:"cm-pricing-content",role:"tabpanel","aria-labelledby":"cm-pricing-"+h},h==="models"?a(be,{state:n,api:o,load:o.loadPricing,mode:"matching",draft:s,setDraft:l,t:M,locale:$,resolveClientPrice:Ka,prettyProviderKey:ut,setField:D,priceEditor:{PriceInput:An,priceFactor:yt,setPriceFactor:Bt,multiplierOptions:ga,priceMultiplierSettings:gt,priceAt:Ze}}):null,h==="catalog"?a("div",{className:"cm-pricing-catalog"},a("h3",{className:"cm-h"},M("priceTableTitle")),a(be,{state:n,api:o,load:o.loadPricing,mode:"catalog",draft:s,setDraft:l,t:M,locale:$,vendorLabels:js,priceEditor:{priceAt:Ze,priceFactor:yt},renderEditor:(P,_,ye)=>P==="deepseek"?a(Is,{modelId:_==="__default__"?M("defaultModelId"):_,entry:ye,isDefault:_==="__default__",draft:s,setDraft:l,t:M}):a(_s,{provider:P,modelId:_,entry:ye,draft:s,setDraft:l,t:M,api:o,lockedIds:P==="openrouter"?n.priceLockIds??[]:[],releaseDisabled:JSON.stringify(s)!==A.current})})):null,h==="tools"?a("div",{className:"cm-pricing-tools"},a("section",{className:"cm-pricing-tool"},a(Es,{state:n,draft:s,setDraft:l,t:M})),a("section",{className:"cm-pricing-tool"},a(be,{state:n,api:o,load:o.loadPricing,mode:"history",locale:$,disabled:m||JSON.stringify(s)!==A.current})),a("section",{className:"cm-pricing-tool"},a("h3",{className:"cm-h"},M("dataSync")),(s??T).currency==="CNY"&&(s??T).prices?.currency!=="CNY"?a("div",{className:"cm-note",role:"status"},M("pricingCnyHint",{rate:(s??T).exchangeRate}),(s??T).pricingCurrency!=="CNY"?a("button",{className:"cm-btn small",disabled:m,onClick:()=>D("pricingCurrency","CNY")},M("pricingCurrencyCny")):null):null,a("div",{className:"cm-field"},a("label",null,M("pricingCurrencyLabel")),a("select",{className:"cm-input",value:s?.pricingCurrency==="CNY"?"CNY":"USD",onChange:P=>D("pricingCurrency",P.target.value)},a("option",{value:"USD"},M("pricingCurrencyUsd")),a("option",{value:"CNY"},M("pricingCurrencyCny"))),a("p",{className:"cm-note"},M("pricingCurrencyNote"))),a("div",{className:"cm-buttons"},d?a(E,null,a("span",{className:"cm-hint"},M("confirmFetch")),a("button",{className:"cm-btn",onClick:le,disabled:m},M("apply")),a("button",{className:"cm-btn",onClick:()=>c(!1)},M("cancel"))):a("button",{className:"cm-btn",onClick:()=>c(!0),disabled:m},M("syncFromDocs"))),a("p",{className:"cm-note"},M("lastSync",{time:T.fetchedAt!==null?new Date(T.fetchedAt).toLocaleString():M("neverSynced")})+M("source",{source:T.priceSource==="official"?M("sourceOfficial"):M("sourceBundled")})),a("p",{className:"cm-note"},M("syncScopeNote"))),a("section",{className:"cm-pricing-tool"},a(be,{state:n,api:o,load:o.loadOpenRouter}))):null)):null,a(be,{state:n,api:o,load:o.loadCommunity,locale:$,quiet:!0,footer:!0}))}const ol=["remote"];async function sl(e){const t=e.remote;if(t===void 0||typeof t.$mount!="function")return;const o=await t.$mount(ro);e.effect(()=>()=>{o()},"cost-meter: remote contribution");const n=e.get("remote.costMeter");if(n===void 0)return;e.inject(["connection"],S=>S.effect(()=>{const I=S.get("connection")?.rpc;return la(I,()=>n.getPiAiCodexQuota(),()=>n.getChatgptSubQuota()),vt(),()=>{U.rpc===I&&(la(null),vt())}},"cost-meter: Codex quota transport"));const s=()=>{try{return ze(e.get("locale")?.getSnapshot?.().active)}catch{return null}},l=Ro({status:"loading",error:null,state:null},S=>{const I=s()||ze(S.state?.meta?.locale)||Pa();return{...S,locale:I,...S.state?{state:{...S.state,config:{...S.state.config,activeLocale:I}}}:{}}}),r=()=>z(H(l.getSnapshot().state?.config||{activeLocale:l.getSnapshot().locale})),i=async(S,I)=>{const q=await n[S](...I??[]);if(q===null||typeof q!="object"||q.ok!==!0)throw new Error(q?.error?.message??r()("rpcFailed",{method:S}));return q.value},d=S=>(l.set({status:"ready",error:null,state:S}),S);let c=Date.now(),u=!1,b=!0,g=1,f=0,m=0,x=Promise.resolve();const h=(S,I)=>{if(typeof S?.pricesRev!="string"||S.pricesRev!==I?.pricesRev)return S;const q=I?.config?.prices;return q===void 0?S:{...S,config:{...S.config,prices:q}}},C=async()=>{if(!b||u||m)return;const S=f,I=()=>b&&S===f&&m===0;u=!0,c=Date.now();const q=l.getSnapshot();q.state===null&&l.set({...q,status:"loading"});try{const X=q.state?.pricesRev,Te=await i(q.state===null?"getLocalState":typeof X=="string"?"getStateSince":"getState",typeof X=="string"?[X]:[]);if(!I())return;if(g=1,l.set({status:"ready",error:null,state:h(Te,q.state)}),q.state===null){const He=await i("getState");I()&&l.set({status:"ready",error:null,state:h(He,Te)})}}catch(X){if(!I())return;q.state===null&&(c=Date.now()),g=Math.min(g*2,60),l.set({status:"error",error:X?.message??String(X),state:l.getSnapshot().state??q.state})}finally{u=!1}};e.effect(()=>e.on("connection/reset",()=>{C()}),"cost-meter: reconnect reload");const N=setInterval(()=>{const S=l.getSnapshot().state,I=S?.config.sidebarModels,q=S?I?.enabled||I?.dock?I.refreshSeconds:60:g;!document.hidden&&Date.now()-c>=(q||60)*1e3&&C()},1e3);e.effect(()=>()=>{b=!1,clearInterval(N)},"cost-meter: poll timer");const y=()=>{b&&e.fiber?.uid!==null&&l.set(l.getSnapshot())},p=S=>S.effect(()=>{y();const I=S.get("locale")?.subscribe?.(y);return()=>{I?.(),y()}},"cost-meter: DSH locale");typeof e.inject=="function"?e.inject(["locale"],p):s()&&p(e),e.effect(()=>e.on("locale/change",y),"cost-meter: locale change"),window.addEventListener?.("languagechange",y),e.effect(()=>()=>window.removeEventListener?.("languagechange",y),"cost-meter: browser locale");const k=()=>{document.visibilityState==="visible"&&C()};document.addEventListener("visibilitychange",k),e.effect(()=>()=>{document.removeEventListener("visibilitychange",k)},"cost-meter: visibility reload");const w=async(S,I="rpcSyncFailed",q=!1)=>{const X=await S;if(X===null||typeof X!="object"||X.ok!==!0)throw new Error(X?.error?.message??(q?X?.value?.message:void 0)??r()(I));return X.value.state!==void 0&&l.set({status:"ready",error:null,state:X.value.state}),X.value},v={},R=S=>(v[S]||(v[S]=ve.async("./client."+S+".js").then(I=>I.mount(e,l,H,{formatMoneyUsd:W,displayCostOf:Q,formatTokens:L,updateConfig:q=>j.updateConfig(q)})).catch(I=>{throw delete v[S],I})),v[S]),j={loadBillingStorage:()=>R("billing-storage"),billingStorage:async S=>i("billingStorage",[Ha.parse(S)]),loadSettingsOverview:()=>R("settings-overview"),loadStatistics:()=>R("statistics"),loadOpenRouter:()=>R("openrouter"),loadCommunity:()=>R("community"),loadPricing:()=>R("pricing"),loadDisplay:()=>Promise.all([R("display"),R("sidebar-order")]).then(([S])=>S),loadCodex:()=>R("codex"),reload:C,updateConfig:async S=>{const{activeLocale:I,...q}=S;f++,m++;const X=x.catch(()=>{}).then(async()=>{const Te=await i("updateConfig",[q]);return l.set({status:"ready",error:null,state:Te}),S.planBilling&&setTimeout(()=>{C()},1500),Te});x=X;try{return await X}finally{m--,f++}},fetchPrices:async()=>w(n.fetchPrices()),releasePriceLock:async S=>{const I=await w(n.releasePriceLock(S),"rpcSyncFailed",!0);if(!I.ok)throw new Error(I.message);return I},resetHistory:async()=>{const S=await i("resetHistory");return l.set({status:"ready",error:null,state:S}),S},applyCodexCompatHistory:async()=>d(await i("applyCodexCompatHistory")),dismissCodexCompat:async()=>d(await i("dismissCodexCompat")),importLegacyHistory:async()=>{const S=await n.importLegacyHistory();if(S===null||typeof S!="object"||S.ok!==!0)throw new Error(S?.error?.message??S?.value?.message??r()("legacyImportFailed",{message:"RPC failed"}));return S.value.state!==void 0&&l.set({status:"ready",error:null,state:S.value.state}),S.value},getDaySessions:async S=>i("getDaySessions",[S]),getSessionCost:async S=>i("getSessionCost",[S]),getTurnCost:async(S,I,q)=>i("getTurnCost",[S,I,q,l.getSnapshot().state?.config?.currency]),getTopSessions:async(S,I,q)=>i("getTopSessions",[S,I,q]),refreshBalance:async()=>w(n.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>w(n.refreshGoQuota()),refreshGatewayQuota:async(S=null)=>w(S==null?n.refreshGatewayQuota():n.refreshGatewayQuota(S)),refreshCustomBalance:async(S=null)=>w(S==null?n.refreshCustomBalance():n.refreshCustomBalance(S)),refreshCodingPlan:async S=>w(n.refreshCodingPlan(S)),loginCodingPlan:async S=>w(n.loginCodingPlan(S)),setCredential:async(S,I)=>w(n.setCredential(S,I),"rpcSyncFailed",!0),clearCredential:async S=>w(n.clearCredential(S),"rpcSyncFailed",!0)},A=S=>{S.target?.closest?.('[data-slot="conversation.input.model"]')&&j.loadOpenRouter().catch(()=>{})};for(const S of["pointerover","focusin"])e.effect(()=>(document.addEventListener(S,A),()=>document.removeEventListener(S,A)));C();const B=e.get("slots");if(B===void 0)return;const F=S=>{typeof B.entries=="function"&&B.entries(S).some(I=>I.locale==="dsh-context")&&j.loadStatistics().catch(()=>{})};e.on("slots/changed",F),["conversation.view","sidebar.right.pane.tab","conversation.input.overlay"].forEach(F);const G=()=>({hooks:{cost:l},api:j});B.inject("plugins.bundle.config",()=>B.register({name:"plugins.bundle.config",key:"dsh-cost-meter",inject:G},On));for(const[S,I]of[["header","conversation.session.header.actions"],["dock","conversation.composer.dock"]])B.inject(I,()=>B.register({name:I,id:"cost-meter-statistics",order:1,inject:()=>({...G(),entryPosition:S})},Ms));B.inject("conversation.chat.turnTail",()=>B.register({name:"conversation.chat.turnTail",id:"cost-meter-turn",order:10,inject:G},Do));const ae=()=>({gen:0,dispose:null}),K=(S,I,q,X,Te=!0)=>{S.dispose!==null&&(S.dispose(),S.dispose=null),S.gen+=1;const He=S.gen;Te&&B.inject(I,()=>{if(S.gen!==He)return;const Re=typeof q=="function"?q():B.register(q,X);if(S.gen!==He){Re();return}return S.dispose=Re,()=>{S.dispose===Re&&(S.dispose=null),Re()}})},$=ae(),M=S=>{const I=S==="header"?"conversation.session.header.actions":"conversation.composer.dock";K($,I,S==="header"?{name:I,id:"cost-meter",order:-5,inject:G}:{name:I,id:"cost-meter",order:5,inject:G},S==="header"?Lo:Eo,S!=="off")},T=ae(),le=S=>{K(T,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:G},vs,S)},Le=ae(),pt=S=>{K(Le,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:G},cn,S)};B.inject("conversation.input.dock",()=>B.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:G},ks)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:G},xs)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-peak-progress-guide",order:1,inject:G},Xo)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-summary-guide",order:1,inject:G},Zo)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:G},ws)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:G},Cs)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-codex-compat",order:1,inject:G},tl));const D=ae(),ne=S=>{K(D,"sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:G},Yo),null,S)};window.cmPeakAlertPreview=S=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(zo,{detail:{kind:S==="offpeak"?"offpeak":"peak"}}))};const oe=ae(),ge=S=>{K(oe,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:S==="en"?Ee.en.sectionLabel:Ee.zh.sectionLabel,inject:G},al?nl:On,!0)},P=ae(),_=S=>{K(P,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:G},Dt,S)},ye=ae(),xe=(S,I)=>{K(ye,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:I==="en"?Ee.en.usageSectionLabel:Ee.zh.usageSectionLabel,inject:G},Dt,S)};let ce=null,pe=null,re=null,wa=null,Dn=null,Ln=null;const En=()=>{const S=l.getSnapshot().state;S?.config?.sessionListCosts&&R("session-list").catch(()=>{});const I=S?.config?.position??"dock",q=S?.config?.sidebar!==!1&&S?.config?.hideTodayCost!==!0,X=S?.config?.balance?.display??"both",Te=(X==="sidebar"||X==="both")&&S?.config?.hideOfficialBalance!==!0,He=jn=>jn?.enabled===!0&&["sidebar","both"].includes(jn.display),Re=q||Te||S?.config?.codexQuotaEnabled===!0||S?.config?.sidebarModels?.enabled===!0||S?.config?.budget?.enabled===!0&&S?.config?.hideBudget!==!0||S?.config?.goQuota?.enabled===!0&&["sidebar","both"].includes(S.config.goQuota.display)||S?.config?.peakEnabled===!0&&S.config.peakNotice!==!1||Object.values(S?.config?.codingPlans??{}).some(He)||(S?.config?.gatewayQuotas?.sources??[]).some(He)||St(S,S?.config).length>0;S?.config?.followSkinTransparency&&R("display").catch(()=>{}),Re&&ve.async&&R("sidebar-order").catch(()=>{});const Na=S?.config?.corner?.enabled===!0||S?.config?.sidebarModels?.dock===!0,Ke=H(S?.config||{activeLocale:l.getSnapshot().locale}),mt=S?.config?.usage?.position??"cost";I!==ce&&(M(I),ce=I),Re!==pe&&(le(Re),pe=Re),Na!==re&&(pt(Na),re=Na);const Sa=S?.config?.peakEnabled===!0;Sa!==Ln&&(ne(Sa),Ln=Sa),Ke!==wa&&(ge(Ke),wa=Ke),mt!==Dn?(ft&&(_(mt==="general"),xe(mt==="section",Ke)),Dn=mt):ft&&mt==="section"&&Ke!==wa&&xe(!0,Ke)};En();const In=l.subscribe(En);return e.effect(()=>()=>{In()},"cost-meter: slot sync"),In}return Lt.apply=sl,Lt.inject=ol,Ca.exports}});
|
|
7
|
+
`),j=p.map((T,le)=>T.text!=null?a("div",{key:le,className:"cm-mm-row wide"},a("span",{className:"cm-bbox-label"},T.name),a("span",{className:"cm-mm-text cm-num"},T.text)):a(E,{key:le},T.view.row)),A=T=>{if(!T.key||T.key==="Enter"||T.key===" "){T.stopPropagation(),T.preventDefault?.();const le=n.accounts[(x+1)%n.accounts.length];bs(o.id,le.id),c({source:o.id,id:le.id})}},B=g?a("span",{className:"cm-gw-switcher","aria-label":i("gatewaySwitchAccount",{account:C||x+1}),onClick:A,onKeyDown:A,role:"button",tabIndex:0},`${x+1}/${n.accounts.length} ⇄`):null,F=g?a("div",{className:"cm-bbox-head"},a("div",{className:"cm-mm-title"},o.label||o.id),B):a("div",{className:"cm-mm-title"},o.label||o.id),G=g&&C?a("div",{className:"cm-gw-sub"},C):null,ae=a(E,null,F,G,...j),K=p.filter(T=>T.view).map(T=>T.view.label).filter(T=>T!==null),$=K.length>0?K.slice(0,2).map(T=>T+"%").join(" "):p[0].text??"—",M=a("div",{className:"cm-bbox-rail cm-num"},$);return a(J,{portal:!0,label:a("span",{style:{whiteSpace:"pre-line"}},R),side:"right",delayMs:300},a("div",{...t,"data-cm-display":"gateway","data-cm-source":o.id,className:"cm-bbox cm-mm clickable"+(k==="ok"?"":" "+k)+(l===!1?" rail":"")+(u.busy?" busy":""),...ke(u.busy,u.run)},l===!1?a(E,null,M,B):ae))}function ys(e,t,o,n){const s=Array.isArray(e.gatewayQuotas)?e.gatewayQuotas:[],l=[];for(const r of t.gatewayQuotas?.sources??[]){if(r.enabled===!1||r.display!=="sidebar"&&r.display!=="both")continue;const i=s.find(d=>d.id===r.id);!i||i.status!=="ok"&&i.status!=="partial"&&i.status!=="stale"||i.accounts.length===0||l.push(a(gs,{key:"gateway:"+r.id,source:r,snapshot:i,state:e,wide:o,api:n}))}return l}const hs={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",clinepass:"CP",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo",factory:"Factory",opendesign:"OpenDesign"};function hn(e,t,o){return e?.enabled!==!0?!1:typeof e.showInComposer=="boolean"?e.showInComposer:e.display!=="off"&&t?.enabled===!0&&t[o]!==!1}function ia(e,t,o){const n=e?.display??"settings";return(typeof e?.showInComposer=="boolean"?e.showInComposer:n!=="off"&&t?.enabled===!0&&t[o]!==!1)?{off:"composer",both:"all"}[n]??n+"-composer":n}function ca(e){const t={composer:"off","sidebar-composer":"sidebar","settings-composer":"settings",all:"both"}[e];return{display:t??e,showInComposer:t!==void 0}}function ua(e){return[["sidebar","balanceSidebar"],["settings","balanceSettings"],["both","quotaSidebarSettings"],["composer","quotaComposer"],["sidebar-composer","quotaSidebarComposer"],["settings-composer","quotaSettingsComposer"],["all","quotaAllPositions"],["off","off"]].map(([t,o])=>a("option",{key:t,value:t},e(o)))}function ks(e){const t=e.useCost?e.useCost(N=>N):void 0,o=t?.state?.config;Pt(o?.codexQuotaEnabled===!0&&o.codexQuotaStrip!==!1&&o.quotaStrip?.enabled===!0,o?.codexQuotaSource);const[n,s]=O(null),[l,r]=O({}),i=t?.state,d=e.api;if(!i)return null;const c=i.config,u=c.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(u.enabled!==!0&&c.goQuota?.showInComposer!==!0&&!Object.values(c.codingPlans??{}).some(N=>N.enabled===!0&&N.showInComposer===!0))return null;const b=z(H(c)),g=[];if(u.enabled===!0&&u.budget!==!1){const N=c.budget??{enabled:!1,amount:100,period:"month"};if(N.enabled===!0){const y=Number(c.exchangeRate),k=(i.budgetUsed??(N.period==="day"?Q(i.today,c):N.period==="all"?Q(i.total,c):Q(i.month,c)))*(Number.isFinite(y)&&y>0?y:1),w=Math.max(0,Number(N.amount)||0);if(w>0){const v=Math.min(999,k/w*100),R=v>=100?"over":v>=80?"warn":"ok";g.push({key:"budget",label:b("budgetShort"),level:R,tip:b("budgetOf",{period:b(Ye[N.period]??"periodMonth")})+" · "+b("usedOf",{used:de(k,c),amount:de(w,c)})+" · "+v.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(we(Math.min(100,v),ie(c,"budget")).width)}]})}}}if(hn(c.goQuota,u,"go")){const N=i.goQuota;if(c?.goQuota?.enabled!==!1&&N?.status==="ok"){const y=c.goQuota.main==="weekly"||c.goQuota.main==="monthly"?c.goQuota.main:"rolling",p=y==="rolling"?N.rolling:y==="weekly"?N.weekly:N.monthly;if(p!==null&&typeof p=="object"&&typeof p.percent=="number"){const k=Math.max(0,Math.min(100,Math.round(Number(p.percent)||0))),w=k>=100?"over":k>=80?"warn":"ok",v=typeof p.resetsAt=="string"&&p.resetsAt.length>0?" · "+b("goResetAt",{time:new Date(p.resetsAt).toLocaleString()}):"";g.push({key:"go",label:"Go "+b(y==="rolling"?"goShortRolling":y==="weekly"?"goShortWeekly":"goShortMonthly"),level:w,tip:fn(N,c,b),segs:[{name:"main",pct:Math.round(we(k,ie(c,"go")).width)}]})}}}for(const N of De){const y=i.codingPlans?.[N.id];if(!hn(c.codingPlans?.[N.id],u,"plans")||!y||y.status!=="ok")continue;const p=y.windows!==null&&typeof y.windows=="object"?y.windows:{},k=Mt(p,N.id),w=N.id==="factory"?[k.filter(([v])=>!v.startsWith("core_")),k.filter(([v])=>v.startsWith("core_"))]:[k];for(const[v,R]of w.entries()){if(R.length===0)continue;const j=hs[N.id]??N.id,A=[],B=[];y.message&&B.push(y.message);let F=0,G=0;for(const[ae,K]of R){const $=We(ae,b),M=typeof K?.resetsAt=="string"&&K.resetsAt.length>0?" · "+b("goResetAt",{time:new Date(K.resetsAt).toLocaleString()}):"",T=K!==null&&typeof K=="object"&&typeof K.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(K.percent)||0))):null;if(B.push($+" "+(T===null?typeof K?.text=="string"?K.text:"—":T+"%")+M),T===null){A.push({name:ae,pct:null,text:typeof K?.text=="string"?K.text:"—"});continue}G>=(N.id==="factory"?3:2)||(G+=1,A.push({name:ae,pct:Math.round(we(T,ie(c,"plan")).width)}),F=Math.max(F,T>=100?2:T>=80?1:0))}y.fetchedAt>0&&B.push(b("goQuotaFetchedAt",{time:new Date(y.fetchedAt).toLocaleTimeString()})),A.length!==0&&g.push({key:N.id+(v?":core":""),label:j+(N.id==="factory"?v?" Core":" Standard":""),level:["ok","warn","over"][F],tip:B.join("; "),segs:A})}}const f=u.enabled===!0&&c.codexQuotaEnabled===!0&&c.codexQuotaStrip!==!1&&U.source===(c.codexQuotaSource??"auto")&&U.status==="ok"?U.windows:{},m=f.five??null,x=f.weekly??null,h=N=>Math.max(0,Math.min(100,Math.round(Number(N.percent)||0)));if(m!==null||x!==null){const N=m===null?null:h(m),y=x===null?null:h(x),p=Math.max(N??0,y??0);g.push({key:"codex",label:"Codex",level:p>=100?"over":p>=80?"warn":"ok",tip:b("codexQuotaTitle")+": "+[N===null?null:"5h "+Oe(100-N,"remaining",b),y===null?null:b("codingPlanRemain7d")+" "+Oe(100-y,"remaining",b)].filter(Boolean).join(" · "),segs:[N===null?null:{name:"5h",pct:100-N},y===null?null:{name:"weekly",pct:100-y}].filter(Boolean)})}if(g.length===0)return null;const C=N=>{n!==null||!d||(s(N),r(y=>({...y,[N]:null})),Promise.resolve().then(()=>N==="budget"?d.reload():N==="go"?d.refreshGoQuota():N==="codex"?At(!0,c.codexQuotaEnabled===!0,c.codexQuotaSource):N==="factory:core"?d.refreshCodingPlan("factory"):d.refreshCodingPlan(N)).catch(y=>{r(p=>({...p,[N]:y?.message??String(y)}))}).finally(()=>s(null)))};return a("div",{className:"cm-qstrip"},g.map(N=>{const y=n===N.key,p=l[N.key],k=[a("span",{className:"cm-qlabel",key:"l"},N.label)];y?k.push(a("span",{className:"cm-qtext",key:"busy"},b("refreshing"))):N.segs.forEach((v,R)=>{R>0&&k.push(a("span",{className:"cm-qsep",key:"sep"+R,"aria-hidden":"true"})),v.pct===null?k.push(a("span",{className:"cm-qtext",key:v.name},v.text)):k.push(a("span",{className:"cm-qseg",key:v.name},a("span",{className:"cm-qbar"},a("span",{className:"cm-qfill",style:{width:v.pct+"%"}})),a("span",null,N.key==="codex"?(N.segs.length>1?(v.name==="5h"?"5h":b("goShortWeekly"))+" ":"")+Oe(v.pct,"remaining",b):v.pct+"%")))});const w=[N.tip];return!y&&d&&w.push(b("clickToRefresh")),y&&w.push(b("refreshing")),p&&w.push("⚠ "+b("balanceRefreshFailed",{message:p})),a(J,{portal:!0,key:N.key,label:w.join("; "),side:"bottom",delayMs:400},a("span",{className:"cm-qchip"+(d?" action":"")+(N.level==="ok"?"":" "+N.level),...d?ke(y,()=>C(N.key)):{}},k))}))}const rt="dsh-cost-meter:simple-guide-dismissed";function da(e){if(e?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(rt)==="1"}catch{return!1}}function xs(e){const t=e.useCost?e.useCost(m=>m):void 0,o=fe(!1),[n,s]=O(!1),[l,r]=O(!1),[i,d]=O(!1),c=t?.state?.config,u=!!c&&!i&&!da(c);if(V(()=>{const m=()=>d(!0);return window.addEventListener?.(rt,m),()=>window.removeEventListener?.(rt,m)},[]),!u)return null;const b=z(H(c)),g=()=>{d(!0);try{window.localStorage.setItem(rt,"1")}catch{}window.dispatchEvent?.(new Event(rt))},f=async m=>{if(!o.current){o.current=!0,s(!0),r(!1);try{if((await e.api.updateConfig({sidebarSimple:m,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==m)throw new Error;g()}catch{r(!0)}finally{o.current=!1,s(!1)}}};return a(dn,{actions:{close:g,keep:()=>f(!1),enable:()=>f(!0)},className:"cm-qguide",role:"dialog","aria-label":b("sidebarSimpleTitle"),"aria-busy":n,onKeyDown:m=>{m.key==="Escape"&&(m.stopPropagation(),g())}},a("div",{className:"cm-bbox-head"},a("h4",null,b("sidebarSimpleTitle")),a("button",{type:"button",className:"cm-btn small","aria-label":b("closeGuide"),"data-cm-action":"close",onClick:g},"×")),a("p",null,b("sidebarSimpleBody")),l?a("p",{role:"alert"},b("sidebarSimpleError")):null,a("div",{className:"cm-buttons"},a("button",{type:"button",className:"cm-btn small","data-cm-action":"keep",disabled:n,onClick:()=>f(!1)},b("sidebarSimpleOff")),a("button",{type:"button",className:"cm-btn small primary","data-cm-action":"enable",disabled:n,onClick:()=>f(!0)},b("sidebarSimpleOn"))))}function ws(e){const t=e.useCost?e.useCost(i=>i):void 0,o=fe(!1),n=t?.state;if(!n)return null;const s=n.config;if(!da(s)||s.quotaStrip?.promptSeen===!0)return null;const l=z(H(s)),r=i=>{if(o.current===!0)return;o.current=!0;const d=s.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};e.api.updateConfig({quotaStrip:{...d,enabled:i,promptSeen:!0}}).catch(()=>{o.current=!1})};return a("div",{className:"cm-qguide",role:"dialog","aria-label":l("quotaStripGuideTitle")},a("h4",null,l("quotaStripGuideTitle")),a("p",null,l("quotaStripGuideBody")),a("div",{className:"cm-buttons"},a("button",{type:"button",className:"cm-btn small",onClick:()=>r(!1)},l("quotaStripGuideOff")),a("button",{type:"button",className:"cm-btn small primary",onClick:()=>r(!0)},l("quotaStripGuideOn"))))}const kn="dsh-cost-meter:balance-click-hint-seen",Ns=()=>{try{return window.localStorage.getItem(kn)==="1"}catch{return!1}},Ss=()=>{try{window.localStorage.setItem(kn,"1")}catch{}};function Cs(e){const t=e.useCost?e.useCost(f=>f):void 0,o=fe(!1),[n,s]=O(!1),[l]=O(Ns),r=t?.state;if(!r)return null;const i=r.config,d=i.balance?.display==="sidebar"||i.balance?.display==="both",c=(i?.customBalances??[]).some(f=>f?.enabled===!0&&(f.display==="sidebar"||f.display==="both"))||i.customBalance?.enabled===!0&&(i.customBalance?.display==="sidebar"||i.customBalance?.display==="both"),u=De.some(f=>{const m=i.codingPlans?.[f.id];return m?.enabled===!0&&(m.display==="sidebar"||m.display==="both")});if(n||l||i.balance?.clickHintSeen===!0||!d&&!c&&!u||!da(i)||i.quotaStrip?.promptSeen!==!0)return null;const b=z(H(i)),g=()=>{o.current!==!0&&(s(!0),o.current=!0,Ss(),e.api.updateConfig({balance:{...i.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,s(!1)}))};return a("div",{className:"cm-qguide",role:"dialog","aria-label":b("balanceClickGuideTitle")},a("h4",null,b("balanceClickGuideTitle")),a("p",null,b("balanceClickGuideBody")),a("div",{className:"cm-buttons"},a("button",{type:"button",className:"cm-btn small primary",onClick:g},b("balanceClickGuideOk"))))}function xn(e,t,o){const n=t.sidebarTodayMetric??"cost";return a("span",{className:"cm-today-values","data-both":n==="both"},n!=="tokens"?a("span",{"data-cm-today":"cost"},W(Q(e,t),t)):null,n!=="cost"?a("span",{"data-cm-today":"tokens"},L(["input","output","cacheRead","cacheWrite"].reduce((s,l)=>s+(Number(e?.[l])||0),0))+" "+o("tokensUnit")):null)}function Tt(e){const{state:t,wide:o}=e,n=t.today,s=t.config,l=z(H(s)),r=xn(n,s,l),i=s.budget??{enabled:!1,amount:100,period:"month"},d=Number(s.exchangeRate),u=(t.budgetUsed??(i.period==="day"?Q(t.today,s):i.period==="all"?Q(t.total,s):Q(t.month,s)))*(Number.isFinite(d)&&d>0?d:1),b=Math.max(0,Number(i.amount)||0),g=b>0?Math.min(999,u/b*100):null,f=g===null?"ok":g>=100?"over":g>=80?"warn":"ok";if(i.enabled===!0&&s.hideBudget!==!0&&e.todayOnly!==!0){const x=[l("budgetOf",{period:l(Ye[i.period]??"periodMonth")}),l("usedOf",{used:de(u,s),amount:de(b,s)})+" · "+(g===null?"—":g.toFixed(1)+"%"),l("monthTotal",{month:W(Q(t.month,s),s),total:W(Q(t.total,s),s)})].join("; ");if(e.summary===!0)return a(J,{portal:!0,label:x,side:"right",delayMs:300},a("div",{"data-cm-display":"budget",className:"cm-simple-summary"+(f==="ok"?"":" "+f),tabIndex:0},a("span",null,l("budgetOf",{period:l(Ye[i.period]??"periodMonth")})),a("span",{className:"cm-num"},de(u,s)+" / "+de(b,s))));const h=ns(t,s,l);return a(J,{portal:!0,label:x,side:"right",delayMs:300},a("div",{"data-cm-display":"budget",className:"cm-bbox"+(f==="ok"?"":" "+f)+(o?"":" rail")},o?h.body:a("div",{className:"cm-bbox-rail cm-num"},h.rail)))}const m=[s.sidebarTodayMetric==="tokens"?l("todayTokensTitle"):l("todayCostTitle"),l("callsTokens",{calls:n.calls,input:L(n.input),cache:L(n.cacheRead+n.cacheWrite),output:L(n.output)}),l("monthCost",{amount:W(Q(t.month,s),s)}),l("totalCost",{amount:W(Q(t.total,s),s)})].join("; ");return a(J,{portal:!0,label:m,side:"right",delayMs:300},a("div",{"data-cm-display":"today",className:"cm-foot"+(o?"":" cm-foot-rail")},o?a(E,null,a("span",null,l("today")),a("span",{className:"cm-num cm-bal-amt"},r)):a(Nt,{size:16})))}function vs(e){const t=e.useCost?e.useCost(l=>l):void 0;Pt(t?.state?.config?.codexQuotaEnabled===!0&&t?.state?.config?.codexQuotaSidebar!==!1,t?.state?.config?.codexQuotaSource);let o;if(e.useProjection)try{o=e.useProjection("costUsage")}catch{o=void 0}Za(e,o);const n=t?.state,s=n?{...n,config:aa(n,o?.provider)}:null;return s?Rt(s,!!e.wide,e.api):null}function Rt(e,t,o,n=!1){const s=aa(e),l=z(H(s)),r=(s.balance?.display==="sidebar"||s.balance?.display==="both")&&s.hideOfficialBalance!==!0,d=St(e,s).length>0,c=r&&s.balance?.showProgressBar===!0&&e.balance?.status==="ok",u=d&&s.balance?.showProgressBar===!0,b=s.goQuota?.main==="weekly"||s.goQuota?.main==="monthly"?s.goQuota.main:"rolling",g=s.goQuota?.enabled!==!1&&(s.goQuota?.display==="sidebar"||s.goQuota?.display==="both")&&e.goQuota?.status==="ok"&&e.goQuota?.[b]!==null,f=De.map(A=>A.id).filter(A=>{const B=s.codingPlans?.[A];if(B?.enabled!==!0||B.display!=="sidebar"&&B.display!=="both")return!1;const F=e.codingPlans?.[A];if(F?.status!=="ok")return!1;const G=F.windows!==null&&typeof F.windows=="object"?F.windows:{};return Object.keys(G).length>0}),m=f.length>0,x=ys(e,s,t,o),h=s.codexQuotaSidebar!==!1&&(s.codexQuotaEnabled===!0||e.codexCompat?.enabled===!0),C=(s.budget??{}).enabled===!0&&s.hideBudget!==!0,N=s.sidebar!==!1&&s.hideTodayCost!==!0,y=_e(s,Date.now())!==null,p=s.sidebarModels?.enabled===!0;if(!p&&!r&&!d&&!g&&!m&&!h&&!C&&!N&&!y&&x.length===0)return null;const k=s.sidebarSimple===!0,w=!k&&t&&s.sidebarStyle==="compact",v=[];k&&t&&N&&!s.sidebarTodayBalanceInline&&v.push(a("div",{key:"today","data-cm-display":"today",className:"cm-simple-summary"},a("span",null,l("today")),a("span",{className:"cm-num"},xn(e.today,s,l)))),c?v.push(a(Fo,{key:"balance",state:e,wide:t,api:o})):r&&v.push(a(Uo,{key:"balance",state:e,wide:t,api:o})),u?v.push(a(Wo,{key:"customBalance",state:e,wide:t,api:o})):d&&v.push(a(Ko,{key:"customBalance",state:e,wide:t,api:o}));const R=v.length;m&&v.push(...f.map(A=>A==="minimax"?a(rs,{key:"plan:"+A,state:e,wide:t,api:o}):a(fs,{key:"plan:"+A,id:A,state:e,wide:t,api:o}))),v.push(...x),h&&v.push(a(ms,{key:"codex",state:e,wide:t,api:o,preview:n})),g&&v.push(a(ss,{key:"go",state:e,wide:t})),C&&v.push(a(Tt,{key:"budget",state:e,wide:t,summary:k&&t})),N&&(!(k&&t)||s.sidebarTodayBalanceInline)&&v.push(a(Tt,{key:"today",state:e,wide:t,todayOnly:!0})),y&&v.push(a(E,{key:"peak"},t?mn(e,s.sidebarStyle==="summary"&&!s.sidebarSimple?{...s,peakProgressVariant:"summary"}:s,l):as(e,s,l))),p&&v.splice(s.sidebarModels.position==="first"?0:s.sidebarModels.position==="afterBalance"?R:v.length,0,a(As,{key:"models",state:e,wide:t,preview:n}));const j=s.sidebarOrder?.length?s.sidebarOrder:s.sidebarStyle==="summary"&&!k?["today","balance","peak"]:[];if(j.length){const A=B=>{const F=j.indexOf(B.key);return F<0?999:F};v.sort((B,F)=>A(B)-A(F))}return a("div",{...k?{tabIndex:0,role:"region","aria-label":l("sidebarSimple")}:{},className:"cm-footer-stack"+(s.sidebarTodayBalanceInline?" same-line":"")+(t?"":" rail")+(w?" compact":"")+(k?" simple":s.sidebarStyle==="summary"&&t?" summary":"")},...v)}const wn={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Nn="dsh-cost-meter:models-open";function Sn(e,t,o){return Pn(e,e.config,o,t).map(n=>({...n,label:e.modelLabels?.[n.key]??(n.key==="deepseek:legacy"?n.label:ut(n.key)),cost:Q(n,e.config)})).sort((n,s)=>s.cost-n.cost||s.tokens-n.tokens||n.key.localeCompare(s.key))}function As({state:e,wide:t,preview:o=!1}){const n={...wn,...e.config.sidebarModels},s=z(H(e.config)),l=()=>{try{const y=n.remember?window.localStorage.getItem(Nn):null;if(y!==null)return y==="1"}catch{}return n.defaultOpen},[r,i]=O(l),[d,c]=O(n.period);V(()=>c(n.period),[n.period]);const u=fe(n.defaultOpen);V(()=>{i(o&&u.current!==n.defaultOpen?n.defaultOpen:l()),u.current=n.defaultOpen},[n.defaultOpen,n.remember]);const b=Sn(e,d,s),g=b.reduce((y,p)=>y+p.cost,0),f=y=>W(y,e.config),m=s(d==="history"?"modelStatsHistory":"modelStatsToday")+" "+f(g)+" · "+s("modelsCount",{n:b.length}),x=n.summary==="top"&&b.length?b[0].label+" "+f(b[0].cost):m,h=a(E,null,a("span",{className:"cm-bal-label"},n.summary==="top"&&b.length?b[0].label:s(d==="history"?"modelStatsHistory":"modelStatsToday")),a("span",{className:"cm-bal-amt cm-num"},n.summary==="top"&&b.length?f(b[0].cost):f(g)+" · "+s("modelsCount",{n:b.length}))),C=()=>{i(!r);try{n.remember&&!o&&window.localStorage.setItem(Nn,r?"0":"1")}catch{}};if(!t||e.config.sidebarSimple)return a("div",{"data-cm-display":"models",className:"cm-foot cm-num"+(t?"":" cm-foot-rail"),title:x+" · "+m},t?h:a(Nt,{size:16}));const N=b.slice(0,n.topN);return b.length>n.topN&&N.push(b.slice(n.topN).reduce((y,p)=>{for(const k of["cost","input","output","cacheRead","cacheWrite"])y[k]+=p[k];return y},{key:"other",label:s("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),a("div",{"data-cm-display":"models",className:"cm-bbox cm-model-costs"},a("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(r),title:m,onClick:C},a("span",{className:"cm-caret"+(r?" open":"")}),h),r?a(E,null,a("div",{className:"cm-buttons"},["today","history"].map(y=>a("button",{key:y,type:"button",className:"cm-mstats-tab"+(d===y?" active":""),"aria-pressed":d===y,onClick:()=>c(y)},s(y==="today"?"modelStatsToday":"modelStatsHistory")))),N.length?N.map(y=>a("div",{key:y.key},a("div",{className:"cm-bbox-head"},a("span",{className:"cm-bal-label",title:y.label},y.label),a("span",{className:"cm-num cm-bal-amt"},f(y.cost))),n.shares?a("div",{className:"cm-bbox-bar",title:(g>0?y.cost/g*100:0).toFixed(1)+"%"},a("div",{className:"cm-bbox-fill",style:{width:(g>0?y.cost/g*100:0)+"%"}})):null,n.tokens?a("div",{className:"cm-mstats-note"},s("modelStatsInput")+" "+L(y.input)+" · "+s("modelStatsCache")+" "+L(y.cacheRead+y.cacheWrite)+" · "+s("modelStatsOutput")+" "+L(y.output)):null)):a("span",{className:"cm-note"},s("modelStatsEmpty"))):null)}function it(e){return a("div",{className:"cm-card"},a("p",{className:"cm-card-title"},e.title),a("div",{className:"cm-card-value cm-num"},e.value),a("p",{className:"cm-card-sub"},e.sub))}const pa=new WeakMap,ma=(e,t)=>e?.().then(o=>(pa.set(e,o),o.prefetch?.(t))).catch(()=>{});function Cn({state:e}){const t=e?.billionContext;return!t||!(t.unresolved>0||["needs_update","changed","bridge_missing"].includes(t.compatibility))?null:a("p",{className:"cm-note","data-billing-accuracy":"billion-context"},H(e.config)==="en"?"Some billion-context usage records are incomplete; cost totals may differ from the provider bill.":"billion-context 部分用量记录不完整,费用统计可能存在偏差。")}function be(e){const t=e.load??e.api.loadStatistics,[o,n]=O(()=>pa.get(t)??null),[s,l]=O(""),[r,i]=O(0);return V(()=>{let d=!0;if(l(""),typeof t=="function")return t().then(c=>{pa.set(t,c),d&&n(()=>c)},c=>{d&&l(String(c.message??c))}),()=>{d=!1}},[e.api,e.load,r]),o?a(o,{...e,formatMoneyUsd:W,formatTokens:L,resolveLocale:H}):e.quiet?null:a("div",{className:s?"":"cm-loading",role:s?"alert":"status","aria-label":H(e.state?.config)==="en"?"Loading":"正在读取"},s||a(E,null,a("i"),a("i"),a("i")),s?a("button",{className:"cm-btn",onClick:()=>i(d=>d+1)},"↻"):null)}const Ps="cm-stat-dialog";function Ms(e){const t=e.useCost?.(u=>u),o=t?.state,[n,s]=O(null),l=Ae.useRef(null),r=o?.config[e.entryPosition==="header"?"hideSessionCostHeader":"hideSessionCostDock"]===!0,i=!r&&!!e.sessionId&&n===e.sessionId;if(V(()=>{i&&l.current?.showModal()},[i]),V(()=>{s(null)},[e.sessionId,r]),!e.sessionId||r)return null;const d=H(o?.config)==="en",c=d?"Conversation cost details":"本会话费用明细";return a(E,null,a("button",{type:"button",className:"cm-btn cm-stat-entry cm-stat-"+(e.entryPosition||"dock"),title:c,"aria-label":c,"aria-haspopup":"dialog",onMouseEnter:()=>ma(e.api.loadStatistics,{state:o,sessionId:e.sessionId}),onFocus:()=>ma(e.api.loadStatistics,{state:o,sessionId:e.sessionId}),onClick:()=>s(e.sessionId)},d?"Cost details":"费用明细"),i?a("dialog",{ref:l,role:"dialog",className:Ps,"aria-label":c,onCancel:()=>s(null)},a("header",{className:"cm-stat-dialog-head"},a("strong",null,c),a("button",{type:"button",className:"cm-btn",autoFocus:!0,"aria-label":d?"Close":"关闭",onClick:()=>s(null)},"×")),a("div",{className:"cm-stat-dialog-body"},o?a(be,{key:e.sessionId,state:o,api:e.api,sessionId:e.sessionId}):a("p",{role:t?.error?"alert":"status"},t?.error||(d?"Loading…":"加载中…"),a("button",{type:"button",className:"cm-btn",onClick:()=>e.api.reload()},d?"Retry":"重试")))):null)}function Ts({state:e,t}){const o=e.externalUsage;if(!o)return null;const n=e.config,s=c=>W(Q(c,n),n),l=c=>t("callsTokens",{calls:c.calls,input:L(c.input),cache:L(c.cacheRead+c.cacheWrite),output:L(c.output)}),r=(c,u)=>({calls:c.calls+u.calls,input:c.input+u.input,output:c.output+u.output,cacheRead:c.cacheRead+u.cacheRead,cacheWrite:c.cacheWrite+u.cacheWrite,cost:Q(c,n)+u.cost,apiCost:Q(c,n)+u.cost}),i=(c,u)=>a("tr",{key:c},a("td",null,c),a("td",{className:"num"},String(u.calls)),a("td",{className:"num"},L(u.input)),a("td",{className:"num"},L(u.cacheRead+u.cacheWrite)),a("td",{className:"num"},L(u.output)),a("td",{className:"num"},s(u))),d=c=>a("div",{className:"cm-scroll"},a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,t("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(u=>a("th",{className:"num"},t(u))))),a("tbody",null,c)));return a("section",{className:"cm-budget"},a("h3",{className:"cm-h"},t("externalUsage")),o.stale?a("p",{className:"cm-note"},t("externalStale")):null,a("div",{className:"cm-cards"},["today","month","total"].map((c,u)=>{const b=r(e[c],o.combined[c]);return a(it,{key:c,title:t("combinedUsage")+" · "+t(["cardToday","cardMonth","cardTotal"][u]),value:s(b),sub:l(b)})})),...o.sources.map(c=>a("details",{key:c.source},a("summary",null,c.source+" · "+t("cardToday")+" "+s(c.today)+" · "+t("cardMonth")+" "+s(c.month)+" · "+l(c.today)),d(["today","month","total"].map((u,b)=>i(t(["cardToday","cardMonth","cardTotal"][b]),c[u]))),a("p",{className:"cm-note"},t("externalHistory")),d(c.history.map(u=>i(u.date,u))))))}const ct=(e,t,o)=>a("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(e),onClick:t},a("span",{className:"cm-caret"+(e?" open":"")}),a("h3",{className:"cm-h"},o));function Rs(e){const{state:t,api:o}=e,n=z(H(t.config)),[s,l]=O(!1);return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(s,()=>l(!s),n("history"))),s?a("div",{className:"cm-collapse-body"},a(Bs,{state:t,api:o})):null)}function Bs(e){const{state:t,api:o}=e,n=z(H(t.config)),[s,l]=O(null),[r,i]=O({}),[d,c]=O(()=>new Set),u=t.history??[];if(u.length===0)return a("p",{className:"cm-empty"},n("noHistory"));const b=f=>{if(s===f){l(null);return}l(f),!(r[f]!==void 0||d.has(f))&&(c(m=>{const x=new Set(m);return x.add(f),x}),o.getDaySessions(f).then(m=>i(x=>({...x,[f]:Array.isArray(m?.sessions)?m.sessions:[]}))).catch(()=>i(m=>({...m,[f]:"error"}))).finally(()=>c(m=>{const x=new Set(m);return x.delete(f),x})))},g=f=>f.map(m=>a("tr",{key:m.id},fa(m,t.config?.showSessionId===!0,n),a("td",{className:"num"},String(m.calls)),a("td",{className:"num"},L(m.input)),a("td",{className:"num"},L(m.cacheRead+m.cacheWrite)),a("td",{className:"num"},L(m.output)),a("td",{className:"num"},W(Q(m,t.config),t.config))));return a("div",{className:"cm-scroll"},a("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},n("historyExpandHint")),a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("colDate")),a("th",{className:"num"},n("colCalls")),a("th",{className:"num"},n("colInTok")),a("th",{className:"num"},n("colCacheTok")),a("th",{className:"num"},n("colOutTok")),a("th",{className:"num"},n("colCost")))),a("tbody",null,u.flatMap(f=>{const m=a("tr",{key:f.date,className:"cm-row-click",onClick:()=>b(f.date)},a("td",null,(s===f.date?"▾ ":"▸ ")+f.date),a("td",{className:"num"},String(f.calls)),a("td",{className:"num"},L(f.input)),a("td",{className:"num"},L(f.cacheRead+f.cacheWrite)),a("td",{className:"num"},L(f.output)),a("td",{className:"num"},W(Q(f,t.config),t.config)));if(s!==f.date)return[m];const x=r[f.date],h=d.has(f.date)&&x===void 0?a("p",{className:"cm-empty"},n("historySessionsLoading")):x==="error"?a("p",{className:"cm-empty"},n("historySessionsError")):!Array.isArray(x)||x.length===0?a("p",{className:"cm-empty"},n("historyNoSessions")):a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("colSession")),a("th",{className:"num"},n("colCalls")),a("th",{className:"num"},n("colInTok")),a("th",{className:"num"},n("colCacheTok")),a("th",{className:"num"},n("colOutTok")),a("th",{className:"num"},n("colCost")))),a("tbody",null,g(x)));return[m,a("tr",{key:f.date+"-sessions"},a("td",{colSpan:6},h))]}))))}function Os(e){const{state:t,api:o}=e,n=z(H(t.config)),[s,l]=O(!1),[r,i]=O(100),[d,c]=O("cost-desc"),[u,b]=O(null),[g,f]=O(!1),[m,x]=O(!1),h=Ae.useRef(0),C=(k,w)=>{const[v,R]=w==="recent"?["recent","desc"]:w.split("-"),j=++h.current;f(!0),x(!1),o.getTopSessions(k,v,R).then(A=>{j===h.current&&b(Array.isArray(A?.sessions)?A.sessions:[])}).catch(()=>{j===h.current&&x(!0)}).finally(()=>{j===h.current&&f(!1)})},N=()=>{l(k=>{const w=!k;return w&&u===null&&!g&&C(r,d),w})},y=k=>{i(k),(s||u!==null)&&C(k,d)},p=k=>{c(k),(s||u!==null)&&C(r,k)};return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(s,N,n("sessionRankTitle"))),s?a("div",{className:"cm-collapse-body"},a("p",{className:"cm-hint"},n("sessionRankHint")),a("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},a("div",{className:"cm-field"},a("label",null,n("sessionRankSort")),a("select",{className:"cm-input",value:d,onChange:k=>p(k.target.value)},a("option",{value:"cost-desc"},n("sessionSortCostDesc")),a("option",{value:"cost-asc"},n("sessionSortCostAsc")),a("option",{value:"time-desc"},n("sessionSortTimeDesc")),a("option",{value:"time-asc"},n("sessionSortTimeAsc")),a("option",{value:"recent"},n("sessionSortRecent")))),a("div",{className:"cm-field"},a("label",null,n("sessionRankLimit")),a("select",{className:"cm-input",value:String(r),onChange:k=>y(Number(k.target.value))},a("option",{value:"50"},"50"),a("option",{value:"100"},"100"),a("option",{value:"200"},"200")))),g?a("p",{className:"cm-empty"},n("sessionRankLoading")):m?a("p",{className:"cm-empty"},n("sessionRankError")):u===null||u.length===0?a("p",{className:"cm-empty"},n("sessionRankEmpty")):a("div",{className:"cm-scroll"},a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("colDate")),a("th",null,n("colSession")),a("th",{className:"num"},n("colCalls")),a("th",{className:"num"},n("colInTok")),a("th",{className:"num"},n("colCacheTok")),a("th",{className:"num"},n("colOutTok")),a("th",{className:"num"},n("colCost")))),a("tbody",null,u.map(k=>a("tr",{key:k.date+":"+k.id},a("td",null,k.date),fa(k,t.config?.showSessionId===!0,n),a("td",{className:"num"},String(k.calls)),a("td",{className:"num"},L(k.input)),a("td",{className:"num"},L((k.cacheRead??0)+(k.cacheWrite??0))),a("td",{className:"num"},L(k.output)),a("td",{className:"num"},W(Q(k,t.config),t.config)))))))):null)}function vn(e){const{state:t}=e,o=z(H(t.config)),n=t.today.sessions??[];if(n.length===0)return a("p",{className:"cm-empty"},o("noSessionsToday"));const s=t.config?.showSessionId===!0;return a("div",{className:"cm-scroll"},a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,o("colSession")),a("th",{className:"num"},o("colCalls")),a("th",{className:"num"},o("colInTok")),a("th",{className:"num"},o("colCacheTok")),a("th",{className:"num"},o("colOutTok")),a("th",{className:"num"},o("colCost")))),a("tbody",null,n.map(l=>a("tr",{key:l.id},fa(l,s,o),a("td",{className:"num"},String(l.calls)),a("td",{className:"num"},L(l.input)),a("td",{className:"num"},L(l.cacheRead+l.cacheWrite)),a("td",{className:"num"},L(l.output)),a("td",{className:"num"},W(Q(l,t.config),t.config)))))))}function fa(e,t,o){const n=typeof e.title=="string"?e.title.trim():"",s=String(e.id).slice(0,14)+"…",l=n.length>0?n:s,r=n.length>0?n+" · "+e.id:e.id;return a("td",{title:r},a("div",{className:"cm-sess-title"+(n.length===0?" cm-sess-id":"")},l),t&&n.length>0?a("div",{className:"cm-sess-id"},s):null)}const Ds={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function Ls(e){const{state:t,draft:o,setDraft:n,t:s}=e,l=t.config,r=o?.budget??l.budget,i=Number(l.exchangeRate),c=(t.budgetUsed??(r.period==="day"?Q(t.today,l):r.period==="all"?Q(t.total,l):Q(t.month,l)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(r.amount)||0),b=r.enabled&&u>0?Math.min(999,c/u*100):null,g=b===null?"ok":b>=100?"over":b>=80?"warn":"ok",f=(h,C)=>{o!==null&&n({...o,budget:{...o.budget??l.budget,[h]:C}})},m=r.period==="custom"?r.customStart+" → "+(r.customEnd??s("periodDay")):null,x=r.enabled&&b!==null?s("budgetStatus",{period:s(Ye[r.period]??"periodMonth"),amount:de(u,l),used:de(c,l),pct:b.toFixed(1)})+(g==="over"?s("overLimit"):g==="warn"?s("nearLimit"):""):null;return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},a("h3",{className:"cm-h"},s("budget")),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:r.enabled===!0,onChange:h=>f("enabled",h.target.checked)}),a("span",null,s("enableBudget")))),r.enabled?a(E,null,a("div",{className:"cm-budget-bar"},a("div",{className:"cm-budget-fill "+(g==="ok"?"":g),style:{width:(b===null?0:Math.min(100,b))+"%"}})),a("div",{className:"cm-budget-line"+(g==="over"?" over":"")+" cm-num"},x),a("div",{className:"cm-budget-controls"},a("div",{className:"cm-field"},a("label",null,s("budgetAmountLabel")),Ge({value:r.amount},h=>f("amount",h))),a("div",{className:"cm-field"},a("label",null,s("budgetPeriodLabel")),a("select",{className:"cm-input",value:r.period,onChange:h=>f("period",h.target.value)},a("option",{value:"day"},s("periodDay")),a("option",{value:"month"},s("periodMonth")),a("option",{value:"all"},s("periodAll")),a("option",{value:"custom"},s("periodCustomRange")))),r.period==="custom"?a(E,null,a("div",{className:"cm-field"},a("label",null,s("startDate")),a("input",{className:"cm-input",type:"date",value:r.customStart??"",onChange:h=>f("customStart",h.target.value===""?null:h.target.value)})),a("div",{className:"cm-field"},a("label",null,s("endDate")),a("input",{className:"cm-input",type:"date",value:r.customEnd??"",onChange:h=>f("customEnd",h.target.value===""?null:h.target.value)}))):null),m!==null?a("p",{className:"cm-hint"},s("rangeText",{range:m})):null):a("p",{className:"cm-note"},s("budgetDisabledNote")))}function Es(e){const{state:t,draft:o,setDraft:n,t:s}=e,l=t.config,r=(u,b)=>{o!==null&&n({...o,[u]:b})},i=o===null?l:{...l,...o},d=(()=>{if(i.peakEnabled!==!0)return s("peakOff");const u=Date.parse(i.peakEffectiveAt||""),b=Date.now();if(Number.isFinite(u)&&b<u)return s("peakNotEffective",{time:new Date(u).toLocaleString()});const g=i.peakWindows??[],f=ta(b,g,i.peakHolidays);return f===null?s("offPeakActive"):f.holiday===!0?s("holidayAllOffPeak"):f.weekend===!0?s("weekendAllOffPeak"):f.inPeak?s("peakActive"):s("offPeakActive")})(),c=(i.peakWindows?.length??0)>0?s("peakSummary",{windows:i.peakWindows.map(u=>u.start+":00-"+u.end+":00").join(H(i)==="zh"?"、":", "),time:i.peakEffectiveAt||s("unknown"),status:d}):s("noPeakWindows",{status:d});return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},a("h3",{className:"cm-h"},s("peakPanelTitle")),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:u=>r("peakEnabled",u.target.checked)}),a("span",null,s("peakEnabledLabel")))),a("div",{className:"cm-grid"},a("div",{className:"cm-field"},a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:u=>r("peakNotice",u.target.checked)}),a("span",null,s("peakNoticeLabel")))),a("div",{className:"cm-field"},a("label",null,s("peakStyleLabel")),a("select",{className:"cm-input",value:o?.peakStyle??"compact",onChange:u=>r("peakStyle",u.target.value)},a("option",{value:"progress"},H(o)==="en"?"Time progress":"时间进度条"),a("option",{value:"compact"},s("peakStyleCompact")),a("option",{value:"classic"},s("peakStyleClassic"))))),a("div",{className:"cm-grid"},a("div",{className:"cm-field"},a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:u=>r("peakAlertEnabled",u.target.checked)}),a("span",null,s("peakAlertLabel")))),a("div",{className:"cm-field"},a("label",null,s("peakAlertAheadLabel")),a("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:u=>{const b=Number(u.target.value);Number.isInteger(b)&&b>=1&&b<=30&&r("peakAlertAhead",b)}})),a("div",{className:"cm-field"},a("label",null,s("peakAlertTargetLabel")),a("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:u=>r("peakAlertTarget",u.target.value)},a("option",{value:"both"},s("peakAlertTargetBoth")),a("option",{value:"peak"},s("peakAlertTargetPeak")),a("option",{value:"offpeak"},s("peakAlertTargetOffPeak"))))),a("div",{className:"cm-grid"},a("div",{className:"cm-field"},a("label",null,s("peakAlertPositionLabel")),a("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:u=>r("peakAlertPosition",u.target.value)},a("option",{value:"corner"},s("peakAlertPositionCorner")),a("option",{value:"center"},s("peakAlertPositionCenter")))),a("div",{className:"cm-field"},a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:u=>{r("peakAlertWebNotify",u.target.checked),u.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),a("span",null,s("peakAlertWebNotifyLabel"))),a("p",{className:"cm-hint"},s("peakAlertWebNotifyHint")))),a("div",{className:"cm-field"},a("label",null,s("peakAlertPreviewLabel")),a("div",{className:"cm-row"},a("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},s("peakAlertPreviewPeak")),a("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},s("peakAlertPreviewOffPeak")))),a("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?mn(t,i,s):a("p",{className:"cm-hint"},s("peakNoticeHiddenHint"))),a("p",{className:"cm-hint"},c),a("div",{className:"cm-field"},a("label",null,s("peakHolidaysLabel")),a("input",{className:"cm-input",defaultValue:(i.peakHolidays??[]).join(", "),onBlur:u=>r("peakHolidays",u.target.value.split(/[,,\s]+/).filter(Boolean))})),a("p",{className:"cm-hint"},s("weekendRuleNote")))}function Ge(e,t){const o=e.value;return a("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",placeholder:e.placeholder,title:e.title,"aria-label":e.label,value:typeof o=="number"?String(o):"",onChange:n=>{const s=n.target.value;if(s===""){if(e.emptyMode==="clear"){t(null);return}if(e.emptyMode==="ignore")return;t(0);return}const l=Number(s);Number.isFinite(l)&&l>=0&&t(l)}})}function An({value:e,entry:t,path:o,emptyMode:n,placeholder:s,label:l,title:r,t:i,onCommit:d}){const c=yt(t,o),u=e==null?"":String(e)+(t.multiplier!==void 0||t.separateMultipliers?" × "+c:""),[b,g]=O(u),[f,m]=O(!1),x=fe(!1);V(()=>{x.current||g(u)},[u]);const h=()=>{if(!x.current)return;const C=b.trim().split(/\s*[×*xX]\s*/),N=/^[+]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;if(b.trim()===""){x.current=!1,m(!1),n==="clear"?d(null):g(u);return}if(C.length>2||!C.every(y=>N.test(y)&&Number.isFinite(Number(y)))||!Number.isFinite(Number(C[0])*(C.length===2?Number(C[1]):c))){m(!0);return}x.current=!1,m(!1),g(String(Number(C[0]))+(t.multiplier!==void 0||t.separateMultipliers||C.length===2?" × "+(C.length===2?Number(C[1]):c):"")),d(Number(C[0]),C.length===2?Number(C[1]):void 0)};return a("input",{className:"cm-input narrow",type:"text",value:b,placeholder:s,"aria-label":l,"aria-invalid":f,title:f?i("priceMultiplyInvalid"):[r,i(t.separateMultipliers?"priceMultiplySingle":"priceMultiplyAll"),e==null?"":"= "+Number((e*c).toPrecision(12))].filter(Boolean).join(" · "),onChange:C=>{x.current=!0,g(C.target.value),m(!1)},onBlur:h,onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),h()),C.key==="Escape"&&(C.stopPropagation(),x.current=!1,m(!1),g(u))}})}function Bt(e,t,o){o!==void 0&&(e.separateMultipliers?e.multipliers={...e.multipliers,[t]:o}:e.multiplier=o)}function ba(e,t,o,n,s,l,r,i=0){const d=n==="cacheWrite",c=t?.[n]??(n==="cacheMiss"?t?.input:n==="cacheHit"?t?.cachedInput:void 0)??null,u=l({cacheHit:"flatCached",cacheMiss:"flatInput",cacheWrite:"flatCacheWrite",output:"flatOutput"}[n]);return a("label",{className:"cm-price-cell"},a("span",{className:"cm-price-cell-label"},u),a(An,{entry:e,value:c,path:o+"."+n,t:l,emptyMode:d||!["base","cny"].includes(o)?"clear":"ignore",placeholder:d?String(t?.cacheHit??t?.cachedInput??t?.cacheMiss??t?.input??i):void 0,label:s+" · "+u,title:d?l("cacheWriteFallback"):void 0,onCommit:r}))}function ga(e,t,o){return a("div",{className:"cm-price-multiplier"},a("label",null,a("input",{type:"checkbox",checked:e.separateMultipliers===!0,onChange:n=>o(n.target.checked)}),t("priceMultiplySeparate")),a("span",{title:t(e.separateMultipliers?"priceMultiplySingle":"priceMultiplyAll")},t("priceMultiplyHint")))}function Is(e){const{modelId:t,entry:o,isDefault:n,draft:s,setDraft:l,t:r}=e,i=Ze(o),d=f=>{const m={...Ze(f)};if(Array.isArray(f.rateHistory)){const x=f.rateHistory.filter(h=>Date.parse(h.before)<=Date.now());x.length>0?m.rateHistory=x:delete m.rateHistory}return m},c=f=>{const m=n?{...s.prices,default:f}:{...s.prices,models:{...s.prices.models,[t]:f}};l({...s,prices:m})},u=(f,m,x,h)=>{const C=n?s.prices.default:s.prices.models[t],N=d(C??{cacheHit:0,cacheMiss:0,output:0}),y=f==="base"?N:{...N[f]??(x===null?{}:Qe(N))};x===null?delete y[m]:y[m]=Math.max(0,x),f!=="base"&&(Object.keys(y).length?N[f]=y:delete N[f]),Bt(N,f+"."+m,h),c(N)},b=()=>{const f={...s.prices.models};delete f[t],l({...s,prices:{...s.prices,models:f}})},g=(f,m)=>{const x=m==="base"?i:i[m]??null;return a("div",{className:"cm-price-row",key:m},a("span",null,f),...["cacheMiss","cacheHit","cacheWrite","output"].map(h=>a(E,{key:h},ba(i,x,m,h,f,r,(C,N)=>u(m,h,C,N),i.cacheHit))))};return a("div",{className:"cm-price-card"},a("div",{className:"cm-price-head"},a("span",{className:"cm-price-name"},t),a("span",{className:"cm-price-unit"},s.prices.currency??"USD"),a(E,null,i?.legacy===!0?a("span",{className:"cm-price-legacy"},r("legacyModel")):null,n?a("span",{className:"cm-price-legacy"},r("defaultFallback")):null,n?null:a("button",{className:"cm-btn small danger",onClick:b},r("remove")))),a("div",{className:"cm-price-row cm-price-columns"},a("span",null,""),a("span",null,r("flatInput")),a("span",null,r("flatCached")),a("span",null,r("flatCacheWrite")),a("span",null,r("flatOutput"))),g(r("tierBase"),"base"),g(r("tierOffPeak"),"offPeak"),g(r("tierPeak"),"peak"),ga(i,r,f=>c({...o,separateMultipliers:f,multipliers:{}})),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?a("p",{className:"cm-note"},r("datedPriceNote")):null)}const js={deepseek:"DeepSeek",stepfun:"StepFun",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"},Hs=e=>e==="zen"?"go":e,ut=e=>e.replace(/^zen:/i,"go:").replace(/^(deepseek(?:-official|-account)?):deepseek-(?:v4(?:\.1)?-)?flash(?:-vision-exp)?$/i,"$1:DeepSeek V4.1 Flash");function Pn(e,t,o,n){const s=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],l=c=>Number.isFinite(Number(c))&&Number(c)>0?Number(c):0,r=(c,u,b)=>{if(!b||typeof b!="object")return;const g=c[u]??(c[u]=Object.fromEntries([...s,"apiCost"].map(m=>[m,0])));for(const m of s)g[m]+=l(b[m]);for(const m of bt)Number.isFinite(b[m])&&(g[m]=(g[m]??0)+b[m]);const f=u.indexOf(":");g.apiCost+=l(b.apiCost??(et(f>0?u.slice(0,f):"deepseek",f>0?u.slice(f+1):u,t)==="plan"?0:b.cost))},i=c=>{if(!c||typeof c!="object")return{};if(c.byProviderModel&&Object.keys(c.byProviderModel).length)return c.byProviderModel;if(c.byModel&&Object.keys(c.byModel).length)return Object.fromEntries(Object.entries(c.byModel).map(([b,g])=>[b.includes(":")?b:"deepseek:"+b,g]));const u={};for(const b of Array.isArray(c.sessions)?c.sessions:[])if(!(!b||typeof b!="object"))if(b.byProviderModel&&Object.keys(b.byProviderModel).length)for(const[g,f]of Object.entries(b.byProviderModel))r(u,g,f);else r(u,(b.provider||"deepseek")+":"+(b.model||"unknown"),b);return Object.keys(u).length?u:s.some(b=>l(c[b])>0)?{"deepseek:legacy":c}:{}};return(c=>{const u={},b=g=>{for(const[f,m]of Object.entries(g??{}))r(u,f,m)};if(c==="today")b(i(e.today));else{const g=Date.parse((e.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const f of e.history??[]){const m=Date.parse(f.date+"T00:00:00Z");m<=g&&m>=g-76896e5&&b(i(f))}}return Object.entries(u).map(([g,f])=>{const m=g.indexOf(":"),x=(m>0?g.slice(0,m):"deepseek").toLowerCase(),h=m>0?g.slice(m+1):g,C=f.input+f.output+f.cacheRead+f.cacheWrite+f.reasoning,N=f.cacheRead+f.input;return{label:e.modelLabels?.[g]??(g==="deepseek:legacy"?o("modelStatsLegacy"):x==="deepseek"||x===""?h:Hs(x)+":"+h),key:g,...f,tokens:C,cls:et(x,h,t),hitRate:N>0?f.cacheRead/N:null,cacheUnreported:wo(f),blended:C>0&&f.cost>0?f.cost/C*1e6:null,perUsd:f.cost>0?C/f.cost:null}}).filter(g=>(g.tokens>0||g.cost>0)&&t.modelStatistics?.[g.key]?.[c==="today"?"today":"summary"]!==!1)})(n).sort((c,u)=>u.cost-c.cost||u.tokens-c.tokens)}function Qs(e){const{state:t,config:o,t:n,initialTab:s,draft:l,setDraft:r}=e,[i,d]=O(s==="history"?"history":"today"),[c,u]=O(!1),b=Pn(t,o,n,i),g=p=>(Math.max(0,Math.min(1,p))*100).toFixed(1)+"%",f=b.reduce((p,k)=>Math.max(p,k.cost),0),m=b.reduce((p,k)=>Math.max(p,k.tokens),0),x=b.reduce((p,k)=>Math.max(p,k.perUsd??0),0),h=(p,k)=>a("button",{className:"cm-mstats-tab"+(i===p?" active":""),onClick:()=>d(p)},k),C=p=>p.cls==="plan"?a("span",{className:"cm-plan-tag",title:n("billingClassLabel")+" · "+(ya(za(p.provider,o,p.model),n)||n("billingClassPlan"))},n("billingClassPlan")):null,N=p=>a("select",{className:"cm-input",title:n("billingClassLabel"),value:o.planBilling?.models?.[p.key]==="plan"&&o.planBilling?.modelPlans?.[p.key]?"plan:"+o.planBilling.modelPlans[p.key]:o.planBilling?.models?.[p.key]??"auto",disabled:l===null,onChange:k=>{const w={...l.planBilling?.models??{}},v={...l.planBilling?.modelPlans??{}},R=k.target.value;delete v[p.key],R.startsWith("plan:")?(w[p.key]="plan",v[p.key]=R.slice(5)):R==="auto"?delete w[p.key]:w[p.key]=R,r({...l,planBilling:{...l.planBilling,models:w,modelPlans:v}})}},a("option",{value:"auto"},n("billingClassAuto")),a("option",{value:"plan"},n("billingClassPlan")),a("option",{value:"api"},n("billingClassApi")),Ue.map(k=>a("option",{key:k,value:"plan:"+k},n("billingClassPlan")+" · "+ya(k,n)))),y=(p,k,w,v,R)=>a("div",{className:"cm-mstats-row"},R?a("div",{className:"cm-mstats-label"},a("span",{className:"cm-mstats-name",title:p},p),R):a("span",{className:"cm-mstats-name",title:p},p),a("div",{className:"cm-mstats-barbg"},a("div",{className:"cm-mstats-bar "+w,style:{width:g(k)}})),a("span",{className:"cm-mstats-val"},v));return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(c,()=>u(!c),n("modelStatsTitle"))),c?a("div",{className:"cm-collapse-body"},a("div",{className:"cm-mstats-tabs"},h("today",n("modelStatsToday")),h("history",n("modelStatsHistory"))),b.length===0?a("p",{className:"cm-note"},n("modelStatsEmpty")):a(E,null,a("div",{className:"cm-mstats-h"},n("modelStatsCostH")),b.map(p=>a(E,{key:"c:"+p.label},y(p.label,f>0?p.cost/f:0,"cost",W(p.cost,o),a(E,null,C(p),N(p),p.cacheUnreported?a("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null)))),a("div",{className:"cm-mstats-h"},n("modelStatsTokensH")),a("div",{className:"cm-mstats-legend"},a("span",null,a("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),n("modelStatsInput")),a("span",null,a("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),n("modelStatsCache")),a("span",null,a("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),n("modelStatsOutput"))),[...b].sort((p,k)=>k.tokens-p.tokens).map(p=>a("div",{className:"cm-mstats-row",key:"t:"+p.label},a("span",{className:"cm-mstats-name",title:p.label},p.label),a("div",{className:"cm-mstats-barbg"},a("div",{className:"cm-mstats-seg in",style:{width:g(m>0?p.input/m:0)}}),a("div",{className:"cm-mstats-seg cache",style:{width:g(m>0?(p.cacheRead+p.cacheWrite)/m:0)}}),a("div",{className:"cm-mstats-seg out",style:{width:g(m>0?(p.output+p.reasoning)/m:0)}})),a("span",{className:"cm-mstats-val"},L(p.tokens)))),a("div",{className:"cm-mstats-h"},n("modelStatsHitH")),[...b].sort((p,k)=>(k.hitRate??-1)-(p.hitRate??-1)).map(p=>a(E,{key:"h:"+p.label},y(p.label,p.hitRate??0,"hit",p.cacheUnreported?n("modelStatsHitUnreported"):p.hitRate===null?"—":(p.hitRate*100).toFixed(1)+"%",p.cacheUnreported?a("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null))),a("div",{className:"cm-mstats-h"},n("modelStatsValueH")),[...b].sort((p,k)=>(k.perUsd??-1)-(p.perUsd??-1)).map(p=>a(E,{key:"v:"+p.label},y(p.label,x>0?(p.perUsd??0)/x:0,"value",p.perUsd===null?"—":L(p.perUsd)+" tok/$"+(p.blended!==null?" · "+n("modelStatsBlended",{price:"$"+p.blended.toFixed(2)}):"")))),a("p",{className:"cm-mstats-note"},n("modelStatsNote")))):null)}function qs(e,t){return e==="fiveHour"?t==="en"?"5-hour":"5 小时":e==="weekly"?t==="en"?"This week":"本周":e==="monthly"?t==="en"?"This month":"本月":e==="daily"?t==="en"?"Today":"当日":e}function ya(e,t){if(e==="go")return"OpenCode Go / Go Plus";const o={codex:"Codex / ChatGPT","volcengine-agent":"Volcengine Agent Plan","tencent-coding":"Tencent Coding Plan","tencent-token":"Tencent Token Plan","baidu-coding":"Baidu Qianfan Coding Plan"};if(o[e])return o[e];const n=De.find(s=>s.id===e);return n!==void 0?t(n.labelKey):e}const Mn=["fiveHour","weekly","monthly","daily"];function Us(e,t){const o=new Map,n=s=>{const l=new Date(s),r=i=>String(i).padStart(2,"0");if(t==="monthly")return l.getFullYear()+"-"+r(l.getMonth()+1);if(t==="weekly"){const i=new Date(l.getFullYear(),l.getMonth(),l.getDate()-(l.getDay()+6)%7);return i.getFullYear()+"-"+r(i.getMonth()+1)+"-"+r(i.getDate())}return l.getFullYear()+"-"+r(l.getMonth()+1)+"-"+r(l.getDate())};for(const s of Object.values(e??{}))for(const l of s??[]){if(l===null||typeof l!="object"||!(l.tokens>0)&&!(l.cost>0))continue;const r=n(Number(l.t1)||Number(l.t0)),i=o.get(r)??{key:r,tokens:0,cost:0,pct:0,intervals:0};i.tokens+=Number(l.tokens)||0,i.cost+=Number(l.cost)||0,i.pct+=Number(l.pct)||0,i.intervals+=1,o.set(r,i)}return[...o.values()].map(s=>({...s,per1Tokens:s.pct>0?s.tokens/s.pct:null,fullTokens:s.pct>0?s.tokens/s.pct*100:null})).sort((s,l)=>s.key<l.key?-1:s.key>l.key?1:0)}function Fs(e){const{state:t,config:o,t:n}=e,[s,l]=O(!1),[r,i]=O("daily"),d=H(o),c=t?.planStats,u=c!=null&&typeof c.providers=="object"?c.providers:{},b=Object.keys(u).sort(),g=w=>W(Number(w)||0,o??t?.config),f=w=>w.method==="none"||w.per1Tokens===null?"—":L(w.per1Tokens)+" tok · "+g(w.per1Cost),m=w=>w.method==="none"||w.fullTokens===null?"—":L(w.fullTokens)+" tok · "+g(w.fullCost),x=w=>w.method==="sample"?n("planStatsMethodSample"):w.method==="live"?n("planStatsMethodLive"):n("planStatsMethodNone"),h=w=>{let v=x(w);return w.method==="sample"&&Number(w.sampleAt)>0&&(v=n("planStatsMethodSampleAt",{method:v,time:new Date(Number(w.sampleAt)).toLocaleString(d==="en"?"en-US":"zh-CN")})),(w.method==="sample"||w.method==="live")&&w.confidence==="low"&&(v+=" · "+n("planStatsConfidenceLow")),v},C=([w,v,R])=>a("tr",{key:v+":"+w},a("td",null,qs(w,d)),a("td",{className:"num"},Math.round(R.percent*10)/10+"%"),a("td",{className:"num"},L(R.localTokens)+" tok · "+g(R.localCost)),a("td",{className:"num"},f(R)),a("td",{className:"num"},m(R)),a("td",{className:"num cm-plan-reset"},R.resetsAt.length>0?n("planStatsResets",{time:new Date(R.resetsAt).toLocaleString(d==="en"?"en-US":"zh-CN")}):"—"),a("td",{className:"cm-plan-method"},h(R))),N=s?b.flatMap(w=>Object.entries(u[w]?.intervals??{})).map(([w,v])=>({winKey:w,list:v})):[],y=Us(Object.fromEntries(N.map(w=>[w.winKey,w.list])),r),p=y.reduce((w,v)=>Math.max(w,v.fullTokens??0),0),k=(w,v)=>a("button",{key:w,className:"cm-mstats-tab"+(r===w?" active":""),onClick:()=>i(w)},v);return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},ct(s,()=>l(!s),n("planStatsTitle"))),s?a("div",{className:"cm-collapse-body"},b.length===0?a("p",{className:"cm-empty"},n("planStatsEmpty")):a(E,null,b.map(w=>{const v=u[w]?.windows??{},R=[...Mn.filter(j=>v[j]!==void 0).map(j=>[j,w,v[j]]),...Object.keys(v).filter(j=>!Mn.includes(j)).map(j=>[j,w,v[j]])];return a("div",{key:w,className:"cm-plan-provider"},a("div",{className:"cm-plan-provider-name"},ya(w,n),a("span",{className:"cm-plan-updated"},(()=>{const j=Number(u[w]?.generatedAt)||Number(c?.generatedAt)||0;return j>0?new Date(j).toLocaleTimeString(d==="en"?"en-US":"zh-CN"):""})())),a("table",{className:"cm-table"},a("thead",null,a("tr",null,a("th",null,n("planStatsWindow")),a("th",{className:"num"},n("planStatsPercent")),a("th",null,n("planStatsLocal")),a("th",null,n("planStatsPer1")),a("th",null,n("planStatsFull")),a("th",null,""),a("th",null,""))),a("tbody",null,R.map(C))))}),a("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},n("planStatsCurveTitle")),a("div",{className:"cm-mstats-tabs"},k("daily",n("planStatsDaily")),k("weekly",n("planStatsWeekly")),k("monthly",n("planStatsMonthly"))),y.length===0?a("p",{className:"cm-note"},n("planStatsCurveEmpty")):a(E,null,[...y].reverse().map(w=>a("div",{className:"cm-mstats-row",key:w.key},a("span",{className:"cm-mstats-name"},w.key),a("div",{className:"cm-mstats-barbg"},a("div",{className:"cm-mstats-bar value",style:{width:(p>0?(w.fullTokens??0)/p*100:0).toFixed(1)+"%"}})),a(J,{label:n("planStatsBarTip",{date:w.key,full:w.fullTokens===null?"—":L(w.fullTokens),per1:w.per1Tokens===null?"—":L(w.per1Tokens),tokens:L(w.tokens),cost:g(w.cost),intervals:w.intervals}),side:"top",delayMs:200},a("span",{className:"cm-mstats-val"},w.fullTokens===null?"—":L(w.fullTokens)))))),a("p",{className:"cm-note"},n("planStatsNote")))):null)}function _s(e){const{provider:t,modelId:o,entry:n,draft:s,setDraft:l,t:r,api:i,lockedIds:d,releaseDisabled:c}=e,u=Array.isArray(d)&&d.includes(o),[b,g]=O(!1),[f,m]=O(""),x=async()=>{if(!(b||c)){g(!0),m("");try{await i.releasePriceLock(o)}catch(p){m(String(p.message??p))}finally{g(!1)}}},h=p=>{const k={...s.prices.providers??{}},w=k[t]??{};k[t]={...w,models:p},l({...s,prices:{...s.prices,providers:k}})},C=(p,k,w)=>{if(s===null)return;const v={...(s.prices.providers??{})[t]?.models??{}};v[o]={...v[o]??{},[p]:Math.max(0,k)},k===null&&delete v[o][p],p==="input"&&delete v[o].cacheMiss,p==="cachedInput"&&(delete v[o].cacheHit,delete v[o].cacheRead),Bt(v[o],"base."+({input:"cacheMiss",cachedInput:"cacheHit"}[p]??p),w),h(v)},N=(p,k,w)=>{if(s===null)return;const v={...(s.prices.providers??{})[t]?.models??{}},R=v[o]??{};v[o]={...R,cny:{...R.cny,[p]:Math.max(0,k)}},k===null&&delete v[o].cny[p],Bt(v[o],"cny."+p,w),h(v)},y=()=>{if(s===null)return;const p={...(s.prices.providers??{})[t]?.models??{}};delete p[o],h(p)};return a("div",{className:"cm-price-card"},a("div",{className:"cm-price-head"},a("span",{className:"cm-price-name"},o),a("span",{className:"cm-price-unit"},n.cny?"USD / CNY":"USD"),a(E,null,n?.unpriced===!0?a("span",{className:"cm-price-legacy"},r("catalogUnpriced")):null,u?a("span",{className:"cm-price-locked",title:r("priceLockHint")},r("priceLockBadge")):null,u&&typeof i?.releasePriceLock=="function"?a("button",{className:"cm-btn small",disabled:b||c,onClick:x},r("priceLockRelease")):null,a("button",{className:"cm-btn small danger",onClick:y},r("unmountBtn")))),f?a("p",{className:"cm-err",role:"alert"},f):null,n?.unpriced===!0?null:a(E,null,a("div",{className:"cm-price-row cm-price-columns"},a("span",null,""),a("span",null,r("flatInput")),a("span",null,r("flatCached")),a("span",null,r("flatCacheWrite")),a("span",null,r("flatOutput"))),a("div",{className:"cm-price-row"},a("span",null,"USD"),...["cacheMiss","cacheHit","cacheWrite","output"].map(p=>a(E,{key:p},ba(n,n,"base",p,"USD",r,(k,w)=>C({cacheMiss:"input",cacheHit:"cachedInput"}[p]??p,k,w))))),n?.cny?a("div",{className:"cm-price-row"},a("span",null,"CNY"),...["cacheMiss","cacheHit","cacheWrite","output"].map(p=>a(E,{key:p},ba(n,n.cny,"cny",p,"CNY",r,(k,w)=>N(p,k,w))))):null,ga(n,r,p=>h({...s.prices.providers[t].models,[o]:{...n,separateMultipliers:p,multipliers:{}}}))))}const ha=e=>[a("option",{key:"sidebar",value:"sidebar"},e("balanceSidebar")),a("option",{key:"settings",value:"settings"},e("balanceSettings")),a("option",{key:"both",value:"both"},e("balanceBoth")),a("option",{key:"off",value:"off"},e("off"))],ka=e=>e!=null?a("div",{className:"cm-msg "+e.kind},e.text):null;function Ws(e){const{state:t,api:o,t:n,draft:s,setDraft:l}=e,[r,i,d]=dt(n,()=>o.refreshBalance()),c=t.balance,u=t.config,b=t.reconcile,g=(s?.balance??u.balance??{}).reconcile!==!1,f=h=>{s===null||typeof l!="function"||l({...s,balance:{...s.balance??u.balance??{},reconcile:h.target.checked}})},m=h=>je(h,u,c?.currency),x=c.status==="ok"?a("div",{className:"cm-bal-line"},a("span",null,n("balanceLine",{total:m(c.totalBalance),granted:m(c.grantedBalance),toppedUp:m(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?a("div",{className:"cm-bal-line err"},n("balanceQueryFailedHint",{message:c.message||n("unknownError")})):a("div",{className:"cm-bal-line"},n("balanceNotQueried"));return a("div",{className:"cm-budget"},a("div",{className:"cm-budget-head"},a("h3",{className:"cm-h"},n("accountBalance")),a("button",{className:"cm-btn small",onClick:d,disabled:r},n(r?"refreshing":"refreshBalance"))),x,a("label",null,n("balanceApiKey")),a(tt,{target:"balance",configured:c.keyConfigured,source:c.keySource,t:n,api:o,placeholder:"sk-…"}),a("p",{className:"cm-hint"},n("balanceKeyHint")),b!==void 0&&b.ok===!1?a("div",{className:"cm-bal-line warn"},"⚠ "+b.message):null,a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:g,onChange:f}),n("reconcileLabel")),ka(i))}function Ot(e){const t=fe(null);V(()=>{e.targeted&&(t.current?.scrollIntoView({block:"start"}),t.current?.focus({preventScroll:!0}))},[e.targeted]);const{name:o,enabled:n,saved:s,busy:l,open:r,statusNode:i,configNode:d,errorMsg:c,onToggle:u,onRefresh:b,onLogin:g,loginRequired:f,onRemove:m,onToggleOpen:x,t:h}=e,C=d!=null,N=f?g:b,y=h(l===!0?f?"loggingIn":"refreshing":f?"loginCodingPlan":"refresh");return a("div",{ref:t,"data-quota-plan":e.planId,tabIndex:e.targeted?-1:void 0,className:"cm-budget cm-quota-card"},a("div",{className:"cm-budget-head"},a("label",{className:"cm-check"},a("input",{type:"checkbox","aria-label":h("enable")+": "+o,checked:n===!0,onChange:p=>u(p.target.checked)})),a("div",{className:"cm-quota-name"},C?ct(r===!0,x,o):a("h3",{className:"cm-h"},o)),m?a("button",{className:"cm-btn small",onClick:m},h("quotaRemove")):null,a("button",{className:"cm-btn small",onClick:N,disabled:l===!0||n!==!0||s?.enabled!==!0||s.display==="off"&&s.showInComposer!==!0,title:n!==!0?h("quotaEnableFirst"):s?.enabled!==!0||s.display==="off"&&s.showInComposer!==!0?h("quotaRefreshReady"):h(f?"loginCodingPlan":"refresh")},y)),i,C&&r===!0?a("div",{className:"cm-collapse-body"},d):null,c!=null?a("div",{className:"cm-msg "+c.kind},c.text):null)}function dt(e,t){const[o,n]=O(!1),[s,l]=O(null),r=fe(!1);return[o,s,async()=>{if(!r.current){r.current=!0,n(!0),l(null);try{const d=await t();l({kind:d.ok?"ok":"err",text:d.message})}catch(d){l({kind:"err",text:e("syncFailed",{message:d?.message??String(d)})})}finally{r.current=!1,n(!1)}}}]}const Gs=e=>{const t=e.filter(n=>n.enabled===!0),o=e.filter(n=>n.enabled!==!0);return[...t,...o]},xa=(e,t,o,n,s,l=t)=>{if(typeof o?.percent!="number")return a("div",{key:l,className:"cm-go-row"+(s?" main":"")},a("span",{className:"cm-go-label"},t),a("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const r=Math.max(0,Math.min(100,Number(o.percent)||0)),i=we(r,n),d=typeof o.resetsAt=="string"&&o.resetsAt.length>0?e("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return a("div",{key:l,className:"cm-go-row"+(s?" main":"")},a("span",{className:"cm-go-label"},t),a("div",{className:"cm-go-bar"},a("div",{className:"cm-go-fill",style:{width:i.width+"%"}})),a("span",{className:"cm-go-num"},i.label===null?"—":e("goQuotaPercent",{percent:String(Math.round(i.label))})),d?a("span",{className:"cm-go-reset"},d):null)};function Ks(e){const{state:t,api:o,t:n,entry:s,index:l,canRemove:r,onPatch:i,onRemove:d}=e,c=s.adapter==="aliyun",u=s.adapter==="tokenrhythm",b=c||u,[g,f]=O(!1),m=()=>({headers:JSON.stringify(s.request?.headers??{},null,2),extract:JSON.stringify(s.extract??{},null,2),body:typeof s.request?.body=="string"?s.request.body:JSON.stringify(s.request?.body,null,2)??""}),[x,h]=O(m),[C,N]=O(()=>(s.allowedHosts??[]).join(", ")),[y,p]=O({}),k=fe(!1),w=t.config,R=(Array.isArray(t.customBalances)?t.customBalances:[]).find(D=>D.index===l)??null,j=s.enabled===!0,A=()=>{f(D=>!D)};V(()=>{g&&!k.current&&(h(m()),N((s.allowedHosts??[]).join(", ")),p({})),k.current=g},[g]);const B=(D,ne)=>i({[D]:ne}),F=(D,ne)=>i({request:{...s.request??{},[D]:ne}}),G=c?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:u?["TOKENRHYTHM_COOKIE"]:[...new Set(Object.values(s.request?.headers??{}).flatMap(D=>typeof D=="string"?[...D.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(ne=>ne[1]):[]))],ae=(D,ne)=>{h(oe=>({...oe,[D]:ne}));try{const oe=D==="body",ge=oe&&!ne.trim()?void 0:JSON.parse(ne);if(!oe&&(ge===null||typeof ge!="object"||Array.isArray(ge)))throw new Error("invalid");if(D==="headers"&&Object.values(ge).some(P=>typeof P!="string"))throw new Error("invalid");p(P=>({...P,[D]:""})),D==="extract"?B(D,ge):F(D,oe?ge===void 0?void 0:ne:ge)}catch{p(oe=>({...oe,[D]:n("customBalanceInvalidJson")}))}},K=(D,ne,oe,ge)=>!b&&a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,n(ne)),ge&&a("span",{className:"cm-hint"},n(ge)),a("textarea",{className:"cm-input",rows:oe,value:x[D],onChange:P=>ae(D,P.target.value)}),y[D]?a("span",{className:"cm-hint err"},y[D]):null),$=D=>{N(D);const ne=D.split(/[\s,;]+/).map(oe=>oe.trim()).filter(oe=>oe.length>0);B("allowedHosts",ne)},[M,T,le]=dt(n,()=>(w.customBalances??[])[l]?.enabled!==!0?Promise.resolve({ok:!1,message:n("quotaEnableFirst")}):o.refreshCustomBalance(l)),Le=R!==null&&R.status==="ok"?a(E,null,w.balance?.showProgressBar===!0&&!u?a("div",{className:"cm-budget",style:{marginTop:"8px"}},a(Jt,{segments:$t(t,w,R,s),direction:ie(w,"balance")}),a("div",{className:"cm-bal-line"},ea(R,w,n,t,s))):a("div",{className:"cm-bal-line"},n("customBalanceRemaining",{amount:Fe(R.remaining,w,R,s)}))):R!==null&&R.status==="error"?a("div",{className:"cm-bal-line err"},R.message||n("unknownError")):a("div",{className:"cm-bal-line"},R?.message||n("balanceNotQueried")),pt=a(E,null,a("p",{className:"cm-note"},n(u?"tokenRhythmBalanceNote":c?"aliyunBalanceNote":"customBalanceConfigNote")),!u&&a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:s.convertToDisplayCurrency===!0,disabled:at(w,R,s)!=="USD",onChange:D=>B("convertToDisplayCurrency",D.target.checked)}),n("customBalanceConvert")),!u&&a("p",{className:"cm-note"},n("customBalanceConvertNote")),a("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([D,ne])=>a("div",{key:D,className:"cm-field"},a("label",null,n(ne)),a("input",{className:"cm-input",value:s[D]??"",onChange:oe=>B(D,oe.target.value)}))),!b&&a("div",{className:"cm-field"},a("label",null,n("customBalanceUnitLabel")),a("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(s.unit)?s.unit:"USD",onChange:D=>B("unit",D.target.value)},a("option",{value:"USD"},"USD ($)"),a("option",{value:"CNY"},"CNY (¥)"),a("option",{value:"EUR"},"EUR (€)"),a("option",{value:"CREDITS"},"CREDITS"))),a("div",{className:"cm-field"},a("label",null,n("customBalanceDisplayLabel")),a("select",{className:"cm-input",value:s.display??"both",onChange:D=>B("display",D.target.value)},...ha(n))),a("div",{className:"cm-field"},a("label",null,n("customBalanceRefreshInterval")),Ge({value:s.refreshMinutes??15},D=>B("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D)))))),!b&&a("div",{className:"cm-field"},a("label",null,n("customBalanceMethod")),a("select",{className:"cm-input",value:s.request?.method??"GET",onChange:D=>F("method",D.target.value)},a("option",{value:"GET"},"GET"),a("option",{value:"POST"},"POST"))),!b&&a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,n("customBalanceUrl")),a("input",{className:"cm-input",value:s.request?.url??"",placeholder:"/plugins/dsh-workbuddy-connect/status",onChange:D=>F("url",D.target.value)}),a("span",{className:"cm-hint"},n("customBalanceUrlHint"))),K("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((s.request?.method??"GET").toUpperCase())&&K("body","customBalanceBody",5,"customBalanceBodyNote"),a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,u?"Token Rhythm Cookie":n("customBalanceCredentialsTitle")),G.length>0?a(E,null,!b&&a("span",{className:"cm-hint"},n("customBalanceCredentialsHint")),G.map(D=>a(tt,{key:"cb-var-"+D,target:"customVar:"+D,configured:(t.customVarStatus?.[D]?.configured??!1)===!0,source:t.customVarStatus?.[D]?.source??"",t:n,api:o,placeholder:u?"tr_session=…":"{{"+D+"}}"}))):a("span",{className:"cm-hint"},n("customBalanceNoPlaceholders"))),!b&&a("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},a("label",null,n("customBalanceAllowedHosts")),a("input",{className:"cm-input",value:C,placeholder:"api.example.com, relay.example.org",onChange:D=>$(D.target.value)}),a("span",{className:"cm-hint"},n("customBalanceAllowedHostsHint"))),!b&&a("label",{className:"cm-check",style:{gridColumn:"1 / -1"}},a("input",{type:"checkbox",checked:s.allowInsecureHttp===!0,onChange:D=>B("allowInsecureHttp",D.target.checked)}),n("customBalanceHttp")),K("extract","customBalanceExtract",8)));return a(Ot,{name:`#${l+1} · `+(Xt(s,H(w))||n("customBalanceTitle")),enabled:j,saved:JSON.stringify(s)===JSON.stringify(w.customBalances?.[l])?w.customBalances[l]:null,busy:M,open:g,statusNode:Le,configNode:pt,errorMsg:T,onToggle:D=>B("enabled",D),onRefresh:le,onRemove:r?d:null,onToggleOpen:A,t:n})}function zs({config:e,draft:t,setDraft:o,t:n,api:s}){const l=t?.goQuota??e.goQuota,r=(i,d)=>{t&&o({...t,goQuota:{...l,[i]:d}})};return a(E,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([i,d])=>a("div",{key:i,className:"cm-field"},a("label",null,n(d)),a("select",{className:"cm-input",value:i==="display"?ia(l,(t??e).quotaStrip,"go"):l[i],onChange:c=>i==="display"?t&&o({...t,goQuota:{...l,...ca(c.target.value)}}):r(i,c.target.value)},i==="display"?ua(n):["rolling","weekly","monthly"].map((c,u)=>a("option",{key:c,value:c},n(["goWindowRolling","goWindowWeekly","goWindowMonthly"][u])))))),a("div",{className:"cm-field"},a("label",null,n("goQuotaRefreshIntervalLabel")),Ge({value:l.refreshMinutes},i=>r("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(i)))))),a("label",null,n("goQuotaKeyLabel")),a(tt,{target:"goQuota",configured:e.goQuota?.keyConfigured===!0,source:e.goQuota?.keySource,t:n,api:s,placeholder:"sk-…"}))}function Ys(e){const{state:t,api:o,t:n,draft:s,setDraft:l}=e,[r,i]=O(!1),d=t.goQuota,c=t.config,u=s?.goQuota?.enabled??c.goQuota?.enabled??!0,b=(p,k)=>{s!==null&&l({...s,goQuota:{...s.goQuota??c.goQuota,[p]:k}})},[g,f,m]=dt(n,()=>o.refreshGoQuota()),x=c.goQuota?.main==="weekly"||c.goQuota?.main==="monthly"?c.goQuota.main:"rolling",h=[x,...["rolling","weekly","monthly"].filter(p=>p!==x)],C=p=>p==="rolling"?"goWindowRolling":p==="weekly"?"goWindowWeekly":"goWindowMonthly",N=p=>p==="rolling"?d.rolling:p==="weekly"?d.weekly:d.monthly,y=u===!1?a("p",{className:"cm-note"},n("goQuotaDisabledNote")):d.status==="ok"?a("div",{className:"cm-go-list"},h.map(p=>xa(n,n(C(p)),N(p),ie(c,"go"),p===x)),a("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:d.fetchedAt>0?new Date(d.fetchedAt).toLocaleTimeString():"—"}))):d.status==="error"?a("div",{className:"cm-bal-line err"},d.message||n("unknownError")):d.status==="off"&&d.message?a("p",{className:"cm-note"},d.message):a("div",{className:"cm-bal-line"},n("goQuotaNotQueried"));return a(Ot,{name:n("goQuotaTitle"),enabled:u,saved:c.goQuota,busy:g,open:r,statusNode:y,errorMsg:f,configNode:a(zs,{config:c,draft:s,setDraft:l,t:n,api:o}),onToggleOpen:()=>i(p=>!p),onToggle:p=>b("enabled",p),onRefresh:m,t:n})}const Vs=(e,t)=>{if(typeof e?.keyVar=="string"&&e.keyVar.length>0)return e.keyVar;const n="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(e?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(t??{}).find(s=>s===n||s.startsWith(n+"_"))??n};function $s(e){const{state:t,api:o,t:n,draft:s,setDraft:l,index:r}=e,i=t.config,c=(s??i).gatewayQuotas?.sources??[],u=c[r]??{},g=(Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[]).find(A=>A.id===u.id)??{id:u.id,status:"off",accounts:[],unsupportedProviders:[]},f=Vs(u,t.customVarStatus),[m,x]=O(!1),[h,C,N]=dt(n,()=>o.refreshGatewayQuota(u.id)),y=A=>{s!==null&&l({...s,gatewayQuotas:{...s.gatewayQuotas??i.gatewayQuotas??{},sources:A}})},p=A=>y(c.map((B,F)=>F===r?{...B,...A}:B)),k=(A,B,F)=>a("div",{className:"cm-field"},a("label",null,A),a("input",{className:"cm-input","aria-label":A,value:B??"",onChange:F})),w=(A,B)=>{const F=lt(A?.label||A?.id||n("gatewaySourceUnknown"),A,ie(i,"plan"),n);return a(E,{key:A?.id||B},F.row,A?.resetsAt?a("div",{className:"cm-note"},st(A,n)):null)},v=(A,B)=>a("div",{key:A.id||B,className:"cm-mm-row wide"},a("span",{className:"cm-bbox-label"},A.label||"package"),a("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),a("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),R=A=>A==null?null:a(E,null,a("div",{className:"cm-mm-row wide"},a("span",{className:"cm-bbox-label"},A.unit||"credits"),a("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),a("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),(A.packages??[]).map(v)),j=(A,B)=>a("div",{key:A.id||B,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},a("div",{className:"cm-budget-head"},a("strong",null,(La[A.provider]??A.provider??n("gatewaySourceUnknown"))+" · "+(A.label||n("gatewaySourceUnknown"))),a("span",{className:"cm-hint"},A.status)),A.plan?a("div",{className:"cm-note"},A.plan):null,A.windows.length>0?a("div",{className:"cm-go-list"},A.windows.map(w)):null,R(A.credits),A.message?a("div",{className:"cm-note"},A.message):null);return a(Ot,{name:u.label||u.id||n("gatewayQuotaTitle"),enabled:u.enabled===!0,saved:i.gatewayQuotas?.sources?.find(A=>A.id===u.id),busy:h,open:m,errorMsg:C,statusNode:a("div",{className:"cm-note"},n("gatewaySourceStatus")+": "+(g.status??n("gatewaySourceUnknown"))+(g.serverVersion?" · "+g.serverVersion:"")+(g.fetchedAt>0?" · "+n("gatewaySourceFetchedAt",{time:new Date(g.fetchedAt).toLocaleTimeString()}):"")+(g.message?" · "+g.message:"")),configNode:a(E,null,a("div",{className:"cm-grid"},k(n("gatewaySourceLabel"),u.label,A=>p({label:A.target.value})),k(n("gatewaySourceBaseURL"),u.baseURL,A=>p({baseURL:A.target.value})),a("div",{className:"cm-field"},a("label",null,n("gatewaySourceDisplay")),a("select",{className:"cm-input",value:u.display??"both",onChange:A=>p({display:A.target.value})},...ha(n))),a("div",{className:"cm-field"},a("label",null,n("gatewaySourceRefreshInterval")),Ge({value:u.refreshMinutes??15},A=>p({refreshMinutes:Math.min(1440,Math.max(1,Math.floor(A)))}))),k(n("gatewaySourceAllowlist"),(u.allowedHosts??[]).join(", "),A=>p({allowedHosts:A.target.value.split(/[\s,;]+/).filter(Boolean)})),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:u.allowInsecureHttp===!0,onChange:A=>p({allowInsecureHttp:A.target.checked})}),a("span",null,n("customBalanceHttp"))),a("label",{className:"cm-check"},a("input",{type:"checkbox",checked:u.antigravityOnlyGemini===!0,onChange:A=>p({antigravityOnlyGemini:A.target.checked})}),a("span",null,n("gatewayOnlyGemini")))),f?a("div",{className:"cm-field"},a("label",null,n("gatewaySourceCredential")),a(tt,{target:"customVar:"+f,configured:t.customVarStatus?.[f]?.configured===!0,source:t.customVarStatus?.[f]?.source??"",t:n,api:o,placeholder:f})):null,g.unsupportedProviders.length>0?a("div",{className:"cm-note"},n("gatewaySourceUnsupported")+": "+g.unsupportedProviders.join(", ")):null,g.accounts.length>0?g.accounts.map(j):a("div",{className:"cm-bal-line"},n("gatewaySourceNoAccounts"))),onToggle:A=>p({enabled:A}),onRefresh:N,onRemove:()=>y(c.filter((A,B)=>B!==r)),onToggleOpen:()=>x(A=>!A),t:n})}const De=[{id:"opendesign",labelKey:"codingPlanOpendesign"},{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:"clinepass",labelKey:"codingPlanClinepass"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"},{id:"workbuddy",labelKey:"wbT"},{id:"factory",labelKey:"codingPlanFactory"}];let Tn;function Js(){return Tn??=ve.async("./client.plan-settings.js").then(e=>e.mount({useQuotaRefresh:dt,miniMaxWindowsOf:na,MiniMaxPlanCard:oa,barDirectionOf:ie,quotaWindowRow:xa,codingPlanWindowLabel:We,codingPlanWindowEntries:Mt,numInput:Ge,CredentialField:tt,QuotaCard:Ot,resolveLocale:H,formatMoneyUsd:W,quotaPlacementValue:ia,quotaPlacementPatch:ca,quotaPlacementOptions:ua})).catch(e=>{throw Tn=null,e})}function Zs(e){return a(be,{...e,load:Js})}function Xs(e){const{state:t,api:o,t:n,draft:s,setDraft:l}=e,r=t.config,i=s??r,d=i.codingPlans??{},c=i.gatewayQuotas?.sources??[],u=s?.customBalances??r.customBalances??[],b=y=>{s!==null&&l({...s,customBalances:y,...y.length===0?{customBalance:{...r.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},g=fe({next:0,keys:[]}).current;for(;g.keys.length<u.length;)g.keys.push(g.next++);g.keys.length=u.length;const f=y=>{g.keys.splice(y,1),b(u.filter((p,k)=>k!==y))},m=(y,p)=>b(u.map((k,w)=>w===y?{...k,...p}:k)),x=(y="custom")=>{if(!(u.length>=8)){if(y==="workbuddy2api"){b([...u,{enabled:!1,label:"WorkBuddy2API 积分",labelEn:"WorkBuddy2API credits",display:"both",unit:"CREDITS",refreshMinutes:15,request:{url:"http://127.0.0.1:8790/api/credits/expiry?package_limit=1",method:"GET",headers:{"X-Admin-Token":"{{WORKBUDDY2API_ADMIN_TOKEN}}"}},extract:{remaining:"summary.available_remaining"},allowedHosts:["127.0.0.1:8790"],allowInsecureHttp:!1}]);return}b([...u,{...y!=="custom"?{adapter:y}:{},enabled:!1,label:y==="tokenrhythm"?"Token Rhythm":y==="aliyun"?"千问 / 阿里云":"",labelEn:y==="tokenrhythm"?"Token Rhythm":y==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:y!=="custom"?"CNY":"USD",refreshMinutes:15,request:{url:y==="tokenrhythm"?"https://tokenrhythm.studio/api/wallet/summary":y==="aliyun"?"https://business.aliyuncs.com/":"",method:y==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])}},h=()=>{c.length>=4||s===null||l({...s,gatewayQuotas:{...s.gatewayQuotas??r.gatewayQuotas??{},sources:[...c,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:Ut,allowedHosts:[],allowInsecureHttp:!1}]}})},C=[...c.map((y,p)=>({kind:"gateway",key:"gw-"+(y.id??p),index:p,enabled:y.enabled===!0})),{kind:"go",key:"go",enabled:i.goQuota?.enabled!==!1},...De.map(y=>({kind:"plan",key:"plan-"+y.id,planId:y.id,labelKey:y.labelKey,enabled:d[y.id]?.enabled===!0})),...u.map((y,p)=>({kind:"custom",key:"cb-"+g.keys[p],index:p,enabled:y.enabled===!0}))],N=y=>y.kind==="plan"?a(Zs,{key:y.key,planId:y.planId,labelKey:y.labelKey,targeted:y.planId===e.targetPlan,state:t,api:o,t:n,draft:s,setDraft:l}):y.kind==="go"?a(Ys,{key:y.key,state:t,api:o,t:n,draft:s,setDraft:l}):y.kind==="gateway"?a($s,{key:y.key,index:y.index,state:t,api:o,t:n,draft:s,setDraft:l}):a(Ks,{key:y.key,state:t,api:o,t:n,entry:u[y.index],index:y.index,canRemove:!0,onPatch:p=>m(y.index,p),onRemove:()=>f(y.index)});return a("div",null,a("p",{className:"cm-note"},n("quotaSectionNote")),a("div",{className:"cm-quota-list"},Gs(C).map(N)),a("div",{className:"cm-buttons"},a("button",{className:"cm-btn small",onClick:h,disabled:c.length>=4},n("gatewaySourceAdd")),a("button",{className:"cm-btn small",onClick:()=>x(),disabled:u.length>=8},n("customBalanceAdd")),a("button",{className:"cm-btn small",onClick:()=>x("aliyun"),disabled:u.length>=8},n("aliyunBalanceAdd")),a("button",{className:"cm-btn small",onClick:()=>x("tokenrhythm"),disabled:u.length>=8},n("tokenRhythmBalanceAdd")),a("button",{className:"cm-btn small",onClick:()=>x("workbuddy2api"),disabled:u.length>=8},n("workBuddyBalanceAdd")),a("p",{className:"cm-note"},n("workBuddyBalanceNote"))))}const el=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Rn=e=>(e.input??0)+(e.output??0)+(e.cacheRead??0)+(e.cacheWrite??0);function Dt(e){const t=e.useCost?e.useCost(p=>p):void 0,o=e.state??t?.state;if(!o)return null;const n=o.config,s=H(n),l=e.t??z(s),r=Array.isArray(o.history)?o.history:[];if(r.length===0)return a("div",null,a("h3",{className:"cm-h"},l("usageTitle")),a("p",{className:"cm-empty"},l("usageEmpty")));const i=o.meta?.dayKey??"",d=new Map(r.map(p=>[p.date,p])),c=p=>{const k=w=>String(w).padStart(2,"0");return p.getFullYear()+"-"+k(p.getMonth()+1)+"-"+k(p.getDate())},u=new Date;u.setHours(0,0,0,0);const b=new Date(u);b.setDate(b.getDate()+(6-(u.getDay()+6)%7));const g=26,f=[],m=[];let x=-1;for(let p=g-1;p>=0;p-=1){for(let w=0;w<7;w+=1){const v=new Date(b);v.setDate(v.getDate()-(p*7+(6-w)));const R=d.get(c(v));f.push(R!==void 0?{day:R,tokens:Rn(R)}:{day:{date:c(v)},tokens:0})}const k=new Date(b);k.setDate(k.getDate()-(p*7+6)),m.push(k.getMonth()!==x?s==="en"?el[k.getMonth()]:String(k.getMonth()+1)+"月":""),x=k.getMonth()}const h=Math.max(...f.map(p=>p.tokens),1),C=p=>{const k=p/h;return k<.25?1:k<.5?2:k<.75?3:4},N=p=>{const{day:k,tokens:w}=p,v="cm-ug-cell"+(w>0?" l"+C(w):"")+(k.date===i?" today":""),R=l("usageDay",{date:k.date,tokens:L(w),input:L(k.input??0),cache:L((k.cacheRead??0)+(k.cacheWrite??0)),output:L(k.output??0),calls:k.calls??0,cost:W(Q(k,n),n)});return a(J,{key:k.date,label:R,side:"top",delayMs:200},a("div",{className:v}))},y=o.total;return a("div",{className:"cm-ug"},a("h3",{className:"cm-h"},l("usageTitle")),a("div",{className:"cm-ug-total"},l("usageTotal",{tokens:L(Rn(y)),input:L(y.input??0),cache:L((y.cacheRead??0)+(y.cacheWrite??0)),output:L(y.output??0),calls:y.calls??0})),a("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+g+",1fr)"}},f.map(N)),a("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+g+",1fr)"}},m.map((p,k)=>a("span",{key:"m"+String(k),className:"cm-ug-monthc"},p))))}function Bn(e){return e.ready?a(be,{...e,load:e.api.loadCodex,quiet:e.view==="prompt"}):null}function tl(e){const t=e.useCost?.(n=>n),o=t?.state;return a(Bn,{...e,state:o,view:"prompt",ready:o?.codexCompat?.enabled===!0&&o?.codexCompat?.promptDue,locale:t?.locale})}const al=!1;function nl(e){const t=e.useCost?.(o=>o);return a(be,{state:t?.state,snapshot:t,api:e.api,load:e.api.loadSettingsOverview,helpers:{makeT:z,Card:it,BillingAccuracyNote:Cn,displayCostOf:Q,quotaWindowRow:xa,codingPlanWindowLabel:We,formatBalanceMoney:je,formatCustomBalanceMoney:Fe,CODING_PLAN_ROWS:De,UsagePanel:Dt,TodaySessions:vn,BudgetBoxContent:Tt,useCodexQuota:Pt,codingPlanWindowEntries:Mt}})}function On(e){const t=e.useCost?e.useCost(P=>P):void 0,o=e.api,n=t?.state??null,[s,l]=O(null),[r,i]=O(null),[d,c]=O(!1),[u,b]=O(!1),[g,f]=O(!1),[m,x]=O(!1),[h,C]=O("models"),[N,y]=O("overview"),p=n?.codexCompat?.installed===!0&&n?.codexCompat?.enabled===!0,k=N==="export"?"statistics":N==="codex"&&!p?"overview":N;V(()=>{p||y(P=>P==="codex"?"overview":P)},[p]);const[w,v]=O(null),[R,j]=O({status:"idle",at:0,error:null}),A=Ae.useRef(null),B=Ae.useRef(null),F=Ae.useRef(null),G=Ae.useRef(Promise.resolve()),ae=Ae.useRef(0),K=Ae.useRef(null);V(()=>()=>{K.current?.()},[]),V(()=>{if(n!==null){const P=JSON.stringify(n.config);l(_=>{const ye=_!==null&&JSON.stringify(_)!==A.current;return ye||(B.current=n.config,F.current=n.config),ye?{..._,activeLocale:n.config.activeLocale}:JSON.parse(P)}),A.current=P}},[n]),V(()=>{s!==null&&F.current===null&&B.current!==null&&(F.current=B.current)},[s]),V(()=>{const P=++ae.current;if(s===null||o===void 0)return;const _=JSON.stringify(s);if(_===A.current){K.current=null;return}j(ce=>ce.status==="saving"?ce:{...ce,status:"saving"});const ye=()=>{G.current=G.current.catch(()=>{}).then(async()=>{if(P!==ae.current)return;const ce={},pe=F.current??B.current;if(pe!==null&&typeof pe=="object")for(const re of Object.keys(s))re==="activeLocale"||s[re]===pe[re]||JSON.stringify(s[re])!==JSON.stringify(pe[re])&&(ce[re]=s[re]);if(Object.keys(ce).length===0){A.current=_,j({status:"saved",at:Date.now(),error:null});return}try{await o.updateConfig(ce),A.current=_,pe!==null&&typeof pe=="object"&&(F.current={...pe,...ce}),P===ae.current&&j({status:"saved",at:Date.now(),error:null})}catch(re){P===ae.current&&j({status:"error",at:0,error:re?.message??String(re)})}})};K.current=ye;const xe=setTimeout(ye,120);return()=>{clearTimeout(xe)}},[s,o]),V(()=>{n!==null&&t?.status==="error"&&t.error&&i({kind:"err",text:M("ledgerReadFailed",{message:t.error})})},[t?.status,t?.error]);const $=H({...s??n?.config,activeLocale:t?.locale}),M=z($);if(t===void 0||n===null)return a("div",{className:"cm-section"},a("p",{className:"cm-empty"},t?.status==="loading"?M("readingLedger"):M("ledgerUnavailable")),t?.error&&a("p",{className:"cm-err",role:"alert"},M("ledgerReadFailed",{message:t.error})),a("button",{className:"cm-btn",disabled:t?.status==="loading"||!o?.reload,onClick:o?.reload},M("refresh")));const T=n.config,le=async()=>{if(!m){x(!0),i(null);try{const P=await o.fetchPrices();if(i({kind:P.ok?"ok":"err",text:P.message}),P.ok&&P.state&&typeof P.state.config=="object"){const _=JSON.stringify(P.state.config);l(JSON.parse(_)),A.current=_}}catch(P){i({kind:"err",text:M("syncFailed",{message:P?.message??String(P)})})}finally{x(!1),c(!1)}}},Le=async()=>{if(!m){x(!0);try{await o.resetHistory(),i({kind:"ok",text:M("historyCleared")})}catch(P){i({kind:"err",text:M("clearFailed",{message:P?.message??String(P)})})}finally{x(!1),b(!1)}}},pt=async()=>{if(!m){x(!0),i(null);try{const P=await o.importLegacyHistory();i({kind:"ok",text:P.message})}catch(P){i({kind:"err",text:M("legacyImportFailed",{message:P?.message??String(P)})})}finally{x(!1),f(!1)}}},D=(P,_)=>{s!==null&&l({...s,[P]:_})},ne=[["overview",M("tabOverview")],["statistics",$==="en"?"Cost statistics":"计费统计"],["quotas",M("tabQuotas")],["usage",M("tabUsage")],["pricing",M("tabPricing")],...p?[["codex","Codex"]]:[],["display",M("tabDisplay")]],oe=P=>ma({statistics:o.loadStatistics,pricing:o.loadOpenRouter,codex:o.loadCodex}[P],{state:n}),ge=R.status==="saving"?a("span",{className:"cm-hint"},M("saving")):R.status==="error"?a("span",{className:"cm-msg err"},M("autoSaveFailed",{message:R.error??""})):a("span",{className:"cm-hint"},R.status==="saved"?M("autoSavedAt",{time:new Date(R.at).toLocaleTimeString()}):M("autoSaveHint"));return a("div",{className:"cm-section"},a("div",{className:"cm-tabs-row"},a("div",{className:"cm-tabs",role:"tablist"},ne.map(([P,_])=>a("button",{key:P,type:"button",role:"tab","aria-selected":String(k===P),className:"cm-tab"+(k===P?" active":""),onMouseEnter:()=>oe(P),onFocus:()=>oe(P),onClick:()=>y(P)},_))),ge),a(be,{state:n,api:o,load:o.loadCommunity,locale:$,quiet:!0}),ka(r),k==="statistics"?a(be,{state:n,api:o,autoExport:N==="export"}):null,k==="overview"?a(E,{key:"overview"},a("div",{className:"cm-overview-grid"},a("div",{className:"cm-cards",style:{"--cm-overview-count":T.hideTodayCost===!0?2:3}},T.hideTodayCost===!0?null:a(it,{title:M("cardToday"),value:W(Q(n.today,T),T),sub:M("callsTokens",{calls:n.today.calls,input:L(n.today.input),cache:L(n.today.cacheRead+n.today.cacheWrite),output:L(n.today.output)})}),a(it,{title:M("cardMonth"),value:W(Q(n.month,T),T),sub:M("callsTokens",{calls:n.month.calls,input:L(n.month.input),cache:L(n.month.cacheRead+n.month.cacheWrite),output:L(n.month.output)})}),a(it,{title:M("cardTotal"),value:W(Q(n.total,T),T),sub:M("cardTotalSub",{calls:n.total.calls})}))),a(Ts,{state:n,t:M}),a("p",{className:"cm-note",key:"cards-footnote"},M("cardsFootnote")),a(Cn,{state:n}),(()=>{const P=To(n);return P!==null?a("p",{className:"cm-note",key:"tz-hint"},M("timezoneHint",{host:P.hostLabel,browser:P.browserLabel})):null})(),a("label",{className:"cm-cards-toggle",title:M("cardsTogglePlanTotalHint")},a("input",{type:"checkbox",checked:(s??T).showTotalWithPlan===!0,onChange:P=>{const _=s??T;_!=null&&l({..._,showTotalWithPlan:P.target.checked})}}),a("span",null,M("cardsTogglePlanTotal"))),a("div",null,a("button",{className:"cm-btn",onClick:()=>y("export")},$==="en"?"Export cost records":"导出费用记录"),a("h3",{className:"cm-h"},M("todaySessions")),a(vn,{state:n,t:M})),a(Ls,{state:n,draft:s,setDraft:l,t:M}),(T.balance?.display==="settings"||T.balance?.display==="both")&&T.hideOfficialBalance!==!0?a(Ws,{state:n,api:o,t:M,draft:s,setDraft:l}):null):null,k==="quotas"?a(Xs,{key:"quotas",state:n,api:o,t:M,draft:s,setDraft:l,targetPlan:w}):null,k==="usage"?a(E,{key:"usage"},!ft||(T.usage?.position??"cost")==="cost"?a(Dt,{state:n,t:M,locale:$}):null,a(Qs,{state:n,config:s??T,t:M,draft:s,setDraft:l}),a(Fs,{state:n,config:s??T,t:M}),a(Rs,{state:n,api:o}),a(Os,{state:n,api:o}),a(be,{state:n,api:o,load:o.loadBillingStorage,draft:s,setDraft:l,locale:$,disabled:R.status==="saving"||(s??T).billingStorageRetentionDays!==T.billingStorageRetentionDays}),a("div",null,a("h3",{className:"cm-h"},M("historyDataTitle")),a("div",{className:"cm-buttons"},g?a(E,null,a("span",{className:"cm-hint"},M("confirmImportLegacy")),a("button",{className:"cm-btn",onClick:pt,disabled:m},M("apply")),a("button",{className:"cm-btn",onClick:()=>f(!1)},M("cancel"))):a("button",{className:"cm-btn",onClick:()=>f(!0),disabled:m},M("importLegacy")),u?a(E,null,a("span",{className:"cm-hint"},M("confirmReset")),a("button",{className:"cm-btn danger",onClick:Le,disabled:m},M("confirmClear")),a("button",{className:"cm-btn",onClick:()=>b(!1)},M("cancel"))):a("button",{className:"cm-btn danger",onClick:()=>b(!0),disabled:m},M("clearAllHistory"))),a("p",{className:"cm-note"},M("legacyImportNote")))):null,k==="codex"?a(Bn,{key:"codex",state:n,api:o,t:M,locale:$,view:"panel",ready:p}):null,k==="display"?a(E,{key:"display"},n?.secretMigration?.pending?.length>0?a(Bo,{pending:n.secretMigration.pending,t:M}):null,a(be,{state:{...n,displayPreviewCodex:U.source===(n.config.codexQuotaSource??"auto")?ra():{status:"idle",windows:{}}},api:o,load:o.loadDisplay,draft:s,setDraft:l,t:M,locale:$,numInput:Ge,displayOptions:ha,quotaPlacementValue:ia,quotaPlacementPatch:ca,quotaPlacementOptions:ua,CURRENCY_PRESETS:Ds,USAGE_POSITION_SWITCHABLE:ft,formatMoneyUsd:W,planOptions:De.map(P=>[P.id,M(P.labelKey)]),onNavigate:(P,_)=>{v(_),y(P)},renderSidebar:(P,_=n)=>Rt({..._,config:P},!0,void 0,!0),renderCorner:P=>a(cn,{useCost:()=>({state:P})}),renderStyleSample:(P,_=n,ye=!0)=>{if(!ye)return Rt({..._,config:P},!0,void 0,!0);const xe=P.sidebarSimple===!0,ce={...P,peakNotice:!1,hideBudget:!1,hideTodayCost:!1,budget:{...P.budget,enabled:!0,amount:Number(P.budget?.amount)>0?P.budget.amount:100}},pe={..._,config:ce},re=na(_.codingPlans?.minimax?.windows??{});return a("div",{className:"cm-footer-stack"+(xe?" simple":P.sidebarStyle==="compact"?" compact":"")},a(Tt,{state:pe,wide:!0,summary:xe}),a(oa,{five:re.five??{percent:24},seven:re.seven??{percent:18},fetchedAt:0,t:M,wide:!0,direction:ie(P,"plan")}))}})):null,k==="pricing"?a("div",{key:"pricing",className:"cm-pricing-page"},a("div",{className:"cm-pricing-heading"},a("div",null,a("h3",{className:"cm-h"},$==="en"?"Pricing":"价格设置"),a("p",{className:"cm-note"},$==="en"?"New prices apply to future calls. Historical costs keep their original rates.":"价格修改用于后续调用,历史费用沿用原价格。")),a("span",{className:"cm-pricing-unit"},$==="en"?"Per 1M tokens":"每百万 Token")),a("div",{className:"cm-pricing-nav",role:"tablist","aria-label":$==="en"?"Pricing sections":"价格分区"},[["models","模型定价","Model pricing"],["catalog","参考价格表","Price tables"],["tools","同步与规则","Sync & rules"]].map(([P,_,ye])=>a("button",{key:P,id:"cm-pricing-"+P,type:"button",role:"tab","aria-selected":h===P,"aria-controls":"cm-pricing-panel",tabIndex:h===P?0:-1,className:"cm-pricing-nav-item"+(h===P?" active":""),onClick:()=>C(P),onKeyDown:xe=>{const ce=["models","catalog","tools"],pe=xe.key==="ArrowRight"?1:xe.key==="ArrowLeft"?-1:0;if(pe){xe.preventDefault();const re=ce[(ce.indexOf(P)+pe+3)%3];C(re),xe.currentTarget.parentElement.querySelector("#cm-pricing-"+re)?.focus()}}},$==="en"?ye:_))),a("div",{id:"cm-pricing-panel",className:"cm-pricing-content",role:"tabpanel","aria-labelledby":"cm-pricing-"+h},h==="models"?a(be,{state:n,api:o,load:o.loadPricing,mode:"matching",draft:s,setDraft:l,t:M,locale:$,resolveClientPrice:Ka,prettyProviderKey:ut,setField:D,priceEditor:{PriceInput:An,priceFactor:yt,setPriceFactor:Bt,multiplierOptions:ga,priceMultiplierSettings:gt,priceAt:Ze}}):null,h==="catalog"?a("div",{className:"cm-pricing-catalog"},a("h3",{className:"cm-h"},M("priceTableTitle")),a(be,{state:n,api:o,load:o.loadPricing,mode:"catalog",draft:s,setDraft:l,t:M,locale:$,vendorLabels:js,priceEditor:{priceAt:Ze,priceFactor:yt},renderEditor:(P,_,ye)=>P==="deepseek"?a(Is,{modelId:_==="__default__"?M("defaultModelId"):_,entry:ye,isDefault:_==="__default__",draft:s,setDraft:l,t:M}):a(_s,{provider:P,modelId:_,entry:ye,draft:s,setDraft:l,t:M,api:o,lockedIds:P==="openrouter"?n.priceLockIds??[]:[],releaseDisabled:JSON.stringify(s)!==A.current})})):null,h==="tools"?a("div",{className:"cm-pricing-tools"},a("section",{className:"cm-pricing-tool"},a(Es,{state:n,draft:s,setDraft:l,t:M})),a("section",{className:"cm-pricing-tool"},a(be,{state:n,api:o,load:o.loadPricing,mode:"history",locale:$,disabled:m||JSON.stringify(s)!==A.current})),a("section",{className:"cm-pricing-tool"},a("h3",{className:"cm-h"},M("dataSync")),(s??T).currency==="CNY"&&(s??T).prices?.currency!=="CNY"?a("div",{className:"cm-note",role:"status"},M("pricingCnyHint",{rate:(s??T).exchangeRate}),(s??T).pricingCurrency!=="CNY"?a("button",{className:"cm-btn small",disabled:m,onClick:()=>D("pricingCurrency","CNY")},M("pricingCurrencyCny")):null):null,a("div",{className:"cm-field"},a("label",null,M("pricingCurrencyLabel")),a("select",{className:"cm-input",value:s?.pricingCurrency==="CNY"?"CNY":"USD",onChange:P=>D("pricingCurrency",P.target.value)},a("option",{value:"USD"},M("pricingCurrencyUsd")),a("option",{value:"CNY"},M("pricingCurrencyCny"))),a("p",{className:"cm-note"},M("pricingCurrencyNote"))),a("div",{className:"cm-buttons"},d?a(E,null,a("span",{className:"cm-hint"},M("confirmFetch")),a("button",{className:"cm-btn",onClick:le,disabled:m},M("apply")),a("button",{className:"cm-btn",onClick:()=>c(!1)},M("cancel"))):a("button",{className:"cm-btn",onClick:()=>c(!0),disabled:m},M("syncFromDocs"))),a("p",{className:"cm-note"},M("lastSync",{time:T.fetchedAt!==null?new Date(T.fetchedAt).toLocaleString():M("neverSynced")})+M("source",{source:T.priceSource==="official"?M("sourceOfficial"):M("sourceBundled")})),a("p",{className:"cm-note"},M("syncScopeNote"))),a("section",{className:"cm-pricing-tool"},a(be,{state:n,api:o,load:o.loadOpenRouter}))):null)):null,a(be,{state:n,api:o,load:o.loadCommunity,locale:$,quiet:!0,footer:!0}))}const ol=["remote"];async function sl(e){const t=e.remote;if(t===void 0||typeof t.$mount!="function")return;const o=await t.$mount(ro);e.effect(()=>()=>{o()},"cost-meter: remote contribution");const n=e.get("remote.costMeter");if(n===void 0)return;e.inject(["connection"],S=>S.effect(()=>{const I=S.get("connection")?.rpc;return la(I,()=>n.getPiAiCodexQuota(),()=>n.getChatgptSubQuota()),vt(),()=>{U.rpc===I&&(la(null),vt())}},"cost-meter: Codex quota transport"));const s=()=>{try{return ze(e.get("locale")?.getSnapshot?.().active)}catch{return null}},l=Ro({status:"loading",error:null,state:null},S=>{const I=s()||ze(S.state?.meta?.locale)||Pa();return{...S,locale:I,...S.state?{state:{...S.state,config:{...S.state.config,activeLocale:I}}}:{}}}),r=()=>z(H(l.getSnapshot().state?.config||{activeLocale:l.getSnapshot().locale})),i=async(S,I)=>{const q=await n[S](...I??[]);if(q===null||typeof q!="object"||q.ok!==!0)throw new Error(q?.error?.message??r()("rpcFailed",{method:S}));return q.value},d=S=>(l.set({status:"ready",error:null,state:S}),S);let c=Date.now(),u=!1,b=!0,g=1,f=0,m=0,x=Promise.resolve();const h=(S,I)=>{if(typeof S?.pricesRev!="string"||S.pricesRev!==I?.pricesRev)return S;const q=I?.config?.prices;return q===void 0?S:{...S,config:{...S.config,prices:q}}},C=async()=>{if(!b||u||m)return;const S=f,I=()=>b&&S===f&&m===0;u=!0,c=Date.now();const q=l.getSnapshot();q.state===null&&l.set({...q,status:"loading"});try{const X=q.state?.pricesRev,Te=await i(q.state===null?"getLocalState":typeof X=="string"?"getStateSince":"getState",typeof X=="string"?[X]:[]);if(!I())return;if(g=1,l.set({status:"ready",error:null,state:h(Te,q.state)}),q.state===null){const He=await i("getState");I()&&l.set({status:"ready",error:null,state:h(He,Te)})}}catch(X){if(!I())return;q.state===null&&(c=Date.now()),g=Math.min(g*2,60),l.set({status:"error",error:X?.message??String(X),state:l.getSnapshot().state??q.state})}finally{u=!1}};e.effect(()=>e.on("connection/reset",()=>{C()}),"cost-meter: reconnect reload");const N=setInterval(()=>{const S=l.getSnapshot().state,I=S?.config.sidebarModels,q=S?I?.enabled||I?.dock?I.refreshSeconds:60:g;!document.hidden&&Date.now()-c>=(q||60)*1e3&&C()},1e3);e.effect(()=>()=>{b=!1,clearInterval(N)},"cost-meter: poll timer");const y=()=>{b&&e.fiber?.uid!==null&&l.set(l.getSnapshot())},p=S=>S.effect(()=>{y();const I=S.get("locale")?.subscribe?.(y);return()=>{I?.(),y()}},"cost-meter: DSH locale");typeof e.inject=="function"?e.inject(["locale"],p):s()&&p(e),e.effect(()=>e.on("locale/change",y),"cost-meter: locale change"),window.addEventListener?.("languagechange",y),e.effect(()=>()=>window.removeEventListener?.("languagechange",y),"cost-meter: browser locale");const k=()=>{document.visibilityState==="visible"&&C()};document.addEventListener("visibilitychange",k),e.effect(()=>()=>{document.removeEventListener("visibilitychange",k)},"cost-meter: visibility reload");const w=async(S,I="rpcSyncFailed",q=!1)=>{const X=await S;if(X===null||typeof X!="object"||X.ok!==!0)throw new Error(X?.error?.message??(q?X?.value?.message:void 0)??r()(I));return X.value.state!==void 0&&l.set({status:"ready",error:null,state:X.value.state}),X.value},v={},R=S=>(v[S]||(v[S]=ve.async("./client."+S+".js").then(I=>I.mount(e,l,H,{formatMoneyUsd:W,displayCostOf:Q,formatTokens:L,updateConfig:q=>j.updateConfig(q)})).catch(I=>{throw delete v[S],I})),v[S]),j={loadBillingStorage:()=>R("billing-storage"),billingStorage:async S=>i("billingStorage",[Ha.parse(S)]),loadSettingsOverview:()=>R("settings-overview"),loadStatistics:()=>R("statistics"),loadOpenRouter:()=>R("openrouter"),loadCommunity:()=>R("community"),loadPricing:()=>R("pricing"),loadDisplay:()=>Promise.all([R("display"),R("sidebar-order")]).then(([S])=>S),loadCodex:()=>R("codex"),reload:C,updateConfig:async S=>{const{activeLocale:I,...q}=S;f++,m++;const X=x.catch(()=>{}).then(async()=>{const Te=await i("updateConfig",[q]);return l.set({status:"ready",error:null,state:Te}),S.planBilling&&setTimeout(()=>{C()},1500),Te});x=X;try{return await X}finally{m--,f++}},fetchPrices:async()=>w(n.fetchPrices()),releasePriceLock:async S=>{const I=await w(n.releasePriceLock(S),"rpcSyncFailed",!0);if(!I.ok)throw new Error(I.message);return I},resetHistory:async()=>{const S=await i("resetHistory");return l.set({status:"ready",error:null,state:S}),S},applyCodexCompatHistory:async()=>d(await i("applyCodexCompatHistory")),dismissCodexCompat:async()=>d(await i("dismissCodexCompat")),importLegacyHistory:async()=>{const S=await n.importLegacyHistory();if(S===null||typeof S!="object"||S.ok!==!0)throw new Error(S?.error?.message??S?.value?.message??r()("legacyImportFailed",{message:"RPC failed"}));return S.value.state!==void 0&&l.set({status:"ready",error:null,state:S.value.state}),S.value},getDaySessions:async S=>i("getDaySessions",[S]),getSessionCost:async S=>i("getSessionCost",[S]),getTurnCost:async(S,I,q)=>i("getTurnCost",[S,I,q,l.getSnapshot().state?.config?.currency]),getTopSessions:async(S,I,q)=>i("getTopSessions",[S,I,q]),refreshBalance:async()=>w(n.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>w(n.refreshGoQuota()),refreshGatewayQuota:async(S=null)=>w(S==null?n.refreshGatewayQuota():n.refreshGatewayQuota(S)),refreshCustomBalance:async(S=null)=>w(S==null?n.refreshCustomBalance():n.refreshCustomBalance(S)),refreshCodingPlan:async S=>w(n.refreshCodingPlan(S)),loginCodingPlan:async S=>w(n.loginCodingPlan(S)),setCredential:async(S,I)=>w(n.setCredential(S,I),"rpcSyncFailed",!0),clearCredential:async S=>w(n.clearCredential(S),"rpcSyncFailed",!0)},A=S=>{S.target?.closest?.('[data-slot="conversation.input.model"]')&&j.loadOpenRouter().catch(()=>{})};for(const S of["pointerover","focusin"])e.effect(()=>(document.addEventListener(S,A),()=>document.removeEventListener(S,A)));C();const B=e.get("slots");if(B===void 0)return;const F=S=>{typeof B.entries=="function"&&B.entries(S).some(I=>I.locale==="dsh-context")&&j.loadStatistics().catch(()=>{})};e.on("slots/changed",F),["conversation.view","sidebar.right.pane.tab","conversation.input.overlay"].forEach(F);const G=()=>({hooks:{cost:l},api:j});B.inject("plugins.bundle.config",()=>B.register({name:"plugins.bundle.config",key:"dsh-cost-meter",inject:G},On));for(const[S,I]of[["header","conversation.session.header.actions"],["dock","conversation.composer.dock"]])B.inject(I,()=>B.register({name:I,id:"cost-meter-statistics",order:1,inject:()=>({...G(),entryPosition:S})},Ms));B.inject("conversation.chat.turnTail",()=>B.register({name:"conversation.chat.turnTail",id:"cost-meter-turn",order:10,select:S=>S,inject:G},Do));const ae=()=>({gen:0,dispose:null}),K=(S,I,q,X,Te=!0)=>{S.dispose!==null&&(S.dispose(),S.dispose=null),S.gen+=1;const He=S.gen;Te&&B.inject(I,()=>{if(S.gen!==He)return;const Re=typeof q=="function"?q():B.register(q,X);if(S.gen!==He){Re();return}return S.dispose=Re,()=>{S.dispose===Re&&(S.dispose=null),Re()}})},$=ae(),M=S=>{const I=S==="header"?"conversation.session.header.actions":"conversation.composer.dock";K($,I,S==="header"?{name:I,id:"cost-meter",order:-5,inject:G}:{name:I,id:"cost-meter",order:5,inject:G},S==="header"?Lo:Eo,S!=="off")},T=ae(),le=S=>{K(T,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:G},vs,S)},Le=ae(),pt=S=>{K(Le,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:G},cn,S)};B.inject("conversation.input.dock",()=>B.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:G},ks)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:G},xs)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-peak-progress-guide",order:1,inject:G},Xo)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-summary-guide",order:1,inject:G},Zo)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:G},ws)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:G},Cs)),B.inject("sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-codex-compat",order:1,inject:G},tl));const D=ae(),ne=S=>{K(D,"sidebar.footer.action",()=>B.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:G},Yo),null,S)};window.cmPeakAlertPreview=S=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(zo,{detail:{kind:S==="offpeak"?"offpeak":"peak"}}))};const oe=ae(),ge=S=>{K(oe,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:S==="en"?Ee.en.sectionLabel:Ee.zh.sectionLabel,inject:G},al?nl:On,!0)},P=ae(),_=S=>{K(P,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:G},Dt,S)},ye=ae(),xe=(S,I)=>{K(ye,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:I==="en"?Ee.en.usageSectionLabel:Ee.zh.usageSectionLabel,inject:G},Dt,S)};let ce=null,pe=null,re=null,wa=null,Dn=null,Ln=null;const En=()=>{const S=l.getSnapshot().state;S?.config?.sessionListCosts&&R("session-list").catch(()=>{});const I=S?.config?.position??"dock",q=S?.config?.sidebar!==!1&&S?.config?.hideTodayCost!==!0,X=S?.config?.balance?.display??"both",Te=(X==="sidebar"||X==="both")&&S?.config?.hideOfficialBalance!==!0,He=jn=>jn?.enabled===!0&&["sidebar","both"].includes(jn.display),Re=q||Te||S?.config?.codexQuotaEnabled===!0||S?.config?.sidebarModels?.enabled===!0||S?.config?.budget?.enabled===!0&&S?.config?.hideBudget!==!0||S?.config?.goQuota?.enabled===!0&&["sidebar","both"].includes(S.config.goQuota.display)||S?.config?.peakEnabled===!0&&S.config.peakNotice!==!1||Object.values(S?.config?.codingPlans??{}).some(He)||(S?.config?.gatewayQuotas?.sources??[]).some(He)||St(S,S?.config).length>0;S?.config?.followSkinTransparency&&R("display").catch(()=>{}),Re&&ve.async&&R("sidebar-order").catch(()=>{});const Na=S?.config?.corner?.enabled===!0||S?.config?.sidebarModels?.dock===!0,Ke=H(S?.config||{activeLocale:l.getSnapshot().locale}),mt=S?.config?.usage?.position??"cost";I!==ce&&(M(I),ce=I),Re!==pe&&(le(Re),pe=Re),Na!==re&&(pt(Na),re=Na);const Sa=S?.config?.peakEnabled===!0;Sa!==Ln&&(ne(Sa),Ln=Sa),Ke!==wa&&(ge(Ke),wa=Ke),mt!==Dn?(ft&&(_(mt==="general"),xe(mt==="section",Ke)),Dn=mt):ft&&mt==="section"&&Ke!==wa&&xe(!0,Ke)};En();const In=l.subscribe(En);return e.effect(()=>()=>{In()},"cost-meter: slot sync"),In}return Lt.apply=sl,Lt.inject=ol,Ca.exports}});
|