dsh-cost-meter 1.7.39 → 1.7.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 +7 -7
- package/README.zh-CN.md +7 -7
- package/docs/external-usage.md +2 -2
- package/docs/provider-pricing.json +101 -3
- package/lib/backfill.js +1 -3
- package/lib/client.js +5 -5
- package/lib/external-usage.js +9 -2
- package/lib/index.js +12 -10
- package/lib/plan-billing.js +5 -3
- package/lib/pricing.js +46 -69
- package/lib/store.js +7 -6
- package/lib/typert.host.js +2 -0
- package/locale/en.json +3 -0
- package/locale/zh.json +6 -0
- package/package.json +18 -6
package/lib/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// This file is generated from the src/client/*.js fragments via `node scripts/build.mjs` (esbuild). Do not edit directly.
|
|
2
|
-
window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:It=>{var Ut={exports:{}},rt=Ut.exports;Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"});const Ee=It("react"),{Tooltip:$}=It("@deepseek-ai/dsh-client-ui-primitives"),Ge=!1,Ea='.cm-root{display:block;text-align:center;max-width:var(--dsh-chat-content-width,720px);width:100%;margin:0 auto;box-sizing:border-box;padding:4px calc(var(--dsh-composer-side-clearance,0px) + 16px) 0;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-chip{display:inline-flex;align-items:center;gap:4px;max-width:180px;padding:0 8px;height:22px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-foot{display:flex;align-items:center;gap:6px;height:32px;padding:0 8px;border-radius:8px;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden}.cm-foot:hover,.cm-foot-rail:hover,.cm-corner-chip:hover,.cm-qchip:hover,.cm-tab:hover,.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}.cm-foot-rail{width:100%;justify-content:center;padding:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-num{font-variant-numeric:tabular-nums}.cm-go-rail{font-size:11px;font-weight:700;color:var(--dsw-alias-label-primary)}.cm-go-list{display:flex;flex-direction:column;gap:10px}.cm-go-row{display:flex;align-items:center;gap:8px;font-size:12px}.cm-go-label{flex:none;width:88px;color:var(--dsw-alias-label-secondary)}.cm-go-bar{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-interactive-bg-hover);overflow:hidden}.cm-go-fill{height:100%;border-radius:3px;background:var(--dsw-alias-brand-primary)}.cm-go-num{flex:none;min-width:44px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.cm-go-reset{flex:none;max-width:230px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-go-time{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-go-row.main .cm-go-label{font-weight:600;color:var(--dsw-alias-label-primary)}.cm-corner{display:flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:2px auto 0;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-corner-chip{display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:20px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums}.cm-qstrip{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:0 auto;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-qchip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:default}.cm-qchip .cm-qlabel{color:var(--dsw-alias-label-primary);font-weight:600}.cm-qchip .cm-qbar{display:block;width:44px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l1);overflow:hidden;flex:none}.cm-qchip .cm-qfill{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-state-ok-primary,#3ba272)}.cm-qchip .cm-qseg{display:inline-flex;align-items:center;gap:4px}.cm-qchip .cm-qsep{width:1px;height:12px;background:var(--dsw-alias-border-l1);flex:none}.cm-qchip .cm-qtext{color:var(--dsw-alias-label-secondary)}.cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}.cm-qchip.over .cm-qfill{background:var(--dsw-alias-state-error-primary)}.cm-qchip.action{cursor:pointer;user-select:none;outline:none}.cm-qchip.action:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-qchip.action:active{transform:translateY(.5px)}.cm-plan-provider{display:flex;flex-direction:column;gap:8px}.cm-plan-provider+.cm-plan-provider{margin-top:14px}.cm-plan-provider-name{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600}.cm-plan-updated{font-size:11px;font-weight:400;color:var(--dsw-alias-label-tertiary)}.cm-plan-tag{flex:none;margin-left:6px;padding:0 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);font-size:10px;line-height:16px;color:var(--dsw-alias-state-warn-primary)}.cm-plan-reset,.cm-plan-method{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-qguide{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:9999;max-width:440px;width:calc(100% - 32px);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 28px #0000002e;padding:14px 16px;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:8px}.cm-qguide h4{margin:0;font-size:13px;font-weight:600}.cm-qguide p{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}.cm-qguide .cm-buttons{display:flex;gap:8px;justify-content:flex-end}.cm-section{display:flex;flex-direction:column;gap:20px;padding:4px 2px 24px;font-size:13px;color:var(--dsw-alias-label-primary)}.cm-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.cm-cards-toggle{display:flex;align-items:center;gap:6px;margin:-6px 2px 0 auto;width:fit-content;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;user-select:none}.cm-cards-toggle:hover{color:var(--dsw-alias-label-primary)}.cm-cards-toggle input{margin:0;cursor:pointer}.cm-card,.cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1)}.cm-card-title{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0 0 8px}.cm-card-value{font-size:20px;line-height:28px;font-weight:600}.cm-card-sub{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-h{font-size:13px;font-weight:600;margin:0}.cm-collapse-h{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;margin:0;cursor:pointer;color:inherit;font:inherit;text-align:left}.cm-collapse-h:hover .cm-h{color:var(--dsw-alias-interactive-text-hover,var(--dsw-alias-label-primary))}.cm-caret{flex:none;width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid var(--dsw-alias-label-secondary);transform:rotate(-90deg);transition:transform .15s ease}.cm-caret.open{transform:rotate(0)}.cm-collapse-body{display:flex;flex-direction:column;gap:12px;margin-top:12px}.cm-toolbar{display:flex;justify-content:flex-end;align-items:center;gap:10px}.cm-toolbar .cm-field{flex-direction:row;align-items:center;gap:8px}.cm-toolbar .cm-field label{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-toolbar .cm-input{min-width:150px;padding:4px 10px}.cm-tabs-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;border-bottom:1px solid var(--dsh-alias-border-l1);padding-bottom:10px}.cm-tabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}.cm-tab{font:inherit;font-size:13px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:8px;padding:6px 14px;cursor:pointer;white-space:nowrap}.cm-tab.active{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary-inverted);font-weight:600}.cm-tabs-row .cm-msg{padding:2px 10px}.cm-note{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0}.cm-table{width:100%;border-collapse:collapse;font-size:12px}.cm-table th,.cm-table td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}.cm-table th{color:var(--dsw-alias-label-tertiary);font-weight:500}.cm-table td.num,.cm-table th.num{text-align:right;font-variant-numeric:tabular-nums}.cm-table tr:last-child td{border-bottom:none}.cm-table tr.cm-row-click{cursor:pointer}.cm-table tr.cm-row-click:hover td{background:var(--dsw-alias-bg-hover,rgba(127,127,127,.08))}.cm-sess-title{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-sess-id{font-size:11px;font-family:ui-monospace,Consolas,monospace;color:var(--dsw-alias-label-tertiary)}.cm-empty{font-size:12px;color:var(--dsw-alias-label-tertiary);padding:8px 0}.cm-scroll{max-height:320px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px}.cm-grid{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:12px}.cm-field{display:flex;flex-direction:column;gap:6px}.cm-field label{font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-input{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;outline:none}.cm-input:focus{border-color:var(--dsw-alias-state-business-primary)}.cm-input.narrow{max-width:120px}.cm-range-row{display:flex;align-items:center;gap:10px}.cm-range{flex:1;min-width:0;accent-color:var(--dsw-alias-state-business-primary)}.cm-range-value{flex:none;min-width:44px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-align:right}.cm-check{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}.cm-price-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:10px;background:var(--dsw-alias-bg-layer-1)}.cm-price-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-price-name{font-weight:600;font-size:13px}.cm-price-legacy{font-size:11px;color:var(--dsw-alias-label-tertiary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px}.cm-price-row{display:grid;grid-template-columns:52px 1fr 1fr 1fr;gap:8px;align-items:center}.cm-price-row span{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-price-row input{width:100%}.cm-buttons{display:flex;flex-wrap:wrap;gap:10px;align-items:center}.cm-btn{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-elevated-fill);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 14px;cursor:pointer}.cm-btn.primary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-label-primary-inverted)}.cm-btn.primary:hover{opacity:.88;background:var(--dsw-alias-state-business-primary)}.cm-btn.danger,.cm-msg.err,.cm-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}.cm-btn.small{padding:3px 10px;font-size:12px}.cm-msg{font-size:12px;line-height:18px;padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1)}.cm-msg.ok{color:var(--dsw-alias-state-success-primary)}.cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-budget{display:flex;flex-direction:column;gap:10px}.cm-peak-alert{position:fixed;z-index:9999;width:340px;max-width:calc(100vw - 32px);padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:0 14px 36px #00000038;display:flex;flex-direction:column;gap:8px;font-size:12px;animation:cm-peak-alert-in .22s cubic-bezier(.2,.8,.2,1)}.cm-peak-alert.cm-peak-alert-corner{right:20px;bottom:20px}.cm-peak-alert.cm-peak-alert-center{top:50%;left:50%;transform:translate(-50%,-50%);animation-name:cm-peak-alert-in-center}.cm-peak-alert-peak{border-top:3px solid var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak{border-top:3px solid var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:600;letter-spacing:.4px;text-transform:uppercase}.cm-peak-alert-badge:before{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 4px color-mix(in srgb,currentColor 16%,transparent)}.cm-peak-alert-peak .cm-peak-alert-badge{color:var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak .cm-peak-alert-badge{color:var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-peak-alert-body{color:var(--dsw-alias-label-secondary);line-height:1.55}.cm-peak-alert-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}.cm-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}@keyframes cm-peak-alert-in{0%{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes cm-peak-alert-in-center{0%{opacity:0;transform:translate(-50%,calc(-50% + 10px))}to{opacity:1;transform:translate(-50%,-50%)}}.cm-budget-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-quota-name{flex:1;min-width:0}.cm-budget-bar{height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-budget-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary);transition:width .3s ease}.cm-ug{display:flex;flex-direction:column;gap:12px}.cm-ug-total{font-size:13px;color:var(--dsw-alias-label-primary)}.cm-ug-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,auto);gap:3px;width:100%}.cm-ug-cell{width:100%;aspect-ratio:1/1;border-radius:3px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);border:1px solid var(--dsw-alias-border-l1)}.cm-ug-cell.l1,.cm-ug-cell.l2,.cm-ug-cell.l3,.cm-ug-cell.l4{border-color:transparent}.cm-ug-cell.l1{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary)}.cm-ug-cell.today{outline:1px solid var(--dsw-alias-label-secondary);outline-offset:1px}.cm-ug-months{display:grid;grid-auto-flow:column;gap:3px;width:100%;font-size:10px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-ug-monthc{white-space:nowrap}.cm-budget-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-budget-line.over{color:var(--dsw-alias-state-error-primary)}.cm-peak-strip{display:flex;align-items:center;gap:6px;margin-top:4px;min-width:0}.cm-peak-track{position:relative;display:flex;flex:1;height:6px;min-width:0;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-segment{height:100%;flex:1}.cm-peak-high{background:#ff9800}.cm-peak-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-marker{position:absolute;top:0;left:50%;width:2px;height:100%;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2}.cm-peak-chip{font-size:11px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-classic{position:relative;display:flex;flex-direction:column;gap:5px;margin-top:6px;min-width:0}.cm-peak-classic .cm-peak-track{flex:none;height:8px}.cm-peak-classic-marker{position:absolute;top:0;left:50%;width:4px;height:12px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2;border-radius:2px}.cm-peak-classic-marker:after{content:"";position:absolute;top:-7px;left:50%;transform:translate(-50%);border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #ff9800}.cm-peak-classic.off .cm-peak-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic.off .cm-peak-classic-marker:after{border-top-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic-chip{align-self:flex-start;font-size:11px;font-weight:600;line-height:1.4;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 8px;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-strip.peak .cm-peak-chip,.cm-peak-classic.peak .cm-peak-classic-chip,.cm-peak-rail.peak .cm-peak-rail-label,.cm-peak-rail-classic.peak .cm-peak-rail-classic-label{color:#ff9800}.cm-peak-strip.off .cm-peak-chip,.cm-peak-classic.off .cm-peak-classic-chip,.cm-peak-rail.off .cm-peak-rail-label,.cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}.cm-peak-strip.weekend .cm-peak-chip,.cm-peak-classic.weekend .cm-peak-classic-chip,.cm-peak-rail.weekend .cm-peak-rail-label,.cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker{border-color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker:after{border-top-color:#34a853}.cm-peak-rail{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-track{position:relative;display:flex;flex-direction:column;width:6px;height:56px;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-segment{width:100%;flex:1}.cm-peak-rail-high{background:#ff9800}.cm-peak-rail-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-rail-marker{position:absolute;left:0;top:50%;width:100%;height:2px;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translateY(-50%);transition:top .4s ease;z-index:2}.cm-peak-rail-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-rail-classic{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-classic-track{position:relative;display:flex;flex-direction:column;width:14px;height:56px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-classic-segment{position:relative;width:100%;flex:1;overflow:hidden}.cm-peak-rail-classic-segment.peak{background:#ff9800;border-radius:999px 999px 0 0}.cm-peak-rail-classic-segment.off{background:var(--dsw-alias-state-business-primary);border-radius:0 0 999px 999px}.cm-peak-rail-classic-marker{position:absolute;left:50%;top:50%;width:12px;height:4px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%,-50%);transition:top .4s ease;z-index:2;border-radius:2px}.cm-peak-rail-classic.off .cm-peak-rail-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-rail-classic-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}.cm-grid-group{grid-column:1 / -1;margin-top:8px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:4px}.cm-grid-group:first-child{margin-top:0}.cm-peak-preview{margin-top:8px}.cm-toggle-btn{background:none;border:none;padding:0;font-size:12px;font-weight:600;color:var(--dsw-alias-state-business-primary);cursor:pointer}.cm-toggle-btn:hover{text-decoration:underline}.cm-collapsed-note{margin-top:4px}.cm-catalog-vendor{margin-top:10px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:2px;display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-vendor-toggle{cursor:pointer;user-select:none}.cm-vendor-toggle:hover{color:var(--dsw-alias-label-secondary)}.cm-vendor-display{display:inline-flex;align-items:center;gap:4px;font-weight:400;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}.cm-catalog-family{margin:6px 0 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}.cm-catalog-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px}.cm-catalog-mounted{display:flex;flex-direction:column;gap:4px;padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1)}.cm-catalog-id{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-catalog-price{color:var(--dsw-alias-label-secondary);white-space:nowrap;font-size:11px}.cm-catalog-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);white-space:nowrap}.cm-mstats-tabs{display:flex;gap:8px;margin-bottom:8px}.cm-mstats-tab{background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}.cm-mstats-tab.active{background:var(--dsw-alias-state-business-primary);border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-bg-base);font-weight:600}.cm-mstats-h{margin:10px 0 4px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}.cm-mstats-row{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:8px;align-items:center;font-size:11px;line-height:1.7}.cm-mstats-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-barbg{position:relative;height:10px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden;display:flex}.cm-mstats-bar{height:100%;min-width:0;border-radius:999px}.cm-mstats-bar.cost{background:#ff9800}.cm-mstats-bar.hit{background:#34a853}.cm-mstats-bar.value{background:#a142f4}.cm-mstats-seg{height:100%;min-width:0}.cm-mstats-seg.in{background:var(--dsw-alias-state-business-primary)}.cm-mstats-seg.cache{background:#ff9800}.cm-mstats-seg.out{background:#34a853}.cm-mstats-val{white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-legend{display:flex;gap:12px;font-size:10px;color:var(--dsw-alias-label-tertiary);margin:2px 0 4px}.cm-mstats-dot{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.cm-mstats-note{margin-top:10px;font-size:10px;line-height:1.6;color:var(--dsw-alias-label-tertiary)}.cm-match-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:12px;flex-wrap:wrap}.cm-match-row .cm-input{flex:1;min-width:160px}.cm-budget-controls{display:grid;grid-template-columns:repeat(2,minmax(180px,1fr));gap:12px}.cm-bbox{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:6px;min-width:148px;box-sizing:border-box}.cm-bbox.rail{padding:6px;min-width:0;width:40px;align-items:center;justify-content:center;border-radius:10px}.cm-bbox.warn{border-color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over{border-color:var(--dsw-alias-state-error-primary)}.cm-bbox-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-bbox-label,.cm-bbox-pct{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}.cm-bbox-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-bbox-bar.segments{display:flex;height:8px}.cm-bbox-bar.segments .cm-bbox-fill{flex:none;border-radius:0;height:100%}.cm-bbox-bar.segments .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments .cm-bbox-seg-today{flex:none;height:100%;background:#ff9800}.cm-bbox-bar.segments .cm-bbox-seg-spent{flex:none;height:100%;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-fill:first-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments.rev .cm-bbox-fill,.cm-bbox-bar.segments.rev .cm-bbox-fill:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}.cm-dir-row{display:flex;align-items:center;gap:8px;margin-top:6px}.cm-dir-label{flex:1 1 40%;font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-dir-row .cm-input{flex:1 1 60%;width:auto}.cm-bbox-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary)}.cm-balance-name{display:inline-flex;align-items:center;gap:4px;min-width:0}.cm-model-costs{font-size:12px}.cm-model-costs .cm-bal-label{white-space:nowrap}.cm-model-top{gap:4px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.cm-model-costs .cm-collapse-h{min-width:0;width:100%;white-space:nowrap}.cm-model-costs .cm-bbox-bar{margin-top:3px}.cm-bal-label{min-width:0;overflow:hidden;text-overflow:ellipsis}.cm-bal-amt{margin-left:auto;text-align:right;flex-shrink:0}.cm-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}.cm-bal-link{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:2px;border-radius:4px;font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary);text-decoration:none;outline:none}.cm-bal-link:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-interactive-bg-hover)}.cm-bal-link:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-bbox.warn .cm-bbox-fill,.cm-bbox .cm-bbox-section.warn .cm-bbox-fill,.cm-bbox .cm-mm-row.warn .cm-bbox-fill,.cm-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-fill,.cm-bbox-section.over .cm-bbox-fill,.cm-mm-row.over .cm-bbox-fill,.cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}.cm-bbox-line{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-bbox-rail{font-size:11px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct,.cm-bbox.warn .cm-bbox-rail,.cm-bbox .cm-bbox-section.warn .cm-bbox-pct,.cm-bbox .cm-mm-row.warn .cm-bbox-pct,.cm-mm-row.warn .cm-bbox-label,.cm-corner-chip.warn,.cm-qchip.warn,.cm-simple-summary.warn{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct,.cm-bbox.over .cm-bbox-rail,.cm-bbox-section.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-label,.cm-corner-chip.over,.cm-qchip.over,.cm-simple-summary.over{color:var(--dsw-alias-state-error-primary)}.cm-bbox-pair{display:flex;flex-direction:column;gap:0;padding:2px 10px}.cm-bbox-pair .cm-bbox-section{display:flex;flex-direction:column;gap:4px;padding:4px 0}.cm-bbox-pair .cm-bbox-bar{height:4px}.cm-bbox-divider{height:1px;background:var(--dsw-alias-border-l1);margin:0}.cm-bbox.clickable,.cm-foot.clickable{cursor:pointer}.cm-bbox.clickable:hover{border-color:var(--dsw-alias-state-business-primary)}.cm-bbox.clickable:focus-visible,.cm-foot.clickable:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}@keyframes cm-click-refresh-pulse{0%,to{opacity:.55}50%{opacity:1}}.cm-bbox.clickable.busy,.cm-foot.clickable.busy{animation:cm-click-refresh-pulse 1.1s ease-in-out infinite}.cm-mm{padding:8px 10px;gap:4px}.cm-mm-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-mm-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);grid-column:1/-1}.cm-gw-switcher{cursor:pointer;user-select:none;font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}.cm-gw-switcher:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.cm-gw-sub{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-mm-row{display:flex;align-items:center;gap:8px;padding:2px 0}.cm-mm-row .cm-bbox-label{flex:none;width:auto;min-width:22px;max-width:115px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;word-break:keep-all}.cm-mm-row .cm-bbox-bar{flex:1;min-width:40px;height:6px}.cm-mm-row .cm-bbox-pct{flex:none;min-width:2.4em;text-align:right;font-variant-numeric:tabular-nums}.cm-mm-row.wide .cm-bbox-label{width:auto;max-width:64px;flex:0 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-mm-row.wide .cm-mm-text{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-bal-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-bal-line.warn{color:var(--dsw-alias-state-warning-primary,#b45309)}.cm-footer-stack{display:flex;flex-direction:column;gap:6px;width:100%;align-items:stretch;box-sizing:border-box}.cm-footer-stack.rail{align-items:center}.cm-footer-stack .cm-bbox{width:100%;min-width:0}.cm-footer-stack .cm-foot{width:100%;box-sizing:border-box}.cm-footer-stack.compact .cm-bbox{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:2px;align-items:center}.cm-footer-stack.compact .cm-bbox>*{grid-column:1/-1}.cm-footer-stack.compact .cm-bbox>.cm-mm-row{grid-column:auto}.cm-footer-stack.compact .cm-mm-row{min-width:0;gap:4px;flex-wrap:nowrap}.cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:0 1 auto;min-width:0;max-width:45%;width:auto}.cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0;flex:1 1 0}.cm-footer-stack.simple{gap:0;max-height:38vh;max-height:min(38dvh,320px);overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.cm-footer-stack.simple>*{flex-shrink:0}.cm-footer-stack.simple:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}.cm-footer-stack.simple .cm-bbox{border:0;border-radius:0;padding:4px 8px;gap:2px;background:transparent;box-shadow:inset 0 -1px var(--dsw-alias-border-l1)}.cm-footer-stack.simple .cm-mm-title{font-size:11px;line-height:16px;margin:0}.cm-footer-stack.simple .cm-mm-row{gap:6px;min-height:16px;line-height:16px;margin:0;padding:0}.cm-footer-stack.simple .cm-mm-text{font-size:11px}.cm-footer-stack.simple>.cm-peak-strip,.cm-footer-stack.simple>.cm-peak-classic{margin:0;padding:4px 8px}.cm-simple-summary>span{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-footer-stack.simple .cm-bbox-pct{font-size:12px;line-height:18px}.cm-footer-stack.simple .cm-bbox-bar{height:4px}.cm-footer-stack.simple .cm-bbox-line{display:none}.cm-footer-stack.simple .cm-foot{height:26px;padding:0 8px}.cm-footer-stack.simple .cm-peak-classic{margin-top:2px;gap:2px}.cm-footer-stack.simple .cm-peak-classic-chip{padding:0 4px;border:0;background:transparent}.cm-simple-summary{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 8px;font-size:12px;font-weight:600;border-bottom:1px solid var(--dsw-alias-border-l1)}.cm-footer-stack.simple.rail{border:0;background:transparent}.cm-footer-stack.simple.rail .cm-bbox{padding:4px 2px}.cm-footer-stack.simple .cm-peak-rail-track,.cm-footer-stack.simple .cm-peak-rail-classic-track{height:28px}@media(max-width:640px){.cm-cards,.cm-grid,.cm-budget-controls{grid-template-columns:1fr}}',jt="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(jt)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=jt,t.textContent=Ea,document.head.appendChild(t)}const Te={zh:{sessionCostTitle:"本会话费用(按每次调用实际时刻精确计费)",sessionDetailTokens:"输入 {input} · 缓存 {cache} · 输出 {output}",sessionDetailCache:"缓存:读 {read} · 写 {write}(写入按命中价计费)",cost:"费用 {amount}",sessionLine:"本会话 {amount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",quotaUnlimited:"无限制",pricingCnyHint:"当前人民币金额来自美元价格 × 汇率 {rate}。对照官方人民币账单,请选择 CNY,再同步价格;同步会更新历史费用。",balanceQueryFailed:"余额查询失败:{message}",unknownError:"未知错误",balance:"余额",queryFailed:"查询失败",balanceTitle:"DeepSeek 开放平台账户余额",reconcileLabel:"官方余额变动与本地账本交叉对账(偏差超阈时提示)",totalBalance:"总余额 {amount}",grantedToppedUp:"赠送 {granted} · 充值 {toppedUp}",updatedAt:"更新时间 {time}",budgetOf:"预算({period})",usedOf:"已用 {used} / {amount}",todayShare:"今日 {amount} · 占预算 {pct}",monthTotal:"本月 {month} · 累计 {total}",budget:"预算",todayCostTitle:"今日费用(按官方价格精确计费)",callsTokens:"调用 {calls} 次 · 输入 {input} · 缓存 {cache} · 输出 {output}",monthCost:"本月 {amount}",totalCost:"累计 {amount}",today:"今日",periodDay:"今日",periodMonth:"本月",periodAll:"累计",periodCustomRange:"自定义区间",noHistory:"暂无历史记录。开始对话后,费用将按天汇总在这里。",colDate:"日期",colCalls:"调用",colInTok:"输入 tok",colCacheTok:"缓存 tok",colOutTok:"输出 tok",colCost:"费用",noSessionsToday:"今日暂无会话记录。",colSession:"会话",enableBudget:"启用预算",budgetAmountLabel:"预算额度(按显示币种)",budgetPeriodLabel:"预算周期",startDate:"开始日期",endDate:"结束日期(留空 = 今日)",rangeText:"统计区间:{range}",budgetDisabledNote:"启用预算后显示额度、已用金额及比例(按显示币种换算);可选今日、本月、累计或自定义周期。",budgetStatus:"{period}预算 {amount} · 已用 {used} · {pct}%",overLimit:"(已超出)",nearLimit:"(接近上限)",legacyModel:"旧模型",defaultFallback:"默认回退",remove:"移除",tierBase:"基础",tierOffPeak:"谷时",tierPeak:"峰时",balanceRefreshFailed:"余额刷新失败:{message}",balanceLine:"总余额 {total} · 赠送 {granted} · 充值 {toppedUp} · 更新于 {time}",balanceQueryFailedHint:"余额查询失败:{message}(使用 设置→模型 中配置的 API Key)",balanceNotQueried:"未查询余额",accountBalance:"官方账户余额",refreshing:"刷新中…",refreshBalance:"刷新余额",customBalanceTitle:"自定义 Provider 余额",customBalanceAdd:"添加配置",aliyunBalanceAdd:"添加千问 / 阿里云余额",aliyunBalanceNote:"查询阿里云中国站资金账户可用金,按接口币种显示。使用有 bss:DescribeBillingAccount 权限的 RAM AccessKey,不用千问 API Key。前两项必填;STS 临时凭据才需 Security Token。密钥只存凭据库。",customBalanceConfigNote:"extract 支持点路径、数值和 add/subtract/divide 运算;NewApi quota 除以 500000 得到美元。",customBalanceLabelZh:"中文名称",customBalanceLabelEn:"英文名称",customBalanceUrl:"请求 URL",customBalanceMethod:"请求方法",customBalanceHeaders:"请求头 (JSON)",customBalanceBody:"请求体 (JSON)",customBalanceBodyNote:"留空不发送;JSON 原文保存并发送。默认 Content-Type 为 application/json,可在请求头覆盖。",customBalanceExtract:"解析规则 (JSON)",customBalanceDisplayLabel:"自定义余额显示位置",customBalanceRefreshInterval:"刷新间隔 (分钟)",customBalanceUnitLabel:"余额原币种",customBalanceConvert:"按显示币种折算(USD 余额)",customBalanceConvertNote:"使用显示汇率与精度;余额币种保持端点原币种。其他币种及积分不折算。",balanceBarRemaining:"余额 {amount}",balanceBarToday:"当日已用 {amount}",balanceBarSpent:"已用 {amount}",balanceShowProgressBar:"余额进度条 (蓝=余额,橙=当日,灰=已用)",barDirectionsTitle:"进度条方向",barDirectionsHint:"各组进度条可独立选择填充方向:「剩余方向」满条起步、随消耗递减;「已用方向」空条起步、随消耗填满。",barDirection_balance:"余额条(官方/自定义)",barDirection_budget:"预算条",barDirection_go:"Go 额度条",barDirection_plan:"Plan / Codex 额度条",barDirectionRemaining:"剩余方向(满 → 空)",barDirectionUsed:"已用方向(空 → 满)",balanceBudgetCapLabel:"额度上限 (可选)",balanceBudgetCapHint:"留空则优先使用 API 返回的 max_budget;仍无则显示整条浅蓝",customBalanceInvalidJson:"JSON 格式无效",customBalanceHeadersVarNote:"{{VAR_NAME}} 从 DSH 凭据库或环境变量读取,不落盘。<ROUTE>_API_KEY 的 ROUTE 是 Provider ID 大写、符号换下划线:openai→OPENAI_API_KEY、abc23-d→ABC23_D_API_KEY。同名共用密钥。",customBalanceAllowedHosts:"凭据白名单 (逗号分隔)",customBalanceAllowedHostsHint:"请求头带密钥时仅放行列表内主机,留空则放行并警告,防导入他人配置外带密钥。",customBalanceCredentialsTitle:"凭据输入",customBalanceCredentialsHint:"为上方 {{VAR}} 占位符存入密钥(write-only,只写凭据库,不回显):",customBalanceNoPlaceholders:'请求头还没有 {{VAR}} 占位符:填入如 "Authorization": "Bearer {{MY_API_KEY}}" 后这里会出现凭据输入框。',enable:"启用",customBalanceLine:"剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}",customBalanceRemaining:"剩余 {amount}",refreshCustomBalance:"刷新自定义余额",goQuotaTitle:"OpenCode Go 订阅额度",goQuotaRowLabel:"Go",goWindowRolling:"滚动 5 小时",goWindowWeekly:"本周",goWindowMonthly:"本月",goResetAt:"重置:{time}",resetReached:"已到重置时间",resetDays:"剩余 {d}天{h}小时",resetHours:"剩余 {h}小时{m}分",resetMinutes:"剩余 {m}分钟",quotaUsed:"已用 {pct}%",quotaRemaining:"剩余 {pct}%",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"更新于 {time}",goQuotaDisplayLabel:"Go 额度显示位置",goQuotaRefreshIntervalLabel:"Go 额度刷新间隔(分钟)",goQuotaRefreshMinutesUnit:"分钟",goQuotaKeyLabel:"OpenCode Go API Key(可选,留空自动发现)",goMainLabel:"Go 额度主档位",goDetailLabel:"Go 图框详细信息",credentialConfiguredOf:"已配置(来源:{source})",credentialNotConfigured:"未配置",credentialSave:"保存",credentialClear:"清除",credentialSaving:"保存中…",credentialInputHint:"密钥只写入 DSH 凭据库,不保存在账本里,也不会回显。",secretMigrationPending:"以下密钥仍在本地账本,未迁入凭据库。请导出对应环境变量后重启:",budgetDetailLabel:"预算图框详细信息",refreshGoQuota:"刷新额度",goQuotaNotQueried:"未查询额度",codingPlanAnthropic:"Anthropic(Claude Pro/Max)",codingPlanZai:"Z.ai / 智谱 GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"查询域名(HTTPS)",minimaxOriginNote:"留空自动选择官方站点。填写后 Key 仅发往该域名;使用可信地址,不含路径。",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"打开 DeepSeek 充值页(platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) 周额度",codexQuotaEnabled:"显示 Codex 额度(需安装并登录 dsh-openai-codex)",includeSubagentCost:"本会话费用包含子代理",gatewayQuotaEmpty:"暂无额度数据",codingPlanDisplayLabel:"显示位置",codingPlanDisplayNote:"选「主页面侧边栏 / 两者」后显示额度卡片;窄栏显示百分比。",codingPlanKeyLabel:"API Key(可选,留空自动发现)",codingPlanRefreshIntervalLabel:"刷新间隔(分钟)",refreshCodingPlan:"刷新",codingPlanNotQueried:"未查询额度",gatewayQuotaTitle:"CLIProxyAPI 网关额度",gatewaySourceAdd:"添加来源",gatewaySourceLabel:"来源名称",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"显示位置",gatewaySourceAllowlist:"允许的 Host",gatewaySourceCredential:"Management Key(只写)",gatewaySourceStatus:"状态",gatewaySourceUnsupported:"不支持的 Provider",gatewaySourceUnknown:"未知",gatewaySourceNoAccounts:"未发现账号",gatewaySourceFetchedAt:"抓取于 {time}",gatewaySwitchAccount:"切换账号 (当前: {account})",gatewayOnlyGemini:"只显示 Gemini 额度",refresh:"刷新",quotaEnableFirst:"先勾选启用这一项",quotaRefreshReady:"启用并保存显示位置后可刷新",quotaRemove:"删除",quotaSectionNote:"勾选启用后会排到最上面;点名称可展开该项自己的配置。自定义余额最多 8 条,网关来源最多 4 条。",codingPlanDisabledNote:"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。",goQuotaDisabledNote:"开启后读取 OpenCode Go 的滚动 5 小时、周、月额度,显示在侧栏、设置页及右下角;无订阅时提示原因。",cornerLabel:"右下角显示(dock)",cornerEnabledLabel:"在右下角显示 OpenCode Go 额度 / 预算",cornerGoRolling:"滚动 5 小时额度",cornerGoWeekly:"本周额度",cornerGoMonthly:"本月额度",cornerBudget:"预算已用%",goShortRolling:"5h",goShortWeekly:"周",goShortMonthly:"月",goShortDaily:"日",budgetShort:"预算",ledgerReadFailed:"账本读取失败:{message}",readingLedger:"正在读取账本…",ledgerUnavailable:"账本不可用",syncFailed:"同步失败:{message}",historyCleared:"历史记录已清除。",clearFailed:"清除失败:{message}",peakOff:"峰谷计价已关闭,按基础价格计费",peakNotEffective:"尚未生效(生效时间:{time}),当前按基础价格计费",peakActive:"当前处于峰时段,按峰时价计费",peakNotice:"当前为 DeepSeek 峰时高价时段,按峰时价计费",offPeakActive:"当前处于谷时段,按谷时价计费",weekendAllOffPeak:"周末时段——全谷价(周六及周日全天按谷时价计费)",weekendChip:"周末时段——全谷价",weekendShort:"周末全谷",holidayAllOffPeak:"法定假日——全天谷价",holidayChip:"法定假日——全谷价",holidayShort:"假日",peakHolidaysLabel:"法定假日(北京日期,逗号分隔)",weekendRuleNote:"自 2026-08-23 北京时间 00:00 起,周末和中国公众假期全天谷价;调休上班的周末仍按谷价。",peakShort:"峰时",offPeakShort:"平价",peakStyleLabel:"峰谷时段条样式",peakStyleCompact:"简洁(单行紧凑)",peakStyleClassic:"经典(分段与胶囊芯片)",peakAlertLabel:"峰/谷切换前弹窗提醒",peakAlertAheadLabel:"提前提醒(分钟,1-30)",peakAlertTargetLabel:"提醒类型",peakAlertTargetPeak:"进入峰时",peakAlertTargetOffPeak:"进入谷时",peakAlertTargetBoth:"峰和谷",peakAlertTitlePeak:"即将进入峰时",peakAlertTitleOffPeak:"即将进入谷时",peakAlertBody:"约 {time} 后计费档位切换为{phase}价,请注意本时段调用成本。",peakAlertPhasePeak:"峰时",peakAlertPhaseOffPeak:"谷时",peakAlertBtn:"知道了",peakAlertBadgePeak:"峰价提醒",peakAlertBadgeOffPeak:"谷价提醒",peakAlertPositionLabel:"弹窗位置",peakAlertPositionCorner:"右下角",peakAlertPositionCenter:"屏幕中心",peakAlertWebNotifyLabel:"同步发送系统通知",peakAlertWebNotifyHint:"开关后请在浏览器地址栏允许通知权限,才能在页面最小化/切走时收到提醒。",peakAlertPreviewLabel:"预览弹窗",peakAlertPreviewPeak:"预览 进入峰",peakAlertPreviewOffPeak:"预览 进入谷",peakAlertPreviewTag:"(预览)",peakPanelTitle:"峰谷计价与提示",peakNoticeHiddenHint:"提示已隐藏:需启用峰谷计价并开启「峰时高价时段显著提示」。",groupGeneral:"常规",groupMoney:"金额与币种",groupSidebar:"侧边栏显示",sidebarSimple:"简化侧栏显示",sidebarSimpleNote:"精简卡片,保留金额、额度和悬停详情;高度最多占屏幕 38%,超出可滚动。关闭后恢复。",sidebarSimpleTitle:"试试更轻巧的侧栏",sidebarSimpleBody:"简化显示可以为会话列表留出更多空间。要现在开启吗?之后可在「设置 → 费用 → 显示」中切换。",sidebarSimpleOn:"开启简化显示",sidebarSimpleOff:"保留当前显示",sidebarSimpleError:"设置未能保存。可重试,或关闭提示后在设置中调整。",closeGuide:"关闭提示",todayBudget:"今日 / {period}预算",sidebarStyleLabel:"侧边栏进度条样式",sidebarStyleStandard:"标准",sidebarStyleCompact:"紧凑(两列)",restorePriceMatches:"恢复已移除的模型 ({count})",removePriceMatchHint:"移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按自动匹配规则计价。",groupCorner:"右下角角标",groupDetail:"图框详细信息",catalogTitle:"拓展价格表",catalogNote:"按厂商、模型家族分类的只读参考价。挂载后复制到可编辑价格表并计费;DeepSeek 取消挂载后用默认价,可重新挂载。",catalogOpen:"展开拓展价格表",catalogCollapse:"收起拓展价格表",mountBtn:"挂载",unmountBtn:"取消挂载",mountedTag:"已挂载",catalogUnpriced:"未核价",catalogDeepseekNote:"DeepSeek 模型支持峰谷两档;取消挂载后按默认价计费且不再被自动匹配命中。",modelStatsTitle:"按模型统计(token 与费用)",modelsTitle:"侧栏模型花费",modelsCount:"{n} 模型",modelsOther:"其它",models_enabled:"显示模型花费卡片",models_defaultOpen:"默认展开",models_remember:"记住展开状态",models_tokens:"显示 Token",models_shares:"显示费用占比条",models_dock:"右下角显示 Top-1 模型",models_period:"默认周期",models_summary:"收起摘要",models_position:"卡片位置",models_topN:"模型行数(1–10)",models_refreshSeconds:"刷新间隔(10–60 秒)",modelsTotal:"周期总额与模型数",modelsTop:"Top-1 模型与金额",modelsFirst:"顶部",modelsAfter:"余额之后",modelsLast:"底部",modelStatsToday:"今日",modelStatsHistory:"近 90 天",modelStatsCostH:"费用排行",modelStatsTokensH:"Token 消耗",modelStatsHitH:"缓存命中率",modelStatsHitUnreported:"未上报?",modelStatsHitUnreportedTip:"长调用始终无缓存命中,代理可能移除缓存字段或破坏缓存。命中率未知;全未命中价是金额上界,可直连官方 API 核对。",modelStatsValueH:"性价比 · 每美元 token 数",modelStatsInput:"输入",modelStatsCache:"缓存",modelStatsOutput:"输出",modelStatsEmpty:"该时段暂无用量数据。",modelStatsBlended:"综合单价 {price}/M",modelStatsNote:"命中率=缓存读÷(缓存读+普通输入);「未上报?」表示可能缺缓存字段(常见于代理),金额按全未命中计(上界);单价=费用÷总 token×1M(USD/M);性价比=总 token÷费用。按调用时美元价计。",modelStatsLegacy:"未分模型(早期数据 · 按当时记录计费)",sessionLineSplit:"本会话 {amount}(API)· Plan 等值 {planAmount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",costChipPlan:"费用 {amount}(+Plan)",sessionDetailPlan:"Plan 订阅额度消耗(等值){amount}",planStatsTitle:"Token Plan 用量统计(每 1% 与满窗估算)",planStatsEmpty:"暂无已启用的 Coding Plan 额度数据;在「额度」标签启用并成功刷新后,这里会显示各窗口的每 1% 额度与满窗用量估算。",planStatsWindow:"窗口",planStatsPercent:"已用 %",planStatsLocal:"本周期实际(本地账本)",planStatsPer1:"每 1% 额度 ≈",planStatsFull:"满窗 100% ≈",planStatsResets:"重置 {time}",planStatsMethodSample:"采样差分",planStatsMethodLive:"当前用量折算",planStatsMethodNone:"样本不足",planStatsMethodSampleAt:"{method}(基准 {time})",planStatsConfidenceLow:"读数精度受限",planStatsCurveTitle:"Plan 用量曲线(按采样区间聚合)",planStatsDaily:"每日",planStatsWeekly:"每周",planStatsMonthly:"每月",planStatsCurveEmpty:"采样区间尚不足(至少两次成功刷新且百分比有变化),曲线会在持续使用后逐步成形。",planStatsBarTip:"{date}:满窗估计 ≈ {full}(每 1% ≈ {per1})· 实际 {tokens} / {cost} · {intervals} 个采样区间",planStatsNote:"金额为目录 API 价等值(订阅耗额度,预算只计 API);估算仅含 dsh 调用,服务端已用%按全账号计;每 1%/满窗由可信样本差分估算(短段精度受限);5h 滚动,周/月按本地日历。",billingClassLabel:"计费方式",billingClassPlan:"Plan 订阅",catalogDisplayLabel:"在费用设置直接显示",catalogDisplayHint:"仅控制是否在费用价格表直接显示;不影响挂载和计费。隐藏的已挂载模型仍可在拓展表编辑。",priceTableDisplayHint:"在下方拓展表逐模型切换直接显示。DeepSeek 默认直接显示;第三方模型挂载后默认留在拓展表。",catalogCustomModels:"手动新增模型",priceMatchLabel:"未知模型名自动匹配",priceMatchAuto:"自动(去后缀 / 前缀 / 家族相似)",priceMatchExact:"仅精确匹配",priceMatchNote:"匹配顺序:精确→手动指定→去版本后缀→前缀→家族;未匹配的 DeepSeek 用默认价,其他 provider 不计价。",unmatchedTitle:"最近出现但未命中价格的模型",unmatchedHint:"当前模式未匹配价格(含跨厂商兜底价)。指定条目会保存手动覆盖;「默认价」使用 DeepSeek 默认价。本地推理(lmstudio/ollama/vLLM)默认零费用,需在此指定价格。",overrideTargetDefault:"DeepSeek 默认价",overrideRemove:"移除",overrideTargetLocal:"本地模型(零消耗)",matchedTitle:"本月已命中价格的模型",matchedHint:"以下模型自动匹配价格。可改选其它条目或「本地模型(零消耗)」:token 仍统计,历史费用即时归零。保存后移入上方手动指定区。",matchedKeepAuto:"保持自动命中",overrideNone:"暂无手动匹配覆盖。",mountedSuffix:"已挂载(参与计费)",flatInput:"输入",flatCached:"缓存",flatOutput:"输出",deepseekMountedHeader:"DeepSeek 价格表(已挂载)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow 硅基流动",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet 超算互联网 Token Plan",codingPlanVolcengine:"火山方舟 Volcano Ark Coding Plan",codingPlanQwen:"千问 Qwen Token Plan",codingPlanMimo:"小米 MiMo Token Plan",mimoWindowPlan:"套餐积分",mimoWindowCompensation:"补偿积分",codingPlanWindowBalance:"余额",qwenSource:"额度来源",qwenSourceLocal:"本地估算",qwenSourceCli:"官方 CLI",qwenSourceBailian:"百炼 CLI",qwenCliNote:"CLI 模式需在 DSH 主机安装 @qianwenai/qianwen-cli,并以同一系统账号运行 qianwen auth login。",qwenBailianNote:"百炼 CLI:在 DSH 主机安装 bailian-cli 并以同一系统账号运行 bl auth login --console。",qwenPlanCreditsLabel:"月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)",qwenPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",qwenRatesLabel:"Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)",qwenRatesModelPlaceholder:"模型名,如 qwen3.8-max-preview",qwenRatePlaceholder:"费率",qwenRate_input:"输入",qwenRate_cachedInput:"缓存读",qwenRate_output:"输出",qwenRateDraftNote:"待填齐三项正数后自动保存;全部清空恢复内置表。",qwenRatesAdd:"添加",qwenLocalNote:"本地估算,Credits 以控制台为准。只计 qwen、qwen-tokenplan、qianwen-tokenplan、qwen-token-plan、qianwen-token-plan 订阅渠道(含 llm- 前缀);排除 API 与 qianwen 按量渠道。表外模型需设抵扣率。",scnetPlanCreditsLabel:"本地估算月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)",scnetPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",scnetLocalNote:"可接入最长 24 小时的控制台快照;否则按官方 Credits 表从本地账本估算。其他工具和表外模型未计入;以控制台为准。",volcengineAccessKeyIdLabel:"火山引擎 AccessKey ID",volcengineSecretAccessKeyLabel:"火山引擎 SecretAccessKey",volcengineNote:"火山方舟使用 AK/SK HMAC 签名(非 ARK_API_KEY)。IAM 需 ArkReadOnlyAccess + BillingCenterReadOnlyAccess;填 AccessKeyID/SecretAccessKey 或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。仅发送至 open.volcengineapi.com。",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}小时",countdownHourMinute:"{h}小时{m}分",countdownMinute:"{m}分钟",nextOffPeakIn:"{time}后进入平价",nextPeakIn:"{time}后进入高峰",peakSummary:"峰时段(UTC):{windows};生效时间:{time}。{status}",noPeakWindows:"未配置峰谷时段。{status}",unknown:"未知",cardToday:"今日费用",cardMonth:"本月费用",cardTotal:"累计费用",cardTotalSub:"自账本建立以来 · 调用 {calls} 次",externalUsage:"外部用量",combinedUsage:"DSH + 外部合计",externalStale:"外部快照超过 24 小时未更新",externalHistory:"近期每日记录",cardsFootnote:"金额取最近落盘快照(2 秒防抖,关闭时落盘),可能比官方账单晚几分钟。tokens 含输入、输出、缓存、推理;推理不另计费(官方并入输出)。以金额对账。",timezoneHint:"今日/本月按宿主时区 {host} 取日界,不同于浏览器({browser});本地午夜后调用可能计入前一天,对账也可能偏差。让 dsh 使用本地时区即可对齐。",todaySessions:"今日会话",historyExpandHint:"点击日期行可展开当日会话明细",historySessionsLoading:"会话明细加载中…",historyNoSessions:"该日无会话明细(早期数据或会话日志已清理)",historySessionsError:"会话明细加载失败",sessionRankTitle:"按会话统计(全部历史)",sessionRankHint:"不按日期分组,全部历史会话;排序与条数可切换",sessionRankEmpty:"暂无会话数据",sessionRankLoading:"会话排行加载中…",sessionRankError:"会话排行加载失败",sessionRankLimit:"显示条数",showSessionIdLabel:"会话列表附显会话 ID",cardsTogglePlanTotal:"金额含 Plan 总额",cardsTogglePlanTotalHint:"开启后所有金额按含 Plan 订阅等值的总费用展示;关闭(默认)仅计真金白银 API 渠道",hideOfficialBalanceLabel:"隐藏官方账户余额(开启后侧边栏与设置页不再显示官方余额)",hideTodayCostLabel:"隐藏今日消耗金额(开启后侧边栏/预算明细/概览卡片不再显示今日费用)",sessionRankSort:"排序",sessionSortCostDesc:"费用 高→低",sessionSortCostAsc:"费用 低→高",sessionSortTimeDesc:"时间 新→旧",sessionSortTimeAsc:"时间 旧→新",sessionSortRecent:"实时顺序",history:"历史记录",usageTitle:"Token 用量统计",usageTotal:"累计 {tokens} tokens · 输入 {input} · 缓存 {cache} · 输出 {output} · {calls} 次调用",usageDay:"{date}:共 {tokens} tokens(输入 {input} · 缓存 {cache} · 输出 {output})· {calls} 次调用 · {cost}",usageEmpty:"暂无历史数据,开始对话后每日用量会汇总在这里",usageSectionLabel:"用量",usagePositionLabel:"Token 用量统计位置",usagePositionCost:"费用设置",usagePositionGeneral:"通用设置",usagePositionSection:"独立分节(用量)",displaySettings:"显示设置",tabOverview:"概览",tabQuotas:"额度",tabUsage:"用量",tabPricing:"价格",tabDisplay:"显示",historyDataTitle:"历史数据",positionLabel:"会话费用显示位置",positionDock:"输入区下方",positionHeader:"会话标题栏",off:"关闭",quotaStripGroup:"输入框上方额度横条",quotaStripEnable:"启用额度横条(输入框上方一条横排显示)",quotaStripShowBudget:"横条含预算已用%",quotaStripShowGo:"横条含 Go 额度",quotaStripShowPlans:"横条含 Coding Plan 额度",quotaStripNote:"横条悬停可见各窗口重置时刻与更新时间;无可用额度数据时自动隐藏。",quotaStripGuideTitle:"新增:输入框上方额度横条",quotaStripGuideBody:"在输入框上方显示预算及 OpenCode Go/Coding Plan 额度百分比。现在开启吗?可在「设置 → 显示设置」修改。",quotaStripGuideOn:"开启横条",quotaStripGuideOff:"暂不开启",clickToRefresh:"点击立即刷新",balanceClickGuideTitle:"新增:余额图框点击刷新",balanceClickGuideBody:"点击侧边栏余额或 Coding Plan 图框即可刷新;刷新时图框闪烁,失败时保留原值并在悬停提示中说明原因。",balanceClickGuideOk:"知道了",sidebarLabel:"当日费用显示",sidebarOn:"侧边栏底部",currencyLabel:"货币单位",currencyCny:"人民币 CNY",currencyUsd:"美元 USD",currencyEur:"欧元 EUR",symbolLabel:"货币符号",rateLabel:"汇率(1 美元 = ? 目标币种)",decimalsLabel:"小数位数",balanceDisplayLabel:"余额显示位置",balanceSidebar:"主页面侧边栏",balanceSettings:"设置页",balanceBoth:"两者都显示",refreshIntervalLabel:"余额刷新间隔(分钟)",peakEnabledLabel:"启用 DeepSeek 峰谷时段价格",peakNoticeLabel:"峰时高价时段显著提示(侧边栏预算框/今日费用;设置页峰谷面板内预览)",badgeNote:"会话按调用时价格计费(含峰谷与历史档位)。输入、输出、缓存读写分开统计;独立缓存写入价与长上下文档位按配置生效。",priceTableTitle:"价格表(美元 / 1M tokens)",pricingCurrencyLabel:"官方价格币种",pricingCurrencyUsd:"美元(英文官方页)",pricingCurrencyCny:"人民币(中文官方页)",pricingCurrencyNote:"决定同步价格所用的官方页语言。切换并同步后后台重算历史;日志不全的会话保留原价。完成后提示。",priceTableNote:"按调用时间计价:Flash 自 9 月 10 日北京 12:00 用新价,V4 Pro 自 9 月 14 日同刻用 Flash 价;此前用历史价。工作日 09–12、14–18 峰价翻倍;周末及中国公众假期全天谷价。缓存写入按命中价。",datedPriceNote:"这里显示当前适用价格。手工编辑会取消此条后续预定调价,已发生的历史价格仍保留。",defaultModelId:"default(未匹配模型时回退)",newModelPlaceholder:"新模型 ID(如 deepseek-v4-pro)",addModel:"添加模型",dataSync:"数据与同步",saving:"保存中…",autoSaveFailed:"自动保存失败:{message}",autoSavedAt:"已自动保存 {time}",autoSaveHint:"配置修改后自动保存",confirmFetch:"确认用官方文档价格覆盖价格表?",apply:"应用",cancel:"取消",syncFromDocs:"从官方文档同步价格",syncScopeNote:"官方同步只更新 DeepSeek 价格(含峰谷);z-ai/Kimi/Qwen/Volcano 等第三方价格随版本更新,也可在拓展价格表或模型名匹配中调整。",confirmReset:"确认清除全部历史?",importLegacy:"导入安装前历史",confirmImportLegacy:"确认导入?将回放全部会话日志,只补账本缺失的日期与会话,不影响已有记录。",legacyImportFailed:"导入安装前历史失败:{message}",legacyImportNote:"首次启动自动导入旧记录;拷入日志后可重跑。按当前价格回推;已删除日志无法回放,跨安装时刻的会话不计此前用量。",confirmClear:"确认清除",clearAllHistory:"清除全部历史",lastSync:"最近同步:{time}",neverSynced:"从未(使用内置价格)",source:";来源:{source}",sourceOfficial:"官方文档",sourceBundled:"内置默认",languageLabel:"界面语言",localeAuto:"跟随浏览器(自动)",localeZh:"简体中文",localeEn:"English",sectionLabel:"费用",rpcFailed:"{method} 调用失败",rpcSyncFailed:"同步调用失败",rpcBalanceFailed:"余额刷新调用失败"},en:{sessionCostTitle:"Cost of this session (billed exactly at each call time)",sessionDetailTokens:"Input {input} · Cache {cache} · Output {output}",sessionDetailCache:"Cache: read {read} · write {write} (writes billed at the hit price)",cost:"Cost {amount}",sessionLine:"This session {amount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",quotaUnlimited:"Unlimited",pricingCnyHint:"CNY totals use USD prices × {rate}. To compare official CNY bills, select CNY, then sync prices; syncing also updates historical costs.",balanceQueryFailed:"Balance query failed: {message}",unknownError:"Unknown error",balance:"Balance",queryFailed:"Query failed",balanceTitle:"DeepSeek open-platform account balance",reconcileLabel:"Cross-check official balance changes against the local ledger (warn when they diverge)",totalBalance:"Total {amount}",grantedToppedUp:"Granted {granted} · Topped-up {toppedUp}",updatedAt:"Updated {time}",budgetOf:"Budget ({period})",usedOf:"Used {used} / {amount}",todayShare:"Today {amount} · {pct} of budget",monthTotal:"This month {month} · All time {total}",budget:"Budget",todayCostTitle:"Today's cost (billed exactly at official prices)",callsTokens:"Calls {calls} · Input {input} · Cache {cache} · Output {output}",monthCost:"This month {amount}",totalCost:"All time {amount}",today:"Today",periodDay:"Today",periodMonth:"This month",periodAll:"All time",periodCustomRange:"Custom range",noHistory:"No history yet. Once you start chatting, costs are aggregated here per day.",colDate:"Date",colCalls:"Calls",colInTok:"In tok",colCacheTok:"Cache tok",colOutTok:"Out tok",colCost:"Cost",noSessionsToday:"No sessions recorded today.",colSession:"Session",enableBudget:"Enable budget",budgetAmountLabel:"Budget amount (in display currency)",budgetPeriodLabel:"Budget period",startDate:"Start date",endDate:"End date (empty = today)",rangeText:"Range: {range}",budgetDisabledNote:"Enable a budget to see its limit, used amount and percentage in the display currency. Choose today, month, all time or a custom range.",budgetStatus:"{period} budget {amount} · Used {used} · {pct}%",overLimit:" (over limit)",nearLimit:" (near limit)",legacyModel:"Legacy",defaultFallback:"Default fallback",remove:"Remove",tierBase:"Base",tierOffPeak:"Off-peak",tierPeak:"Peak",balanceRefreshFailed:"Balance refresh failed: {message}",balanceLine:"Total {total} · Granted {granted} · Topped-up {toppedUp} · Updated {time}",balanceQueryFailedHint:"Balance query failed: {message} (uses the API key configured in Settings → Models)",balanceNotQueried:"Balance not queried",accountBalance:"Account balance",refreshing:"Refreshing…",refreshBalance:"Refresh balance",customBalanceTitle:"Custom provider balance",customBalanceAdd:"Add entry",aliyunBalanceAdd:"Add Qianwen / Alibaba Cloud balance",aliyunBalanceNote:"Shows Alibaba Cloud China funds in the returned currency. Use a RAM AccessKey with bss:DescribeBillingAccount, not a Qianwen key. First two fields are required; Security Token is STS-only. Secrets stay in the credential store.",customBalanceConfigNote:"Extract accepts paths, numbers and add/subtract/divide. Divide NewApi quota by 500000 for USD.",customBalanceLabelZh:"Chinese name",customBalanceLabelEn:"English name",customBalanceUrl:"Request URL",customBalanceMethod:"HTTP method",customBalanceHeaders:"Headers (JSON)",customBalanceBody:"Request body (JSON)",customBalanceBodyNote:"Blank sends no body; JSON text is saved and sent as entered. Content-Type defaults to application/json; headers can override it.",customBalanceExtract:"Extract rules (JSON)",customBalanceDisplayLabel:"Custom balance display",customBalanceRefreshInterval:"Refresh interval (minutes)",customBalanceUnitLabel:"Source currency",customBalanceConvert:"Convert USD balance to display currency",customBalanceConvertNote:"Uses the display rate and precision. Keep the source currency; other currencies and credits stay unchanged.",balanceBarRemaining:"Balance {amount}",balanceBarToday:"Today {amount}",balanceBarSpent:"Spent {amount}",balanceShowProgressBar:"Balance progress bar (blue=balance, orange=today, gray=spent)",barDirectionsTitle:"Progress bar direction",barDirectionsHint:'Each group of bars can independently choose its fill direction: "Remaining" starts full and drains with usage; "Used" starts empty and fills up.',barDirection_balance:"Balance bars (official/custom)",barDirection_budget:"Budget bar",barDirection_go:"Go quota bar",barDirection_plan:"Plan / Codex quota bars",barDirectionRemaining:"Remaining (full → empty)",barDirectionUsed:"Used (empty → full)",balanceBudgetCapLabel:"Budget cap (optional)",balanceBudgetCapHint:"Leave empty to use API max_budget; if still missing, show full light-blue bar",customBalanceInvalidJson:"Invalid JSON",customBalanceHeadersVarNote:"{{VAR_NAME}} reads a DSH credential or env variable without storing it. <ROUTE>_API_KEY uses uppercase Provider ID with symbols replaced by underscores: openai→OPENAI_API_KEY, abc23-d→ABC23_D_API_KEY. Same name shares a key.",customBalanceAllowedHosts:"Allowed hosts (comma-separated)",customBalanceAllowedHostsHint:"When headers carry credentials only listed hosts are allowed; leave empty to allow with a warning. Protects keys when importing someone else's config.",customBalanceCredentialsTitle:"Credential input",customBalanceCredentialsHint:"Store the key for each {{VAR}} placeholder above (write-only: stored in the DSH credential store, never echoed back):",customBalanceNoPlaceholders:'No {{VAR}} placeholders in the headers yet — add e.g. "Authorization": "Bearer {{MY_API_KEY}}" and a credential input will appear here.',enable:"Enable",customBalanceLine:"Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}",customBalanceRemaining:"Remaining {amount}",refreshCustomBalance:"Refresh custom balance",goQuotaTitle:"OpenCode Go subscription quota",goQuotaRowLabel:"Go",goWindowRolling:"Rolling 5h",goWindowWeekly:"Weekly",goWindowMonthly:"Monthly",goResetAt:"Resets: {time}",resetReached:"Reset time reached",resetDays:"{d}d {h}h left",resetHours:"{h}h {m}m left",resetMinutes:"{m}m left",quotaUsed:"{pct}% used",quotaRemaining:"{pct}% remaining",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"Updated {time}",goQuotaDisplayLabel:"Go quota display position",goQuotaRefreshIntervalLabel:"Go quota refresh interval (minutes)",goQuotaRefreshMinutesUnit:"min",goQuotaKeyLabel:"OpenCode Go API key (optional; empty = auto-detect)",goMainLabel:"Go quota primary window",goDetailLabel:"Go box details",credentialConfiguredOf:"Configured (source: {source})",credentialNotConfigured:"Not configured",credentialSave:"Save",credentialClear:"Clear",credentialSaving:"Saving…",credentialInputHint:"The key is written to the DSH credential store only — it is never saved in the ledger and never echoed back.",secretMigrationPending:"These credentials remain in the local ledger. Export the matching environment variables and restart:",budgetDetailLabel:"Budget box details",refreshGoQuota:"Refresh quota",goQuotaNotQueried:"Quota not queried",codingPlanAnthropic:"Anthropic (Claude Pro/Max)",codingPlanZai:"Z.ai / Zhipu GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"Quota origin (HTTPS)",minimaxOriginNote:"Empty: official sites. Otherwise the Key is sent only to this origin. Use a trusted address without a path.",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"Open DeepSeek top-up page (platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) weekly quota",codexQuotaEnabled:"Show Codex quota (requires signed-in dsh-openai-codex)",includeSubagentCost:"Include subagents in session cost",gatewayQuotaEmpty:"No quota data",codingPlanDisplayLabel:"Display position",codingPlanDisplayNote:"“Main sidebar / Both” shows a quota card; the narrow rail shows percentages.",codingPlanKeyLabel:"API key (optional; empty = auto-detect)",codingPlanRefreshIntervalLabel:"Refresh interval (minutes)",refreshCodingPlan:"Refresh",codingPlanNotQueried:"Quota not queried",gatewayQuotaTitle:"CLIProxyAPI gateway quotas",gatewaySourceAdd:"Add source",gatewaySourceLabel:"Source label",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"Display",gatewaySourceAllowlist:"Allowed hosts",gatewaySourceCredential:"Management key (write-only)",gatewaySourceStatus:"Status",gatewaySourceUnsupported:"Unsupported providers",gatewaySourceUnknown:"Unknown",gatewaySourceNoAccounts:"No accounts",gatewaySourceFetchedAt:"fetched {time}",gatewaySwitchAccount:"Switch account (current: {account})",gatewayOnlyGemini:"Gemini quota only",refresh:"Refresh",quotaEnableFirst:"Enable this item first",quotaRefreshReady:"Enable and save a display position to refresh",quotaRemove:"Remove",quotaSectionNote:"Enabled items move to the top; click a name to expand its own settings. Up to 8 custom balances and 4 gateway sources.",codingPlanDisabledNote:"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.",goQuotaDisabledNote:"Enable OpenCode Go rolling 5h, weekly and monthly quotas in the sidebar, Settings and bottom-right corner. Missing subscriptions show a reason.",cornerLabel:"Bottom-right (dock) display",cornerEnabledLabel:"Show OpenCode Go quota / budget at the bottom-right",cornerGoRolling:"Rolling-5h quota",cornerGoWeekly:"Weekly quota",cornerGoMonthly:"Monthly quota",cornerBudget:"Budget used %",goShortRolling:"5h",goShortWeekly:"Wk",goShortMonthly:"Mo",goShortDaily:"Daily",budgetShort:"Budget",ledgerReadFailed:"Ledger read failed: {message}",readingLedger:"Reading ledger…",ledgerUnavailable:"Ledger unavailable",syncFailed:"Sync failed: {message}",historyCleared:"History cleared.",clearFailed:"Clear failed: {message}",peakOff:"Peak/off-peak pricing is off; base prices are used",peakNotEffective:"Not yet effective (effective at {time}); base prices are currently used",peakActive:"Peak hour now; peak prices apply",peakNotice:"DeepSeek peak-hour pricing is active; current calls are billed at peak prices",offPeakActive:"Off-peak now; off-peak prices apply",weekendAllOffPeak:"Weekend — all off-peak (Sat & Sun billed at off-peak prices all day)",weekendChip:"Weekend — all off-peak",weekendShort:"Weekend",holidayAllOffPeak:"Chinese public holiday — off-peak all day",holidayChip:"Public holiday — all off-peak",holidayShort:"Holiday",peakHolidaysLabel:"Public holidays (Beijing dates, comma separated)",weekendRuleNote:"Since Aug 23, 2026 (Beijing time), weekends and Chinese public holidays are off-peak all day, including work-shift weekends.",peakShort:"Peak",offPeakShort:"Off-peak",peakStyleLabel:"Peak period strip style",peakStyleCompact:"Compact (one-line)",peakStyleClassic:"Classic (segments & chip)",peakAlertLabel:"Popup alert before peak/off-peak switch",peakAlertAheadLabel:"Lead time (minutes, 1-30)",peakAlertTargetLabel:"Alert type",peakAlertTargetPeak:"Entering peak",peakAlertTargetOffPeak:"Entering off-peak",peakAlertTargetBoth:"Both",peakAlertTitlePeak:"Entering peak hours soon",peakAlertTitleOffPeak:"Entering off-peak hours soon",peakAlertBody:"Billing switches to {phase} pricing in about {time}; mind your call costs in this window.",peakAlertPhasePeak:"peak",peakAlertPhaseOffPeak:"off-peak",peakAlertBtn:"Got it",peakAlertBadgePeak:"Peak alert",peakAlertBadgeOffPeak:"Off-peak alert",peakAlertPositionLabel:"Popup position",peakAlertPositionCorner:"Bottom-right",peakAlertPositionCenter:"Screen center",peakAlertWebNotifyLabel:"Also send a system notification",peakAlertWebNotifyHint:"When enabled, allow notification permission in the browser address bar so you get alerted even when the page is minimized or backgrounded.",peakAlertPreviewLabel:"Preview the popup",peakAlertPreviewPeak:"Preview entering peak",peakAlertPreviewOffPeak:"Preview entering off-peak",peakAlertPreviewTag:" (preview)",peakPanelTitle:"Peak/off-peak pricing & notice",peakNoticeHiddenHint:"Notice hidden: enable peak/off-peak pricing and the “prominent notice” toggle.",groupGeneral:"General",groupMoney:"Money & currency",groupSidebar:"Sidebar display",sidebarSimple:"Simplify the sidebar",sidebarSimpleNote:"Condense cards but keep amounts, quotas and hover details. Height is capped at 38% of the viewport with scrolling. Turn off to restore.",sidebarSimpleTitle:"A lighter sidebar",sidebarSimpleBody:"Simple display leaves more room for conversations. Enable it now? You can change it in Settings → Cost → Display anytime.",sidebarSimpleOn:"Enable simple display",sidebarSimpleOff:"Keep current display",sidebarSimpleError:"Settings could not be saved. Retry or dismiss this guide and change them later in Settings.",closeGuide:"Dismiss guide",todayBudget:"Today / {period} budget",sidebarStyleLabel:"Sidebar progress style",sidebarStyleStandard:"Standard",sidebarStyleCompact:"Compact (2 columns)",restorePriceMatches:"Restore removed models ({count})",removePriceMatchHint:"Remove clears the override and hides the row until restored. Usage records are kept; automatic price matching applies.",groupCorner:"Corner chips",groupDetail:"Box details",catalogTitle:"Extended price catalog",catalogNote:"Read-only prices by vendor and model family. Mount to bill; unmount DeepSeek to restore its default price. You can remount later.",catalogOpen:"Expand extended price catalog",catalogCollapse:"Collapse extended price catalog",mountBtn:"Mount",unmountBtn:"Unmount",mountedTag:"Mounted",catalogUnpriced:"Unpriced",catalogDeepseekNote:"DeepSeek models support peak/off-peak tiers; once unmounted they bill at the default price and are no longer hit by auto-matching.",modelStatsTitle:"Per-model statistics (tokens & cost)",modelsTitle:"Sidebar model costs",modelsCount:"{n} models",modelsOther:"Other",models_enabled:"Show model cost card",models_defaultOpen:"Expand by default",models_remember:"Remember expansion",models_tokens:"Show tokens",models_shares:"Show cost shares",models_dock:"Top model in corner dock",models_period:"Default period",models_summary:"Collapsed summary",models_position:"Card position",models_topN:"Model rows (1–10)",models_refreshSeconds:"Refresh interval (10–60 seconds)",modelsTotal:"Period total and model count",modelsTop:"Top model and cost",modelsFirst:"Top",modelsAfter:"After balances",modelsLast:"Bottom",modelStatsToday:"Today",modelStatsHistory:"Last 90 days",modelStatsCostH:"Cost ranking",modelStatsTokensH:"Token usage",modelStatsHitH:"Cache hit rate",modelStatsHitUnreported:"unreported?",modelStatsHitUnreportedTip:"Zero hits on long calls may mean a relay removed cache fields or broke caching. Hit rate is unknown; all-miss cost is an upper bound. Check via direct API.",modelStatsValueH:"Value · tokens per USD",modelStatsInput:"Input",modelStatsCache:"Cache",modelStatsOutput:"Output",modelStatsEmpty:"No usage data for this period.",modelStatsBlended:"blended {price}/M",modelStatsNote:"Hit rate = cache reads ÷ (reads + uncached input). “Unreported?” suggests missing cache fields, often behind relays; all-miss cost is an upper bound. Unit cost = cost ÷ tokens × 1M; value = tokens ÷ cost. Call-time USD prices apply.",billingClassLabel:"Billing class",billingClassPlan:"Plan subscription",modelStatsLegacy:"Unattributed (early data · billed as recorded)",sessionLineSplit:"This session {amount} (API) · Plan equiv. {planAmount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",costChipPlan:"Cost {amount} (+Plan)",sessionDetailPlan:"Plan subscription quota usage (equiv.) {amount}",planStatsTitle:"Token Plan usage stats (per-1% & full-window estimates)",planStatsEmpty:"No enabled coding-plan quota data yet; enable and successfully refresh a provider under the Quotas tab to see per-1% and full-window usage estimates here.",planStatsWindow:"Window",planStatsPercent:"Used %",planStatsLocal:"This period actual (local ledger)",planStatsPer1:"Per 1% quota ≈",planStatsFull:"Full window (100%) ≈",planStatsResets:"resets {time}",planStatsMethodSample:"sample delta",planStatsMethodLive:"current usage ratio",planStatsMethodNone:"not enough samples",planStatsMethodSampleAt:"{method} (as of {time})",planStatsConfidenceLow:"low reading precision",planStatsCurveTitle:"Plan usage curves (aggregated from sample intervals)",planStatsDaily:"Daily",planStatsWeekly:"Weekly",planStatsMonthly:"Monthly",planStatsCurveEmpty:"Not enough sample intervals yet (at least two successful refreshes with a percent change); the curves will take shape with continued use.",planStatsBarTip:"{date}: full-window est. ≈ {full} (per 1% ≈ {per1}) · actual {tokens} / {cost} · {intervals} sample interval(s)",planStatsNote:"Amounts are catalog-price equivalents; plans use quota, budget counts API only. Estimates cover dsh calls; server used % covers the account. Per-1% and full-window estimates use sample deltas (short spans have limited precision). 5h rolls; week/month use local dates.",catalogDisplayLabel:"Show directly in Cost settings",catalogDisplayHint:"Controls direct display in Cost settings; mounting and billing stay unchanged. Hidden models remain editable in this catalog.",priceTableDisplayHint:"Toggle direct display per model below. DeepSeek appears by default; mounted third-party models stay in the extended catalog.",catalogCustomModels:"Custom models",priceMatchLabel:"Auto-match unknown model names",priceMatchAuto:"Auto (strip suffix / prefix / family similarity)",priceMatchExact:"Exact match only",priceMatchNote:"Match order: exact → manual → strip version → prefix → family. Unmatched DeepSeek uses default price; other providers stay unpriced.",unmatchedTitle:"Recently seen models without a price hit",unmatchedHint:"No price matched, including fallback. Choose an entry to bill manually; “Default price” uses DeepSeek defaults. Local models (lmstudio/ollama/vLLM) cost zero until assigned.",overrideTargetDefault:"DeepSeek default price",overrideRemove:"Remove",overrideTargetLocal:"Local model (zero cost)",matchedTitle:"Models matched this month",matchedHint:"These models matched automatically. Choose another entry or “Local model (zero cost)”. Tokens still count; historical costs become zero. Overrides move to the manual list.",matchedKeepAuto:"Keep auto match",overrideNone:"No manual match overrides.",mountedSuffix:"Mounted (billed)",flatInput:"Input",flatCached:"Cached",flatOutput:"Output",deepseekMountedHeader:"DeepSeek price table (mounted)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet Token Plan",codingPlanVolcengine:"Volcano Ark Coding Plan",codingPlanQwen:"Qwen Token Plan (qianwenai.com)",codingPlanMimo:"Xiaomi MiMo Token Plan",mimoWindowPlan:"Plan credits",mimoWindowCompensation:"Compensation",codingPlanWindowBalance:"Balance",qwenSource:"Quota source",qwenSourceLocal:"Local estimate",qwenSourceCli:"Official CLI",qwenSourceBailian:"Bailian CLI",qwenCliNote:"Install @qianwenai/qianwen-cli on the DSH host and run qianwen auth login as the same OS user.",qwenBailianNote:"Bailian CLI: install bailian-cli on the DSH host and run bl auth login --console as the same OS user.",qwenPlanCreditsLabel:"Monthly credits quota (personal Lite 50K / Standard 500K; see your plan page)",qwenPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",qwenRatesLabel:"Credits rate overrides (optional; credits deducted per 1M tokens; empty = built-in table)",qwenRatesModelPlaceholder:"Model name, e.g. qwen3.8-max-preview",qwenRatePlaceholder:"rate",qwenRate_input:"Input",qwenRate_cachedInput:"Cached input",qwenRate_output:"Output",qwenRateDraftNote:"Enter all three positive rates to save automatically; clear all to restore the built-in table.",qwenRatesAdd:"Add",qwenLocalNote:"Local estimate; console is authoritative. Counts qwen, qwen-tokenplan, qianwen-tokenplan, qwen-token-plan and qianwen-token-plan (also llm- prefix). Excludes API and pay-as-you-go qianwen. Add rates for other models.",scnetPlanCreditsLabel:"Monthly credits quota for local estimates (Basic 60,000 / Standard 240,000 / Pro 600,000)",scnetPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",scnetLocalNote:"Accepts console snapshots up to 24h old; otherwise estimates from local records and official rates. Other tools and unlisted models are excluded. Check the console.",volcengineAccessKeyIdLabel:"Volcengine AccessKey ID",volcengineSecretAccessKeyLabel:"Volcengine SecretAccessKey",volcengineNote:"Volcano Ark uses AK/SK HMAC (not ARK_API_KEY). IAM needs ArkReadOnlyAccess + BillingCenterReadOnlyAccess. Enter AccessKeyID/SecretAccessKey or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Credentials only go to open.volcengineapi.com.",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}h",countdownHourMinute:"{h}h {m}m",countdownMinute:"{m}m",nextOffPeakIn:"Off-peak in {time}",nextPeakIn:"Peak in {time}",peakSummary:"Peak hours (UTC): {windows}; effective: {time}. {status}",noPeakWindows:"No peak windows configured. {status}",unknown:"unknown",cardToday:"Today",cardMonth:"This month",cardTotal:"All time",cardTotalSub:"Since the ledger was created · Calls {calls}",externalUsage:"External usage",combinedUsage:"DSH + external total",externalStale:"External snapshot has not been updated for 24 hours",externalHistory:"Recent daily records",cardsFootnote:"Amounts use the latest snapshot (2s debounce, flush on exit) and may lag the official bill by minutes. Tokens include input, output, cache and reasoning. Reasoning is not billed separately; reconcile by amount.",timezoneHint:"Today/month use host timezone {host}, unlike this browser ({browser}). Calls after local midnight may land on the previous day and affect reconciliation. Run dsh in your local timezone to align.",todaySessions:"Today's sessions",historyExpandHint:"Click a date row to expand its session details",historySessionsLoading:"Loading session details…",historyNoSessions:"No session details for this day (early data or session logs cleaned)",historySessionsError:"Failed to load session details",sessionRankTitle:"By session (all history)",sessionRankHint:"All historical sessions, not grouped by date; sort and row count are switchable",sessionRankEmpty:"No session data yet",sessionRankLoading:"Loading session ranking…",sessionRankError:"Failed to load session ranking",sessionRankLimit:"Rows",showSessionIdLabel:"Show session IDs in session lists",cardsTogglePlanTotal:"Include plan totals",cardsTogglePlanTotalHint:"When on, every amount shows total equivalent cost including plan subscriptions; off (default) counts real-money API channels only",hideOfficialBalanceLabel:"Hide official account balance (balance UI removed from sidebar and settings)",hideTodayCostLabel:"Hide today's cost (today's amount removed from sidebar, budget details and overview card)",sessionRankSort:"Sort",sessionSortCostDesc:"Cost high→low",sessionSortCostAsc:"Cost low→high",sessionSortTimeDesc:"Time new→old",sessionSortTimeAsc:"Time old→new",sessionSortRecent:"Recent order",history:"History",usageTitle:"Token usage stats",usageTotal:"All-time {tokens} tokens · input {input} · cache {cache} · output {output} · {calls} calls",usageDay:"{date}: {tokens} tokens (input {input} · cache {cache} · output {output}) · {calls} calls · {cost}",usageEmpty:"No history yet — daily usage will accumulate here",usageSectionLabel:"Usage",usagePositionLabel:"Token usage stats position",usagePositionCost:"Cost settings",usagePositionGeneral:"General settings",usagePositionSection:"Own section (Usage)",displaySettings:"Display settings",tabOverview:"Overview",tabQuotas:"Quotas",tabUsage:"Usage",tabPricing:"Pricing",tabDisplay:"Display",historyDataTitle:"History data",positionLabel:"Session cost display position",positionDock:"Below the composer",positionHeader:"Session title bar",off:"Off",quotaStripGroup:"Quota strip above the input",quotaStripEnable:"Enable the quota strip (one row above the input box)",quotaStripShowBudget:"Strip includes budget used %",quotaStripShowGo:"Strip includes the Go quota",quotaStripShowPlans:"Strip includes coding plan quotas",quotaStripNote:"Hover a chip for reset times and the last refresh; the strip hides itself when there is no quota data.",quotaStripGuideTitle:"New: quota strip above the input",quotaStripGuideBody:"Show budget and OpenCode Go/coding-plan percentages above the input box. Enable now? Change it anytime in Settings → Display.",quotaStripGuideOn:"Enable the strip",quotaStripGuideOff:"Not now",clickToRefresh:"Click to refresh now",balanceClickGuideTitle:"New: click the balance box to refresh",balanceClickGuideBody:"Click a sidebar balance or plan box to refresh. It pulses while loading; on failure it keeps the old value and shows the reason on hover.",balanceClickGuideOk:"Got it",sidebarLabel:"Today cost display",sidebarOn:"Sidebar footer",currencyLabel:"Currency",currencyCny:"Chinese Yuan (CNY)",currencyUsd:"US Dollar (USD)",currencyEur:"Euro (EUR)",symbolLabel:"Currency symbol",rateLabel:"Exchange rate (1 USD = ? target currency)",decimalsLabel:"Decimal places",balanceDisplayLabel:"Balance display position",balanceSidebar:"Main sidebar",balanceSettings:"Settings page",balanceBoth:"Both",refreshIntervalLabel:"Balance refresh interval (minutes)",peakEnabledLabel:"Use DeepSeek peak-hour prices",peakNoticeLabel:"Prominent notice during peak hours (sidebar budget box, today's cost; previewed in the Settings peak panel)",badgeNote:"Session cost uses call-time prices, including peak and historical rates. Input, output, cache reads and writes are separate; configured cache-write and long-context rates apply.",priceTableTitle:"Price table (USD / 1M tokens)",pricingCurrencyLabel:"Official price currency",pricingCurrencyUsd:"USD (English official page)",pricingCurrencyCny:"CNY (Chinese official page)",pricingCurrencyNote:"Selects the official pricing-page language. Sync then recalculates history in the background; sessions without full logs keep their earlier basis.",priceTableNote:"Call-time prices: Flash changes Sep 10 04:00 UTC; V4 Pro uses Flash prices from Sep 14 04:00 UTC. Earlier calls retain history. Mon–Fri peaks 01–04 and 06–10 UTC cost 2×; weekends and Chinese public holidays are off-peak. Cache writes use hit rates.",datedPriceNote:"Current rates are shown here. Editing cancels any future scheduled change for this entry; earlier historical rates are retained.",defaultModelId:"default (fallback for unmatched models)",newModelPlaceholder:"New model ID (e.g. deepseek-v4-pro)",addModel:"Add model",dataSync:"Data & sync",saving:"Saving…",autoSaveFailed:"Auto-save failed: {message}",autoSavedAt:"Auto-saved {time}",autoSaveHint:"Settings are auto-saved",confirmFetch:"Overwrite the price table with prices from the official docs?",apply:"Apply",cancel:"Cancel",syncFromDocs:"Sync prices from official docs",syncScopeNote:"Official sync updates DeepSeek prices (including peak rates). Third-party prices (z-ai/Kimi/Qwen/Volcano) follow releases; edit in the extended catalog or model matching.",confirmReset:"Clear all history?",importLegacy:"Import pre-install history",confirmImportLegacy:"Confirm import? Replays all session logs and only fills dates/sessions missing from the ledger; existing records are untouched.",legacyImportFailed:"Failed to import pre-install history: {message}",legacyImportNote:"Pre-install history imports at first launch; rerun after copying old logs. Costs use current prices. Deleted logs cannot replay; sessions spanning installation exclude earlier usage.",confirmClear:"Confirm clear",clearAllHistory:"Clear all history",lastSync:"Last sync: {time}",neverSynced:"Never (bundled prices)",source:"; Source: {source}",sourceOfficial:"Official docs",sourceBundled:"Bundled",languageLabel:"Language",localeAuto:"Follow browser (auto)",localeZh:"Simplified Chinese",localeEn:"English",sectionLabel:"Cost",rpcFailed:"{method} call failed",rpcSyncFailed:"Sync call failed",rpcBalanceFailed:"Balance refresh call failed"}};function qa(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function W(t){return t==="zh"||t==="en"?t:qa()}function K(t){const s=t==="zh"?Te.zh:Te.en;return(o,a)=>{let n=s[o]??Te.en[o]??o;if(a)for(const i of Object.keys(a))n=n.split("{"+i+"}").join(String(a[i]));return n}}const qe={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustomRange"};function ce(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function fe(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&ce(s,"object"),t}function de(t,s){return(typeof t!="number"||!Number.isFinite(t))&&ce(s,"number"),t}function Se(t,s){return typeof t!="string"&&ce(s,"string"),t}const Ke=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function Qt(t,s=!1){return t===null||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([o,a])=>s?o.length>0&&["plan","api"].includes(a):["auto","plan","api"].includes(a)))}function Ft(t,s){return typeof t!="boolean"&&ce(s,"boolean"),t}const Ye=(t,s,o)=>Object.fromEntries(s.map(a=>[a,o(t[a])]));function _t(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const a of Object.keys(t)){const n=t[a];if(n===null||typeof n!="object"||Array.isArray(n))continue;const i=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:0;o[a]={...Ye(n,["input","output","cacheRead","cacheWrite","reasoning","cost"],i),apiCost:n.apiCost===void 0?i(n.cost):i(n.apiCost)}}return o}function Wt(t,s){fe(t,s);const o={reasoning:t.reasoning===void 0?0:de(t.reasoning,s+".reasoning"),apiCost:t.apiCost===void 0?void 0:de(t.apiCost,s+".apiCost"),byModel:_t(t.byModel,s+".byModel"),byProviderModel:_t(t.byProviderModel,s+".byProviderModel")};for(const a of["input","output","cacheRead","cacheWrite","calls","cost"])o[a]=de(t[a],s+"."+a);return o}function ct(t,s){return{...Wt(t,s),id:Se(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:""}}function be(t,s){const o={...Wt(t,s),date:Se(t.date,s+".date"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||ce(s+".sessions","array"),o.sessions=t.sessions.map((a,n)=>ct(a,s+".sessions["+n+"]"))),o}function zt(t,s,o=["cacheWrite","reasoning"]){const a={};for(const n of["cacheHit","cacheMiss","output"])a[n]=de(t[n],s+"."+n);for(const n of o)t[n]!==void 0&&(a[n]=de(t[n],s+"."+n));return a}function dt(t,s){fe(t,s);const o=zt(t,s);for(const a of["offPeak","peak","legacyBase","longContext"])t[a]!==void 0&&(o[a]=zt(t[a],s+"."+a,["cacheWrite","reasoning","aboveInputTokens"]));t.legacy!==void 0&&(o.legacy=Ft(t.legacy,s+".legacy")),t.rateHistory!==void 0&&((!Array.isArray(t.rateHistory)||t.rateHistory.length>16)&&ce(s+".rateHistory","price history"),o.rateHistory=t.rateHistory.map((a,n)=>((!a||typeof a.before!="string"||!Number.isFinite(Date.parse(a.before)))&&ce(s+".rateHistory","dated price"),{...dt({...a,rateHistory:void 0},s+".rateHistory."+n),before:a.before})));for(const a of["billingMode","sourceUrl","checkedAt","notes"])typeof t[a]=="string"&&(o[a]=t[a]);return o}function Ha(t,s){const o=n=>n==null?void 0:{...n.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:n.enabled===!0,label:typeof n.label=="string"?n.label:"",labelEn:typeof n.labelEn=="string"?n.labelEn:"",display:Ke(n.display,["sidebar","settings","off"],"both"),unit:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",convertToDisplayCurrency:n.convertToDisplayCurrency===!0,refreshMinutes:typeof n.refreshMinutes=="number"&&Number.isFinite(n.refreshMinutes)?n.refreshMinutes:15,request:n.request&&typeof n.request=="object"?n.request:{url:""},extract:n.extract&&typeof n.extract=="object"?n.extract:{},allowedHosts:Array.isArray(n?.allowedHosts)?n.allowedHosts.filter(i=>typeof i=="string"):[]};fe(t,s);const a={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const n of Object.keys(t.prices.models))a[n]=dt(t.prices.models[n],s+".prices.models."+n);return{locale:t.locale==="zh"||t.locale==="en"||t.locale==="auto"?t.locale:"auto",position:t.position==="header"||t.position==="off"?t.position:"dock",sidebar:t.sidebar!==!1,showSessionId:t.showSessionId===!0,hideOfficialBalance:t.hideOfficialBalance===!0,hideTodayCost:t.hideTodayCost===!0,showTotalWithPlan:t.showTotalWithPlan===!0,sidebarSimple:t.sidebarSimple===!0,sidebarSimplePromptSeen:t.sidebarSimplePromptSeen===!0,sidebarModels:Object.fromEntries(Object.entries(Dt).map(([n,i])=>[n,t.sidebarModels?.[n]??i])),codexQuotaEnabled:t.codexQuotaEnabled===!0,includeSubagentCost:t.includeSubagentCost===!0,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(n=>typeof n=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:de(t.decimals,s+".decimals"),exchangeRate:de(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((n,i)=>({start:de(n.start,s+".peakWindows["+i+"].start"),end:de(n.end,s+".peakWindows["+i+"].end")})):[],peakHolidays:Array.isArray(t.peakHolidays)?t.peakHolidays.filter(n=>typeof n=="string"):[],peakNotice:t.peakNotice!==!1,peakAlertEnabled:t.peakAlertEnabled!==!1,peakAlertAhead:Number.isFinite(t.peakAlertAhead)&&t.peakAlertAhead>=1&&t.peakAlertAhead<=30?t.peakAlertAhead:2,peakAlertTarget:t.peakAlertTarget==="peak"||t.peakAlertTarget==="offpeak"?t.peakAlertTarget:"both",peakAlertPosition:t.peakAlertPosition==="center"?"center":"corner",peakAlertWebNotify:t.peakAlertWebNotify===!0,peakStyle:t.peakStyle==="classic"?"classic":"compact",priceMatch:t.priceMatch==="exact"?"exact":"auto",priceOverrides:(()=>{const n={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[i,l]of Object.entries(t.priceOverrides))typeof i=="string"&&typeof l=="string"&&(n[i]=l);return n})(),priceTableDisplay:(()=>{const n={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[i,l]of Object.entries(t.priceTableDisplay))typeof i=="string"&&(n[i]=l===!0);return n})(),codingPlans:(()=>{const n={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const i of Object.keys(t.codingPlans)){const l=t.codingPlans[i];l===null||typeof l!="object"||Array.isArray(l)||(n[i]={enabled:l.enabled===!0,display:l.display==="sidebar"||l.display==="both"||l.display==="off"?l.display:"settings",refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?l.refreshMinutes:15,apiKey:typeof l.apiKey=="string"?l.apiKey:"",...i==="minimax"?{baseUrl:typeof l.baseUrl=="string"?l.baseUrl:""}:{},...i==="qwen"?{quotaSource:["cli","bailian"].includes(l.quotaSource)?l.quotaSource:"local"}:{},...typeof l.planCredits=="number"&&Number.isFinite(l.planCredits)&&l.planCredits>0?{planCredits:l.planCredits}:{},...typeof l.planStart=="string"?{planStart:l.planStart}:{},...l.rates!==null&&typeof l.rates=="object"&&!Array.isArray(l.rates)?{rates:l.rates}:{},...typeof l.accessKeyId=="string"?{accessKeyId:l.accessKeyId}:{},...typeof l.secretAccessKey=="string"?{secretAccessKey:l.secretAccessKey}:{}})}return n})(),prices:{models:a,default:dt(t.prices?.default??{cacheHit:0,cacheMiss:0,output:0},s+".prices.default"),providers:t.prices?.providers&&typeof t.prices.providers=="object"?t.prices.providers:{},currency:typeof t.prices?.currency=="string"&&t.prices.currency.length>0?t.prices.currency:void 0},historyDays:de(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:Se(t.fetchedAt,s+".fetchedAt"),priceSource:typeof t.priceSource=="string"?t.priceSource:"bundled",budget:{enabled:t.budget?.enabled===!0,amount:typeof t.budget?.amount=="number"&&Number.isFinite(t.budget.amount)?t.budget.amount:100,period:t.budget?.period==="day"||t.budget?.period==="all"||t.budget?.period==="custom"?t.budget.period:"month",customStart:typeof t.budget?.customStart=="string"?t.budget.customStart:null,customEnd:typeof t.budget?.customEnd=="string"?t.budget.customEnd:null,detail:t.budget?.detail!==!1},balance:{display:Ke(t.balance?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.balance?.refreshMinutes=="number"&&Number.isFinite(t.balance.refreshMinutes)?t.balance.refreshMinutes:5,showProgressBar:t.balance?.showProgressBar===!0,budgetCap:typeof t.balance?.budgetCap=="number"&&Number.isFinite(t.balance.budgetCap)&&t.balance.budgetCap>0?t.balance.budgetCap:null,clickHintSeen:t.balance?.clickHintSeen===!0},goQuota:{enabled:t.goQuota?.enabled!==!1,display:Ke(t.goQuota?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.goQuota?.refreshMinutes=="number"&&Number.isFinite(t.goQuota.refreshMinutes)?t.goQuota.refreshMinutes:15,apiKey:typeof t.goQuota?.apiKey=="string"?t.goQuota.apiKey:"",main:t.goQuota?.main==="weekly"||t.goQuota?.main==="monthly"?t.goQuota.main:"rolling",detail:t.goQuota?.detail!==!1},customBalance:o(t.customBalance),gatewayQuotas:(()=>{const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(n)?n.slice(0,4).filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).map(l=>({id:typeof l.id=="string"?l.id.slice(0,48):"",type:"cliproxyapi",label:typeof l.label=="string"?l.label.slice(0,80):"",baseURL:typeof l.baseURL=="string"?l.baseURL:"",enabled:l.enabled!==!1,display:Ke(l.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?Math.min(1440,Math.max(1,Math.floor(l.refreshMinutes))):15,includeProviders:Array.isArray(l.includeProviders)?[...new Set(l.includeProviders.filter(r=>typeof r=="string").map(r=>r.toLowerCase()).filter(r=>pt.includes(r)))]:pt,allowedHosts:Array.isArray(l.allowedHosts)?l.allowedHosts.filter(r=>typeof r=="string").slice(0,16):[],allowInsecureHttp:l.allowInsecureHttp===!0,antigravityOnlyGemini:l.antigravityOnlyGemini===!0,keyVar:typeof l.keyVar=="string"?l.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(i=>i!==null&&typeof i=="object").slice(0,8).map(o).filter(Boolean);const n=o(t.customBalance);return n?[n]:[]})(),corner:{enabled:t.corner?.enabled===!0,goRolling:t.corner?.goRolling!==!1,goWeekly:t.corner?.goWeekly!==!1,goMonthly:t.corner?.goMonthly!==!1,budget:t.corner?.budget!==!1},quotaStrip:{enabled:t.quotaStrip?.enabled===!0,budget:t.quotaStrip?.budget!==!1,go:t.quotaStrip?.go!==!1,plans:t.quotaStrip?.plans!==!1,promptSeen:t.quotaStrip?.promptSeen===!0},usage:{position:t.usage?.position==="general"||t.usage?.position==="section"?t.usage.position:"cost"},barDirections:(()=>{const n=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},i=(l,r)=>n[l]==="remaining"||n[l]==="used"?n[l]:r;return{balance:i("balance","remaining"),budget:i("budget","used"),go:i("go","used"),plan:i("plan","used")}})(),planBilling:{providers:Qt(t.planBilling?.providers),models:Qt(t.planBilling?.models,!0)}}}const He=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Ce=t=>He(t)??0,Ia={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},Ua={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},Gt=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function ut(t,s){return fe(t,s),{status:t.status==="ok"||t.status==="error"?t.status:"off",message:typeof t.message=="string"?t.message:"",fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:0}}function ja(t,s){return{...ut(t,s),currency:typeof t.currency=="string"?t.currency:"",totalBalance:Ce(t.totalBalance),grantedBalance:Ce(t.grantedBalance),toppedUpBalance:Ce(t.toppedUpBalance)}}function mt(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&ce(s,"object"),{percent:Ce(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function Qa(t,s){return{...ut(t,s),rolling:mt(t.rolling,s+".rolling"),weekly:mt(t.weekly,s+".weekly"),monthly:mt(t.monthly,s+".monthly")}}function Kt(t,s){return{...ut(t,s),label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:Ce(t.remaining),maxBudget:He(t.maxBudget),spend:He(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const Fa=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),_a=new Set(["off","loading","ok","partial","stale","error"]),pt=["antigravity","claude","codex","kimi","xai","workbuddy"],Yt={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function Wa(t,s){fe(t,s);const o=(l,r="")=>typeof l=="string"?l:r,a=l=>He(l),n=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{id:o(l.id),label:o(l.label),...a(l.percent)===null?{}:{percent:a(l.percent)},resetsAt:o(l.resetsAt),periodHours:a(l.periodHours),scope:o(l.scope)}:null,i=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{unit:o(l.unit,"credits"),used:a(l.used),remaining:a(l.remaining),limit:a(l.limit),fetchedAt:o(l.fetchedAt),packages:Array.isArray(l.packages)?l.packages.filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)).map(r=>({id:o(r.id),label:o(r.label),used:a(r.used),remaining:a(r.remaining),limit:a(r.limit),startsAt:o(r.startsAt),resetsAt:o(r.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:_a.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:a(t.fetchedAt)??0,attemptedAt:a(t.attemptedAt)??0,serverVersion:o(t.serverVersion),keyConfigured:t.keyConfigured===!0,keySource:o(t.keySource,"none"),accounts:Array.isArray(t.accounts)?t.accounts.filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).slice(0,16).map(l=>({id:o(l.id),provider:o(l.provider,"unknown"),label:o(l.label,"unknown"),status:Fa.has(l.status)?l.status:"unknown",message:o(l.message),plan:o(l.plan),windows:Array.isArray(l.windows)?l.windows.map(n).filter(Boolean):[],credits:i(l.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(l=>typeof l=="string").slice(0,32):[]}}function za(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};if(t.providers!==null&&typeof t.providers=="object"&&!Array.isArray(t.providers))for(const[o,a]of Object.entries(t.providers)){if(a===null||typeof a!="object"||Array.isArray(a))continue;const n={},i={};if(a.windows!==null&&typeof a.windows=="object"&&!Array.isArray(a.windows))for(const[l,r]of Object.entries(a.windows))r===null||typeof r!="object"||Array.isArray(r)||(n[l]={...Ye(r,["percent","localTokens","localCost","sampleCount"],Ce),...Ye(r,["sampleAt","per1Tokens","per1Cost","fullTokens","fullCost"],He),resetsAt:typeof r.resetsAt=="string"?r.resetsAt:"",method:r.method==="sample"||r.method==="live"?r.method:"none",confidence:r.confidence==="high"||r.confidence==="low"?r.confidence:null});if(a.intervals!==null&&typeof a.intervals=="object"&&!Array.isArray(a.intervals))for(const[l,r]of Object.entries(a.intervals))Array.isArray(r)&&(i[l]=r.filter(u=>u!==null&&typeof u=="object"&&!Array.isArray(u)).map(u=>Ye(u,["t0","t1","tokens","cost","pct","per1Tokens","per1Cost"],Ce)));s[o]={windows:n,intervals:i}}return{generatedAt:Ce(t.generatedAt),providers:s}}function Vt(t,s){return fe(t,s),{today:be(t.today,s+".today"),month:be(t.month,s+".month"),total:be(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?Ia:ja(t.balance,s+".balance"),goQuota:t.goQuota==null?Ua:Qa(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?Gt():Kt(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,a)=>Kt(o,s+".customBalances["+a+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,a)=>Wa(o,s+".gatewayQuotas["+a+"]")):[],customVarStatus:t.customVarStatus!==null&&typeof t.customVarStatus=="object"&&!Array.isArray(t.customVarStatus)?Object.fromEntries(Object.entries(t.customVarStatus).filter(([,o])=>o!==null&&typeof o=="object").map(([o,a])=>[o,{configured:a.configured===!0,source:typeof a.source=="string"?a.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:za(t.planStats),history:Array.isArray(t.history)?t.history.map((o,a)=>be(o,s+".history["+a+"]")):[],externalUsage:t.externalUsage&&Array.isArray(t.externalUsage.sources)?{fetchedAt:Number(t.externalUsage.fetchedAt)||0,stale:t.externalUsage.stale===!0,sources:t.externalUsage.sources.map(o=>({source:String(o.source),today:be(o.today,s+".external.today"),month:be(o.month,s+".external.month"),total:be(o.total,s+".external.total"),history:(o.history??[]).map(a=>be(a,s+".external.history"))})),combined:Object.fromEntries(["today","month","total","history"].map(o=>[o,o==="history"?(t.externalUsage.combined.history??[]).map(a=>be(a,s+".external.history")):be(t.externalUsage.combined[o],s+".external."+o)]))}:null,config:Ha(t.config,s+".config"),reconcile:t.reconcile===null||t.reconcile===void 0?void 0:{ok:t.reconcile.ok===!0,message:typeof t.reconcile.message=="string"?t.reconcile.message:""},priceCatalog:t.priceCatalog!==null&&typeof t.priceCatalog=="object"&&!Array.isArray(t.priceCatalog)?t.priceCatalog:null,meta:{now:typeof t.meta?.now=="number"?t.meta.now:Date.now(),timezoneOffsetMinutes:typeof t.meta?.timezoneOffsetMinutes=="number"?t.meta.timezoneOffsetMinutes:0,timezone:typeof t.meta?.timezone=="string"?t.meta.timezone:"",dayKey:typeof t.meta?.dayKey=="string"?t.meta.dayKey:"",monthKey:typeof t.meta?.monthKey=="string"?t.meta.monthKey:""}}}function Ga(t,s){fe(t,s);const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=Vt(t.state,s+".state")),o}function se(t){return{parse:t}}const ft=se(Vt),Ka=se(t=>fe(t,"patch")),Ya=se(Ga),Jt=se(t=>Se(t,"provider")),Va=se(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&ce("index","0-7 integer"),t}),Ja=se(t=>Se(t,"date")),$a=se(t=>fe(t,"day")),Za=se(t=>(Number.isFinite(Number(t))||ce("limit","number"),Number(t))),$t=se(t=>Se(t,"sort")),Xa=se(t=>fe(t,"topSessions")),Zt=se(t=>Se(t,"target")),en=se(t=>Se(t,"value")),Ae=(t,s)=>({mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:s,create:()=>s}),ie=(t,s,o,a=!1)=>({name:t,wire:t,source:"json",codec:Ae(s,o),...a?{acceptsUndefined:!0}:{}}),tn={package:"dsh-cost-meter",descriptors:[{method:"getState",result:Ae("CostState",ft)},{method:"updateConfig",parameters:[ie("patch","ConfigPatch",Ka)],result:Ae("CostState",ft)},{method:"fetchPrices"},{method:"refreshBalance"},{method:"refreshGoQuota"},{method:"refreshCustomBalance",parameters:[ie("index","CustomBalanceIndex",Va,!0)]},{method:"refreshCodingPlan",parameters:[ie("provider","CodingPlanProvider",Jt)]},{method:"refreshGatewayQuota",parameters:[ie("sourceId","GatewayQuotaSourceId",se(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&ce("sourceId","gateway source id"),t}),!0)]},{method:"resetHistory",result:Ae("CostState",ft)},{method:"importLegacyHistory"},{method:"getDaySessions",parameters:[ie("date","DayKey",Ja)],result:Ae("DayRecord",$a)},{method:"getSessionCost",parameters:[ie("sessionId","SessionId",Jt)],result:Ae("SessionCost",se(t=>({own:ct(t.own,"own"),subagents:ct(t.subagents,"subagents"),found:Ft(t.found,"found"),subagentCount:de(t.subagentCount,"subagentCount")})))},{method:"getTopSessions",parameters:[ie("limit","SessionLimit",Za),ie("sort","SessionSort",$t,!0),ie("dir","SessionSortDir",$t,!0)],result:Ae("TopSessions",Xa)},{method:"setCredential",parameters:[ie("target","CredentialTarget",Zt),ie("value","CredentialValue",en)]},{method:"clearCredential",parameters:[ie("target","CredentialTarget",Zt)]}].map(t=>({id:"dsh-cost-meter#costMeter/"+t.method,service:"costMeter",namespace:"costMeter",invocation:{kind:"direct"},parameters:[],result:Ae("FetchPricesResult",Ya),...t}))};function an(t,s){const o=s?.models??{};return typeof t=="string"&&t.length>0&&o[t]!==void 0?o[t]:s?.default??{cacheHit:0,cacheMiss:0,output:0}}function Ie(t){if(t===null||typeof t!="object")return;const s=l=>{const r=t[l];return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0},o=s("cacheMiss")??s("input")??0,n={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},i=s("reasoning");return i!==void 0&&(n.reasoning=i),s("cacheWrite")!==void 0&&(n.cacheWrite=s("cacheWrite")),n}function nn(t){const s=Ie(t);if(s===void 0)return null;for(const o of["offPeak","peak","legacyBase"]){const a=Ie(t[o]);a!==void 0&&(s[o]=a)}return Number.isFinite(t.longContext?.aboveInputTokens)&&t.longContext.aboveInputTokens>0&&(s.longContext={...Ie(t.longContext),aboveInputTokens:t.longContext.aboveInputTokens}),Array.isArray(t.rateHistory)&&(s.rateHistory=t.rateHistory.slice(0,16).map(o=>{const a={...Ie(o),before:o.before};for(const n of["offPeak","peak"]){const i=Ie(o[n]);i!==void 0&&(a[n]=i)}return a})),s}function Ve(t,s=Date.now()){if(!t||!Number.isFinite(s)||!Array.isArray(t.rateHistory))return t;let o=null,a=1/0;for(const l of t.rateHistory){const r=Date.parse(l.before);s<r&&r<a&&(o=l,a=r)}if(!o)return t;const{before:n,...i}=o;return{...t,...i}}const bt=Date.parse("2026-08-22T16:00:00Z");function Xt(t){if(!Number.isFinite(t)||t<bt)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const a=o===6?s:s-1;return{start:Math.max(a*864e5-8*36e5,bt),end:(a+2)*864e5-8*36e5}}function ea(t,s){if(!Number.isFinite(t)||t<bt||!Array.isArray(s))return null;const o=Math.floor((t+8*36e5)/864e5);return s.includes(new Date(o*864e5).toISOString().slice(0,10))?{start:o*864e5-8*36e5,end:(o+1)*864e5-8*36e5}:null}const sn=(t,s)=>ea(t,s)??Xt(t);function Je(t,s,o,a){if(!Array.isArray(o)||o.length===0||sn(t,a)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(i=>{const l=Number(i.start),r=Number(i.end);return!Number.isFinite(l)||!Number.isFinite(r)?!1:l<r?n>=l&&n<r:n>=l||n<r})}const on=Date.parse("2026-08-16T16:00:00Z");function ta(t,s,o){const a=Ve(t,s)??{cacheHit:0,cacheMiss:0,output:0},n=l=>({cacheHit:l.cacheHit,cacheMiss:l.cacheMiss,output:l.output,reasoning:l.reasoning??0,...l.cacheWrite===void 0?{}:{cacheWrite:l.cacheWrite},...l.longContext===void 0?{}:{longContext:l.longContext}});if(Number.isFinite(s)&&s<on){const l=a.legacyBase;return n(l===void 0?a:l)}if(o?.enabled!==!0)return n(a);const i=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(Je(s,i,o.windows,o.holidays)){const l=a.peak;return n(l===void 0?a:l)}if(i!==void 0&&s>=i){const l=a.offPeak;return n(l===void 0?a:l)}return n(a)}function aa(t,s){const o=Math.max(0,Number(t.input)||0),a=Math.max(0,Number(t.output)||0),n=Math.max(0,Number(t.cacheRead)||0),i=Math.max(0,Number(t.cacheWrite)||0),l=Math.max(0,Number(t.reasoning)||0);return s.longContext&&o+n+i>s.longContext.aboveInputTokens&&(s=s.longContext),(o*s.cacheMiss+a*s.output+n*s.cacheHit+i*(s.cacheWrite??s.cacheHit)+l*(s.reasoning??0))/1e6}function na(t,s,o){const a=Number(t);if(!Number.isFinite(a)||a<0||a===0)return 0;if(s!=="CNY")return a;const n=Number(o);return!Number.isFinite(n)||n<=0?a:a/n}function te(t,s){const o=t?.barDirections,a=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return a;const n=o[s];return n==="remaining"||n==="used"?n:a}function ue(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),a=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:a,label:a}}const sa=(t,s)=>t.toFixed(s).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1");function oe(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",a=Number(s?.decimals),n=Math.max(0,Math.min(10,Number.isFinite(a)?Math.floor(a):2));let i=n;return t>0&&t<Math.pow(10,-n)&&(i=n+2),o+sa(t,i)}function Y(t,s){const o=Number(s?.exchangeRate),a=t*(Number.isFinite(o)&&o>0?o:1);return oe(a,s)}function I(t){const s=Math.max(0,Number(t)||0),o=a=>a>=100?String(Math.round(a)):String(Math.round(a*10)/10);return s<1e3?String(Math.round(s)):s>=999500?o(s/1e6)+"M":s<1e6?o(s/1e3)+"K":o(s/1e6)+"M"}function re(t){return String(t??"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/([^)]*)/g," ").replace(/[^a-z0-9]+/g,"")}function Be(t,s){if(typeof t!="string"||t.length===0)return null;const o=Array.isArray(s)?s.filter(k=>typeof k=="string"&&k.length>0):[];if(o.length===0)return null;const a=k=>String(k).toLowerCase().replace(/[-@]\d{4}-?\d{2}-?\d{2}$/,"").replace(/[-@]v\d+(\.\d+)*$/,""),n=o.find(k=>k===t);if(n!==void 0)return n;const i=re(t);if(i.length===0)return null;const l=o.find(k=>re(k)===i);if(l!==void 0)return l;let r=null,u=0;for(const k of o){const b=re(k);if(!(b.length<4||b===i)&&i.includes(b)&&b.length>u){const v=i.indexOf(b);if(/^\d{1,2}$/.test(i.slice(v+b.length)))continue;r=k,u=b.length}}if(r!==null)return r;const d=a(t),c=o.find(k=>a(k)===d);if(c!==void 0)return c;let f=null;for(const k of o){const b=a(k);if(b.length===0||b===d)continue;const v=d.slice(b.length);if(d.startsWith(b)&&/^[-_./:]/.test(v)){if(/^\d{1,2}$/.test(v.replace(/^[-_./:]+/,"")))continue;(f===null||a(f).length<b.length)&&(f=k)}}if(f!==null)return f;const m=k=>a(k).split(/[-_./:]+/).filter(Boolean),p=m(t);if(p.length<2)return null;let g=null,x=0;for(const k of o){const b=m(k);let v=0;for(;v<p.length&&v<b.length&&p[v]===b[v];)v+=1;v<p.length&&v<b.length&&/^\d+$/.test(p[v])&&/^\d+$/.test(b[v])||v>=2&&v===b.length&&v<p.length&&p.slice(v).every(S=>/^\d{1,2}$/.test(S))||v>=2&&v<p.length&&v<b.length&&(/^\d{1,2}$/.test(p[v])&&/^[a-z]/.test(b[v])||/^\d{1,2}$/.test(b[v])&&/^[a-z]/.test(p[v]))||v>=2&&(v>x||v===x&&g!==null&&k.length<g.length)&&(g=k,x=v)}return g}const ln=new Set(["lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),rn=["lmstudio:","lmstudio/","ollama:","ollama/","jan:","jan/","gpt4all:","gpt4all/","koboldcpp:","koboldcpp/","llamacpp:","llamacpp/","llama-cpp:","llama-cpp/","localai:","localai/","vllm:","vllm/","sglang:","sglang/","tabbyapi:","tabbyapi/","lmdeploy:","oobabooga/","text-generation-webui/","llama-server:","gguf:","local:"];function cn(t,s){if(typeof t=="string"&&ln.has(t))return!0;const o=typeof s=="string"?s.toLowerCase():"";return rn.some(a=>o.startsWith(a))}function gt(t,s,o){const a=o?.prices??{},n=o?.priceMatch==="exact"?"exact":"auto",i=o?.priceOverrides&&typeof o.priceOverrides=="object"?o.priceOverrides:{};let l=String(t??"").trim().toLowerCase();l.startsWith("llm-")&&(l=l.slice(4)),l===""&&(l="deepseek");let r=l,u=s;const d=i[l+":"+s];if(d==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof d=="string"&&d.length>0){const m=d.indexOf(":");if(m>0&&d.slice(m+1).length>0?(r=d.slice(0,m).trim().toLowerCase(),u=d.slice(m+1)):u=d,r==="deepseek"&&u==="__default__")return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}if(cn(r,u))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(r==="deepseek"||r.includes("deepseek")){const m=a.models??{},p=m[u]!==void 0?u:n==="auto"?Be(u,Object.keys(m)):null;if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0};if(n==="auto"){let g=null,x=-1,k="flat";for(const[b,v]of Object.entries(a.providers??{})){const S=v?.models??{},w=Be(u,Object.keys(S));if(w===null||S[w]?.unpriced===!0)continue;const y=(w===u||re(w)===re(u)?1e3:0)+re(w).length;y>x&&(g=S[w],x=y,k=S[w]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(g!==null)return{entry:g,priced:!0,billingMode:k,matched:!0}}return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}const c=a.providers?.[r]?.models??{},f=c[u]!==void 0?u:n==="auto"?Be(u,Object.keys(c)):null;if(f!==null)return{entry:c[f],priced:c[f]?.unpriced!==!0,billingMode:"flat",matched:!0};if(n==="auto"){const m=a.models??{},p=Be(u,Object.keys(m));if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0};let g=null,x=-1,k="flat";for(const[b,v]of Object.entries(a.providers??{})){if(b===r)continue;const S=v?.models??{},w=Be(u,Object.keys(S));if(w===null||S[w]?.unpriced===!0)continue;const y=(w===u||re(w)===re(u)?1e3:0)+re(w).length;y>x&&(g=S[w],x=y,k=S[w]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(g!==null)return{entry:g,priced:!0,billingMode:k,matched:!0}}if(l!=="deepseek"&&!l.includes("deepseek")&&typeof d=="string"&&d.length>0&&!d.includes(":")){const m=a.models??{},p=m[d]!==void 0?d:n==="auto"?Be(d,Object.keys(m)):null;if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function dn(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,a=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&a===0}function $e(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:la(t,s).total}function ht(t){if(t===null||typeof t!="object")return 0;const s=Number(t.cost)||0,o=t.apiCost===void 0||t.apiCost===null?s:Number(t.apiCost);return Number.isFinite(o)&&o>=0?Math.min(o,s):s}function _(t,s){return s!==null&&typeof s=="object"&&s.showTotalWithPlan===!0?Number(t?.cost)||0:ht(t)}const un={go:["go","zen","opencode","opencode-go"],qwen:["qwen","qwen-tokenplan","qianwen-tokenplan","qwen-token-plan","qianwen-token-plan"],scnet:["scnet","scnet-tokenplan","scnet-token-plan"],mimo:["mimo","xiaomimimo","mimo-token-plan","xiaomi-token-plan","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","xiaomi-token-plan-ams"]},oa=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","mimo","go"];function mn(t){const s=String(t??"").trim().toLowerCase().replace(/^llm-/,"");if(s.length===0)return null;for(const[o,a]of Object.entries(un))if(a.includes(s))return o;return oa.includes(s)?s:null}function pn(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const a of oa)a!=="go"&&o[a]?.enabled===!0&&s.add(a);return t?.goQuota?.enabled===!0&&s.add("go"),s}function fn(t,s,o){const a=String(t??"").trim().toLowerCase();if(a.length>0&&a!=="deepseek"&&!a.includes("deepseek"))return!1;const n=re(s);if(n.length===0)return!1;const i=o?.prices,l=i?.models??{};for(const r of Object.keys(l))if(re(r)===n)return!1;for(const r of Object.values(i?.providers??{}))for(const u of Object.keys(r?.models??{}))if(re(u)===n)return!0;return!1}function Ue(t,s,o){let a=mn(t);if(a===null&&fn(t,s,o)&&(a="go"),a===null)return"api";const n=o?.planBilling?.models;if(n!==null&&typeof n=="object"){const l=n[t+":"+s];if(l==="plan"||l==="api")return l;const r=n[a+":"+s];if(r==="plan"||r==="api")return r}const i=o?.planBilling?.providers?.[a];return i==="plan"||i==="api"?i:pn(o).has(a)?"plan":"api"}function la(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows,holidays:s.peakHolidays},a=Date.now(),n=t.byProviderModel??t.byModel??{};let i=0,l=0;for(const f of Object.keys(n)){const m=f.indexOf(":"),p=m>0?f.slice(0,m):"deepseek",g=m>0?f.slice(m+1):f,x=gt(p,g,s);if(x.priced){const k=aa(n[f],ta(nn(x.entry),a,{...o,enabled:x.billingMode==="deepseek-peak"&&o.enabled})),b=na(k,x.billingMode==="deepseek-peak"&&s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);i+=b,Ue(p,g,s)==="api"&&(l+=b)}}const r={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const f of Object.keys(n))r.input+=n[f].input??0,r.output+=n[f].output??0,r.cacheRead+=n[f].cacheRead??0,r.cacheWrite+=n[f].cacheWrite??0,r.reasoning+=n[f].reasoning??0;const u={input:Math.max(0,(t.input??0)-r.input),output:Math.max(0,(t.output??0)-r.output),cacheRead:Math.max(0,(t.cacheRead??0)-r.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-r.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-r.reasoning)},d=aa(u,ta(an("default",s.prices),a,o)),c=na(d,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return i+=c,l+=c,{total:i,api:l}}function ia(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const a of Object.keys(o)){const n=a.indexOf(":"),i=n>0?a.slice(0,n):"deepseek",l=n>0?a.slice(n+1):a;if(Ue(i,l,s)==="plan")return!0}return!1}function yt(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function ra(t,s){if(t?.apiCost!==void 0)return ht(t);if(!ia(t,s))return $e(t,s);let o=0;for(const[a,n]of Object.entries(t.byProviderModel??{})){if(!Number.isFinite(n.cost))return la(t,s).api;const i=a.indexOf(":");Ue(a.slice(0,i),a.slice(i+1),s)==="plan"&&(o+=n.cost)}return Math.max(0,$e(t,s)-o)}function kt(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),a=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(a>0?":"+String(a).padStart(2,"0"):"")}function bn(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const a=-new Date().getTimezoneOffset();if(a===o)return null;const n=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:n?n+" ("+kt(o)+")":kt(o),browserLabel:kt(a)}}function gn(t){let s=t;const o=new Set;return{getSnapshot:()=>s,subscribe:a=>(o.add(a),()=>{o.delete(a)}),set:a=>{if(a!==s){s=a;for(const n of[...o])n()}}}}const{createElement:e,Fragment:q,useState:L,useEffect:X,useRef:we}=Ee;function De({target:t,configured:s,source:o,t:a,api:n,placeholder:i,disabled:l}){const[r,u]=L(""),[d,c]=L(!1),[f,m]=L(null),p=l===!0||d,g=async()=>{const k=r.trim();if(!(k.length===0||p)){c(!0),m(null);try{const b=await n.setCredential(t,k);u(""),m({kind:"ok",text:b?.message??a("credentialSave")})}catch(b){m({kind:"err",text:String(b?.message??b)})}finally{c(!1)}}},x=async()=>{if(!p){c(!0),m(null);try{const k=await n.clearCredential(t);u(""),m({kind:"ok",text:k?.message??a("credentialClear")})}catch(k){m({kind:"err",text:String(k?.message??k)})}finally{c(!1)}}};return e("div",{className:"cm-field"},e("input",{className:"cm-input",type:"password",value:r,placeholder:typeof i=="string"?i:"",disabled:p,autoComplete:"off",onChange:k=>u(k.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:g,disabled:p||r.trim().length===0},a(d?"credentialSaving":"credentialSave")),s===!0?e("button",{className:"cm-btn small",onClick:x,disabled:p},a("credentialClear")):null),e("span",{className:"cm-hint"},s===!0?a("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):a("credentialNotConfigured")),e("span",{className:"cm-hint"},a("credentialInputHint")),Et(f))}function hn({pending:t,t:s}){return!Array.isArray(t)||t.length===0?null:e("div",{className:"cm-msg err"},e("div",null,s("secretMigrationPending")),e("div",null,t.join("、")))}function Ze({size:t=16,className:s}){return e("svg",{width:t,height:t,className:s,viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e("path",{d:"M4 4H12A2 2 0 0 1 14 6V11.5A2 2 0 0 1 12 13.5H4A2 2 0 0 1 2 11.5V6A2 2 0 0 1 4 4ZM4 5.3H12A0.7 0.7 0 0 1 12.7 6V11.5A0.7 0.7 0 0 1 12 12.2H4A0.7 0.7 0 0 1 3.3 11.5V6A0.7 0.7 0 0 1 4 5.3Z",fill:"currentColor",fillRule:"evenodd"}),e("path",{d:"M3.3 5.3H12.7V7.1H3.3Z",fill:"currentColor"}),e("path",{d:"M8 2.8A1.3 1.3 0 1 0 8 5.4A1.3 1.3 0 1 0 8 2.8Z",fill:"currentColor"}))}function ca(t,s){const o=we(!1),a=we(""),n=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(i=>String(i??0)).join("|"):"";X(()=>{if(!o.current){o.current=!0,a.current=n;return}if(n===""||n===a.current)return;a.current=n;const i=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(i)},[n])}function yn(t,s,o,a){const n=u=>["input","output","cacheRead","cacheWrite"].reduce((d,c)=>d+(u?.[c]??0),0),i=s?.found&&n(s.own)>=n(t)?s.own:t;if(!o||!s?.subagentCount)return i;const l=s.subagents,r={...i};for(const u of["input","output","cacheRead","cacheWrite","reasoning","cost"])r[u]=(i?.[u]??0)+(l?.[u]??0);r.apiCost=ra(i,a)+ht(l);for(const u of["byModel","byProviderModel"]){r[u]={...i?.[u]};for(const[d,c]of Object.entries(l?.[u]??{})){const f={...r[u][d]};for(const m of["input","output","cacheRead","cacheWrite","reasoning","cost"])f[m]=(f[m]??0)+(c[m]??0);delete f.apiCost,r[u][d]=f}}return r}function da(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?.(r=>r)?.state,a=o?.config,[n,i]=L(null);ca(t,s),X(()=>{if(!t.sessionId||!t.api?.getSessionCost)return;let r=!0,u=!1;const d=async()=>{if(!u){u=!0;try{const f=await t.api.getSessionCost(t.sessionId);r&&i({id:t.sessionId,include:a?.includeSubagentCost===!0,value:f})}catch{}finally{u=!1}}};d();const c=a?.includeSubagentCost===!0?setInterval(d,1e4):null;return()=>{r=!1,c!==null&&clearInterval(c)}},[t.sessionId,o?.meta?.now,s,a?.includeSubagentCost]);const l=n&&n.id===t.sessionId&&n.include===(a?.includeSubagentCost===!0)?n.value:null;return{usage:yn(s,l,a?.includeSubagentCost===!0,a),config:a}}function ua(t,s){let o=0,a=$e(t,s);if(s.showTotalWithPlan!==!0&&(t.apiCost!==void 0||ia(t,s))){const n={total:$e(t,s),api:ra(t,s)};o=Math.max(0,n.total-n.api),o>0&&(a=n.api)}return{cost:a,planPart:o}}function kn(t){const{usage:s,config:o}=da(t);if(!s||!o||yt(s)+(s?.output??0)===0)return null;const a=K(W(o.locale)),{cost:n,planPart:i}=ua(s,o),l=[a("sessionCostTitle"),a("sessionDetailTokens",{input:I(s?.input??0),cache:I((s?.cacheRead??0)+(s?.cacheWrite??0)),output:I(s?.output??0)}),a("sessionDetailCache",{read:I(s?.cacheRead??0),write:I(s?.cacheWrite??0)}),a("cost",{amount:Y(n,o)}),...i>0?[a("sessionDetailPlan",{amount:Y(i,o)})]:[]].join("; ");return e($,{label:l,side:"top",delayMs:500},e("div",{className:"cm-chip"},i>0?a("costChipPlan",{amount:Y(n,o)}):a("cost",{amount:Y(n,o)})))}function wn(t){const{usage:s,config:o}=da(t);if(!s||!o)return null;const a=s.input??0,n=(s.cacheRead??0)+(s.cacheWrite??0),i=s.output??0;if(a+n+i===0)return null;const l=K(W(o.locale)),{cost:r,planPart:u}=ua(s,o),d=yt(s)>0?((s.cacheRead??0)/yt(s)*100).toFixed(1)+"%":"—";return e("div",{className:"cm-root"},l(u>0?"sessionLineSplit":"sessionLine",{amount:Y(r,o),planAmount:Y(u,o),hitRate:d,input:I(a),cache:I(n),output:I(i)}))}const xn={USD:"$",CNY:"¥",EUR:"€"};function xe(t,s,o){const a=typeof o=="string"?o.toUpperCase():"",n=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return oe(t,{symbol:xn[a]??n,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function ma(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const a=Number(s?.maxBudget);return Number.isFinite(a)&&a>0?a:null}function vn(t){const s=t.today,o=s?.byProviderModel;if(o===null||typeof o!="object"||Object.keys(o).length===0)return Number(s?.cost)||0;let a=0;for(const[n,i]of Object.entries(o)){const l=n.indexOf(":");let r=l>=0?n.slice(0,l):n;r.startsWith("llm-")&&(r=r.slice(4)),!(r!=="deepseek"&&r!=="deepseek-official")&&(a+=Number(i?.cost)||0)}return a}function pa(t,s,o,a,n=null){const i=o==="official"?vn(t):Number(t.today?.cost)||0;if(o==="custom"){const r=je(s,a,n);if(r==="USD")return i;if(r==="CREDITS")return 0;const u=Number(s?.exchangeRate);return i*(Number.isFinite(u)&&u>0?u:1)}const l=Number(s?.exchangeRate);return i*(Number.isFinite(l)&&l>0?l:1)}function fa({remaining:t,spend:s,todayUsed:o,cap:a}){if(a===null||a<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const n=Math.max(0,Number(t)||0),i=Math.max(0,Number(s)||0),l=Math.max(0,Math.min(i,Number(o)||0)),r=Math.max(0,i-l),u=Math.max(0,Math.min(100,n/a*100)),d=Math.max(0,Math.min(100-u,l/a*100)),c=Math.max(0,Math.min(100-u-d,r/a*100));return{remainingPct:u,todayPct:d,spentPct:c,hasCap:!0,pastSpend:r,today:l}}function wt(t,s,o=null,a=null){const n=o??t.customBalance,i=ma(je(s,n,a)==="CREDITS"?null:s,n),l=Number(n?.remaining)||0,r=Number(n?.spend)||0,u=pa(t,s,"custom",n,a);return{cap:i,...fa({remaining:l,spend:r,todayUsed:u,cap:i})}}function Nn(t,s){const o=t.balance,a=ma(s,null),n=Number(o?.totalBalance)||0,i=pa(t,s,"official",null),l=a!==null?Math.max(0,a-n):0;return{cap:a,...fa({remaining:n,spend:l,todayUsed:i,cap:a})}}function xt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:a,todayPct:n,spentPct:i}=s,l=[];a>0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:a+"%"}})),n>0&&l.push(e("div",{className:"cm-bbox-seg-today",style:{width:n+"%"}})),i>0&&l.push(e("div",{className:"cm-bbox-seg-spent",style:{width:i+"%"}})),l.length===0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const r=o==="used"?[...l].reverse():l;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...r)}function ba(t,s,o,a,n){const i=[t("balanceBarRemaining",{amount:a})];return o.today>0&&i.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&i.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),n!==null&&n>0&&i.push(t("balanceBudgetCapLabel")+": "+s(n)),i.join(" · ")}function Pe(t){const[s,o]=L(!1),[a,n]=L(null);return{busy:s,err:a,run:()=>{s||typeof t!="function"||(o(!0),n(null),Promise.resolve().then(t).catch(l=>{n(l?.message??String(l))}).finally(()=>{o(!1)}))}}}const me=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function ge(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const Sn="https://platform.deepseek.com/usage";function ga(t){return e("a",{className:"cm-bal-link",href:Sn,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},e("svg",{width:14,height:14,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},e("path",{d:"M8 4H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4M11 3h6v6M9 11l8-8"})))}function Cn(t){const{state:s,wide:o,api:a}=t,n=s.balance,i=K(W(s.config?.locale)),l=Pe(a?()=>a.refreshBalance():null);if(!n||n.status==="off")return null;if(n.status==="error")return e($,{label:[i("balanceQueryFailed",{message:n.message||i("unknownError")}),...ge(i,l)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,i("balance")," ",e("span",{className:"cm-num"},i("queryFailed"))):"⚠"));const r=[i("balanceTitle"),i("totalBalance",{amount:xe(n.totalBalance,s.config,n.currency)}),i("grantedToppedUp",{granted:xe(n.grantedBalance,s.config,n.currency),toppedUp:xe(n.toppedUpBalance,s.config,n.currency)}),i("updatedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ge(i,l)].join("; ");return e($,{label:r,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,e("span",{className:"cm-balance-name"},i("balance"),ga(i)),e("span",{className:"cm-num cm-bal-amt"},xe(n.totalBalance,s.config,n.currency)),s.reconcile?.ok===!1?" ⚠":""):e(Ze,{size:16})))}function An(t){const{state:s,wide:o,api:a}=t,n=s.config,i=s.balance,l=K(W(n?.locale)),r=Pe(a?()=>a.refreshBalance():null);if(!i||i.status!=="ok")return null;const u=Nn(s,n),d=xe(i.totalBalance,n,i.currency),c=p=>xe(p,n,i.currency),f=[l("balanceTitle"),ba(l,c,u,d,u.cap),l("grantedToppedUp",{granted:xe(i.grantedBalance,n,i.currency),toppedUp:xe(i.toppedUpBalance,n,i.currency)}),l("updatedAt",{time:i.fetchedAt>0?new Date(i.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ge(l,r)].join("; "),m=e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-balance-name"},e("span",{className:"cm-bbox-label"},l("balance")),ga(l)),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},d)),e(xt,{segments:u,direction:te(n,"balance")}));return e($,{label:f,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(r.busy?" busy":""),...me(r.busy,r.run)},o?m:e("div",{className:"cm-bbox-rail cm-num"},Math.round(u.remainingPct)+"%")))}function vt(t,s){const o=typeof t?.label=="string"?t.label:"",a=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?a||o||"Custom balance":o||a||"自定义余额"}function je(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const a=o?.unit??t?.customBalance?.unit;return["CNY","EUR","USD","CREDITS"].includes(a)?a:["CNY","EUR","CREDITS"].includes(s?.unit)?s.unit:"USD"}function Qe(t,s,o,a){const n=je(s,o,a),i=Number(t);if(!Number.isFinite(i))return"—";const l=s?.currency==="USD"?1:Number(s?.exchangeRate);if((a??s?.customBalance)?.convertToDisplayCurrency===!0&&n==="USD"&&Number.isFinite(l)&&l>0){const c=i*l;return Number.isFinite(c)?oe(c,s):"—"}const r=n==="CREDITS",u=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4)));return(r?"":n==="CNY"?"¥":n==="EUR"?"€":"$")+sa(i,u)+(r?" Credits":"")}function Nt(t,s,o,a,n=null){const i=Qe(t.remaining,s,t,n),l=m=>Qe(m,s,t,n);if(a&&s.balance?.showProgressBar===!0){const m=wt(a,s,t,n);return[ba(o,l,m,i,m.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const r=t.spend!==null?l(t.spend):"—",u=t.maxBudget!==null?l(t.maxBudget):"—",d=je(s,t,n)==="CREDITS"?NaN:Number(s?.balance?.budgetCap),c=Number.isFinite(d)&&d>0?o("balanceBudgetCapLabel")+": "+l(d):"",f=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:i,spend:r,maxBudget:u,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:i});return c?f+" · "+c:f}function Pn(t,s,o,a,n){const i=vt(n??s.customBalance??{},W(s?.locale)),l=Qe(a.remaining,s,a,n),r=wt(t,s,a,n);return{level:"ok",rail:Math.round(r.remainingPct)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},i),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},l)),e(xt,{segments:r,direction:te(s,"balance")}))}}function St(t,s){const o=s?.customBalances??[],a=Array.isArray(t?.customBalances)?t.customBalances:[],n=[];return o.forEach((i,l)=>{if(i?.enabled!==!0||i.display!=="sidebar"&&i.display!=="both")return;const r=a.find(u=>u.index===l)??(a.length===1&&o.length===1?a[0]:null);n.push({index:l,entry:i,snapshot:r})}),n.length===0&&a.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&n.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),n}function Mn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(W(n?.locale)),l=St(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:u,snapshot:d})=>e(Tn,{key:"cb-"+r,state:s,wide:o,api:a,t:i,index:r,entry:u,snapshot:d})))}function Tn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,u=s.config;if(r==null||r.status!=="ok")return null;const d=Pe(a?()=>a.refreshCustomBalance(i):null),c=Pn(s,u,n,r,l),f=[Nt(r,u,n,s,l),...ge(n,d)].join(" · ");return e($,{label:f,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(d.busy?" busy":""),...me(d.busy,d.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function Bn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(W(n?.locale)),l=St(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:u,snapshot:d})=>e(Dn,{key:"cbr-"+r,state:s,wide:o,api:a,t:i,index:r,entry:u,snapshot:d})))}function Dn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,u=s.config,d=r??Gt(i);if(d.status==="off")return null;const c=Pe(a?()=>a.refreshCustomBalance(i):null),f=vt(l??u.customBalance??{},W(u?.locale));if(d.status==="error")return e($,{label:[d.message||n("unknownError"),...ge(n,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:f},f),e("span",{className:"cm-num cm-bal-amt"},n("queryFailed"))):"⚠"));const m=Qe(d.remaining,u,d,l),p=[Nt(d,u,n,s,l),...ge(n,c)].join(" · ");return e($,{label:p,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:f},f),e("span",{className:"cm-num cm-bal-amt"},m)):e(Ze,{size:16})))}function On(t){const o=(t.useCost?t.useCost(g=>g):void 0)?.state;if(!o)return null;const a=o.config,n=K(W(a?.locale)),i=a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},l=o.goQuota,r=a?.goQuota?.enabled!==!1&&l?.status==="ok",u=g=>g!==null&&typeof g?.percent=="number"?Math.round(Math.max(0,Math.min(100,g.percent))):null,d=[];if(a.sidebarModels?.dock){const g=Aa(o,a.sidebarModels.period,n);g.length&&d.push({key:"model-top",text:e(q,null,e("span",{className:"cm-bal-label"},g[0].label),e("span",{className:"cm-bal-amt"},Y(g[0].cost,a))),tip:g[0].label+" "+Y(g[0].cost,a),level:"ok"})}const c=(g,x,k,b)=>{if(!i.enabled||!g||!r)return;const v=u(x);if(v===null)return;const S=typeof x.resetsAt=="string"&&x.resetsAt.length>0?n("goResetAt",{time:new Date(x.resetsAt).toLocaleString()}):"";d.push({key:k,text:n(k)+" "+v+"%",tip:n(b)+": "+v+"%"+(S?" · "+S:""),level:v>=100?"over":v>=80?"warn":"ok"})},f=a?.goQuota?.main==="weekly"||a?.goQuota?.main==="monthly"?a.goQuota.main:"rolling",m=[f,...["rolling","weekly","monthly"].filter(g=>g!==f)],p=g=>g==="rolling"?["goRolling",l?.rolling,"goShortRolling","cornerGoRolling"]:g==="weekly"?["goWeekly",l?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",l?.monthly,"goShortMonthly","cornerGoMonthly"];for(const g of m){const[x,k,b,v]=p(g);c(i[x]===!0,k,b,v)}if(i.enabled&&i.budget===!0){const g=a.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const x=Number(a.exchangeRate),b=(o.budgetUsed??(g.period==="day"?_(o.today,a):g.period==="all"?_(o.total,a):_(o.month,a)))*(Number.isFinite(x)&&x>0?x:1),v=Math.max(0,Number(g.amount)||0),S=v>0?Math.min(999,b/v*100):null;if(S!==null){const w=S>=100?"over":S>=80?"warn":"ok";d.push({key:"budget",text:n("budgetShort")+" "+S.toFixed(1)+"%",tip:n("budgetOf",{period:n(qe[g.period]??"periodMonth")})+" · "+n("usedOf",{used:oe(b,a),amount:oe(v,a)}),level:w})}}}return d.length===0?null:e("div",{className:"cm-corner"},d.map(g=>e($,{key:g.key,label:g.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(g.key==="model-top"?" cm-model-top":"")+(g.level==="ok"?"":" "+g.level)},g.text))))}function Xe(t,s,o){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const a=(m,p)=>{const g=new Date(t);return g.setUTCDate(g.getUTCDate()+m),g.setUTCHours(p,0,0,0),g.getTime()},n=new Set,i=Math.max(12,Math.min(380,(Array.isArray(o)?o.length:0)+7));for(let m=-i;m<=i;m+=1){n.add(a(m,16));for(const p of s){const g=Number(p?.start),x=Number(p?.end);!Number.isFinite(g)||!Number.isFinite(x)||(n.add(a(m,g)),n.add(a(x<=g?m+1:m,x)))}}const l=[...n].sort((m,p)=>m-p).flatMap(m=>{const p=Je(m-1,void 0,s,o),g=Je(m,void 0,s,o);return p===g?[]:[{at:m,intoPeak:g}]});let r=null,u=null;for(const m of l)m.at<=t&&(r===null||m.at>r.at)&&(r=m),m.at>t&&(u===null||m.at<u.at)&&(u=m);const d=ea(t,o),c=d??Xt(t);return c!==null?u===null?null:{inPeak:!1,weekend:d===null,...d?{holiday:!0}:{},prevAtMs:c.start,nextAtMs:u.at,nextIntoPeak:u.intoPeak}:r===null||u===null?null:{inPeak:Je(t,void 0,s,o),weekend:!1,prevAtMs:r.at,nextAtMs:u.at,nextIntoPeak:u.intoPeak}}function et(t,s){if(!t||t.peakNotice===!1||t.peakEnabled!==!0)return null;const o=Date.parse(t.peakEffectiveAt||"");if(Number.isFinite(o)&&s<o)return null;const a=Array.isArray(t.peakWindows)?t.peakWindows:[];return Xe(s,a,t.peakHolidays)}function tt(t){return t.holiday===!0?{short:"holidayShort",chip:"holidayChip",notice:"holidayAllOffPeak"}:t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function he(t,s,o){const a=Math.max(0,t.nextAtMs-s),n=Math.max(1,Math.ceil(a/6e4)),i=Math.floor(n/60),l=n%60;return i>0?l>0?o("countdownHourMinute",{h:i,m:l}):o("countdownHoursOnly",{h:i}):o("countdownMinute",{m:n})}const Ct="cm-peak-alert-preview";let ha=0;function Rn(t){const s=t.useCost?t.useCost(x=>x):void 0,o=s?.state?.config,[a,n]=L(Date.now()),[i,l]=L(null),[r,u]=L(null);if(X(()=>{const x=window.setInterval(()=>n(Date.now()),1e4);return()=>window.clearInterval(x)},[]),X(()=>{const x=k=>{const b=k.detail?.kind==="offpeak"?"offpeak":"peak";u(b);const v=s?.state?.config;if(v?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const S=K(W(v.locale));try{new Notification(S(b==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+S("peakAlertPreviewTag"),{body:S("peakAlertBody",{time:S("countdownMinute",{m:2}),phase:S(b==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(Ct,x),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(Ct,x),window.__cmPeakAlertLive=!1}},[]),X(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const x=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(x===null)return;const k=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",b=x.nextIntoPeak===!0;if(k!=="both"&&k!==(b?"peak":"offpeak"))return;const v=Number(o.peakAlertAhead),S=(Number.isFinite(v)&&v>=1?v:2)*6e4;if(a<x.nextAtMs-S||a>=x.nextAtMs||ha===x.nextAtMs)return;const w=K(W(o.locale));ha=x.nextAtMs;try{new Notification(w(b?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:w("peakAlertBody",{time:he(x,a,w),phase:w(b?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[a]),!o||o.peakEnabled!==!0)return null;let d=null;if(o.peakAlertEnabled===!0){const x=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(x)&&a<x)){const k=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(k!==null){const b=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",v=Number(o.peakAlertAhead),S=(Number.isFinite(v)&&v>=1?v:2)*6e4;(b==="both"||b===(k.nextIntoPeak?"peak":"offpeak"))&&a>=k.nextAtMs-S&&a<k.nextAtMs&&i!==k.nextAtMs&&(d=k)}}}let c=null,f=!1,m=null;if(d!==null)c=d,f=d.nextIntoPeak===!0,m=()=>l(d.nextAtMs);else if(r!==null)c={nextAtMs:a+2*6e4,nextIntoPeak:r==="peak"},f=r==="peak",m=()=>u(null);else return null;const p=K(W(o.locale)),g=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+g+" "+(f?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},p(f?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},p(f?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},p("peakAlertBody",{time:he(c,a,p),phase:p(f?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:m},p("peakAlertBtn"))))}function Ln(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)});return e($,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"}),e("div",{className:"cm-peak-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(l.chip)+" · "+r)))}function En(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)});return e($,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}}),e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"})),e("span",{className:"cm-peak-classic-chip"},o(l.chip)+" · "+r)))}function at(t,s,o){return e(s?.peakStyle==="classic"?En:Ln,{config:s,t:o})}function qn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)}),u=[o(l.notice),r];return e($,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-track"},e("div",{className:"cm-peak-rail-segment cm-peak-rail-high"}),e("div",{className:"cm-peak-rail-segment cm-peak-rail-low"}),e("div",{className:"cm-peak-rail-marker",style:{top:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(l.short))))}function Hn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)}),u=[o(l.notice),r];return e($,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-classic-track"},e("div",{className:"cm-peak-rail-classic-segment peak"}),e("div",{className:"cm-peak-rail-classic-segment off"}),e("div",{className:"cm-peak-rail-classic-marker",style:{top:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(l.short))))}function In(t,s,o){return e(s?.peakStyle==="classic"?Hn:qn,{config:s,t:o})}function ya(t,s,o){const a=t.today,n=s.budget??{enabled:!1,amount:100,period:"month"},i=Number(s.exchangeRate),r=(t.budgetUsed??(n.period==="day"?_(t.today,s):n.period==="all"?_(t.total,s):_(t.month,s)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(n.amount)||0),d=u>0?Math.min(999,r/u*100):null,c=ue(d===null?null:Math.min(100,d),te(s,"budget")),f=_(a,s)*(Number.isFinite(i)&&i>0?i:1),m=u>0?Math.min(999,f/u*100):null,p=n.detail!==!1;return{level:d===null?"ok":d>=100?"over":d>=80?"warn":"ok",rail:c.label===null?"—":Math.round(c.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("budget")),e("span",{className:"cm-bbox-pct cm-num"},c.label===null?"—":c.label.toFixed(1)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:c.width+"%"}})),p?e(q,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},o("todayShare",{amount:Y(_(a,s),s),pct:m===null?"—":m.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:oe(r,s),amount:oe(u,s)}))):null,at(t,s,o))}}function ka(t,s,o){const a=t.goQuota,n=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",i=a[n],l=i!==null&&typeof i?.percent=="number"?Math.max(0,Math.min(100,Number(i.percent)||0)):0,r=p=>p!==null&&typeof p?.percent=="number"?Math.round(Math.max(0,Math.min(100,p.percent)))+"%":"—",u=p=>o(p==="rolling"?"goShortRolling":p==="weekly"?"goShortWeekly":"goShortMonthly"),d=["rolling","weekly","monthly"].filter(p=>p!==n),c=i!==null&&typeof i?.resetsAt=="string"&&i.resetsAt.length>0?o("goResetAt",{time:new Date(i.resetsAt).toLocaleString()}):"",f=s?.goQuota?.detail!==!1,m=ue(l,te(s,"go"));return{level:l>=100?"over":l>=80?"warn":"ok",rail:m.label===null?"—":Math.round(m.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+u(n)),e("span",{className:"cm-bbox-pct cm-num"},m.label===null?"—":Math.round(m.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:m.width+"%"}})),f?e(q,null,e("div",{className:"cm-bbox-line cm-num"},d.map(p=>u(p)+" "+r(a[p])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function Un(t){const{state:s,wide:o}=t,a=s.goQuota,n=K(W(s.config?.locale));if(!a||a.status!=="ok")return null;const i=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(a[i]===null||typeof a[i]?.percent!="number")return null;const l=ka(s,s.config,n),r=[n("goQuotaTitle"),n("goWindowRolling")+": "+(a.rolling===null?"—":Math.round(a.rolling.percent)+"%"),n("goWindowWeekly")+": "+(a.weekly===null?"—":Math.round(a.weekly.percent)+"%"),n("goWindowMonthly")+": "+(a.monthly===null?"—":Math.round(a.monthly.percent)+"%"+(a.monthly!==null&&typeof a.monthly.resetsAt=="string"&&a.monthly.resetsAt.length>0?" · "+n("goResetAt",{time:new Date(a.monthly.resetsAt).toLocaleString()}):"")),n("goQuotaFetchedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e($,{label:r,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(l.level==="ok"?"":" "+l.level)+(o?"":" rail")},o?l.body:e("div",{className:"cm-bbox-rail cm-num"},l.rail)))}function jn(t){return t===null||typeof t!="object"||t.unlimited||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function Fe(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function wa(t,s,o=Date.now()){if(typeof t!="string"||!t)return"";const a=Date.parse(t);if(!Number.isFinite(a))return"";const n=a-o;if(n<=0)return s("resetReached");const i=Math.ceil(n/6e4),l=Math.floor(i/1440),r=Math.floor(i%1440/60),u=i%60;return l>0?s("resetDays",{d:l,h:r}):r>0?s("resetHours",{h:r,m:u}):s("resetMinutes",{m:u})}function _e(t,s,o=Date.now()){const a=wa(t?.resetsAt,s,o);return a?s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})+" ("+a+")":""}function nt(t,s,o){return t===null?"—":o(s==="remaining"?"quotaRemaining":"quotaUsed",{pct:t})}function st(t){const[,s]=L(0),o=()=>s(Date.now());return X(()=>{if(!t)return;const a=setInterval(o,6e4);return()=>clearInterval(a)},[t]),{onMouseEnter:o,onFocus:o}}function We(t,s,o,a){const n=jn(s),i=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",l=ue(n,o),r=s?.unlimited?"∞":l.label===null?"—":l.label+"%";return{level:i,pct:n,text:r,label:l.label,row:e("div",{className:"cm-mm-row"+(i==="ok"?"":" "+i)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:l.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r))}}function xa(t){const{five:s,seven:o,fetchedAt:a,t:n,wide:i,refresh:l,direction:r="used"}=t,u=st(s?.resetsAt),d=wa(s?.resetsAt,n),c=We(n("codingPlanRemain5h"),s,r,n),f=We(n("codingPlanRemain7d"),o,r,n),m=c.level==="over"||f.level==="over"?"over":c.level==="warn"||f.level==="warn"?"warn":"ok",p=(b,v,S)=>{const w=v?.unlimited?n("quotaUnlimited"):nt(S.label,r,n),A=_e(v,n);return b+" "+w+(A?" · "+A:"")},g=[n("codingPlanMinimaxTitle"),p(n("codingPlanRemain5h"),s,c),p(n("codingPlanRemain7d"),o,f),a>0?n("goQuotaFetchedAt",{time:new Date(a).toLocaleTimeString()}):null,...l?ge(n,l):[]].filter(Boolean).join(`
|
|
3
|
-
`),
|
|
4
|
-
`),
|
|
5
|
-
`),
|
|
6
|
-
`),B=w.map((O,G)=>O.text!=null?e("div",{key:G,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},O.name),e("span",{className:"cm-mm-text cm-num"},O.text)):e(q,{key:G},O.view.row)),P=O=>{if(!O.key||O.key==="Enter"||O.key===" "){O.stopPropagation(),O.preventDefault?.();const G=a.accounts[(x+1)%a.accounts.length];Vn(o.id,G.id),d({source:o.id,id:G.id})}},E=m?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:b||x+1}),onClick:P,onKeyDown:P,role:"button",tabIndex:0},`${x+1}/${a.accounts.length} ⇄`):null,h=m?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),E):e("div",{className:"cm-mm-title"},o.label||o.id),U=m&&b?e("div",{className:"cm-gw-sub"},b):null,ee=e(q,null,h,U,...B),ye=w.filter(O=>O.view).map(O=>O.view.label).filter(O=>O!==null),ve=ye.length>0?ye.slice(0,2).map(O=>O+"%").join(" "):w[0].text??"—",D=e("div",{className:"cm-bbox-rail cm-num"},ve);return e($,{label:e("span",{style:{whiteSpace:"pre-line"}},T),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(A==="ok"?"":" "+A)+(i===!1?" rail":"")+(c.busy?" busy":""),...me(c.busy,c.run)},i===!1?e(q,null,D,E):ee))}function $n(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],i=[];for(const l of s.gatewayQuotas?.sources??[]){if(l.enabled===!1||l.display!=="sidebar"&&l.display!=="both")continue;const r=n.find(u=>u.id===l.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||i.push(e(Jn,{source:l,snapshot:r,state:t,wide:o,api:a}))}return i}const Zn={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function Xn(t){const s=t.useCost?t.useCost(g=>g):void 0;Pt(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=L(null),[n,i]=L({}),l=s?.state,r=t.api;if(!l)return null;const u=l.config,d=u.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(d.enabled!==!0)return null;const c=K(W(u?.locale)),f=[];if(d.budget!==!1){const g=u.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const x=Number(u.exchangeRate),b=(l.budgetUsed??(g.period==="day"?_(l.today,u):g.period==="all"?_(l.total,u):_(l.month,u)))*(Number.isFinite(x)&&x>0?x:1),v=Math.max(0,Number(g.amount)||0);if(v>0){const S=Math.min(999,b/v*100),w=S>=100?"over":S>=80?"warn":"ok";f.push({key:"budget",label:c("budgetShort"),level:w,tip:c("budgetOf",{period:c(qe[g.period]??"periodMonth")})+" · "+c("usedOf",{used:oe(b,u),amount:oe(v,u)})+" · "+S.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(ue(Math.min(100,S),te(u,"budget")).width)}]})}}}if(d.go!==!1){const g=l.goQuota;if(u?.goQuota?.enabled!==!1&&g?.status==="ok"){const x=u.goQuota.main==="weekly"||u.goQuota.main==="monthly"?u.goQuota.main:"rolling",k=x==="rolling"?g.rolling:x==="weekly"?g.weekly:g.monthly;if(k!==null&&typeof k=="object"&&typeof k.percent=="number"){const b=Math.max(0,Math.min(100,Math.round(Number(k.percent)||0))),v=b>=100?"over":b>=80?"warn":"ok",S=typeof k.resetsAt=="string"&&k.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(k.resetsAt).toLocaleString()}):"";f.push({key:"go",label:"Go "+c(x==="rolling"?"goShortRolling":x==="weekly"?"goShortWeekly":"goShortMonthly"),level:v,tip:"Go: "+b+"%"+S,segs:[{name:"main",pct:Math.round(ue(b,te(u,"go")).width)}]})}}}if(d.plans!==!1)for(const g of Re){const x=l.codingPlans?.[g.id];if(u.codingPlans?.[g.id]?.enabled!==!0||!x||x.status!=="ok")continue;const k=x.windows!==null&&typeof x.windows=="object"?x.windows:{},b=Object.entries(k);if(b.length===0)continue;const v=Zn[g.id]??g.id,S=[],w=[];let A=0,y=0;for(const[M,T]of b){const B=Mt(M,c),P=typeof T?.resetsAt=="string"&&T.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(T.resetsAt).toLocaleString()}):"",E=T!==null&&typeof T=="object"&&typeof T.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(T.percent)||0))):null;if(w.push(B+" "+(E===null?typeof T?.text=="string"?T.text:"—":E+"%")+P),E===null){S.push({name:M,pct:null,text:typeof T?.text=="string"?T.text:"—"});continue}y>=2||(y+=1,S.push({name:M,pct:Math.round(ue(E,te(u,"plan")).width)}),A=Math.max(A,E>=100?2:E>=80?1:0))}x.fetchedAt>0&&w.push(c("goQuotaFetchedAt",{time:new Date(x.fetchedAt).toLocaleTimeString()})),S.length!==0&&f.push({key:g.id,label:v,level:["ok","warn","over"][A],tip:w.join("; "),segs:S})}const m=u.codexQuotaEnabled===!0&&J.status==="ok"?J.windows.weekly??null:null;if(m!==null&&typeof m.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(m.percent)||0))),x=typeof m.resetsAt=="string"&&m.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(m.resetsAt).toLocaleString()}):"";f.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+x,segs:[{name:"weekly",pct:Math.round(ue(g,te(u,"plan")).width)}]})}if(f.length===0)return null;const p=g=>{o!==null||!r||(a(g),i(x=>({...x,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?At(!0,u.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(x=>{i(k=>({...k,[g]:x?.message??String(x)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},f.map(g=>{const x=o===g.key,k=n[g.key],b=[e("span",{className:"cm-qlabel",key:"l"},g.label)];x?b.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((S,w)=>{w>0&&b.push(e("span",{className:"cm-qsep",key:"sep"+w,"aria-hidden":"true"})),S.pct===null?b.push(e("span",{className:"cm-qtext",key:S.name},S.text)):b.push(e("span",{className:"cm-qseg",key:S.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:S.pct+"%"}})),e("span",null,S.pct+"%")))});const v=[g.tip];return!x&&r&&v.push(c("clickToRefresh")),x&&v.push(c("refreshing")),k&&v.push("⚠ "+c("balanceRefreshFailed",{message:k})),e($,{key:g.key,label:v.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?me(x,()=>p(g.key)):{}},b))}))}const Na="dsh-cost-meter:simple-guide-dismissed";function Tt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Na)==="1"}catch{return!1}}function es(t){const s=t.useCost?t.useCost(p=>p):void 0,o=we(!1),[a,n]=L(!1),[i,l]=L(!1),[r,u]=L(!1),d=s?.state?.config;if(!d||r||Tt(d))return null;const c=K(W(d.locale)),f=()=>{u(!0);try{window.localStorage.setItem(Na,"1")}catch{}},m=async p=>{if(!o.current){o.current=!0,n(!0),l(!1);try{if((await t.api.updateConfig({sidebarSimple:p,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==p)throw new Error;f()}catch{l(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:p=>{p.key==="Escape"&&(p.stopPropagation(),f())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:f},"×")),e("p",null,c("sidebarSimpleBody")),i?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>m(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>m(!0)},c("sidebarSimpleOn"))))}function ts(t){const s=t.useCost?t.useCost(r=>r):void 0,o=we(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Tt(n)||n.quotaStrip?.promptSeen===!0)return null;const i=K(W(n?.locale)),l=r=>{if(o.current===!0)return;o.current=!0;const u=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...u,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":i("quotaStripGuideTitle")},e("h4",null,i("quotaStripGuideTitle")),e("p",null,i("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>l(!1)},i("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>l(!0)},i("quotaStripGuideOn"))))}const Sa="dsh-cost-meter:balance-click-hint-seen",as=()=>{try{return window.localStorage.getItem(Sa)==="1"}catch{return!1}},ns=()=>{try{window.localStorage.setItem(Sa,"1")}catch{}};function ss(t){const s=t.useCost?t.useCost(p=>p):void 0,o=we(!1),[a,n]=L(!1),[i]=L(as),l=s?.state;if(!l)return null;const r=l.config,u=r.balance?.display==="sidebar"||r.balance?.display==="both",d=(r?.customBalances??[]).some(p=>p?.enabled===!0&&(p.display==="sidebar"||p.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Re.some(p=>{const g=r.codingPlans?.[p.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||i||r.balance?.clickHintSeen===!0||!u&&!d&&!c||!Tt(r)||r.quotaStrip?.promptSeen!==!0)return null;const f=K(W(r?.locale)),m=()=>{o.current!==!0&&(n(!0),o.current=!0,ns(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":f("balanceClickGuideTitle")},e("h4",null,f("balanceClickGuideTitle")),e("p",null,f("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:m},f("balanceClickGuideOk"))))}function Bt(t){const{state:s,wide:o}=t,a=s.today,n=s.config,i=K(W(n?.locale)),l=n.budget??{enabled:!1,amount:100,period:"month"},r=Number(n.exchangeRate),d=(s.budgetUsed??(l.period==="day"?_(s.today,n):l.period==="all"?_(s.total,n):_(s.month,n)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),f=c>0?Math.min(999,d/c*100):null,m=f===null?"ok":f>=100?"over":f>=80?"warn":"ok";if(l.enabled===!0){const g=_(a,n),x=g*(Number.isFinite(r)&&r>0?r:1),k=c>0?Math.min(999,x/c*100):null,b=[i("budgetOf",{period:i(qe[l.period]??"periodMonth")}),i("usedOf",{used:oe(d,n),amount:oe(c,n)})+" · "+(f===null?"—":f.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[i("todayShare",{amount:Y(g,n),pct:k===null?"—":k.toFixed(1)+"%"})],i("monthTotal",{month:Y(_(s.month,n),n),total:Y(_(s.total,n),n)})].join("; ");if(t.summary===!0)return e($,{label:b,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(m==="ok"?"":" "+m),tabIndex:0},e("span",null,i("todayBudget",{period:i(qe[l.period]??"periodMonth")})),e("span",{className:"cm-num"},Y(g,n)+" / "+oe(c,n))));const v=ya(s,n,i);return e($,{label:b,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(m==="ok"?"":" "+m)+(o?"":" rail")},o?v.body:e("div",{className:"cm-bbox-rail cm-num"},v.rail)))}const p=[i("todayCostTitle"),i("callsTokens",{calls:a.calls,input:I(a.input),cache:I(a.cacheRead+a.cacheWrite),output:I(a.output)}),i("monthCost",{amount:Y(_(s.month,n),n)}),i("totalCost",{amount:Y(_(s.total,n),n)})].join("; ");return e($,{label:p,side:"right",delayMs:300},e(q,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(q,null,i("today")," ",e("span",{className:"cm-num"},Y(_(a,n),n))):e(Ze,{size:16})),o?at(s,n,i):null))}function os(t){const s=t.useCost?t.useCost(E=>E):void 0;Pt(s?.state?.config?.codexQuotaEnabled===!0);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}ca(t,o);const a=s?.state,n=!!t.wide,i=we(null);if(X(()=>{const E=i.current,h=E?.parentElement;if(!E||!h)return;const U=()=>{n?h.firstElementChild!==E&&h.insertBefore(E,h.firstElementChild):h.lastElementChild!==E&&h.appendChild(E)};U();const ee=new MutationObserver(()=>{E.isConnected&&U()});return ee.observe(h,{childList:!0}),n?(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap=""):(h.style.flexDirection="column",h.style.flexWrap="nowrap",h.style.alignItems="center",h.style.gap="6px"),()=>{ee.disconnect(),n||(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap="")}},[n,a]),!a)return null;const l=a.config,r=K(W(l?.locale)),u=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,c=St(a,l).length>0,f=u&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",m=c&&l.balance?.showProgressBar===!0,p=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",g=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[p]!==null,x=Re.map(E=>E.id).filter(E=>{const h=l.codingPlans?.[E];if(h?.enabled!==!0||h.display!=="sidebar"&&h.display!=="both")return!1;const U=a.codingPlans?.[E];if(U?.status!=="ok")return!1;const ee=U.windows!==null&&typeof U.windows=="object"?U.windows:{};return Object.keys(ee).length>0}),k=x.length>0,b=$n(a,l,n,t.api),v=l.codexQuotaEnabled===!0&&J.status==="ok"&&J.windows.weekly!==null,S=(l.budget??{}).enabled===!0,w=l.sidebar!==!1&&l.hideTodayCost!==!0,A=l.sidebarModels?.enabled===!0;if(!A&&!u&&!c&&!g&&!k&&!v&&!S&&!w&&b.length===0)return null;const y=l.sidebarSimple===!0,M=!y&&n&&l.sidebarStyle==="compact",T=y&&n&&w&&S,B=[];T?B.push(e(Bt,{state:a,wide:n,summary:!0})):y&&n&&w&&B.push(e("div",{className:"cm-simple-summary"},e("span",null,r("today")),e("span",{className:"cm-num"},Y(_(a.today,l),l)))),f?B.push(e(An,{state:a,wide:n,api:t.api})):u&&B.push(e(Cn,{state:a,wide:n,api:t.api})),m?B.push(e(Mn,{state:a,wide:n,api:t.api})):c&&B.push(e(Bn,{state:a,wide:n,api:t.api}));const P=B.length;if(k&&B.push(...x.map(E=>E==="minimax"?e(Qn,{state:a,wide:n,api:t.api}):e(Yn,{id:E,state:a,wide:n,api:t.api}))),B.push(...b),v&&B.push(e(Kn,{state:a,wide:n,api:t.api})),g&&S&&n&&!y){const E=ka(a,l,r),h=ya(a,l,r),U=E.level==="over"||h.level==="over"?"over":E.level==="warn"||h.level==="warn"?"warn":"ok";B.push(e("div",{className:"cm-bbox cm-bbox-pair"+(U==="ok"?"":" "+U)},e("div",{className:"cm-bbox-section"+(E.level==="ok"?"":" "+E.level)},E.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(h.level==="ok"?"":" "+h.level)},h.body)))}else g&&B.push(e(Un,{state:a,wide:n})),S&&!T&&B.push(e(Bt,{state:a,wide:n}));return!S&&w&&!(y&&n)&&B.push(e(Bt,{state:a,wide:n})),y&&n&&w&&B.push(at(a,l,r)),n||B.push(In(a,l,r)),A&&B.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?P:B.length,0,e(ls,{key:"models",state:a,wide:n})),e("div",{ref:i,...y?{tabIndex:0,role:"region","aria-label":r("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(M?" compact":"")+(y?" simple":"")},...B)}const Dt={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Ca="dsh-cost-meter:models-open";function Aa(t,s,o){return Ta(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:Lt(a.key),cost:_(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function ls({state:t,wide:s}){const o={...Dt,...t.config.sidebarModels},a=K(W(t.config.locale)),n=()=>{try{const b=o.remember?window.localStorage.getItem(Ca):null;if(b!==null)return b==="1"}catch{}return o.defaultOpen},[i,l]=L(n),[r,u]=L(o.period);X(()=>u(o.period),[o.period]),X(()=>l(n()),[o.defaultOpen,o.remember]);const d=Aa(t,r,a),c=d.reduce((b,v)=>b+v.cost,0),f=b=>Y(b,t.config),m=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+f(c)+" · "+a("modelsCount",{n:d.length}),p=o.summary==="top"&&d.length?d[0].label+" "+f(d[0].cost):m,g=o.summary==="top"&&d.length?e(q,null,e("span",{className:"cm-bal-label"},d[0].label),e("span",{className:"cm-bal-amt"},f(d[0].cost))):e("span",{className:"cm-bal-label"},p),x=()=>{l(!i);try{o.remember&&window.localStorage.setItem(Ca,i?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:p+" · "+m},s?g:e(Ze,{size:16}));const k=d.slice(0,o.topN);return d.length>o.topN&&k.push(d.slice(o.topN).reduce((b,v)=>{for(const S of["cost","input","output","cacheRead","cacheWrite"])b[S]+=v[S];return b},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(i),title:m,onClick:x},e("span",{className:"cm-caret"+(i?" open":"")}),g),i?e(q,null,e("div",{className:"cm-buttons"},["today","history"].map(b=>e("button",{key:b,type:"button",className:"cm-mstats-tab"+(r===b?" active":""),"aria-pressed":r===b,onClick:()=>u(b)},a(b==="today"?"modelStatsToday":"modelStatsHistory")))),k.length?k.map(b=>e("div",{key:b.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:b.label},b.label),e("span",{className:"cm-num cm-bal-amt"},f(b.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?b.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?b.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+I(b.input)+" · "+a("modelStatsCache")+" "+I(b.cacheRead+b.cacheWrite)+" · "+a("modelStatsOutput")+" "+I(b.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function is({draft:t,setDraft:s,t:o}){const a={...Dt,...t?.sidebarModels},n=(l,r)=>{t&&s({...t,sidebarModels:{...a,[l]:r}})},i=(l,r)=>e("div",{className:"cm-field",key:l},e("label",null,o("models_"+l)),e("select",{className:"cm-input",value:a[l],onChange:u=>n(l,u.target.value)},r.map(([u,d])=>e("option",{key:u,value:u},o(d)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(l=>e("label",{key:l,className:"cm-check"},e("input",{type:"checkbox",checked:a[l],onChange:r=>n(l,r.target.checked)}),o("models_"+l))),i("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),i("summary",[["total","modelsTotal"],["top","modelsTop"]]),i("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(l=>e("div",{key:l,className:"cm-field"},e("label",null,o("models_"+l)),ae({value:a[l]},r=>n(l,Math.max(l==="topN"?1:10,Math.min(l==="topN"?10:60,Math.floor(r))))))))}function ot(t){return e("div",{className:"cm-card"},e("p",{className:"cm-card-title"},t.title),e("div",{className:"cm-card-value cm-num"},t.value),e("p",{className:"cm-card-sub"},t.sub))}function rs({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=d=>Y(_(d,a),a),i=d=>s("callsTokens",{calls:d.calls,input:I(d.input),cache:I(d.cacheRead+d.cacheWrite),output:I(d.output)}),l=(d,c)=>({calls:d.calls+c.calls,input:d.input+c.input,output:d.output+c.output,cacheRead:d.cacheRead+c.cacheRead,cacheWrite:d.cacheWrite+c.cacheWrite,cost:_(d,a)+c.cost,apiCost:_(d,a)+c.cost}),r=(d,c)=>e("tr",{key:d},e("td",null,d),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},I(c.input)),e("td",{className:"num"},I(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},I(c.output)),e("td",{className:"num"},n(c))),u=d=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,d)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((d,c)=>{const f=l(t[d],o.combined[d]);return e(ot,{key:d,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(f),sub:i(f)})})),...o.sources.map(d=>e("details",{key:d.source},e("summary",null,d.source+" · "+s("cardToday")+" "+n(d.today)+" · "+s("cardMonth")+" "+n(d.month)+" · "+i(d.today)),u(["today","month","total"].map((c,f)=>r(s(["cardToday","cardMonth","cardTotal"][f]),d[c]))),e("p",{className:"cm-note"},s("externalHistory")),u(d.history.map(c=>r(c.date,c))))))}const Oe=(t,s,o)=>e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(t),onClick:s},e("span",{className:"cm-caret"+(t?" open":"")}),e("h3",{className:"cm-h"},o));function cs(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,i]=L(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,()=>i(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(ds,{state:s,api:o})):null)}function ds(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,i]=L(null),[l,r]=L({}),[u,d]=L(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const f=p=>{if(n===p){i(null);return}i(p),!(l[p]!==void 0||u.has(p))&&(d(g=>{const x=new Set(g);return x.add(p),x}),o.getDaySessions(p).then(g=>r(x=>({...x,[p]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[p]:"error"}))).finally(()=>d(g=>{const x=new Set(g);return x.delete(p),x})))},m=p=>p.map(g=>e("tr",{key:g.id},Ot(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},I(g.input)),e("td",{className:"num"},I(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},I(g.output)),e("td",{className:"num"},Y(_(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(p=>{const g=e("tr",{key:p.date,className:"cm-row-click",onClick:()=>f(p.date)},e("td",null,(n===p.date?"▾ ":"▸ ")+p.date),e("td",{className:"num"},String(p.calls)),e("td",{className:"num"},I(p.input)),e("td",{className:"num"},I(p.cacheRead+p.cacheWrite)),e("td",{className:"num"},I(p.output)),e("td",{className:"num"},Y(_(p,s.config),s.config)));if(n!==p.date)return[g];const x=l[p.date],k=u.has(p.date)&&x===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):x==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(x)||x.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,m(x)));return[g,e("tr",{key:p.date+"-sessions"},e("td",{colSpan:6},k))]}))))}function us(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,i]=L(!1),[l,r]=L(100),[u,d]=L("cost-desc"),[c,f]=L(null),[m,p]=L(!1),[g,x]=L(!1),k=Ee.useRef(0),b=(A,y)=>{const[M,T]=y==="recent"?["recent","desc"]:y.split("-"),B=++k.current;p(!0),x(!1),o.getTopSessions(A,M,T).then(P=>{B===k.current&&f(Array.isArray(P?.sessions)?P.sessions:[])}).catch(()=>{B===k.current&&x(!0)}).finally(()=>{B===k.current&&p(!1)})},v=()=>{i(A=>{const y=!A;return y&&c===null&&!m&&b(l,u),y})},S=A=>{r(A),(n||c!==null)&&b(A,u)},w=A=>{d(A),(n||c!==null)&&b(l,A)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,v,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:u,onChange:A=>w(A.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(l),onChange:A=>S(Number(A.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),m?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(A=>e("tr",{key:A.date+":"+A.id},e("td",null,A.date),Ot(A,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(A.calls)),e("td",{className:"num"},I(A.input)),e("td",{className:"num"},I((A.cacheRead??0)+(A.cacheWrite??0))),e("td",{className:"num"},I(A.output)),e("td",{className:"num"},Y(_(A,s.config),s.config)))))))):null)}function ms(t){const{state:s}=t,o=K(W(s.config?.locale)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(i=>e("tr",{key:i.id},Ot(i,n,o),e("td",{className:"num"},String(i.calls)),e("td",{className:"num"},I(i.input)),e("td",{className:"num"},I(i.cacheRead+i.cacheWrite)),e("td",{className:"num"},I(i.output)),e("td",{className:"num"},Y(_(i,s.config),s.config)))))))}function Ot(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",i=a.length>0?a:n,l=a.length>0?a+" · "+t.id:t.id;return e("td",{title:l},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},i),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const ps={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function fs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=o?.budget??i.budget,r=Number(i.exchangeRate),d=(s.budgetUsed??(l.period==="day"?_(s.today,i):l.period==="all"?_(s.total,i):_(s.month,i)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),f=l.enabled&&c>0?Math.min(999,d/c*100):null,m=f===null?"ok":f>=100?"over":f>=80?"warn":"ok",p=(k,b)=>{o!==null&&a({...o,budget:{...o.budget??i.budget,[k]:b}})},g=l.period==="custom"?l.customStart+" → "+(l.customEnd??n("periodDay")):null,x=l.enabled&&f!==null?n("budgetStatus",{period:n(qe[l.period]??"periodMonth"),amount:oe(c,i),used:oe(d,i),pct:f.toFixed(1)})+(m==="over"?n("overLimit"):m==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:l.enabled===!0,onChange:k=>p("enabled",k.target.checked)}),e("span",null,n("enableBudget")))),l.enabled?e(q,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(m==="ok"?"":m),style:{width:(f===null?0:Math.min(100,f))+"%"}})),e("div",{className:"cm-budget-line"+(m==="over"?" over":"")+" cm-num"},x),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ae({value:l.amount},k=>p("amount",k))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:l.period,onChange:k=>p("period",k.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),l.period==="custom"?e(q,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:l.customStart??"",onChange:k=>p("customStart",k.target.value===""?null:k.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:l.customEnd??"",onChange:k=>p("customEnd",k.target.value===""?null:k.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function bs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=(c,f)=>{o!==null&&a({...o,[c]:f})},r=o===null?i:{...i,...o},u=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),f=Date.now();if(Number.isFinite(c)&&f<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const m=r.peakWindows??[],p=Xe(f,m,r.peakHolidays);return p===null?n("offPeakActive"):p.holiday===!0?n("holidayAllOffPeak"):p.weekend===!0?n("weekendAllOffPeak"):p.inPeak?n("peakActive"):n("offPeakActive")})(),d=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(W(r.locale)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:u}):n("noPeakWindows",{status:u});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>l("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>l("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>l("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>l("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const f=Number(c.target.value);Number.isInteger(f)&&f>=1&&f<=30&&l("peakAlertAhead",f)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>l("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>l("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{l("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?at(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},d),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>l("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ae(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const i=Number(n);Number.isFinite(i)&&i>=0&&s(i)}})}function Rt(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:i,t:l}=t,r=Ve(o),u=m=>{const p={...Ve(m)};if(Array.isArray(m.rateHistory)){const g=m.rateHistory.filter(x=>Date.parse(x.before)<=Date.now());g.length>0?p.rateHistory=g:delete p.rateHistory}return p},d=(m,p,g)=>{if(g===null){if(a){const M=u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),T={...M[m]??{}};delete T[p];const B={...M};Object.keys(T).length>0?B[m]=T:delete B[m],i({...n,prices:{...n.prices,default:B}});return}const S={...n.prices.models},w=u(S[s]??{cacheHit:0,cacheMiss:0,output:0}),A={...w[m]??{}};delete A[p];const y={...w};Object.keys(A).length>0?y[m]=A:delete y[m],S[s]=y,i({...n,prices:{...n.prices,models:S}});return}const x=Math.max(0,g);if(a){let w={...u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(m==="base")w[p]=x;else{const A={...w[m]??{},[p]:x};w={...w,[m]:A}}i({...n,prices:{...n.prices,default:w}});return}const k={...n.prices.models},b=u(k[s]??{cacheHit:0,cacheMiss:0,output:0});let v={...b};if(m==="base")v[p]=x;else{const S={...b[m]??{},[p]:x};v={...b,[m]:S}}k[s]=v,i({...n,prices:{...n.prices,models:k}})},c=()=>{const m={...n.prices.models};delete m[s],i({...n,prices:{...n.prices,models:m}})},f=(m,p)=>{const g=p==="base"?r:r[p]??null,x=p==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:p},e("span",null,m),ae({value:g?.cacheHit??null,emptyMode:x},k=>d(p,"cacheHit",k)),ae({value:g?.cacheMiss??null,emptyMode:x},k=>d(p,"cacheMiss",k)),ae({value:g?.output??null,emptyMode:x},k=>d(p,"output",k)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(q,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},l("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},l("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},l("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatCached")),e("span",null,l("flatInput")),e("span",null,l("flatOutput"))),f(l("tierBase"),"base"),f(l("tierOffPeak"),"offPeak"),f(l("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},l("datedPriceNote")):null)}const Pa={deepseek:"DeepSeek",openai:"OpenAI",anthropic:"Anthropic",google:"Google Gemini",moonshot:"Moonshot (Kimi)","z-ai":"Z.ai / 智谱",xai:"xAI",alibaba:"阿里云百炼",minimax:"MiniMax",tencent:"腾讯混元",xiaomi:"小米",upstage:"Upstage",nvidia:"NVIDIA",mistral:"Mistral",meta:"Meta",meituan:"美团 LongCat","opencode-go":"OpenCode Go"};function gs(t,s,o="USD"){if(t=Ve(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");const a=i=>(o==="CNY"?"¥":"$")+String(i),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function hs(t){const{state:s,draft:o,setDraft:a,t:n}=t,[i,l]=L(!1),[r,u]=L({}),d=s.priceCatalog;if(d===null||typeof d!="object")return null;const c=o?.prices??s.config.prices,f=o?.priceTableDisplay??s.config.priceTableDisplay??{},m=(y,M)=>{const T=f[y+":"+M];return typeof T=="boolean"?T:y==="deepseek"},p=(y,M,T)=>{o!==null&&a({...o,priceTableDisplay:{...f,[y+":"+M]:T}})},g=(y,M)=>y==="deepseek"?c.models?.[M]!==void 0:c.providers?.[y]?.models?.[M]!==void 0,x=(y,M,T)=>{if(o===null)return;const B=JSON.parse(JSON.stringify(T));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[M]:B}}});return}const P={...o.prices.providers??{}},E=P[y]??{};P[y]={...E,models:{...E.models??{},[M]:B}},a({...o,prices:{...o.prices,providers:P}})},k=(y,M)=>{if(o===null)return;if(y==="deepseek"){const P={...o.prices.models};delete P[M],a({...o,prices:{...o.prices,models:P}});return}const T={...o.prices.providers??{}},B=T[y];if(B!==void 0&&B.models!==void 0){const P={...B.models};delete P[M],T[y]={...B,models:P},a({...o,prices:{...o.prices,providers:T}})}},b=Object.keys(d).sort((y,M)=>y==="deepseek"?-1:M==="deepseek"?1:y.localeCompare(M)),v=y=>Object.values(d[y]).reduce((M,T)=>M+Object.keys(T).length,0),S=new Set(Object.values(d.deepseek??{}).flatMap(y=>Object.keys(y))),w=Object.keys(c.models??{}).filter(y=>!S.has(y)).sort(),A=(y,M,T)=>{const B=g(y,M),P=m(y,M),E=B?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:P,onChange:h=>p(y,M,h.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(B&&!P&&o!==null){const h=y==="deepseek"?e(Rt,{key:M,modelId:M,entry:c.models[M],isDefault:!1,draft:o,setDraft:a,t:n}):e(Da,{key:M,provider:y,modelId:M,entry:c.providers?.[y]?.models?.[M],draft:o,setDraft:a,t:n});return e("div",{key:M,className:"cm-catalog-mounted"},E,h)}return e("div",{key:M,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},M),e("span",{className:"cm-catalog-price"},gs(T,n,y==="deepseek"?c.currency:"USD")),B?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,E,e("button",{className:"cm-btn small",disabled:!B&&T?.unpriced===!0,onClick:()=>B?k(y,M):x(y,M,T)},n(B?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>l(y=>!y)},n(i?"catalogCollapse":"catalogOpen"))),i?e(q,null,e("p",{className:"cm-note"},n("catalogNote")),b.map(y=>{const M=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>u(T=>({...T,[y]:!M}))},e("span",null,(M?"▾ ":"▸ ")+(Pa[y]??y)+" · "+v(y))),M?e(q,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(d[y]).sort().map(T=>e("div",{key:T},e("div",{className:"cm-catalog-family"},T),Object.keys(d[y][T]).sort().map(B=>A(y,B,d[y][T][B])))),y==="deepseek"&&w.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),w.map(T=>A("deepseek",T,null))):null):null)})):null)}const Ma=t=>t==="zen"?"go":t,Lt=t=>{const s=t.indexOf(":");return s<=0?t:Ma(t.slice(0,s).toLowerCase())+t.slice(s)};function Ta(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],i=d=>Number.isFinite(Number(d))&&Number(d)>0?Number(d):0,l=(d,c,f)=>{if(!f||typeof f!="object")return;const m=d[c]??(d[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)m[g]+=i(f[g]);const p=c.indexOf(":");m.apiCost+=i(f.apiCost??(Ue(p>0?c.slice(0,p):"deepseek",p>0?c.slice(p+1):c,s)==="plan"?0:f.cost))},r=d=>{if(!d||typeof d!="object")return{};if(d.byProviderModel&&Object.keys(d.byProviderModel).length)return d.byProviderModel;if(d.byModel&&Object.keys(d.byModel).length)return Object.fromEntries(Object.entries(d.byModel).map(([f,m])=>[f.includes(":")?f:"deepseek:"+f,m]));const c={};for(const f of Array.isArray(d.sessions)?d.sessions:[])if(!(!f||typeof f!="object"))if(f.byProviderModel&&Object.keys(f.byProviderModel).length)for(const[m,p]of Object.entries(f.byProviderModel))l(c,m,p);else l(c,(f.provider||"deepseek")+":"+(f.model||"unknown"),f);return Object.keys(c).length?c:n.some(f=>i(d[f])>0)?{"deepseek:legacy":d}:{}};return(d=>{const c={},f=m=>{for(const[p,g]of Object.entries(m??{}))l(c,p,g)};if(d==="today")f(r(t.today));else{const m=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const p of t.history??[]){const g=Date.parse(p.date+"T00:00:00Z");g<=m&&g>=m-76896e5&&f(r(p))}}return Object.entries(c).map(([m,p])=>{const g=m.indexOf(":"),x=(g>0?m.slice(0,g):"deepseek").toLowerCase(),k=g>0?m.slice(g+1):m,b=p.input+p.output+p.cacheRead+p.cacheWrite+p.reasoning,v=p.cacheRead+p.input;return{label:m==="deepseek:legacy"?o("modelStatsLegacy"):x==="deepseek"||x===""?k:Ma(x)+":"+k,key:m,...p,tokens:b,cls:Ue(x,k,s),hitRate:v>0?p.cacheRead/v:null,cacheUnreported:dn(p),blended:b>0&&p.cost>0?p.cost/b*1e6:null,perUsd:p.cost>0?b/p.cost:null}}).filter(m=>m.tokens>0||m.cost>0)})(a).sort((d,c)=>c.cost-d.cost||c.tokens-d.tokens)}function ys(t){const{state:s,config:o,t:a,initialTab:n}=t,[i,l]=L(n==="history"?"history":"today"),[r,u]=L(!1),d=Ta(s,o,a,i),c=b=>(Math.max(0,Math.min(1,b))*100).toFixed(1)+"%",f=d.reduce((b,v)=>Math.max(b,v.cost),0),m=d.reduce((b,v)=>Math.max(b,v.tokens),0),p=d.reduce((b,v)=>Math.max(b,v.perUsd??0),0),g=(b,v)=>e("button",{className:"cm-mstats-tab"+(i===b?" active":""),onClick:()=>l(b)},v),x=b=>b.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,k=(b,v,S,w,A)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:b},b,A??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+S,style:{width:c(v)}})),e("span",{className:"cm-mstats-val"},w));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(r,()=>u(!r),a("modelStatsTitle"))),r?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},g("today",a("modelStatsToday")),g("history",a("modelStatsHistory"))),d.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(q,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),d.map(b=>e(q,{key:"c:"+b.label},k(b.label,f>0?b.cost/f:0,"cost",Y(b.cost,o),e(q,null,x(b),b.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...d].sort((b,v)=>v.tokens-b.tokens).map(b=>e("div",{className:"cm-mstats-row",key:"t:"+b.label},e("span",{className:"cm-mstats-name",title:b.label},b.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:c(m>0?b.input/m:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:c(m>0?(b.cacheRead+b.cacheWrite)/m:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:c(m>0?(b.output+b.reasoning)/m:0)}})),e("span",{className:"cm-mstats-val"},I(b.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...d].sort((b,v)=>(v.hitRate??-1)-(b.hitRate??-1)).map(b=>e(q,{key:"h:"+b.label},k(b.label,b.hitRate??0,"hit",b.cacheUnreported?a("modelStatsHitUnreported"):b.hitRate===null?"—":(b.hitRate*100).toFixed(1)+"%",b.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...d].sort((b,v)=>(v.perUsd??-1)-(b.perUsd??-1)).map(b=>e(q,{key:"v:"+b.label},k(b.label,p>0?(b.perUsd??0)/p:0,"value",b.perUsd===null?"—":I(b.perUsd)+" tok/$"+(b.blended!==null?" · "+a("modelStatsBlended",{price:"$"+b.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function ks(t,s){return t==="fiveHour"?s==="en"?"5-hour":"5 小时":t==="weekly"?s==="en"?"This week":"本周":t==="monthly"?s==="en"?"This month":"本月":t==="daily"?s==="en"?"Today":"当日":t}function ws(t,s){if(t==="go")return"OpenCode Go";const o=Re.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const Ba=["fiveHour","weekly","monthly","daily"];function xs(t,s){const o=new Map,a=n=>{const i=new Date(n),l=r=>String(r).padStart(2,"0");if(s==="monthly")return i.getFullYear()+"-"+l(i.getMonth()+1);if(s==="weekly"){const r=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(i.getDay()+6)%7);return r.getFullYear()+"-"+l(r.getMonth()+1)+"-"+l(r.getDate())}return i.getFullYear()+"-"+l(i.getMonth()+1)+"-"+l(i.getDate())};for(const n of Object.values(t??{}))for(const i of n??[]){if(i===null||typeof i!="object"||!(i.tokens>0)&&!(i.cost>0))continue;const l=a(Number(i.t1)||Number(i.t0)),r=o.get(l)??{key:l,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(i.tokens)||0,r.cost+=Number(i.cost)||0,r.pct+=Number(i.pct)||0,r.intervals+=1,o.set(l,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,i)=>n.key<i.key?-1:n.key>i.key?1:0)}function vs(t){const{state:s,config:o,t:a}=t,[n,i]=L(!1),[l,r]=L("daily"),u=W(o?.locale),d=s?.planStats,c=d!=null&&typeof d.providers=="object"?d.providers:{},f=Object.keys(c).sort(),m=y=>Y(Number(y)||0,o??s?.config),p=y=>y.method==="none"||y.per1Tokens===null?"—":I(y.per1Tokens)+" tok · "+m(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":I(y.fullTokens)+" tok · "+m(y.fullCost),x=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),k=y=>{let M=x(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(M=a("planStatsMethodSampleAt",{method:M,time:new Date(Number(y.sampleAt)).toLocaleString(u==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(M+=" · "+a("planStatsConfidenceLow")),M},b=([y,M,T])=>e("tr",{key:M+":"+y},e("td",null,ks(y,u)),e("td",{className:"num"},Math.round(T.percent*10)/10+"%"),e("td",{className:"num"},I(T.localTokens)+" tok · "+m(T.localCost)),e("td",{className:"num"},p(T)),e("td",{className:"num"},g(T)),e("td",{className:"num cm-plan-reset"},T.resetsAt.length>0?a("planStatsResets",{time:new Date(T.resetsAt).toLocaleString(u==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},k(T))),v=n?f.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,M])=>({winKey:y,list:M})):[],S=xs(Object.fromEntries(v.map(y=>[y.winKey,y.list])),l),w=S.reduce((y,M)=>Math.max(y,M.fullTokens??0),0),A=(y,M)=>e("button",{key:y,className:"cm-mstats-tab"+(l===y?" active":""),onClick:()=>r(y)},M);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,()=>i(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},f.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(q,null,f.map(y=>{const M=c[y]?.windows??{},T=[...Ba.filter(B=>M[B]!==void 0).map(B=>[B,y,M[B]]),...Object.keys(M).filter(B=>!Ba.includes(B)).map(B=>[B,y,M[B]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},ws(y,a),e("span",{className:"cm-plan-updated"},(()=>{const B=Number(c[y]?.generatedAt)||Number(d?.generatedAt)||0;return B>0?new Date(B).toLocaleTimeString(u==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,T.map(b))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},A("daily",a("planStatsDaily")),A("weekly",a("planStatsWeekly")),A("monthly",a("planStatsMonthly"))),S.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(q,null,[...S].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(w>0?(y.fullTokens??0)/w*100:0).toFixed(1)+"%"}})),e($,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":I(y.fullTokens),per1:y.per1Tokens===null?"—":I(y.per1Tokens),tokens:I(y.tokens),cost:m(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":I(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Da(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:i,t:l}=t,r=c=>{const f={...n.prices.providers??{}},m=f[s]??{};f[s]={...m,models:c},i({...n,prices:{...n.prices,providers:f}})},u=(c,f)=>{if(n===null)return;const m={...(n.prices.providers??{})[s]?.models??{}};m[o]={...m[o]??{},[c]:Math.max(0,f)},r(m)},d=()=>{if(n===null)return;const c={...(n.prices.providers??{})[s]?.models??{}};delete c[o],r(c)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(q,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},l("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:d},l("unmountBtn")))),a?.unpriced===!0?null:e(q,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatInput")),e("span",null,l("flatCached")),e("span",null,l("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ae({value:a?.input??null,emptyMode:"ignore"},c=>u("input",c)),ae({value:a?.cachedInput??null,emptyMode:"ignore"},c=>u("cachedInput",c)),ae({value:a?.output??null,emptyMode:"ignore"},c=>u("output",c)))))}const ze=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Et=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function Ns(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),[u,d]=L(null),c=s.balance,f=s.config,m=s.reconcile,p=(n?.balance??f.balance??{}).reconcile!==!1,g=v=>{n===null||typeof i!="function"||i({...n,balance:{...n.balance??f.balance??{},reconcile:v.target.checked}})},x=async()=>{if(!l){r(!0),d(null);try{const v=await o.refreshBalance();d({kind:v.ok?"ok":"err",text:v.message})}catch(v){d({kind:"err",text:a("balanceRefreshFailed",{message:v?.message??String(v)})})}finally{r(!1)}}},k=v=>xe(v,f,c?.currency),b=c.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:k(c.totalBalance),granted:k(c.grantedBalance),toppedUp:k(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:c.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:x,disabled:l},a(l?"refreshing":"refreshBalance"))),b,m!==void 0&&m.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+m.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:p,onChange:g}),a("reconcileLabel")),Et(u))}function lt(t){const{name:s,enabled:o,saved:a,busy:n,open:i,statusNode:l,configNode:r,errorMsg:u,onToggle:d,onRefresh:c,onRemove:f,onToggleOpen:m,t:p}=t,g=r!=null;return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":p("enable")+": "+s,checked:o===!0,onChange:x=>d(x.target.checked)})),e("div",{className:"cm-quota-name"},g?Oe(i===!0,m,s):e("h3",{className:"cm-h"},s)),f?e("button",{className:"cm-btn small",onClick:f},p("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:c,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?p("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?p("quotaRefreshReady"):p("refresh")},p(n===!0?"refreshing":"refresh"))),l,g&&i===!0?e("div",{className:"cm-collapse-body"},r):null,u!=null?e("div",{className:"cm-msg "+u.kind},u.text):null)}function it(t,s){const[o,a]=L(!1),[n,i]=L(null),l=we(!1);return[o,n,async()=>{if(!l.current){l.current=!0,a(!0),i(null);try{const u=await s();i({kind:u.ok?"ok":"err",text:u.message})}catch(u){i({kind:"err",text:t("syncFailed",{message:u?.message??String(u)})})}finally{l.current=!1,a(!1)}}}]}const Ss=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},Oa=(t,s,o,a,n,i=s)=>{if(typeof o?.percent!="number")return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const l=Math.max(0,Math.min(100,Number(o.percent)||0)),r=ue(l,a),u=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),u?e("span",{className:"cm-go-reset"},u):null)};function Cs(t){const{state:s,api:o,t:a,entry:n,index:i,canRemove:l,onPatch:r,onRemove:u}=t,d=n.adapter==="aliyun",[c,f]=L(!1),m=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[p,g]=L(m),[x,k]=L(()=>(n.allowedHosts??[]).join(", ")),[b,v]=L({}),S=we(!1),w=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(R=>R.index===i)??null,M=n.enabled===!0,T=()=>{f(R=>!R)};X(()=>{c&&!S.current&&(g(m()),k((n.allowedHosts??[]).join(", ")),v({})),S.current=c},[c]);const B=(R,V)=>r({[R]:V}),P=(R,V)=>r({request:{...n.request??{},[R]:V}}),E=d?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(R=>typeof R=="string"?[...R.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(V=>V[1]):[]))],h=(R,V)=>{g(N=>({...N,[R]:V}));try{const N=R==="body",H=N&&!V.trim()?void 0:JSON.parse(V);if(!N&&(H===null||typeof H!="object"||Array.isArray(H)))throw new Error("invalid");if(R==="headers"&&Object.values(H).some(Q=>typeof Q!="string"))throw new Error("invalid");v(Q=>({...Q,[R]:""})),R==="extract"?B(R,H):P(R,N?H===void 0?void 0:V:H)}catch{v(N=>({...N,[R]:a("customBalanceInvalidJson")}))}},U=(R,V,N,H)=>!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(V)),H&&e("span",{className:"cm-hint"},a(H)),e("textarea",{className:"cm-input",rows:N,value:p[R],onChange:Q=>h(R,Q.target.value)}),b[R]?e("span",{className:"cm-hint err"},b[R]):null),ee=R=>{k(R);const V=R.split(/[\s,;]+/).map(N=>N.trim()).filter(N=>N.length>0);B("allowedHosts",V)},[ye,ve,D]=it(a,()=>(w.customBalances??[])[i]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(i)),O=y!==null&&y.status==="ok"?e(q,null,w.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(xt,{segments:wt(s,w,y,n),direction:te(w,"balance")}),e("div",{className:"cm-bal-line"},Nt(y,w,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:Qe(y.remaining,w,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),G=e(q,null,e("p",{className:"cm-note"},a(d?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:je(w,y,n)!=="USD",onChange:R=>B("convertToDisplayCurrency",R.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([R,V])=>e("div",{key:R,className:"cm-field"},e("label",null,a(V)),e("input",{className:"cm-input",value:n[R]??"",onChange:N=>B(R,N.target.value)}))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:R=>B("unit",R.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:R=>B("display",R.target.value)},...ze(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ae({value:n.refreshMinutes??15},R=>B("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(R)))))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:R=>P("method",R.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:R=>P("url",R.target.value)})),U("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&U("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),E.length>0?e(q,null,!d&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),E.map(R=>e(De,{key:"cb-var-"+R,target:"customVar:"+R,configured:(s.customVarStatus?.[R]?.configured??!1)===!0,source:s.customVarStatus?.[R]?.source??"",t:a,api:o,placeholder:"{{"+R+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:x,placeholder:"api.example.com, relay.example.org",onChange:R=>ee(R.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),U("extract","customBalanceExtract",8)));return e(lt,{name:`#${i+1} · `+(vt(n,W(w?.locale))||a("customBalanceTitle")),enabled:M,saved:JSON.stringify(n)===JSON.stringify(w.customBalances?.[i])?w.customBalances[i]:null,busy:ye,open:c,statusNode:O,configNode:G,errorMsg:ve,onToggle:R=>B("enabled",R),onRefresh:D,onRemove:l?u:null,onToggleOpen:T,t:a})}function Ra({config:t,draft:s,setDraft:o,t:a,api:n}){const i=s?.goQuota??t.goQuota,l=(r,u)=>{s&&o({...s,goQuota:{...i,[r]:u}})};return e(q,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,u])=>e("div",{key:r,className:"cm-field"},e("label",null,a(u)),e("select",{className:"cm-input",value:i[r],onChange:d=>l(r,d.target.value)},r==="display"?ze(a):["rolling","weekly","monthly"].map((d,c)=>e("option",{key:d,value:d},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ae({value:i.refreshMinutes},r=>l("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function As(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),u=s.goQuota,d=s.config,c=n?.goQuota?.enabled??d.goQuota?.enabled??!0,f=(w,A)=>{n!==null&&i({...n,goQuota:{...n.goQuota??d.goQuota,[w]:A}})},[m,p,g]=it(a,()=>o.refreshGoQuota()),x=d.goQuota?.main==="weekly"||d.goQuota?.main==="monthly"?d.goQuota.main:"rolling",k=[x,...["rolling","weekly","monthly"].filter(w=>w!==x)],b=w=>w==="rolling"?"goWindowRolling":w==="weekly"?"goWindowWeekly":"goWindowMonthly",v=w=>w==="rolling"?u.rolling:w==="weekly"?u.weekly:u.monthly,S=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},k.map(w=>Oa(a,a(b(w)),v(w),te(d,"go"),w===x)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||a("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(lt,{name:a("goQuotaTitle"),enabled:c,saved:d.goQuota,busy:m,open:l,statusNode:S,errorMsg:p,configNode:e(Ra,{config:d,draft:n,setDraft:i,t:a,api:o}),onToggleOpen:()=>r(w=>!w),onToggle:w=>f("enabled",w),onRefresh:g,t:a})}const Ps=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Ms(t){const{state:s,api:o,t:a,draft:n,setDraft:i,index:l}=t,r=s.config,d=(n??r).gatewayQuotas?.sources??[],c=d[l]??{},m=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(P=>P.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},p=Ps(c,s.customVarStatus),[g,x]=L(!1),[k,b,v]=it(a,()=>o.refreshGatewayQuota(c.id)),S=P=>{n!==null&&i({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:P}})},w=P=>S(d.map((E,h)=>h===l?{...E,...P}:E)),A=(P,E,h)=>e("div",{className:"cm-field"},e("label",null,P),e("input",{className:"cm-input",value:E??"",onChange:h})),y=(P,E)=>{const h=We(P?.label||P?.id||a("gatewaySourceUnknown"),P,te(r,"plan"),a);return e(q,{key:P?.id||E},h.row,P?.resetsAt?e("div",{className:"cm-note"},_e(P,a)):null)},M=(P,E)=>e("div",{key:P.id||E,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},P.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(P.used??"—")+" / "+(P.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(P.remaining??"—")+" remaining")),T=P=>P==null?null:e(q,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},P.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(P.used??"—")+" / "+(P.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(P.remaining??"—")+" remaining")),(P.packages??[]).map(M)),B=(P,E)=>e("div",{key:P.id||E,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Yt[P.provider]??P.provider??a("gatewaySourceUnknown"))+" · "+(P.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},P.status)),P.plan?e("div",{className:"cm-note"},P.plan):null,P.windows.length>0?e("div",{className:"cm-go-list"},P.windows.map(y)):null,T(P.credits),P.message?e("div",{className:"cm-note"},P.message):null);return e(lt,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(P=>P.id===c.id),busy:k,open:g,errorMsg:b,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(m.status??a("gatewaySourceUnknown"))+(m.serverVersion?" · "+m.serverVersion:"")+(m.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(m.fetchedAt).toLocaleTimeString()}):"")+(m.message?" · "+m.message:"")),configNode:e(q,null,e("div",{className:"cm-grid"},A(a("gatewaySourceLabel"),c.label,P=>w({label:P.target.value})),A(a("gatewaySourceBaseURL"),c.baseURL,P=>w({baseURL:P.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:P=>w({display:P.target.value})},...ze(a))),A(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),P=>w({allowedHosts:P.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:P=>w({antigravityOnlyGemini:P.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),p?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+p,configured:s.customVarStatus?.[p]?.configured===!0,source:s.customVarStatus?.[p]?.source??"",t:a,api:o,placeholder:p})):null,m.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+m.unsupportedProviders.join(", ")):null,m.accounts.length>0?m.accounts.map(B):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:P=>w({enabled:P}),onRefresh:v,onRemove:()=>S(d.filter((P,E)=>E!==l)),onToggleOpen:()=>x(P=>!P),t:a})}const Re=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function Ts(t){const{state:s,api:o,t:a,draft:n,setDraft:i,planId:l,labelKey:r}=t,u=s.config,d=s.codingPlans??{},c=n?.codingPlans?.[l]??u.codingPlans?.[l]??{},f=d[l]??{status:"off",message:"",fetchedAt:0,windows:{}},m=c.enabled===!0,[p,g]=L(!1),[x,k,b]=it(a,()=>o.refreshCodingPlan(l)),v=(D,O)=>{if(n===null)return;const G=n.codingPlans??u.codingPlans??{};i({...n,codingPlans:{...G,[l]:{...G[l]??{},[D]:O}}})},[S,w]=L(""),[A,y]=L({}),M=D=>D?.rates!==null&&typeof D?.rates=="object"&&!Array.isArray(D.rates)?D.rates:{},T=["input","cachedInput","output"],B=D=>A[D]??M(c)[D]??{},P=D=>T.every(O=>Number.isFinite(Number(D[O]))&&Number(D[O])>0),E=(D,O,G)=>{if(n===null)return;const R={...B(D),[O]:String(G)};y(Q=>({...Q,[D]:R}));const V=T.every(Q=>String(R[Q]??"").trim()==="");if(!V&&!P(R))return;const N=n.codingPlans??u.codingPlans??{},H={...(N.qwen??{}).rates??{}};V?delete H[D]:H[D]=Object.fromEntries(T.map(Q=>[Q,Number(R[Q])])),i({...n,codingPlans:{...N,qwen:{...N.qwen??{},rates:H}}})},h=D=>{n!==null&&y(O=>({...O,[D]:O[D]??M(c)[D]??{}}))},U=D=>{if(n===null)return;y(R=>{const V={...R};return delete V[D],V});const O=n.codingPlans??u.codingPlans??{},G={...(O.qwen??{}).rates??{}};delete G[D],i({...n,codingPlans:{...O,qwen:{...O.qwen??{},rates:G}}})},ee=f.windows!==null&&typeof f.windows=="object"?f.windows:{},ye=m===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):f.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(ee).length>0?l==="minimax"&&(Fe(ee).five!=null||Fe(ee).seven!=null)?e(xa,{five:Fe(ee).five,seven:Fe(ee).seven,fetchedAt:f.fetchedAt,t:a,wide:!0,direction:te(u,"plan")}):Object.entries(ee).map(([D,O])=>Oa(a,D.replace(/_/g," "),O,te(u,"plan"),!1,D)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:f.fetchedAt>0?new Date(f.fetchedAt).toLocaleTimeString():"—"}))):f.status==="error"?e("div",{className:"cm-bal-line err"},f.message||a("unknownError")):f.status==="off"&&f.message?e("p",{className:"cm-note"},f.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),ve=e(q,null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:D=>v("baseUrl",D.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:D=>v("quotaSource",D.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:l==="minimax"?"both":"settings",onChange:D=>v("display",D.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),l!=="scnet"&&(l!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ae({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},D=>{v("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D))))})):null,l==="scnet"||l==="qwen"&&(c.quotaSource??"local")==="local"?e(q,null,e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:l==="qwen"?5e5:24e4,onChange:D=>{const O=Number(D.target.value);Number.isFinite(O)&&O>0&&v("planCredits",Math.floor(O))}})),e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:D=>v("planStart",D.target.value)})),l==="qwen"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(M(c)),...Object.keys(A)])].sort().map(D=>e("div",{key:D,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},D),T.map(O=>e("input",{key:O,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:B(D)[O]??"",placeholder:a("qwenRate_"+O),"aria-label":D+" · "+a("qwenRate_"+O),onChange:G=>{const R=G.target.value;E(D,O,R)}})),e("button",{className:"cm-btn small",onClick:()=>U(D)},a("overrideRemove")),D in A&&!P(B(D))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:S,onChange:D=>w(D.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const D=S.trim();D.length!==0&&(h(D),w(""))},disabled:S.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:f.keyConfigured===!0,source:f.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:f.keyConfigured===!0,source:f.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(q,null,e("div",{className:"cm-field"},e("label",null,l==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+l,configured:f.keyConfigured===!0,source:f.keySource,t:a,api:o,placeholder:l==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(lt,{name:a(r),enabled:m,saved:u.codingPlans?.[l],busy:x,open:p,errorMsg:k,statusNode:ye,configNode:ve,onToggle:D=>v("enabled",D),onRefresh:b,onToggleOpen:()=>g(D=>!D),t:a})}function Bs(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,l=s.config,r=n??l,u=r.codingPlans??{},d=r.gatewayQuotas?.sources??[],c=n?.customBalances??l.customBalances??[],f=S=>{n!==null&&i({...n,customBalances:S,...S.length===0?{customBalance:{...l.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},m=we({next:0,keys:[]}).current;for(;m.keys.length<c.length;)m.keys.push(m.next++);m.keys.length=c.length;const p=S=>{m.keys.splice(S,1),f(c.filter((w,A)=>A!==S))},g=(S,w)=>f(c.map((A,y)=>y===S?{...A,...w}:A)),x=(S="custom")=>{c.length>=8||f([...c,{...S==="aliyun"?{adapter:S}:{},enabled:!1,label:S==="aliyun"?"千问 / 阿里云":"",labelEn:S==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:S==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:S==="aliyun"?"https://business.aliyuncs.com/":"",method:S==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},k=()=>{d.length>=4||n===null||i({...n,gatewayQuotas:{...n.gatewayQuotas??l.gatewayQuotas??{},sources:[...d,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:pt,allowedHosts:[],allowInsecureHttp:!1}]}})},b=[...d.map((S,w)=>({kind:"gateway",key:"gw-"+(S.id??w),index:w,enabled:S.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Re.map(S=>({kind:"plan",key:"plan-"+S.id,planId:S.id,labelKey:S.labelKey,enabled:u[S.id]?.enabled===!0})),...c.map((S,w)=>({kind:"custom",key:"cb-"+m.keys[w],index:w,enabled:S.enabled===!0}))],v=S=>S.kind==="plan"?e(Ts,{key:S.key,planId:S.planId,labelKey:S.labelKey,state:s,api:o,t:a,draft:n,setDraft:i}):S.kind==="go"?e(As,{key:S.key,state:s,api:o,t:a,draft:n,setDraft:i}):S.kind==="gateway"?e(Ms,{key:S.key,index:S.index,state:s,api:o,t:a,draft:n,setDraft:i}):e(Cs,{key:S.key,state:s,api:o,t:a,entry:c[S.index],index:S.index,canRemove:!0,onPatch:w=>g(S.index,w),onRemove:()=>p(S.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ss(b).map(v)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:k,disabled:d.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>x(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>x("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const Ds=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],La=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function qt(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=W(a?.locale),i=t.t??K(n),l=Array.isArray(o.history)?o.history:[];if(l.length===0)return e("div",null,e("h3",{className:"cm-h"},i("usageTitle")),e("p",{className:"cm-empty"},i("usageEmpty")));const r=o.meta?.dayKey??"",u=new Map(l.map(w=>[w.date,w])),d=w=>{const A=y=>String(y).padStart(2,"0");return w.getFullYear()+"-"+A(w.getMonth()+1)+"-"+A(w.getDate())},c=new Date;c.setHours(0,0,0,0);const f=new Date(c);f.setDate(f.getDate()+(6-(c.getDay()+6)%7));const m=26,p=[],g=[];let x=-1;for(let w=m-1;w>=0;w-=1){for(let y=0;y<7;y+=1){const M=new Date(f);M.setDate(M.getDate()-(w*7+(6-y)));const T=u.get(d(M));p.push(T!==void 0?{day:T,tokens:La(T)}:{day:{date:d(M)},tokens:0})}const A=new Date(f);A.setDate(A.getDate()-(w*7+6)),g.push(A.getMonth()!==x?n==="en"?Ds[A.getMonth()]:String(A.getMonth()+1)+"月":""),x=A.getMonth()}const k=Math.max(...p.map(w=>w.tokens),1),b=w=>{const A=w/k;return A<.25?1:A<.5?2:A<.75?3:4},v=w=>{const{day:A,tokens:y}=w,M="cm-ug-cell"+(y>0?" l"+b(y):"")+(A.date===r?" today":""),T=i("usageDay",{date:A.date,tokens:I(y),input:I(A.input??0),cache:I((A.cacheRead??0)+(A.cacheWrite??0)),output:I(A.output??0),calls:A.calls??0,cost:Y(_(A,a),a)});return e($,{key:A.date,label:T,side:"top",delayMs:200},e("div",{className:M}))},S=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},i("usageTitle")),e("div",{className:"cm-ug-total"},i("usageTotal",{tokens:I(La(S)),input:I(S.input??0),cache:I((S.cacheRead??0)+(S.cacheWrite??0)),output:I(S.output??0),calls:S.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+m+",1fr)"}},p.map(v)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+m+",1fr)"}},g.map((w,A)=>e("span",{key:"m"+String(A),className:"cm-ug-monthc"},w))))}function Os(t){const s=t.useCost?t.useCost(N=>N):void 0,o=t.api,a=s?.state??null,[n,i]=L(null),[l,r]=L(null),[u,d]=L(!1),[c,f]=L(!1),[m,p]=L(!1),[g,x]=L(""),[k,b]=L(!1),[v,S]=L(!1),[w,A]=L("overview"),[y,M]=L({status:"idle",at:0,error:null}),T=Ee.useRef(null),B=Ee.useRef(null),P=Ee.useRef(null);X(()=>{if(a!==null){const N=JSON.stringify(a.config);i(H=>{const Q=H!==null&&JSON.stringify(H)!==T.current;return Q||(B.current=a.config,P.current=a.config),Q?H:JSON.parse(N)}),T.current=N}},[a]),X(()=>{n!==null&&P.current===null&&B.current!==null&&(P.current=B.current)},[n]),X(()=>{if(n===null||o===void 0)return;const N=JSON.stringify(n);if(N===T.current)return;M(Q=>Q.status==="saving"?Q:{...Q,status:"saving"});const H=setTimeout(()=>{const Q={},le=P.current??B.current;if(le!==null&&typeof le=="object")for(const C of Object.keys(n))JSON.stringify(n[C])!==JSON.stringify(le[C])&&(Q[C]=n[C]);if(Object.keys(Q).length===0){T.current=N,M({status:"saved",at:Date.now(),error:null});return}o.updateConfig(Q).then(()=>{T.current=N,le!==null&&typeof le=="object"&&(P.current={...le,...Q}),M({status:"saved",at:Date.now(),error:null})},C=>{M({status:"error",at:0,error:C?.message??String(C)})})},600);return()=>{clearTimeout(H)}},[n,o]),X(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:h("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const E=W((n??a?.config)?.locale),h=K(E);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?h("readingLedger"):h("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},h("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},h("refresh")));const U=a.config,ee=async()=>{if(!k){b(!0),r(null);try{const N=await o.fetchPrices();if(r({kind:N.ok?"ok":"err",text:N.message}),N.ok&&N.state&&typeof N.state.config=="object"){const H=JSON.stringify(N.state.config);i(JSON.parse(H)),T.current=H}}catch(N){r({kind:"err",text:h("syncFailed",{message:N?.message??String(N)})})}finally{b(!1),d(!1)}}},ye=async()=>{if(!k){b(!0);try{await o.resetHistory(),r({kind:"ok",text:h("historyCleared")})}catch(N){r({kind:"err",text:h("clearFailed",{message:N?.message??String(N)})})}finally{b(!1),f(!1)}}},ve=async()=>{if(!k){b(!0),r(null);try{const N=await o.importLegacyHistory();r({kind:"ok",text:N.message})}catch(N){r({kind:"err",text:h("legacyImportFailed",{message:N?.message??String(N)})})}finally{b(!1),p(!1)}}},D=(N,H)=>{n!==null&&i({...n,[N]:H})},O=()=>{if(n===null)return;const N=g.trim().toLowerCase();if(N.length===0||!/^[a-z0-9_.-]+$/.test(N)||n?.prices.models[N]!==void 0)return;const H={...n.prices.models,[N]:{cacheHit:0,cacheMiss:0,output:0}};i({...n,prices:{...n.prices,models:H}}),x("")},G=n===null?[]:Object.keys(n.prices.models).filter(N=>{const Q=(n?.priceTableDisplay??U.priceTableDisplay??{})["deepseek:"+N];return typeof Q=="boolean"?Q:!0}).map(N=>e(Rt,{key:N,modelId:N,entry:n.prices.models[N]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:i,t:h})),R=[["overview",h("tabOverview")],["quotas",h("tabQuotas")],["usage",h("tabUsage")],["pricing",h("tabPricing")],["display",h("tabDisplay")]],V=y.status==="saving"?e("span",{className:"cm-hint"},h("saving")):y.status==="error"?e("span",{className:"cm-msg err"},h("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?h("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):h("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},R.map(([N,H])=>e("button",{key:N,type:"button",role:"tab","aria-selected":String(w===N),className:"cm-tab"+(w===N?" active":""),onClick:()=>A(N)},H))),V),Et(l),w==="overview"?e(q,{key:"overview"},e("div",{className:"cm-cards"},U.hideTodayCost===!0?null:e(ot,{title:h("cardToday"),value:Y(_(a.today,U),U),sub:h("callsTokens",{calls:a.today.calls,input:I(a.today.input),cache:I(a.today.cacheRead+a.today.cacheWrite),output:I(a.today.output)})}),e(ot,{title:h("cardMonth"),value:Y(_(a.month,U),U),sub:h("callsTokens",{calls:a.month.calls,input:I(a.month.input),cache:I(a.month.cacheRead+a.month.cacheWrite),output:I(a.month.output)})}),e(ot,{title:h("cardTotal"),value:Y(_(a.total,U),U),sub:h("cardTotalSub",{calls:a.total.calls})})),e(rs,{state:a,t:h}),e("p",{className:"cm-note",key:"cards-footnote"},h("cardsFootnote")),(()=>{const N=bn(a);return N!==null?e("p",{className:"cm-note",key:"tz-hint"},h("timezoneHint",{host:N.hostLabel,browser:N.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:h("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??U).showTotalWithPlan===!0,onChange:N=>{const H=n??U;H!=null&&i({...H,showTotalWithPlan:N.target.checked})}}),e("span",null,h("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},h("todaySessions")),e(ms,{state:a,t:h})),e(fs,{state:a,draft:n,setDraft:i,t:h}),(U.balance?.display==="settings"||U.balance?.display==="both")&&U.hideOfficialBalance!==!0?e(Ns,{state:a,api:o,t:h,draft:n,setDraft:i}):null):null,w==="quotas"?e(Bs,{key:"quotas",state:a,api:o,t:h,draft:n,setDraft:i}):null,w==="usage"?e(q,{key:"usage"},!Ge||(U.usage?.position??"cost")==="cost"?e(qt,{state:a,t:h,locale:E}):null,e(ys,{state:a,config:n??U,t:h}),e(vs,{state:a,config:n??U,t:h}),e(cs,{state:a,api:o}),e(us,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},h("historyDataTitle")),e("div",{className:"cm-buttons"},m?e(q,null,e("span",{className:"cm-hint"},h("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:ve,disabled:k},h("apply")),e("button",{className:"cm-btn",onClick:()=>p(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>p(!0),disabled:k},h("importLegacy")),c?e(q,null,e("span",{className:"cm-hint"},h("confirmReset")),e("button",{className:"cm-btn danger",onClick:ye,disabled:k},h("confirmClear")),e("button",{className:"cm-btn",onClick:()=>f(!1)},h("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>f(!0),disabled:k},h("clearAllHistory"))),e("p",{className:"cm-note"},h("legacyImportNote")))):null,w==="display"?e(q,{key:"display"},e(is,{draft:n,setDraft:i,t:h}),a?.secretMigration?.pending?.length>0?e(hn,{pending:a.secretMigration.pending,t:h}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,h("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:N=>D("locale",N.target.value)},e("option",{value:"auto"},h("localeAuto")),e("option",{value:"zh"},h("localeZh")),e("option",{value:"en"},h("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},h("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},h("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled"].map(N=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[N]===!0,onChange:H=>D(N,H.target.checked)}),e("span",null,h(N)))),Ge?e("div",{className:"cm-field"},e("label",null,h("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:N=>{n!==null&&i({...n,usage:{...n.usage??{position:"cost"},position:N.target.value}})}},e("option",{value:"cost"},h("usagePositionCost")),e("option",{value:"general"},h("usagePositionGeneral")),e("option",{value:"section"},h("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,h("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:N=>D("position",N.target.value)},e("option",{value:"dock"},h("positionDock")),e("option",{value:"header"},h("positionHeader")),e("option",{value:"off"},h("off")))),e("div",{className:"cm-field"},e("label",null,h("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:N=>D("sidebar",N.target.value==="on")},e("option",{value:"on"},h("sidebarOn")),e("option",{value:"off"},h("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:N=>D("showSessionId",N.target.checked)}),e("span",null,h("showSessionIdLabel"))),e("div",{className:"cm-grid-group"},h("groupMoney")),e("div",{className:"cm-field"},e("label",null,h("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:N=>{const H=ps[N.target.value];H!==void 0&&n!==null&&i({...n,currency:N.target.value,...H})}},e("option",{value:"CNY"},h("currencyCny")),e("option",{value:"USD"},h("currencyUsd")),e("option",{value:"EUR"},h("currencyEur")))),e("div",{className:"cm-field"},e("label",null,h("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:N=>D("symbol",N.target.value)})),e("div",{className:"cm-field"},e("label",null,h("rateLabel")),ae({value:n?.exchangeRate??1,emptyMode:"ignore"},N=>D("exchangeRate",N))),e("div",{className:"cm-field"},e("label",null,h("decimalsLabel")),ae({value:n?.decimals??2},N=>D("decimals",Math.min(10,Math.floor(N))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:N=>D("hideOfficialBalance",N.target.checked)}),e("span",null,h("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:N=>D("hideTodayCost",N.target.checked)}),e("span",null,h("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},h("groupSidebar")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:N=>{n&&i({...n,sidebarSimple:N.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,h("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,h("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:N=>D("sidebarStyle",N.target.value)},e("option",{value:"standard"},h("sidebarStyleStandard")),e("option",{value:"compact"},h("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,h("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:N.target.value}})}},...ze(h))),e("div",{className:"cm-field"},e("label",null,h("refreshIntervalLabel")),ae({value:n?.balance?.refreshMinutes??5},N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(N)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:N.target.checked}})}}),e("span",null,h("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,h("balanceBudgetCapLabel")),ae({value:n?.balance?.budgetCap??""},N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:N>0?N:null}})}),e("span",{className:"cm-hint"},h("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,h("barDirectionsTitle")),["balance","budget","go","plan"].map(N=>e("div",{className:"cm-dir-row",key:N},e("span",{className:"cm-dir-label"},h("barDirection_"+N)),e("select",{className:"cm-input",value:n?.barDirections?.[N]??(N==="balance"?"remaining":"used"),onChange:H=>{if(n===null)return;const Q={balance:"remaining",budget:"used",go:"used",plan:"used"};i({...n,barDirections:{...n.barDirections??Q,[N]:H.target.value}})}},e("option",{value:"remaining"},h("barDirectionRemaining")),e("option",{value:"used"},h("barDirectionUsed"))))),e("span",{className:"cm-hint"},h("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,h("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??U.customBalance?.display??"both",onChange:N=>{n!==null&&i({...n,customBalance:{...n.customBalance??U.customBalance??{},display:N.target.value}})}},...ze(h))),e("div",{className:"cm-field"},e("label",null,h("customBalanceRefreshInterval")),ae({value:n?.customBalance?.refreshMinutes??U.customBalance?.refreshMinutes??15},N=>{n!==null&&i({...n,customBalance:{...n.customBalance??U.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(N)))}})})),e(Ra,{config:U,draft:n,setDraft:i,t:h,api:o}),e("div",{className:"cm-grid-group"},h("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:N=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:N.target.checked,promptSeen:!0}})}}),e("span",null,h("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([N,H])=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[N]!==!1,onChange:Q=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip,[N]:Q.target.checked}})}}),e("span",null,h(H)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("quotaStripNote"))),e("div",{className:"cm-grid-group"},h("groupCorner")),e("div",{className:"cm-field"},e("label",null,h("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:N=>{n!==null&&i({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:N.target.checked}})}}),e("span",null,h("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([N,H])=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[N]!==!1,onChange:Q=>{n!==null&&i({...n,corner:{...n.corner,[N]:Q.target.checked}})}}),e("span",null,h(H)))):null),e("div",{className:"cm-grid-group"},h("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:N=>{n!==null&&i({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:N.target.checked}})}}),e("span",null,h("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:N=>{n!==null&&i({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:N.target.checked}})}}),e("span",null,h("budgetDetailLabel"))))),e("p",{className:"cm-note"},h("badgeNote")))):null,w==="pricing"?e(q,{key:"pricing"},e(bs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,Oe(v,()=>S(!v),h("priceTableTitle")),v?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},h("priceTableNote")),e("p",{className:"cm-hint"},h("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},h("deepseekMountedHeader")),G,e(Rt,{key:"__default__",modelId:h("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:i,t:h}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:h("newModelPlaceholder"),value:g,onChange:N=>x(N.target.value)}),e("button",{className:"cm-btn small",onClick:O,disabled:g.trim().length===0},h("addModel"))),(()=>{const N=n?.priceTableDisplay??U.priceTableDisplay??{},H=n?.prices?.providers??{},Q=C=>Object.keys(H[C]?.models??{}).filter(F=>N[C+":"+F]===!0),le=Object.keys(H).filter(C=>Q(C).length>0).sort((C,F)=>C.localeCompare(F));return le.length===0?null:le.map(C=>e("div",{key:C},e("div",{className:"cm-catalog-vendor"},(Pa[C]??C)+" · "+h("mountedSuffix")),Q(C).sort().map(F=>e(Da,{key:C+":"+F,provider:C,modelId:F,entry:H[C].models[F],draft:n,setDraft:i,t:h}))))})()):null),(()=>{const N=n?.priceOverrides??U.priceOverrides??{},H=n?.priceMatchDismissed??U.priceMatchDismissed??[],Q=n?.prices??U.prices,le=a.today.byProviderModel??{},C={prices:Q,priceMatch:n?.priceMatch??U.priceMatch},F=Object.keys(le).filter(j=>{if(H.includes(j)||N[j]!==void 0)return!1;const z=j.indexOf(":"),ke=(z>0?j.slice(0,z):"deepseek").toLowerCase(),Ht=z>0?j.slice(z+1):j;return gt(ke,Ht,C).matched!==!0}),Z=[...new Set([...F,...Object.keys(N)])].filter(j=>!H.includes(j)),ne=a.month?.byProviderModel??{},Le=Object.keys(ne).filter(j=>{if(H.includes(j)||N[j]!==void 0)return!1;const z=j.indexOf(":"),ke=(z>0?j.slice(0,z):"deepseek").toLowerCase(),Ht=z>0?j.slice(z+1):j;return gt(ke,Ht,C).matched===!0}).sort(),Ne=[{value:"__local__",label:h("overrideTargetLocal")},{value:"deepseek:__default__",label:h("overrideTargetDefault")},...Object.keys(Q.models??{}).map(j=>({value:"deepseek:"+j,label:"DeepSeek · "+j})),...Object.entries(Q.providers??{}).flatMap(([j,z])=>Object.keys(z?.models??{}).map(ke=>({value:j+":"+ke,label:j+" · "+ke})))],pe=(j,z)=>{if(n===null)return;const ke={...n.priceOverrides??{}};z===""?delete ke[j]:ke[j]=z,i({...n,priceOverrides:ke})},Me=j=>{if(n===null)return;const z={...n.priceOverrides??{}};delete z[j],i({...n,priceOverrides:z,priceMatchDismissed:[...new Set([...H,j])]})};return e("div",null,e("h3",{className:"cm-h"},h("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:j=>D("priceMatch",j.target.value)},e("option",{value:"auto"},h("priceMatchAuto")),e("option",{value:"exact"},h("priceMatchExact")))),e("p",{className:"cm-note"},h("priceMatchNote")),Z.length>0?e(q,null,e("h3",{className:"cm-h"},h("unmatchedTitle")),e("p",{className:"cm-hint"},h("unmatchedHint")),Z.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,Lt(j)),e("select",{className:"cm-input",value:N[j]??"",onChange:z=>pe(j,z.target.value)},e("option",{value:""},"—"),Ne.map(z=>e("option",{key:z.value,value:z.value},z.label))),e("button",{className:"cm-btn small",title:h("removePriceMatchHint"),onClick:()=>Me(j)},h("overrideRemove"))))):e("p",{className:"cm-hint"},h("overrideNone")),H.length>0?e("button",{className:"cm-btn small",onClick:()=>D("priceMatchDismissed",[])},h("restorePriceMatches",{count:H.length})):null,Le.length>0?e(q,null,e("h3",{className:"cm-h"},h("matchedTitle")),e("p",{className:"cm-hint"},h("matchedHint")),Le.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,Lt(j)),e("select",{className:"cm-input",value:"",onChange:z=>{z.target.value!==""&&pe(j,z.target.value)}},e("option",{value:""},h("matchedKeepAuto")),Ne.map(z=>e("option",{key:z.value,value:z.value},z.label)))))):null)})(),e(hs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,e("h3",{className:"cm-h"},h("dataSync")),(n??U).currency==="CNY"&&(n??U).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},h("pricingCnyHint",{rate:(n??U).exchangeRate}),(n??U).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:k,onClick:()=>D("pricingCurrency","CNY")},h("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,h("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:N=>D("pricingCurrency",N.target.value)},e("option",{value:"USD"},h("pricingCurrencyUsd")),e("option",{value:"CNY"},h("pricingCurrencyCny"))),e("p",{className:"cm-note"},h("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},u?e(q,null,e("span",{className:"cm-hint"},h("confirmFetch")),e("button",{className:"cm-btn",onClick:ee,disabled:k},h("apply")),e("button",{className:"cm-btn",onClick:()=>d(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>d(!0),disabled:k},h("syncFromDocs"))),e("p",{className:"cm-note"},h("lastSync",{time:U.fetchedAt!==null?new Date(U.fetchedAt).toLocaleString():h("neverSynced")})+h("source",{source:U.priceSource==="official"?h("sourceOfficial"):h("sourceBundled")})),e("p",{className:"cm-note"},h("syncScopeNote")))):null)}const Rs=["remote"];async function Ls(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(tn);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=gn({status:"loading",error:null,state:null}),i=()=>K(W(n.getSnapshot().state?.config?.locale)),l=async(C,F)=>{const Z=await a[C](...F??[]);if(Z===null||typeof Z!="object"||Z.ok!==!0)throw new Error(Z?.error?.message??i()("rpcFailed",{method:C}));return Z.value};let r=Date.now(),u=!1,d=!0,c=1;const f=async()=>{if(!d||u)return;u=!0,r=Date.now();const C=n.getSnapshot();C.state===null&&n.set({...C,status:"loading"});try{const F=await l("getState");if(!d)return;c=1,n.set({status:"ready",error:null,state:F})}catch(F){if(!d)return;C.state===null&&(r=Date.now()),c=Math.min(c*2,60),n.set({status:"error",error:F?.message??String(F),state:C.state})}finally{u=!1}};t.effect(()=>t.on("connection/reset",()=>{f()}),"cost-meter: reconnect reload");const m=setInterval(()=>{const C=n.getSnapshot().state,F=C?.config.sidebarModels,Z=C?F?.enabled||F?.dock?F.refreshSeconds:60:c;!document.hidden&&Date.now()-r>=(Z||60)*1e3&&f()},1e3);t.effect(()=>()=>{d=!1,clearInterval(m)},"cost-meter: poll timer");const p=()=>{document.visibilityState==="visible"&&f()};document.addEventListener("visibilitychange",p),t.effect(()=>()=>{document.removeEventListener("visibilitychange",p)},"cost-meter: visibility reload");const g=async(C,F="rpcSyncFailed",Z=!1)=>{const ne=await C;if(ne===null||typeof ne!="object"||ne.ok!==!0)throw new Error(ne?.error?.message??(Z?ne?.value?.message:void 0)??i()(F));return ne.value.state!==void 0&&n.set({status:"ready",error:null,state:ne.value.state}),ne.value},x={reload:f,updateConfig:async C=>{const F=await l("updateConfig",[C]);return n.set({status:"ready",error:null,state:F}),F},fetchPrices:async()=>g(a.fetchPrices()),resetHistory:async()=>{const C=await l("resetHistory");return n.set({status:"ready",error:null,state:C}),C},importLegacyHistory:async()=>{const C=await a.importLegacyHistory();if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??i()("legacyImportFailed",{message:"RPC failed"}));return C.value.state!==void 0&&n.set({status:"ready",error:null,state:C.value.state}),C.value},getDaySessions:async C=>l("getDaySessions",[C]),getSessionCost:async C=>l("getSessionCost",[C]),getTopSessions:async(C,F,Z)=>l("getTopSessions",[C,F,Z]),refreshBalance:async()=>g(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>g(a.refreshGoQuota()),refreshGatewayQuota:async(C=null)=>g(C==null?a.refreshGatewayQuota():a.refreshGatewayQuota(C)),refreshCustomBalance:async(C=null)=>g(C==null?a.refreshCustomBalance():a.refreshCustomBalance(C)),refreshCodingPlan:async C=>g(a.refreshCodingPlan(C)),setCredential:async(C,F)=>g(a.setCredential(C,F),"rpcSyncFailed",!0),clearCredential:async C=>g(a.clearCredential(C),"rpcSyncFailed",!0)};f();const k=t.get("slots");if(k===void 0)return;const b=()=>({hooks:{cost:n},api:x}),v=()=>({gen:0,dispose:null}),S=(C,F,Z,ne,Le=!0)=>{C.dispose!==null&&(C.dispose(),C.dispose=null),C.gen+=1;const Ne=C.gen;Le&&k.inject(F,()=>{if(C.gen!==Ne)return;const pe=typeof Z=="function"?Z():k.register(Z,ne);if(C.gen!==Ne){pe();return}return C.dispose=pe,()=>{C.dispose===pe&&(C.dispose=null),pe()}})},w=v(),A=C=>{const F=C==="header"?"conversation.session.header.actions":"conversation.composer.dock";S(w,F,C==="header"?{name:F,id:"cost-meter",order:-5,inject:b}:{name:F,id:"cost-meter",order:5,inject:b},C==="header"?kn:wn,C!=="off")},y=v(),M=C=>{S(y,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:b},os,C)},T=v(),B=C=>{S(T,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:b},On,C)};k.inject("conversation.input.dock",()=>k.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:b},Xn)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:b},es)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:b},ts)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:b},ss));const P=v(),E=C=>{S(P,"sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:b},Rn),null,C)};window.cmPeakAlertPreview=C=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(Ct,{detail:{kind:C==="offpeak"?"offpeak":"peak"}}))};const h=v(),U=C=>{S(h,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:C==="en"?Te.en.sectionLabel:Te.zh.sectionLabel,inject:b},Os,!0)},ee=v(),ye=C=>{S(ee,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:b},qt,C)},ve=v(),D=(C,F)=>{S(ve,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:F==="en"?Te.en.usageSectionLabel:Te.zh.usageSectionLabel,inject:b},qt,C)};let O=null,G=null,R=null,V=null,N=null,H=null;const Q=()=>{const C=n.getSnapshot().state,F=C?.config?.position??"dock",Z=C?.config?.sidebar!==!1&&C?.config?.hideTodayCost!==!0,ne=C?.config?.balance?.display??"both",Le=(ne==="sidebar"||ne==="both")&&C?.config?.hideOfficialBalance!==!0,Ne=Z||Le||C?.config?.codexQuotaEnabled===!0||C?.config?.sidebarModels?.enabled===!0,pe=C?.config?.corner?.enabled===!0||C?.config?.sidebarModels?.dock===!0,Me=W(C?.config?.locale),j=C?.config?.usage?.position??"cost";F!==O&&(A(F),O=F),Ne!==G&&(M(Ne),G=Ne),pe!==R&&(B(pe),R=pe);const z=C?.config?.peakEnabled===!0;z!==H&&(E(z),H=z),Me!==V&&(U(Me),V=Me),j!==N?(Ge&&(ye(j==="general"),D(j==="section",Me)),N=j):Ge&&j==="section"&&Me!==V&&D(!0,Me)};Q();const le=n.subscribe(Q);return()=>{le()}}return rt.apply=Ls,rt.inject=Rs,Ut.exports}});
|
|
2
|
+
window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:jt=>{var Qt={exports:{}},rt=Qt.exports;Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"});const Ee=jt("react"),{Tooltip:Z}=jt("@deepseek-ai/dsh-client-ui-primitives"),Ge=!1,qa='.cm-root{display:block;text-align:center;max-width:var(--dsh-chat-content-width,720px);width:100%;margin:0 auto;box-sizing:border-box;padding:4px calc(var(--dsh-composer-side-clearance,0px) + 16px) 0;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-chip{display:inline-flex;align-items:center;gap:4px;max-width:180px;padding:0 8px;height:22px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-foot{display:flex;align-items:center;gap:6px;height:32px;padding:0 8px;border-radius:8px;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden}.cm-foot:hover,.cm-foot-rail:hover,.cm-corner-chip:hover,.cm-qchip:hover,.cm-tab:hover,.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}.cm-foot-rail{width:100%;justify-content:center;padding:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-num{font-variant-numeric:tabular-nums}.cm-go-rail{font-size:11px;font-weight:700;color:var(--dsw-alias-label-primary)}.cm-go-list{display:flex;flex-direction:column;gap:10px}.cm-go-row{display:flex;align-items:center;gap:8px;font-size:12px}.cm-go-label{flex:none;width:88px;color:var(--dsw-alias-label-secondary)}.cm-go-bar{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-interactive-bg-hover);overflow:hidden}.cm-go-fill{height:100%;border-radius:3px;background:var(--dsw-alias-brand-primary)}.cm-go-num{flex:none;min-width:44px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.cm-go-reset{flex:none;max-width:230px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-go-time{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-go-row.main .cm-go-label{font-weight:600;color:var(--dsw-alias-label-primary)}.cm-corner{display:flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:2px auto 0;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-corner-chip{display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:20px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums}.cm-qstrip{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:0 auto;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-qchip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:default}.cm-qchip .cm-qlabel{color:var(--dsw-alias-label-primary);font-weight:600}.cm-qchip .cm-qbar{display:block;width:44px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l1);overflow:hidden;flex:none}.cm-qchip .cm-qfill{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-state-ok-primary,#3ba272)}.cm-qchip .cm-qseg{display:inline-flex;align-items:center;gap:4px}.cm-qchip .cm-qsep{width:1px;height:12px;background:var(--dsw-alias-border-l1);flex:none}.cm-qchip .cm-qtext{color:var(--dsw-alias-label-secondary)}.cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}.cm-qchip.over .cm-qfill{background:var(--dsw-alias-state-error-primary)}.cm-qchip.action{cursor:pointer;user-select:none;outline:none}.cm-qchip.action:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-qchip.action:active{transform:translateY(.5px)}.cm-plan-provider{display:flex;flex-direction:column;gap:8px}.cm-plan-provider+.cm-plan-provider{margin-top:14px}.cm-plan-provider-name{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600}.cm-plan-updated{font-size:11px;font-weight:400;color:var(--dsw-alias-label-tertiary)}.cm-plan-tag{flex:none;margin-left:6px;padding:0 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);font-size:10px;line-height:16px;color:var(--dsw-alias-state-warn-primary)}.cm-plan-reset,.cm-plan-method{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-qguide{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:9999;max-width:440px;width:calc(100% - 32px);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 28px #0000002e;padding:14px 16px;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:8px}.cm-qguide h4{margin:0;font-size:13px;font-weight:600}.cm-qguide p{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}.cm-qguide .cm-buttons{display:flex;gap:8px;justify-content:flex-end}.cm-section{display:flex;flex-direction:column;gap:20px;padding:4px 2px 24px;font-size:13px;color:var(--dsw-alias-label-primary)}.cm-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.cm-cards-toggle{display:flex;align-items:center;gap:6px;margin:-6px 2px 0 auto;width:fit-content;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;user-select:none}.cm-cards-toggle:hover{color:var(--dsw-alias-label-primary)}.cm-cards-toggle input{margin:0;cursor:pointer}.cm-card,.cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1)}.cm-card-title{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0 0 8px}.cm-card-value{font-size:20px;line-height:28px;font-weight:600}.cm-card-sub{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-h{font-size:13px;font-weight:600;margin:0}.cm-collapse-h{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;margin:0;cursor:pointer;color:inherit;font:inherit;text-align:left}.cm-collapse-h:hover .cm-h{color:var(--dsw-alias-interactive-text-hover,var(--dsw-alias-label-primary))}.cm-caret{flex:none;width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid var(--dsw-alias-label-secondary);transform:rotate(-90deg);transition:transform .15s ease}.cm-caret.open{transform:rotate(0)}.cm-collapse-body{display:flex;flex-direction:column;gap:12px;margin-top:12px}.cm-toolbar{display:flex;justify-content:flex-end;align-items:center;gap:10px}.cm-toolbar .cm-field{flex-direction:row;align-items:center;gap:8px}.cm-toolbar .cm-field label{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-toolbar .cm-input{min-width:150px;padding:4px 10px}.cm-tabs-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;border-bottom:1px solid var(--dsh-alias-border-l1);padding-bottom:10px}.cm-tabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}.cm-tab{font:inherit;font-size:13px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:8px;padding:6px 14px;cursor:pointer;white-space:nowrap}.cm-tab.active{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary-inverted);font-weight:600}.cm-tabs-row .cm-msg{padding:2px 10px}.cm-note{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0}.cm-table{width:100%;border-collapse:collapse;font-size:12px}.cm-table th,.cm-table td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}.cm-table th{color:var(--dsw-alias-label-tertiary);font-weight:500}.cm-table td.num,.cm-table th.num{text-align:right;font-variant-numeric:tabular-nums}.cm-table tr:last-child td{border-bottom:none}.cm-table tr.cm-row-click{cursor:pointer}.cm-table tr.cm-row-click:hover td{background:var(--dsw-alias-bg-hover,rgba(127,127,127,.08))}.cm-sess-title{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-sess-id{font-size:11px;font-family:ui-monospace,Consolas,monospace;color:var(--dsw-alias-label-tertiary)}.cm-empty{font-size:12px;color:var(--dsw-alias-label-tertiary);padding:8px 0}.cm-scroll{max-height:320px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px}.cm-grid{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:12px}.cm-field{display:flex;flex-direction:column;gap:6px}.cm-field label{font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-input{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;outline:none}.cm-input:focus{border-color:var(--dsw-alias-state-business-primary)}.cm-input.narrow{max-width:120px}.cm-range-row{display:flex;align-items:center;gap:10px}.cm-range{flex:1;min-width:0;accent-color:var(--dsw-alias-state-business-primary)}.cm-range-value{flex:none;min-width:44px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-align:right}.cm-check{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}.cm-price-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:10px;background:var(--dsw-alias-bg-layer-1)}.cm-price-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-price-name{font-weight:600;font-size:13px}.cm-price-legacy{font-size:11px;color:var(--dsw-alias-label-tertiary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px}.cm-price-row{display:grid;grid-template-columns:52px 1fr 1fr 1fr;gap:8px;align-items:center}.cm-price-row span{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-price-row input{width:100%}.cm-buttons{display:flex;flex-wrap:wrap;gap:10px;align-items:center}.cm-btn{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-elevated-fill);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 14px;cursor:pointer}.cm-btn.primary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-label-primary-inverted)}.cm-btn.primary:hover{opacity:.88;background:var(--dsw-alias-state-business-primary)}.cm-btn.danger,.cm-msg.err,.cm-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}.cm-btn.small{padding:3px 10px;font-size:12px}.cm-msg{font-size:12px;line-height:18px;padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1)}.cm-msg.ok{color:var(--dsw-alias-state-success-primary)}.cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-budget{display:flex;flex-direction:column;gap:10px}.cm-peak-alert{position:fixed;z-index:9999;width:340px;max-width:calc(100vw - 32px);padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:0 14px 36px #00000038;display:flex;flex-direction:column;gap:8px;font-size:12px;animation:cm-peak-alert-in .22s cubic-bezier(.2,.8,.2,1)}.cm-peak-alert.cm-peak-alert-corner{right:20px;bottom:20px}.cm-peak-alert.cm-peak-alert-center{top:50%;left:50%;transform:translate(-50%,-50%);animation-name:cm-peak-alert-in-center}.cm-peak-alert-peak{border-top:3px solid var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak{border-top:3px solid var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:600;letter-spacing:.4px;text-transform:uppercase}.cm-peak-alert-badge:before{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 4px color-mix(in srgb,currentColor 16%,transparent)}.cm-peak-alert-peak .cm-peak-alert-badge{color:var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak .cm-peak-alert-badge{color:var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-peak-alert-body{color:var(--dsw-alias-label-secondary);line-height:1.55}.cm-peak-alert-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}.cm-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}@keyframes cm-peak-alert-in{0%{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes cm-peak-alert-in-center{0%{opacity:0;transform:translate(-50%,calc(-50% + 10px))}to{opacity:1;transform:translate(-50%,-50%)}}.cm-budget-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-quota-name{flex:1;min-width:0}.cm-budget-bar{height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-budget-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary);transition:width .3s ease}.cm-ug{display:flex;flex-direction:column;gap:12px}.cm-ug-total{font-size:13px;color:var(--dsw-alias-label-primary)}.cm-ug-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,auto);gap:3px;width:100%}.cm-ug-cell{width:100%;aspect-ratio:1/1;border-radius:3px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);border:1px solid var(--dsw-alias-border-l1)}.cm-ug-cell.l1,.cm-ug-cell.l2,.cm-ug-cell.l3,.cm-ug-cell.l4{border-color:transparent}.cm-ug-cell.l1{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary)}.cm-ug-cell.today{outline:1px solid var(--dsw-alias-label-secondary);outline-offset:1px}.cm-ug-months{display:grid;grid-auto-flow:column;gap:3px;width:100%;font-size:10px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-ug-monthc{white-space:nowrap}.cm-budget-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-budget-line.over{color:var(--dsw-alias-state-error-primary)}.cm-peak-strip{display:flex;align-items:center;gap:6px;margin-top:4px;min-width:0}.cm-peak-track{position:relative;display:flex;flex:1;height:6px;min-width:0;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-segment{height:100%;flex:1}.cm-peak-high{background:#ff9800}.cm-peak-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-marker{position:absolute;top:0;left:50%;width:2px;height:100%;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2}.cm-peak-chip{font-size:11px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-classic{position:relative;display:flex;flex-direction:column;gap:5px;margin-top:6px;min-width:0}.cm-peak-classic .cm-peak-track{flex:none;height:8px}.cm-peak-classic-marker{position:absolute;top:0;left:50%;width:4px;height:12px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2;border-radius:2px}.cm-peak-classic-marker:after{content:"";position:absolute;top:-7px;left:50%;transform:translate(-50%);border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #ff9800}.cm-peak-classic.off .cm-peak-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic.off .cm-peak-classic-marker:after{border-top-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic-chip{align-self:flex-start;font-size:11px;font-weight:600;line-height:1.4;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 8px;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-strip.peak .cm-peak-chip,.cm-peak-classic.peak .cm-peak-classic-chip,.cm-peak-rail.peak .cm-peak-rail-label,.cm-peak-rail-classic.peak .cm-peak-rail-classic-label{color:#ff9800}.cm-peak-strip.off .cm-peak-chip,.cm-peak-classic.off .cm-peak-classic-chip,.cm-peak-rail.off .cm-peak-rail-label,.cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}.cm-peak-strip.weekend .cm-peak-chip,.cm-peak-classic.weekend .cm-peak-classic-chip,.cm-peak-rail.weekend .cm-peak-rail-label,.cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker{border-color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker:after{border-top-color:#34a853}.cm-peak-rail{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-track{position:relative;display:flex;flex-direction:column;width:6px;height:56px;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-segment{width:100%;flex:1}.cm-peak-rail-high{background:#ff9800}.cm-peak-rail-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-rail-marker{position:absolute;left:0;top:50%;width:100%;height:2px;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translateY(-50%);transition:top .4s ease;z-index:2}.cm-peak-rail-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-rail-classic{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-classic-track{position:relative;display:flex;flex-direction:column;width:14px;height:56px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-classic-segment{position:relative;width:100%;flex:1;overflow:hidden}.cm-peak-rail-classic-segment.peak{background:#ff9800;border-radius:999px 999px 0 0}.cm-peak-rail-classic-segment.off{background:var(--dsw-alias-state-business-primary);border-radius:0 0 999px 999px}.cm-peak-rail-classic-marker{position:absolute;left:50%;top:50%;width:12px;height:4px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%,-50%);transition:top .4s ease;z-index:2;border-radius:2px}.cm-peak-rail-classic.off .cm-peak-rail-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-rail-classic-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}.cm-grid-group{grid-column:1 / -1;margin-top:8px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:4px}.cm-grid-group:first-child{margin-top:0}.cm-peak-preview{margin-top:8px}.cm-toggle-btn{background:none;border:none;padding:0;font-size:12px;font-weight:600;color:var(--dsw-alias-state-business-primary);cursor:pointer}.cm-toggle-btn:hover{text-decoration:underline}.cm-collapsed-note{margin-top:4px}.cm-catalog-vendor{margin-top:10px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:2px;display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-vendor-toggle{cursor:pointer;user-select:none}.cm-vendor-toggle:hover{color:var(--dsw-alias-label-secondary)}.cm-vendor-display{display:inline-flex;align-items:center;gap:4px;font-weight:400;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}.cm-catalog-family{margin:6px 0 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}.cm-catalog-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px}.cm-catalog-mounted{display:flex;flex-direction:column;gap:4px;padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1)}.cm-catalog-id{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-catalog-price{color:var(--dsw-alias-label-secondary);white-space:nowrap;font-size:11px}.cm-catalog-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);white-space:nowrap}.cm-mstats-tabs{display:flex;gap:8px;margin-bottom:8px}.cm-mstats-tab{background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}.cm-mstats-tab.active{background:var(--dsw-alias-state-business-primary);border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-bg-base);font-weight:600}.cm-mstats-h{margin:10px 0 4px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}.cm-mstats-row{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:8px;align-items:center;font-size:11px;line-height:1.7}.cm-mstats-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-barbg{position:relative;height:10px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden;display:flex}.cm-mstats-bar{height:100%;min-width:0;border-radius:999px}.cm-mstats-bar.cost{background:#ff9800}.cm-mstats-bar.hit{background:#34a853}.cm-mstats-bar.value{background:#a142f4}.cm-mstats-seg{height:100%;min-width:0}.cm-mstats-seg.in{background:var(--dsw-alias-state-business-primary)}.cm-mstats-seg.cache{background:#ff9800}.cm-mstats-seg.out{background:#34a853}.cm-mstats-val{white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-legend{display:flex;gap:12px;font-size:10px;color:var(--dsw-alias-label-tertiary);margin:2px 0 4px}.cm-mstats-dot{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.cm-mstats-note{margin-top:10px;font-size:10px;line-height:1.6;color:var(--dsw-alias-label-tertiary)}.cm-match-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:12px;flex-wrap:wrap}.cm-match-row .cm-input{flex:1;min-width:160px}.cm-budget-controls{display:grid;grid-template-columns:repeat(2,minmax(180px,1fr));gap:12px}.cm-bbox{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:6px;min-width:148px;box-sizing:border-box}.cm-bbox.rail{padding:6px;min-width:0;width:40px;align-items:center;justify-content:center;border-radius:10px}.cm-bbox.warn{border-color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over{border-color:var(--dsw-alias-state-error-primary)}.cm-bbox-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-bbox-label,.cm-bbox-pct{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}.cm-bbox-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-bbox-bar.segments{display:flex;height:8px}.cm-bbox-bar.segments .cm-bbox-fill{flex:none;border-radius:0;height:100%}.cm-bbox-bar.segments .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments .cm-bbox-seg-today{flex:none;height:100%;background:#ff9800}.cm-bbox-bar.segments .cm-bbox-seg-spent{flex:none;height:100%;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-fill:first-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments.rev .cm-bbox-fill,.cm-bbox-bar.segments.rev .cm-bbox-fill:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}.cm-dir-row{display:flex;align-items:center;gap:8px;margin-top:6px}.cm-dir-label{flex:1 1 40%;font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-dir-row .cm-input{flex:1 1 60%;width:auto}.cm-bbox-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary)}.cm-balance-name{display:inline-flex;align-items:center;gap:4px;min-width:0}.cm-model-costs{font-size:12px}.cm-model-costs .cm-bal-label{white-space:nowrap}.cm-model-top{gap:4px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.cm-model-costs .cm-collapse-h{min-width:0;width:100%;white-space:nowrap}.cm-model-costs .cm-bbox-bar{margin-top:3px}.cm-bal-label{min-width:0;overflow:hidden;text-overflow:ellipsis}.cm-bal-amt{margin-left:auto;text-align:right;flex-shrink:0}.cm-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}.cm-bal-link{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:2px;border-radius:4px;font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary);text-decoration:none;outline:none}.cm-bal-link:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-interactive-bg-hover)}.cm-bal-link:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-bbox.warn .cm-bbox-fill,.cm-bbox .cm-bbox-section.warn .cm-bbox-fill,.cm-bbox .cm-mm-row.warn .cm-bbox-fill,.cm-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-fill,.cm-bbox-section.over .cm-bbox-fill,.cm-mm-row.over .cm-bbox-fill,.cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}.cm-bbox-line{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-bbox-rail{font-size:11px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct,.cm-bbox.warn .cm-bbox-rail,.cm-bbox .cm-bbox-section.warn .cm-bbox-pct,.cm-bbox .cm-mm-row.warn .cm-bbox-pct,.cm-mm-row.warn .cm-bbox-label,.cm-corner-chip.warn,.cm-qchip.warn,.cm-simple-summary.warn{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct,.cm-bbox.over .cm-bbox-rail,.cm-bbox-section.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-label,.cm-corner-chip.over,.cm-qchip.over,.cm-simple-summary.over{color:var(--dsw-alias-state-error-primary)}.cm-bbox-pair{display:flex;flex-direction:column;gap:0;padding:2px 10px}.cm-bbox-pair .cm-bbox-section{display:flex;flex-direction:column;gap:4px;padding:4px 0}.cm-bbox-pair .cm-bbox-bar{height:4px}.cm-bbox-divider{height:1px;background:var(--dsw-alias-border-l1);margin:0}.cm-bbox.clickable,.cm-foot.clickable{cursor:pointer}.cm-bbox.clickable:hover{border-color:var(--dsw-alias-state-business-primary)}.cm-bbox.clickable:focus-visible,.cm-foot.clickable:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}@keyframes cm-click-refresh-pulse{0%,to{opacity:.55}50%{opacity:1}}.cm-bbox.clickable.busy,.cm-foot.clickable.busy{animation:cm-click-refresh-pulse 1.1s ease-in-out infinite}.cm-mm{padding:8px 10px;gap:4px}.cm-mm-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-mm-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);grid-column:1/-1}.cm-gw-switcher{cursor:pointer;user-select:none;font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}.cm-gw-switcher:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.cm-gw-sub{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-mm-row{display:flex;align-items:center;gap:8px;padding:2px 0}.cm-mm-row .cm-bbox-label{flex:none;width:auto;min-width:22px;max-width:115px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;word-break:keep-all}.cm-mm-row .cm-bbox-bar{flex:1;min-width:40px;height:6px}.cm-mm-row .cm-bbox-pct{flex:none;min-width:2.4em;text-align:right;font-variant-numeric:tabular-nums}.cm-mm-row.wide .cm-bbox-label{width:auto;max-width:64px;flex:0 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-mm-row.wide .cm-mm-text{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-bal-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-bal-line.warn{color:var(--dsw-alias-state-warning-primary,#b45309)}.cm-footer-stack{display:flex;flex-direction:column;gap:6px;width:100%;align-items:stretch;box-sizing:border-box}.cm-footer-stack.rail{align-items:center}.cm-footer-stack .cm-bbox{width:100%;min-width:0}.cm-footer-stack .cm-foot{width:100%;box-sizing:border-box}.cm-footer-stack.compact .cm-bbox{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:2px;align-items:center}.cm-footer-stack.compact .cm-bbox>*{grid-column:1/-1}.cm-footer-stack.compact .cm-bbox>.cm-mm-row{grid-column:auto}.cm-footer-stack.compact .cm-mm-row{min-width:0;gap:4px;flex-wrap:nowrap}.cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:0 1 auto;min-width:0;max-width:45%;width:auto}.cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0;flex:1 1 0}.cm-footer-stack.simple{gap:0;max-height:38vh;max-height:min(38dvh,320px);overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.cm-footer-stack.simple>*{flex-shrink:0}.cm-footer-stack.simple:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}.cm-footer-stack.simple .cm-bbox{border:0;border-radius:0;padding:4px 8px;gap:2px;background:transparent;box-shadow:inset 0 -1px var(--dsw-alias-border-l1)}.cm-footer-stack.simple .cm-mm-title{font-size:11px;line-height:16px;margin:0}.cm-footer-stack.simple .cm-mm-row{gap:6px;min-height:16px;line-height:16px;margin:0;padding:0}.cm-footer-stack.simple .cm-mm-text{font-size:11px}.cm-footer-stack.simple>.cm-peak-strip,.cm-footer-stack.simple>.cm-peak-classic{margin:0;padding:4px 8px}.cm-simple-summary>span{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-footer-stack.simple .cm-bbox-pct{font-size:12px;line-height:18px}.cm-footer-stack.simple .cm-bbox-bar{height:4px}.cm-footer-stack.simple .cm-bbox-line{display:none}.cm-footer-stack.simple .cm-foot{height:26px;padding:0 8px}.cm-footer-stack.simple .cm-peak-classic{margin-top:2px;gap:2px}.cm-footer-stack.simple .cm-peak-classic-chip{padding:0 4px;border:0;background:transparent}.cm-simple-summary{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 8px;font-size:12px;font-weight:600;border-bottom:1px solid var(--dsw-alias-border-l1)}.cm-footer-stack.simple.rail{border:0;background:transparent}.cm-footer-stack.simple.rail .cm-bbox{padding:4px 2px}.cm-footer-stack.simple .cm-peak-rail-track,.cm-footer-stack.simple .cm-peak-rail-classic-track{height:28px}@media(max-width:640px){.cm-cards,.cm-grid,.cm-budget-controls{grid-template-columns:1fr}}',Ft="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(Ft)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=Ft,t.textContent=qa,document.head.appendChild(t)}const Te={zh:{sessionCostTitle:"本会话费用(按每次调用实际时刻精确计费)",sessionDetailTokens:"输入 {input} · 缓存 {cache} · 输出 {output}",sessionDetailCache:"缓存:读 {read} · 写 {write}(写入按命中价计费)",cost:"费用 {amount}",sessionLine:"本会话 {amount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",quotaUnlimited:"无限制",pricingCnyHint:"当前人民币金额来自美元价格 × 汇率 {rate}。对照官方人民币账单,请选择 CNY,再同步价格;同步会更新历史费用。",balanceQueryFailed:"余额查询失败:{message}",unknownError:"未知错误",balance:"余额",queryFailed:"查询失败",balanceTitle:"DeepSeek 开放平台账户余额",reconcileLabel:"官方余额变动与本地账本交叉对账(偏差超阈时提示)",totalBalance:"总余额 {amount}",grantedToppedUp:"赠送 {granted} · 充值 {toppedUp}",updatedAt:"更新时间 {time}",budgetOf:"预算({period})",usedOf:"已用 {used} / {amount}",todayShare:"今日 {amount} · 占预算 {pct}",monthTotal:"本月 {month} · 累计 {total}",budget:"预算",todayCostTitle:"今日费用(按官方价格精确计费)",todayTokensTitle:"今日 Token 用量",tokensUnit:"tokens",callsTokens:"调用 {calls} 次 · 输入 {input} · 缓存 {cache} · 输出 {output}",monthCost:"本月 {amount}",totalCost:"累计 {amount}",today:"今日",sidebarTodayMetric:"侧边栏今日显示",sidebarTodayCost:"费用",sidebarTodayTokens:"Token 用量",periodDay:"今日",periodMonth:"本月",periodAll:"累计",periodCustomRange:"自定义区间",noHistory:"暂无历史记录。开始对话后,费用将按天汇总在这里。",colDate:"日期",colCalls:"调用",colInTok:"输入 tok",colCacheTok:"缓存 tok",colOutTok:"输出 tok",colCost:"费用",noSessionsToday:"今日暂无会话记录。",colSession:"会话",enableBudget:"启用预算",budgetAmountLabel:"预算额度(按显示币种)",budgetPeriodLabel:"预算周期",startDate:"开始日期",endDate:"结束日期(留空 = 今日)",rangeText:"统计区间:{range}",budgetDisabledNote:"启用预算后显示额度、已用金额及比例(按显示币种换算);可选今日、本月、累计或自定义周期。",budgetStatus:"{period}预算 {amount} · 已用 {used} · {pct}%",overLimit:"(已超出)",nearLimit:"(接近上限)",legacyModel:"旧模型",defaultFallback:"默认回退",remove:"移除",tierBase:"基础",tierOffPeak:"谷时",tierPeak:"峰时",balanceRefreshFailed:"余额刷新失败:{message}",balanceLine:"总余额 {total} · 赠送 {granted} · 充值 {toppedUp} · 更新于 {time}",balanceQueryFailedHint:"余额查询失败:{message}(使用 设置→模型 中配置的 API Key)",balanceNotQueried:"未查询余额",accountBalance:"官方账户余额",refreshing:"刷新中…",refreshBalance:"刷新余额",customBalanceTitle:"自定义 Provider 余额",customBalanceAdd:"添加配置",aliyunBalanceAdd:"添加千问 / 阿里云余额",aliyunBalanceNote:"查询阿里云中国站可用金。RAM AccessKey 需 bss:DescribeBillingAccount 权限。前两项必填;STS 才需 Security Token。密钥存凭据库。",customBalanceConfigNote:"extract 支持点路径、数值和 add/subtract/divide 运算;NewApi quota 除以 500000 得到美元。",customBalanceLabelZh:"中文名称",customBalanceLabelEn:"英文名称",customBalanceUrl:"请求 URL",customBalanceMethod:"请求方法",customBalanceHeaders:"请求头 (JSON)",customBalanceBody:"请求体 (JSON)",customBalanceBodyNote:"留空不发送;JSON 原文保存并发送。默认 Content-Type 为 application/json,可在请求头覆盖。",customBalanceExtract:"解析规则 (JSON)",customBalanceDisplayLabel:"自定义余额显示位置",customBalanceRefreshInterval:"刷新间隔 (分钟)",customBalanceUnitLabel:"余额原币种",customBalanceConvert:"按显示币种折算(USD 余额)",customBalanceConvertNote:"使用显示汇率与精度;余额币种保持端点原币种。其他币种及积分不折算。",balanceBarRemaining:"余额 {amount}",balanceBarToday:"当日已用 {amount}",balanceBarSpent:"已用 {amount}",balanceShowProgressBar:"余额进度条 (蓝=余额,橙=当日,灰=已用)",barDirectionsTitle:"进度条方向",barDirectionsHint:"各组进度条可独立选择填充方向:「剩余方向」满条起步、随消耗递减;「已用方向」空条起步、随消耗填满。",barDirection_balance:"余额条(官方/自定义)",barDirection_budget:"预算条",barDirection_go:"Go 额度条",barDirection_plan:"Plan / Codex 额度条",barDirectionRemaining:"剩余方向(满 → 空)",barDirectionUsed:"已用方向(空 → 满)",balanceBudgetCapLabel:"额度上限 (可选)",balanceBudgetCapHint:"留空则优先使用 API 返回的 max_budget;仍无则显示整条浅蓝",customBalanceInvalidJson:"JSON 格式无效",customBalanceHeadersVarNote:"{{VAR_NAME}} 从凭据库或环境变量读取。<ROUTE>_API_KEY 中 ROUTE 为大写 Provider ID,符号改下划线,如 openai→OPENAI_API_KEY。同名共用密钥。",customBalanceAllowedHosts:"凭据白名单 (逗号分隔)",customBalanceAllowedHostsHint:"请求头带密钥时仅放行列表内主机,留空则放行并警告,防导入他人配置外带密钥。",customBalanceCredentialsTitle:"凭据输入",customBalanceCredentialsHint:"为上方 {{VAR}} 占位符存入密钥(write-only,只写凭据库,不回显):",customBalanceNoPlaceholders:'请求头还没有 {{VAR}} 占位符:填入如 "Authorization": "Bearer {{MY_API_KEY}}" 后这里会出现凭据输入框。',enable:"启用",customBalanceLine:"剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}",customBalanceRemaining:"剩余 {amount}",refreshCustomBalance:"刷新自定义余额",goQuotaTitle:"OpenCode Go 订阅额度",goQuotaRowLabel:"Go",goWindowRolling:"滚动 5 小时",goWindowWeekly:"本周",goWindowMonthly:"本月",goResetAt:"重置:{time}",resetReached:"已到重置时间",resetDays:"剩余 {d}天{h}小时",resetHours:"剩余 {h}小时{m}分",resetMinutes:"剩余 {m}分钟",quotaUsed:"已用 {pct}%",quotaRemaining:"剩余 {pct}%",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"更新于 {time}",goQuotaDisplayLabel:"Go 额度显示位置",goQuotaRefreshIntervalLabel:"Go 额度刷新间隔(分钟)",goQuotaRefreshMinutesUnit:"分钟",goQuotaKeyLabel:"OpenCode Go API Key(可选,留空自动发现)",goMainLabel:"Go 额度主档位",goDetailLabel:"Go 图框详细信息",credentialConfiguredOf:"已配置(来源:{source})",credentialNotConfigured:"未配置",credentialSave:"保存",credentialClear:"清除",credentialSaving:"保存中…",credentialInputHint:"密钥只写入 DSH 凭据库,不保存在账本里,也不会回显。",secretMigrationPending:"以下密钥仍在本地账本,未迁入凭据库。请导出对应环境变量后重启:",budgetDetailLabel:"预算图框详细信息",refreshGoQuota:"刷新额度",goQuotaNotQueried:"未查询额度",codingPlanAnthropic:"Anthropic(Claude Pro/Max)",codingPlanZai:"Z.ai / 智谱 GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"查询域名(HTTPS)",minimaxOriginNote:"留空自动选择官方站点。填写后 Key 仅发往该域名;使用可信地址,不含路径。",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"打开 DeepSeek 充值页(platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) 周额度",codexQuotaEnabled:"显示 Codex 额度(需安装并登录 dsh-openai-codex)",includeSubagentCost:"本会话费用包含子代理",gatewayQuotaEmpty:"暂无额度数据",codingPlanDisplayLabel:"显示位置",codingPlanDisplayNote:"选「主页面侧边栏 / 两者」后显示额度卡片;窄栏显示百分比。",codingPlanKeyLabel:"API Key(可选,留空自动发现)",codingPlanRefreshIntervalLabel:"刷新间隔(分钟)",refreshCodingPlan:"刷新",codingPlanNotQueried:"未查询额度",gatewayQuotaTitle:"CLIProxyAPI 网关额度",gatewaySourceAdd:"添加来源",gatewaySourceLabel:"来源名称",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"显示位置",gatewaySourceAllowlist:"允许的 Host",gatewaySourceCredential:"Management Key(只写)",gatewaySourceStatus:"状态",gatewaySourceUnsupported:"不支持的 Provider",gatewaySourceUnknown:"未知",gatewaySourceNoAccounts:"未发现账号",gatewaySourceFetchedAt:"抓取于 {time}",gatewaySwitchAccount:"切换账号 (当前: {account})",gatewayOnlyGemini:"只显示 Gemini 额度",refresh:"刷新",quotaEnableFirst:"先勾选启用这一项",quotaRefreshReady:"启用并保存显示位置后可刷新",quotaRemove:"删除",quotaSectionNote:"勾选启用后会排到最上面;点名称可展开该项自己的配置。自定义余额最多 8 条,网关来源最多 4 条。",codingPlanDisabledNote:"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。",goQuotaDisabledNote:"开启后读取 OpenCode Go 的滚动 5 小时、周、月额度,显示在侧栏、设置页及右下角;无订阅时提示原因。",cornerLabel:"右下角显示(dock)",cornerEnabledLabel:"在右下角显示 OpenCode Go 额度 / 预算",cornerGoRolling:"滚动 5 小时额度",cornerGoWeekly:"本周额度",cornerGoMonthly:"本月额度",cornerBudget:"预算已用%",goShortRolling:"5h",goShortWeekly:"周",goShortMonthly:"月",goShortDaily:"日",budgetShort:"预算",ledgerReadFailed:"账本读取失败:{message}",readingLedger:"正在读取账本…",ledgerUnavailable:"账本不可用",syncFailed:"同步失败:{message}",historyCleared:"历史记录已清除。",clearFailed:"清除失败:{message}",peakOff:"峰谷计价已关闭,按基础价格计费",peakNotEffective:"尚未生效(生效时间:{time}),当前按基础价格计费",peakActive:"当前处于峰时段,按峰时价计费",peakNotice:"当前为 DeepSeek 峰时高价时段,按峰时价计费",offPeakActive:"当前处于谷时段,按谷时价计费",weekendAllOffPeak:"周末时段——全谷价(周六及周日全天按谷时价计费)",weekendChip:"周末时段——全谷价",weekendShort:"周末全谷",holidayAllOffPeak:"法定假日——全天谷价",holidayChip:"法定假日——全谷价",holidayShort:"假日",peakHolidaysLabel:"法定假日(北京日期,逗号分隔)",weekendRuleNote:"自 2026-08-23 北京时间 00:00 起,周末和中国公众假期全天谷价;调休上班的周末仍按谷价。",peakShort:"峰时",offPeakShort:"平价",peakStyleLabel:"峰谷时段条样式",peakStyleCompact:"简洁(单行紧凑)",peakStyleClassic:"经典(分段与胶囊芯片)",peakAlertLabel:"峰/谷切换前弹窗提醒",peakAlertAheadLabel:"提前提醒(分钟,1-30)",peakAlertTargetLabel:"提醒类型",peakAlertTargetPeak:"进入峰时",peakAlertTargetOffPeak:"进入谷时",peakAlertTargetBoth:"峰和谷",peakAlertTitlePeak:"即将进入峰时",peakAlertTitleOffPeak:"即将进入谷时",peakAlertBody:"约 {time} 后计费档位切换为{phase}价,请注意本时段调用成本。",peakAlertPhasePeak:"峰时",peakAlertPhaseOffPeak:"谷时",peakAlertBtn:"知道了",peakAlertBadgePeak:"峰价提醒",peakAlertBadgeOffPeak:"谷价提醒",peakAlertPositionLabel:"弹窗位置",peakAlertPositionCorner:"右下角",peakAlertPositionCenter:"屏幕中心",peakAlertWebNotifyLabel:"同步发送系统通知",peakAlertWebNotifyHint:"开关后请在浏览器地址栏允许通知权限,才能在页面最小化/切走时收到提醒。",peakAlertPreviewLabel:"预览弹窗",peakAlertPreviewPeak:"预览 进入峰",peakAlertPreviewOffPeak:"预览 进入谷",peakAlertPreviewTag:"(预览)",peakPanelTitle:"峰谷计价与提示",peakNoticeHiddenHint:"提示已隐藏:需启用峰谷计价并开启「峰时高价时段显著提示」。",groupGeneral:"常规",groupMoney:"金额与币种",groupSidebar:"侧边栏显示",sidebarSimple:"简化侧栏显示",sidebarSimpleNote:"精简卡片,保留金额、额度和悬停详情;高度最多占屏幕 38%,超出可滚动。关闭后恢复。",sidebarSimpleTitle:"试试更轻巧的侧栏",sidebarSimpleBody:"简化显示可以为会话列表留出更多空间。要现在开启吗?之后可在「设置 → 费用 → 显示」中切换。",sidebarSimpleOn:"开启简化显示",sidebarSimpleOff:"保留当前显示",sidebarSimpleError:"设置未能保存。可重试,或关闭提示后在设置中调整。",closeGuide:"关闭提示",todayBudget:"今日 / {period}预算",sidebarStyleLabel:"侧边栏进度条样式",sidebarStyleStandard:"标准",sidebarStyleCompact:"紧凑(两列)",restorePriceMatches:"恢复已移除的模型 ({count})",removePriceMatchHint:"移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按自动匹配规则计价。",groupCorner:"右下角角标",groupDetail:"图框详细信息",catalogTitle:"拓展价格表",catalogNote:"按厂商和模型分类的参考价。挂载后可编辑并计费;DeepSeek 取消挂载后用默认价。",catalogOpen:"展开拓展价格表",catalogCollapse:"收起拓展价格表",mountBtn:"挂载",unmountBtn:"取消挂载",mountedTag:"已挂载",catalogUnpriced:"未核价",catalogDeepseekNote:"DeepSeek 取消挂载后按默认价计费。",modelStatsTitle:"按模型统计(token 与费用)",modelsTitle:"侧栏模型花费",modelsCount:"{n} 模型",modelsOther:"其它",models_enabled:"显示模型花费卡片",models_defaultOpen:"默认展开",models_remember:"记住展开状态",models_tokens:"显示 Token",models_shares:"显示费用占比条",models_dock:"右下角显示 Top-1 模型",models_period:"默认周期",models_summary:"收起摘要",models_position:"卡片位置",models_topN:"模型行数(1–10)",models_refreshSeconds:"刷新间隔(10–60 秒)",modelsTotal:"周期总额与模型数",modelsTop:"Top-1 模型与金额",modelsFirst:"顶部",modelsAfter:"余额之后",modelsLast:"底部",modelStatsToday:"今日",modelStatsHistory:"近 90 天",modelStatsCostH:"费用排行",modelStatsTokensH:"Token 消耗",modelStatsHitH:"缓存命中率",modelStatsHitUnreported:"未上报?",modelStatsHitUnreportedTip:"长调用无缓存命中:代理可能移除缓存字段。金额按全未命中计,是上界;可直连核对。",modelStatsValueH:"性价比 · 每美元 token 数",modelStatsInput:"输入",modelStatsCache:"缓存",modelStatsOutput:"输出",modelStatsEmpty:"该时段暂无用量数据。",modelStatsBlended:"综合单价 {price}/M",modelStatsNote:"命中率=缓存读÷(缓存读+普通输入);「未上报?」表示缓存字段可能缺失,金额为上界。单价=费用÷token×1M;性价比=token÷费用。",modelStatsLegacy:"未分模型(早期数据 · 按当时记录计费)",sessionLineSplit:"本会话 {amount}(API)· Plan 等值 {planAmount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",costChipPlan:"费用 {amount}(+Plan)",sessionDetailPlan:"Plan 订阅额度消耗(等值){amount}",planStatsTitle:"Token Plan 用量统计(每 1% 与满窗估算)",planStatsEmpty:"尚无 Coding Plan 额度数据;请在「额度」页开启并刷新厂商。",planStatsWindow:"窗口",planStatsPercent:"已用 %",planStatsLocal:"本周期实际(本地账本)",planStatsPer1:"每 1% 额度 ≈",planStatsFull:"满窗 100% ≈",planStatsResets:"重置 {time}",planStatsMethodSample:"采样差分",planStatsMethodLive:"当前用量折算",planStatsMethodNone:"样本不足",planStatsMethodSampleAt:"{method}(基准 {time})",planStatsConfidenceLow:"读数精度受限",planStatsCurveTitle:"Plan 用量曲线(按采样区间聚合)",planStatsDaily:"每日",planStatsWeekly:"每周",planStatsMonthly:"每月",planStatsCurveEmpty:"采样不足:至少两次成功刷新,且额度百分比发生变化。",planStatsBarTip:"{date}:满窗估计 ≈ {full}(每 1% ≈ {per1})· 实际 {tokens} / {cost} · {intervals} 个采样区间",planStatsNote:"金额是目录价等值;订阅耗额度,预算只计 API。估算仅含 dsh 调用;服务端百分比含全账号。短时样本精度有限;5h 滚动,周/月按本地日历。",billingClassLabel:"计费方式",billingClassPlan:"Plan 订阅",billingClassAuto:"自动",billingClassApi:"API 按量",catalogDisplayLabel:"在费用设置直接显示",catalogDisplayHint:"仅控制是否在费用价格表直接显示;不影响挂载和计费。隐藏的已挂载模型仍可在拓展表编辑。",priceTableDisplayHint:"可逐模型切换显示位置。DeepSeek 默认直接显示,第三方默认在拓展表。",catalogCustomModels:"手动新增模型",priceMatchLabel:"未知模型名自动匹配",priceMatchAuto:"自动(去后缀 / 前缀 / 家族相似)",priceMatchExact:"仅精确匹配",priceMatchNote:"手动指定优先;自动匹配只接受同名及日期、版本、上下文后缀。未命中的 DeepSeek 用默认价,其他渠道不计价。",unmatchedTitle:"最近出现但未命中价格的模型",unmatchedHint:"这些模型没有价格。可手动指定;「默认价」使用 DeepSeek 默认价。本地推理默认零费用。",overrideTargetDefault:"DeepSeek 默认价",overrideRemove:"移除",overrideTargetLocal:"本地模型(零消耗)",matchedTitle:"本月已命中价格的模型",matchedHint:"这些模型自动匹配价格。可改选价格或零费用;token 仍统计。保存后移入手动指定区。",matchedKeepAuto:"保持自动命中",overrideNone:"暂无手动匹配覆盖。",mountedSuffix:"已挂载(参与计费)",flatInput:"输入",flatCached:"缓存",flatOutput:"输出",deepseekMountedHeader:"DeepSeek 价格表(已挂载)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow 硅基流动",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet 超算互联网 Token Plan",codingPlanVolcengine:"火山方舟 Volcano Ark Coding Plan",codingPlanQwen:"千问 Qwen Token Plan",codingPlanMimo:"小米 MiMo Token Plan",mimoWindowPlan:"套餐积分",mimoWindowCompensation:"补偿积分",codingPlanWindowBalance:"余额",qwenSource:"额度来源",qwenSourceLocal:"本地估算",qwenSourceCli:"官方 CLI",qwenSourceBailian:"百炼 CLI",qwenCliNote:"CLI 模式需在 DSH 主机安装 @qianwenai/qianwen-cli,并以同一系统账号运行 qianwen auth login。",qwenBailianNote:"百炼 CLI:在 DSH 主机安装 bailian-cli 并以同一系统账号运行 bl auth login --console。",qwenPlanCreditsLabel:"月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)",qwenPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",qwenRatesLabel:"Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)",qwenRatesModelPlaceholder:"模型名,如 qwen3.8-max-preview",qwenRatePlaceholder:"费率",qwenRate_input:"输入",qwenRate_cachedInput:"缓存读",qwenRate_output:"输出",qwenRateDraftNote:"待填齐三项正数后自动保存;全部清空恢复内置表。",qwenRatesAdd:"添加",qwenLocalNote:"Credits 本地估算,以控制台为准。只计 qwen 及 qwen/qianwen-tokenplan 订阅渠道,含 llm- 前缀;不计按量 API。表外模型需设抵扣率。",scnetPlanCreditsLabel:"本地估算月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)",scnetPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",scnetLocalNote:"优先用 24 小时内的控制台快照,否则按本地账本和官方 Credits 表估算。其他工具和表外模型不计入。",volcengineAccessKeyIdLabel:"火山引擎 AccessKey ID",volcengineSecretAccessKeyLabel:"火山引擎 SecretAccessKey",volcengineNote:"火山方舟需 AK/SK、ArkReadOnlyAccess 和 BillingCenterReadOnlyAccess;可填凭据或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。只连接 open.volcengineapi.com。",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}小时",countdownHourMinute:"{h}小时{m}分",countdownMinute:"{m}分钟",nextOffPeakIn:"{time}后进入平价",nextPeakIn:"{time}后进入高峰",peakSummary:"峰时段(UTC):{windows};生效时间:{time}。{status}",noPeakWindows:"未配置峰谷时段。{status}",unknown:"未知",cardToday:"今日费用",cardMonth:"本月费用",cardTotal:"累计费用",cardTotalSub:"自账本建立以来 · 调用 {calls} 次",externalUsage:"外部用量",combinedUsage:"DSH + 外部合计",externalStale:"外部快照超过 24 小时未更新",externalHistory:"近期每日记录",cardsFootnote:"金额取最近快照,可能比官方账单晚几分钟。tokens 含输入、输出、缓存和推理;推理并入输出计费。以金额对账。",timezoneHint:"今日/本月按宿主时区 {host},浏览器为 {browser}。时区不同会影响日界和对账;可将 dsh 改为本地时区。",todaySessions:"今日会话",historyExpandHint:"点击日期行可展开当日会话明细",historySessionsLoading:"会话明细加载中…",historyNoSessions:"该日无会话明细(早期数据或会话日志已清理)",historySessionsError:"会话明细加载失败",sessionRankTitle:"按会话统计(全部历史)",sessionRankHint:"不按日期分组,全部历史会话;排序与条数可切换",sessionRankEmpty:"暂无会话数据",sessionRankLoading:"会话排行加载中…",sessionRankError:"会话排行加载失败",sessionRankLimit:"显示条数",showSessionIdLabel:"会话列表附显会话 ID",cardsTogglePlanTotal:"金额含 Plan 总额",cardsTogglePlanTotalHint:"开启后所有金额按含 Plan 订阅等值的总费用展示;关闭(默认)仅计真金白银 API 渠道",hideOfficialBalanceLabel:"隐藏官方账户余额(开启后侧边栏与设置页不再显示官方余额)",hideTodayCostLabel:"隐藏今日消耗金额(开启后侧边栏/预算明细/概览卡片不再显示今日费用)",sessionRankSort:"排序",sessionSortCostDesc:"费用 高→低",sessionSortCostAsc:"费用 低→高",sessionSortTimeDesc:"时间 新→旧",sessionSortTimeAsc:"时间 旧→新",sessionSortRecent:"实时顺序",history:"历史记录",usageTitle:"Token 用量统计",usageTotal:"累计 {tokens} tokens · 输入 {input} · 缓存 {cache} · 输出 {output} · {calls} 次调用",usageDay:"{date}:共 {tokens} tokens(输入 {input} · 缓存 {cache} · 输出 {output})· {calls} 次调用 · {cost}",usageEmpty:"暂无历史数据,开始对话后每日用量会汇总在这里",usageSectionLabel:"用量",usagePositionLabel:"Token 用量统计位置",usagePositionCost:"费用设置",usagePositionGeneral:"通用设置",usagePositionSection:"独立分节(用量)",displaySettings:"显示设置",tabOverview:"概览",tabQuotas:"额度",tabUsage:"用量",tabPricing:"价格",tabDisplay:"显示",historyDataTitle:"历史数据",positionLabel:"会话费用显示位置",positionDock:"输入区下方",positionHeader:"会话标题栏",off:"关闭",quotaStripGroup:"输入框上方额度横条",quotaStripEnable:"启用额度横条(输入框上方一条横排显示)",quotaStripShowBudget:"横条含预算已用%",quotaStripShowGo:"横条含 Go 额度",quotaStripShowPlans:"横条含 Coding Plan 额度",quotaStripNote:"横条悬停可见各窗口重置时刻与更新时间;无可用额度数据时自动隐藏。",quotaStripGuideTitle:"新增:输入框上方额度横条",quotaStripGuideBody:"在输入框上方显示预算及 OpenCode Go/Coding Plan 额度百分比。现在开启吗?可在「设置 → 显示设置」修改。",quotaStripGuideOn:"开启横条",quotaStripGuideOff:"暂不开启",clickToRefresh:"点击立即刷新",balanceClickGuideTitle:"新增:余额图框点击刷新",balanceClickGuideBody:"点击侧边栏余额或 Coding Plan 图框即可刷新;刷新时图框闪烁,失败时保留原值并在悬停提示中说明原因。",balanceClickGuideOk:"知道了",sidebarLabel:"当日费用显示",sidebarOn:"侧边栏底部",currencyLabel:"货币单位",currencyCny:"人民币 CNY",currencyUsd:"美元 USD",currencyEur:"欧元 EUR",symbolLabel:"货币符号",rateLabel:"汇率(1 美元 = ? 目标币种)",decimalsLabel:"小数位数",balanceDisplayLabel:"余额显示位置",balanceSidebar:"主页面侧边栏",balanceSettings:"设置页",balanceBoth:"两者都显示",refreshIntervalLabel:"余额刷新间隔(分钟)",peakEnabledLabel:"启用 DeepSeek 峰谷时段价格",peakNoticeLabel:"峰时高价时段显著提示(侧边栏预算框/今日费用;设置页峰谷面板内预览)",badgeNote:"会话按调用时价格计费(含峰谷与历史档位)。输入、输出、缓存读写分开统计;独立缓存写入价与长上下文档位按配置生效。",priceTableTitle:"价格表(美元 / 1M tokens)",pricingCurrencyLabel:"官方价格币种",pricingCurrencyUsd:"美元(英文官方页)",pricingCurrencyCny:"人民币(中文官方页)",pricingCurrencyNote:"决定同步价格所用的官方页语言。切换并同步后后台重算历史;日志不全的会话保留原价。完成后提示。",priceTableNote:"按调用时间计价:Flash 自 9 月 10 日北京 12:00 用新价,V4 Pro 自 9 月 14 日同刻用 Flash 价;此前用历史价。工作日 09–12、14–18 峰价翻倍;周末及中国公众假期全天谷价。缓存写入按命中价。",datedPriceNote:"这里显示当前适用价格。手工编辑会取消此条后续预定调价,已发生的历史价格仍保留。",defaultModelId:"default(未匹配模型时回退)",newModelPlaceholder:"新模型 ID(如 deepseek-v4-pro)",addModel:"添加模型",dataSync:"数据与同步",saving:"保存中…",autoSaveFailed:"自动保存失败:{message}",autoSavedAt:"已自动保存 {time}",autoSaveHint:"配置修改后自动保存",confirmFetch:"确认用官方文档价格覆盖价格表?",apply:"应用",cancel:"取消",syncFromDocs:"从官方文档同步价格",syncScopeNote:"官方同步只更新 DeepSeek 价格(含峰谷);z-ai/Kimi/Qwen/Volcano 等第三方价格随版本更新,也可在拓展价格表或模型名匹配中调整。",confirmReset:"确认清除全部历史?",importLegacy:"导入安装前历史",confirmImportLegacy:"确认导入?将回放全部会话日志,只补账本缺失的日期与会话,不影响已有记录。",legacyImportFailed:"导入安装前历史失败:{message}",legacyImportNote:"首次启动自动导入旧记录;拷入日志后可重跑。按当前价格回推;已删除日志无法回放,跨安装时刻的会话不计此前用量。",confirmClear:"确认清除",clearAllHistory:"清除全部历史",lastSync:"最近同步:{time}",neverSynced:"从未(使用内置价格)",source:";来源:{source}",sourceOfficial:"官方文档",sourceBundled:"内置默认",languageLabel:"界面语言",localeAuto:"跟随浏览器(自动)",localeZh:"简体中文",localeEn:"English",sectionLabel:"费用",rpcFailed:"{method} 调用失败",rpcSyncFailed:"同步调用失败",rpcBalanceFailed:"余额刷新调用失败"},en:{sessionCostTitle:"Cost of this session (billed exactly at each call time)",sessionDetailTokens:"Input {input} · Cache {cache} · Output {output}",sessionDetailCache:"Cache: read {read} · write {write} (writes billed at the hit price)",cost:"Cost {amount}",sessionLine:"This session {amount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",quotaUnlimited:"Unlimited",pricingCnyHint:"CNY totals use USD prices × {rate}. To compare official CNY bills, select CNY, then sync prices; syncing also updates historical costs.",balanceQueryFailed:"Balance query failed: {message}",unknownError:"Unknown error",balance:"Balance",queryFailed:"Query failed",balanceTitle:"DeepSeek open-platform account balance",reconcileLabel:"Cross-check official balance changes against the local ledger (warn when they diverge)",totalBalance:"Total {amount}",grantedToppedUp:"Granted {granted} · Topped-up {toppedUp}",updatedAt:"Updated {time}",budgetOf:"Budget ({period})",usedOf:"Used {used} / {amount}",todayShare:"Today {amount} · {pct} of budget",monthTotal:"This month {month} · All time {total}",budget:"Budget",todayCostTitle:"Today's cost (billed exactly at official prices)",todayTokensTitle:"Today's token usage",tokensUnit:"tokens",callsTokens:"Calls {calls} · Input {input} · Cache {cache} · Output {output}",monthCost:"This month {amount}",totalCost:"All time {amount}",today:"Today",sidebarTodayMetric:"Sidebar today display",sidebarTodayCost:"Cost",sidebarTodayTokens:"Token usage",periodDay:"Today",periodMonth:"This month",periodAll:"All time",periodCustomRange:"Custom range",noHistory:"No history yet. Once you start chatting, costs are aggregated here per day.",colDate:"Date",colCalls:"Calls",colInTok:"In tok",colCacheTok:"Cache tok",colOutTok:"Out tok",colCost:"Cost",noSessionsToday:"No sessions recorded today.",colSession:"Session",enableBudget:"Enable budget",budgetAmountLabel:"Budget amount (in display currency)",budgetPeriodLabel:"Budget period",startDate:"Start date",endDate:"End date (empty = today)",rangeText:"Range: {range}",budgetDisabledNote:"Enable a budget to see its limit, used amount and percentage in the display currency. Choose today, month, all time or a custom range.",budgetStatus:"{period} budget {amount} · Used {used} · {pct}%",overLimit:" (over limit)",nearLimit:" (near limit)",legacyModel:"Legacy",defaultFallback:"Default fallback",remove:"Remove",tierBase:"Base",tierOffPeak:"Off-peak",tierPeak:"Peak",balanceRefreshFailed:"Balance refresh failed: {message}",balanceLine:"Total {total} · Granted {granted} · Topped-up {toppedUp} · Updated {time}",balanceQueryFailedHint:"Balance query failed: {message} (uses the API key configured in Settings → Models)",balanceNotQueried:"Balance not queried",accountBalance:"Account balance",refreshing:"Refreshing…",refreshBalance:"Refresh balance",customBalanceTitle:"Custom provider balance",customBalanceAdd:"Add entry",aliyunBalanceAdd:"Add Qianwen / Alibaba Cloud balance",aliyunBalanceNote:"Shows Alibaba Cloud China funds. RAM AccessKey needs bss:DescribeBillingAccount. The first two fields are required; Security Token is for STS. Secrets stay in the credential store.",customBalanceConfigNote:"Extract accepts paths, numbers and add/subtract/divide. Divide NewApi quota by 500000 for USD.",customBalanceLabelZh:"Chinese name",customBalanceLabelEn:"English name",customBalanceUrl:"Request URL",customBalanceMethod:"HTTP method",customBalanceHeaders:"Headers (JSON)",customBalanceBody:"Request body (JSON)",customBalanceBodyNote:"Blank sends no body; JSON text is saved and sent as entered. Content-Type defaults to application/json; headers can override it.",customBalanceExtract:"Extract rules (JSON)",customBalanceDisplayLabel:"Custom balance display",customBalanceRefreshInterval:"Refresh interval (minutes)",customBalanceUnitLabel:"Source currency",customBalanceConvert:"Convert USD balance to display currency",customBalanceConvertNote:"Uses the display rate and precision. Keep the source currency; other currencies and credits stay unchanged.",balanceBarRemaining:"Balance {amount}",balanceBarToday:"Today {amount}",balanceBarSpent:"Spent {amount}",balanceShowProgressBar:"Balance progress bar (blue=balance, orange=today, gray=spent)",barDirectionsTitle:"Progress bar direction",barDirectionsHint:'Each group of bars can independently choose its fill direction: "Remaining" starts full and drains with usage; "Used" starts empty and fills up.',barDirection_balance:"Balance bars (official/custom)",barDirection_budget:"Budget bar",barDirection_go:"Go quota bar",barDirection_plan:"Plan / Codex quota bars",barDirectionRemaining:"Remaining (full → empty)",barDirectionUsed:"Used (empty → full)",balanceBudgetCapLabel:"Budget cap (optional)",balanceBudgetCapHint:"Leave empty to use API max_budget; if still missing, show full light-blue bar",customBalanceInvalidJson:"Invalid JSON",customBalanceHeadersVarNote:"{{VAR_NAME}} reads a credential or environment variable. <ROUTE>_API_KEY uses an uppercase Provider ID with underscores, such as openai→OPENAI_API_KEY. Names can share a key.",customBalanceAllowedHosts:"Allowed hosts (comma-separated)",customBalanceAllowedHostsHint:"When headers carry credentials only listed hosts are allowed; leave empty to allow with a warning. Protects keys when importing someone else's config.",customBalanceCredentialsTitle:"Credential input",customBalanceCredentialsHint:"Store the key for each {{VAR}} placeholder above (write-only: stored in the DSH credential store, never echoed back):",customBalanceNoPlaceholders:'No {{VAR}} placeholders in the headers yet — add e.g. "Authorization": "Bearer {{MY_API_KEY}}" and a credential input will appear here.',enable:"Enable",customBalanceLine:"Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}",customBalanceRemaining:"Remaining {amount}",refreshCustomBalance:"Refresh custom balance",goQuotaTitle:"OpenCode Go subscription quota",goQuotaRowLabel:"Go",goWindowRolling:"Rolling 5h",goWindowWeekly:"Weekly",goWindowMonthly:"Monthly",goResetAt:"Resets: {time}",resetReached:"Reset time reached",resetDays:"{d}d {h}h left",resetHours:"{h}h {m}m left",resetMinutes:"{m}m left",quotaUsed:"{pct}% used",quotaRemaining:"{pct}% remaining",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"Updated {time}",goQuotaDisplayLabel:"Go quota display position",goQuotaRefreshIntervalLabel:"Go quota refresh interval (minutes)",goQuotaRefreshMinutesUnit:"min",goQuotaKeyLabel:"OpenCode Go API key (optional; empty = auto-detect)",goMainLabel:"Go quota primary window",goDetailLabel:"Go box details",credentialConfiguredOf:"Configured (source: {source})",credentialNotConfigured:"Not configured",credentialSave:"Save",credentialClear:"Clear",credentialSaving:"Saving…",credentialInputHint:"The key is written to the DSH credential store only — it is never saved in the ledger and never echoed back.",secretMigrationPending:"These credentials remain in the local ledger. Export the matching environment variables and restart:",budgetDetailLabel:"Budget box details",refreshGoQuota:"Refresh quota",goQuotaNotQueried:"Quota not queried",codingPlanAnthropic:"Anthropic (Claude Pro/Max)",codingPlanZai:"Z.ai / Zhipu GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"Quota origin (HTTPS)",minimaxOriginNote:"Empty: official sites. Otherwise the Key is sent only to this origin. Use a trusted address without a path.",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"Open DeepSeek top-up page (platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) weekly quota",codexQuotaEnabled:"Show Codex quota (requires signed-in dsh-openai-codex)",includeSubagentCost:"Include subagents in session cost",gatewayQuotaEmpty:"No quota data",codingPlanDisplayLabel:"Display position",codingPlanDisplayNote:"“Main sidebar / Both” shows a quota card; the narrow rail shows percentages.",codingPlanKeyLabel:"API key (optional; empty = auto-detect)",codingPlanRefreshIntervalLabel:"Refresh interval (minutes)",refreshCodingPlan:"Refresh",codingPlanNotQueried:"Quota not queried",gatewayQuotaTitle:"CLIProxyAPI gateway quotas",gatewaySourceAdd:"Add source",gatewaySourceLabel:"Source label",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"Display",gatewaySourceAllowlist:"Allowed hosts",gatewaySourceCredential:"Management key (write-only)",gatewaySourceStatus:"Status",gatewaySourceUnsupported:"Unsupported providers",gatewaySourceUnknown:"Unknown",gatewaySourceNoAccounts:"No accounts",gatewaySourceFetchedAt:"fetched {time}",gatewaySwitchAccount:"Switch account (current: {account})",gatewayOnlyGemini:"Gemini quota only",refresh:"Refresh",quotaEnableFirst:"Enable this item first",quotaRefreshReady:"Enable and save a display position to refresh",quotaRemove:"Remove",quotaSectionNote:"Enabled items move to the top; click a name to expand its own settings. Up to 8 custom balances and 4 gateway sources.",codingPlanDisabledNote:"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.",goQuotaDisabledNote:"Enable OpenCode Go rolling 5h, weekly and monthly quotas in the sidebar, Settings and bottom-right corner. Missing subscriptions show a reason.",cornerLabel:"Bottom-right (dock) display",cornerEnabledLabel:"Show OpenCode Go quota / budget at the bottom-right",cornerGoRolling:"Rolling-5h quota",cornerGoWeekly:"Weekly quota",cornerGoMonthly:"Monthly quota",cornerBudget:"Budget used %",goShortRolling:"5h",goShortWeekly:"Wk",goShortMonthly:"Mo",goShortDaily:"Daily",budgetShort:"Budget",ledgerReadFailed:"Ledger read failed: {message}",readingLedger:"Reading ledger…",ledgerUnavailable:"Ledger unavailable",syncFailed:"Sync failed: {message}",historyCleared:"History cleared.",clearFailed:"Clear failed: {message}",peakOff:"Peak/off-peak pricing is off; base prices are used",peakNotEffective:"Not yet effective (effective at {time}); base prices are currently used",peakActive:"Peak hour now; peak prices apply",peakNotice:"DeepSeek peak-hour pricing is active; current calls are billed at peak prices",offPeakActive:"Off-peak now; off-peak prices apply",weekendAllOffPeak:"Weekend — all off-peak (Sat & Sun billed at off-peak prices all day)",weekendChip:"Weekend — all off-peak",weekendShort:"Weekend",holidayAllOffPeak:"Chinese public holiday — off-peak all day",holidayChip:"Public holiday — all off-peak",holidayShort:"Holiday",peakHolidaysLabel:"Public holidays (Beijing dates, comma separated)",weekendRuleNote:"Since Aug 23, 2026 (Beijing time), weekends and Chinese public holidays are off-peak all day, including work-shift weekends.",peakShort:"Peak",offPeakShort:"Off-peak",peakStyleLabel:"Peak period strip style",peakStyleCompact:"Compact (one-line)",peakStyleClassic:"Classic (segments & chip)",peakAlertLabel:"Popup alert before peak/off-peak switch",peakAlertAheadLabel:"Lead time (minutes, 1-30)",peakAlertTargetLabel:"Alert type",peakAlertTargetPeak:"Entering peak",peakAlertTargetOffPeak:"Entering off-peak",peakAlertTargetBoth:"Both",peakAlertTitlePeak:"Entering peak hours soon",peakAlertTitleOffPeak:"Entering off-peak hours soon",peakAlertBody:"Billing switches to {phase} pricing in about {time}; mind your call costs in this window.",peakAlertPhasePeak:"peak",peakAlertPhaseOffPeak:"off-peak",peakAlertBtn:"Got it",peakAlertBadgePeak:"Peak alert",peakAlertBadgeOffPeak:"Off-peak alert",peakAlertPositionLabel:"Popup position",peakAlertPositionCorner:"Bottom-right",peakAlertPositionCenter:"Screen center",peakAlertWebNotifyLabel:"Also send a system notification",peakAlertWebNotifyHint:"When enabled, allow notification permission in the browser address bar so you get alerted even when the page is minimized or backgrounded.",peakAlertPreviewLabel:"Preview the popup",peakAlertPreviewPeak:"Preview entering peak",peakAlertPreviewOffPeak:"Preview entering off-peak",peakAlertPreviewTag:" (preview)",peakPanelTitle:"Peak/off-peak pricing & notice",peakNoticeHiddenHint:"Notice hidden: enable peak/off-peak pricing and the “prominent notice” toggle.",groupGeneral:"General",groupMoney:"Money & currency",groupSidebar:"Sidebar display",sidebarSimple:"Simplify the sidebar",sidebarSimpleNote:"Condense cards but keep amounts, quotas and hover details. Height is capped at 38% of the viewport with scrolling. Turn off to restore.",sidebarSimpleTitle:"A lighter sidebar",sidebarSimpleBody:"Simple display leaves more room for conversations. Enable it now? You can change it in Settings → Cost → Display anytime.",sidebarSimpleOn:"Enable simple display",sidebarSimpleOff:"Keep current display",sidebarSimpleError:"Settings could not be saved. Retry or dismiss this guide and change them later in Settings.",closeGuide:"Dismiss guide",todayBudget:"Today / {period} budget",sidebarStyleLabel:"Sidebar progress style",sidebarStyleStandard:"Standard",sidebarStyleCompact:"Compact (2 columns)",restorePriceMatches:"Restore removed models ({count})",removePriceMatchHint:"Remove clears the override and hides the row until restored. Usage records are kept; automatic price matching applies.",groupCorner:"Corner chips",groupDetail:"Box details",catalogTitle:"Extended price catalog",catalogNote:"Reference prices by vendor and model. Mount to edit and bill; unmounted DeepSeek uses its default price.",catalogOpen:"Expand extended price catalog",catalogCollapse:"Collapse extended price catalog",mountBtn:"Mount",unmountBtn:"Unmount",mountedTag:"Mounted",catalogUnpriced:"Unpriced",catalogDeepseekNote:"Unmounted DeepSeek models use the default price.",modelStatsTitle:"Per-model statistics (tokens & cost)",modelsTitle:"Sidebar model costs",modelsCount:"{n} models",modelsOther:"Other",models_enabled:"Show model cost card",models_defaultOpen:"Expand by default",models_remember:"Remember expansion",models_tokens:"Show tokens",models_shares:"Show cost shares",models_dock:"Top model in corner dock",models_period:"Default period",models_summary:"Collapsed summary",models_position:"Card position",models_topN:"Model rows (1–10)",models_refreshSeconds:"Refresh interval (10–60 seconds)",modelsTotal:"Period total and model count",modelsTop:"Top model and cost",modelsFirst:"Top",modelsAfter:"After balances",modelsLast:"Bottom",modelStatsToday:"Today",modelStatsHistory:"Last 90 days",modelStatsCostH:"Cost ranking",modelStatsTokensH:"Token usage",modelStatsHitH:"Cache hit rate",modelStatsHitUnreported:"unreported?",modelStatsHitUnreportedTip:"Zero cache hits on long calls may mean a relay removed cache fields. All-miss cost is an upper bound; check with the direct API.",modelStatsValueH:"Value · tokens per USD",modelStatsInput:"Input",modelStatsCache:"Cache",modelStatsOutput:"Output",modelStatsEmpty:"No usage data for this period.",modelStatsBlended:"blended {price}/M",modelStatsNote:"Hit rate = cache reads ÷ (reads + uncached input). “Unreported?” means cache data may be missing, so cost is an upper bound. Unit price = cost ÷ tokens × 1M; value = tokens ÷ cost.",billingClassLabel:"Billing class",billingClassPlan:"Plan subscription",billingClassAuto:"Auto",billingClassApi:"API usage",modelStatsLegacy:"Unattributed (early data · billed as recorded)",sessionLineSplit:"This session {amount} (API) · Plan equiv. {planAmount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",costChipPlan:"Cost {amount} (+Plan)",sessionDetailPlan:"Plan subscription quota usage (equiv.) {amount}",planStatsTitle:"Token Plan usage stats (per-1% & full-window estimates)",planStatsEmpty:"No Coding Plan quota data yet. Enable and refresh a provider under Quotas.",planStatsWindow:"Window",planStatsPercent:"Used %",planStatsLocal:"This period actual (local ledger)",planStatsPer1:"Per 1% quota ≈",planStatsFull:"Full window (100%) ≈",planStatsResets:"resets {time}",planStatsMethodSample:"sample delta",planStatsMethodLive:"current usage ratio",planStatsMethodNone:"not enough samples",planStatsMethodSampleAt:"{method} (as of {time})",planStatsConfidenceLow:"low reading precision",planStatsCurveTitle:"Plan usage curves (aggregated from sample intervals)",planStatsDaily:"Daily",planStatsWeekly:"Weekly",planStatsMonthly:"Monthly",planStatsCurveEmpty:"Not enough samples: refresh successfully twice with a quota percentage change.",planStatsBarTip:"{date}: full-window est. ≈ {full} (per 1% ≈ {per1}) · actual {tokens} / {cost} · {intervals} sample interval(s)",planStatsNote:"Amounts are catalog-price equivalents. Plans use quota; budgets count API only. Estimates cover dsh calls, while server percentages cover the account. Short samples are less precise. 5h rolls; week/month use local dates.",catalogDisplayLabel:"Show directly in Cost settings",catalogDisplayHint:"Controls direct display in Cost settings; mounting and billing stay unchanged. Hidden models remain editable in this catalog.",priceTableDisplayHint:"Choose where each model appears. DeepSeek shows directly; other vendors default to the catalog.",catalogCustomModels:"Custom models",priceMatchLabel:"Auto-match unknown model names",priceMatchAuto:"Auto (strip suffix / prefix / family similarity)",priceMatchExact:"Exact match only",priceMatchNote:"Manual overrides take priority. Auto-match accepts only the same name or date, version and context suffixes. Unknown DeepSeek models use the default price; other providers stay unpriced.",unmatchedTitle:"Recently seen models without a price hit",unmatchedHint:"These models have no price. Assign one manually; “Default price” uses DeepSeek defaults. Local inference costs zero until assigned.",overrideTargetDefault:"DeepSeek default price",overrideRemove:"Remove",overrideTargetLocal:"Local model (zero cost)",matchedTitle:"Models matched this month",matchedHint:"These models matched automatically. Choose another price or zero cost; tokens still count. Saved overrides move to the manual list.",matchedKeepAuto:"Keep auto match",overrideNone:"No manual match overrides.",mountedSuffix:"Mounted (billed)",flatInput:"Input",flatCached:"Cached",flatOutput:"Output",deepseekMountedHeader:"DeepSeek price table (mounted)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet Token Plan",codingPlanVolcengine:"Volcano Ark Coding Plan",codingPlanQwen:"Qwen Token Plan (qianwenai.com)",codingPlanMimo:"Xiaomi MiMo Token Plan",mimoWindowPlan:"Plan credits",mimoWindowCompensation:"Compensation",codingPlanWindowBalance:"Balance",qwenSource:"Quota source",qwenSourceLocal:"Local estimate",qwenSourceCli:"Official CLI",qwenSourceBailian:"Bailian CLI",qwenCliNote:"Install @qianwenai/qianwen-cli on the DSH host and run qianwen auth login as the same OS user.",qwenBailianNote:"Bailian CLI: install bailian-cli on the DSH host and run bl auth login --console as the same OS user.",qwenPlanCreditsLabel:"Monthly credits quota (personal Lite 50K / Standard 500K; see your plan page)",qwenPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",qwenRatesLabel:"Credits rate overrides (optional; credits deducted per 1M tokens; empty = built-in table)",qwenRatesModelPlaceholder:"Model name, e.g. qwen3.8-max-preview",qwenRatePlaceholder:"rate",qwenRate_input:"Input",qwenRate_cachedInput:"Cached input",qwenRate_output:"Output",qwenRateDraftNote:"Enter all three positive rates to save automatically; clear all to restore the built-in table.",qwenRatesAdd:"Add",qwenLocalNote:"Local Credits estimate; console is authoritative. Counts qwen and qwen/qianwen-tokenplan subscription routes, including llm- prefix. Excludes pay-as-you-go API. Add rates for other models.",scnetPlanCreditsLabel:"Monthly credits quota for local estimates (Basic 60,000 / Standard 240,000 / Pro 600,000)",scnetPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",scnetLocalNote:"Uses console snapshots newer than 24h, then estimates from local records and official Credits rates. Other tools and unlisted models are excluded.",volcengineAccessKeyIdLabel:"Volcengine AccessKey ID",volcengineSecretAccessKeyLabel:"Volcengine SecretAccessKey",volcengineNote:"Volcano Ark needs AK/SK, ArkReadOnlyAccess and BillingCenterReadOnlyAccess. Enter credentials or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Only open.volcengineapi.com is contacted.",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}h",countdownHourMinute:"{h}h {m}m",countdownMinute:"{m}m",nextOffPeakIn:"Off-peak in {time}",nextPeakIn:"Peak in {time}",peakSummary:"Peak hours (UTC): {windows}; effective: {time}. {status}",noPeakWindows:"No peak windows configured. {status}",unknown:"unknown",cardToday:"Today",cardMonth:"This month",cardTotal:"All time",cardTotalSub:"Since the ledger was created · Calls {calls}",externalUsage:"External usage",combinedUsage:"DSH + external total",externalStale:"External snapshot has not been updated for 24 hours",externalHistory:"Recent daily records",cardsFootnote:"Amounts use the latest snapshot and may lag the official bill by minutes. Tokens include input, output, cache and reasoning; reasoning is billed with output. Reconcile by amount.",timezoneHint:"Today/month use host timezone {host}; this browser uses {browser}. Different day boundaries affect reconciliation. Set dsh to your local timezone to align.",todaySessions:"Today's sessions",historyExpandHint:"Click a date row to expand its session details",historySessionsLoading:"Loading session details…",historyNoSessions:"No session details for this day (early data or session logs cleaned)",historySessionsError:"Failed to load session details",sessionRankTitle:"By session (all history)",sessionRankHint:"All historical sessions, not grouped by date; sort and row count are switchable",sessionRankEmpty:"No session data yet",sessionRankLoading:"Loading session ranking…",sessionRankError:"Failed to load session ranking",sessionRankLimit:"Rows",showSessionIdLabel:"Show session IDs in session lists",cardsTogglePlanTotal:"Include plan totals",cardsTogglePlanTotalHint:"When on, every amount shows total equivalent cost including plan subscriptions; off (default) counts real-money API channels only",hideOfficialBalanceLabel:"Hide official account balance (balance UI removed from sidebar and settings)",hideTodayCostLabel:"Hide today's cost (today's amount removed from sidebar, budget details and overview card)",sessionRankSort:"Sort",sessionSortCostDesc:"Cost high→low",sessionSortCostAsc:"Cost low→high",sessionSortTimeDesc:"Time new→old",sessionSortTimeAsc:"Time old→new",sessionSortRecent:"Recent order",history:"History",usageTitle:"Token usage stats",usageTotal:"All-time {tokens} tokens · input {input} · cache {cache} · output {output} · {calls} calls",usageDay:"{date}: {tokens} tokens (input {input} · cache {cache} · output {output}) · {calls} calls · {cost}",usageEmpty:"No history yet — daily usage will accumulate here",usageSectionLabel:"Usage",usagePositionLabel:"Token usage stats position",usagePositionCost:"Cost settings",usagePositionGeneral:"General settings",usagePositionSection:"Own section (Usage)",displaySettings:"Display settings",tabOverview:"Overview",tabQuotas:"Quotas",tabUsage:"Usage",tabPricing:"Pricing",tabDisplay:"Display",historyDataTitle:"History data",positionLabel:"Session cost display position",positionDock:"Below the composer",positionHeader:"Session title bar",off:"Off",quotaStripGroup:"Quota strip above the input",quotaStripEnable:"Enable the quota strip (one row above the input box)",quotaStripShowBudget:"Strip includes budget used %",quotaStripShowGo:"Strip includes the Go quota",quotaStripShowPlans:"Strip includes coding plan quotas",quotaStripNote:"Hover a chip for reset times and the last refresh; the strip hides itself when there is no quota data.",quotaStripGuideTitle:"New: quota strip above the input",quotaStripGuideBody:"Show budget and OpenCode Go/coding-plan percentages above the input box. Enable now? Change it anytime in Settings → Display.",quotaStripGuideOn:"Enable the strip",quotaStripGuideOff:"Not now",clickToRefresh:"Click to refresh now",balanceClickGuideTitle:"New: click the balance box to refresh",balanceClickGuideBody:"Click a sidebar balance or plan box to refresh. It pulses while loading; on failure it keeps the old value and shows the reason on hover.",balanceClickGuideOk:"Got it",sidebarLabel:"Today cost display",sidebarOn:"Sidebar footer",currencyLabel:"Currency",currencyCny:"Chinese Yuan (CNY)",currencyUsd:"US Dollar (USD)",currencyEur:"Euro (EUR)",symbolLabel:"Currency symbol",rateLabel:"Exchange rate (1 USD = ? target currency)",decimalsLabel:"Decimal places",balanceDisplayLabel:"Balance display position",balanceSidebar:"Main sidebar",balanceSettings:"Settings page",balanceBoth:"Both",refreshIntervalLabel:"Balance refresh interval (minutes)",peakEnabledLabel:"Use DeepSeek peak-hour prices",peakNoticeLabel:"Prominent notice during peak hours (sidebar budget box, today's cost; previewed in the Settings peak panel)",badgeNote:"Session cost uses call-time prices, including peak and historical rates. Input, output, cache reads and writes are separate; configured cache-write and long-context rates apply.",priceTableTitle:"Price table (USD / 1M tokens)",pricingCurrencyLabel:"Official price currency",pricingCurrencyUsd:"USD (English official page)",pricingCurrencyCny:"CNY (Chinese official page)",pricingCurrencyNote:"Selects the official pricing-page language. Sync then recalculates history in the background; sessions without full logs keep their earlier basis.",priceTableNote:"Call-time prices: Flash changes Sep 10 04:00 UTC; V4 Pro uses Flash prices from Sep 14 04:00 UTC. Earlier calls retain history. Mon–Fri peaks 01–04 and 06–10 UTC cost 2×; weekends and Chinese public holidays are off-peak. Cache writes use hit rates.",datedPriceNote:"Current rates are shown here. Editing cancels any future scheduled change for this entry; earlier historical rates are retained.",defaultModelId:"default (fallback for unmatched models)",newModelPlaceholder:"New model ID (e.g. deepseek-v4-pro)",addModel:"Add model",dataSync:"Data & sync",saving:"Saving…",autoSaveFailed:"Auto-save failed: {message}",autoSavedAt:"Auto-saved {time}",autoSaveHint:"Settings are auto-saved",confirmFetch:"Overwrite the price table with prices from the official docs?",apply:"Apply",cancel:"Cancel",syncFromDocs:"Sync prices from official docs",syncScopeNote:"Official sync updates DeepSeek prices (including peak rates). Third-party prices (z-ai/Kimi/Qwen/Volcano) follow releases; edit in the extended catalog or model matching.",confirmReset:"Clear all history?",importLegacy:"Import pre-install history",confirmImportLegacy:"Confirm import? Replays all session logs and only fills dates/sessions missing from the ledger; existing records are untouched.",legacyImportFailed:"Failed to import pre-install history: {message}",legacyImportNote:"Pre-install history imports at first launch; rerun after copying old logs. Costs use current prices. Deleted logs cannot replay; sessions spanning installation exclude earlier usage.",confirmClear:"Confirm clear",clearAllHistory:"Clear all history",lastSync:"Last sync: {time}",neverSynced:"Never (bundled prices)",source:"; Source: {source}",sourceOfficial:"Official docs",sourceBundled:"Bundled",languageLabel:"Language",localeAuto:"Follow browser (auto)",localeZh:"Simplified Chinese",localeEn:"English",sectionLabel:"Cost",rpcFailed:"{method} call failed",rpcSyncFailed:"Sync call failed",rpcBalanceFailed:"Balance refresh call failed"}};function Ua(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function _(t){return t==="zh"||t==="en"?t:Ua()}function K(t){const s=t==="zh"?Te.zh:Te.en;return(o,a)=>{let n=s[o]??Te.en[o]??o;if(a)for(const i of Object.keys(a))n=n.split("{"+i+"}").join(String(a[i]));return n}}const qe={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustomRange"};function re(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function be(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&re(s,"object"),t}function ce(t,s){return(typeof t!="number"||!Number.isFinite(t))&&re(s,"number"),t}function Se(t,s){return typeof t!="string"&&re(s,"string"),t}const Ke=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function _t(t,s=!1){return t===null||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([o,a])=>s?o.length>0&&["plan","api"].includes(a):["auto","plan","api"].includes(a)))}function Wt(t,s){return typeof t!="boolean"&&re(s,"boolean"),t}const Ye=(t,s,o)=>Object.fromEntries(s.map(a=>[a,o(t[a])]));function zt(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const a of Object.keys(t)){const n=t[a];if(n===null||typeof n!="object"||Array.isArray(n))continue;const i=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:0;o[a]={...Ye(n,["input","output","cacheRead","cacheWrite","reasoning","cost"],i),apiCost:n.apiCost===void 0?i(n.cost):i(n.apiCost)}}return o}function Gt(t,s){be(t,s);const o={reasoning:t.reasoning===void 0?0:ce(t.reasoning,s+".reasoning"),apiCost:t.apiCost===void 0?void 0:ce(t.apiCost,s+".apiCost"),byModel:zt(t.byModel,s+".byModel"),byProviderModel:zt(t.byProviderModel,s+".byProviderModel")};for(const a of["input","output","cacheRead","cacheWrite","calls","cost"])o[a]=ce(t[a],s+"."+a);return o}function ct(t,s){return{...Gt(t,s),id:Se(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:""}}function fe(t,s){const o={...Gt(t,s),date:Se(t.date,s+".date"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||re(s+".sessions","array"),o.sessions=t.sessions.map((a,n)=>ct(a,s+".sessions["+n+"]"))),o}function dt(t,s,o=["cacheWrite","reasoning"]){const a={};for(const n of["cacheHit","cacheMiss","output"])a[n]=ce(t[n],s+"."+n);for(const n of o)t[n]!==void 0&&(a[n]=ce(t[n],s+"."+n));return a}function ut(t,s){be(t,s);const o=dt(t,s);for(const a of["offPeak","peak","legacyBase","longContext"])t[a]!==void 0&&(o[a]=dt(t[a],s+"."+a,["cacheWrite","reasoning","aboveInputTokens"]));t.cny!==void 0&&(o.cny=dt(t.cny,s+".cny")),t.legacy!==void 0&&(o.legacy=Wt(t.legacy,s+".legacy")),t.rateHistory!==void 0&&((!Array.isArray(t.rateHistory)||t.rateHistory.length>16)&&re(s+".rateHistory","price history"),o.rateHistory=t.rateHistory.map((a,n)=>((!a||typeof a.before!="string"||!Number.isFinite(Date.parse(a.before)))&&re(s+".rateHistory","dated price"),{...ut({...a,rateHistory:void 0},s+".rateHistory."+n),before:a.before})));for(const a of["billingMode","sourceUrl","checkedAt","notes"])typeof t[a]=="string"&&(o[a]=t[a]);return o}function Ha(t,s){const o=n=>n==null?void 0:{...n.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:n.enabled===!0,label:typeof n.label=="string"?n.label:"",labelEn:typeof n.labelEn=="string"?n.labelEn:"",display:Ke(n.display,["sidebar","settings","off"],"both"),unit:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",convertToDisplayCurrency:n.convertToDisplayCurrency===!0,refreshMinutes:typeof n.refreshMinutes=="number"&&Number.isFinite(n.refreshMinutes)?n.refreshMinutes:15,request:n.request&&typeof n.request=="object"?n.request:{url:""},extract:n.extract&&typeof n.extract=="object"?n.extract:{},allowedHosts:Array.isArray(n?.allowedHosts)?n.allowedHosts.filter(i=>typeof i=="string"):[]};be(t,s);const a={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const n of Object.keys(t.prices.models))a[n]=ut(t.prices.models[n],s+".prices.models."+n);return{locale:t.locale==="zh"||t.locale==="en"||t.locale==="auto"?t.locale:"auto",position:t.position==="header"||t.position==="off"?t.position:"dock",sidebar:t.sidebar!==!1,showSessionId:t.showSessionId===!0,hideOfficialBalance:t.hideOfficialBalance===!0,hideTodayCost:t.hideTodayCost===!0,sidebarTodayMetric:t.sidebarTodayMetric==="tokens"?"tokens":"cost",showTotalWithPlan:t.showTotalWithPlan===!0,sidebarSimple:t.sidebarSimple===!0,sidebarSimplePromptSeen:t.sidebarSimplePromptSeen===!0,sidebarModels:Object.fromEntries(Object.entries(Rt).map(([n,i])=>[n,t.sidebarModels?.[n]??i])),codexQuotaEnabled:t.codexQuotaEnabled===!0,includeSubagentCost:t.includeSubagentCost===!0,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(n=>typeof n=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:ce(t.decimals,s+".decimals"),exchangeRate:ce(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((n,i)=>({start:ce(n.start,s+".peakWindows["+i+"].start"),end:ce(n.end,s+".peakWindows["+i+"].end")})):[],peakHolidays:Array.isArray(t.peakHolidays)?t.peakHolidays.filter(n=>typeof n=="string"):[],peakNotice:t.peakNotice!==!1,peakAlertEnabled:t.peakAlertEnabled!==!1,peakAlertAhead:Number.isFinite(t.peakAlertAhead)&&t.peakAlertAhead>=1&&t.peakAlertAhead<=30?t.peakAlertAhead:2,peakAlertTarget:t.peakAlertTarget==="peak"||t.peakAlertTarget==="offpeak"?t.peakAlertTarget:"both",peakAlertPosition:t.peakAlertPosition==="center"?"center":"corner",peakAlertWebNotify:t.peakAlertWebNotify===!0,peakStyle:t.peakStyle==="classic"?"classic":"compact",priceMatch:t.priceMatch==="exact"?"exact":"auto",priceOverrides:(()=>{const n={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[i,l]of Object.entries(t.priceOverrides))typeof i=="string"&&typeof l=="string"&&(n[i]=l);return n})(),priceTableDisplay:(()=>{const n={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[i,l]of Object.entries(t.priceTableDisplay))typeof i=="string"&&(n[i]=l===!0);return n})(),codingPlans:(()=>{const n={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const i of Object.keys(t.codingPlans)){const l=t.codingPlans[i];l===null||typeof l!="object"||Array.isArray(l)||(n[i]={enabled:l.enabled===!0,display:l.display==="sidebar"||l.display==="both"||l.display==="off"?l.display:"settings",refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?l.refreshMinutes:15,apiKey:typeof l.apiKey=="string"?l.apiKey:"",...i==="minimax"?{baseUrl:typeof l.baseUrl=="string"?l.baseUrl:""}:{},...i==="qwen"?{quotaSource:["cli","bailian"].includes(l.quotaSource)?l.quotaSource:"local"}:{},...typeof l.planCredits=="number"&&Number.isFinite(l.planCredits)&&l.planCredits>0?{planCredits:l.planCredits}:{},...typeof l.planStart=="string"?{planStart:l.planStart}:{},...l.rates!==null&&typeof l.rates=="object"&&!Array.isArray(l.rates)?{rates:l.rates}:{},...typeof l.accessKeyId=="string"?{accessKeyId:l.accessKeyId}:{},...typeof l.secretAccessKey=="string"?{secretAccessKey:l.secretAccessKey}:{}})}return n})(),prices:{models:a,default:ut(t.prices?.default??{cacheHit:0,cacheMiss:0,output:0},s+".prices.default"),providers:t.prices?.providers&&typeof t.prices.providers=="object"?t.prices.providers:{},currency:typeof t.prices?.currency=="string"&&t.prices.currency.length>0?t.prices.currency:void 0},historyDays:ce(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:Se(t.fetchedAt,s+".fetchedAt"),priceSource:typeof t.priceSource=="string"?t.priceSource:"bundled",budget:{enabled:t.budget?.enabled===!0,amount:typeof t.budget?.amount=="number"&&Number.isFinite(t.budget.amount)?t.budget.amount:100,period:t.budget?.period==="day"||t.budget?.period==="all"||t.budget?.period==="custom"?t.budget.period:"month",customStart:typeof t.budget?.customStart=="string"?t.budget.customStart:null,customEnd:typeof t.budget?.customEnd=="string"?t.budget.customEnd:null,detail:t.budget?.detail!==!1},balance:{display:Ke(t.balance?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.balance?.refreshMinutes=="number"&&Number.isFinite(t.balance.refreshMinutes)?t.balance.refreshMinutes:5,showProgressBar:t.balance?.showProgressBar===!0,budgetCap:typeof t.balance?.budgetCap=="number"&&Number.isFinite(t.balance.budgetCap)&&t.balance.budgetCap>0?t.balance.budgetCap:null,clickHintSeen:t.balance?.clickHintSeen===!0},goQuota:{enabled:t.goQuota?.enabled!==!1,display:Ke(t.goQuota?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.goQuota?.refreshMinutes=="number"&&Number.isFinite(t.goQuota.refreshMinutes)?t.goQuota.refreshMinutes:15,apiKey:typeof t.goQuota?.apiKey=="string"?t.goQuota.apiKey:"",main:t.goQuota?.main==="weekly"||t.goQuota?.main==="monthly"?t.goQuota.main:"rolling",detail:t.goQuota?.detail!==!1},customBalance:o(t.customBalance),gatewayQuotas:(()=>{const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(n)?n.slice(0,4).filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).map(l=>({id:typeof l.id=="string"?l.id.slice(0,48):"",type:"cliproxyapi",label:typeof l.label=="string"?l.label.slice(0,80):"",baseURL:typeof l.baseURL=="string"?l.baseURL:"",enabled:l.enabled!==!1,display:Ke(l.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?Math.min(1440,Math.max(1,Math.floor(l.refreshMinutes))):15,includeProviders:Array.isArray(l.includeProviders)?[...new Set(l.includeProviders.filter(r=>typeof r=="string").map(r=>r.toLowerCase()).filter(r=>bt.includes(r)))]:bt,allowedHosts:Array.isArray(l.allowedHosts)?l.allowedHosts.filter(r=>typeof r=="string").slice(0,16):[],allowInsecureHttp:l.allowInsecureHttp===!0,antigravityOnlyGemini:l.antigravityOnlyGemini===!0,keyVar:typeof l.keyVar=="string"?l.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(i=>i!==null&&typeof i=="object").slice(0,8).map(o).filter(Boolean);const n=o(t.customBalance);return n?[n]:[]})(),corner:{enabled:t.corner?.enabled===!0,goRolling:t.corner?.goRolling!==!1,goWeekly:t.corner?.goWeekly!==!1,goMonthly:t.corner?.goMonthly!==!1,budget:t.corner?.budget!==!1},quotaStrip:{enabled:t.quotaStrip?.enabled===!0,budget:t.quotaStrip?.budget!==!1,go:t.quotaStrip?.go!==!1,plans:t.quotaStrip?.plans!==!1,promptSeen:t.quotaStrip?.promptSeen===!0},usage:{position:t.usage?.position==="general"||t.usage?.position==="section"?t.usage.position:"cost"},barDirections:(()=>{const n=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},i=(l,r)=>n[l]==="remaining"||n[l]==="used"?n[l]:r;return{balance:i("balance","remaining"),budget:i("budget","used"),go:i("go","used"),plan:i("plan","used")}})(),planBilling:{providers:_t(t.planBilling?.providers),models:_t(t.planBilling?.models,!0)}}}const Ue=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Ce=t=>Ue(t)??0,Ia={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},ja={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},Kt=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function mt(t,s){return be(t,s),{status:t.status==="ok"||t.status==="error"?t.status:"off",message:typeof t.message=="string"?t.message:"",fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:0}}function Qa(t,s){return{...mt(t,s),currency:typeof t.currency=="string"?t.currency:"",totalBalance:Ce(t.totalBalance),grantedBalance:Ce(t.grantedBalance),toppedUpBalance:Ce(t.toppedUpBalance)}}function pt(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&re(s,"object"),{percent:Ce(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function Fa(t,s){return{...mt(t,s),rolling:pt(t.rolling,s+".rolling"),weekly:pt(t.weekly,s+".weekly"),monthly:pt(t.monthly,s+".monthly")}}function Yt(t,s){return{...mt(t,s),label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:Ce(t.remaining),maxBudget:Ue(t.maxBudget),spend:Ue(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const _a=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),Wa=new Set(["off","loading","ok","partial","stale","error"]),bt=["antigravity","claude","codex","kimi","xai","workbuddy"],Vt={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function za(t,s){be(t,s);const o=(l,r="")=>typeof l=="string"?l:r,a=l=>Ue(l),n=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{id:o(l.id),label:o(l.label),...a(l.percent)===null?{}:{percent:a(l.percent)},resetsAt:o(l.resetsAt),periodHours:a(l.periodHours),scope:o(l.scope)}:null,i=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{unit:o(l.unit,"credits"),used:a(l.used),remaining:a(l.remaining),limit:a(l.limit),fetchedAt:o(l.fetchedAt),packages:Array.isArray(l.packages)?l.packages.filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)).map(r=>({id:o(r.id),label:o(r.label),used:a(r.used),remaining:a(r.remaining),limit:a(r.limit),startsAt:o(r.startsAt),resetsAt:o(r.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:Wa.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:a(t.fetchedAt)??0,attemptedAt:a(t.attemptedAt)??0,serverVersion:o(t.serverVersion),keyConfigured:t.keyConfigured===!0,keySource:o(t.keySource,"none"),accounts:Array.isArray(t.accounts)?t.accounts.filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).slice(0,16).map(l=>({id:o(l.id),provider:o(l.provider,"unknown"),label:o(l.label,"unknown"),status:_a.has(l.status)?l.status:"unknown",message:o(l.message),plan:o(l.plan),windows:Array.isArray(l.windows)?l.windows.map(n).filter(Boolean):[],credits:i(l.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(l=>typeof l=="string").slice(0,32):[]}}function Ga(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};if(t.providers!==null&&typeof t.providers=="object"&&!Array.isArray(t.providers))for(const[o,a]of Object.entries(t.providers)){if(a===null||typeof a!="object"||Array.isArray(a))continue;const n={},i={};if(a.windows!==null&&typeof a.windows=="object"&&!Array.isArray(a.windows))for(const[l,r]of Object.entries(a.windows))r===null||typeof r!="object"||Array.isArray(r)||(n[l]={...Ye(r,["percent","localTokens","localCost","sampleCount"],Ce),...Ye(r,["sampleAt","per1Tokens","per1Cost","fullTokens","fullCost"],Ue),resetsAt:typeof r.resetsAt=="string"?r.resetsAt:"",method:r.method==="sample"||r.method==="live"?r.method:"none",confidence:r.confidence==="high"||r.confidence==="low"?r.confidence:null});if(a.intervals!==null&&typeof a.intervals=="object"&&!Array.isArray(a.intervals))for(const[l,r]of Object.entries(a.intervals))Array.isArray(r)&&(i[l]=r.filter(u=>u!==null&&typeof u=="object"&&!Array.isArray(u)).map(u=>Ye(u,["t0","t1","tokens","cost","pct","per1Tokens","per1Cost"],Ce)));s[o]={windows:n,intervals:i}}return{generatedAt:Ce(t.generatedAt),providers:s}}function Jt(t,s){return be(t,s),{today:fe(t.today,s+".today"),month:fe(t.month,s+".month"),total:fe(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?Ia:Qa(t.balance,s+".balance"),goQuota:t.goQuota==null?ja:Fa(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?Kt():Yt(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,a)=>Yt(o,s+".customBalances["+a+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,a)=>za(o,s+".gatewayQuotas["+a+"]")):[],customVarStatus:t.customVarStatus!==null&&typeof t.customVarStatus=="object"&&!Array.isArray(t.customVarStatus)?Object.fromEntries(Object.entries(t.customVarStatus).filter(([,o])=>o!==null&&typeof o=="object").map(([o,a])=>[o,{configured:a.configured===!0,source:typeof a.source=="string"?a.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:Ga(t.planStats),history:Array.isArray(t.history)?t.history.map((o,a)=>fe(o,s+".history["+a+"]")):[],externalUsage:t.externalUsage&&Array.isArray(t.externalUsage.sources)?{fetchedAt:Number(t.externalUsage.fetchedAt)||0,stale:t.externalUsage.stale===!0,sources:t.externalUsage.sources.map(o=>({source:String(o.source),today:fe(o.today,s+".external.today"),month:fe(o.month,s+".external.month"),total:fe(o.total,s+".external.total"),history:(o.history??[]).map(a=>fe(a,s+".external.history"))})),combined:Object.fromEntries(["today","month","total","history"].map(o=>[o,o==="history"?(t.externalUsage.combined.history??[]).map(a=>fe(a,s+".external.history")):fe(t.externalUsage.combined[o],s+".external."+o)]))}:null,config:Ha(t.config,s+".config"),reconcile:t.reconcile===null||t.reconcile===void 0?void 0:{ok:t.reconcile.ok===!0,message:typeof t.reconcile.message=="string"?t.reconcile.message:""},priceCatalog:t.priceCatalog!==null&&typeof t.priceCatalog=="object"&&!Array.isArray(t.priceCatalog)?t.priceCatalog:null,meta:{now:typeof t.meta?.now=="number"?t.meta.now:Date.now(),timezoneOffsetMinutes:typeof t.meta?.timezoneOffsetMinutes=="number"?t.meta.timezoneOffsetMinutes:0,timezone:typeof t.meta?.timezone=="string"?t.meta.timezone:"",dayKey:typeof t.meta?.dayKey=="string"?t.meta.dayKey:"",monthKey:typeof t.meta?.monthKey=="string"?t.meta.monthKey:""}}}function Ka(t,s){be(t,s);const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=Jt(t.state,s+".state")),o}function se(t){return{parse:t}}const ft=se(Jt),Ya=se(t=>be(t,"patch")),Va=se(Ka),Zt=se(t=>Se(t,"provider")),Ja=se(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&re("index","0-7 integer"),t}),Za=se(t=>Se(t,"date")),$a=se(t=>be(t,"day")),Xa=se(t=>(Number.isFinite(Number(t))||re("limit","number"),Number(t))),$t=se(t=>Se(t,"sort")),en=se(t=>be(t,"topSessions")),Xt=se(t=>Se(t,"target")),tn=se(t=>Se(t,"value")),Ae=(t,s)=>({mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:s,create:()=>s}),ie=(t,s,o,a=!1)=>({name:t,wire:t,source:"json",codec:Ae(s,o),...a?{acceptsUndefined:!0}:{}}),an={package:"dsh-cost-meter",descriptors:[{method:"getState",result:Ae("CostState",ft)},{method:"updateConfig",parameters:[ie("patch","ConfigPatch",Ya)],result:Ae("CostState",ft)},{method:"fetchPrices"},{method:"refreshBalance"},{method:"refreshGoQuota"},{method:"refreshCustomBalance",parameters:[ie("index","CustomBalanceIndex",Ja,!0)]},{method:"refreshCodingPlan",parameters:[ie("provider","CodingPlanProvider",Zt)]},{method:"refreshGatewayQuota",parameters:[ie("sourceId","GatewayQuotaSourceId",se(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&re("sourceId","gateway source id"),t}),!0)]},{method:"resetHistory",result:Ae("CostState",ft)},{method:"importLegacyHistory"},{method:"getDaySessions",parameters:[ie("date","DayKey",Za)],result:Ae("DayRecord",$a)},{method:"getSessionCost",parameters:[ie("sessionId","SessionId",Zt)],result:Ae("SessionCost",se(t=>({own:ct(t.own,"own"),subagents:ct(t.subagents,"subagents"),found:Wt(t.found,"found"),subagentCount:ce(t.subagentCount,"subagentCount")})))},{method:"getTopSessions",parameters:[ie("limit","SessionLimit",Xa),ie("sort","SessionSort",$t,!0),ie("dir","SessionSortDir",$t,!0)],result:Ae("TopSessions",en)},{method:"setCredential",parameters:[ie("target","CredentialTarget",Xt),ie("value","CredentialValue",tn)]},{method:"clearCredential",parameters:[ie("target","CredentialTarget",Xt)]}].map(t=>({id:"dsh-cost-meter#costMeter/"+t.method,service:"costMeter",namespace:"costMeter",invocation:{kind:"direct"},parameters:[],result:Ae("FetchPricesResult",Va),...t}))};function nn(t,s){const o=s?.models??{};return typeof t=="string"&&t.length>0&&o[t]!==void 0?o[t]:s?.default??{cacheHit:0,cacheMiss:0,output:0}}function He(t){if(t===null||typeof t!="object")return;const s=l=>{const r=t[l];return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0},o=s("cacheMiss")??s("input")??0,n={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},i=s("reasoning");return i!==void 0&&(n.reasoning=i),s("cacheWrite")!==void 0&&(n.cacheWrite=s("cacheWrite")),n}function sn(t){const s=He(t);if(s===void 0)return null;for(const o of["offPeak","peak","legacyBase"]){const a=He(t[o]);a!==void 0&&(s[o]=a)}return Number.isFinite(t.longContext?.aboveInputTokens)&&t.longContext.aboveInputTokens>0&&(s.longContext={...He(t.longContext),aboveInputTokens:t.longContext.aboveInputTokens}),Array.isArray(t.rateHistory)&&(s.rateHistory=t.rateHistory.slice(0,16).map(o=>{const a={...He(o),before:o.before};for(const n of["offPeak","peak"]){const i=He(o[n]);i!==void 0&&(a[n]=i)}return a})),s}function Ve(t,s=Date.now()){if(!t||!Number.isFinite(s)||!Array.isArray(t.rateHistory))return t;let o=null,a=1/0;for(const l of t.rateHistory){const r=Date.parse(l.before);s<r&&r<a&&(o=l,a=r)}if(!o)return t;const{before:n,...i}=o;return{...t,...i}}const gt=Date.parse("2026-08-22T16:00:00Z");function ea(t){if(!Number.isFinite(t)||t<gt)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const a=o===6?s:s-1;return{start:Math.max(a*864e5-8*36e5,gt),end:(a+2)*864e5-8*36e5}}function ta(t,s){if(!Number.isFinite(t)||t<gt||!Array.isArray(s))return null;const o=Math.floor((t+8*36e5)/864e5);return s.includes(new Date(o*864e5).toISOString().slice(0,10))?{start:o*864e5-8*36e5,end:(o+1)*864e5-8*36e5}:null}const on=(t,s)=>ta(t,s)??ea(t);function Je(t,s,o,a){if(!Array.isArray(o)||o.length===0||on(t,a)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(i=>{const l=Number(i.start),r=Number(i.end);return!Number.isFinite(l)||!Number.isFinite(r)?!1:l<r?n>=l&&n<r:n>=l||n<r})}const ln=Date.parse("2026-08-16T16:00:00Z");function aa(t,s,o){const a=Ve(t,s)??{cacheHit:0,cacheMiss:0,output:0},n=l=>({cacheHit:l.cacheHit,cacheMiss:l.cacheMiss,output:l.output,reasoning:l.reasoning??0,...l.cacheWrite===void 0?{}:{cacheWrite:l.cacheWrite},...l.longContext===void 0?{}:{longContext:l.longContext}});if(Number.isFinite(s)&&s<ln){const l=a.legacyBase;return n(l===void 0?a:l)}if(o?.enabled!==!0)return n(a);const i=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(Je(s,i,o.windows,o.holidays)){const l=a.peak;return n(l===void 0?a:l)}if(i!==void 0&&s>=i){const l=a.offPeak;return n(l===void 0?a:l)}return n(a)}function na(t,s){const o=Math.max(0,Number(t.input)||0),a=Math.max(0,Number(t.output)||0),n=Math.max(0,Number(t.cacheRead)||0),i=Math.max(0,Number(t.cacheWrite)||0),l=Math.max(0,Number(t.reasoning)||0);return s.longContext&&o+n+i>s.longContext.aboveInputTokens&&(s=s.longContext),(o*s.cacheMiss+a*s.output+n*s.cacheHit+i*(s.cacheWrite??s.cacheHit)+l*(s.reasoning??0))/1e6}function sa(t,s,o){const a=Number(t);if(!Number.isFinite(a)||a<0||a===0)return 0;if(s!=="CNY")return a;const n=Number(o);return!Number.isFinite(n)||n<=0?a:a/n}function ae(t,s){const o=t?.barDirections,a=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return a;const n=o[s];return n==="remaining"||n==="used"?n:a}function de(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),a=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:a,label:a}}const oa=(t,s)=>t.toFixed(s).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1");function oe(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",a=Number(s?.decimals),n=Math.max(0,Math.min(10,Number.isFinite(a)?Math.floor(a):2));let i=n;return t>0&&t<Math.pow(10,-n)&&(i=n+2),o+oa(t,i)}function V(t,s){const o=Number(s?.exchangeRate),a=t*(Number.isFinite(o)&&o>0?o:1);return oe(a,s)}function H(t){const s=Math.max(0,Number(t)||0),o=a=>a>=100?String(Math.round(a)):String(Math.round(a*10)/10);return s<1e3?String(Math.round(s)):s>=999500?o(s/1e6)+"M":s<1e6?o(s/1e3)+"K":o(s/1e6)+"M"}function ue(t){return String(t??"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/([^)]*)/g," ").replace(/[^a-z0-9]+/g,"")}function Be(t,s){if(typeof t!="string"||t.length===0)return null;const o=Array.isArray(s)?s.filter(c=>typeof c=="string"&&c.length>0):[];if(o.length===0)return null;const a=c=>String(c).toLowerCase().replace(/[-@]\d{4}-?\d{2}-?\d{2}$/,"").replace(/[-@]v\d+(\.\d+)*$/,""),n=o.find(c=>c===t);if(n!==void 0)return n;const i=ue(t);if(i.length===0)return null;const l=o.find(c=>ue(c)===i);if(l!==void 0)return l;const r=a(t),u=o.find(c=>a(c)===r);if(u!==void 0)return u;const d=/^(?:[-_./:@](?:\d{4}-?\d{2}-?\d{2}|v\d+(?:\.\d+)*|\d+k|latest))+$/;return o.filter(c=>r.startsWith(a(c))&&d.test(r.slice(a(c).length))).sort((c,m)=>m.length-c.length)[0]??null}const rn=new Set(["lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),cn=["lmstudio:","lmstudio/","ollama:","ollama/","jan:","jan/","gpt4all:","gpt4all/","koboldcpp:","koboldcpp/","llamacpp:","llamacpp/","llama-cpp:","llama-cpp/","localai:","localai/","vllm:","vllm/","sglang:","sglang/","tabbyapi:","tabbyapi/","lmdeploy:","oobabooga/","text-generation-webui/","llama-server:","gguf:","local:"];function dn(t,s){if(typeof t=="string"&&rn.has(t))return!0;const o=typeof s=="string"?s.toLowerCase():"";return cn.some(a=>o.startsWith(a))}function un(t,s,o){const a=o?.prices??{},n=o?.priceMatch==="exact"?"exact":"auto",i=o?.priceOverrides&&typeof o.priceOverrides=="object"?o.priceOverrides:{};let l=String(t??"").trim().toLowerCase();l.startsWith("llm-")&&(l=l.slice(4)),l===""&&(l="deepseek");let r=l,u=s;const d=i[l+":"+s];if(d==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof d=="string"&&d.length>0){const p=d.indexOf(":");if(p>0&&d.slice(p+1).length>0?(r=d.slice(0,p).trim().toLowerCase(),u=d.slice(p+1)):u=d,r==="deepseek"&&u==="__default__")return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}if(dn(r,u))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(r==="deepseek"||r.includes("deepseek")){const p=a.models??{},f=p[u]!==void 0?u:n==="auto"?Be(u,Object.keys(p)):null;if(f!==null)return{entry:p[f],priced:!0,billingMode:"deepseek-peak",matched:!0};if(n==="auto"){let g=null,k=-1,v="flat";for(const[N,A]of Object.entries(a.providers??{})){const w=A?.models??{},b=Be(u,Object.keys(w));if(b===null||w[b]?.unpriced===!0)continue;const y=(b===u||ue(b)===ue(u)?1e3:0)+ue(b).length;y>k&&(g=w[b],k=y,v=w[b]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(g!==null)return{entry:g,priced:!0,billingMode:v,matched:!0}}return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}const c=a.providers?.[r]?.models??{},m=c[u]!==void 0?u:n==="auto"?Be(u,Object.keys(c)):null;if(m!==null)return{entry:c[m],priced:c[m]?.unpriced!==!0,billingMode:"flat",matched:!0};if(r==="opencode-go")return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(n==="auto"){const p=a.models??{},f=Be(u,Object.keys(p));if(f!==null)return{entry:p[f],priced:!0,billingMode:"deepseek-peak",matched:!0};let g=null,k=-1,v="flat";for(const[N,A]of Object.entries(a.providers??{})){if(N===r)continue;const w=A?.models??{},b=Be(u,Object.keys(w));if(b===null||w[b]?.unpriced===!0)continue;const y=(b===u||ue(b)===ue(u)?1e3:0)+ue(b).length;y>k&&(g=w[b],k=y,v=w[b]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(g!==null)return{entry:g,priced:!0,billingMode:v,matched:!0}}if(l!=="deepseek"&&!l.includes("deepseek")&&typeof d=="string"&&d.length>0&&!d.includes(":")){const p=a.models??{},f=p[d]!==void 0?d:n==="auto"?Be(d,Object.keys(p)):null;if(f!==null)return{entry:p[f],priced:!0,billingMode:"deepseek-peak",matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function ht(t,s,o){const a=un(t,s,o);return a.priced&&o?.prices?.currency==="CNY"&&a.entry?.cny?{...a,entry:a.entry.cny,currency:"CNY"}:{...a,currency:a.billingMode==="deepseek-peak"&&o?.prices?.currency==="CNY"?"CNY":"USD"}}function mn(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,a=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&a===0}function Ze(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:ia(t,s).total}function yt(t){if(t===null||typeof t!="object")return 0;const s=Number(t.cost)||0,o=t.apiCost===void 0||t.apiCost===null?s:Number(t.apiCost);return Number.isFinite(o)&&o>=0?Math.min(o,s):s}function W(t,s){return s!==null&&typeof s=="object"&&s.showTotalWithPlan===!0?Number(t?.cost)||0:yt(t)}const pn={go:["go","zen","opencode","opencode-go"],qwen:["qwen","qwen-tokenplan","qianwen-tokenplan","qwen-token-plan","qianwen-token-plan"],scnet:["scnet","scnet-tokenplan","scnet-token-plan"],mimo:["mimo","xiaomimimo","mimo-token-plan","xiaomi-token-plan","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","xiaomi-token-plan-ams"]},la=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","mimo","go"];function bn(t){const s=String(t??"").trim().toLowerCase().replace(/^llm-/,"");if(s.length===0)return null;for(const[o,a]of Object.entries(pn))if(a.includes(s))return o;return la.includes(s)?s:null}function fn(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const a of la)a!=="go"&&o[a]?.enabled===!0&&s.add(a);return t?.goQuota?.enabled===!0&&s.add("go"),s}function gn(t,s,o){const a=String(t??"").trim().toLowerCase();if(a.length>0&&a!=="deepseek"&&!a.includes("deepseek"))return!1;const n=ue(s);if(n.length===0)return!1;const i=o?.prices,l=i?.models??{};for(const r of Object.keys(l))if(ue(r)===n)return!1;for(const r of Object.values(i?.providers??{}))for(const u of Object.keys(r?.models??{}))if(ue(u)===n)return!0;return!1}function Ie(t,s,o){let a=bn(t);a===null&&gn(t,s,o)&&(a="go");const n=o?.planBilling?.models;if(n!==null&&typeof n=="object"){const l=n[t+":"+s];if(l==="plan"||l==="api")return l;if(a!==null){const r=n[a+":"+s];if(r==="plan"||r==="api")return r}}if(a===null)return"api";const i=o?.planBilling?.providers?.[a];return i==="plan"||i==="api"?i:fn(o).has(a)?"plan":"api"}function ia(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows,holidays:s.peakHolidays},a=Date.now(),n=t.byProviderModel??t.byModel??{};let i=0,l=0;for(const m of Object.keys(n)){const p=m.indexOf(":"),f=p>0?m.slice(0,p):"deepseek",g=p>0?m.slice(p+1):m,k=ht(f,g,s);if(k.priced){const v=na(n[m],aa(sn(k.entry),a,{...o,enabled:k.billingMode==="deepseek-peak"&&o.enabled})),N=sa(v,k.currency,s.exchangeRate);i+=N,Ie(f,g,s)==="api"&&(l+=N)}}const r={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const m of Object.keys(n))r.input+=n[m].input??0,r.output+=n[m].output??0,r.cacheRead+=n[m].cacheRead??0,r.cacheWrite+=n[m].cacheWrite??0,r.reasoning+=n[m].reasoning??0;const u={input:Math.max(0,(t.input??0)-r.input),output:Math.max(0,(t.output??0)-r.output),cacheRead:Math.max(0,(t.cacheRead??0)-r.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-r.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-r.reasoning)},d=na(u,aa(nn("default",s.prices),a,o)),c=sa(d,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return i+=c,l+=c,{total:i,api:l}}function ra(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const a of Object.keys(o)){const n=a.indexOf(":"),i=n>0?a.slice(0,n):"deepseek",l=n>0?a.slice(n+1):a;if(Ie(i,l,s)==="plan")return!0}return!1}function kt(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function ca(t,s){if(t?.apiCost!==void 0)return yt(t);if(!ra(t,s))return Ze(t,s);let o=0;for(const[a,n]of Object.entries(t.byProviderModel??{})){if(!Number.isFinite(n.cost))return ia(t,s).api;const i=a.indexOf(":");Ie(a.slice(0,i),a.slice(i+1),s)==="plan"&&(o+=n.cost)}return Math.max(0,Ze(t,s)-o)}function wt(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),a=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(a>0?":"+String(a).padStart(2,"0"):"")}function hn(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const a=-new Date().getTimezoneOffset();if(a===o)return null;const n=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:n?n+" ("+wt(o)+")":wt(o),browserLabel:wt(a)}}function yn(t){let s=t;const o=new Set;return{getSnapshot:()=>s,subscribe:a=>(o.add(a),()=>{o.delete(a)}),set:a=>{if(a!==s){s=a;for(const n of[...o])n()}}}}const{createElement:e,Fragment:q,useState:L,useEffect:X,useRef:we}=Ee;function De({target:t,configured:s,source:o,t:a,api:n,placeholder:i,disabled:l}){const[r,u]=L(""),[d,c]=L(!1),[m,p]=L(null),f=l===!0||d,g=async()=>{const v=r.trim();if(!(v.length===0||f)){c(!0),p(null);try{const N=await n.setCredential(t,v);u(""),p({kind:"ok",text:N?.message??a("credentialSave")})}catch(N){p({kind:"err",text:String(N?.message??N)})}finally{c(!1)}}},k=async()=>{if(!f){c(!0),p(null);try{const v=await n.clearCredential(t);u(""),p({kind:"ok",text:v?.message??a("credentialClear")})}catch(v){p({kind:"err",text:String(v?.message??v)})}finally{c(!1)}}};return e("div",{className:"cm-field"},e("input",{className:"cm-input",type:"password",value:r,placeholder:typeof i=="string"?i:"",disabled:f,autoComplete:"off",onChange:v=>u(v.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:g,disabled:f||r.trim().length===0},a(d?"credentialSaving":"credentialSave")),s===!0?e("button",{className:"cm-btn small",onClick:k,disabled:f},a("credentialClear")):null),e("span",{className:"cm-hint"},s===!0?a("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):a("credentialNotConfigured")),e("span",{className:"cm-hint"},a("credentialInputHint")),Ut(m))}function kn({pending:t,t:s}){return!Array.isArray(t)||t.length===0?null:e("div",{className:"cm-msg err"},e("div",null,s("secretMigrationPending")),e("div",null,t.join("、")))}function $e({size:t=16,className:s}){return e("svg",{width:t,height:t,className:s,viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e("path",{d:"M4 4H12A2 2 0 0 1 14 6V11.5A2 2 0 0 1 12 13.5H4A2 2 0 0 1 2 11.5V6A2 2 0 0 1 4 4ZM4 5.3H12A0.7 0.7 0 0 1 12.7 6V11.5A0.7 0.7 0 0 1 12 12.2H4A0.7 0.7 0 0 1 3.3 11.5V6A0.7 0.7 0 0 1 4 5.3Z",fill:"currentColor",fillRule:"evenodd"}),e("path",{d:"M3.3 5.3H12.7V7.1H3.3Z",fill:"currentColor"}),e("path",{d:"M8 2.8A1.3 1.3 0 1 0 8 5.4A1.3 1.3 0 1 0 8 2.8Z",fill:"currentColor"}))}function da(t,s){const o=we(!1),a=we(""),n=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(i=>String(i??0)).join("|"):"";X(()=>{if(!o.current){o.current=!0,a.current=n;return}if(n===""||n===a.current)return;a.current=n;const i=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(i)},[n])}function wn(t,s,o,a){const n=u=>["input","output","cacheRead","cacheWrite"].reduce((d,c)=>d+(u?.[c]??0),0),i=s?.found&&n(s.own)>=n(t)?s.own:t;if(!o||!s?.subagentCount)return i;const l=s.subagents,r={...i};for(const u of["input","output","cacheRead","cacheWrite","reasoning","cost"])r[u]=(i?.[u]??0)+(l?.[u]??0);r.apiCost=ca(i,a)+yt(l);for(const u of["byModel","byProviderModel"]){r[u]={...i?.[u]};for(const[d,c]of Object.entries(l?.[u]??{})){const m={...r[u][d]};for(const p of["input","output","cacheRead","cacheWrite","reasoning","cost"])m[p]=(m[p]??0)+(c[p]??0);delete m.apiCost,r[u][d]=m}}return r}function ua(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?.(r=>r)?.state,a=o?.config,[n,i]=L(null);da(t,s),X(()=>{if(!t.sessionId||!t.api?.getSessionCost)return;let r=!0,u=!1;const d=async()=>{if(!u){u=!0;try{const m=await t.api.getSessionCost(t.sessionId);r&&i({id:t.sessionId,include:a?.includeSubagentCost===!0,value:m})}catch{}finally{u=!1}}};d();const c=a?.includeSubagentCost===!0?setInterval(d,1e4):null;return()=>{r=!1,c!==null&&clearInterval(c)}},[t.sessionId,o?.meta?.now,s,a?.includeSubagentCost]);const l=n&&n.id===t.sessionId&&n.include===(a?.includeSubagentCost===!0)?n.value:null;return{usage:wn(s,l,a?.includeSubagentCost===!0,a),config:a}}function ma(t,s){let o=0,a=Ze(t,s);if(s.showTotalWithPlan!==!0&&(t.apiCost!==void 0||ra(t,s))){const n={total:Ze(t,s),api:ca(t,s)};o=Math.max(0,n.total-n.api),o>0&&(a=n.api)}return{cost:a,planPart:o}}function xn(t){const{usage:s,config:o}=ua(t);if(!s||!o||kt(s)+(s?.output??0)===0)return null;const a=K(_(o.locale)),{cost:n,planPart:i}=ma(s,o),l=[a("sessionCostTitle"),a("sessionDetailTokens",{input:H(s?.input??0),cache:H((s?.cacheRead??0)+(s?.cacheWrite??0)),output:H(s?.output??0)}),a("sessionDetailCache",{read:H(s?.cacheRead??0),write:H(s?.cacheWrite??0)}),a("cost",{amount:V(n,o)}),...i>0?[a("sessionDetailPlan",{amount:V(i,o)})]:[]].join("; ");return e(Z,{label:l,side:"top",delayMs:500},e("div",{className:"cm-chip"},i>0?a("costChipPlan",{amount:V(n,o)}):a("cost",{amount:V(n,o)})))}function vn(t){const{usage:s,config:o}=ua(t);if(!s||!o)return null;const a=s.input??0,n=(s.cacheRead??0)+(s.cacheWrite??0),i=s.output??0;if(a+n+i===0)return null;const l=K(_(o.locale)),{cost:r,planPart:u}=ma(s,o),d=kt(s)>0?((s.cacheRead??0)/kt(s)*100).toFixed(1)+"%":"—";return e("div",{className:"cm-root"},l(u>0?"sessionLineSplit":"sessionLine",{amount:V(r,o),planAmount:V(u,o),hitRate:d,input:H(a),cache:H(n),output:H(i)}))}const Nn={USD:"$",CNY:"¥",EUR:"€"};function xe(t,s,o){const a=typeof o=="string"?o.toUpperCase():"",n=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return oe(t,{symbol:Nn[a]??n,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function pa(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const a=Number(s?.maxBudget);return Number.isFinite(a)&&a>0?a:null}function Sn(t){const s=t.today,o=s?.byProviderModel;if(o===null||typeof o!="object"||Object.keys(o).length===0)return Number(s?.cost)||0;let a=0;for(const[n,i]of Object.entries(o)){const l=n.indexOf(":");let r=l>=0?n.slice(0,l):n;r.startsWith("llm-")&&(r=r.slice(4)),!(r!=="deepseek"&&r!=="deepseek-official")&&(a+=Number(i?.cost)||0)}return a}function ba(t,s,o,a,n=null){const i=o==="official"?Sn(t):Number(t.today?.cost)||0;if(o==="custom"){const r=je(s,a,n);if(r==="USD")return i;if(r==="CREDITS")return 0;const u=Number(s?.exchangeRate);return i*(Number.isFinite(u)&&u>0?u:1)}const l=Number(s?.exchangeRate);return i*(Number.isFinite(l)&&l>0?l:1)}function fa({remaining:t,spend:s,todayUsed:o,cap:a}){if(a===null||a<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const n=Math.max(0,Number(t)||0),i=Math.max(0,Number(s)||0),l=Math.max(0,Math.min(i,Number(o)||0)),r=Math.max(0,i-l),u=Math.max(0,Math.min(100,n/a*100)),d=Math.max(0,Math.min(100-u,l/a*100)),c=Math.max(0,Math.min(100-u-d,r/a*100));return{remainingPct:u,todayPct:d,spentPct:c,hasCap:!0,pastSpend:r,today:l}}function xt(t,s,o=null,a=null){const n=o??t.customBalance,i=pa(je(s,n,a)==="CREDITS"?null:s,n),l=Number(n?.remaining)||0,r=Number(n?.spend)||0,u=ba(t,s,"custom",n,a);return{cap:i,...fa({remaining:l,spend:r,todayUsed:u,cap:i})}}function Cn(t,s){const o=t.balance,a=pa(s,null),n=Number(o?.totalBalance)||0,i=ba(t,s,"official",null),l=a!==null?Math.max(0,a-n):0;return{cap:a,...fa({remaining:n,spend:l,todayUsed:i,cap:a})}}function vt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:a,todayPct:n,spentPct:i}=s,l=[];a>0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:a+"%"}})),n>0&&l.push(e("div",{className:"cm-bbox-seg-today",style:{width:n+"%"}})),i>0&&l.push(e("div",{className:"cm-bbox-seg-spent",style:{width:i+"%"}})),l.length===0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const r=o==="used"?[...l].reverse():l;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...r)}function ga(t,s,o,a,n){const i=[t("balanceBarRemaining",{amount:a})];return o.today>0&&i.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&i.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),n!==null&&n>0&&i.push(t("balanceBudgetCapLabel")+": "+s(n)),i.join(" · ")}function Pe(t){const[s,o]=L(!1),[a,n]=L(null);return{busy:s,err:a,run:()=>{s||typeof t!="function"||(o(!0),n(null),Promise.resolve().then(t).catch(l=>{n(l?.message??String(l))}).finally(()=>{o(!1)}))}}}const me=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function ge(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const An="https://platform.deepseek.com/usage";function ha(t){return e("a",{className:"cm-bal-link",href:An,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},e("svg",{width:14,height:14,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},e("path",{d:"M8 4H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4M11 3h6v6M9 11l8-8"})))}function Pn(t){const{state:s,wide:o,api:a}=t,n=s.balance,i=K(_(s.config?.locale)),l=Pe(a?()=>a.refreshBalance():null);if(!n||n.status==="off")return null;if(n.status==="error")return e(Z,{label:[i("balanceQueryFailed",{message:n.message||i("unknownError")}),...ge(i,l)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,i("balance")," ",e("span",{className:"cm-num"},i("queryFailed"))):"⚠"));const r=[i("balanceTitle"),i("totalBalance",{amount:xe(n.totalBalance,s.config,n.currency)}),i("grantedToppedUp",{granted:xe(n.grantedBalance,s.config,n.currency),toppedUp:xe(n.toppedUpBalance,s.config,n.currency)}),i("updatedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ge(i,l)].join("; ");return e(Z,{label:r,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,e("span",{className:"cm-balance-name"},i("balance"),ha(i)),e("span",{className:"cm-num cm-bal-amt"},xe(n.totalBalance,s.config,n.currency)),s.reconcile?.ok===!1?" ⚠":""):e($e,{size:16})))}function Mn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=s.balance,l=K(_(n?.locale)),r=Pe(a?()=>a.refreshBalance():null);if(!i||i.status!=="ok")return null;const u=Cn(s,n),d=xe(i.totalBalance,n,i.currency),c=f=>xe(f,n,i.currency),m=[l("balanceTitle"),ga(l,c,u,d,u.cap),l("grantedToppedUp",{granted:xe(i.grantedBalance,n,i.currency),toppedUp:xe(i.toppedUpBalance,n,i.currency)}),l("updatedAt",{time:i.fetchedAt>0?new Date(i.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ge(l,r)].join("; "),p=e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-balance-name"},e("span",{className:"cm-bbox-label"},l("balance")),ha(l)),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},d)),e(vt,{segments:u,direction:ae(n,"balance")}));return e(Z,{label:m,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(r.busy?" busy":""),...me(r.busy,r.run)},o?p:e("div",{className:"cm-bbox-rail cm-num"},Math.round(u.remainingPct)+"%")))}function Nt(t,s){const o=typeof t?.label=="string"?t.label:"",a=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?a||o||"Custom balance":o||a||"自定义余额"}function je(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const a=o?.unit??t?.customBalance?.unit;return["CNY","EUR","USD","CREDITS"].includes(a)?a:["CNY","EUR","CREDITS"].includes(s?.unit)?s.unit:"USD"}function Qe(t,s,o,a){const n=je(s,o,a),i=Number(t);if(!Number.isFinite(i))return"—";const l=s?.currency==="USD"?1:Number(s?.exchangeRate);if((a??s?.customBalance)?.convertToDisplayCurrency===!0&&n==="USD"&&Number.isFinite(l)&&l>0){const c=i*l;return Number.isFinite(c)?oe(c,s):"—"}const r=n==="CREDITS",u=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4)));return(r?"":n==="CNY"?"¥":n==="EUR"?"€":"$")+oa(i,u)+(r?" Credits":"")}function St(t,s,o,a,n=null){const i=Qe(t.remaining,s,t,n),l=p=>Qe(p,s,t,n);if(a&&s.balance?.showProgressBar===!0){const p=xt(a,s,t,n);return[ga(o,l,p,i,p.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const r=t.spend!==null?l(t.spend):"—",u=t.maxBudget!==null?l(t.maxBudget):"—",d=je(s,t,n)==="CREDITS"?NaN:Number(s?.balance?.budgetCap),c=Number.isFinite(d)&&d>0?o("balanceBudgetCapLabel")+": "+l(d):"",m=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:i,spend:r,maxBudget:u,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:i});return c?m+" · "+c:m}function Tn(t,s,o,a,n){const i=Nt(n??s.customBalance??{},_(s?.locale)),l=Qe(a.remaining,s,a,n),r=xt(t,s,a,n);return{level:"ok",rail:Math.round(r.remainingPct)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},i),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},l)),e(vt,{segments:r,direction:ae(s,"balance")}))}}function Ct(t,s){const o=s?.customBalances??[],a=Array.isArray(t?.customBalances)?t.customBalances:[],n=[];return o.forEach((i,l)=>{if(i?.enabled!==!0||i.display!=="sidebar"&&i.display!=="both")return;const r=a.find(u=>u.index===l)??(a.length===1&&o.length===1?a[0]:null);n.push({index:l,entry:i,snapshot:r})}),n.length===0&&a.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&n.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),n}function Bn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(_(n?.locale)),l=Ct(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:u,snapshot:d})=>e(Dn,{key:"cb-"+r,state:s,wide:o,api:a,t:i,index:r,entry:u,snapshot:d})))}function Dn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,u=s.config;if(r==null||r.status!=="ok")return null;const d=Pe(a?()=>a.refreshCustomBalance(i):null),c=Tn(s,u,n,r,l),m=[St(r,u,n,s,l),...ge(n,d)].join(" · ");return e(Z,{label:m,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(d.busy?" busy":""),...me(d.busy,d.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function On(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(_(n?.locale)),l=Ct(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:u,snapshot:d})=>e(Rn,{key:"cbr-"+r,state:s,wide:o,api:a,t:i,index:r,entry:u,snapshot:d})))}function Rn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,u=s.config,d=r??Kt(i);if(d.status==="off")return null;const c=Pe(a?()=>a.refreshCustomBalance(i):null),m=Nt(l??u.customBalance??{},_(u?.locale));if(d.status==="error")return e(Z,{label:[d.message||n("unknownError"),...ge(n,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:m},m),e("span",{className:"cm-num cm-bal-amt"},n("queryFailed"))):"⚠"));const p=Qe(d.remaining,u,d,l),f=[St(d,u,n,s,l),...ge(n,c)].join(" · ");return e(Z,{label:f,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:m},m),e("span",{className:"cm-num cm-bal-amt"},p)):e($e,{size:16})))}function Ln(t){const o=(t.useCost?t.useCost(g=>g):void 0)?.state;if(!o)return null;const a=o.config,n=K(_(a?.locale)),i=a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},l=o.goQuota,r=a?.goQuota?.enabled!==!1&&l?.status==="ok",u=g=>g!==null&&typeof g?.percent=="number"?Math.round(Math.max(0,Math.min(100,g.percent))):null,d=[];if(a.sidebarModels?.dock){const g=Pa(o,a.sidebarModels.period,n);g.length&&d.push({key:"model-top",text:e(q,null,e("span",{className:"cm-bal-label"},g[0].label),e("span",{className:"cm-bal-amt"},V(g[0].cost,a))),tip:g[0].label+" "+V(g[0].cost,a),level:"ok"})}const c=(g,k,v,N)=>{if(!i.enabled||!g||!r)return;const A=u(k);if(A===null)return;const w=typeof k.resetsAt=="string"&&k.resetsAt.length>0?n("goResetAt",{time:new Date(k.resetsAt).toLocaleString()}):"";d.push({key:v,text:n(v)+" "+A+"%",tip:n(N)+": "+A+"%"+(w?" · "+w:""),level:A>=100?"over":A>=80?"warn":"ok"})},m=a?.goQuota?.main==="weekly"||a?.goQuota?.main==="monthly"?a.goQuota.main:"rolling",p=[m,...["rolling","weekly","monthly"].filter(g=>g!==m)],f=g=>g==="rolling"?["goRolling",l?.rolling,"goShortRolling","cornerGoRolling"]:g==="weekly"?["goWeekly",l?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",l?.monthly,"goShortMonthly","cornerGoMonthly"];for(const g of p){const[k,v,N,A]=f(g);c(i[k]===!0,v,N,A)}if(i.enabled&&i.budget===!0){const g=a.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const k=Number(a.exchangeRate),N=(o.budgetUsed??(g.period==="day"?W(o.today,a):g.period==="all"?W(o.total,a):W(o.month,a)))*(Number.isFinite(k)&&k>0?k:1),A=Math.max(0,Number(g.amount)||0),w=A>0?Math.min(999,N/A*100):null;if(w!==null){const b=w>=100?"over":w>=80?"warn":"ok";d.push({key:"budget",text:n("budgetShort")+" "+w.toFixed(1)+"%",tip:n("budgetOf",{period:n(qe[g.period]??"periodMonth")})+" · "+n("usedOf",{used:oe(N,a),amount:oe(A,a)}),level:b})}}}return d.length===0?null:e("div",{className:"cm-corner"},d.map(g=>e(Z,{key:g.key,label:g.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(g.key==="model-top"?" cm-model-top":"")+(g.level==="ok"?"":" "+g.level)},g.text))))}function Xe(t,s,o){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const a=(p,f)=>{const g=new Date(t);return g.setUTCDate(g.getUTCDate()+p),g.setUTCHours(f,0,0,0),g.getTime()},n=new Set,i=Math.max(12,Math.min(380,(Array.isArray(o)?o.length:0)+7));for(let p=-i;p<=i;p+=1){n.add(a(p,16));for(const f of s){const g=Number(f?.start),k=Number(f?.end);!Number.isFinite(g)||!Number.isFinite(k)||(n.add(a(p,g)),n.add(a(k<=g?p+1:p,k)))}}const l=[...n].sort((p,f)=>p-f).flatMap(p=>{const f=Je(p-1,void 0,s,o),g=Je(p,void 0,s,o);return f===g?[]:[{at:p,intoPeak:g}]});let r=null,u=null;for(const p of l)p.at<=t&&(r===null||p.at>r.at)&&(r=p),p.at>t&&(u===null||p.at<u.at)&&(u=p);const d=ta(t,o),c=d??ea(t);return c!==null?u===null?null:{inPeak:!1,weekend:d===null,...d?{holiday:!0}:{},prevAtMs:c.start,nextAtMs:u.at,nextIntoPeak:u.intoPeak}:r===null||u===null?null:{inPeak:Je(t,void 0,s,o),weekend:!1,prevAtMs:r.at,nextAtMs:u.at,nextIntoPeak:u.intoPeak}}function et(t,s){if(!t||t.peakNotice===!1||t.peakEnabled!==!0)return null;const o=Date.parse(t.peakEffectiveAt||"");if(Number.isFinite(o)&&s<o)return null;const a=Array.isArray(t.peakWindows)?t.peakWindows:[];return Xe(s,a,t.peakHolidays)}function tt(t){return t.holiday===!0?{short:"holidayShort",chip:"holidayChip",notice:"holidayAllOffPeak"}:t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function he(t,s,o){const a=Math.max(0,t.nextAtMs-s),n=Math.max(1,Math.ceil(a/6e4)),i=Math.floor(n/60),l=n%60;return i>0?l>0?o("countdownHourMinute",{h:i,m:l}):o("countdownHoursOnly",{h:i}):o("countdownMinute",{m:n})}const At="cm-peak-alert-preview";let ya=0;function En(t){const s=t.useCost?t.useCost(k=>k):void 0,o=s?.state?.config,[a,n]=L(Date.now()),[i,l]=L(null),[r,u]=L(null);if(X(()=>{const k=window.setInterval(()=>n(Date.now()),1e4);return()=>window.clearInterval(k)},[]),X(()=>{const k=v=>{const N=v.detail?.kind==="offpeak"?"offpeak":"peak";u(N);const A=s?.state?.config;if(A?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const w=K(_(A.locale));try{new Notification(w(N==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+w("peakAlertPreviewTag"),{body:w("peakAlertBody",{time:w("countdownMinute",{m:2}),phase:w(N==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(At,k),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(At,k),window.__cmPeakAlertLive=!1}},[]),X(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const k=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(k===null)return;const v=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",N=k.nextIntoPeak===!0;if(v!=="both"&&v!==(N?"peak":"offpeak"))return;const A=Number(o.peakAlertAhead),w=(Number.isFinite(A)&&A>=1?A:2)*6e4;if(a<k.nextAtMs-w||a>=k.nextAtMs||ya===k.nextAtMs)return;const b=K(_(o.locale));ya=k.nextAtMs;try{new Notification(b(N?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:b("peakAlertBody",{time:he(k,a,b),phase:b(N?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[a]),!o||o.peakEnabled!==!0)return null;let d=null;if(o.peakAlertEnabled===!0){const k=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(k)&&a<k)){const v=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(v!==null){const N=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",A=Number(o.peakAlertAhead),w=(Number.isFinite(A)&&A>=1?A:2)*6e4;(N==="both"||N===(v.nextIntoPeak?"peak":"offpeak"))&&a>=v.nextAtMs-w&&a<v.nextAtMs&&i!==v.nextAtMs&&(d=v)}}}let c=null,m=!1,p=null;if(d!==null)c=d,m=d.nextIntoPeak===!0,p=()=>l(d.nextAtMs);else if(r!==null)c={nextAtMs:a+2*6e4,nextIntoPeak:r==="peak"},m=r==="peak",p=()=>u(null);else return null;const f=K(_(o.locale)),g=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+g+" "+(m?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},f(m?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},f(m?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},f("peakAlertBody",{time:he(c,a,f),phase:f(m?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:p},f("peakAlertBtn"))))}function qn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)});return e(Z,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"}),e("div",{className:"cm-peak-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(l.chip)+" · "+r)))}function Un(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)});return e(Z,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}}),e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"})),e("span",{className:"cm-peak-classic-chip"},o(l.chip)+" · "+r)))}function at(t,s,o){return e(s?.peakStyle==="classic"?Un:qn,{config:s,t:o})}function Hn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)}),u=[o(l.notice),r];return e(Z,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-track"},e("div",{className:"cm-peak-rail-segment cm-peak-rail-high"}),e("div",{className:"cm-peak-rail-segment cm-peak-rail-low"}),e("div",{className:"cm-peak-rail-marker",style:{top:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(l.short))))}function In(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)}),u=[o(l.notice),r];return e(Z,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-classic-track"},e("div",{className:"cm-peak-rail-classic-segment peak"}),e("div",{className:"cm-peak-rail-classic-segment off"}),e("div",{className:"cm-peak-rail-classic-marker",style:{top:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(l.short))))}function jn(t,s,o){return e(s?.peakStyle==="classic"?In:Hn,{config:s,t:o})}function ka(t,s,o){const a=t.today,n=s.budget??{enabled:!1,amount:100,period:"month"},i=Number(s.exchangeRate),r=(t.budgetUsed??(n.period==="day"?W(t.today,s):n.period==="all"?W(t.total,s):W(t.month,s)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(n.amount)||0),d=u>0?Math.min(999,r/u*100):null,c=de(d===null?null:Math.min(100,d),ae(s,"budget")),m=W(a,s)*(Number.isFinite(i)&&i>0?i:1),p=u>0?Math.min(999,m/u*100):null,f=n.detail!==!1;return{level:d===null?"ok":d>=100?"over":d>=80?"warn":"ok",rail:c.label===null?"—":Math.round(c.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("budget")),e("span",{className:"cm-bbox-pct cm-num"},c.label===null?"—":c.label.toFixed(1)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:c.width+"%"}})),f?e(q,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},s.sidebarTodayMetric==="tokens"?o("today")+" "+Dt(a,s,o):o("todayShare",{amount:V(W(a,s),s),pct:p===null?"—":p.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:oe(r,s),amount:oe(u,s)}))):null,at(t,s,o))}}function wa(t,s,o){const a=t.goQuota,n=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",i=a[n],l=i!==null&&typeof i?.percent=="number"?Math.max(0,Math.min(100,Number(i.percent)||0)):0,r=f=>f!==null&&typeof f?.percent=="number"?Math.round(Math.max(0,Math.min(100,f.percent)))+"%":"—",u=f=>o(f==="rolling"?"goShortRolling":f==="weekly"?"goShortWeekly":"goShortMonthly"),d=["rolling","weekly","monthly"].filter(f=>f!==n),c=i!==null&&typeof i?.resetsAt=="string"&&i.resetsAt.length>0?o("goResetAt",{time:new Date(i.resetsAt).toLocaleString()}):"",m=s?.goQuota?.detail!==!1,p=de(l,ae(s,"go"));return{level:l>=100?"over":l>=80?"warn":"ok",rail:p.label===null?"—":Math.round(p.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+u(n)),e("span",{className:"cm-bbox-pct cm-num"},p.label===null?"—":Math.round(p.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:p.width+"%"}})),m?e(q,null,e("div",{className:"cm-bbox-line cm-num"},d.map(f=>u(f)+" "+r(a[f])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function Qn(t){const{state:s,wide:o}=t,a=s.goQuota,n=K(_(s.config?.locale));if(!a||a.status!=="ok")return null;const i=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(a[i]===null||typeof a[i]?.percent!="number")return null;const l=wa(s,s.config,n),r=[n("goQuotaTitle"),n("goWindowRolling")+": "+(a.rolling===null?"—":Math.round(a.rolling.percent)+"%"),n("goWindowWeekly")+": "+(a.weekly===null?"—":Math.round(a.weekly.percent)+"%"),n("goWindowMonthly")+": "+(a.monthly===null?"—":Math.round(a.monthly.percent)+"%"+(a.monthly!==null&&typeof a.monthly.resetsAt=="string"&&a.monthly.resetsAt.length>0?" · "+n("goResetAt",{time:new Date(a.monthly.resetsAt).toLocaleString()}):"")),n("goQuotaFetchedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e(Z,{label:r,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(l.level==="ok"?"":" "+l.level)+(o?"":" rail")},o?l.body:e("div",{className:"cm-bbox-rail cm-num"},l.rail)))}function Fn(t){return t===null||typeof t!="object"||t.unlimited||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function Fe(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function xa(t,s,o=Date.now()){if(typeof t!="string"||!t)return"";const a=Date.parse(t);if(!Number.isFinite(a))return"";const n=a-o;if(n<=0)return s("resetReached");const i=Math.ceil(n/6e4),l=Math.floor(i/1440),r=Math.floor(i%1440/60),u=i%60;return l>0?s("resetDays",{d:l,h:r}):r>0?s("resetHours",{h:r,m:u}):s("resetMinutes",{m:u})}function _e(t,s,o=Date.now()){const a=xa(t?.resetsAt,s,o);return a?s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})+" ("+a+")":""}function nt(t,s,o){return t===null?"—":o(s==="remaining"?"quotaRemaining":"quotaUsed",{pct:t})}function st(t){const[,s]=L(0),o=()=>s(Date.now());return X(()=>{if(!t)return;const a=setInterval(o,6e4);return()=>clearInterval(a)},[t]),{onMouseEnter:o,onFocus:o}}function We(t,s,o,a){const n=Fn(s),i=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",l=de(n,o),r=s?.unlimited?"∞":l.label===null?"—":l.label+"%";return{level:i,pct:n,text:r,label:l.label,row:e("div",{className:"cm-mm-row"+(i==="ok"?"":" "+i)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:l.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r))}}function va(t){const{five:s,seven:o,fetchedAt:a,t:n,wide:i,refresh:l,direction:r="used"}=t,u=st(s?.resetsAt),d=xa(s?.resetsAt,n),c=We(n("codingPlanRemain5h"),s,r,n),m=We(n("codingPlanRemain7d"),o,r,n),p=c.level==="over"||m.level==="over"?"over":c.level==="warn"||m.level==="warn"?"warn":"ok",f=(N,A,w)=>{const b=A?.unlimited?n("quotaUnlimited"):nt(w.label,r,n),S=_e(A,n);return N+" "+b+(S?" · "+S:"")},g=[n("codingPlanMinimaxTitle"),f(n("codingPlanRemain5h"),s,c),f(n("codingPlanRemain7d"),o,m),a>0?n("goQuotaFetchedAt",{time:new Date(a).toLocaleTimeString()}):null,...l?ge(n,l):[]].filter(Boolean).join(`
|
|
3
|
+
`),k=e(q,null,e("div",{className:"cm-mm-title"},n("codingPlanMinimaxTitle")),c.row,m.row,d?e("div",{className:"cm-mm-reset"},"5h · "+d):null),v=e(q,null,e("div",{className:"cm-bbox-rail cm-num"},c.text),e("div",{className:"cm-bbox-rail cm-num"},m.text));return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},g),side:"right",delayMs:300},e("div",{...u,className:"cm-bbox cm-mm"+(p==="ok"?"":" "+p)+(i===!1?" rail":"")+(l?" clickable"+(l.busy?" busy":""):""),...l?me(l.busy,l.run):{}},i===!1?v:k))}function _n(t){const{state:s,wide:o,api:a}=t,n=s.codingPlans?.minimax,i=K(_(s.config?.locale)),l=Pe(a?()=>a.refreshCodingPlan("minimax"):null);if(!n||n.status!=="ok")return null;const{five:r,seven:u}=Fe(n.windows);return r==null&&u==null?null:e(va,{five:r,seven:u,fetchedAt:n.fetchedAt,t:i,wide:o,refresh:l,direction:ae(s.config,"plan")})}const Wn="/plugins/dsh-openai-codex/auth/status",zn=168*3600;function Gn(t){if(t===null||typeof t!="object"||t.status!=="signed-in")return null;const s=t.usage!==null&&typeof t.usage=="object"?t.usage.rateLimits:null;if(!Array.isArray(s))return null;const o=s.find(r=>r!==null&&typeof r=="object"&&r.id==="codex");if(!o||!Array.isArray(o.windows))return null;const a=o.windows.find(r=>r!==null&&typeof r=="object"&&Number(r.windowSeconds)===zn);if(!a||typeof a.remainingPercent!="number"||!Number.isFinite(Number(a.remainingPercent)))return null;const n=Math.max(0,Math.min(100,Math.round((100-Number(a.remainingPercent))*10)/10)),i=Number(a.resetAt),l=Number.isFinite(i)&&i>0?new Date(i*1e3).toISOString():"";return{weekly:{percent:n,resetsAt:l}}}const J={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},Kn=t=>(J.listeners.push(t),()=>{J.listeners=J.listeners.filter(s=>s!==t)}),Yn=()=>{for(const t of J.listeners)try{t()}catch{}};async function Pt(t=!1,s=!1){if(!s)return;if(J.inFlight!==null)return J.inFlight;if(!t&&J.fetchedAt>0&&Date.now()-J.fetchedAt<5*6e4)return;const o=(async()=>{try{const a=await fetch(Wn,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(a.ok){const i=Gn(await a.json().catch(()=>null));i!==null&&(n=i)}J.status=Object.keys(n).length>0?"ok":"unavailable",J.windows=n}catch{J.status="unavailable"}finally{J.fetchedAt=Date.now(),J.inFlight=null,Yn()}})();return J.inFlight=o,o}function Mt(t){const[s,o]=L(()=>({status:J.status,windows:J.windows,fetchedAt:J.fetchedAt}));return X(()=>{if(!t)return;let a=!0;const n=()=>{a&&o({status:J.status,windows:J.windows,fetchedAt:J.fetchedAt})},i=Kn(n);return n(),Pt(!1,!0),()=>{a=!1,i()}},[t]),s}function Vn(t){const s=st(),{state:o,wide:a}=t,n=K(_(o.config?.locale)),i=Mt(o.config?.codexQuotaEnabled===!0),l=Pe(()=>Pt(!0,o.config?.codexQuotaEnabled===!0));if(o.config?.codexQuotaEnabled!==!0||i.status!=="ok")return null;const r=i.windows.weekly??null;if(r===null)return null;const u=ae(o.config,"plan"),d=We(n("goShortWeekly"),r,u,n),c=[n("codexQuotaTitle"),nt(d.label,u,n),_e(r,n),i.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()}):null,...ge(n,l)].filter(Boolean).join(`
|
|
4
|
+
`),m=e(q,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),d.row),p=e("div",{className:"cm-bbox-rail cm-num"},d.label===null?"—":d.label+"%");return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},c),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(d.level==="ok"?"":" "+d.level)+(a===!1?" rail":"")+(l.busy?" busy":""),...me(l.busy,l.run)},a===!1?p:m))}function Tt(t,s){return t==="fiveHour"||t==="5h"?"5h":t==="weekly"||t==="week"||t==="7d"?t==="7d"?"7d":s("goShortWeekly"):t==="monthly"||t==="month"?s("goShortMonthly"):t==="daily"||t==="day"?s("goShortDaily"):t==="plan"?s("mimoWindowPlan"):t==="compensation"?s("mimoWindowCompensation"):t==="balance"?s("codingPlanWindowBalance"):String(t).replace(/_/g," ")}function Jn(t){const s=st(),{id:o,state:a,wide:n,api:i}=t,l=a.codingPlans?.[o],r=K(_(a.config?.locale)),u=Pe(i?()=>i.refreshCodingPlan(o):null),d=Re.find(b=>b.id===o);if(!d||!l||l.status!=="ok")return null;const c=l.windows!==null&&typeof l.windows=="object"?l.windows:{},m=Object.entries(c);if(m.length===0)return null;const p=b=>b!==null&&typeof b=="object"&&typeof b.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(b.percent)||0))):null,f=ae(a.config,"plan"),g=m.map(([b,S])=>{const y=p(S);if(y===null)return e("div",{key:b,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof S?.text=="string"?S.text:"—"));const P=y>=100?"over":y>=80?"warn":"ok",T=de(y,f);return e("div",{key:b,className:"cm-mm-row wide"+(P==="ok"?"":" "+P)},e("span",{className:"cm-bbox-label"},Tt(b,r)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:T.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},T.label===null?"—":T.label+"%"))}),k=m.map(([b,S])=>{const y=p(S),P=_e(S,r),T=y===null?typeof S?.text=="string"?S.text:"—":nt(de(y,f).label,f,r);return Tt(b,r)+" "+T+(P?" · "+P:"")});l.fetchedAt>0&&k.push(r("goQuotaFetchedAt",{time:new Date(l.fetchedAt).toLocaleTimeString()})),k.push(...ge(r,u));const v=[r(d.labelKey),...k].join(`
|
|
5
|
+
`),N=m.map(([,b])=>p(b)).filter(b=>b!==null),A=N.some(b=>b>=100)?"over":N.some(b=>b>=80)?"warn":"ok",w=N.length>0?N.slice(0,2).map(b=>de(b,f).label+"%").join(" "):typeof m[0][1]?.text=="string"?m[0][1].text:"—";return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},v),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(A==="ok"?"":" "+A)+(n===!1?" rail":"")+(u.busy?" busy":""),...me(u.busy,u.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},w):e(q,null,e("div",{className:"cm-mm-title"},r(d.labelKey)),...g)))}const Na=t=>{try{return window.localStorage?.getItem?.("cm.gw."+t)??""}catch{return""}},Zn=(t,s)=>{try{window.localStorage?.setItem?.("cm.gw."+t,s)}catch{}};function $n(t){const s=st(),{source:o,snapshot:a,state:n,wide:i,api:l}=t,r=K(_(n.config?.locale)),[u,d]=L(()=>({source:o.id,id:Na(o.id)})),c=Pe(l?()=>l.refreshGatewayQuota(o.id):null),m=ae(n.config,"plan"),p=a.accounts.length>1,f=u.source===o.id?u.id:Na(o.id),g=a.accounts.findIndex(O=>O.id===f),k=g>=0?g:Math.max(0,a.accounts.findIndex(O=>O.windows.length>0||O.credits!=null)),v=a.accounts[k]??a.accounts[0],N=v?.label||v?.id||"",A=O=>p?(Vt[O.provider]??O.provider)+" · ":"",w=p&&v?[v]:a.accounts,b=[];for(const O of w){if(b.length>=4)break;for(const G of O.windows){if(b.length>=4)break;const R=A(O)+(G.label||G.id||r("gatewaySourceUnknown"));b.push({win:G,name:R,view:We(R,G,m,r)})}O.windows.length===0&&O.credits!=null&&b.push({win:null,name:A(O)+(O.credits.unit||"credits"),text:(O.credits.used??"—")+" / "+(O.credits.limit??"—")})}b.length===0&&b.push({name:r("gatewayQuotaEmpty"),text:"—"});const S=b.some(O=>O.view?.level==="over")?"over":b.some(O=>O.view?.level==="warn")?"warn":"ok",y=b.map(O=>{if(O.text!=null)return O.name+" "+O.text;const G=_e(O.win,r);return O.name+" "+nt(O.view.label,m,r)+(G?" · "+G:"")});a.fetchedAt>0&&y.push(r("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()})),y.push(...ge(r,c));const T=[p&&N?`${o.label||o.id} (${k+1}/${a.accounts.length} · ${N})`:o.label||o.id,...y].join(`
|
|
6
|
+
`),B=b.map((O,G)=>O.text!=null?e("div",{key:G,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},O.name),e("span",{className:"cm-mm-text cm-num"},O.text)):e(q,{key:G},O.view.row)),M=O=>{if(!O.key||O.key==="Enter"||O.key===" "){O.stopPropagation(),O.preventDefault?.();const G=a.accounts[(k+1)%a.accounts.length];Zn(o.id,G.id),d({source:o.id,id:G.id})}},E=p?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:N||k+1}),onClick:M,onKeyDown:M,role:"button",tabIndex:0},`${k+1}/${a.accounts.length} ⇄`):null,h=p?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),E):e("div",{className:"cm-mm-title"},o.label||o.id),I=p&&N?e("div",{className:"cm-gw-sub"},N):null,te=e(q,null,h,I,...B),ye=b.filter(O=>O.view).map(O=>O.view.label).filter(O=>O!==null),ve=ye.length>0?ye.slice(0,2).map(O=>O+"%").join(" "):b[0].text??"—",D=e("div",{className:"cm-bbox-rail cm-num"},ve);return e(Z,{label:e("span",{style:{whiteSpace:"pre-line"}},T),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(S==="ok"?"":" "+S)+(i===!1?" rail":"")+(c.busy?" busy":""),...me(c.busy,c.run)},i===!1?e(q,null,D,E):te))}function Xn(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],i=[];for(const l of s.gatewayQuotas?.sources??[]){if(l.enabled===!1||l.display!=="sidebar"&&l.display!=="both")continue;const r=n.find(u=>u.id===l.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||i.push(e($n,{source:l,snapshot:r,state:t,wide:o,api:a}))}return i}const es={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function ts(t){const s=t.useCost?t.useCost(g=>g):void 0;Mt(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=L(null),[n,i]=L({}),l=s?.state,r=t.api;if(!l)return null;const u=l.config,d=u.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(d.enabled!==!0)return null;const c=K(_(u?.locale)),m=[];if(d.budget!==!1){const g=u.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const k=Number(u.exchangeRate),N=(l.budgetUsed??(g.period==="day"?W(l.today,u):g.period==="all"?W(l.total,u):W(l.month,u)))*(Number.isFinite(k)&&k>0?k:1),A=Math.max(0,Number(g.amount)||0);if(A>0){const w=Math.min(999,N/A*100),b=w>=100?"over":w>=80?"warn":"ok";m.push({key:"budget",label:c("budgetShort"),level:b,tip:c("budgetOf",{period:c(qe[g.period]??"periodMonth")})+" · "+c("usedOf",{used:oe(N,u),amount:oe(A,u)})+" · "+w.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(de(Math.min(100,w),ae(u,"budget")).width)}]})}}}if(d.go!==!1){const g=l.goQuota;if(u?.goQuota?.enabled!==!1&&g?.status==="ok"){const k=u.goQuota.main==="weekly"||u.goQuota.main==="monthly"?u.goQuota.main:"rolling",v=k==="rolling"?g.rolling:k==="weekly"?g.weekly:g.monthly;if(v!==null&&typeof v=="object"&&typeof v.percent=="number"){const N=Math.max(0,Math.min(100,Math.round(Number(v.percent)||0))),A=N>=100?"over":N>=80?"warn":"ok",w=typeof v.resetsAt=="string"&&v.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(v.resetsAt).toLocaleString()}):"";m.push({key:"go",label:"Go "+c(k==="rolling"?"goShortRolling":k==="weekly"?"goShortWeekly":"goShortMonthly"),level:A,tip:"Go: "+N+"%"+w,segs:[{name:"main",pct:Math.round(de(N,ae(u,"go")).width)}]})}}}if(d.plans!==!1)for(const g of Re){const k=l.codingPlans?.[g.id];if(u.codingPlans?.[g.id]?.enabled!==!0||!k||k.status!=="ok")continue;const v=k.windows!==null&&typeof k.windows=="object"?k.windows:{},N=Object.entries(v);if(N.length===0)continue;const A=es[g.id]??g.id,w=[],b=[];let S=0,y=0;for(const[P,T]of N){const B=Tt(P,c),M=typeof T?.resetsAt=="string"&&T.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(T.resetsAt).toLocaleString()}):"",E=T!==null&&typeof T=="object"&&typeof T.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(T.percent)||0))):null;if(b.push(B+" "+(E===null?typeof T?.text=="string"?T.text:"—":E+"%")+M),E===null){w.push({name:P,pct:null,text:typeof T?.text=="string"?T.text:"—"});continue}y>=2||(y+=1,w.push({name:P,pct:Math.round(de(E,ae(u,"plan")).width)}),S=Math.max(S,E>=100?2:E>=80?1:0))}k.fetchedAt>0&&b.push(c("goQuotaFetchedAt",{time:new Date(k.fetchedAt).toLocaleTimeString()})),w.length!==0&&m.push({key:g.id,label:A,level:["ok","warn","over"][S],tip:b.join("; "),segs:w})}const p=u.codexQuotaEnabled===!0&&J.status==="ok"?J.windows.weekly??null:null;if(p!==null&&typeof p.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(p.percent)||0))),k=typeof p.resetsAt=="string"&&p.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(p.resetsAt).toLocaleString()}):"";m.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+k,segs:[{name:"weekly",pct:Math.round(de(g,ae(u,"plan")).width)}]})}if(m.length===0)return null;const f=g=>{o!==null||!r||(a(g),i(k=>({...k,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?Pt(!0,u.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(k=>{i(v=>({...v,[g]:k?.message??String(k)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},m.map(g=>{const k=o===g.key,v=n[g.key],N=[e("span",{className:"cm-qlabel",key:"l"},g.label)];k?N.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((w,b)=>{b>0&&N.push(e("span",{className:"cm-qsep",key:"sep"+b,"aria-hidden":"true"})),w.pct===null?N.push(e("span",{className:"cm-qtext",key:w.name},w.text)):N.push(e("span",{className:"cm-qseg",key:w.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:w.pct+"%"}})),e("span",null,w.pct+"%")))});const A=[g.tip];return!k&&r&&A.push(c("clickToRefresh")),k&&A.push(c("refreshing")),v&&A.push("⚠ "+c("balanceRefreshFailed",{message:v})),e(Z,{key:g.key,label:A.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?me(k,()=>f(g.key)):{}},N))}))}const Sa="dsh-cost-meter:simple-guide-dismissed";function Bt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Sa)==="1"}catch{return!1}}function as(t){const s=t.useCost?t.useCost(f=>f):void 0,o=we(!1),[a,n]=L(!1),[i,l]=L(!1),[r,u]=L(!1),d=s?.state?.config;if(!d||r||Bt(d))return null;const c=K(_(d.locale)),m=()=>{u(!0);try{window.localStorage.setItem(Sa,"1")}catch{}},p=async f=>{if(!o.current){o.current=!0,n(!0),l(!1);try{if((await t.api.updateConfig({sidebarSimple:f,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==f)throw new Error;m()}catch{l(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:f=>{f.key==="Escape"&&(f.stopPropagation(),m())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:m},"×")),e("p",null,c("sidebarSimpleBody")),i?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>p(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>p(!0)},c("sidebarSimpleOn"))))}function ns(t){const s=t.useCost?t.useCost(r=>r):void 0,o=we(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Bt(n)||n.quotaStrip?.promptSeen===!0)return null;const i=K(_(n?.locale)),l=r=>{if(o.current===!0)return;o.current=!0;const u=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...u,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":i("quotaStripGuideTitle")},e("h4",null,i("quotaStripGuideTitle")),e("p",null,i("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>l(!1)},i("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>l(!0)},i("quotaStripGuideOn"))))}const Ca="dsh-cost-meter:balance-click-hint-seen",ss=()=>{try{return window.localStorage.getItem(Ca)==="1"}catch{return!1}},os=()=>{try{window.localStorage.setItem(Ca,"1")}catch{}};function ls(t){const s=t.useCost?t.useCost(f=>f):void 0,o=we(!1),[a,n]=L(!1),[i]=L(ss),l=s?.state;if(!l)return null;const r=l.config,u=r.balance?.display==="sidebar"||r.balance?.display==="both",d=(r?.customBalances??[]).some(f=>f?.enabled===!0&&(f.display==="sidebar"||f.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Re.some(f=>{const g=r.codingPlans?.[f.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||i||r.balance?.clickHintSeen===!0||!u&&!d&&!c||!Bt(r)||r.quotaStrip?.promptSeen!==!0)return null;const m=K(_(r?.locale)),p=()=>{o.current!==!0&&(n(!0),o.current=!0,os(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":m("balanceClickGuideTitle")},e("h4",null,m("balanceClickGuideTitle")),e("p",null,m("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:p},m("balanceClickGuideOk"))))}function Dt(t,s,o){return s.sidebarTodayMetric==="tokens"?H((Number(t?.input)||0)+(Number(t?.output)||0))+" "+o("tokensUnit"):V(W(t,s),s)}function Ot(t){const{state:s,wide:o}=t,a=s.today,n=s.config,i=K(_(n?.locale)),l=Dt(a,n,i),r=n.budget??{enabled:!1,amount:100,period:"month"},u=Number(n.exchangeRate),c=(s.budgetUsed??(r.period==="day"?W(s.today,n):r.period==="all"?W(s.total,n):W(s.month,n)))*(Number.isFinite(u)&&u>0?u:1),m=Math.max(0,Number(r.amount)||0),p=m>0?Math.min(999,c/m*100):null,f=p===null?"ok":p>=100?"over":p>=80?"warn":"ok";if(r.enabled===!0){const v=W(a,n)*(Number.isFinite(u)&&u>0?u:1),N=m>0?Math.min(999,v/m*100):null,A=[i("budgetOf",{period:i(qe[r.period]??"periodMonth")}),i("usedOf",{used:oe(c,n),amount:oe(m,n)})+" · "+(p===null?"—":p.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[n.sidebarTodayMetric==="tokens"?i("today")+" "+l:i("todayShare",{amount:l,pct:N===null?"—":N.toFixed(1)+"%"})],i("monthTotal",{month:V(W(s.month,n),n),total:V(W(s.total,n),n)})].join("; ");if(t.summary===!0)return e(Z,{label:A,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(f==="ok"?"":" "+f),tabIndex:0},e("span",null,i("todayBudget",{period:i(qe[r.period]??"periodMonth")})),e("span",{className:"cm-num"},l+" / "+oe(m,n))));const w=ka(s,n,i);return e(Z,{label:A,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(f==="ok"?"":" "+f)+(o?"":" rail")},o?w.body:e("div",{className:"cm-bbox-rail cm-num"},w.rail)))}const g=[n.sidebarTodayMetric==="tokens"?i("todayTokensTitle"):i("todayCostTitle"),i("callsTokens",{calls:a.calls,input:H(a.input),cache:H(a.cacheRead+a.cacheWrite),output:H(a.output)}),i("monthCost",{amount:V(W(s.month,n),n)}),i("totalCost",{amount:V(W(s.total,n),n)})].join("; ");return e(Z,{label:g,side:"right",delayMs:300},e(q,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(q,null,i("today")," ",e("span",{className:"cm-num"},l)):e($e,{size:16})),o?at(s,n,i):null))}function is(t){const s=t.useCost?t.useCost(E=>E):void 0;Mt(s?.state?.config?.codexQuotaEnabled===!0);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}da(t,o);const a=s?.state,n=!!t.wide,i=we(null);if(X(()=>{const E=i.current,h=E?.parentElement;if(!E||!h)return;const I=()=>{n?h.firstElementChild!==E&&h.insertBefore(E,h.firstElementChild):h.lastElementChild!==E&&h.appendChild(E)};I();const te=new MutationObserver(()=>{E.isConnected&&I()});return te.observe(h,{childList:!0}),n?(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap=""):(h.style.flexDirection="column",h.style.flexWrap="nowrap",h.style.alignItems="center",h.style.gap="6px"),()=>{te.disconnect(),n||(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap="")}},[n,a]),!a)return null;const l=a.config,r=K(_(l?.locale)),u=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,c=Ct(a,l).length>0,m=u&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",p=c&&l.balance?.showProgressBar===!0,f=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",g=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[f]!==null,k=Re.map(E=>E.id).filter(E=>{const h=l.codingPlans?.[E];if(h?.enabled!==!0||h.display!=="sidebar"&&h.display!=="both")return!1;const I=a.codingPlans?.[E];if(I?.status!=="ok")return!1;const te=I.windows!==null&&typeof I.windows=="object"?I.windows:{};return Object.keys(te).length>0}),v=k.length>0,N=Xn(a,l,n,t.api),A=l.codexQuotaEnabled===!0&&J.status==="ok"&&J.windows.weekly!==null,w=(l.budget??{}).enabled===!0,b=l.sidebar!==!1&&l.hideTodayCost!==!0,S=l.sidebarModels?.enabled===!0;if(!S&&!u&&!c&&!g&&!v&&!A&&!w&&!b&&N.length===0)return null;const y=l.sidebarSimple===!0,P=!y&&n&&l.sidebarStyle==="compact",T=y&&n&&b&&w,B=[];T?B.push(e(Ot,{state:a,wide:n,summary:!0})):y&&n&&b&&B.push(e("div",{className:"cm-simple-summary"},e("span",null,r("today")),e("span",{className:"cm-num"},Dt(a.today,l,r)))),m?B.push(e(Mn,{state:a,wide:n,api:t.api})):u&&B.push(e(Pn,{state:a,wide:n,api:t.api})),p?B.push(e(Bn,{state:a,wide:n,api:t.api})):c&&B.push(e(On,{state:a,wide:n,api:t.api}));const M=B.length;if(v&&B.push(...k.map(E=>E==="minimax"?e(_n,{state:a,wide:n,api:t.api}):e(Jn,{id:E,state:a,wide:n,api:t.api}))),B.push(...N),A&&B.push(e(Vn,{state:a,wide:n,api:t.api})),g&&w&&n&&!y){const E=wa(a,l,r),h=ka(a,l,r),I=E.level==="over"||h.level==="over"?"over":E.level==="warn"||h.level==="warn"?"warn":"ok";B.push(e("div",{className:"cm-bbox cm-bbox-pair"+(I==="ok"?"":" "+I)},e("div",{className:"cm-bbox-section"+(E.level==="ok"?"":" "+E.level)},E.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(h.level==="ok"?"":" "+h.level)},h.body)))}else g&&B.push(e(Qn,{state:a,wide:n})),w&&!T&&B.push(e(Ot,{state:a,wide:n}));return!w&&b&&!(y&&n)&&B.push(e(Ot,{state:a,wide:n})),y&&n&&b&&B.push(at(a,l,r)),n||B.push(jn(a,l,r)),S&&B.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?M:B.length,0,e(rs,{key:"models",state:a,wide:n})),e("div",{ref:i,...y?{tabIndex:0,role:"region","aria-label":r("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(P?" compact":"")+(y?" simple":"")},...B)}const Rt={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Aa="dsh-cost-meter:models-open";function Pa(t,s,o){return Ba(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:qt(a.key),cost:W(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function rs({state:t,wide:s}){const o={...Rt,...t.config.sidebarModels},a=K(_(t.config.locale)),n=()=>{try{const N=o.remember?window.localStorage.getItem(Aa):null;if(N!==null)return N==="1"}catch{}return o.defaultOpen},[i,l]=L(n),[r,u]=L(o.period);X(()=>u(o.period),[o.period]),X(()=>l(n()),[o.defaultOpen,o.remember]);const d=Pa(t,r,a),c=d.reduce((N,A)=>N+A.cost,0),m=N=>V(N,t.config),p=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+m(c)+" · "+a("modelsCount",{n:d.length}),f=o.summary==="top"&&d.length?d[0].label+" "+m(d[0].cost):p,g=o.summary==="top"&&d.length?e(q,null,e("span",{className:"cm-bal-label"},d[0].label),e("span",{className:"cm-bal-amt"},m(d[0].cost))):e("span",{className:"cm-bal-label"},f),k=()=>{l(!i);try{o.remember&&window.localStorage.setItem(Aa,i?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:f+" · "+p},s?g:e($e,{size:16}));const v=d.slice(0,o.topN);return d.length>o.topN&&v.push(d.slice(o.topN).reduce((N,A)=>{for(const w of["cost","input","output","cacheRead","cacheWrite"])N[w]+=A[w];return N},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(i),title:p,onClick:k},e("span",{className:"cm-caret"+(i?" open":"")}),g),i?e(q,null,e("div",{className:"cm-buttons"},["today","history"].map(N=>e("button",{key:N,type:"button",className:"cm-mstats-tab"+(r===N?" active":""),"aria-pressed":r===N,onClick:()=>u(N)},a(N==="today"?"modelStatsToday":"modelStatsHistory")))),v.length?v.map(N=>e("div",{key:N.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:N.label},N.label),e("span",{className:"cm-num cm-bal-amt"},m(N.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?N.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?N.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+H(N.input)+" · "+a("modelStatsCache")+" "+H(N.cacheRead+N.cacheWrite)+" · "+a("modelStatsOutput")+" "+H(N.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function cs({draft:t,setDraft:s,t:o}){const a={...Rt,...t?.sidebarModels},n=(l,r)=>{t&&s({...t,sidebarModels:{...a,[l]:r}})},i=(l,r)=>e("div",{className:"cm-field",key:l},e("label",null,o("models_"+l)),e("select",{className:"cm-input",value:a[l],onChange:u=>n(l,u.target.value)},r.map(([u,d])=>e("option",{key:u,value:u},o(d)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(l=>e("label",{key:l,className:"cm-check"},e("input",{type:"checkbox",checked:a[l],onChange:r=>n(l,r.target.checked)}),o("models_"+l))),i("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),i("summary",[["total","modelsTotal"],["top","modelsTop"]]),i("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(l=>e("div",{key:l,className:"cm-field"},e("label",null,o("models_"+l)),ee({value:a[l]},r=>n(l,Math.max(l==="topN"?1:10,Math.min(l==="topN"?10:60,Math.floor(r))))))))}function ot(t){return e("div",{className:"cm-card"},e("p",{className:"cm-card-title"},t.title),e("div",{className:"cm-card-value cm-num"},t.value),e("p",{className:"cm-card-sub"},t.sub))}function ds({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=d=>V(W(d,a),a),i=d=>s("callsTokens",{calls:d.calls,input:H(d.input),cache:H(d.cacheRead+d.cacheWrite),output:H(d.output)}),l=(d,c)=>({calls:d.calls+c.calls,input:d.input+c.input,output:d.output+c.output,cacheRead:d.cacheRead+c.cacheRead,cacheWrite:d.cacheWrite+c.cacheWrite,cost:W(d,a)+c.cost,apiCost:W(d,a)+c.cost}),r=(d,c)=>e("tr",{key:d},e("td",null,d),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},H(c.input)),e("td",{className:"num"},H(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},H(c.output)),e("td",{className:"num"},n(c))),u=d=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,d)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((d,c)=>{const m=l(t[d],o.combined[d]);return e(ot,{key:d,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(m),sub:i(m)})})),...o.sources.map(d=>e("details",{key:d.source},e("summary",null,d.source+" · "+s("cardToday")+" "+n(d.today)+" · "+s("cardMonth")+" "+n(d.month)+" · "+i(d.today)),u(["today","month","total"].map((c,m)=>r(s(["cardToday","cardMonth","cardTotal"][m]),d[c]))),e("p",{className:"cm-note"},s("externalHistory")),u(d.history.map(c=>r(c.date,c))))))}const Oe=(t,s,o)=>e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(t),onClick:s},e("span",{className:"cm-caret"+(t?" open":"")}),e("h3",{className:"cm-h"},o));function us(t){const{state:s,api:o}=t,a=K(_(s.config?.locale)),[n,i]=L(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,()=>i(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(ms,{state:s,api:o})):null)}function ms(t){const{state:s,api:o}=t,a=K(_(s.config?.locale)),[n,i]=L(null),[l,r]=L({}),[u,d]=L(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const m=f=>{if(n===f){i(null);return}i(f),!(l[f]!==void 0||u.has(f))&&(d(g=>{const k=new Set(g);return k.add(f),k}),o.getDaySessions(f).then(g=>r(k=>({...k,[f]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[f]:"error"}))).finally(()=>d(g=>{const k=new Set(g);return k.delete(f),k})))},p=f=>f.map(g=>e("tr",{key:g.id},Lt(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},H(g.input)),e("td",{className:"num"},H(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},H(g.output)),e("td",{className:"num"},V(W(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(f=>{const g=e("tr",{key:f.date,className:"cm-row-click",onClick:()=>m(f.date)},e("td",null,(n===f.date?"▾ ":"▸ ")+f.date),e("td",{className:"num"},String(f.calls)),e("td",{className:"num"},H(f.input)),e("td",{className:"num"},H(f.cacheRead+f.cacheWrite)),e("td",{className:"num"},H(f.output)),e("td",{className:"num"},V(W(f,s.config),s.config)));if(n!==f.date)return[g];const k=l[f.date],v=u.has(f.date)&&k===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):k==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(k)||k.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,p(k)));return[g,e("tr",{key:f.date+"-sessions"},e("td",{colSpan:6},v))]}))))}function ps(t){const{state:s,api:o}=t,a=K(_(s.config?.locale)),[n,i]=L(!1),[l,r]=L(100),[u,d]=L("cost-desc"),[c,m]=L(null),[p,f]=L(!1),[g,k]=L(!1),v=Ee.useRef(0),N=(S,y)=>{const[P,T]=y==="recent"?["recent","desc"]:y.split("-"),B=++v.current;f(!0),k(!1),o.getTopSessions(S,P,T).then(M=>{B===v.current&&m(Array.isArray(M?.sessions)?M.sessions:[])}).catch(()=>{B===v.current&&k(!0)}).finally(()=>{B===v.current&&f(!1)})},A=()=>{i(S=>{const y=!S;return y&&c===null&&!p&&N(l,u),y})},w=S=>{r(S),(n||c!==null)&&N(S,u)},b=S=>{d(S),(n||c!==null)&&N(l,S)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,A,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:u,onChange:S=>b(S.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(l),onChange:S=>w(Number(S.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),p?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(S=>e("tr",{key:S.date+":"+S.id},e("td",null,S.date),Lt(S,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(S.calls)),e("td",{className:"num"},H(S.input)),e("td",{className:"num"},H((S.cacheRead??0)+(S.cacheWrite??0))),e("td",{className:"num"},H(S.output)),e("td",{className:"num"},V(W(S,s.config),s.config)))))))):null)}function bs(t){const{state:s}=t,o=K(_(s.config?.locale)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(i=>e("tr",{key:i.id},Lt(i,n,o),e("td",{className:"num"},String(i.calls)),e("td",{className:"num"},H(i.input)),e("td",{className:"num"},H(i.cacheRead+i.cacheWrite)),e("td",{className:"num"},H(i.output)),e("td",{className:"num"},V(W(i,s.config),s.config)))))))}function Lt(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",i=a.length>0?a:n,l=a.length>0?a+" · "+t.id:t.id;return e("td",{title:l},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},i),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const fs={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function gs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=o?.budget??i.budget,r=Number(i.exchangeRate),d=(s.budgetUsed??(l.period==="day"?W(s.today,i):l.period==="all"?W(s.total,i):W(s.month,i)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),m=l.enabled&&c>0?Math.min(999,d/c*100):null,p=m===null?"ok":m>=100?"over":m>=80?"warn":"ok",f=(v,N)=>{o!==null&&a({...o,budget:{...o.budget??i.budget,[v]:N}})},g=l.period==="custom"?l.customStart+" → "+(l.customEnd??n("periodDay")):null,k=l.enabled&&m!==null?n("budgetStatus",{period:n(qe[l.period]??"periodMonth"),amount:oe(c,i),used:oe(d,i),pct:m.toFixed(1)})+(p==="over"?n("overLimit"):p==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:l.enabled===!0,onChange:v=>f("enabled",v.target.checked)}),e("span",null,n("enableBudget")))),l.enabled?e(q,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(p==="ok"?"":p),style:{width:(m===null?0:Math.min(100,m))+"%"}})),e("div",{className:"cm-budget-line"+(p==="over"?" over":"")+" cm-num"},k),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ee({value:l.amount},v=>f("amount",v))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:l.period,onChange:v=>f("period",v.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),l.period==="custom"?e(q,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:l.customStart??"",onChange:v=>f("customStart",v.target.value===""?null:v.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:l.customEnd??"",onChange:v=>f("customEnd",v.target.value===""?null:v.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function hs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=(c,m)=>{o!==null&&a({...o,[c]:m})},r=o===null?i:{...i,...o},u=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),m=Date.now();if(Number.isFinite(c)&&m<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const p=r.peakWindows??[],f=Xe(m,p,r.peakHolidays);return f===null?n("offPeakActive"):f.holiday===!0?n("holidayAllOffPeak"):f.weekend===!0?n("weekendAllOffPeak"):f.inPeak?n("peakActive"):n("offPeakActive")})(),d=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(_(r.locale)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:u}):n("noPeakWindows",{status:u});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>l("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>l("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>l("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>l("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const m=Number(c.target.value);Number.isInteger(m)&&m>=1&&m<=30&&l("peakAlertAhead",m)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>l("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>l("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{l("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?at(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},d),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>l("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ee(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const i=Number(n);Number.isFinite(i)&&i>=0&&s(i)}})}function Et(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:i,t:l}=t,r=Ve(o),u=p=>{const f={...Ve(p)};if(Array.isArray(p.rateHistory)){const g=p.rateHistory.filter(k=>Date.parse(k.before)<=Date.now());g.length>0?f.rateHistory=g:delete f.rateHistory}return f},d=(p,f,g)=>{if(g===null){if(a){const P=u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),T={...P[p]??{}};delete T[f];const B={...P};Object.keys(T).length>0?B[p]=T:delete B[p],i({...n,prices:{...n.prices,default:B}});return}const w={...n.prices.models},b=u(w[s]??{cacheHit:0,cacheMiss:0,output:0}),S={...b[p]??{}};delete S[f];const y={...b};Object.keys(S).length>0?y[p]=S:delete y[p],w[s]=y,i({...n,prices:{...n.prices,models:w}});return}const k=Math.max(0,g);if(a){let b={...u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(p==="base")b[f]=k;else{const S={...b[p]??{},[f]:k};b={...b,[p]:S}}i({...n,prices:{...n.prices,default:b}});return}const v={...n.prices.models},N=u(v[s]??{cacheHit:0,cacheMiss:0,output:0});let A={...N};if(p==="base")A[f]=k;else{const w={...N[p]??{},[f]:k};A={...N,[p]:w}}v[s]=A,i({...n,prices:{...n.prices,models:v}})},c=()=>{const p={...n.prices.models};delete p[s],i({...n,prices:{...n.prices,models:p}})},m=(p,f)=>{const g=f==="base"?r:r[f]??null,k=f==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:f},e("span",null,p),ee({value:g?.cacheHit??null,emptyMode:k},v=>d(f,"cacheHit",v)),ee({value:g?.cacheMiss??null,emptyMode:k},v=>d(f,"cacheMiss",v)),ee({value:g?.output??null,emptyMode:k},v=>d(f,"output",v)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(q,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},l("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},l("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},l("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatCached")),e("span",null,l("flatInput")),e("span",null,l("flatOutput"))),m(l("tierBase"),"base"),m(l("tierOffPeak"),"offPeak"),m(l("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},l("datedPriceNote")):null)}const Ma={deepseek:"DeepSeek",openai:"OpenAI",anthropic:"Anthropic",google:"Google Gemini",moonshot:"Moonshot (Kimi)","z-ai":"Z.ai / 智谱",xai:"xAI",alibaba:"阿里云百炼",minimax:"MiniMax",tencent:"腾讯混元",xiaomi:"小米",upstage:"Upstage",nvidia:"NVIDIA",mistral:"Mistral",meta:"Meta",meituan:"美团 LongCat","opencode-go":"OpenCode Go"};function ys(t,s,o="USD"){if(t=Ve(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");o==="CNY"&&t.cny&&(t=t.cny);const a=i=>(o==="CNY"?"¥":"$")+String(i),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function ks(t){const{state:s,draft:o,setDraft:a,t:n}=t,[i,l]=L(!1),[r,u]=L({}),d=s.priceCatalog;if(d===null||typeof d!="object")return null;const c=o?.prices??s.config.prices,m=o?.priceTableDisplay??s.config.priceTableDisplay??{},p=(y,P)=>{const T=m[y+":"+P];return typeof T=="boolean"?T:y==="deepseek"},f=(y,P,T)=>{o!==null&&a({...o,priceTableDisplay:{...m,[y+":"+P]:T}})},g=(y,P)=>y==="deepseek"?c.models?.[P]!==void 0:c.providers?.[y]?.models?.[P]!==void 0,k=(y,P,T)=>{if(o===null)return;const B=JSON.parse(JSON.stringify(T));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[P]:B}}});return}const M={...o.prices.providers??{}},E=M[y]??{};M[y]={...E,models:{...E.models??{},[P]:B}},a({...o,prices:{...o.prices,providers:M}})},v=(y,P)=>{if(o===null)return;if(y==="deepseek"){const M={...o.prices.models};delete M[P],a({...o,prices:{...o.prices,models:M}});return}const T={...o.prices.providers??{}},B=T[y];if(B!==void 0&&B.models!==void 0){const M={...B.models};delete M[P],T[y]={...B,models:M},a({...o,prices:{...o.prices,providers:T}})}},N=Object.keys(d).sort((y,P)=>y==="deepseek"?-1:P==="deepseek"?1:y.localeCompare(P)),A=y=>Object.values(d[y]).reduce((P,T)=>P+Object.keys(T).length,0),w=new Set(Object.values(d.deepseek??{}).flatMap(y=>Object.keys(y))),b=Object.keys(c.models??{}).filter(y=>!w.has(y)).sort(),S=(y,P,T)=>{const B=g(y,P),M=p(y,P),E=B?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:M,onChange:h=>f(y,P,h.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(B&&!M&&o!==null){const h=y==="deepseek"?e(Et,{key:P,modelId:P,entry:c.models[P],isDefault:!1,draft:o,setDraft:a,t:n}):e(Oa,{key:P,provider:y,modelId:P,entry:c.providers?.[y]?.models?.[P],draft:o,setDraft:a,t:n});return e("div",{key:P,className:"cm-catalog-mounted"},E,h)}return e("div",{key:P,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},P),e("span",{className:"cm-catalog-price"},ys(T,n,y==="deepseek"||T?.cny?c.currency:"USD")),B?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,E,e("button",{className:"cm-btn small",disabled:!B&&T?.unpriced===!0,onClick:()=>B?v(y,P):k(y,P,T)},n(B?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>l(y=>!y)},n(i?"catalogCollapse":"catalogOpen"))),i?e(q,null,e("p",{className:"cm-note"},n("catalogNote")),N.map(y=>{const P=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>u(T=>({...T,[y]:!P}))},e("span",null,(P?"▾ ":"▸ ")+(Ma[y]??y)+" · "+A(y))),P?e(q,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(d[y]).sort().map(T=>e("div",{key:T},e("div",{className:"cm-catalog-family"},T),Object.keys(d[y][T]).sort().map(B=>S(y,B,d[y][T][B])))),y==="deepseek"&&b.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),b.map(T=>S("deepseek",T,null))):null):null)})):null)}const Ta=t=>t==="zen"?"go":t,qt=t=>{const s=t.indexOf(":");return s<=0?t:Ta(t.slice(0,s).toLowerCase())+t.slice(s)};function Ba(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],i=d=>Number.isFinite(Number(d))&&Number(d)>0?Number(d):0,l=(d,c,m)=>{if(!m||typeof m!="object")return;const p=d[c]??(d[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)p[g]+=i(m[g]);const f=c.indexOf(":");p.apiCost+=i(m.apiCost??(Ie(f>0?c.slice(0,f):"deepseek",f>0?c.slice(f+1):c,s)==="plan"?0:m.cost))},r=d=>{if(!d||typeof d!="object")return{};if(d.byProviderModel&&Object.keys(d.byProviderModel).length)return d.byProviderModel;if(d.byModel&&Object.keys(d.byModel).length)return Object.fromEntries(Object.entries(d.byModel).map(([m,p])=>[m.includes(":")?m:"deepseek:"+m,p]));const c={};for(const m of Array.isArray(d.sessions)?d.sessions:[])if(!(!m||typeof m!="object"))if(m.byProviderModel&&Object.keys(m.byProviderModel).length)for(const[p,f]of Object.entries(m.byProviderModel))l(c,p,f);else l(c,(m.provider||"deepseek")+":"+(m.model||"unknown"),m);return Object.keys(c).length?c:n.some(m=>i(d[m])>0)?{"deepseek:legacy":d}:{}};return(d=>{const c={},m=p=>{for(const[f,g]of Object.entries(p??{}))l(c,f,g)};if(d==="today")m(r(t.today));else{const p=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const f of t.history??[]){const g=Date.parse(f.date+"T00:00:00Z");g<=p&&g>=p-76896e5&&m(r(f))}}return Object.entries(c).map(([p,f])=>{const g=p.indexOf(":"),k=(g>0?p.slice(0,g):"deepseek").toLowerCase(),v=g>0?p.slice(g+1):p,N=f.input+f.output+f.cacheRead+f.cacheWrite+f.reasoning,A=f.cacheRead+f.input;return{label:p==="deepseek:legacy"?o("modelStatsLegacy"):k==="deepseek"||k===""?v:Ta(k)+":"+v,key:p,...f,tokens:N,cls:Ie(k,v,s),hitRate:A>0?f.cacheRead/A:null,cacheUnreported:mn(f),blended:N>0&&f.cost>0?f.cost/N*1e6:null,perUsd:f.cost>0?N/f.cost:null}}).filter(p=>p.tokens>0||p.cost>0)})(a).sort((d,c)=>c.cost-d.cost||c.tokens-d.tokens)}function ws(t){const{state:s,config:o,t:a,initialTab:n,draft:i,setDraft:l}=t,[r,u]=L(n==="history"?"history":"today"),[d,c]=L(!1),m=Ba(s,o,a,r),p=b=>(Math.max(0,Math.min(1,b))*100).toFixed(1)+"%",f=m.reduce((b,S)=>Math.max(b,S.cost),0),g=m.reduce((b,S)=>Math.max(b,S.tokens),0),k=m.reduce((b,S)=>Math.max(b,S.perUsd??0),0),v=(b,S)=>e("button",{className:"cm-mstats-tab"+(r===b?" active":""),onClick:()=>u(b)},S),N=b=>b.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,A=b=>e("select",{className:"cm-input",title:a("billingClassLabel"),value:o.planBilling?.models?.[b.key]??"auto",disabled:i===null,onChange:S=>{const y={...i.planBilling?.models??{}};S.target.value==="auto"?delete y[b.key]:y[b.key]=S.target.value,l({...i,planBilling:{...i.planBilling,models:y}})}},e("option",{value:"auto"},a("billingClassAuto")),e("option",{value:"plan"},a("billingClassPlan")),e("option",{value:"api"},a("billingClassApi"))),w=(b,S,y,P,T)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:b},b,T??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+y,style:{width:p(S)}})),e("span",{className:"cm-mstats-val"},P));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(d,()=>c(!d),a("modelStatsTitle"))),d?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},v("today",a("modelStatsToday")),v("history",a("modelStatsHistory"))),m.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(q,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),m.map(b=>e(q,{key:"c:"+b.label},w(b.label,f>0?b.cost/f:0,"cost",V(b.cost,o),e(q,null,N(b),A(b),b.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...m].sort((b,S)=>S.tokens-b.tokens).map(b=>e("div",{className:"cm-mstats-row",key:"t:"+b.label},e("span",{className:"cm-mstats-name",title:b.label},b.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:p(g>0?b.input/g:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:p(g>0?(b.cacheRead+b.cacheWrite)/g:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:p(g>0?(b.output+b.reasoning)/g:0)}})),e("span",{className:"cm-mstats-val"},H(b.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...m].sort((b,S)=>(S.hitRate??-1)-(b.hitRate??-1)).map(b=>e(q,{key:"h:"+b.label},w(b.label,b.hitRate??0,"hit",b.cacheUnreported?a("modelStatsHitUnreported"):b.hitRate===null?"—":(b.hitRate*100).toFixed(1)+"%",b.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...m].sort((b,S)=>(S.perUsd??-1)-(b.perUsd??-1)).map(b=>e(q,{key:"v:"+b.label},w(b.label,k>0?(b.perUsd??0)/k:0,"value",b.perUsd===null?"—":H(b.perUsd)+" tok/$"+(b.blended!==null?" · "+a("modelStatsBlended",{price:"$"+b.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function xs(t,s){return t==="fiveHour"?s==="en"?"5-hour":"5 小时":t==="weekly"?s==="en"?"This week":"本周":t==="monthly"?s==="en"?"This month":"本月":t==="daily"?s==="en"?"Today":"当日":t}function vs(t,s){if(t==="go")return"OpenCode Go";const o=Re.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const Da=["fiveHour","weekly","monthly","daily"];function Ns(t,s){const o=new Map,a=n=>{const i=new Date(n),l=r=>String(r).padStart(2,"0");if(s==="monthly")return i.getFullYear()+"-"+l(i.getMonth()+1);if(s==="weekly"){const r=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(i.getDay()+6)%7);return r.getFullYear()+"-"+l(r.getMonth()+1)+"-"+l(r.getDate())}return i.getFullYear()+"-"+l(i.getMonth()+1)+"-"+l(i.getDate())};for(const n of Object.values(t??{}))for(const i of n??[]){if(i===null||typeof i!="object"||!(i.tokens>0)&&!(i.cost>0))continue;const l=a(Number(i.t1)||Number(i.t0)),r=o.get(l)??{key:l,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(i.tokens)||0,r.cost+=Number(i.cost)||0,r.pct+=Number(i.pct)||0,r.intervals+=1,o.set(l,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,i)=>n.key<i.key?-1:n.key>i.key?1:0)}function Ss(t){const{state:s,config:o,t:a}=t,[n,i]=L(!1),[l,r]=L("daily"),u=_(o?.locale),d=s?.planStats,c=d!=null&&typeof d.providers=="object"?d.providers:{},m=Object.keys(c).sort(),p=y=>V(Number(y)||0,o??s?.config),f=y=>y.method==="none"||y.per1Tokens===null?"—":H(y.per1Tokens)+" tok · "+p(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":H(y.fullTokens)+" tok · "+p(y.fullCost),k=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),v=y=>{let P=k(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(P=a("planStatsMethodSampleAt",{method:P,time:new Date(Number(y.sampleAt)).toLocaleString(u==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(P+=" · "+a("planStatsConfidenceLow")),P},N=([y,P,T])=>e("tr",{key:P+":"+y},e("td",null,xs(y,u)),e("td",{className:"num"},Math.round(T.percent*10)/10+"%"),e("td",{className:"num"},H(T.localTokens)+" tok · "+p(T.localCost)),e("td",{className:"num"},f(T)),e("td",{className:"num"},g(T)),e("td",{className:"num cm-plan-reset"},T.resetsAt.length>0?a("planStatsResets",{time:new Date(T.resetsAt).toLocaleString(u==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},v(T))),A=n?m.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,P])=>({winKey:y,list:P})):[],w=Ns(Object.fromEntries(A.map(y=>[y.winKey,y.list])),l),b=w.reduce((y,P)=>Math.max(y,P.fullTokens??0),0),S=(y,P)=>e("button",{key:y,className:"cm-mstats-tab"+(l===y?" active":""),onClick:()=>r(y)},P);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,()=>i(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},m.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(q,null,m.map(y=>{const P=c[y]?.windows??{},T=[...Da.filter(B=>P[B]!==void 0).map(B=>[B,y,P[B]]),...Object.keys(P).filter(B=>!Da.includes(B)).map(B=>[B,y,P[B]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},vs(y,a),e("span",{className:"cm-plan-updated"},(()=>{const B=Number(c[y]?.generatedAt)||Number(d?.generatedAt)||0;return B>0?new Date(B).toLocaleTimeString(u==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,T.map(N))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},S("daily",a("planStatsDaily")),S("weekly",a("planStatsWeekly")),S("monthly",a("planStatsMonthly"))),w.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(q,null,[...w].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(b>0?(y.fullTokens??0)/b*100:0).toFixed(1)+"%"}})),e(Z,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":H(y.fullTokens),per1:y.per1Tokens===null?"—":H(y.per1Tokens),tokens:H(y.tokens),cost:p(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":H(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Oa(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:i,t:l}=t,r=m=>{const p={...n.prices.providers??{}},f=p[s]??{};p[s]={...f,models:m},i({...n,prices:{...n.prices,providers:p}})},u=(m,p)=>{if(n===null)return;const f={...(n.prices.providers??{})[s]?.models??{}};f[o]={...f[o]??{},[m]:Math.max(0,p)},r(f)},d=(m,p)=>{if(n===null)return;const f={...(n.prices.providers??{})[s]?.models??{}},g=f[o]??{};f[o]={...g,cny:{...g.cny,[m]:Math.max(0,p)}},r(f)},c=()=>{if(n===null)return;const m={...(n.prices.providers??{})[s]?.models??{}};delete m[o],r(m)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(q,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},l("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:c},l("unmountBtn")))),a?.unpriced===!0?null:e(q,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatInput")),e("span",null,l("flatCached")),e("span",null,l("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ee({value:a?.input??null,emptyMode:"ignore"},m=>u("input",m)),ee({value:a?.cachedInput??null,emptyMode:"ignore"},m=>u("cachedInput",m)),ee({value:a?.output??null,emptyMode:"ignore"},m=>u("output",m))),a?.cny?e("div",{className:"cm-price-row"},e("span",null,"CNY"),ee({value:a.cny.cacheMiss,emptyMode:"ignore"},m=>d("cacheMiss",m)),ee({value:a.cny.cacheHit,emptyMode:"ignore"},m=>d("cacheHit",m)),ee({value:a.cny.output,emptyMode:"ignore"},m=>d("output",m))):null))}const ze=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Ut=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function Cs(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),[u,d]=L(null),c=s.balance,m=s.config,p=s.reconcile,f=(n?.balance??m.balance??{}).reconcile!==!1,g=A=>{n===null||typeof i!="function"||i({...n,balance:{...n.balance??m.balance??{},reconcile:A.target.checked}})},k=async()=>{if(!l){r(!0),d(null);try{const A=await o.refreshBalance();d({kind:A.ok?"ok":"err",text:A.message})}catch(A){d({kind:"err",text:a("balanceRefreshFailed",{message:A?.message??String(A)})})}finally{r(!1)}}},v=A=>xe(A,m,c?.currency),N=c.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:v(c.totalBalance),granted:v(c.grantedBalance),toppedUp:v(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:c.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:k,disabled:l},a(l?"refreshing":"refreshBalance"))),N,p!==void 0&&p.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+p.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:f,onChange:g}),a("reconcileLabel")),Ut(u))}function lt(t){const{name:s,enabled:o,saved:a,busy:n,open:i,statusNode:l,configNode:r,errorMsg:u,onToggle:d,onRefresh:c,onRemove:m,onToggleOpen:p,t:f}=t,g=r!=null;return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":f("enable")+": "+s,checked:o===!0,onChange:k=>d(k.target.checked)})),e("div",{className:"cm-quota-name"},g?Oe(i===!0,p,s):e("h3",{className:"cm-h"},s)),m?e("button",{className:"cm-btn small",onClick:m},f("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:c,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?f("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?f("quotaRefreshReady"):f("refresh")},f(n===!0?"refreshing":"refresh"))),l,g&&i===!0?e("div",{className:"cm-collapse-body"},r):null,u!=null?e("div",{className:"cm-msg "+u.kind},u.text):null)}function it(t,s){const[o,a]=L(!1),[n,i]=L(null),l=we(!1);return[o,n,async()=>{if(!l.current){l.current=!0,a(!0),i(null);try{const u=await s();i({kind:u.ok?"ok":"err",text:u.message})}catch(u){i({kind:"err",text:t("syncFailed",{message:u?.message??String(u)})})}finally{l.current=!1,a(!1)}}}]}const As=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},Ra=(t,s,o,a,n,i=s)=>{if(typeof o?.percent!="number")return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const l=Math.max(0,Math.min(100,Number(o.percent)||0)),r=de(l,a),u=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),u?e("span",{className:"cm-go-reset"},u):null)};function Ps(t){const{state:s,api:o,t:a,entry:n,index:i,canRemove:l,onPatch:r,onRemove:u}=t,d=n.adapter==="aliyun",[c,m]=L(!1),p=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[f,g]=L(p),[k,v]=L(()=>(n.allowedHosts??[]).join(", ")),[N,A]=L({}),w=we(!1),b=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(R=>R.index===i)??null,P=n.enabled===!0,T=()=>{m(R=>!R)};X(()=>{c&&!w.current&&(g(p()),v((n.allowedHosts??[]).join(", ")),A({})),w.current=c},[c]);const B=(R,Y)=>r({[R]:Y}),M=(R,Y)=>r({request:{...n.request??{},[R]:Y}}),E=d?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(R=>typeof R=="string"?[...R.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(Y=>Y[1]):[]))],h=(R,Y)=>{g(x=>({...x,[R]:Y}));try{const x=R==="body",U=x&&!Y.trim()?void 0:JSON.parse(Y);if(!x&&(U===null||typeof U!="object"||Array.isArray(U)))throw new Error("invalid");if(R==="headers"&&Object.values(U).some(Q=>typeof Q!="string"))throw new Error("invalid");A(Q=>({...Q,[R]:""})),R==="extract"?B(R,U):M(R,x?U===void 0?void 0:Y:U)}catch{A(x=>({...x,[R]:a("customBalanceInvalidJson")}))}},I=(R,Y,x,U)=>!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(Y)),U&&e("span",{className:"cm-hint"},a(U)),e("textarea",{className:"cm-input",rows:x,value:f[R],onChange:Q=>h(R,Q.target.value)}),N[R]?e("span",{className:"cm-hint err"},N[R]):null),te=R=>{v(R);const Y=R.split(/[\s,;]+/).map(x=>x.trim()).filter(x=>x.length>0);B("allowedHosts",Y)},[ye,ve,D]=it(a,()=>(b.customBalances??[])[i]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(i)),O=y!==null&&y.status==="ok"?e(q,null,b.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(vt,{segments:xt(s,b,y,n),direction:ae(b,"balance")}),e("div",{className:"cm-bal-line"},St(y,b,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:Qe(y.remaining,b,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),G=e(q,null,e("p",{className:"cm-note"},a(d?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:je(b,y,n)!=="USD",onChange:R=>B("convertToDisplayCurrency",R.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([R,Y])=>e("div",{key:R,className:"cm-field"},e("label",null,a(Y)),e("input",{className:"cm-input",value:n[R]??"",onChange:x=>B(R,x.target.value)}))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:R=>B("unit",R.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:R=>B("display",R.target.value)},...ze(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ee({value:n.refreshMinutes??15},R=>B("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(R)))))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:R=>M("method",R.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:R=>M("url",R.target.value)})),I("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&I("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),E.length>0?e(q,null,!d&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),E.map(R=>e(De,{key:"cb-var-"+R,target:"customVar:"+R,configured:(s.customVarStatus?.[R]?.configured??!1)===!0,source:s.customVarStatus?.[R]?.source??"",t:a,api:o,placeholder:"{{"+R+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:k,placeholder:"api.example.com, relay.example.org",onChange:R=>te(R.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),I("extract","customBalanceExtract",8)));return e(lt,{name:`#${i+1} · `+(Nt(n,_(b?.locale))||a("customBalanceTitle")),enabled:P,saved:JSON.stringify(n)===JSON.stringify(b.customBalances?.[i])?b.customBalances[i]:null,busy:ye,open:c,statusNode:O,configNode:G,errorMsg:ve,onToggle:R=>B("enabled",R),onRefresh:D,onRemove:l?u:null,onToggleOpen:T,t:a})}function La({config:t,draft:s,setDraft:o,t:a,api:n}){const i=s?.goQuota??t.goQuota,l=(r,u)=>{s&&o({...s,goQuota:{...i,[r]:u}})};return e(q,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,u])=>e("div",{key:r,className:"cm-field"},e("label",null,a(u)),e("select",{className:"cm-input",value:i[r],onChange:d=>l(r,d.target.value)},r==="display"?ze(a):["rolling","weekly","monthly"].map((d,c)=>e("option",{key:d,value:d},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ee({value:i.refreshMinutes},r=>l("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function Ms(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),u=s.goQuota,d=s.config,c=n?.goQuota?.enabled??d.goQuota?.enabled??!0,m=(b,S)=>{n!==null&&i({...n,goQuota:{...n.goQuota??d.goQuota,[b]:S}})},[p,f,g]=it(a,()=>o.refreshGoQuota()),k=d.goQuota?.main==="weekly"||d.goQuota?.main==="monthly"?d.goQuota.main:"rolling",v=[k,...["rolling","weekly","monthly"].filter(b=>b!==k)],N=b=>b==="rolling"?"goWindowRolling":b==="weekly"?"goWindowWeekly":"goWindowMonthly",A=b=>b==="rolling"?u.rolling:b==="weekly"?u.weekly:u.monthly,w=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},v.map(b=>Ra(a,a(N(b)),A(b),ae(d,"go"),b===k)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||a("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(lt,{name:a("goQuotaTitle"),enabled:c,saved:d.goQuota,busy:p,open:l,statusNode:w,errorMsg:f,configNode:e(La,{config:d,draft:n,setDraft:i,t:a,api:o}),onToggleOpen:()=>r(b=>!b),onToggle:b=>m("enabled",b),onRefresh:g,t:a})}const Ts=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Bs(t){const{state:s,api:o,t:a,draft:n,setDraft:i,index:l}=t,r=s.config,d=(n??r).gatewayQuotas?.sources??[],c=d[l]??{},p=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(M=>M.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},f=Ts(c,s.customVarStatus),[g,k]=L(!1),[v,N,A]=it(a,()=>o.refreshGatewayQuota(c.id)),w=M=>{n!==null&&i({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:M}})},b=M=>w(d.map((E,h)=>h===l?{...E,...M}:E)),S=(M,E,h)=>e("div",{className:"cm-field"},e("label",null,M),e("input",{className:"cm-input",value:E??"",onChange:h})),y=(M,E)=>{const h=We(M?.label||M?.id||a("gatewaySourceUnknown"),M,ae(r,"plan"),a);return e(q,{key:M?.id||E},h.row,M?.resetsAt?e("div",{className:"cm-note"},_e(M,a)):null)},P=(M,E)=>e("div",{key:M.id||E,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(M.used??"—")+" / "+(M.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(M.remaining??"—")+" remaining")),T=M=>M==null?null:e(q,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(M.used??"—")+" / "+(M.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(M.remaining??"—")+" remaining")),(M.packages??[]).map(P)),B=(M,E)=>e("div",{key:M.id||E,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Vt[M.provider]??M.provider??a("gatewaySourceUnknown"))+" · "+(M.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},M.status)),M.plan?e("div",{className:"cm-note"},M.plan):null,M.windows.length>0?e("div",{className:"cm-go-list"},M.windows.map(y)):null,T(M.credits),M.message?e("div",{className:"cm-note"},M.message):null);return e(lt,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(M=>M.id===c.id),busy:v,open:g,errorMsg:N,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(p.status??a("gatewaySourceUnknown"))+(p.serverVersion?" · "+p.serverVersion:"")+(p.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(p.fetchedAt).toLocaleTimeString()}):"")+(p.message?" · "+p.message:"")),configNode:e(q,null,e("div",{className:"cm-grid"},S(a("gatewaySourceLabel"),c.label,M=>b({label:M.target.value})),S(a("gatewaySourceBaseURL"),c.baseURL,M=>b({baseURL:M.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:M=>b({display:M.target.value})},...ze(a))),S(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),M=>b({allowedHosts:M.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:M=>b({antigravityOnlyGemini:M.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),f?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+f,configured:s.customVarStatus?.[f]?.configured===!0,source:s.customVarStatus?.[f]?.source??"",t:a,api:o,placeholder:f})):null,p.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+p.unsupportedProviders.join(", ")):null,p.accounts.length>0?p.accounts.map(B):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:M=>b({enabled:M}),onRefresh:A,onRemove:()=>w(d.filter((M,E)=>E!==l)),onToggleOpen:()=>k(M=>!M),t:a})}const Re=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function Ds(t){const{state:s,api:o,t:a,draft:n,setDraft:i,planId:l,labelKey:r}=t,u=s.config,d=s.codingPlans??{},c=n?.codingPlans?.[l]??u.codingPlans?.[l]??{},m=d[l]??{status:"off",message:"",fetchedAt:0,windows:{}},p=c.enabled===!0,[f,g]=L(!1),[k,v,N]=it(a,()=>o.refreshCodingPlan(l)),A=(D,O)=>{if(n===null)return;const G=n.codingPlans??u.codingPlans??{};i({...n,codingPlans:{...G,[l]:{...G[l]??{},[D]:O}}})},[w,b]=L(""),[S,y]=L({}),P=D=>D?.rates!==null&&typeof D?.rates=="object"&&!Array.isArray(D.rates)?D.rates:{},T=["input","cachedInput","output"],B=D=>S[D]??P(c)[D]??{},M=D=>T.every(O=>Number.isFinite(Number(D[O]))&&Number(D[O])>0),E=(D,O,G)=>{if(n===null)return;const R={...B(D),[O]:String(G)};y(Q=>({...Q,[D]:R}));const Y=T.every(Q=>String(R[Q]??"").trim()==="");if(!Y&&!M(R))return;const x=n.codingPlans??u.codingPlans??{},U={...(x.qwen??{}).rates??{}};Y?delete U[D]:U[D]=Object.fromEntries(T.map(Q=>[Q,Number(R[Q])])),i({...n,codingPlans:{...x,qwen:{...x.qwen??{},rates:U}}})},h=D=>{n!==null&&y(O=>({...O,[D]:O[D]??P(c)[D]??{}}))},I=D=>{if(n===null)return;y(R=>{const Y={...R};return delete Y[D],Y});const O=n.codingPlans??u.codingPlans??{},G={...(O.qwen??{}).rates??{}};delete G[D],i({...n,codingPlans:{...O,qwen:{...O.qwen??{},rates:G}}})},te=m.windows!==null&&typeof m.windows=="object"?m.windows:{},ye=p===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):m.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(te).length>0?l==="minimax"&&(Fe(te).five!=null||Fe(te).seven!=null)?e(va,{five:Fe(te).five,seven:Fe(te).seven,fetchedAt:m.fetchedAt,t:a,wide:!0,direction:ae(u,"plan")}):Object.entries(te).map(([D,O])=>Ra(a,D.replace(/_/g," "),O,ae(u,"plan"),!1,D)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:m.fetchedAt>0?new Date(m.fetchedAt).toLocaleTimeString():"—"}))):m.status==="error"?e("div",{className:"cm-bal-line err"},m.message||a("unknownError")):m.status==="off"&&m.message?e("p",{className:"cm-note"},m.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),ve=e(q,null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:D=>A("baseUrl",D.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:D=>A("quotaSource",D.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:l==="minimax"?"both":"settings",onChange:D=>A("display",D.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),l!=="scnet"&&(l!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ee({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},D=>{A("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D))))})):null,l==="scnet"||l==="qwen"&&(c.quotaSource??"local")==="local"?e(q,null,e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:l==="qwen"?5e5:24e4,onChange:D=>{const O=Number(D.target.value);Number.isFinite(O)&&O>0&&A("planCredits",Math.floor(O))}})),e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:D=>A("planStart",D.target.value)})),l==="qwen"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(P(c)),...Object.keys(S)])].sort().map(D=>e("div",{key:D,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},D),T.map(O=>e("input",{key:O,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:B(D)[O]??"",placeholder:a("qwenRate_"+O),"aria-label":D+" · "+a("qwenRate_"+O),onChange:G=>{const R=G.target.value;E(D,O,R)}})),e("button",{className:"cm-btn small",onClick:()=>I(D)},a("overrideRemove")),D in S&&!M(B(D))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:w,onChange:D=>b(D.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const D=w.trim();D.length!==0&&(h(D),b(""))},disabled:w.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(q,null,e("div",{className:"cm-field"},e("label",null,l==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+l,configured:m.keyConfigured===!0,source:m.keySource,t:a,api:o,placeholder:l==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(lt,{name:a(r),enabled:p,saved:u.codingPlans?.[l],busy:k,open:f,errorMsg:v,statusNode:ye,configNode:ve,onToggle:D=>A("enabled",D),onRefresh:N,onToggleOpen:()=>g(D=>!D),t:a})}function Os(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,l=s.config,r=n??l,u=r.codingPlans??{},d=r.gatewayQuotas?.sources??[],c=n?.customBalances??l.customBalances??[],m=w=>{n!==null&&i({...n,customBalances:w,...w.length===0?{customBalance:{...l.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},p=we({next:0,keys:[]}).current;for(;p.keys.length<c.length;)p.keys.push(p.next++);p.keys.length=c.length;const f=w=>{p.keys.splice(w,1),m(c.filter((b,S)=>S!==w))},g=(w,b)=>m(c.map((S,y)=>y===w?{...S,...b}:S)),k=(w="custom")=>{c.length>=8||m([...c,{...w==="aliyun"?{adapter:w}:{},enabled:!1,label:w==="aliyun"?"千问 / 阿里云":"",labelEn:w==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:w==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:w==="aliyun"?"https://business.aliyuncs.com/":"",method:w==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},v=()=>{d.length>=4||n===null||i({...n,gatewayQuotas:{...n.gatewayQuotas??l.gatewayQuotas??{},sources:[...d,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:bt,allowedHosts:[],allowInsecureHttp:!1}]}})},N=[...d.map((w,b)=>({kind:"gateway",key:"gw-"+(w.id??b),index:b,enabled:w.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Re.map(w=>({kind:"plan",key:"plan-"+w.id,planId:w.id,labelKey:w.labelKey,enabled:u[w.id]?.enabled===!0})),...c.map((w,b)=>({kind:"custom",key:"cb-"+p.keys[b],index:b,enabled:w.enabled===!0}))],A=w=>w.kind==="plan"?e(Ds,{key:w.key,planId:w.planId,labelKey:w.labelKey,state:s,api:o,t:a,draft:n,setDraft:i}):w.kind==="go"?e(Ms,{key:w.key,state:s,api:o,t:a,draft:n,setDraft:i}):w.kind==="gateway"?e(Bs,{key:w.key,index:w.index,state:s,api:o,t:a,draft:n,setDraft:i}):e(Ps,{key:w.key,state:s,api:o,t:a,entry:c[w.index],index:w.index,canRemove:!0,onPatch:b=>g(w.index,b),onRemove:()=>f(w.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},As(N).map(A)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:v,disabled:d.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>k(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>k("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const Rs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ea=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function Ht(t){const s=t.useCost?t.useCost(b=>b):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=_(a?.locale),i=t.t??K(n),l=Array.isArray(o.history)?o.history:[];if(l.length===0)return e("div",null,e("h3",{className:"cm-h"},i("usageTitle")),e("p",{className:"cm-empty"},i("usageEmpty")));const r=o.meta?.dayKey??"",u=new Map(l.map(b=>[b.date,b])),d=b=>{const S=y=>String(y).padStart(2,"0");return b.getFullYear()+"-"+S(b.getMonth()+1)+"-"+S(b.getDate())},c=new Date;c.setHours(0,0,0,0);const m=new Date(c);m.setDate(m.getDate()+(6-(c.getDay()+6)%7));const p=26,f=[],g=[];let k=-1;for(let b=p-1;b>=0;b-=1){for(let y=0;y<7;y+=1){const P=new Date(m);P.setDate(P.getDate()-(b*7+(6-y)));const T=u.get(d(P));f.push(T!==void 0?{day:T,tokens:Ea(T)}:{day:{date:d(P)},tokens:0})}const S=new Date(m);S.setDate(S.getDate()-(b*7+6)),g.push(S.getMonth()!==k?n==="en"?Rs[S.getMonth()]:String(S.getMonth()+1)+"月":""),k=S.getMonth()}const v=Math.max(...f.map(b=>b.tokens),1),N=b=>{const S=b/v;return S<.25?1:S<.5?2:S<.75?3:4},A=b=>{const{day:S,tokens:y}=b,P="cm-ug-cell"+(y>0?" l"+N(y):"")+(S.date===r?" today":""),T=i("usageDay",{date:S.date,tokens:H(y),input:H(S.input??0),cache:H((S.cacheRead??0)+(S.cacheWrite??0)),output:H(S.output??0),calls:S.calls??0,cost:V(W(S,a),a)});return e(Z,{key:S.date,label:T,side:"top",delayMs:200},e("div",{className:P}))},w=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},i("usageTitle")),e("div",{className:"cm-ug-total"},i("usageTotal",{tokens:H(Ea(w)),input:H(w.input??0),cache:H((w.cacheRead??0)+(w.cacheWrite??0)),output:H(w.output??0),calls:w.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+p+",1fr)"}},f.map(A)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+p+",1fr)"}},g.map((b,S)=>e("span",{key:"m"+String(S),className:"cm-ug-monthc"},b))))}function Ls(t){const s=t.useCost?t.useCost(x=>x):void 0,o=t.api,a=s?.state??null,[n,i]=L(null),[l,r]=L(null),[u,d]=L(!1),[c,m]=L(!1),[p,f]=L(!1),[g,k]=L(""),[v,N]=L(!1),[A,w]=L(!1),[b,S]=L("overview"),[y,P]=L({status:"idle",at:0,error:null}),T=Ee.useRef(null),B=Ee.useRef(null),M=Ee.useRef(null);X(()=>{if(a!==null){const x=JSON.stringify(a.config);i(U=>{const Q=U!==null&&JSON.stringify(U)!==T.current;return Q||(B.current=a.config,M.current=a.config),Q?U:JSON.parse(x)}),T.current=x}},[a]),X(()=>{n!==null&&M.current===null&&B.current!==null&&(M.current=B.current)},[n]),X(()=>{if(n===null||o===void 0)return;const x=JSON.stringify(n);if(x===T.current)return;P(Q=>Q.status==="saving"?Q:{...Q,status:"saving"});const U=setTimeout(()=>{const Q={},le=M.current??B.current;if(le!==null&&typeof le=="object")for(const C of Object.keys(n))JSON.stringify(n[C])!==JSON.stringify(le[C])&&(Q[C]=n[C]);if(Object.keys(Q).length===0){T.current=x,P({status:"saved",at:Date.now(),error:null});return}o.updateConfig(Q).then(()=>{T.current=x,le!==null&&typeof le=="object"&&(M.current={...le,...Q}),P({status:"saved",at:Date.now(),error:null})},C=>{P({status:"error",at:0,error:C?.message??String(C)})})},600);return()=>{clearTimeout(U)}},[n,o]),X(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:h("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const E=_((n??a?.config)?.locale),h=K(E);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?h("readingLedger"):h("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},h("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},h("refresh")));const I=a.config,te=async()=>{if(!v){N(!0),r(null);try{const x=await o.fetchPrices();if(r({kind:x.ok?"ok":"err",text:x.message}),x.ok&&x.state&&typeof x.state.config=="object"){const U=JSON.stringify(x.state.config);i(JSON.parse(U)),T.current=U}}catch(x){r({kind:"err",text:h("syncFailed",{message:x?.message??String(x)})})}finally{N(!1),d(!1)}}},ye=async()=>{if(!v){N(!0);try{await o.resetHistory(),r({kind:"ok",text:h("historyCleared")})}catch(x){r({kind:"err",text:h("clearFailed",{message:x?.message??String(x)})})}finally{N(!1),m(!1)}}},ve=async()=>{if(!v){N(!0),r(null);try{const x=await o.importLegacyHistory();r({kind:"ok",text:x.message})}catch(x){r({kind:"err",text:h("legacyImportFailed",{message:x?.message??String(x)})})}finally{N(!1),f(!1)}}},D=(x,U)=>{n!==null&&i({...n,[x]:U})},O=()=>{if(n===null)return;const x=g.trim().toLowerCase();if(x.length===0||!/^[a-z0-9_.-]+$/.test(x)||n?.prices.models[x]!==void 0)return;const U={...n.prices.models,[x]:{cacheHit:0,cacheMiss:0,output:0}};i({...n,prices:{...n.prices,models:U}}),k("")},G=n===null?[]:Object.keys(n.prices.models).filter(x=>{const Q=(n?.priceTableDisplay??I.priceTableDisplay??{})["deepseek:"+x];return typeof Q=="boolean"?Q:!0}).map(x=>e(Et,{key:x,modelId:x,entry:n.prices.models[x]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:i,t:h})),R=[["overview",h("tabOverview")],["quotas",h("tabQuotas")],["usage",h("tabUsage")],["pricing",h("tabPricing")],["display",h("tabDisplay")]],Y=y.status==="saving"?e("span",{className:"cm-hint"},h("saving")):y.status==="error"?e("span",{className:"cm-msg err"},h("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?h("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):h("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},R.map(([x,U])=>e("button",{key:x,type:"button",role:"tab","aria-selected":String(b===x),className:"cm-tab"+(b===x?" active":""),onClick:()=>S(x)},U))),Y),Ut(l),b==="overview"?e(q,{key:"overview"},e("div",{className:"cm-cards"},I.hideTodayCost===!0?null:e(ot,{title:h("cardToday"),value:V(W(a.today,I),I),sub:h("callsTokens",{calls:a.today.calls,input:H(a.today.input),cache:H(a.today.cacheRead+a.today.cacheWrite),output:H(a.today.output)})}),e(ot,{title:h("cardMonth"),value:V(W(a.month,I),I),sub:h("callsTokens",{calls:a.month.calls,input:H(a.month.input),cache:H(a.month.cacheRead+a.month.cacheWrite),output:H(a.month.output)})}),e(ot,{title:h("cardTotal"),value:V(W(a.total,I),I),sub:h("cardTotalSub",{calls:a.total.calls})})),e(ds,{state:a,t:h}),e("p",{className:"cm-note",key:"cards-footnote"},h("cardsFootnote")),(()=>{const x=hn(a);return x!==null?e("p",{className:"cm-note",key:"tz-hint"},h("timezoneHint",{host:x.hostLabel,browser:x.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:h("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??I).showTotalWithPlan===!0,onChange:x=>{const U=n??I;U!=null&&i({...U,showTotalWithPlan:x.target.checked})}}),e("span",null,h("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},h("todaySessions")),e(bs,{state:a,t:h})),e(gs,{state:a,draft:n,setDraft:i,t:h}),(I.balance?.display==="settings"||I.balance?.display==="both")&&I.hideOfficialBalance!==!0?e(Cs,{state:a,api:o,t:h,draft:n,setDraft:i}):null):null,b==="quotas"?e(Os,{key:"quotas",state:a,api:o,t:h,draft:n,setDraft:i}):null,b==="usage"?e(q,{key:"usage"},!Ge||(I.usage?.position??"cost")==="cost"?e(Ht,{state:a,t:h,locale:E}):null,e(ws,{state:a,config:n??I,t:h,draft:n,setDraft:i}),e(Ss,{state:a,config:n??I,t:h}),e(us,{state:a,api:o}),e(ps,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},h("historyDataTitle")),e("div",{className:"cm-buttons"},p?e(q,null,e("span",{className:"cm-hint"},h("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:ve,disabled:v},h("apply")),e("button",{className:"cm-btn",onClick:()=>f(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>f(!0),disabled:v},h("importLegacy")),c?e(q,null,e("span",{className:"cm-hint"},h("confirmReset")),e("button",{className:"cm-btn danger",onClick:ye,disabled:v},h("confirmClear")),e("button",{className:"cm-btn",onClick:()=>m(!1)},h("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>m(!0),disabled:v},h("clearAllHistory"))),e("p",{className:"cm-note"},h("legacyImportNote")))):null,b==="display"?e(q,{key:"display"},e(cs,{draft:n,setDraft:i,t:h}),a?.secretMigration?.pending?.length>0?e(kn,{pending:a.secretMigration.pending,t:h}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,h("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:x=>D("locale",x.target.value)},e("option",{value:"auto"},h("localeAuto")),e("option",{value:"zh"},h("localeZh")),e("option",{value:"en"},h("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},h("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},h("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled"].map(x=>e("label",{key:x,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[x]===!0,onChange:U=>D(x,U.target.checked)}),e("span",null,h(x)))),Ge?e("div",{className:"cm-field"},e("label",null,h("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:x=>{n!==null&&i({...n,usage:{...n.usage??{position:"cost"},position:x.target.value}})}},e("option",{value:"cost"},h("usagePositionCost")),e("option",{value:"general"},h("usagePositionGeneral")),e("option",{value:"section"},h("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,h("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:x=>D("position",x.target.value)},e("option",{value:"dock"},h("positionDock")),e("option",{value:"header"},h("positionHeader")),e("option",{value:"off"},h("off")))),e("div",{className:"cm-field"},e("label",null,h("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:x=>D("sidebar",x.target.value==="on")},e("option",{value:"on"},h("sidebarOn")),e("option",{value:"off"},h("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:x=>D("showSessionId",x.target.checked)}),e("span",null,h("showSessionIdLabel"))),e("div",{className:"cm-grid-group"},h("groupMoney")),e("div",{className:"cm-field"},e("label",null,h("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:x=>{const U=fs[x.target.value];U!==void 0&&n!==null&&i({...n,currency:x.target.value,...U})}},e("option",{value:"CNY"},h("currencyCny")),e("option",{value:"USD"},h("currencyUsd")),e("option",{value:"EUR"},h("currencyEur")))),e("div",{className:"cm-field"},e("label",null,h("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:x=>D("symbol",x.target.value)})),e("div",{className:"cm-field"},e("label",null,h("rateLabel")),ee({value:n?.exchangeRate??1,emptyMode:"ignore"},x=>D("exchangeRate",x))),e("div",{className:"cm-field"},e("label",null,h("decimalsLabel")),ee({value:n?.decimals??2},x=>D("decimals",Math.min(10,Math.floor(x))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:x=>D("hideOfficialBalance",x.target.checked)}),e("span",null,h("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:x=>D("hideTodayCost",x.target.checked)}),e("span",null,h("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},h("groupSidebar")),e("div",{className:"cm-field"},e("label",null,h("sidebarTodayMetric")),e("select",{className:"cm-input",value:n?.sidebarTodayMetric??"cost",onChange:x=>D("sidebarTodayMetric",x.target.value)},e("option",{value:"cost"},h("sidebarTodayCost")),e("option",{value:"tokens"},h("sidebarTodayTokens")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:x=>{n&&i({...n,sidebarSimple:x.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,h("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,h("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:x=>D("sidebarStyle",x.target.value)},e("option",{value:"standard"},h("sidebarStyleStandard")),e("option",{value:"compact"},h("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,h("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:x=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:x.target.value}})}},...ze(h))),e("div",{className:"cm-field"},e("label",null,h("refreshIntervalLabel")),ee({value:n?.balance?.refreshMinutes??5},x=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(x)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:x=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:x.target.checked}})}}),e("span",null,h("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,h("balanceBudgetCapLabel")),ee({value:n?.balance?.budgetCap??""},x=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:x>0?x:null}})}),e("span",{className:"cm-hint"},h("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,h("barDirectionsTitle")),["balance","budget","go","plan"].map(x=>e("div",{className:"cm-dir-row",key:x},e("span",{className:"cm-dir-label"},h("barDirection_"+x)),e("select",{className:"cm-input",value:n?.barDirections?.[x]??(x==="balance"?"remaining":"used"),onChange:U=>{if(n===null)return;const Q={balance:"remaining",budget:"used",go:"used",plan:"used"};i({...n,barDirections:{...n.barDirections??Q,[x]:U.target.value}})}},e("option",{value:"remaining"},h("barDirectionRemaining")),e("option",{value:"used"},h("barDirectionUsed"))))),e("span",{className:"cm-hint"},h("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,h("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??I.customBalance?.display??"both",onChange:x=>{n!==null&&i({...n,customBalance:{...n.customBalance??I.customBalance??{},display:x.target.value}})}},...ze(h))),e("div",{className:"cm-field"},e("label",null,h("customBalanceRefreshInterval")),ee({value:n?.customBalance?.refreshMinutes??I.customBalance?.refreshMinutes??15},x=>{n!==null&&i({...n,customBalance:{...n.customBalance??I.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(x)))}})})),e(La,{config:I,draft:n,setDraft:i,t:h,api:o}),e("div",{className:"cm-grid-group"},h("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:x=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:x.target.checked,promptSeen:!0}})}}),e("span",null,h("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([x,U])=>e("label",{key:x,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[x]!==!1,onChange:Q=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip,[x]:Q.target.checked}})}}),e("span",null,h(U)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("quotaStripNote"))),e("div",{className:"cm-grid-group"},h("groupCorner")),e("div",{className:"cm-field"},e("label",null,h("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:x=>{n!==null&&i({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:x.target.checked}})}}),e("span",null,h("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([x,U])=>e("label",{key:x,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[x]!==!1,onChange:Q=>{n!==null&&i({...n,corner:{...n.corner,[x]:Q.target.checked}})}}),e("span",null,h(U)))):null),e("div",{className:"cm-grid-group"},h("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:x=>{n!==null&&i({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:x.target.checked}})}}),e("span",null,h("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:x=>{n!==null&&i({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:x.target.checked}})}}),e("span",null,h("budgetDetailLabel"))))),e("p",{className:"cm-note"},h("badgeNote")))):null,b==="pricing"?e(q,{key:"pricing"},e(hs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,Oe(A,()=>w(!A),h("priceTableTitle")),A?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},h("priceTableNote")),e("p",{className:"cm-hint"},h("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},h("deepseekMountedHeader")),G,e(Et,{key:"__default__",modelId:h("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:i,t:h}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:h("newModelPlaceholder"),value:g,onChange:x=>k(x.target.value)}),e("button",{className:"cm-btn small",onClick:O,disabled:g.trim().length===0},h("addModel"))),(()=>{const x=n?.priceTableDisplay??I.priceTableDisplay??{},U=n?.prices?.providers??{},Q=C=>Object.keys(U[C]?.models??{}).filter(F=>x[C+":"+F]===!0),le=Object.keys(U).filter(C=>Q(C).length>0).sort((C,F)=>C.localeCompare(F));return le.length===0?null:le.map(C=>e("div",{key:C},e("div",{className:"cm-catalog-vendor"},(Ma[C]??C)+" · "+h("mountedSuffix")),Q(C).sort().map(F=>e(Oa,{key:C+":"+F,provider:C,modelId:F,entry:U[C].models[F],draft:n,setDraft:i,t:h}))))})()):null),(()=>{const x=n?.priceOverrides??I.priceOverrides??{},U=n?.priceMatchDismissed??I.priceMatchDismissed??[],Q=n?.prices??I.prices,le=a.today.byProviderModel??{},C={prices:Q,priceMatch:n?.priceMatch??I.priceMatch},F=Object.keys(le).filter(j=>{if(U.includes(j)||x[j]!==void 0)return!1;const z=j.indexOf(":"),ke=(z>0?j.slice(0,z):"deepseek").toLowerCase(),It=z>0?j.slice(z+1):j;return ht(ke,It,C).matched!==!0}),$=[...new Set([...F,...Object.keys(x)])].filter(j=>!U.includes(j)),ne=a.month?.byProviderModel??{},Le=Object.keys(ne).filter(j=>{if(U.includes(j)||x[j]!==void 0)return!1;const z=j.indexOf(":"),ke=(z>0?j.slice(0,z):"deepseek").toLowerCase(),It=z>0?j.slice(z+1):j;return ht(ke,It,C).matched===!0}).sort(),Ne=[{value:"__local__",label:h("overrideTargetLocal")},{value:"deepseek:__default__",label:h("overrideTargetDefault")},...Object.keys(Q.models??{}).map(j=>({value:"deepseek:"+j,label:"DeepSeek · "+j})),...Object.entries(Q.providers??{}).flatMap(([j,z])=>Object.keys(z?.models??{}).map(ke=>({value:j+":"+ke,label:j+" · "+ke})))],pe=(j,z)=>{if(n===null)return;const ke={...n.priceOverrides??{}};z===""?delete ke[j]:ke[j]=z,i({...n,priceOverrides:ke})},Me=j=>{if(n===null)return;const z={...n.priceOverrides??{}};delete z[j],i({...n,priceOverrides:z,priceMatchDismissed:[...new Set([...U,j])]})};return e("div",null,e("h3",{className:"cm-h"},h("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:j=>D("priceMatch",j.target.value)},e("option",{value:"auto"},h("priceMatchAuto")),e("option",{value:"exact"},h("priceMatchExact")))),e("p",{className:"cm-note"},h("priceMatchNote")),$.length>0?e(q,null,e("h3",{className:"cm-h"},h("unmatchedTitle")),e("p",{className:"cm-hint"},h("unmatchedHint")),$.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,qt(j)),e("select",{className:"cm-input",value:x[j]??"",onChange:z=>pe(j,z.target.value)},e("option",{value:""},"—"),Ne.map(z=>e("option",{key:z.value,value:z.value},z.label))),e("button",{className:"cm-btn small",title:h("removePriceMatchHint"),onClick:()=>Me(j)},h("overrideRemove"))))):e("p",{className:"cm-hint"},h("overrideNone")),U.length>0?e("button",{className:"cm-btn small",onClick:()=>D("priceMatchDismissed",[])},h("restorePriceMatches",{count:U.length})):null,Le.length>0?e(q,null,e("h3",{className:"cm-h"},h("matchedTitle")),e("p",{className:"cm-hint"},h("matchedHint")),Le.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,qt(j)),e("select",{className:"cm-input",value:"",onChange:z=>{z.target.value!==""&&pe(j,z.target.value)}},e("option",{value:""},h("matchedKeepAuto")),Ne.map(z=>e("option",{key:z.value,value:z.value},z.label)))))):null)})(),e(ks,{state:a,draft:n,setDraft:i,t:h}),e("div",null,e("h3",{className:"cm-h"},h("dataSync")),(n??I).currency==="CNY"&&(n??I).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},h("pricingCnyHint",{rate:(n??I).exchangeRate}),(n??I).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:v,onClick:()=>D("pricingCurrency","CNY")},h("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,h("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:x=>D("pricingCurrency",x.target.value)},e("option",{value:"USD"},h("pricingCurrencyUsd")),e("option",{value:"CNY"},h("pricingCurrencyCny"))),e("p",{className:"cm-note"},h("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},u?e(q,null,e("span",{className:"cm-hint"},h("confirmFetch")),e("button",{className:"cm-btn",onClick:te,disabled:v},h("apply")),e("button",{className:"cm-btn",onClick:()=>d(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>d(!0),disabled:v},h("syncFromDocs"))),e("p",{className:"cm-note"},h("lastSync",{time:I.fetchedAt!==null?new Date(I.fetchedAt).toLocaleString():h("neverSynced")})+h("source",{source:I.priceSource==="official"?h("sourceOfficial"):h("sourceBundled")})),e("p",{className:"cm-note"},h("syncScopeNote")))):null)}const Es=["remote"];async function qs(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(an);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=yn({status:"loading",error:null,state:null}),i=()=>K(_(n.getSnapshot().state?.config?.locale)),l=async(C,F)=>{const $=await a[C](...F??[]);if($===null||typeof $!="object"||$.ok!==!0)throw new Error($?.error?.message??i()("rpcFailed",{method:C}));return $.value};let r=Date.now(),u=!1,d=!0,c=1;const m=async()=>{if(!d||u)return;u=!0,r=Date.now();const C=n.getSnapshot();C.state===null&&n.set({...C,status:"loading"});try{const F=await l("getState");if(!d)return;c=1,n.set({status:"ready",error:null,state:F})}catch(F){if(!d)return;C.state===null&&(r=Date.now()),c=Math.min(c*2,60),n.set({status:"error",error:F?.message??String(F),state:C.state})}finally{u=!1}};t.effect(()=>t.on("connection/reset",()=>{m()}),"cost-meter: reconnect reload");const p=setInterval(()=>{const C=n.getSnapshot().state,F=C?.config.sidebarModels,$=C?F?.enabled||F?.dock?F.refreshSeconds:60:c;!document.hidden&&Date.now()-r>=($||60)*1e3&&m()},1e3);t.effect(()=>()=>{d=!1,clearInterval(p)},"cost-meter: poll timer");const f=()=>{document.visibilityState==="visible"&&m()};document.addEventListener("visibilitychange",f),t.effect(()=>()=>{document.removeEventListener("visibilitychange",f)},"cost-meter: visibility reload");const g=async(C,F="rpcSyncFailed",$=!1)=>{const ne=await C;if(ne===null||typeof ne!="object"||ne.ok!==!0)throw new Error(ne?.error?.message??($?ne?.value?.message:void 0)??i()(F));return ne.value.state!==void 0&&n.set({status:"ready",error:null,state:ne.value.state}),ne.value},k={reload:m,updateConfig:async C=>{const F=await l("updateConfig",[C]);return n.set({status:"ready",error:null,state:F}),F},fetchPrices:async()=>g(a.fetchPrices()),resetHistory:async()=>{const C=await l("resetHistory");return n.set({status:"ready",error:null,state:C}),C},importLegacyHistory:async()=>{const C=await a.importLegacyHistory();if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??i()("legacyImportFailed",{message:"RPC failed"}));return C.value.state!==void 0&&n.set({status:"ready",error:null,state:C.value.state}),C.value},getDaySessions:async C=>l("getDaySessions",[C]),getSessionCost:async C=>l("getSessionCost",[C]),getTopSessions:async(C,F,$)=>l("getTopSessions",[C,F,$]),refreshBalance:async()=>g(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>g(a.refreshGoQuota()),refreshGatewayQuota:async(C=null)=>g(C==null?a.refreshGatewayQuota():a.refreshGatewayQuota(C)),refreshCustomBalance:async(C=null)=>g(C==null?a.refreshCustomBalance():a.refreshCustomBalance(C)),refreshCodingPlan:async C=>g(a.refreshCodingPlan(C)),setCredential:async(C,F)=>g(a.setCredential(C,F),"rpcSyncFailed",!0),clearCredential:async C=>g(a.clearCredential(C),"rpcSyncFailed",!0)};m();const v=t.get("slots");if(v===void 0)return;const N=()=>({hooks:{cost:n},api:k}),A=()=>({gen:0,dispose:null}),w=(C,F,$,ne,Le=!0)=>{C.dispose!==null&&(C.dispose(),C.dispose=null),C.gen+=1;const Ne=C.gen;Le&&v.inject(F,()=>{if(C.gen!==Ne)return;const pe=typeof $=="function"?$():v.register($,ne);if(C.gen!==Ne){pe();return}return C.dispose=pe,()=>{C.dispose===pe&&(C.dispose=null),pe()}})},b=A(),S=C=>{const F=C==="header"?"conversation.session.header.actions":"conversation.composer.dock";w(b,F,C==="header"?{name:F,id:"cost-meter",order:-5,inject:N}:{name:F,id:"cost-meter",order:5,inject:N},C==="header"?xn:vn,C!=="off")},y=A(),P=C=>{w(y,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:N},is,C)},T=A(),B=C=>{w(T,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:N},Ln,C)};v.inject("conversation.input.dock",()=>v.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:N},ts)),v.inject("sidebar.footer.action",()=>v.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:N},as)),v.inject("sidebar.footer.action",()=>v.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:N},ns)),v.inject("sidebar.footer.action",()=>v.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:N},ls));const M=A(),E=C=>{w(M,"sidebar.footer.action",()=>v.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:N},En),null,C)};window.cmPeakAlertPreview=C=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(At,{detail:{kind:C==="offpeak"?"offpeak":"peak"}}))};const h=A(),I=C=>{w(h,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:C==="en"?Te.en.sectionLabel:Te.zh.sectionLabel,inject:N},Ls,!0)},te=A(),ye=C=>{w(te,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:N},Ht,C)},ve=A(),D=(C,F)=>{w(ve,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:F==="en"?Te.en.usageSectionLabel:Te.zh.usageSectionLabel,inject:N},Ht,C)};let O=null,G=null,R=null,Y=null,x=null,U=null;const Q=()=>{const C=n.getSnapshot().state,F=C?.config?.position??"dock",$=C?.config?.sidebar!==!1&&C?.config?.hideTodayCost!==!0,ne=C?.config?.balance?.display??"both",Le=(ne==="sidebar"||ne==="both")&&C?.config?.hideOfficialBalance!==!0,Ne=$||Le||C?.config?.codexQuotaEnabled===!0||C?.config?.sidebarModels?.enabled===!0,pe=C?.config?.corner?.enabled===!0||C?.config?.sidebarModels?.dock===!0,Me=_(C?.config?.locale),j=C?.config?.usage?.position??"cost";F!==O&&(S(F),O=F),Ne!==G&&(P(Ne),G=Ne),pe!==R&&(B(pe),R=pe);const z=C?.config?.peakEnabled===!0;z!==U&&(E(z),U=z),Me!==Y&&(I(Me),Y=Me),j!==x?(Ge&&(ye(j==="general"),D(j==="section",Me)),x=j):Ge&&j==="section"&&Me!==Y&&D(!0,Me)};Q();const le=n.subscribe(Q);return()=>{le()}}return rt.apply=qs,rt.inject=Es,Qt.exports}});
|