dsh-cost-meter 1.7.13 → 1.7.14

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/lib/client.js CHANGED
@@ -1,3 +1,3 @@
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:ht=>{var yt={exports:{}},Ve=yt.exports;Object.defineProperty(Ve,Symbol.toStringTag,{value:"Module"});const Le=ht("react"),{Tooltip:X}=ht("@deepseek-ai/dsh-client-ui-primitives"),je=!1,aa=["/* dsh-cost-meter: 会话费用徽章与设置页 */",".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{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-foot-rail:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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-corner-chip:hover{background:var(--dsw-alias-interactive-bg-hover)}",".cm-corner-chip.warn{color:var(--dsw-alias-state-warn-primary)}",".cm-corner-chip.over{color:var(--dsw-alias-state-error-primary)}",".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:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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{color:var(--dsw-alias-state-warn-primary)}",".cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}",".cm-qchip.over{color:var(--dsw-alias-state-error-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(0.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:translateX(-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 rgba(0,0,0,.18);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{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:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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:0.88;background:var(--dsw-alias-state-business-primary)}",".cm-btn.danger{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-msg.err{color:var(--dsw-alias-state-error-primary)}",".cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}",".cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1);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 rgba(0,0,0,.22);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{from{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}","@keyframes cm-peak-alert-in-center{from{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-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-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}",".cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}",".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{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3));border-color:transparent}",".cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3));border-color:transparent}",".cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3));border-color:transparent}",".cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary);border-color:transparent}",".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:translateX(-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-strip.peak .cm-peak-chip{color:#ff9800}",".cm-peak-strip.off .cm-peak-chip{color:var(--dsw-alias-state-business-primary)}",".cm-peak-strip.weekend .cm-peak-chip{color:#34a853}",".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:translateX(-50%);transition:left .4s ease;z-index:2;border-radius:2px}",'.cm-peak-classic-marker::after{content:"";position:absolute;top:-7px;left:50%;transform:translateX(-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-classic.peak .cm-peak-classic-chip{color:#ff9800}",".cm-peak-classic.off .cm-peak-classic-chip{color:var(--dsw-alias-state-business-primary)}",".cm-peak-classic.weekend .cm-peak-classic-chip{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.peak .cm-peak-rail-label{color:#ff9800}",".cm-peak-rail.off .cm-peak-rail-label{color:var(--dsw-alias-state-business-primary)}",".cm-peak-rail.weekend .cm-peak-rail-label{color:#34a853}",".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.peak .cm-peak-rail-classic-label{color:#ff9800}",".cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}",".cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}",".cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{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}",".cm-mstats-bar.cost{background:#ff9800;border-radius:999px}",".cm-mstats-bar.hit{background:#34a853;border-radius:999px}",".cm-mstats-bar.value{background:#a142f4;border-radius:999px}",".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{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}",".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{border-radius:0 999px 999px 0}",".cm-bbox-bar.segments.rev .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}",".cm-bbox-bar.segments.rev .cm-bbox-fill:last-child{border-radius:0 999px 999px 0}",".cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}",".cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child{border-radius:0 999px 999px 0}",".cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}",".cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 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-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}",".cm-bal-link{flex:none;display:inline-flex;align-items:center;padding:1px 5px;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{background:var(--dsw-alias-state-warn-primary)}",".cm-bbox.over .cm-bbox-fill{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-rail{color:var(--dsw-alias-state-warn-primary)}",".cm-bbox.over .cm-bbox-rail{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-section.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}",".cm-bbox-section.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}",".cm-bbox-section.warn .cm-bbox-fill{background:var(--dsw-alias-state-warn-primary)}",".cm-bbox-section.over .cm-bbox-fill{background:var(--dsw-alias-state-error-primary)}",".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%,100%{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-row{display:flex;align-items:center;gap:8px;padding:2px 0}",".cm-mm-row .cm-bbox-label{flex:none;width:22px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}",".cm-mm-row .cm-bbox-bar{flex:1;min-width:0;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.warn .cm-bbox-label,.cm-mm-row.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}",".cm-mm-row.over .cm-bbox-label,.cm-mm-row.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}",".cm-mm-row.warn .cm-bbox-fill{background:var(--dsw-alias-state-warn-primary)}",".cm-mm-row.over .cm-bbox-fill{background:var(--dsw-alias-state-error-primary)}",".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-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}",".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}","@media (max-width:640px){.cm-cards{grid-template-columns:1fr}.cm-grid{grid-template-columns:1fr}.cm-budget-controls{grid-template-columns:1fr}}"].join(`
3
- `),kt="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(kt)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=kt,t.textContent=aa,document.head.appendChild(t)}const Ne={zh:{sessionCostTitle:"本会话费用(按每次调用实际时刻精确计费)",sessionDetailTokens:"输入 {input} · 缓存 {cache} · 输出 {output}",sessionDetailCache:"缓存:读 {read} · 写 {write}(写入按命中价计费)",cost:"费用 {amount}",sessionLine:"本会话 {amount} · 输入 {input} · 缓存 {cache} · 输出 {output}",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 余额",customBalanceMultiNote:"支持配置多个自定义提供商(最多 8 条),每条独立的请求与解析规则、独立开关与显示位置、独立刷新间隔;升级前的单条配置已自动迁移为第 1 条。",customBalanceAdd:"添加配置",aliyunBalanceAdd:"添加千问 / 阿里云余额",aliyunBalanceNote:"查询阿里云中国站资金账户可用金,按接口币种显示。使用 RAM AccessKey(需 bss:DescribeBillingAccount 权限),不是千问模型 API Key;共享同一组阿里云凭据。前两项必填,Security Token 仅 STS 临时凭据需要。密钥只存入凭据库。",customBalanceRemove:"删除",customBalanceEmpty:"尚未配置自定义 Provider 余额,点击「添加配置」新建。",customBalanceConfigNote:"配置自定义 Provider 的余额查询请求与解析规则。请求头支持 {{ENV_VAR}} 占位符,从 DSH 凭据库或环境变量解析;extract 规则支持点路径、数字常量与 add / subtract / divide 运算(NewApi 等 quota 端点用 divide 按 500000 换算美元)。",customBalanceLabelZh:"中文名称",customBalanceLabelEn:"英文名称",customBalanceUrl:"请求 URL",customBalanceMethod:"请求方法",customBalanceHeaders:"请求头 (JSON)",customBalanceExtract:"解析规则 (JSON)",customBalanceDisplayLabel:"自定义余额显示位置",customBalanceRefreshInterval:"刷新间隔 (分钟)",customBalanceUnitLabel:"余额币种",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:"启用",customBalanceOpenConfig:"展开配置",customBalanceCollapseConfig:"收起配置",customBalanceLine:"剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}",customBalanceRemaining:"剩余 {amount}",refreshCustomBalance:"刷新自定义余额",customBalanceRefreshFailed:"自定义余额刷新失败:{message}",goQuotaTitle:"OpenCode Go 订阅额度",goQuotaRowLabel:"Go",goWindowRolling:"滚动 5 小时",goWindowWeekly:"本周",goWindowMonthly:"本月",goResetAt:"重置:{time}",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:"未查询额度",enableGoQuota:"启用 OpenCode Go 额度",codingPlansTitle:"Coding Plan 额度",codingPlansNote:"按厂商查询 coding plan 订阅额度(各家独立开关与凭据)。凭据只发送到对应厂商的官方端点;Key 留空时按环境变量与 CLI 登录态自动发现。",codingPlansOpen:"展开 Coding Plan 额度配置",codingPlansCollapse:"折叠 Coding Plan 额度",codingPlansCollapsedHint:"默认收起;展开后可为各家启用、填 Key 并查询额度,展开/收起状态会被记住。",codingPlanAnthropic:"Anthropic(Claude Pro/Max)",codingPlanZai:"Z.ai / 智谱 GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"打开 DeepSeek 充值页(platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) 周额度",enableCodingPlan:"启用额度查询",codingPlanDisplayLabel:"显示位置",codingPlanDisplayNote:"选「主页面侧边栏 / 两者」后,该厂商额度以图框卡片常驻侧边栏(与 Go 额度/余额同款,收起窄栏显示百分比)。",codingPlanKeyLabel:"API Key(可选,留空自动发现)",codingPlanRefreshIntervalLabel:"刷新间隔(分钟)",refreshCodingPlan:"刷新",codingPlanNotQueried:"未查询额度",gatewayQuotaTitle:"CLIProxyAPI 网关额度",gatewayQuotaNote:"只读查询网关 Provider 额度;Management Key 仅写入凭据库。",gatewaySourceAdd:"添加来源",gatewaySourceRemove:"删除来源",gatewaySourceEmpty:"尚未配置网关来源",gatewaySourceEnabled:"启用来源",gatewaySourceLabel:"来源名称",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"显示位置",gatewaySourceAllowlist:"允许的 Host",gatewaySourceCredential:"Management Key(只写)",gatewaySourceStatus:"状态",gatewaySourceUnsupported:"不支持的 Provider",gatewaySourceUnknown:"未知",gatewaySourceNoAccounts:"未发现账号",gatewaySourceRefreshing:"刷新中…",gatewaySourceFetchedAt:"抓取于 {time}",codingPlanDisabledNote:"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。",goQuotaDisabledNote:"未启用额度。开启后将读取 OpenCode Go 订阅额度(滚动 5 小时 / 本周 / 本月)并显示在侧边栏图框、设置页与右下角;没有 Go 订阅时会在这里提示原因。",cornerLabel:"右下角显示(dock)",cornerEnabledLabel:"在右下角显示 OpenCode Go 额度 / 预算",cornerGoRolling:"滚动 5 小时额度",cornerGoWeekly:"本周额度",cornerGoMonthly:"本月额度",cornerBudget:"预算已用%",goShortRolling:"5h",goShortWeekly:"周",goShortMonthly:"月",budgetShort:"预算",ledgerReadFailed:"账本读取失败:{message}",readingLedger:"正在读取账本…",ledgerUnavailable:"账本不可用",syncFailed:"同步失败:{message}",historyCleared:"历史记录已清除。",clearFailed:"清除失败:{message}",peakOff:"峰谷计价已关闭,按基础价格计费",peakNotEffective:"尚未生效(生效时间:{time}),当前按基础价格计费",peakActive:"当前处于峰时段,按峰时价计费",peakNotice:"当前为 DeepSeek 峰时高价时段,按峰时价计费",offPeakActive:"当前处于谷时段,按谷时价计费",weekendAllOffPeak:"周末时段——全谷价(周六及周日全天按谷时价计费)",weekendChip:"周末时段——全谷价",weekendShort:"周末全谷",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:"侧边栏显示",groupCorner:"右下角角标",groupDetail:"图框详细信息",catalogTitle:"拓展价格表",catalogNote:"内置各厂商、按模型家族分类的参考价格目录(只读)。挂载 = 把条目复制进上方可编辑价格表并参与计费;DeepSeek 模型可取消挂载(回退默认价,目录中仍可重新挂载)。",catalogOpen:"展开拓展价格表",catalogCollapse:"收起拓展价格表",mountBtn:"挂载",unmountBtn:"取消挂载",mountedTag:"已挂载",catalogUnpriced:"未核价",catalogDeepseekNote:"DeepSeek 模型支持峰谷两档;取消挂载后按默认价计费且不再被自动匹配命中。",modelStatsTitle:"按模型统计(token 与费用)",modelStatsToday:"今日",modelStatsHistory:"近 90 天",modelStatsCostH:"费用排行",modelStatsTokensH:"Token 消耗",modelStatsHitH:"缓存命中率",modelStatsHitUnreported:"未上报?",modelStatsHitUnreportedTip:"该模型累计多次长上下文调用而缓存命中恒为 0:大概率是中转/代理层剥掉了用量里的缓存字段(或中转请求导致缓存真实未命中),命中率无法统计,且金额按全未命中价计(为上界)。直连官方 API 可恢复准确的缓存命中与更低的金额。",modelStatsValueH:"性价比 · 每美元 token 数",modelStatsInput:"输入",modelStatsCache:"缓存",modelStatsOutput:"输出",modelStatsEmpty:"该时段暂无用量数据。",modelStatsBlended:"综合单价 {price}/M",modelStatsNote:"口径:缓存命中率 = 缓存读 ÷ (缓存读 + 非缓存输入);「未上报?」= 用量疑似未含缓存字段(常见于中转/代理链路),命中率无法统计且金额按全未命中价计(上界);综合单价 = 费用 ÷ 总 token × 1M(USD/M tokens);性价比 = 总 token ÷ 费用,越高越好;费用为账本按每次调用实际时刻计费的美元值。",modelStatsLegacy:"未分模型(早期数据 · 按当时记录计费)",sessionLineSplit:"本会话 {amount}(API)· Plan 等值 {planAmount} · 输入 {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%/满窗取可信采样段差分(短段波动大,标注「精度受限」)。5 小时窗滚动,周/月按本地日历。",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 照常统计、费用按 0 计,历史金额即时归零。写入后该行转入上方手动指定区。",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",qwenPlanCreditsLabel:"月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)",qwenPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",qwenRatesLabel:"Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)",qwenRatesModelPlaceholder:"模型名,如 qwen3.8-max-preview",qwenRatePlaceholder:"费率",qwenRatesAdd:"添加",qwenLocalNote:"千问 Token Plan 无 API 额度查询端点(额度仅控制台可见):按官方 Credits 抵扣率由本地账本估算当前计费周期用量,实际消耗以控制台为准;内置表覆盖的模型自动折算,其余模型不计入,可在上方手动指定抵扣率。",scnetPlanCreditsLabel:"月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)",scnetPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",scnetLocalNote:"SCNet 无 API 额度查询端点:按官方 Credits 抵扣表(2026-08-11 生效)由本地账本估算当前计费周期用量,实际消耗以控制台账单为准;抵扣表覆盖的模型自动折算,其余模型不计入。",volcengineAccessKeyIdLabel:"火山引擎 AccessKey ID",volcengineSecretAccessKeyLabel:"火山引擎 SecretAccessKey",volcengineNote:"火山方舟管控面需 AK/SK 签名(非 ARK_API_KEY Bearer):在火山引擎控制台 IAM 创建子用户并授予 ArkReadOnlyAccess + BillingCenterReadOnlyAccess,填写 AccessKeyID 与 SecretAccessKey;也可在环境变量导出 VOLC_ACCESSKEY / VOLC_SECRETKEY 自动发现(官方 SDK 约定);凭据仅发往 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} 次",cardsFootnote:"口径说明:金额为最近一次落盘快照(2 秒防抖;正常关闭会先强制落盘再退出),与官方实时账单存在分钟级时差属预期;tokens 列为输入+输出+缓存+推理的合计——推理 tokens 由 API 单独上报且不计费(官方账单将其并入「输出」列展示),对账请以金额为准。",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:"会话徽章为按每次调用实际时刻精确计费(含峰谷档位;峰谷时代分界 2026-08-16 16:00 UTC 之前按当时基础价),与账本当日/月度/累计同口径。输入/缓存/输出 token 分开统计,缓存读写按命中价计费。",priceTableTitle:"价格表(美元 / 1M tokens)",pricingCurrencyLabel:"官方价格币种",pricingCurrencyUsd:"美元(英文官方页)",pricingCurrencyCny:"人民币(中文官方页)",pricingCurrencyNote:"决定「从官方文档同步价格」抓取哪个语言的官方页。切换并同步后,历史账目会按新价目整体重算(日志覆盖不全的会话保持原口径),历史与官方账单同基准;重算在后台进行,完成后有提示。",priceTableNote:"「谷时/峰时」为峰谷计价生效后的价格;分界 2026-08-16 16:00 UTC 之前的调用按当时基础价(legacyBase)计费;缓存写入按缓存命中价格计费(与官方规则一致)。无缓存折扣的模型(如 Anthropic/Gemini 等)可只填输入与输出价,命中价自动取未命中价。所有设置修改后自动保存。",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} · Input {input} · Cache {cache} · Output {output}",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:"Budget is disabled. Once enabled, this panel shows the budget limit, the amount used and the used percentage (converted to the display currency); the period can be today / this month / all time / a custom date 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",customBalanceMultiNote:"Configure multiple custom providers (up to 8): each entry has its own request & extract rules, enable switch, display position and refresh interval; your previous single entry was migrated to #1 automatically.",customBalanceAdd:"Add entry",aliyunBalanceAdd:"Add Qianwen / Alibaba Cloud balance",aliyunBalanceNote:"Queries available funds for an Alibaba Cloud China account in the returned currency. Uses shared RAM AccessKey credentials with bss:DescribeBillingAccount permission, not a Qianwen model API key. The first two fields are required; Security Token is only for temporary STS credentials. Secrets stay in the credential store.",customBalanceRemove:"Remove",customBalanceEmpty:'No custom provider balance configured yet — click "Add entry" to create one.',customBalanceConfigNote:"Configure the balance query request and extract rules. Headers support {{ENV_VAR}} placeholders resolved from DSH credentials or environment variables; extract rules accept dot paths, numeric constants, and add / subtract / divide operations (use divide with 500000 for NewApi-style quota endpoints).",customBalanceLabelZh:"Chinese name",customBalanceLabelEn:"English name",customBalanceUrl:"Request URL",customBalanceMethod:"HTTP method",customBalanceHeaders:"Headers (JSON)",customBalanceExtract:"Extract rules (JSON)",customBalanceDisplayLabel:"Custom balance display",customBalanceRefreshInterval:"Refresh interval (minutes)",customBalanceUnitLabel:"Balance currency",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:"Values support {{VAR_NAME}} placeholders resolved from the DSH credential store or env, never written to disk. The name follows <ROUTE>_API_KEY, where <ROUTE> is the Models-page Provider ID uppercased with non-alphanumerics replaced by underscores, e.g. openai→OPENAI_API_KEY, abc23-d→ABC23_D_API_KEY; sharing a name shares the same 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",customBalanceOpenConfig:"Expand config",customBalanceCollapseConfig:"Collapse config",customBalanceLine:"Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}",customBalanceRemaining:"Remaining {amount}",refreshCustomBalance:"Refresh custom balance",customBalanceRefreshFailed:"Custom balance refresh failed: {message}",goQuotaTitle:"OpenCode Go subscription quota",goQuotaRowLabel:"Go",goWindowRolling:"Rolling 5h",goWindowWeekly:"Weekly",goWindowMonthly:"Monthly",goResetAt:"Resets: {time}",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 are still stored in plaintext in the local ledger and could not be migrated automatically. Export the matching environment variables and restart:",budgetDetailLabel:"Budget box details",refreshGoQuota:"Refresh quota",goQuotaNotQueried:"Quota not queried",enableGoQuota:"Enable OpenCode Go quota",codingPlansTitle:"Coding plan quotas",codingPlansNote:"Query coding plan subscription quotas per vendor (independent enable switch and credentials per vendor). Credentials are only sent to the vendor's official endpoint; leave the key empty to auto-detect from environment variables and CLI logins.",codingPlansOpen:"Expand Coding Plan quotas",codingPlansCollapse:"Collapse Coding Plan quotas",codingPlansCollapsedHint:"Collapsed by default; expand to enable providers, enter keys and query quotas. The open/closed state is remembered.",codingPlanAnthropic:"Anthropic (Claude Pro/Max)",codingPlanZai:"Z.ai / Zhipu GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"Open DeepSeek top-up page (platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) weekly quota",enableCodingPlan:"Enable quota queries",codingPlanDisplayLabel:"Display position",codingPlanDisplayNote:`With "Main sidebar / Both" selected, this vendor's quota shows as a card in the sidebar (same box style as the Go quota / balance; the collapsed rail shows percentages).`,codingPlanKeyLabel:"API key (optional; empty = auto-detect)",codingPlanRefreshIntervalLabel:"Refresh interval (minutes)",refreshCodingPlan:"Refresh",codingPlanNotQueried:"Quota not queried",gatewayQuotaTitle:"CLIProxyAPI gateway quotas",gatewayQuotaNote:"Read-only gateway provider quotas; management keys are write-only.",gatewaySourceAdd:"Add source",gatewaySourceRemove:"Remove source",gatewaySourceEmpty:"No gateway source configured",gatewaySourceEnabled:"Enable 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",gatewaySourceRefreshing:"Refreshing…",gatewaySourceFetchedAt:"fetched {time}",codingPlanDisabledNote:"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.",goQuotaDisabledNote:"Quota disabled. Enable it to read the OpenCode Go subscription quota (rolling 5h / weekly / monthly) and show it in the sidebar box, Settings page and bottom-right corner; if you have no Go subscription, the reason will be shown here.",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",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",weekendRuleNote:"From Aug 23, 2026 00:00 (Beijing time), weekends (Saturday & Sunday) are billed entirely at off-peak prices; charges before that still follow the previous rules.",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",groupCorner:"Corner chips",groupDetail:"Box details",catalogTitle:"Extended price catalog",catalogNote:"A built-in, read-only reference catalog grouped by vendor and model family. Mounting copies an entry into the editable price table above so it is used for billing; DeepSeek models can be unmounted (they fall back to the default price and can be re-mounted here).",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)",modelStatsToday:"Today",modelStatsHistory:"Last 90 days",modelStatsCostH:"Cost ranking",modelStatsTokensH:"Token usage",modelStatsHitH:"Cache hit rate",modelStatsHitUnreported:"unreported?",modelStatsHitUnreportedTip:"This model has many long-context calls but zero cache hits: most likely a relay/proxy strips the cache fields from usage (or the relay genuinely breaks the prefix cache). The hit rate cannot be computed and the cost is priced as all-cache-miss (an upper bound). Connecting directly to the official API restores accurate cache hits and lower costs.",modelStatsValueH:"Value · tokens per USD",modelStatsInput:"Input",modelStatsCache:"Cache",modelStatsOutput:"Output",modelStatsEmpty:"No usage data for this period.",modelStatsBlended:"blended {price}/M",modelStatsNote:'Cache hit rate = cache reads ÷ (reads + non-cached input); "unreported?" = usage carries no cache fields (common behind relays), cost priced as all-miss (upper bound); blended = cost ÷ tokens × 1M; value = tokens ÷ cost (higher better). Costs are USD as billed.',billingClassLabel:"Billing class",billingClassPlan:"Plan subscription",modelStatsLegacy:"Unattributed (early data · billed as recorded)",sessionLineSplit:"This session {amount} (API) · Plan equiv. {planAmount} · 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:'Scope: amounts are catalog-price equivalents — plans consume quota, budget counts API only. Estimates cover dsh-made calls only; server "used %" covers the whole account. Per-1%/full-window from trustworthy sample deltas (short segments fluctuate, tagged low-precision). 5h window rolling, week/month local calendar.',catalogDisplayLabel:"Show directly in Cost settings",catalogDisplayHint:"Only decides whether this model's price card appears directly in the Cost settings price table; mounting and billing are unaffected. When hidden, the mounted model stays editable inside the expanded vendor section of this catalog.",priceTableDisplayHint:"Use the per-model “Show directly in Cost settings” toggle in the extended price catalog below to choose which models appear here; DeepSeek models default to direct display, third-party models default to the catalog once mounted.",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 override → strip date/version suffix → prefix → family similarity. Unmatched DeepSeek ids fall back to the default price; other providers stay unpriced.",unmatchedTitle:"Recently seen models without a price hit",unmatchedHint:"No price entry hit under the current match mode (incl. cross-vendor fallback), or fell back to the DeepSeek default. Pick which entry each bills against (saved as a manual override); “Default price” = DeepSeek default. Local-runtime models (lmstudio / ollama / vLLM / …) are zero-cost automatically; assign an entry here to bill them.",overrideTargetDefault:"DeepSeek default price",overrideRemove:"Remove",overrideTargetLocal:"Local model (zero cost)",matchedTitle:"Models matched this month",matchedHint:"These models already auto-matched a price entry. Pick a target to re-map them, or pick “Local model (zero cost)” to mark them as local — tokens are still counted, cost is 0, and their historical amounts are zeroed immediately. Overridden rows move to the manual list above.",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)",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",qwenRatesAdd:"Add",qwenLocalNote:"Qwen Token Plan exposes no API quota endpoint (usage is console-only): the current billing period is estimated from the local ledger using official credits rates; actual consumption is subject to the console. Models covered by the built-in table are converted automatically; others can be assigned a rate above.",scnetPlanCreditsLabel:"Monthly credits quota (Basic 60,000 / Standard 240,000 / Pro 600,000)",scnetPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",scnetLocalNote:"SCNet exposes no API quota endpoint: usage for the current billing period is estimated from the local ledger using the official credits deduction table (effective 2026-08-11); actual consumption is subject to the SCNet console. Only models covered by the table are counted.",volcengineAccessKeyIdLabel:"Volcengine AccessKey ID",volcengineSecretAccessKeyLabel:"Volcengine SecretAccessKey",volcengineNote:"Volcano Ark control-plane requires AK/SK HMAC signature (not ARK_API_KEY Bearer): create an IAM sub-user with ArkReadOnlyAccess + BillingCenterReadOnlyAccess and enter AccessKeyID and SecretAccessKey; or export VOLC_ACCESSKEY / VOLC_SECRETKEY (official SDK env) for auto-discovery; credentials are only sent 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}",cardsFootnote:"Amounts reflect the latest ledger snapshot (2s debounce; clean shutdown flushes first), so minute-level lag vs the live official bill is expected. Token columns sum input+output+cache+reasoning; reasoning tokens are unbilled (the official bill folds them into output) — reconcile by amount.",timezoneHint:"Timezone notice: today/this-month key by the host's timezone {host}, which differs from this browser ({browser}) — calls after your local midnight land on the previous day (not lost). 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 subscription quotas (OpenCode Go / coding plans) as one compact strip above the input box. Enable it now? You can change this 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 the official balance / custom balance / coding-plan box in the sidebar to fetch the latest data immediately — no need to wait for the auto-refresh interval or open Settings. While refreshing the box pulses; on failure the previous value is kept and the reason appears in the hover tooltip.",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:"The session badge is billed exactly at each call's actual time (peak/off-peak tiers; calls before the 2026-08-16 16:00 UTC boundary are billed at the base prices of that era), consistent with the ledger's today/month/all-time figures. Input/cache/output tokens are counted separately; cache reads and writes are billed at the cache-hit price.",priceTableTitle:"Price table (USD / 1M tokens)",pricingCurrencyLabel:"Official price currency",pricingCurrencyUsd:"USD (English official page)",pricingCurrencyCny:"CNY (Chinese official page)",pricingCurrencyNote:'Which language of the official pricing page "Sync" fetches. After re-syncing, history is re-costed on the new table (sessions without full log coverage keep their basis); the recompute runs in the background.',priceTableNote:"Off-peak/peak prices apply after the 2026-08-16 16:00 UTC boundary; earlier calls use the legacy base prices. Cache writes bill at the hit price. Models without a cache discount need only input+output. Auto-saved.",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:'Sync scope: "Sync prices from official docs" only updates DeepSeek official prices (incl. peak/off-peak tiers). Third-party catalog prices (z-ai / Kimi / Qwen / Volcano etc.) change only per plugin release; to adjust, mount them in the extended catalog and edit, or match by model name.',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 is imported automatically once on first launch; this button re-runs it manually (e.g. after copying in old logs). Costs are estimated with the current price catalog; cleaned logs cannot be replayed, and for a session spanning the install moment its pre-install usage is not counted.",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 na(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function H(t){return t==="zh"||t==="en"?t:na()}function G(t){const s=t==="zh"?Ne.zh:Ne.en;return(o,n)=>{let a=s[o]??Ne.en[o]??o;if(n)for(const r of Object.keys(n))a=a.split("{"+r+"}").join(String(n[r]));return a}}const Ue={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustom"};function Y(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function Q(t,s){return(typeof t!="number"||!Number.isFinite(t))&&Y(s,"number"),t}function Ye(t,s){return typeof t!="string"&&Y(s,"string"),t}const He=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function sa(t,s){return typeof t!="boolean"&&Y(s,"boolean"),t}function Ie(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const n of Object.keys(t)){const a=t[n];if(a===null||typeof a!="object"||Array.isArray(a))continue;const r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:0;o[n]={input:r(a.input),output:r(a.output),cacheRead:r(a.cacheRead),cacheWrite:r(a.cacheWrite),reasoning:r(a.reasoning),cost:r(a.cost),apiCost:a.apiCost===void 0?r(a.cost):r(a.apiCost)}}return o}function oa(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object"),{id:Ye(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:"",input:Q(t.input,s+".input"),output:Q(t.output,s+".output"),cacheRead:Q(t.cacheRead,s+".cacheRead"),cacheWrite:Q(t.cacheWrite,s+".cacheWrite"),reasoning:t.reasoning===void 0?0:Q(t.reasoning,s+".reasoning"),calls:Q(t.calls,s+".calls"),cost:Q(t.cost,s+".cost"),apiCost:t.apiCost===void 0?void 0:Q(t.apiCost,s+".apiCost"),byModel:Ie(t.byModel,s+".byModel"),byProviderModel:Ie(t.byProviderModel,s+".byProviderModel")}}function Qe(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object");const o={date:Ye(t.date,s+".date"),input:Q(t.input,s+".input"),output:Q(t.output,s+".output"),cacheRead:Q(t.cacheRead,s+".cacheRead"),cacheWrite:Q(t.cacheWrite,s+".cacheWrite"),reasoning:t.reasoning===void 0?0:Q(t.reasoning,s+".reasoning"),calls:Q(t.calls,s+".calls"),cost:Q(t.cost,s+".cost"),apiCost:t.apiCost===void 0?void 0:Q(t.apiCost,s+".apiCost"),byModel:Ie(t.byModel,s+".byModel"),byProviderModel:Ie(t.byProviderModel,s+".byProviderModel"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||Y(s+".sessions","array"),o.sessions=t.sessions.map((n,a)=>oa(n,s+".sessions["+a+"]"))),o}function wt(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object");const o={cacheHit:Q(t.cacheHit,s+".cacheHit"),cacheMiss:Q(t.cacheMiss,s+".cacheMiss"),output:Q(t.output,s+".output")};return t.offPeak!==void 0&&(o.offPeak={cacheHit:Q(t.offPeak.cacheHit,s+".offPeak.cacheHit"),cacheMiss:Q(t.offPeak.cacheMiss,s+".offPeak.cacheMiss"),output:Q(t.offPeak.output,s+".offPeak.output")}),t.peak!==void 0&&(o.peak={cacheHit:Q(t.peak.cacheHit,s+".peak.cacheHit"),cacheMiss:Q(t.peak.cacheMiss,s+".peak.cacheMiss"),output:Q(t.peak.output,s+".peak.output")}),t.legacyBase!==void 0&&(o.legacyBase={cacheHit:Q(t.legacyBase.cacheHit,s+".legacyBase.cacheHit"),cacheMiss:Q(t.legacyBase.cacheMiss,s+".legacyBase.cacheMiss"),output:Q(t.legacyBase.output,s+".legacyBase.output")}),t.legacy!==void 0&&(o.legacy=sa(t.legacy,s+".legacy")),o}function la(t,s){const o=a=>a==null?void 0:{...a.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:a.enabled===!0,label:typeof a.label=="string"?a.label:"",labelEn:typeof a.labelEn=="string"?a.labelEn:"",display:He(a.display,["sidebar","settings","off"],"both"),unit:a.unit==="CNY"||a.unit==="EUR"?a.unit:"USD",refreshMinutes:typeof a.refreshMinutes=="number"&&Number.isFinite(a.refreshMinutes)?a.refreshMinutes:15,request:a.request&&typeof a.request=="object"?a.request:{url:""},extract:a.extract&&typeof a.extract=="object"?a.extract:{},allowedHosts:Array.isArray(a?.allowedHosts)?a.allowedHosts.filter(r=>typeof r=="string"):[]};(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object");const n={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const a of Object.keys(t.prices.models))n[a]=wt(t.prices.models[a],s+".prices.models."+a);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,pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:Q(t.decimals,s+".decimals"),exchangeRate:Q(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((a,r)=>({start:Q(a.start,s+".peakWindows["+r+"].start"),end:Q(a.end,s+".peakWindows["+r+"].end")})):[],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 a={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[r,l]of Object.entries(t.priceOverrides))typeof r=="string"&&typeof l=="string"&&(a[r]=l);return a})(),priceTableDisplay:(()=>{const a={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[r,l]of Object.entries(t.priceTableDisplay))typeof r=="string"&&(a[r]=l===!0);return a})(),codingPlans:(()=>{const a={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const r of Object.keys(t.codingPlans)){const l=t.codingPlans[r];l===null||typeof l!="object"||Array.isArray(l)||(a[r]={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:"",...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 a})(),prices:{models:n,default:wt(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:Q(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:Ye(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:He(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:He(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 a=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(a)?a.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:He(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(i=>typeof i=="string").map(i=>i.toLowerCase()).filter(i=>$e.includes(i)))]:$e,allowedHosts:Array.isArray(l.allowedHosts)?l.allowedHosts.filter(i=>typeof i=="string").slice(0,16):[],allowInsecureHttp:l.allowInsecureHttp===!0,keyVar:typeof l.keyVar=="string"?l.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(r=>r!==null&&typeof r=="object").slice(0,8).map(o).filter(Boolean);const a=o(t.customBalance);return a?[a]:[]})(),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 a=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},r=(l,i)=>a[l]==="remaining"||a[l]==="used"?a[l]:i;return{balance:r("balance","remaining"),budget:r("budget","used"),go:r("go","used"),plan:r("plan","used")}})(),planBilling:{providers:(()=>{const a={};if(t.planBilling?.providers!==null&&typeof t.planBilling?.providers=="object"&&!Array.isArray(t.planBilling.providers))for(const[r,l]of Object.entries(t.planBilling.providers))typeof r=="string"&&(l==="auto"||l==="plan"||l==="api")&&(a[r]=l);return a})(),models:(()=>{const a={};if(t.planBilling?.models!==null&&typeof t.planBilling?.models=="object"&&!Array.isArray(t.planBilling.models))for(const[r,l]of Object.entries(t.planBilling.models))typeof r=="string"&&r.length>0&&(l==="plan"||l==="api")&&(a[r]=l);return a})()}}}const ge=t=>typeof t=="number"&&Number.isFinite(t)?t:null,ee=t=>ge(t)??0,ra={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},ia={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},vt=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function ca(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object"),{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,currency:typeof t.currency=="string"?t.currency:"",totalBalance:ee(t.totalBalance),grantedBalance:ee(t.grantedBalance),toppedUpBalance:ee(t.toppedUpBalance)}}function Je(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&Y(s,"object"),{percent:ee(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function ua(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object"),{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,rolling:t.rolling===void 0||t.rolling===null?null:Je(t.rolling,s+".rolling"),weekly:t.weekly===void 0||t.weekly===null?null:Je(t.weekly,s+".weekly"),monthly:t.monthly===void 0||t.monthly===null?null:Je(t.monthly,s+".monthly")}}function xt(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object"),{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,label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:ee(t.remaining),maxBudget:ge(t.maxBudget),spend:ge(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const da=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),ma=new Set(["off","loading","ok","partial","stale","error"]),$e=["antigravity","claude","codex","kimi","xai","workbuddy"],Nt={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function pa(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object");const o=(l,i="")=>typeof l=="string"?l:i,n=l=>ge(l),a=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{id:o(l.id),label:o(l.label),...n(l.percent)===null?{}:{percent:n(l.percent)},resetsAt:o(l.resetsAt),periodHours:n(l.periodHours),scope:o(l.scope)}:null,r=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{unit:o(l.unit,"credits"),used:n(l.used),remaining:n(l.remaining),limit:n(l.limit),fetchedAt:o(l.fetchedAt),packages:Array.isArray(l.packages)?l.packages.filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).map(i=>({id:o(i.id),label:o(i.label),used:n(i.used),remaining:n(i.remaining),limit:n(i.limit),startsAt:o(i.startsAt),resetsAt:o(i.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:ma.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:n(t.fetchedAt)??0,attemptedAt:n(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:da.has(l.status)?l.status:"unknown",message:o(l.message),plan:o(l.plan),windows:Array.isArray(l.windows)?l.windows.map(a).filter(Boolean):[],credits:r(l.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(l=>typeof l=="string").slice(0,32):[]}}function fa(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,n]of Object.entries(t.providers)){if(n===null||typeof n!="object"||Array.isArray(n))continue;const a={},r={};if(n.windows!==null&&typeof n.windows=="object"&&!Array.isArray(n.windows))for(const[l,i]of Object.entries(n.windows))i===null||typeof i!="object"||Array.isArray(i)||(a[l]={percent:ee(i.percent),resetsAt:typeof i.resetsAt=="string"?i.resetsAt:"",localTokens:ee(i.localTokens),localCost:ee(i.localCost),method:i.method==="sample"||i.method==="live"?i.method:"none",sampleAt:ge(i.sampleAt),confidence:i.confidence==="high"||i.confidence==="low"?i.confidence:null,per1Tokens:ge(i.per1Tokens),per1Cost:ge(i.per1Cost),fullTokens:ge(i.fullTokens),fullCost:ge(i.fullCost),sampleCount:ee(i.sampleCount)});if(n.intervals!==null&&typeof n.intervals=="object"&&!Array.isArray(n.intervals))for(const[l,i]of Object.entries(n.intervals))Array.isArray(i)&&(r[l]=i.filter(d=>d!==null&&typeof d=="object"&&!Array.isArray(d)).map(d=>({t0:ee(d.t0),t1:ee(d.t1),tokens:ee(d.tokens),cost:ee(d.cost),pct:ee(d.pct),per1Tokens:ee(d.per1Tokens),per1Cost:ee(d.per1Cost)})));s[o]={windows:a,intervals:r}}return{generatedAt:ee(t.generatedAt),providers:s}}function St(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object"),{today:Qe(t.today,s+".today"),month:Qe(t.month,s+".month"),total:Qe(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?ra:ca(t.balance,s+".balance"),goQuota:t.goQuota==null?ia:ua(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?vt():xt(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,n)=>xt(o,s+".customBalances["+n+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,n)=>pa(o,s+".gatewayQuotas["+n+"]")):[],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,n])=>[o,{configured:n.configured===!0,source:typeof n.source=="string"?n.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:fa(t.planStats),history:Array.isArray(t.history)?t.history.map((o,n)=>Qe(o,s+".history["+n+"]")):[],config:la(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){(t===null||typeof t!="object"||Array.isArray(t))&&Y(s,"object");const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=St(t.state,s+".state")),o}function le(t){return{parse:t}}const Ze=le(St),ba=le(t=>((t===null||typeof t!="object"||Array.isArray(t))&&Y("patch","object"),t)),be=le(ga),ha=le(t=>(typeof t!="string"&&Y("provider","string"),t)),ya=le(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&Y("index","0-7 integer"),t}),ka=le(t=>(typeof t!="string"&&Y("date","string"),t)),wa=le(t=>((t===null||typeof t!="object"||Array.isArray(t))&&Y("day","object"),t)),va=le(t=>(Number.isFinite(Number(t))||Y("limit","number"),Number(t))),Ct=le(t=>(typeof t!="string"&&Y("sort","string"),t)),xa=le(t=>((t===null||typeof t!="object"||Array.isArray(t))&&Y("topSessions","object"),t)),At=le(t=>(typeof t!="string"&&Y("target","string"),t)),Na=le(t=>(typeof t!="string"&&Y("value","string"),t)),Sa={package:"dsh-cost-meter",descriptors:[{id:"dsh-cost-meter#costMeter/getState",service:"costMeter",namespace:"costMeter",method:"getState",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#CostState",schema:Ze}},{id:"dsh-cost-meter#costMeter/updateConfig",service:"costMeter",namespace:"costMeter",method:"updateConfig",invocation:{kind:"direct"},parameters:[{name:"patch",wire:"patch",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#ConfigPatch",schema:ba}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#CostState",schema:Ze}},{id:"dsh-cost-meter#costMeter/fetchPrices",service:"costMeter",namespace:"costMeter",method:"fetchPrices",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/refreshBalance",service:"costMeter",namespace:"costMeter",method:"refreshBalance",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/refreshGoQuota",service:"costMeter",namespace:"costMeter",method:"refreshGoQuota",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/refreshCustomBalance",service:"costMeter",namespace:"costMeter",method:"refreshCustomBalance",invocation:{kind:"direct"},parameters:[{name:"index",wire:"index",source:"json",acceptsUndefined:!0,codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CustomBalanceIndex",schema:ya}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/refreshCodingPlan",service:"costMeter",namespace:"costMeter",method:"refreshCodingPlan",invocation:{kind:"direct"},parameters:[{name:"provider",wire:"provider",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CodingPlanProvider",schema:ha}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/refreshGatewayQuota",service:"costMeter",namespace:"costMeter",method:"refreshGatewayQuota",invocation:{kind:"direct"},parameters:[{name:"sourceId",wire:"sourceId",source:"json",acceptsUndefined:!0,codec:{mode:"strict",typeSymbol:"dsh-cost-meter#GatewayQuotaSourceId",schema:le(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&Y("sourceId","gateway source id"),t})}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/resetHistory",service:"costMeter",namespace:"costMeter",method:"resetHistory",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#CostState",schema:Ze}},{id:"dsh-cost-meter#costMeter/importLegacyHistory",service:"costMeter",namespace:"costMeter",method:"importLegacyHistory",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/getDaySessions",service:"costMeter",namespace:"costMeter",method:"getDaySessions",invocation:{kind:"direct"},parameters:[{name:"date",wire:"date",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#DayKey",schema:ka}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#DayRecord",schema:wa}},{id:"dsh-cost-meter#costMeter/getTopSessions",service:"costMeter",namespace:"costMeter",method:"getTopSessions",invocation:{kind:"direct"},parameters:[{name:"limit",wire:"limit",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#SessionLimit",schema:va}},{name:"sort",wire:"sort",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#SessionSort",schema:Ct},acceptsUndefined:!0},{name:"dir",wire:"dir",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#SessionSortDir",schema:Ct},acceptsUndefined:!0}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#TopSessions",schema:xa}},{id:"dsh-cost-meter#costMeter/setCredential",service:"costMeter",namespace:"costMeter",method:"setCredential",invocation:{kind:"direct"},parameters:[{name:"target",wire:"target",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CredentialTarget",schema:At}},{name:"value",wire:"value",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CredentialValue",schema:Na}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}},{id:"dsh-cost-meter#costMeter/clearCredential",service:"costMeter",namespace:"costMeter",method:"clearCredential",invocation:{kind:"direct"},parameters:[{name:"target",wire:"target",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CredentialTarget",schema:At}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:be}}]};function Ca(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 Pt(t){if(t===null||typeof t!="object")return;const s=l=>{const i=t[l];return typeof i=="number"&&Number.isFinite(i)&&i>=0?i:void 0},o=s("cacheMiss")??s("input")??0,a={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},r=s("reasoning");return r!==void 0&&(a.reasoning=r),a}function Aa(t){const s=Pt(t);if(s===void 0)return null;for(const o of["offPeak","peak","legacyBase"]){const n=Pt(t[o]);n!==void 0&&(s[o]=n)}return s}const Mt=Date.parse("2026-08-22T16:00:00Z");function qe(t){if(!Number.isFinite(t)||t<Mt)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const n=o===6?s:s-1;return{start:Math.max(n*864e5-8*36e5,Mt),end:(n+2)*864e5-8*36e5}}function Tt(t,s,o){if(!Array.isArray(o)||o.length===0||qe(t)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(a=>{const r=Number(a.start),l=Number(a.end);return!Number.isFinite(r)||!Number.isFinite(l)?!1:r<l?n>=r&&n<l:n>=r||n<l})}const Pa=Date.parse("2026-08-16T16:00:00Z");function Bt(t,s,o){const n=t??{cacheHit:0,cacheMiss:0,output:0},a=l=>({cacheHit:l.cacheHit,cacheMiss:l.cacheMiss,output:l.output,reasoning:l.reasoning??0});if(Number.isFinite(s)&&s<Pa){const l=n.legacyBase;return a(l===void 0?n:l)}if(o?.enabled!==!0)return a(n);const r=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(Tt(s,r,o.windows)){const l=n.peak;return a(l===void 0?n:l)}if(r!==void 0&&s>=r){const l=n.offPeak;return a(l===void 0?n:l)}return a(n)}function Lt(t,s){const o=Math.max(0,Number(t.input)||0),n=Math.max(0,Number(t.output)||0),a=Math.max(0,Number(t.cacheRead)||0),r=Math.max(0,Number(t.cacheWrite)||0),l=Math.max(0,Number(t.reasoning)||0);return(o*s.cacheMiss+n*s.output+(a+r)*s.cacheHit+l*(s.reasoning??0))/1e6}function Rt(t,s,o){const n=Number(t);if(!Number.isFinite(n)||n<0||n===0)return 0;if(s!=="CNY")return n;const a=Number(o);return!Number.isFinite(a)||a<=0?n:n/a}function te(t,s){const o=t?.barDirections,n=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return n;const a=o[s];return a==="remaining"||a==="used"?a:n}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))),n=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:n,label:n}}function re(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",n=Number(s?.decimals),a=Math.max(0,Math.min(10,Number.isFinite(n)?Math.floor(n):2));let r=a;t>0&&t<Math.pow(10,-a)&&(r=a+2);const l=t.toFixed(r),i=l.includes(".")?l.replace(/0+$/,"").replace(/\.$/,""):l;return o+i}function J(t,s){const o=Number(s?.exchangeRate),n=t*(Number.isFinite(o)&&o>0?o:1);return re(n,s)}function j(t){const s=Math.max(0,Number(t)||0),o=n=>n>=100?String(Math.round(n)):String(Math.round(n*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 ie(t){return String(t??"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/([^)]*)/g," ").replace(/[^a-z0-9]+/g,"")}function Ae(t,s){if(typeof t!="string"||t.length===0)return null;const o=Array.isArray(s)?s.filter(N=>typeof N=="string"&&N.length>0):[];if(o.length===0)return null;const n=N=>String(N).toLowerCase().replace(/[-@]\d{4}-?\d{2}-?\d{2}$/,"").replace(/[-@]v\d+(\.\d+)*$/,""),a=o.find(N=>N===t);if(a!==void 0)return a;const r=ie(t);if(r.length===0)return null;const l=o.find(N=>ie(N)===r);if(l!==void 0)return l;let i=null,d=0;for(const N of o){const P=ie(N);if(!(P.length<4||P===r)&&r.includes(P)&&P.length>d){const M=r.indexOf(P);if(/^\d{1,2}$/.test(r.slice(M+P.length)))continue;i=N,d=P.length}}if(i!==null)return i;const h=n(t),c=o.find(N=>n(N)===h);if(c!==void 0)return c;let b=null;for(const N of o){const P=n(N);if(P.length===0||P===h)continue;const M=h.slice(P.length);if(h.startsWith(P)&&/^[-_./:]/.test(M)){if(/^\d{1,2}$/.test(M.replace(/^[-_./:]+/,"")))continue;(b===null||n(b).length<P.length)&&(b=N)}}if(b!==null)return b;const w=N=>n(N).split(/[-_./:]+/).filter(Boolean),y=w(t);if(y.length<2)return null;let f=null,A=0;for(const N of o){const P=w(N);let M=0;for(;M<y.length&&M<P.length&&y[M]===P[M];)M+=1;M<y.length&&M<P.length&&/^\d+$/.test(y[M])&&/^\d+$/.test(P[M])||M>=2&&M===P.length&&M<y.length&&y.slice(M).every(g=>/^\d{1,2}$/.test(g))||M>=2&&M<y.length&&M<P.length&&(/^\d{1,2}$/.test(y[M])&&/^[a-z]/.test(P[M])||/^\d{1,2}$/.test(P[M])&&/^[a-z]/.test(y[M]))||M>=2&&(M>A||M===A&&f!==null&&N.length<f.length)&&(f=N,A=M)}return f}const Ma=new Set(["lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),Ta=["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 Ba(t,s){if(typeof t=="string"&&Ma.has(t))return!0;const o=typeof s=="string"?s.toLowerCase():"";return Ta.some(n=>o.startsWith(n))}function Xe(t,s,o){const n=o?.prices??{},a=o?.priceMatch==="exact"?"exact":"auto",r=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 i=l,d=s;const h=r[l+":"+s];if(h==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof h=="string"&&h.length>0){const w=h.indexOf(":");if(w>0&&h.slice(w+1).length>0?(i=h.slice(0,w).trim().toLowerCase(),d=h.slice(w+1)):d=h,i==="deepseek"&&d==="__default__")return{entry:n.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}if(Ba(i,d))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(i==="deepseek"||i.includes("deepseek")){const w=n.models??{},y=w[d]!==void 0?d:a==="auto"?Ae(d,Object.keys(w)):null;if(y!==null)return{entry:w[y],priced:!0,billingMode:"deepseek-peak",matched:!0};if(a==="auto"){let f=null,A=-1,N="flat";for(const[P,M]of Object.entries(n.providers??{})){const g=M?.models??{},v=Ae(d,Object.keys(g));if(v===null||g[v]?.unpriced===!0)continue;const p=(v===d||ie(v)===ie(d)?1e3:0)+ie(v).length;p>A&&(f=g[v],A=p,N=g[v]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(f!==null)return{entry:f,priced:!0,billingMode:N,matched:!0}}return{entry:n.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}const c=n.providers?.[i]?.models??{},b=c[d]!==void 0?d:a==="auto"?Ae(d,Object.keys(c)):null;if(b!==null)return{entry:c[b],priced:c[b]?.unpriced!==!0,billingMode:"flat",matched:!0};if(a==="auto"){const w=n.models??{},y=Ae(d,Object.keys(w));if(y!==null)return{entry:w[y],priced:!0,billingMode:"deepseek-peak",matched:!0};let f=null,A=-1,N="flat";for(const[P,M]of Object.entries(n.providers??{})){if(P===i)continue;const g=M?.models??{},v=Ae(d,Object.keys(g));if(v===null||g[v]?.unpriced===!0)continue;const p=(v===d||ie(v)===ie(d)?1e3:0)+ie(v).length;p>A&&(f=g[v],A=p,N=g[v]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(f!==null)return{entry:f,priced:!0,billingMode:N,matched:!0}}if(l!=="deepseek"&&!l.includes("deepseek")&&typeof h=="string"&&h.length>0&&!h.includes(":")){const w=n.models??{},y=w[h]!==void 0?h:a==="auto"?Ae(h,Object.keys(w)):null;if(y!==null)return{entry:w[y],priced:!0,billingMode:"deepseek-peak",matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function La(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,n=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&n===0}function Ot(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:tt(t,s).total}function Ra(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:Ra(t)}const Oa={go:["go","zen","opencode","opencode-go"]},Dt=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","go"];function Da(t){const s=String(t??"").trim().toLowerCase();if(s.length===0)return null;for(const[o,n]of Object.entries(Oa))if(n.includes(s))return o;return Dt.includes(s)?s:null}function Ea(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const n of Dt)n!=="go"&&o[n]?.enabled===!0&&s.add(n);return t?.goQuota?.enabled===!0&&s.add("go"),s}function ja(t,s,o){const n=String(t??"").trim().toLowerCase();if(n.length>0&&n!=="deepseek"&&!n.includes("deepseek"))return!1;const a=ie(s);if(a.length===0)return!1;const r=o?.prices,l=r?.models??{};for(const i of Object.keys(l))if(ie(i)===a)return!1;for(const i of Object.values(r?.providers??{}))for(const d of Object.keys(i?.models??{}))if(ie(d)===a)return!0;return!1}function et(t,s,o){let n=Da(t);if(n===null&&ja(t,s,o)&&(n="go"),n===null)return"api";const a=o?.planBilling?.models;if(a!==null&&typeof a=="object"){const l=a[t+":"+s];if(l==="plan"||l==="api")return l;const i=a[n+":"+s];if(i==="plan"||i==="api")return i}const r=o?.planBilling?.providers?.[n];return r==="plan"||r==="api"?r:Ea(o).has(n)?"plan":"api"}function tt(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows},n=Date.now(),a=t.byProviderModel??t.byModel??{};let r=0,l=0;for(const b of Object.keys(a)){const w=b.indexOf(":"),y=w>0?b.slice(0,w):"deepseek",f=w>0?b.slice(w+1):b,A=Xe(y,f,s);if(A.priced){const N=Lt(a[b],Bt(Aa(A.entry),n,{...o,enabled:A.billingMode==="deepseek-peak"&&o.enabled})),P=Rt(N,A.billingMode==="deepseek-peak"&&s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);r+=P,et(y,f,s)==="api"&&(l+=P)}}const i={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const b of Object.keys(a))i.input+=a[b].input??0,i.output+=a[b].output??0,i.cacheRead+=a[b].cacheRead??0,i.cacheWrite+=a[b].cacheWrite??0,i.reasoning+=a[b].reasoning??0;const d={input:Math.max(0,(t.input??0)-i.input),output:Math.max(0,(t.output??0)-i.output),cacheRead:Math.max(0,(t.cacheRead??0)-i.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-i.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-i.reasoning)},h=Lt(d,Bt(Ca("default",s.prices),n,o)),c=Rt(h,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return r+=c,l+=c,{total:r,api:l}}function Et(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const n of Object.keys(o)){const a=n.indexOf(":"),r=a>0?n.slice(0,a):"deepseek",l=a>0?n.slice(a+1):n;if(et(r,l,s)==="plan")return!0}return!1}function jt(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function at(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),n=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(n>0?":"+String(n).padStart(2,"0"):"")}function Ua(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const n=-new Date().getTimezoneOffset();if(n===o)return null;const a=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:a?a+" ("+at(o)+")":at(o),browserLabel:at(n)}}function Ha(t){let s=t;const o=new Set;return{getSnapshot:()=>s,subscribe:n=>(o.add(n),()=>{o.delete(n)}),set:n=>{if(n!==s){s=n;for(const a of[...o])a()}}}}const{createElement:e,Fragment:D,useState:O,useEffect:se,useRef:Pe}=Le;function Me({target:t,configured:s,source:o,t:n,api:a,placeholder:r,disabled:l}){const[i,d]=O(""),[h,c]=O(!1),[b,w]=O(null),y=l===!0||h,f=async()=>{const N=i.trim();if(!(N.length===0||y)){c(!0),w(null);try{const P=await a.setCredential(t,N);d(""),w({kind:"ok",text:P?.message??n("credentialSave")})}catch(P){w({kind:"err",text:String(P?.message??P)})}finally{c(!1)}}},A=async()=>{if(!y){c(!0),w(null);try{const N=await a.clearCredential(t);d(""),w({kind:"ok",text:N?.message??n("credentialClear")})}catch(N){w({kind:"err",text:String(N?.message??N)})}finally{c(!1)}}};return e("div",{className:"cm-field"},e("input",{className:"cm-input",type:"password",value:i,placeholder:typeof r=="string"?r:"",disabled:y,autoComplete:"off",onChange:N=>d(N.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:f,disabled:y||i.trim().length===0},n(h?"credentialSaving":"credentialSave")),s===!0?e("button",{className:"cm-btn small",onClick:A,disabled:y},n("credentialClear")):null),e("span",{className:"cm-hint"},s===!0?n("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):n("credentialNotConfigured")),e("span",{className:"cm-hint"},n("credentialInputHint")),Ee(b))}function Ia({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 nt({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 st(t,s){const o=Pe(!1),n=Pe(""),a=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(r=>String(r??0)).join("|"):"";se(()=>{if(!o.current){o.current=!0,n.current=a;return}if(a===""||a===n.current)return;n.current=a;const r=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(r)},[a])}function Qa(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?t.useCost(h=>h):void 0;st(t,s);const n=o?.state?.config;if(!s||!n||jt(s)+(s?.output??0)===0)return null;const a=G(H(n.locale));let r=0,l=Ot(s,n);if(n.showTotalWithPlan!==!0&&Et(s,n)){const h=tt(s,n);r=Math.max(0,h.total-h.api),r>0&&(l=h.api)}const i=jt(s),d=[a("sessionCostTitle"),a("sessionDetailTokens",{input:j(s?.input??0),cache:j((s?.cacheRead??0)+(s?.cacheWrite??0)),output:j(s?.output??0)}),a("sessionDetailCache",{read:j(s?.cacheRead??0),write:j(s?.cacheWrite??0)}),a("cost",{amount:J(l,n)}),...r>0?[a("sessionDetailPlan",{amount:J(r,n)})]:[]].join("; ");return e(X,{label:d,side:"top",delayMs:500},e("div",{className:"cm-chip"},r>0?a("costChipPlan",{amount:J(l,n)}):a("cost",{amount:J(l,n)})))}function qa(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?t.useCost(c=>c):void 0;st(t,s);const n=o?.state?.config;if(!s||!n)return null;const a=s.input??0,r=(s.cacheRead??0)+(s.cacheWrite??0),l=s.output??0;if(a+r+l===0)return null;const i=G(H(n.locale));let d=0,h=Ot(s,n);if(n.showTotalWithPlan!==!0&&Et(s,n)){const c=tt(s,n);d=Math.max(0,c.total-c.api),d>0&&(h=c.api)}return e("div",{className:"cm-root"},d>0?i("sessionLineSplit",{amount:J(h,n),planAmount:J(d,n),input:j(a),cache:j(r),output:j(l)}):i("sessionLine",{amount:J(h,n),input:j(a),cache:j(r),output:j(l)}))}const Fa={USD:"$",CNY:"¥",EUR:"€"};function he(t,s,o){const n=typeof o=="string"?o.toUpperCase():"",a=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return re(t,{symbol:Fa[n]??a,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function Ut(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const n=Number(s?.maxBudget);return Number.isFinite(n)&&n>0?n:null}function Wa(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 n=0;for(const[a,r]of Object.entries(o)){const l=a.indexOf(":");let i=l>=0?a.slice(0,l):a;i.startsWith("llm-")&&(i=i.slice(4)),!(i!=="deepseek"&&i!=="deepseek-official")&&(n+=Number(r?.cost)||0)}return n}function Ht(t,s,o,n,a=null){const r=o==="official"?Wa(t):Number(t.today?.cost)||0;if(o==="custom"){if(Ft(s,n,a)==="USD")return r;const d=Number(s?.exchangeRate);return r*(Number.isFinite(d)&&d>0?d:1)}const l=Number(s?.exchangeRate);return r*(Number.isFinite(l)&&l>0?l:1)}function It({remaining:t,spend:s,todayUsed:o,cap:n}){if(n===null||n<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const a=Math.max(0,Number(t)||0),r=Math.max(0,Number(s)||0),l=Math.max(0,Math.min(r,Number(o)||0)),i=Math.max(0,r-l),d=Math.max(0,Math.min(100,a/n*100)),h=Math.max(0,Math.min(100-d,l/n*100)),c=Math.max(0,Math.min(100-d-h,i/n*100));return{remainingPct:d,todayPct:h,spentPct:c,hasCap:!0,pastSpend:i,today:l}}function ot(t,s,o=null,n=null){const a=o??t.customBalance,r=Ut(s,a),l=Number(a?.remaining)||0,i=Number(a?.spend)||0,d=Ht(t,s,"custom",a,n);return{cap:r,...It({remaining:l,spend:i,todayUsed:d,cap:r})}}function _a(t,s){const o=t.balance,n=Ut(s,null),a=Number(o?.totalBalance)||0,r=Ht(t,s,"official",null),l=n!==null?Math.max(0,n-a):0;return{cap:n,...It({remaining:a,spend:l,todayUsed:r,cap:n})}}function lt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:n,todayPct:a,spentPct:r}=s,l=[];n>0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:n+"%"}})),a>0&&l.push(e("div",{className:"cm-bbox-seg-today",style:{width:a+"%"}})),r>0&&l.push(e("div",{className:"cm-bbox-seg-spent",style:{width:r+"%"}})),l.length===0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const i=o==="used"?[...l].reverse():l;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...i)}function Qt(t,s,o,n,a){const r=[t("balanceBarRemaining",{amount:n})];return o.today>0&&r.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&r.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),a!==null&&a>0&&r.push(t("balanceBudgetCapLabel")+": "+s(a)),r.join(" · ")}function ke(t){const[s,o]=O(!1),[n,a]=O(null);return{busy:s,err:n,run:()=>{s||typeof t!="function"||(o(!0),a(null),Promise.resolve().then(t).catch(l=>{a(l?.message??String(l))}).finally(()=>{o(!1)}))}}}const ce=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function de(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const za="https://platform.deepseek.com/usage";function qt(t){return e("a",{className:"cm-bal-link",href:za,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},"↗")}function Ga(t){const{state:s,wide:o,api:n}=t,a=s.balance,r=G(H(s.config?.locale)),l=ke(n?()=>n.refreshBalance():null);if(!a||a.status==="off")return null;if(a.status==="error")return e(X,{label:[r("balanceQueryFailed",{message:a.message||r("unknownError")}),...de(r,l)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(l.busy?" busy":""),...ce(l.busy,l.run)},o?e(D,null,r("balance")," ",e("span",{className:"cm-num"},r("queryFailed"))):"⚠"));const i=[r("balanceTitle"),r("totalBalance",{amount:he(a.totalBalance,s.config,a.currency)}),r("grantedToppedUp",{granted:he(a.grantedBalance,s.config,a.currency),toppedUp:he(a.toppedUpBalance,s.config,a.currency)}),r("updatedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...de(r,l)].join("; ");return e(X,{label:i,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(l.busy?" busy":""),...ce(l.busy,l.run)},o?e(D,null,r("balance")," ",e("span",{className:"cm-num"},he(a.totalBalance,s.config,a.currency))," ",qt(r),s.reconcile?.ok===!1?" ⚠":""):e(nt,{size:16})))}function Ka(t){const{state:s,wide:o,api:n}=t,a=s.config,r=s.balance,l=G(H(a?.locale)),i=ke(n?()=>n.refreshBalance():null);if(!r||r.status!=="ok")return null;const d=_a(s,a),h=he(r.totalBalance,a,r.currency),c=y=>he(y,a,r.currency),b=[l("balanceTitle"),Qt(l,c,d,h,d.cap),l("grantedToppedUp",{granted:he(r.grantedBalance,a,r.currency),toppedUp:he(r.toppedUpBalance,a,r.currency)}),l("updatedAt",{time:r.fetchedAt>0?new Date(r.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...de(l,i)].join("; "),w=e(D,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},l("balance")),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},h),qt(l)),e(lt,{segments:d,direction:te(a,"balance")}));return e(X,{label:b,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(i.busy?" busy":""),...ce(i.busy,i.run)},o?w:e("div",{className:"cm-bbox-rail cm-num"},Math.round(d.remainingPct)+"%")))}function Fe(t,s){const o=typeof t?.label=="string"?t.label:"",n=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?n||o||"Custom balance":o||n||"自定义余额"}function Ft(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const n=o?.unit??t?.customBalance?.unit;return n==="CNY"||n==="EUR"||n==="USD"?n:s?.unit==="CNY"||s?.unit==="EUR"?s.unit:"USD"}function we(t,s,o,n){const a=Ft(s,o,n),r=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4))),l=a==="CNY"?"¥":a==="EUR"?"€":"$",i=Number(t);if(!Number.isFinite(i))return"—";let d=i.toFixed(r);return d.includes(".")&&(d=d.replace(/0+$/,"").replace(/\.$/,"")),l+d}function rt(t,s,o,n,a=null){const r=we(t.remaining,s,t,a),l=w=>we(w,s,t,a);if(n&&s.balance?.showProgressBar===!0){const w=ot(n,s,t,a);return[Qt(o,l,w,r,w.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const i=t.spend!==null?we(t.spend,s,t,a):"—",d=t.maxBudget!==null?we(t.maxBudget,s,t,a):"—",h=Number(s?.balance?.budgetCap),c=Number.isFinite(h)&&h>0?o("balanceBudgetCapLabel")+": "+we(h,s,t,a):"",b=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:r,spend:i,maxBudget:d,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:r});return c?b+" · "+c:b}function Va(t,s,o,n,a){const r=Fe(a??s.customBalance??{},H(s?.locale)),l=we(n.remaining,s,n,a),i=ot(t,s,n,a);return{level:"ok",rail:Math.round(i.remainingPct)+"%",body:e(D,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},r),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},l)),e(lt,{segments:i,direction:te(s,"balance")}))}}function it(t,s){const o=s?.customBalances??[],n=Array.isArray(t?.customBalances)?t.customBalances:[],a=[];return o.forEach((r,l)=>{if(r?.enabled!==!0||r.display!=="sidebar"&&r.display!=="both")return;const i=n.find(d=>d.index===l)??(n.length===1&&o.length===1?n[0]:null);a.push({index:l,entry:r,snapshot:i})}),a.length===0&&n.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&a.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),a}function Ya(t){const{state:s,wide:o,api:n}=t,a=s.config,r=G(H(a?.locale)),l=it(s,a);return l.length===0?null:e(D,null,l.map(({index:i,entry:d,snapshot:h})=>e(Ja,{key:"cb-"+i,state:s,wide:o,api:n,t:r,index:i,entry:d,snapshot:h})))}function Ja(t){const{state:s,wide:o,api:n,t:a,index:r,entry:l,snapshot:i}=t,d=s.config;if(i==null||i.status!=="ok")return null;const h=ke(n?()=>n.refreshCustomBalance(r):null),c=Va(s,d,a,i,l),b=[rt(i,d,a,s,l),...de(a,h)].join(" · ");return e(X,{label:b,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(h.busy?" busy":""),...ce(h.busy,h.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function $a(t){const{state:s,wide:o,api:n}=t,a=s.config,r=G(H(a?.locale)),l=it(s,a);return l.length===0?null:e(D,null,l.map(({index:i,entry:d,snapshot:h})=>e(Za,{key:"cbr-"+i,state:s,wide:o,api:n,t:r,index:i,entry:d,snapshot:h})))}function Za(t){const{state:s,wide:o,api:n,t:a,index:r,entry:l,snapshot:i}=t,d=s.config,h=i??vt(r);if(h.status==="off")return null;const c=ke(n?()=>n.refreshCustomBalance(r):null),b=Fe(l??d.customBalance??{},H(d?.locale));if(h.status==="error")return e(X,{label:[h.message||a("unknownError"),...de(a,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...ce(c.busy,c.run)},o?e(D,null,b," ",e("span",{className:"cm-num"},a("queryFailed"))):"⚠"));const w=we(h.remaining,d,h,l),y=[rt(h,d,a,s,l),...de(a,c)].join(" · ");return e(X,{label:y,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...ce(c.busy,c.run)},o?e(D,null,b," ",e("span",{className:"cm-num"},w)):e(nt,{size:16})))}function Xa(t){const o=(t.useCost?t.useCost(f=>f):void 0)?.state;if(!o)return null;const n=o.config,a=G(H(n?.locale)),r=n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},l=o.goQuota,i=n?.goQuota?.enabled!==!1&&l?.status==="ok",d=f=>f!==null&&typeof f?.percent=="number"?Math.round(Math.max(0,Math.min(100,f.percent))):null,h=[],c=(f,A,N,P)=>{if(!f||!i)return;const M=d(A);if(M===null)return;const g=typeof A.resetsAt=="string"&&A.resetsAt.length>0?a("goResetAt",{time:new Date(A.resetsAt).toLocaleString()}):"";h.push({key:N,text:a(N)+" "+M+"%",tip:a(P)+": "+M+"%"+(g?" · "+g:""),level:M>=100?"over":M>=80?"warn":"ok"})},b=n?.goQuota?.main==="weekly"||n?.goQuota?.main==="monthly"?n.goQuota.main:"rolling",w=[b,...["rolling","weekly","monthly"].filter(f=>f!==b)],y=f=>f==="rolling"?["goRolling",l?.rolling,"goShortRolling","cornerGoRolling"]:f==="weekly"?["goWeekly",l?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",l?.monthly,"goShortMonthly","cornerGoMonthly"];for(const f of w){const[A,N,P,M]=y(f);c(r[A]===!0,N,P,M)}if(r.budget===!0){const f=n.budget??{enabled:!1,amount:100,period:"month"};if(f.enabled===!0){const A=Number(n.exchangeRate),P=(o.budgetUsed??(f.period==="day"?_(o.today,n):f.period==="all"?_(o.total,n):_(o.month,n)))*(Number.isFinite(A)&&A>0?A:1),M=Math.max(0,Number(f.amount)||0),g=M>0?Math.min(999,P/M*100):null;if(g!==null){const v=g>=100?"over":g>=80?"warn":"ok";h.push({key:"budget",text:a("budgetShort")+" "+g.toFixed(1)+"%",tip:a("budgetOf",{period:a(Ue[f.period]??"periodMonth")})+" · "+a("usedOf",{used:re(P,n),amount:re(M,n)}),level:v})}}}return h.length===0?null:e("div",{className:"cm-corner"},h.map(f=>e(X,{key:f.key,label:f.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(f.level==="ok"?"":" "+f.level)},f.text))))}function We(t,s){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const o=(d,h)=>{const c=new Date(t);return c.setUTCDate(c.getUTCDate()+d),c.setUTCHours(h,0,0,0),c.getTime()},n=[];for(let d=-4;d<=4;d+=1)for(const h of s){const c=Number(h?.start),b=Number(h?.end);if(!Number.isFinite(c)||!Number.isFinite(b))continue;const w={at:o(d,c),intoPeak:!0},y={at:o(b<=c?d+1:d,b),intoPeak:!1};qe(w.at)===null&&n.push(w),qe(y.at)===null&&n.push(y)}let a=null,r=null;for(const d of n)d.at<=t&&(a===null||d.at>a.at)&&(a=d),d.at>t&&(r===null||d.at<r.at)&&(r=d);const l=qe(t);return l!==null?r===null?null:{inPeak:!1,weekend:!0,prevAtMs:l.start,nextAtMs:r.at,nextIntoPeak:r.intoPeak}:a===null||r===null?null:{inPeak:Tt(t,void 0,s),weekend:!1,prevAtMs:a.at,nextAtMs:r.at,nextIntoPeak:r.intoPeak}}function _e(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 n=Array.isArray(t.peakWindows)?t.peakWindows:[];return We(s,n)}function ze(t){return t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function me(t,s,o){const n=Math.max(0,t.nextAtMs-s),a=Math.max(1,Math.ceil(n/6e4)),r=Math.floor(a/60),l=a%60;return r>0?l>0?o("countdownHourMinute",{h:r,m:l}):o("countdownHoursOnly",{h:r}):o("countdownMinute",{m:a})}const ct="cm-peak-alert-preview";let Wt=0;function en(t){const s=t.useCost?t.useCost(A=>A):void 0,o=s?.state?.config,[n,a]=O(Date.now()),[r,l]=O(null),[i,d]=O(null);if(se(()=>{const A=window.setInterval(()=>a(Date.now()),1e4);return()=>window.clearInterval(A)},[]),se(()=>{const A=N=>{const P=N.detail?.kind==="offpeak"?"offpeak":"peak";d(P);const M=s?.state?.config;if(M?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const g=G(H(M.locale));try{new Notification(g(P==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+g("peakAlertPreviewTag"),{body:g("peakAlertBody",{time:g("countdownMinute",{m:2}),phase:g(P==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(ct,A),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(ct,A),window.__cmPeakAlertLive=!1}},[]),se(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const A=We(n,Array.isArray(o.peakWindows)?o.peakWindows:[]);if(A===null)return;const N=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",P=A.nextIntoPeak===!0;if(N!=="both"&&N!==(P?"peak":"offpeak"))return;const M=Number(o.peakAlertAhead),g=(Number.isFinite(M)&&M>=1?M:2)*6e4;if(n<A.nextAtMs-g||n>=A.nextAtMs||Wt===A.nextAtMs)return;const v=G(H(o.locale));Wt=A.nextAtMs;try{new Notification(v(P?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:v("peakAlertBody",{time:me(A,n,v),phase:v(P?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[n]),!o||o.peakEnabled!==!0)return null;let h=null;if(o.peakAlertEnabled===!0){const A=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(A)&&n<A)){const N=We(n,Array.isArray(o.peakWindows)?o.peakWindows:[]);if(N!==null){const P=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",M=Number(o.peakAlertAhead),g=(Number.isFinite(M)&&M>=1?M:2)*6e4;(P==="both"||P===(N.nextIntoPeak?"peak":"offpeak"))&&n>=N.nextAtMs-g&&n<N.nextAtMs&&r!==N.nextAtMs&&(h=N)}}}let c=null,b=!1,w=null;if(h!==null)c=h,b=h.nextIntoPeak===!0,w=()=>l(h.nextAtMs);else if(i!==null)c={nextAtMs:n+2*6e4,nextIntoPeak:i==="peak"},b=i==="peak",w=()=>d(null);else return null;const y=G(H(o.locale)),f=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+f+" "+(b?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},y(b?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},y(b?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},y("peakAlertBody",{time:me(c,n,y),phase:y(b?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:w},y("peakAlertBtn"))))}function tn(t){const{config:s,t:o}=t,[n,a]=O(Date.now());se(()=>{const d=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const r=_e(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:me(r,n,o)}):o("nextOffPeakIn",{time:me(r,n,o)});return e(X,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(r.weekend?"weekend":r.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:r.weekend?"50%":r.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(l.chip)+" · "+i)))}function an(t){const{config:s,t:o}=t,[n,a]=O(Date.now());se(()=>{const d=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const r=_e(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:me(r,n,o)}):o("nextOffPeakIn",{time:me(r,n,o)});return e(X,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(r.weekend?"weekend":r.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:r.weekend?"50%":r.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)+" · "+i)))}function ut(t,s,o){return e(s?.peakStyle==="classic"?an:tn,{config:s,t:o})}function nn(t){const{config:s,t:o}=t,[n,a]=O(Date.now());se(()=>{const h=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(h)},[]);const r=_e(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:me(r,n,o)}):o("nextOffPeakIn",{time:me(r,n,o)}),d=[o(l.notice),i];return e(X,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(r.weekend?"weekend":r.inPeak?"peak":"off"),"aria-label":d.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:r.weekend?"50%":r.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(l.short))))}function sn(t){const{config:s,t:o}=t,[n,a]=O(Date.now());se(()=>{const h=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(h)},[]);const r=_e(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:me(r,n,o)}):o("nextOffPeakIn",{time:me(r,n,o)}),d=[o(l.notice),i];return e(X,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(r.weekend?"weekend":r.inPeak?"peak":"off"),"aria-label":d.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:r.weekend?"50%":r.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(l.short))))}function on(t,s,o){return e(s?.peakStyle==="classic"?sn:nn,{config:s,t:o})}function _t(t,s,o){const n=t.today,a=s.budget??{enabled:!1,amount:100,period:"month"},r=Number(s.exchangeRate),i=(t.budgetUsed??(a.period==="day"?_(t.today,s):a.period==="all"?_(t.total,s):_(t.month,s)))*(Number.isFinite(r)&&r>0?r:1),d=Math.max(0,Number(a.amount)||0),h=d>0?Math.min(999,i/d*100):null,c=ue(h===null?null:Math.min(100,h),te(s,"budget")),b=_(n,s)*(Number.isFinite(r)&&r>0?r:1),w=d>0?Math.min(999,b/d*100):null,y=a.detail!==!1;return{level:h===null?"ok":h>=100?"over":h>=80?"warn":"ok",rail:c.label===null?"—":Math.round(c.label)+"%",body:e(D,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+"%"}})),y?e(D,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},o("todayShare",{amount:J(_(n,s),s),pct:w===null?"—":w.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:re(i,s),amount:re(d,s)}))):null,ut(t,s,o))}}function zt(t,s,o){const n=t.goQuota,a=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",r=n[a],l=r!==null&&typeof r?.percent=="number"?Math.max(0,Math.min(100,Number(r.percent)||0)):0,i=y=>y!==null&&typeof y?.percent=="number"?Math.round(Math.max(0,Math.min(100,y.percent)))+"%":"—",d=y=>o(y==="rolling"?"goShortRolling":y==="weekly"?"goShortWeekly":"goShortMonthly"),h=["rolling","weekly","monthly"].filter(y=>y!==a),c=r!==null&&typeof r?.resetsAt=="string"&&r.resetsAt.length>0?o("goResetAt",{time:new Date(r.resetsAt).toLocaleString()}):"",b=s?.goQuota?.detail!==!1,w=ue(l,te(s,"go"));return{level:l>=100?"over":l>=80?"warn":"ok",rail:w.label===null?"—":Math.round(w.label)+"%",body:e(D,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+d(a)),e("span",{className:"cm-bbox-pct cm-num"},w.label===null?"—":Math.round(w.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:w.width+"%"}})),b?e(D,null,e("div",{className:"cm-bbox-line cm-num"},h.map(y=>d(y)+" "+i(n[y])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function ln(t){const{state:s,wide:o}=t,n=s.goQuota,a=G(H(s.config?.locale));if(!n||n.status!=="ok")return null;const r=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(n[r]===null||typeof n[r]?.percent!="number")return null;const l=zt(s,s.config,a),i=[a("goQuotaTitle"),a("goWindowRolling")+": "+(n.rolling===null?"—":Math.round(n.rolling.percent)+"%"),a("goWindowWeekly")+": "+(n.weekly===null?"—":Math.round(n.weekly.percent)+"%"),a("goWindowMonthly")+": "+(n.monthly===null?"—":Math.round(n.monthly.percent)+"%"+(n.monthly!==null&&typeof n.monthly.resetsAt=="string"&&n.monthly.resetsAt.length>0?" · "+a("goResetAt",{time:new Date(n.monthly.resetsAt).toLocaleString()}):"")),a("goQuotaFetchedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e(X,{label:i,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 rn(t){return t===null||typeof t!="object"||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function Re(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function Ge(t,s){return!t||typeof t.resetsAt!="string"||t.resetsAt.length===0?"":s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})}function Oe(t,s,o){const n=rn(s),a=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",r=ue(n,o);return{level:a,pct:n,label:r.label,row:e("div",{className:"cm-mm-row"+(a==="ok"?"":" "+a)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r.label===null?"—":r.label+"%"))}}function Gt(t){const{five:s,seven:o,fetchedAt:n,t:a,wide:r,refresh:l,direction:i="used"}=t,d=Oe(a("codingPlanRemain5h"),s,i),h=Oe(a("codingPlanRemain7d"),o,i),c=d.level==="over"||h.level==="over"?"over":d.level==="warn"||h.level==="warn"?"warn":"ok",b=(A,N,P)=>{const M=P.pct===null?"—":P.pct+"%",g=Ge(N,a);return A+" "+M+(g?" · "+g:"")},w=[a("codingPlanMinimaxTitle"),b(a("codingPlanRemain5h"),s,d),b(a("codingPlanRemain7d"),o,h),n>0?a("goQuotaFetchedAt",{time:new Date(n).toLocaleTimeString()}):null,...l?de(a,l):[]].filter(Boolean).join("; "),y=e(D,null,e("div",{className:"cm-mm-title"},a("codingPlanMinimaxTitle")),d.row,h.row),f=e(D,null,e("div",{className:"cm-bbox-rail cm-num"},d.pct===null?"—":d.pct+"%"),e("div",{className:"cm-bbox-rail cm-num"},h.pct===null?"—":h.pct+"%"));return e(X,{label:w,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm"+(c==="ok"?"":" "+c)+(r===!1?" rail":"")+(l?" clickable"+(l.busy?" busy":""):""),...l?ce(l.busy,l.run):{}},r===!1?f:y))}function cn(t){const{state:s,wide:o,api:n}=t,a=s.codingPlans?.minimax,r=G(H(s.config?.locale)),l=ke(n?()=>n.refreshCodingPlan("minimax"):null);if(!a||a.status!=="ok")return null;const{five:i,seven:d}=Re(a.windows);return i==null&&d==null?null:e(Gt,{five:i,seven:d,fetchedAt:a.fetchedAt,t:r,wide:o,refresh:l,direction:te(s.config,"plan")})}const un="/plugins/dsh-openai-codex/auth/status",dn=168*3600;function mn(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(i=>i!==null&&typeof i=="object"&&i.id==="codex");if(!o||!Array.isArray(o.windows))return null;const n=o.windows.find(i=>i!==null&&typeof i=="object"&&Number(i.windowSeconds)===dn);if(!n||typeof n.remainingPercent!="number"||!Number.isFinite(Number(n.remainingPercent)))return null;const a=Math.max(0,Math.min(100,Math.round((100-Number(n.remainingPercent))*10)/10)),r=Number(n.resetAt),l=Number.isFinite(r)&&r>0?new Date(r*1e3).toISOString():"";return{weekly:{percent:a,resetsAt:l}}}const $={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},pn=t=>($.listeners.push(t),()=>{$.listeners=$.listeners.filter(s=>s!==t)}),fn=()=>{for(const t of $.listeners)try{t()}catch{}};async function Ke(t=!1){if($.inFlight!==null)return $.inFlight;if(!t&&$.fetchedAt>0&&Date.now()-$.fetchedAt<5*6e4)return;const s=(async()=>{try{const o=await fetch(un,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(o.ok){const a=mn(await o.json().catch(()=>null));a!==null&&(n=a)}$.status=Object.keys(n).length>0?"ok":"unavailable",$.windows=n}catch{$.status="unavailable"}finally{$.fetchedAt=Date.now(),$.inFlight=null,fn()}})();return $.inFlight=s,s}Ke(!1);function gn(){const[t,s]=O(()=>({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt}));return se(()=>{let o=!0;const a=pn(()=>{o&&s({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt})});return Ke(!1),()=>{o=!1,a()}},[]),t}function bn(t){const{state:s,wide:o}=t,n=G(H(s.config?.locale)),a=gn(),r=ke(()=>Ke(!0));if(a.status!=="ok")return null;const l=a.windows.weekly??null;if(l===null)return null;const i=te(s.config,"plan"),d=Oe(n("goShortWeekly"),l,i),h=[n("codexQuotaTitle"),d.label===null?"—":d.label+"%",Ge(l,n),a.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()}):null,...de(n,r)].filter(Boolean).join("; "),c=e(D,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),d.row),b=e("div",{className:"cm-bbox-rail cm-num"},d.label===null?"—":d.label+"%");return e(X,{label:h,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm clickable"+(d.level==="ok"?"":" "+d.level)+(o===!1?" rail":"")+(r.busy?" busy":""),...ce(r.busy,r.run)},o===!1?b:c))}function dt(t,s){return t==="fiveHour"||t==="5h"?"5h":t==="weekly"||t==="week"||t==="7d"?t==="7d"?"7d":s("goShortWeekly"):t==="monthly"||t==="month"?s("goShortMonthly"):String(t).replace(/_/g," ")}function hn(t){const{id:s,state:o,wide:n,api:a}=t,r=o.codingPlans?.[s],l=G(H(o.config?.locale)),i=ke(a?()=>a.refreshCodingPlan(s):null),d=Be.find(g=>g.id===s);if(!d||!r||r.status!=="ok")return null;const h=r.windows!==null&&typeof r.windows=="object"?r.windows:{},c=Object.entries(h);if(c.length===0)return null;const b=g=>g!==null&&typeof g=="object"&&typeof g.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(g.percent)||0))):null,w=te(o.config,"plan"),y=c.map(([g,v])=>{const x=b(v);if(x===null)return e("div",{key:g,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof v?.text=="string"?v.text:"—"));const p=x>=100?"over":x>=80?"warn":"ok",S=ue(x,w);return e("div",{key:g,className:"cm-mm-row wide"+(p==="ok"?"":" "+p)},e("span",{className:"cm-bbox-label"},dt(g,l)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:S.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},S.label===null?"—":S.label+"%"))}),f=c.map(([g,v])=>{const x=b(v),p=typeof v?.resetsAt=="string"&&v.resetsAt.length>0?" · "+l("goResetAt",{time:new Date(v.resetsAt).toLocaleString()}):"",S=x===null?typeof v?.text=="string"?v.text:"—":x+"%";return dt(g,l)+" "+S+p});r.fetchedAt>0&&f.push(l("goQuotaFetchedAt",{time:new Date(r.fetchedAt).toLocaleTimeString()})),f.push(...de(l,i));const A=[l(d.labelKey),...f].join("; "),N=c.map(([,g])=>b(g)).filter(g=>g!==null),P=N.some(g=>g>=100)?"over":N.some(g=>g>=80)?"warn":"ok",M=N.length>0?N.slice(0,2).map(g=>g+"%").join(" "):typeof c[0][1]?.text=="string"?c[0][1].text:"—";return e(X,{label:A,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm clickable"+(P==="ok"?"":" "+P)+(n===!1?" rail":"")+(i.busy?" busy":""),...ce(i.busy,i.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},M):e(D,null,e("div",{className:"cm-mm-title"},l(d.labelKey)),...y)))}function yn(t){const{source:s,snapshot:o,state:n,wide:a,api:r}=t,l=G(H(n.config?.locale)),i=ke(r?()=>r.refreshGatewayQuota(s.id):null),d=te(n.config,"plan"),h=o.accounts.length>1,c=v=>h?(Nt[v.provider]??v.provider)+" · ":"",b=[];for(const v of o.accounts){if(b.length>=4)break;for(const x of v.windows){if(b.length>=4)break;const p=x.label||x.id||l("gatewaySourceUnknown");b.push({win:x,name:c(v)+p,view:Oe(p,x,d)})}v.windows.length===0&&v.credits!=null&&b.push({win:null,name:c(v)+(v.credits.unit||"credits"),text:(v.credits.used??"—")+" / "+(v.credits.limit??"—")})}if(b.length===0)return null;const w=b.some(v=>v.view?.level==="over")?"over":b.some(v=>v.view?.level==="warn")?"warn":"ok",y=b.map(v=>{if(v.text!=null)return v.name+" "+v.text;const x=Ge(v.win,l);return v.name+" "+(v.view.pct===null?"—":v.view.pct+"%")+(x?" · "+x:"")});o.fetchedAt>0&&y.push(l("goQuotaFetchedAt",{time:new Date(o.fetchedAt).toLocaleTimeString()})),y.push(...de(l,i));const f=[s.label||s.id,...y].join("; "),A=b.map((v,x)=>v.text!=null?e("div",{key:x,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},v.name),e("span",{className:"cm-mm-text cm-num"},v.text)):e(D,{key:x},v.view.row)),N=e(D,null,e("div",{className:"cm-mm-title"},s.label||s.id),...A),P=b.filter(v=>v.view).map(v=>v.view.pct).filter(v=>v!==null),M=P.length>0?P.slice(0,2).map(v=>v+"%").join(" "):b[0].text??"—",g=e("div",{className:"cm-bbox-rail cm-num"},M);return e(X,{label:f,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm clickable"+(w==="ok"?"":" "+w)+(a===!1?" rail":"")+(i.busy?" busy":""),...ce(i.busy,i.run)},a===!1?g:N))}function kn(t,s,o,n){const a=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],r=[];for(const l of s.gatewayQuotas?.sources??[]){if(l.enabled===!1||l.display!=="sidebar"&&l.display!=="both")continue;const i=a.find(d=>d.id===l.id);!i||i.status!=="ok"&&i.status!=="partial"&&i.status!=="stale"||i.accounts.length===0||r.push(e(yn,{source:l,snapshot:i,state:t,wide:o,api:n}))}return r}const wn={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen"};function vn(t){const s=t.useCost?t.useCost(f=>f):void 0,[o,n]=O(null),[a,r]=O({}),l=s?.state,i=t.api;if(!l)return null;const d=l.config,h=d.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(h.enabled!==!0)return null;const c=G(H(d?.locale)),b=[];if(h.budget!==!1){const f=d.budget??{enabled:!1,amount:100,period:"month"};if(f.enabled===!0){const A=Number(d.exchangeRate),P=(l.budgetUsed??(f.period==="day"?_(l.today,d):f.period==="all"?_(l.total,d):_(l.month,d)))*(Number.isFinite(A)&&A>0?A:1),M=Math.max(0,Number(f.amount)||0);if(M>0){const g=Math.min(999,P/M*100),v=g>=100?"over":g>=80?"warn":"ok";b.push({key:"budget",label:c("budgetShort"),level:v,tip:c("budgetOf",{period:c(Ue[f.period]??"periodMonth")})+" · "+c("usedOf",{used:re(P,d),amount:re(M,d)})+" · "+g.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(ue(Math.min(100,g),te(d,"budget")).width)}]})}}}if(h.go!==!1){const f=l.goQuota;if(d?.goQuota?.enabled!==!1&&f?.status==="ok"){const A=d.goQuota.main==="weekly"||d.goQuota.main==="monthly"?d.goQuota.main:"rolling",N=A==="rolling"?f.rolling:A==="weekly"?f.weekly:f.monthly;if(N!==null&&typeof N=="object"&&typeof N.percent=="number"){const P=Math.max(0,Math.min(100,Math.round(Number(N.percent)||0))),M=P>=100?"over":P>=80?"warn":"ok",g=typeof N.resetsAt=="string"&&N.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(N.resetsAt).toLocaleString()}):"";b.push({key:"go",label:"Go "+c(A==="rolling"?"goShortRolling":A==="weekly"?"goShortWeekly":"goShortMonthly"),level:M,tip:"Go: "+P+"%"+g,segs:[{name:"main",pct:Math.round(ue(P,te(d,"go")).width)}]})}}}if(h.plans!==!1)for(const f of Be){const A=l.codingPlans?.[f.id];if(d.codingPlans?.[f.id]?.enabled!==!0||!A||A.status!=="ok")continue;const N=A.windows!==null&&typeof A.windows=="object"?A.windows:{},P=Object.entries(N);if(P.length===0)continue;const M=wn[f.id]??f.id,g=[],v=[];let x=0,p=0;for(const[S,T]of P){const L=dt(S,c),U=typeof T?.resetsAt=="string"&&T.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(T.resetsAt).toLocaleString()}):"",k=T!==null&&typeof T=="object"&&typeof T.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(T.percent)||0))):null;if(v.push(L+" "+(k===null?typeof T?.text=="string"?T.text:"—":k+"%")+U),k===null){g.push({name:S,pct:null,text:typeof T?.text=="string"?T.text:"—"});continue}p>=2||(p+=1,g.push({name:S,pct:Math.round(ue(k,te(d,"plan")).width)}),x=Math.max(x,k>=100?2:k>=80?1:0))}A.fetchedAt>0&&v.push(c("goQuotaFetchedAt",{time:new Date(A.fetchedAt).toLocaleTimeString()})),g.length!==0&&b.push({key:f.id,label:M,level:["ok","warn","over"][x],tip:v.join("; "),segs:g})}const w=$.status==="ok"?$.windows.weekly??null:null;if(w!==null&&typeof w.percent=="number"){const f=Math.max(0,Math.min(100,Math.round(Number(w.percent)||0))),A=typeof w.resetsAt=="string"&&w.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(w.resetsAt).toLocaleString()}):"";b.push({key:"codex",label:"Codex",level:f>=100?"over":f>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+f+"%"+A,segs:[{name:"weekly",pct:Math.round(ue(f,te(d,"plan")).width)}]})}if(b.length===0)return null;const y=f=>{o!==null||!i||(n(f),r(A=>({...A,[f]:null})),Promise.resolve().then(()=>f==="budget"?i.reload():f==="go"?i.refreshGoQuota():f==="codex"?Ke(!0):i.refreshCodingPlan(f)).catch(A=>{r(N=>({...N,[f]:A?.message??String(A)}))}).finally(()=>n(null)))};return e("div",{className:"cm-qstrip"},b.map(f=>{const A=o===f.key,N=a[f.key],P=[e("span",{className:"cm-qlabel",key:"l"},f.label)];A?P.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):f.segs.forEach((g,v)=>{v>0&&P.push(e("span",{className:"cm-qsep",key:"sep"+v,"aria-hidden":"true"})),g.pct===null?P.push(e("span",{className:"cm-qtext",key:g.name},g.text)):P.push(e("span",{className:"cm-qseg",key:g.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:g.pct+"%"}})),e("span",null,g.pct+"%")))});const M=[f.tip];return!A&&i&&M.push(c("clickToRefresh")),A&&M.push(c("refreshing")),N&&M.push("⚠ "+c("balanceRefreshFailed",{message:N})),e(X,{key:f.key,label:M.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(i?" action":"")+(f.level==="ok"?"":" "+f.level),...i?ce(A,()=>y(f.key)):{}},P))}))}function xn(t){const s=t.useCost?t.useCost(i=>i):void 0,o=Pe(!1),n=s?.state;if(!n)return null;const a=n.config;if(a.quotaStrip?.promptSeen===!0)return null;const r=G(H(a?.locale)),l=i=>{if(o.current===!0)return;o.current=!0;const d=a.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...d,enabled:i,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":r("quotaStripGuideTitle")},e("h4",null,r("quotaStripGuideTitle")),e("p",null,r("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>l(!1)},r("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>l(!0)},r("quotaStripGuideOn"))))}const Kt="dsh-cost-meter:balance-click-hint-seen",Nn=()=>{try{return window.localStorage.getItem(Kt)==="1"}catch{return!1}},Sn=()=>{try{window.localStorage.setItem(Kt,"1")}catch{}};function Cn(t){const s=t.useCost?t.useCost(y=>y):void 0,o=Pe(!1),[n,a]=O(!1),[r]=O(Nn),l=s?.state;if(!l)return null;const i=l.config,d=i.balance?.display==="sidebar"||i.balance?.display==="both",h=(i?.customBalances??[]).some(y=>y?.enabled===!0&&(y.display==="sidebar"||y.display==="both"))||i.customBalance?.enabled===!0&&(i.customBalance?.display==="sidebar"||i.customBalance?.display==="both"),c=Be.some(y=>{const f=i.codingPlans?.[y.id];return f?.enabled===!0&&(f.display==="sidebar"||f.display==="both")});if(n||r||i.balance?.clickHintSeen===!0||!d&&!h&&!c||i.quotaStrip?.promptSeen!==!0)return null;const b=G(H(i?.locale)),w=()=>{o.current!==!0&&(a(!0),o.current=!0,Sn(),t.api.updateConfig({balance:{...i.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,a(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":b("balanceClickGuideTitle")},e("h4",null,b("balanceClickGuideTitle")),e("p",null,b("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:w},b("balanceClickGuideOk"))))}function Vt(t){const{state:s,wide:o}=t,n=s.today,a=s.config,r=G(H(a?.locale)),l=a.budget??{enabled:!1,amount:100,period:"month"},i=Number(a.exchangeRate),h=(s.budgetUsed??(l.period==="day"?_(s.today,a):l.period==="all"?_(s.total,a):_(s.month,a)))*(Number.isFinite(i)&&i>0?i:1),c=Math.max(0,Number(l.amount)||0),b=c>0?Math.min(999,h/c*100):null,w=b===null?"ok":b>=100?"over":b>=80?"warn":"ok";if(l.enabled===!0){const f=_(n,a),A=f*(Number.isFinite(i)&&i>0?i:1),N=c>0?Math.min(999,A/c*100):null,P=[r("budgetOf",{period:r(Ue[l.period]??"periodMonth")}),r("usedOf",{used:re(h,a),amount:re(c,a)})+" · "+(b===null?"—":b.toFixed(1)+"%"),...a.hideTodayCost===!0?[]:[r("todayShare",{amount:J(f,a),pct:N===null?"—":N.toFixed(1)+"%"})],r("monthTotal",{month:J(_(s.month,a),a),total:J(_(s.total,a),a)})].join("; "),M=_t(s,a,r);return e(X,{label:P,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(w==="ok"?"":" "+w)+(o?"":" rail")},o?M.body:e("div",{className:"cm-bbox-rail cm-num"},M.rail)))}const y=[r("todayCostTitle"),r("callsTokens",{calls:n.calls,input:j(n.input),cache:j(n.cacheRead+n.cacheWrite),output:j(n.output)}),r("monthCost",{amount:J(_(s.month,a),a)}),r("totalCost",{amount:J(_(s.total,a),a)})].join("; ");return e(X,{label:y,side:"right",delayMs:300},e(D,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(D,null,r("today")," ",e("span",{className:"cm-num"},J(_(n,a),a))):e(nt,{size:16})),o?ut(s,a,r):null))}function An(t){const s=t.useCost?t.useCost(p=>p):void 0;let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}st(t,o);const n=s?.state,a=!!t.wide,r=Pe(null);if(se(()=>{const p=r.current,S=p?.parentElement;if(!p||!S)return;const T=()=>{a?S.firstElementChild!==p&&S.insertBefore(p,S.firstElementChild):S.lastElementChild!==p&&S.appendChild(p)};T();const L=new MutationObserver(()=>{p.isConnected&&T()});return L.observe(S,{childList:!0}),a?(S.style.flexDirection="",S.style.flexWrap="",S.style.alignItems="",S.style.gap=""):(S.style.flexDirection="column",S.style.flexWrap="nowrap",S.style.alignItems="center",S.style.gap="6px"),()=>{L.disconnect(),a||(S.style.flexDirection="",S.style.flexWrap="",S.style.alignItems="",S.style.gap="")}},[a,n]),!n)return null;const l=n.config,i=G(H(l?.locale)),d=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,c=it(n,l).length>0,b=d&&l.balance?.showProgressBar===!0&&n.balance?.status==="ok",w=c&&l.balance?.showProgressBar===!0,y=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",f=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&n.goQuota?.status==="ok"&&n.goQuota?.[y]!==null,A=Be.map(p=>p.id).filter(p=>{const S=l.codingPlans?.[p];if(S?.enabled!==!0||S.display!=="sidebar"&&S.display!=="both")return!1;const T=n.codingPlans?.[p];if(T?.status!=="ok")return!1;const L=T.windows!==null&&typeof T.windows=="object"?T.windows:{};return Object.keys(L).length>0}),N=A.length>0,P=kn(n,l,a,t.api),M=$.status==="ok"&&$.windows.weekly!==null,g=(l.budget??{}).enabled===!0,v=l.sidebar!==!1&&l.hideTodayCost!==!0;if(!d&&!c&&!f&&!N&&!M&&!g&&!v&&P.length===0)return null;const x=[];if(b?x.push(e(Ka,{state:n,wide:a,api:t.api})):d&&x.push(e(Ga,{state:n,wide:a,api:t.api})),w?x.push(e(Ya,{state:n,wide:a,api:t.api})):c&&x.push(e($a,{state:n,wide:a,api:t.api})),N&&x.push(...A.map(p=>p==="minimax"?e(cn,{state:n,wide:a,api:t.api}):e(hn,{id:p,state:n,wide:a,api:t.api}))),x.push(...P),M&&x.push(e(bn,{state:n,wide:a,api:t.api})),f&&g&&a){const p=zt(n,l,i),S=_t(n,l,i),T=p.level==="over"||S.level==="over"?"over":p.level==="warn"||S.level==="warn"?"warn":"ok";x.push(e("div",{className:"cm-bbox cm-bbox-pair"+(T==="ok"?"":" "+T)},e("div",{className:"cm-bbox-section"+(p.level==="ok"?"":" "+p.level)},p.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(S.level==="ok"?"":" "+S.level)},S.body)))}else f&&x.push(e(ln,{state:n,wide:a})),g&&x.push(e(Vt,{state:n,wide:a}));return!g&&v&&x.push(e(Vt,{state:n,wide:a})),a||x.push(on(n,l,i)),e("div",{ref:r,className:"cm-footer-stack"+(a?"":" rail")},...x)}function mt(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))}const Te=(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 Pn(t){const{state:s,api:o}=t,n=G(H(s.config?.locale)),[a,r]=O(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Te(a,()=>r(!a),n("history"))),a?e("div",{className:"cm-collapse-body"},e(Mn,{state:s,api:o})):null)}function Mn(t){const{state:s,api:o}=t,n=G(H(s.config?.locale)),[a,r]=O(null),[l,i]=O({}),[d,h]=O(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},n("noHistory"));const b=y=>{if(a===y){r(null);return}r(y),!(l[y]!==void 0||d.has(y))&&(h(f=>{const A=new Set(f);return A.add(y),A}),o.getDaySessions(y).then(f=>i(A=>({...A,[y]:Array.isArray(f?.sessions)?f.sessions:[]}))).catch(()=>i(f=>({...f,[y]:"error"}))).finally(()=>h(f=>{const A=new Set(f);return A.delete(y),A})))},w=y=>y.map(f=>e("tr",{key:f.id},pt(f,s.config?.showSessionId===!0,n),e("td",{className:"num"},String(f.calls)),e("td",{className:"num"},j(f.input)),e("td",{className:"num"},j(f.cacheRead+f.cacheWrite)),e("td",{className:"num"},j(f.output)),e("td",{className:"num"},J(_(f,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},n("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("colDate")),e("th",{className:"num"},n("colCalls")),e("th",{className:"num"},n("colInTok")),e("th",{className:"num"},n("colCacheTok")),e("th",{className:"num"},n("colOutTok")),e("th",{className:"num"},n("colCost")))),e("tbody",null,c.flatMap(y=>{const f=e("tr",{key:y.date,className:"cm-row-click",onClick:()=>b(y.date)},e("td",null,(a===y.date?"▾ ":"▸ ")+y.date),e("td",{className:"num"},String(y.calls)),e("td",{className:"num"},j(y.input)),e("td",{className:"num"},j(y.cacheRead+y.cacheWrite)),e("td",{className:"num"},j(y.output)),e("td",{className:"num"},J(_(y,s.config),s.config)));if(a!==y.date)return[f];const A=l[y.date],N=d.has(y.date)&&A===void 0?e("p",{className:"cm-empty"},n("historySessionsLoading")):A==="error"?e("p",{className:"cm-empty"},n("historySessionsError")):!Array.isArray(A)||A.length===0?e("p",{className:"cm-empty"},n("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("colSession")),e("th",{className:"num"},n("colCalls")),e("th",{className:"num"},n("colInTok")),e("th",{className:"num"},n("colCacheTok")),e("th",{className:"num"},n("colOutTok")),e("th",{className:"num"},n("colCost")))),e("tbody",null,w(A)));return[f,e("tr",{key:y.date+"-sessions"},e("td",{colSpan:6},N))]}))))}function Tn(t){const{state:s,api:o}=t,n=G(H(s.config?.locale)),[a,r]=O(!1),[l,i]=O(100),[d,h]=O("cost-desc"),[c,b]=O(null),[w,y]=O(!1),[f,A]=O(!1),N=Le.useRef(0),P=(x,p)=>{const[S,T]=p==="recent"?["recent","desc"]:p.split("-"),L=++N.current;y(!0),A(!1),o.getTopSessions(x,S,T).then(U=>{L===N.current&&b(Array.isArray(U?.sessions)?U.sessions:[])}).catch(()=>{L===N.current&&A(!0)}).finally(()=>{L===N.current&&y(!1)})},M=()=>{r(x=>{const p=!x;return p&&c===null&&!w&&P(l,d),p})},g=x=>{i(x),(a||c!==null)&&P(x,d)},v=x=>{h(x),(a||c!==null)&&P(l,x)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Te(a,M,n("sessionRankTitle"))),a?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},n("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,n("sessionRankSort")),e("select",{className:"cm-input",value:d,onChange:x=>v(x.target.value)},e("option",{value:"cost-desc"},n("sessionSortCostDesc")),e("option",{value:"cost-asc"},n("sessionSortCostAsc")),e("option",{value:"time-desc"},n("sessionSortTimeDesc")),e("option",{value:"time-asc"},n("sessionSortTimeAsc")),e("option",{value:"recent"},n("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,n("sessionRankLimit")),e("select",{className:"cm-input",value:String(l),onChange:x=>g(Number(x.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),w?e("p",{className:"cm-empty"},n("sessionRankLoading")):f?e("p",{className:"cm-empty"},n("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},n("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("colDate")),e("th",null,n("colSession")),e("th",{className:"num"},n("colCalls")),e("th",{className:"num"},n("colInTok")),e("th",{className:"num"},n("colCacheTok")),e("th",{className:"num"},n("colOutTok")),e("th",{className:"num"},n("colCost")))),e("tbody",null,c.map(x=>e("tr",{key:x.date+":"+x.id},e("td",null,x.date),pt(x,s.config?.showSessionId===!0,n),e("td",{className:"num"},String(x.calls)),e("td",{className:"num"},j(x.input)),e("td",{className:"num"},j((x.cacheRead??0)+(x.cacheWrite??0))),e("td",{className:"num"},j(x.output)),e("td",{className:"num"},J(_(x,s.config),s.config)))))))):null)}function Bn(t){const{state:s}=t,o=G(H(s.config?.locale)),n=s.today.sessions??[];if(n.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const a=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,n.map(r=>e("tr",{key:r.id},pt(r,a,o),e("td",{className:"num"},String(r.calls)),e("td",{className:"num"},j(r.input)),e("td",{className:"num"},j(r.cacheRead+r.cacheWrite)),e("td",{className:"num"},j(r.output)),e("td",{className:"num"},J(_(r,s.config),s.config)))))))}function pt(t,s,o){const n=typeof t.title=="string"?t.title.trim():"",a=String(t.id).slice(0,14)+"…",r=n.length>0?n:a,l=n.length>0?n+" · "+t.id:t.id;return e("td",{title:l},e("div",{className:"cm-sess-title"+(n.length===0?" cm-sess-id":"")},r),s&&n.length>0?e("div",{className:"cm-sess-id"},a):null)}const Ln={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function Rn(t){const{state:s,draft:o,setDraft:n,t:a}=t,r=s.config,l=o?.budget??r.budget,i=Number(r.exchangeRate),h=(s.budgetUsed??(l.period==="day"?_(s.today,r):l.period==="all"?_(s.total,r):_(s.month,r)))*(Number.isFinite(i)&&i>0?i:1),c=Math.max(0,Number(l.amount)||0),b=l.enabled&&c>0?Math.min(999,h/c*100):null,w=b===null?"ok":b>=100?"over":b>=80?"warn":"ok",y=(N,P)=>{o!==null&&n({...o,budget:{...o.budget??r.budget,[N]:P}})},f=l.period==="custom"?l.customStart+" → "+(l.customEnd??a("periodDay")):null,A=l.enabled&&b!==null?a("budgetStatus",{period:a(Ue[l.period]??"periodMonth"),amount:re(c,r),used:re(h,r),pct:b.toFixed(1)})+(w==="over"?a("overLimit"):w==="warn"?a("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:l.enabled===!0,onChange:N=>y("enabled",N.target.checked)}),e("span",null,a("enableBudget")))),l.enabled?e(D,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(w==="ok"?"":w),style:{width:(b===null?0:Math.min(100,b))+"%"}})),e("div",{className:"cm-budget-line"+(w==="over"?" over":"")+" cm-num"},A),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,a("budgetAmountLabel")),oe({value:l.amount},N=>y("amount",N))),e("div",{className:"cm-field"},e("label",null,a("budgetPeriodLabel")),e("select",{className:"cm-input",value:l.period,onChange:N=>y("period",N.target.value)},e("option",{value:"day"},a("periodDay")),e("option",{value:"month"},a("periodMonth")),e("option",{value:"all"},a("periodAll")),e("option",{value:"custom"},a("periodCustomRange")))),l.period==="custom"?e(D,null,e("div",{className:"cm-field"},e("label",null,a("startDate")),e("input",{className:"cm-input",type:"date",value:l.customStart??"",onChange:N=>y("customStart",N.target.value===""?null:N.target.value)})),e("div",{className:"cm-field"},e("label",null,a("endDate")),e("input",{className:"cm-input",type:"date",value:l.customEnd??"",onChange:N=>y("customEnd",N.target.value===""?null:N.target.value)}))):null),f!==null?e("p",{className:"cm-hint"},a("rangeText",{range:f})):null):e("p",{className:"cm-note"},a("budgetDisabledNote")))}function On(t){const{state:s,draft:o,setDraft:n,t:a}=t,r=s.config,l=(c,b)=>{o!==null&&n({...o,[c]:b})},i=o===null?r:{...r,...o},d=(()=>{if(i.peakEnabled!==!0)return a("peakOff");const c=Date.parse(i.peakEffectiveAt||""),b=Date.now();if(Number.isFinite(c)&&b<c)return a("peakNotEffective",{time:new Date(c).toLocaleString()});const w=i.peakWindows??[],y=We(b,w);return y===null?a("offPeakActive"):y.weekend===!0?a("weekendAllOffPeak"):y.inPeak?a("peakActive"):a("offPeakActive")})(),h=(i.peakWindows?.length??0)>0?a("peakSummary",{windows:i.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(H(i.locale)==="zh"?"、":", "),time:i.peakEffectiveAt||a("unknown"),status:d}):a("noPeakWindows",{status:d});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>l("peakEnabled",c.target.checked)}),e("span",null,a("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,a("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,a("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>l("peakStyle",c.target.value)},e("option",{value:"compact"},a("peakStyleCompact")),e("option",{value:"classic"},a("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,a("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,a("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 b=Number(c.target.value);Number.isInteger(b)&&b>=1&&b<=30&&l("peakAlertAhead",b)}})),e("div",{className:"cm-field"},e("label",null,a("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"},a("peakAlertTargetBoth")),e("option",{value:"peak"},a("peakAlertTargetPeak")),e("option",{value:"offpeak"},a("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,a("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>l("peakAlertPosition",c.target.value)},e("option",{value:"corner"},a("peakAlertPositionCorner")),e("option",{value:"center"},a("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,a("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},a("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,a("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},a("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},a("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?ut(s,i,a):e("p",{className:"cm-hint"},a("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},h),e("p",{className:"cm-hint"},a("weekendRuleNote")))}function oe(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:n=>{const a=n.target.value;if(a===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const r=Number(a);Number.isFinite(r)&&r>=0&&s(r)}})}function ft(t){const{modelId:s,entry:o,isDefault:n,draft:a,setDraft:r,t:l}=t,i=(c,b,w)=>{if(w===null){if(n){const x=a.prices.default??{cacheHit:0,cacheMiss:0,output:0},p={...x[c]??{}};delete p[b];const S={...x};Object.keys(p).length>0?S[c]=p:delete S[c],r({...a,prices:{...a.prices,default:S}});return}const P={...a.prices.models},M=P[s]??{cacheHit:0,cacheMiss:0,output:0},g={...M[c]??{}};delete g[b];const v={...M};Object.keys(g).length>0?v[c]=g:delete v[c],P[s]=v,r({...a,prices:{...a.prices,models:P}});return}const y=Math.max(0,w);if(n){let M={...a.prices.default??{cacheHit:0,cacheMiss:0,output:0}};if(c==="base")M[b]=y;else{const g={...M[c]??{},[b]:y};M={...M,[c]:g}}r({...a,prices:{...a.prices,default:M}});return}const f={...a.prices.models},A=f[s]??{cacheHit:0,cacheMiss:0,output:0};let N={...A};if(c==="base")N[b]=y;else{const P={...A[c]??{},[b]:y};N={...A,[c]:P}}f[s]=N,r({...a,prices:{...a.prices,models:f}})},d=()=>{const c={...a.prices.models};delete c[s],r({...a,prices:{...a.prices,models:c}})},h=(c,b)=>{const w=b==="base"?o:o[b]??null,y=b==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:b},e("span",null,c),oe({value:w?.cacheHit??null,emptyMode:y},f=>i(b,"cacheHit",f)),oe({value:w?.cacheMiss??null,emptyMode:y},f=>i(b,"cacheMiss",f)),oe({value:w?.output??null,emptyMode:y},f=>i(b,"output",f)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(D,null,o?.legacy===!0?e("span",{className:"cm-price-legacy"},l("legacyModel")):null,n?e("span",{className:"cm-price-legacy"},l("defaultFallback")):null,n?null:e("button",{className:"cm-btn small danger",onClick:d},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"))),h(l("tierBase"),"base"),h(l("tierOffPeak"),"offPeak"),h(l("tierPeak"),"peak"))}const Yt={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 Dn(t,s){if(t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");const o=a=>"$"+String(a),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?o(t.cacheMiss)+"/"+o(n.cacheMiss)+" in · "+o(t.output)+"/"+o(n.output)+" out":o(t.cacheMiss??t.input??0)+" in · "+o(t.output??0)+" out"}function En(t){const{state:s,draft:o,setDraft:n,t:a}=t,[r,l]=O(!1),[i,d]=O({}),h=s.priceCatalog;if(h===null||typeof h!="object")return null;const c=o?.prices??s.config.prices,b=o?.priceTableDisplay??s.config.priceTableDisplay??{},w=(p,S)=>{const T=b[p+":"+S];return typeof T=="boolean"?T:p==="deepseek"},y=(p,S,T)=>{o!==null&&n({...o,priceTableDisplay:{...b,[p+":"+S]:T}})},f=(p,S)=>p==="deepseek"?c.models?.[S]!==void 0:c.providers?.[p]?.models?.[S]!==void 0,A=(p,S,T)=>{if(o===null)return;const L=JSON.parse(JSON.stringify(T));if(p==="deepseek"){n({...o,prices:{...o.prices,models:{...o.prices.models,[S]:L}}});return}const U={...o.prices.providers??{}},k=U[p]??{};U[p]={...k,models:{...k.models??{},[S]:L}},n({...o,prices:{...o.prices,providers:U}})},N=(p,S)=>{if(o===null)return;if(p==="deepseek"){const U={...o.prices.models};delete U[S],n({...o,prices:{...o.prices,models:U}});return}const T={...o.prices.providers??{}},L=T[p];if(L!==void 0&&L.models!==void 0){const U={...L.models};delete U[S],T[p]={...L,models:U},n({...o,prices:{...o.prices,providers:T}})}},P=Object.keys(h).sort((p,S)=>p==="deepseek"?-1:S==="deepseek"?1:p.localeCompare(S)),M=p=>Object.values(h[p]).reduce((S,T)=>S+Object.keys(T).length,0),g=new Set(Object.values(h.deepseek??{}).flatMap(p=>Object.keys(p))),v=Object.keys(c.models??{}).filter(p=>!g.has(p)).sort(),x=(p,S,T)=>{const L=f(p,S),U=w(p,S),k=L?e("label",{className:"cm-check cm-vendor-display",title:a("catalogDisplayHint")},e("input",{type:"checkbox",checked:U,onChange:m=>y(p,S,m.target.checked)}),e("span",null,a("catalogDisplayLabel"))):null;if(L&&!U&&o!==null){const m=p==="deepseek"?e(ft,{key:S,modelId:S,entry:c.models[S],isDefault:!1,draft:o,setDraft:n,t:a}):e(Xt,{key:S,provider:p,modelId:S,entry:c.providers?.[p]?.models?.[S],draft:o,setDraft:n,t:a});return e("div",{key:S,className:"cm-catalog-mounted"},k,m)}return e("div",{key:S,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},S),e("span",{className:"cm-catalog-price"},Dn(T,a)),L?e("span",{className:"cm-catalog-tag"},a("mountedTag")):null,k,e("button",{className:"cm-btn small",disabled:!L&&T?.unpriced===!0,onClick:()=>L?N(p,S):A(p,S,T)},a(L?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>l(p=>!p)},a(r?"catalogCollapse":"catalogOpen"))),r?e(D,null,e("p",{className:"cm-note"},a("catalogNote")),P.map(p=>{const S=i[p]===!0;return e("div",{key:p},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>d(T=>({...T,[p]:!S}))},e("span",null,(S?"▾ ":"▸ ")+(Yt[p]??p)+" · "+M(p))),S?e(D,null,p==="deepseek"?e("p",{className:"cm-hint"},a("catalogDeepseekNote")):null,Object.keys(h[p]).sort().map(T=>e("div",{key:T},e("div",{className:"cm-catalog-family"},T),Object.keys(h[p][T]).sort().map(L=>x(p,L,h[p][T][L])))),p==="deepseek"&&v.length>0?e("div",null,e("div",{className:"cm-catalog-family"},a("catalogCustomModels")),v.map(T=>x("deepseek",T,null))):null):null)})):null)}const Jt=t=>t==="zen"?"go":t,$t=t=>{const s=t.indexOf(":");return s<=0?t:Jt(t.slice(0,s).toLowerCase())+t.slice(s)};function jn(t){const{state:s,config:o,t:n,initialTab:a}=t,[r,l]=O(a==="history"?"history":"today"),[i,d]=O(!1),h=g=>{if(g===null||typeof g!="object")return{};if(g.byProviderModel&&Object.keys(g.byProviderModel).length>0)return g.byProviderModel;if(g.byModel&&Object.keys(g.byModel).length>0)return g.byModel;const v={};if(Array.isArray(g.sessions))for(const x of g.sessions){if(x===null||typeof x!="object")continue;const p=typeof x.provider=="string"&&x.provider.length>0?x.provider:"deepseek",S=typeof x.model=="string"&&x.model.length>0?x.model:"unknown",T=p+":"+S,L=v[T]??(v[T]={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0,cost:0}),U=k=>typeof k=="number"&&Number.isFinite(k)&&k>=0?k:0;L.input+=U(x.input),L.output+=U(x.output),L.cacheRead+=U(x.cacheRead),L.cacheWrite+=U(x.cacheWrite),L.reasoning+=U(x.reasoning),L.cost+=U(x.cost)}if(Object.keys(v).length>0)return v;if(Number(g.cost)>0||Number(g.input)>0||Number(g.output)>0){const x=p=>typeof p=="number"&&Number.isFinite(p)&&p>=0?p:0;return{"deepseek:legacy":{input:x(g.input),output:x(g.output),cacheRead:x(g.cacheRead),cacheWrite:x(g.cacheWrite),reasoning:x(g.reasoning),cost:x(g.cost)}}}return{}},b=(g=>{const v={},x=p=>{for(const S of Object.keys(p??{})){const T=p[S];if(T===null||typeof T!="object")continue;const L=v[S]??(v[S]={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0,cost:0,calls:0});L.input+=Number(T.input)||0,L.output+=Number(T.output)||0,L.cacheRead+=Number(T.cacheRead)||0,L.cacheWrite+=Number(T.cacheWrite)||0,L.reasoning+=Number(T.reasoning)||0,L.cost+=Number(T.cost)||0,L.calls+=Number(T.calls)||0}};if(g==="today")x(h(s.today));else for(const p of s.history??[])x(h(p));return Object.entries(v).map(([p,S])=>{const T=p.indexOf(":"),L=(T>0?p.slice(0,T):"deepseek").toLowerCase(),U=T>0?p.slice(T+1):p,k=S.input+S.output+S.cacheRead+S.cacheWrite+S.reasoning,m=S.cacheRead+S.input;return{label:p==="deepseek:legacy"?n("modelStatsLegacy"):L==="deepseek"||L===""?U:Jt(L)+":"+U,...S,tokens:k,cls:et(L,U,o),hitRate:m>0?S.cacheRead/m:null,cacheUnreported:La(S),blended:k>0&&S.cost>0?S.cost/k*1e6:null,perUsd:S.cost>0?k/S.cost:null}}).filter(p=>p.tokens>0||p.cost>0)})(r).sort((g,v)=>v.cost-g.cost||v.tokens-g.tokens),w=g=>(Math.max(0,Math.min(1,g))*100).toFixed(1)+"%",y=b.reduce((g,v)=>Math.max(g,v.cost),0),f=b.reduce((g,v)=>Math.max(g,v.tokens),0),A=b.reduce((g,v)=>Math.max(g,v.perUsd??0),0),N=(g,v)=>e("button",{className:"cm-mstats-tab"+(r===g?" active":""),onClick:()=>l(g)},v),P=g=>g.cls==="plan"?e("span",{className:"cm-plan-tag",title:n("billingClassLabel")},n("billingClassPlan")):null,M=(g,v,x,p,S)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name"},g,S??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+x,style:{width:w(v)}})),e("span",{className:"cm-mstats-val"},p));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Te(i,()=>d(!i),n("modelStatsTitle"))),i?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},N("today",n("modelStatsToday")),N("history",n("modelStatsHistory"))),b.length===0?e("p",{className:"cm-note"},n("modelStatsEmpty")):e(D,null,e("div",{className:"cm-mstats-h"},n("modelStatsCostH")),b.map(g=>e(D,{key:"c:"+g.label},M(g.label,y>0?g.cost/y:0,"cost",J(g.cost,o),e(D,null,P(g),g.cacheUnreported?e("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},n("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),n("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),n("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),n("modelStatsOutput"))),[...b].sort((g,v)=>v.tokens-g.tokens).map(g=>e("div",{className:"cm-mstats-row",key:"t:"+g.label},e("span",{className:"cm-mstats-name"},g.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:w(f>0?g.input/f:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:w(f>0?(g.cacheRead+g.cacheWrite)/f:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:w(f>0?(g.output+g.reasoning)/f:0)}})),e("span",{className:"cm-mstats-val"},j(g.tokens)))),e("div",{className:"cm-mstats-h"},n("modelStatsHitH")),[...b].sort((g,v)=>(v.hitRate??-1)-(g.hitRate??-1)).map(g=>e(D,{key:"h:"+g.label},M(g.label,g.hitRate??0,"hit",g.cacheUnreported?n("modelStatsHitUnreported"):g.hitRate===null?"—":(g.hitRate*100).toFixed(1)+"%",g.cacheUnreported?e("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},n("modelStatsValueH")),[...b].sort((g,v)=>(v.perUsd??-1)-(g.perUsd??-1)).map(g=>e(D,{key:"v:"+g.label},M(g.label,A>0?(g.perUsd??0)/A:0,"value",g.perUsd===null?"—":j(g.perUsd)+" tok/$"+(g.blended!==null?" · "+n("modelStatsBlended",{price:"$"+g.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},n("modelStatsNote")))):null)}function Un(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 Hn(t,s){if(t==="go")return"OpenCode Go";const o=Be.find(n=>n.id===t);return o!==void 0?s(o.labelKey):t}const Zt=["fiveHour","weekly","monthly","daily"];function In(t,s){const o=new Map,n=a=>{const r=new Date(a),l=i=>String(i).padStart(2,"0");if(s==="monthly")return r.getFullYear()+"-"+l(r.getMonth()+1);if(s==="weekly"){const i=new Date(r.getFullYear(),r.getMonth(),r.getDate()-(r.getDay()+6)%7);return i.getFullYear()+"-"+l(i.getMonth()+1)+"-"+l(i.getDate())}return r.getFullYear()+"-"+l(r.getMonth()+1)+"-"+l(r.getDate())};for(const a of Object.values(t??{}))for(const r of a??[]){if(r===null||typeof r!="object"||!(r.tokens>0)&&!(r.cost>0))continue;const l=n(Number(r.t1)||Number(r.t0)),i=o.get(l)??{key:l,tokens:0,cost:0,pct:0,intervals:0};i.tokens+=Number(r.tokens)||0,i.cost+=Number(r.cost)||0,i.pct+=Number(r.pct)||0,i.intervals+=1,o.set(l,i)}return[...o.values()].map(a=>({...a,per1Tokens:a.pct>0?a.tokens/a.pct:null,fullTokens:a.pct>0?a.tokens/a.pct*100:null})).sort((a,r)=>a.key<r.key?-1:a.key>r.key?1:0)}function Qn(t){const{state:s,config:o,t:n}=t,[a,r]=O(!1),[l,i]=O("daily"),d=H(o?.locale),h=s?.planStats,c=h!=null&&typeof h.providers=="object"?h.providers:{},b=Object.keys(c).sort(),w=p=>J(Number(p)||0,o??s?.config),y=p=>p.method==="none"||p.per1Tokens===null?"—":j(p.per1Tokens)+" tok · "+w(p.per1Cost),f=p=>p.method==="none"||p.fullTokens===null?"—":j(p.fullTokens)+" tok · "+w(p.fullCost),A=p=>p.method==="sample"?n("planStatsMethodSample"):p.method==="live"?n("planStatsMethodLive"):n("planStatsMethodNone"),N=p=>{let S=A(p);return p.method==="sample"&&Number(p.sampleAt)>0&&(S=n("planStatsMethodSampleAt",{method:S,time:new Date(Number(p.sampleAt)).toLocaleString(d==="en"?"en-US":"zh-CN")})),(p.method==="sample"||p.method==="live")&&p.confidence==="low"&&(S+=" · "+n("planStatsConfidenceLow")),S},P=([p,S,T])=>e("tr",{key:S+":"+p},e("td",null,Un(p,d)),e("td",{className:"num"},Math.round(T.percent*10)/10+"%"),e("td",{className:"num"},j(T.localTokens)+" tok · "+w(T.localCost)),e("td",{className:"num"},y(T)),e("td",{className:"num"},f(T)),e("td",{className:"num cm-plan-reset"},T.resetsAt.length>0?n("planStatsResets",{time:new Date(T.resetsAt).toLocaleString(d==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},N(T))),M=a?b.flatMap(p=>Object.entries(c[p]?.intervals??{})).map(([p,S])=>({winKey:p,list:S})):[],g=In(Object.fromEntries(M.map(p=>[p.winKey,p.list])),l),v=g.reduce((p,S)=>Math.max(p,S.fullTokens??0),0),x=(p,S)=>e("button",{key:p,className:"cm-mstats-tab"+(l===p?" active":""),onClick:()=>i(p)},S);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Te(a,()=>r(!a),n("planStatsTitle"))),a?e("div",{className:"cm-collapse-body"},b.length===0?e("p",{className:"cm-empty"},n("planStatsEmpty")):e(D,null,b.map(p=>{const S=c[p]?.windows??{},T=[...Zt.filter(L=>S[L]!==void 0).map(L=>[L,p,S[L]]),...Object.keys(S).filter(L=>!Zt.includes(L)).map(L=>[L,p,S[L]])];return e("div",{key:p,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},Hn(p,n),e("span",{className:"cm-plan-updated"},(()=>{const L=Number(c[p]?.generatedAt)||Number(h?.generatedAt)||0;return L>0?new Date(L).toLocaleTimeString(d==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("planStatsWindow")),e("th",{className:"num"},n("planStatsPercent")),e("th",null,n("planStatsLocal")),e("th",null,n("planStatsPer1")),e("th",null,n("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,T.map(P))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},n("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},x("daily",n("planStatsDaily")),x("weekly",n("planStatsWeekly")),x("monthly",n("planStatsMonthly"))),g.length===0?e("p",{className:"cm-note"},n("planStatsCurveEmpty")):e(D,null,[...g].reverse().map(p=>e("div",{className:"cm-mstats-row",key:p.key},e("span",{className:"cm-mstats-name"},p.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(v>0?(p.fullTokens??0)/v*100:0).toFixed(1)+"%"}})),e(X,{label:n("planStatsBarTip",{date:p.key,full:p.fullTokens===null?"—":j(p.fullTokens),per1:p.per1Tokens===null?"—":j(p.per1Tokens),tokens:j(p.tokens),cost:w(p.cost),intervals:p.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},p.fullTokens===null?"—":j(p.fullTokens)))))),e("p",{className:"cm-note"},n("planStatsNote")))):null)}function Xt(t){const{provider:s,modelId:o,entry:n,draft:a,setDraft:r,t:l}=t,i=c=>{const b={...a.prices.providers??{}},w=b[s]??{};b[s]={...w,models:c},r({...a,prices:{...a.prices,providers:b}})},d=(c,b)=>{if(a===null)return;const w={...(a.prices.providers??{})[s]?.models??{}};w[o]={...w[o]??{},[c]:Math.max(0,b)},i(w)},h=()=>{if(a===null)return;const c={...(a.prices.providers??{})[s]?.models??{}};delete c[o],i(c)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(D,null,n?.unpriced===!0?e("span",{className:"cm-price-legacy"},l("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:h},l("unmountBtn")))),n?.unpriced===!0?null:e(D,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"),oe({value:n?.input??null,emptyMode:"ignore"},c=>d("input",c)),oe({value:n?.cachedInput??null,emptyMode:"ignore"},c=>d("cachedInput",c)),oe({value:n?.output??null,emptyMode:"ignore"},c=>d("output",c)))))}const De=t=>[e("option",{value:"sidebar"},t("balanceSidebar")),e("option",{value:"settings"},t("balanceSettings")),e("option",{value:"both"},t("balanceBoth")),e("option",{value:"off"},t("off"))],Ee=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function qn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(!1),[d,h]=O(null),c=s.balance,b=s.config,w=s.reconcile,y=(a?.balance??b.balance??{}).reconcile!==!1,f=M=>{a===null||typeof r!="function"||r({...a,balance:{...a.balance??b.balance??{},reconcile:M.target.checked}})},A=async()=>{if(!l){i(!0),h(null);try{const M=await o.refreshBalance();h({kind:M.ok?"ok":"err",text:M.message})}catch(M){h({kind:"err",text:n("balanceRefreshFailed",{message:M?.message??String(M)})})}finally{i(!1)}}},N=M=>he(M,b,c?.currency),P=c.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,n("balanceLine",{total:N(c.totalBalance),granted:N(c.grantedBalance),toppedUp:N(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?e("div",{className:"cm-bal-line err"},n("balanceQueryFailedHint",{message:c.message||n("unknownError")})):e("div",{className:"cm-bal-line"},n("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("accountBalance")),e("button",{className:"cm-btn small",onClick:A,disabled:l},n(l?"refreshing":"refreshBalance"))),P,w!==void 0&&w.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+w.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:y,onChange:f}),n("reconcileLabel")),Ee(d))}function Fn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,l=s.config,i=a?.customBalances??l.customBalances??[],d=w=>{a!==null&&r({...a,customBalances:w,...w.length===0?{customBalance:{...l.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},h=(w,y)=>{d(i.map((f,A)=>A===w?{...f,...y}:f))},c=w=>{d(i.filter((y,f)=>f!==w))},b=(w="custom")=>{i.length>=8||d([...i,{...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:[]}])};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("customBalanceTitle")),e("button",{className:"cm-btn small",onClick:()=>b(),disabled:i.length>=8},n("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>b("aliyun"),disabled:i.length>=8},n("aliyunBalanceAdd"))),e("p",{className:"cm-note"},n("customBalanceMultiNote")),i.length===0?e("p",{className:"cm-hint"},n("customBalanceEmpty")):i.map((w,y)=>e(Wn,{key:"cbe-"+y,state:s,api:o,t:n,entry:w,index:y,canRemove:!0,onPatch:f=>h(y,f),onRemove:()=>c(y)})))}function Wn(t){const{state:s,api:o,t:n,entry:a,index:r,canRemove:l,onPatch:i,onRemove:d}=t,h=a.adapter==="aliyun",[c,b]=O(!1),[w,y]=O(null),[f,A]=O(!1),[N,P]=O(()=>JSON.stringify(a.request?.headers??{},null,2)),[M,g]=O(()=>JSON.stringify(a.extract??{},null,2)),[v,x]=O(()=>(a.allowedHosts??[]).join(", ")),[p,S]=O({headers:"",extract:""}),T=Pe(!1),L=s.config,k=(Array.isArray(s.customBalances)?s.customBalances:[]).find(C=>C.index===r)??null,m=a.enabled===!0,B=()=>{A(C=>!C)};se(()=>{f&&!T.current&&(P(JSON.stringify(a.request?.headers??{},null,2)),g(JSON.stringify(a.extract??{},null,2)),x((a.allowedHosts??[]).join(", ")),S({headers:"",extract:""})),T.current=f},[f]);const E=(C,R)=>i({[C]:R}),K=(C,R)=>i({request:{...a.request??{},[C]:R}}),I=(()=>{if(h)return["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"];const C=new Set,R=[];for(const z of Object.values(a.request?.headers??{}))if(typeof z=="string")for(const W of z.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g))C.has(W[1])||(C.add(W[1]),R.push(W[1]));return R})(),Z=C=>{P(C);try{const R=JSON.parse(C);if(R===null||typeof R!="object"||Array.isArray(R))throw new Error("invalid");if(Object.values(R).some(z=>typeof z!="string"))throw new Error("invalid");S(z=>({...z,headers:""})),K("headers",R)}catch{S(R=>({...R,headers:n("customBalanceInvalidJson")}))}},q=C=>{x(C);const R=C.split(/[\s,;]+/).map(z=>z.trim()).filter(z=>z.length>0);E("allowedHosts",R)},ne=C=>{g(C);try{const R=JSON.parse(C);if(R===null||typeof R!="object"||Array.isArray(R))throw new Error("invalid");S(z=>({...z,extract:""})),E("extract",R)}catch{S(R=>({...R,extract:n("customBalanceInvalidJson")}))}},ve=async()=>{const C=(L.customBalances??[])[r];if(!(c||C?.enabled!==!0)){b(!0),y(null);try{const R=await o.refreshCustomBalance(r);y({kind:R.ok?"ok":"err",text:R.message})}catch(R){y({kind:"err",text:n("customBalanceRefreshFailed",{message:R?.message??String(R)})})}finally{b(!1)}}},Se=k!==null&&k.status==="ok"?e(D,null,L.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(lt,{segments:ot(s,L,k,a),direction:te(L,"balance")}),e("div",{className:"cm-bal-line"},rt(k,L,n,s,a))):e("div",{className:"cm-bal-line"},n("customBalanceRemaining",{amount:we(k.remaining,L,k,a)}))):k!==null&&k.status==="error"?e("div",{className:"cm-bal-line err"},k.message||n("unknownError")):e("div",{className:"cm-bal-line"},k?.message||n("balanceNotQueried")),u=f?e(D,null,e("p",{className:"cm-note"},n(h?"aliyunBalanceNote":"customBalanceConfigNote")),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("customBalanceLabelZh")),e("input",{className:"cm-input",value:a.label??"",onChange:C=>E("label",C.target.value)})),e("div",{className:"cm-field"},e("label",null,n("customBalanceLabelEn")),e("input",{className:"cm-input",value:a.labelEn??"",onChange:C=>E("labelEn",C.target.value)})),!h&&e("div",{className:"cm-field"},e("label",null,n("customBalanceUnitLabel")),e("select",{className:"cm-input",value:a.unit==="CNY"||a.unit==="EUR"?a.unit:"USD",onChange:C=>E("unit",C.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"))),e("div",{className:"cm-field"},e("label",null,n("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:a.display??"both",onChange:C=>E("display",C.target.value)},...De(n))),e("div",{className:"cm-field"},e("label",null,n("customBalanceRefreshInterval")),oe({value:a.refreshMinutes??15},C=>E("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(C)))))),!h&&e("div",{className:"cm-field"},e("label",null,n("customBalanceMethod")),e("select",{className:"cm-input",value:a.request?.method??"GET",onChange:C=>K("method",C.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceUrl")),e("input",{className:"cm-input",value:a.request?.url??"",placeholder:"https://example.com/key/info",onChange:C=>K("url",C.target.value)})),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceHeaders")),e("span",{className:"cm-hint"},n("customBalanceHeadersVarNote")),e("textarea",{className:"cm-input",rows:5,value:N,onChange:C=>Z(C.target.value)}),p.headers?e("span",{className:"cm-hint err"},p.headers):null),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceCredentialsTitle")),I.length>0?e(D,null,!h&&e("span",{className:"cm-hint"},n("customBalanceCredentialsHint")),I.map(C=>e(Me,{key:"cb-var-"+C,target:"customVar:"+C,configured:(s.customVarStatus?.[C]?.configured??!1)===!0,source:s.customVarStatus?.[C]?.source??"",t:n,api:o,placeholder:"{{"+C+"}}"}))):e("span",{className:"cm-hint"},n("customBalanceNoPlaceholders"))),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:v,placeholder:"api.example.com, relay.example.org",onChange:C=>q(C.target.value)}),e("span",{className:"cm-hint"},n("customBalanceAllowedHostsHint"))),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceExtract")),e("textarea",{className:"cm-input",rows:8,value:M,onChange:C=>ne(C.target.value)}),p.extract?e("span",{className:"cm-hint err"},p.extract):null))):e("p",{className:"cm-note cm-collapsed-note"},Fe(a,H(L?.locale))||n("customBalanceTitle"));return e("div",{className:"cm-budget",style:{marginTop:"10px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},`#${r+1} · `+(Fe(a,H(L?.locale))||n("customBalanceTitle"))),e("button",{className:"cm-toggle-btn",onClick:B},n(f?"customBalanceCollapseConfig":"customBalanceOpenConfig")),e("button",{className:"cm-btn small",onClick:ve,disabled:c||m===!1},n(c?"refreshing":"refreshCustomBalance")),l?e("button",{className:"cm-btn small",onClick:d},n("customBalanceRemove")):null),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:m===!0,onChange:C=>E("enabled",C.target.checked)}),e("span",null,n("enable"))),Se,u,Ee(w))}function _n(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(!1),[d,h]=O(null),c=s.goQuota,b=s.config,w=a?.goQuota?.enabled??b.goQuota?.enabled??!0,y=(x,p)=>{a!==null&&r({...a,goQuota:{...a.goQuota??b.goQuota,[x]:p}})},f=async()=>{if(!(l||w===!1)){i(!0),h(null);try{const x=await o.refreshGoQuota();h({kind:x.ok?"ok":"err",text:x.message})}catch(x){h({kind:"err",text:n("syncFailed",{message:x?.message??String(x)})})}finally{i(!1)}}},A=b.goQuota?.main==="weekly"||b.goQuota?.main==="monthly"?b.goQuota.main:"rolling",N=[A,...["rolling","weekly","monthly"].filter(x=>x!==A)],P=x=>x==="rolling"?"goWindowRolling":x==="weekly"?"goWindowWeekly":"goWindowMonthly",M=x=>x==="rolling"?c.rolling:x==="weekly"?c.weekly:c.monthly,g=(x,p,S)=>{const T=p!==null&&typeof p=="object"&&typeof p.percent=="number",L=T?Math.max(0,Math.min(100,Number(p.percent)||0)):null,U=ue(L,te(b,"go")),k=T&&typeof p.resetsAt=="string"&&p.resetsAt.length>0?n("goResetAt",{time:new Date(p.resetsAt).toLocaleString()}):"";return e("div",{className:"cm-go-row"+(S?" main":"")},e("span",{className:"cm-go-label"},n(x)),e("div",{className:"cm-go-bar"},L===null?null:e("div",{className:"cm-go-fill",style:{width:U.width+"%"}})),e("span",{className:"cm-go-num"},U.label===null?"—":n("goQuotaPercent",{percent:String(Math.round(U.label))})),k?e("span",{className:"cm-go-reset"},k):null)},v=w===!1?e("p",{className:"cm-note"},n("goQuotaDisabledNote")):c.status==="ok"?e("div",{className:"cm-go-list"},N.map(x=>g(P(x),M(x),x===A)),e("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?e("div",{className:"cm-bal-line err"},c.message||n("unknownError")):c.status==="off"&&c.message?e("p",{className:"cm-note"},c.message):e("div",{className:"cm-bal-line"},n("goQuotaNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("goQuotaTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:w===!0,onChange:x=>y("enabled",x.target.checked)}),e("span",null,n("enableGoQuota"))),e("button",{className:"cm-btn small",onClick:f,disabled:l||w===!1},n(l?"refreshing":"refreshGoQuota"))),v,Ee(d))}const zn=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const n="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(a=>a===n||a.startsWith(n+"_"))??n};function Gn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(null),[d,h]=O({}),[c,b]=O({}),w=s.config,f=(a??w).gatewayQuotas?.sources??[],A=Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[],N=k=>{a!==null&&r({...a,gatewayQuotas:{...a.gatewayQuotas??w.gatewayQuotas??{},sources:k}})},P=(k,m)=>N(f.map((B,E)=>E===k?{...B,...m}:B)),M=k=>b(m=>({...m,[k]:m[k]!==!0})),g=async k=>{if(l!==null)return;const m=(w.gatewayQuotas?.sources??[]).find(B=>B.id===k);if(!(!m||m.enabled!==!0||m.display==="off")){i(k),h(B=>({...B,[k]:null}));try{const B=await o.refreshGatewayQuota(k);h(E=>({...E,[k]:{kind:B.ok?"ok":"err",text:B.message}}))}catch(B){h(E=>({...E,[k]:{kind:"err",text:B?.message??String(B)}}))}finally{i(null)}}},v=()=>{if(f.length>=4)return;const k="gateway-"+Date.now().toString(36);b(m=>({...m,[k]:!0})),N([...f,{id:k,type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:$e,allowedHosts:[],allowInsecureHttp:!1}])},x=(k,m,B)=>e("div",{className:"cm-field"},e("label",null,k),e("input",{className:"cm-input",value:m??"",onChange:B})),p=(k,m)=>{const B=Oe(k?.label||k?.id||n("gatewaySourceUnknown"),k,te(w,"plan"));return e(D,{key:k?.id||m},B.row,k?.resetsAt?e("div",{className:"cm-note"},Ge(k,n)):null)},S=k=>e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},k.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(k.used??"—")+" / "+(k.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(k.remaining??"—")+" remaining")),T=k=>k==null?null:e(D,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},k.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(k.used??"—")+" / "+(k.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(k.remaining??"—")+" remaining")),(k.packages??[]).map(S)),L=(k,m)=>e("div",{key:k.id||m,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Nt[k.provider]??k.provider??n("gatewaySourceUnknown"))+" · "+(k.label||n("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},k.status)),k.plan?e("div",{className:"cm-note"},k.plan):null,k.windows.length>0?e("div",{className:"cm-go-list"},k.windows.map(p)):null,T(k.credits),k.message?e("div",{className:"cm-note"},k.message):null),U=(k,m)=>{const B=A.find(I=>I.id===k.id)??{id:k.id,status:"off",accounts:[],unsupportedProviders:[]},E=zn(k,s.customVarStatus),K=c[k.id]===!0;return e("div",{key:k.id||m,className:"cm-budget"},e("div",{className:"cm-budget-head"},Te(K,()=>M(k.id),k.label||k.id||n("gatewayQuotaTitle")),K?null:e("span",{className:"cm-hint"},B.status??n("gatewaySourceUnknown")),e("button",{className:"cm-btn small",onClick:()=>g(k.id),disabled:l!==null||k.enabled!==!0},l===k.id?n("gatewaySourceRefreshing"):n("refreshGoQuota")),e("button",{className:"cm-btn small",onClick:()=>N(f.filter((I,Z)=>Z!==m))},n("gatewaySourceRemove"))),K?e("div",{className:"cm-collapse-body"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:k.enabled===!0,onChange:I=>P(m,{enabled:I.target.checked})}),n("gatewaySourceEnabled")),e("div",{className:"cm-grid"},x(n("gatewaySourceLabel"),k.label,I=>P(m,{label:I.target.value})),x(n("gatewaySourceBaseURL"),k.baseURL,I=>P(m,{baseURL:I.target.value})),e("div",{className:"cm-field"},e("label",null,n("gatewaySourceDisplay")),e("select",{className:"cm-input",value:k.display??"both",onChange:I=>P(m,{display:I.target.value})},...De(n))),x(n("gatewaySourceAllowlist"),(k.allowedHosts??[]).join(", "),I=>P(m,{allowedHosts:I.target.value.split(/[\s,;]+/).filter(Boolean)}))),E?e("div",{className:"cm-field"},e("label",null,n("gatewaySourceCredential")),e(Me,{target:"customVar:"+E,configured:s.customVarStatus?.[E]?.configured===!0,source:s.customVarStatus?.[E]?.source??"",t:n,api:o,placeholder:E})):null,e("div",{className:"cm-note"},n("gatewaySourceStatus")+": "+(B.status??n("gatewaySourceUnknown"))+(B.serverVersion?" · "+B.serverVersion:"")+(B.fetchedAt>0?" · "+n("gatewaySourceFetchedAt",{time:new Date(B.fetchedAt).toLocaleTimeString()}):"")+(B.message?" · "+B.message:"")),B.unsupportedProviders.length>0?e("div",{className:"cm-note"},n("gatewaySourceUnsupported")+": "+B.unsupportedProviders.join(", ")):null,B.accounts.length>0?B.accounts.map(L):e("div",{className:"cm-bal-line"},n("gatewaySourceNoAccounts")),d[k.id]?e("div",{className:"cm-msg "+d[k.id].kind},d[k.id].text):null):null)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("gatewayQuotaTitle")),e("button",{className:"cm-btn small",onClick:v,disabled:f.length>=4},n("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>o.refreshGatewayQuota(),disabled:l!==null||f.length===0},n(l===null?"refreshGoQuota":"gatewaySourceRefreshing"))),e("p",{className:"cm-note"},n("gatewayQuotaNote")),f.length===0?e("p",{className:"cm-hint"},n("gatewaySourceEmpty")):f.map(U))}const Be=[{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"}],ea="dsh-cost-meter.codingPlans.open";function Kn(){try{return window.localStorage.getItem(ea)==="1"}catch{return!1}}function Vn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(null),[d,h]=O({}),[c,b]=O(Kn),w=()=>{b(k=>{const m=!k;try{window.localStorage.setItem(ea,m?"1":"0")}catch{}return m})},y=s.codingPlans??{},f=s.config,A=k=>a?.codingPlans?.[k]??f.codingPlans?.[k]??{},N=k=>y[k]??{status:"off",message:"",fetchedAt:0,windows:{}},P=(k,m,B)=>{if(a===null)return;const E=a.codingPlans??f.codingPlans??{};r({...a,codingPlans:{...E,[k]:{...E[k]??{},[m]:B}}})},[M,g]=O(""),v=k=>k?.rates!==null&&typeof k?.rates=="object"&&!Array.isArray(k.rates)?k.rates:{},x=(k,m,B)=>{if(a===null)return;const E=a.codingPlans??f.codingPlans??{},K={...(E.qwen??{}).rates??{}},I={...K[k]??{}},Z=String(B).trim();if(Z==="")delete I[m];else{const q=Number(Z);Number.isFinite(q)&&q>0&&(I[m]=q)}I.input===void 0&&I.cachedInput===void 0&&I.output===void 0?delete K[k]:K[k]=I,r({...a,codingPlans:{...E,qwen:{...E.qwen??{},rates:K}}})},p=k=>{if(a===null)return;const m=a.codingPlans??f.codingPlans??{},B={...(m.qwen??{}).rates??{}};B[k]={...B[k]??{}},r({...a,codingPlans:{...m,qwen:{...m.qwen??{},rates:B}}})},S=k=>{if(a===null)return;const m=a.codingPlans??f.codingPlans??{},B={...(m.qwen??{}).rates??{}};delete B[k],r({...a,codingPlans:{...m,qwen:{...m.qwen??{},rates:B}}})},T=async k=>{if(l===null){i(k),h(m=>({...m,[k]:null}));try{const m=await o.refreshCodingPlan(k);h(B=>({...B,[k]:{kind:m.ok?"ok":"err",text:m.message}}))}catch(m){h(B=>({...B,[k]:{kind:"err",text:n("syncFailed",{message:m?.message??String(m)})}}))}finally{i(null)}}},L=(k,m)=>{if(typeof m?.percent!="number")return e("div",{className:"cm-go-row"},e("span",{className:"cm-go-label"},k.replace(/_/g," ")),e("span",{className:"cm-go-num"},typeof m?.text=="string"?m.text:"—"));const B=m?Math.max(0,Math.min(100,Number(m.percent)||0)):0,E=ue(B,te(f,"plan")),K=m&&typeof m.resetsAt=="string"&&m.resetsAt.length>0?n("goResetAt",{time:new Date(m.resetsAt).toLocaleString()}):"";return e("div",{className:"cm-go-row"},e("span",{className:"cm-go-label"},k.replace(/_/g," ")),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:E.width+"%"}})),e("span",{className:"cm-go-num"},n("goQuotaPercent",{percent:String(Math.round(E.label))})),K?e("span",{className:"cm-go-reset"},K):null)},U=({id:k,labelKey:m})=>{const B=A(k),E=N(k),K=B.enabled===!0,I=E.windows!==null&&typeof E.windows=="object"?E.windows:{},Z=K===!1?e("p",{className:"cm-note"},n("codingPlanDisabledNote")):E.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(I).length>0?k==="minimax"&&(Re(I).five!=null||Re(I).seven!=null)?e(Gt,{five:Re(I).five,seven:Re(I).seven,fetchedAt:E.fetchedAt,t:n,wide:!0,direction:te(f,"plan")}):Object.entries(I).map(([q,ne])=>L(q,ne)):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried")),e("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:E.fetchedAt>0?new Date(E.fetchedAt).toLocaleTimeString():"—"}))):E.status==="error"?e("div",{className:"cm-bal-line err"},E.message||n("unknownError")):E.status==="off"&&E.message?e("p",{className:"cm-note"},E.message):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried"));return e("div",{key:k,className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n(m)),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:K,onChange:q=>P(k,"enabled",q.target.checked)}),e("span",null,n("enableCodingPlan"))),e("button",{className:"cm-btn small",onClick:()=>{T(k)},disabled:l!==null||K===!1},n(l===k?"refreshing":"refreshCodingPlan"))),K?e("div",{className:"cm-field"},e("label",null,n("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof B.display=="string"?B.display:k==="minimax"?"both":"settings",onChange:q=>P(k,"display",q.target.value)},e("option",{value:"sidebar"},n("balanceSidebar")),e("option",{value:"settings"},n("balanceSettings")),e("option",{value:"both"},n("balanceBoth")),e("option",{value:"off"},n("off"))),e("span",{className:"cm-hint"},n("codingPlanDisplayNote"))):null,K&&k!=="scnet"&&k!=="qwen"?e("div",{className:"cm-field"},e("label",null,n("codingPlanRefreshIntervalLabel")),oe({value:typeof B.refreshMinutes=="number"&&Number.isFinite(B.refreshMinutes)&&B.refreshMinutes>0?B.refreshMinutes:15},q=>{P(k,"refreshMinutes",Math.min(1440,Math.max(1,Math.floor(q))))})):null,K?k==="scnet"||k==="qwen"?e(D,null,e("div",{className:"cm-field"},e("label",null,n(k==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof B.planCredits=="number"&&Number.isFinite(B.planCredits)&&B.planCredits>0?B.planCredits:k==="qwen"?5e5:24e4,onChange:q=>{const ne=Number(q.target.value);Number.isFinite(ne)&&ne>0&&P(k,"planCredits",Math.floor(ne))}})),e("div",{className:"cm-field"},e("label",null,n(k==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof B.planStart=="string"?B.planStart:"",onChange:q=>P(k,"planStart",q.target.value)})),k==="qwen"?e(D,null,e("div",{className:"cm-field"},e("label",null,n("qwenRatesLabel"))),Object.keys(v(B)).sort().map(q=>e("div",{key:q,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},q),["input","cachedInput","output"].map(ne=>e("input",{key:ne,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:v(B)[q]?.[ne]??"",placeholder:n("qwenRatePlaceholder"),onChange:ve=>{const Se=ve.target.value;x(q,ne,Se)}})),e("button",{className:"cm-btn small",onClick:()=>S(q)},n("overrideRemove")))),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:n("qwenRatesModelPlaceholder"),value:M,onChange:q=>g(q.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const q=M.trim();q.length!==0&&(p(q),g(""))},disabled:M.trim().length===0},n("qwenRatesAdd")))):null,e("p",{className:"cm-note"},n(k==="qwen"?"qwenLocalNote":"scnetLocalNote"))):k==="volcengine"?e(D,null,e("div",{className:"cm-field"},e("label",null,n("volcengineAccessKeyIdLabel"))),e(Me,{target:"codingPlans.volcengine.ak",configured:E.keyConfigured===!0,source:E.keySource,t:n,api:o,placeholder:n("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,n("volcengineSecretAccessKeyLabel"))),e(Me,{target:"codingPlans.volcengine.sk",configured:E.keyConfigured===!0,source:E.keySource,t:n,api:o,placeholder:n("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},n("volcengineNote"))):e(D,null,e("div",{className:"cm-field"},e("label",null,n("codingPlanKeyLabel"))),e(Me,{target:"codingPlans."+k,configured:E.keyConfigured===!0,source:E.keySource,t:n,api:o,placeholder:"sk-…"})):null,Z,d[k]!=null?e("div",{className:"cm-msg "+d[k].kind},d[k].text):null)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("codingPlansTitle")),e("button",{className:"cm-toggle-btn",onClick:w},n(c?"codingPlansCollapse":"codingPlansOpen"))),c?e(D,null,e("p",{className:"cm-note"},n("codingPlansNote")),Be.map(U)):e("p",{className:"cm-note cm-collapsed-note"},n("codingPlansCollapsedHint")))}const Yn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ta=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function gt(t){const s=t.useCost?t.useCost(v=>v):void 0,o=t.state??s?.state;if(!o)return null;const n=o.config,a=H(n?.locale),r=t.t??G(a),l=Array.isArray(o.history)?o.history:[];if(l.length===0)return e("div",null,e("h3",{className:"cm-h"},r("usageTitle")),e("p",{className:"cm-empty"},r("usageEmpty")));const i=o.meta?.dayKey??"",d=new Map(l.map(v=>[v.date,v])),h=v=>{const x=p=>String(p).padStart(2,"0");return v.getFullYear()+"-"+x(v.getMonth()+1)+"-"+x(v.getDate())},c=new Date;c.setHours(0,0,0,0);const b=new Date(c);b.setDate(b.getDate()+(6-(c.getDay()+6)%7));const w=26,y=[],f=[];let A=-1;for(let v=w-1;v>=0;v-=1){for(let p=0;p<7;p+=1){const S=new Date(b);S.setDate(S.getDate()-(v*7+(6-p)));const T=d.get(h(S));y.push(T!==void 0?{day:T,tokens:ta(T)}:{day:{date:h(S)},tokens:0})}const x=new Date(b);x.setDate(x.getDate()-(v*7+6)),f.push(x.getMonth()!==A?a==="en"?Yn[x.getMonth()]:String(x.getMonth()+1)+"月":""),A=x.getMonth()}const N=Math.max(...y.map(v=>v.tokens),1),P=v=>{const x=v/N;return x<.25?1:x<.5?2:x<.75?3:4},M=v=>{const{day:x,tokens:p}=v,S="cm-ug-cell"+(p>0?" l"+P(p):"")+(x.date===i?" today":""),T=r("usageDay",{date:x.date,tokens:j(p),input:j(x.input??0),cache:j((x.cacheRead??0)+(x.cacheWrite??0)),output:j(x.output??0),calls:x.calls??0,cost:J(_(x,n),n)});return e(X,{key:x.date,label:T,side:"top",delayMs:200},e("div",{className:S}))},g=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},r("usageTitle")),e("div",{className:"cm-ug-total"},r("usageTotal",{tokens:j(ta(g)),input:j(g.input??0),cache:j((g.cacheRead??0)+(g.cacheWrite??0)),output:j(g.output??0),calls:g.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+w+",1fr)"}},y.map(M)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+w+",1fr)"}},f.map((v,x)=>e("span",{key:"m"+String(x),className:"cm-ug-monthc"},v))))}function Jn(t){const s=t.useCost?t.useCost(u=>u):void 0,o=t.api,n=s?.state??null,[a,r]=O(null),[l,i]=O(null),[d,h]=O(!1),[c,b]=O(!1),[w,y]=O(!1),[f,A]=O(""),[N,P]=O(!1),[M,g]=O(!1),[v,x]=O("overview"),[p,S]=O({status:"idle",at:0,error:null}),T=Le.useRef(null),L=Le.useRef(null),U=Le.useRef(null);se(()=>{if(n!==null){const u=JSON.stringify(n.config);r(C=>{const R=C!==null&&JSON.stringify(C)!==T.current;return R||(L.current=n.config,U.current=n.config),R?C:JSON.parse(u)}),T.current=u}},[n]),se(()=>{a!==null&&U.current===null&&L.current!==null&&(U.current=L.current)},[a]),se(()=>{if(a===null||o===void 0)return;const u=JSON.stringify(a);if(u===T.current)return;S(R=>R.status==="saving"?R:{...R,status:"saving"});const C=setTimeout(()=>{const R={},z=U.current??L.current;if(z!==null&&typeof z=="object")for(const W of Object.keys(a))JSON.stringify(a[W])!==JSON.stringify(z[W])&&(R[W]=a[W]);if(Object.keys(R).length===0){T.current=u,S({status:"saved",at:Date.now(),error:null});return}o.updateConfig(R).then(()=>{T.current=u,z!==null&&typeof z=="object"&&(U.current={...z,...R}),S({status:"saved",at:Date.now(),error:null})},W=>{S({status:"error",at:0,error:W?.message??String(W)})})},600);return()=>{clearTimeout(C)}},[a,o]),se(()=>{s?.status==="error"&&s.error&&i({kind:"err",text:m("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const k=H((a??n?.config)?.locale),m=G(k);if(s===void 0||n===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?m("readingLedger"):m("ledgerUnavailable")));const B=n.config,E=async()=>{if(!N){P(!0),i(null);try{const u=await o.fetchPrices();if(i({kind:u.ok?"ok":"err",text:u.message}),u.ok&&u.state&&typeof u.state.config=="object"){const C=JSON.stringify(u.state.config);r(JSON.parse(C)),T.current=C}}catch(u){i({kind:"err",text:m("syncFailed",{message:u?.message??String(u)})})}finally{P(!1),h(!1)}}},K=async()=>{if(!N){P(!0);try{await o.resetHistory(),i({kind:"ok",text:m("historyCleared")})}catch(u){i({kind:"err",text:m("clearFailed",{message:u?.message??String(u)})})}finally{P(!1),b(!1)}}},I=async()=>{if(!N){P(!0),i(null);try{const u=await o.importLegacyHistory();i({kind:"ok",text:u.message})}catch(u){i({kind:"err",text:m("legacyImportFailed",{message:u?.message??String(u)})})}finally{P(!1),y(!1)}}},Z=(u,C)=>{a!==null&&r({...a,[u]:C})},q=()=>{if(a===null)return;const u=f.trim().toLowerCase();if(u.length===0||!/^[a-z0-9_.-]+$/.test(u)||a?.prices.models[u]!==void 0)return;const C={...a.prices.models,[u]:{cacheHit:0,cacheMiss:0,output:0}};r({...a,prices:{...a.prices,models:C}}),A("")},ne=a===null?[]:Object.keys(a.prices.models).filter(u=>{const R=(a?.priceTableDisplay??B.priceTableDisplay??{})["deepseek:"+u];return typeof R=="boolean"?R:!0}).map(u=>e(ft,{key:u,modelId:u,entry:a.prices.models[u]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:a,setDraft:r,t:m})),ve=[["overview",m("tabOverview")],["quotas",m("tabQuotas")],["usage",m("tabUsage")],["pricing",m("tabPricing")],["display",m("tabDisplay")]],Se=p.status==="saving"?e("span",{className:"cm-hint"},m("saving")):p.status==="error"?e("span",{className:"cm-msg err"},m("autoSaveFailed",{message:p.error??""})):e("span",{className:"cm-hint"},p.status==="saved"?m("autoSavedAt",{time:new Date(p.at).toLocaleTimeString()}):m("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},ve.map(([u,C])=>e("button",{key:u,type:"button",role:"tab","aria-selected":String(v===u),className:"cm-tab"+(v===u?" active":""),onClick:()=>x(u)},C))),Se),Ee(l),v==="overview"?e(D,{key:"overview"},e("div",{className:"cm-cards"},B.hideTodayCost===!0?null:e(mt,{title:m("cardToday"),value:J(_(n.today,B),B),sub:m("callsTokens",{calls:n.today.calls,input:j(n.today.input),cache:j(n.today.cacheRead+n.today.cacheWrite),output:j(n.today.output)})}),e(mt,{title:m("cardMonth"),value:J(_(n.month,B),B),sub:m("callsTokens",{calls:n.month.calls,input:j(n.month.input),cache:j(n.month.cacheRead+n.month.cacheWrite),output:j(n.month.output)})}),e(mt,{title:m("cardTotal"),value:J(_(n.total,B),B),sub:m("cardTotalSub",{calls:n.total.calls})})),e("p",{className:"cm-note",key:"cards-footnote"},m("cardsFootnote")),(()=>{const u=Ua(n);return u!==null?e("p",{className:"cm-note",key:"tz-hint"},m("timezoneHint",{host:u.hostLabel,browser:u.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:m("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(a??B).showTotalWithPlan===!0,onChange:u=>{const C=a??B;C!=null&&r({...C,showTotalWithPlan:u.target.checked})}}),e("span",null,m("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},m("todaySessions")),e(Bn,{state:n,t:m})),e(Rn,{state:n,draft:a,setDraft:r,t:m}),(B.balance?.display==="settings"||B.balance?.display==="both")&&B.hideOfficialBalance!==!0?e(qn,{state:n,api:o,t:m,draft:a,setDraft:r}):null):null,v==="quotas"?e(D,{key:"quotas"},e(Gn,{state:n,api:o,t:m,draft:a,setDraft:r}),e(_n,{state:n,api:o,t:m,draft:a,setDraft:r}),e(Vn,{state:n,api:o,t:m,draft:a,setDraft:r}),e(Fn,{state:n,api:o,t:m,draft:a,setDraft:r})):null,v==="usage"?e(D,{key:"usage"},!je||(B.usage?.position??"cost")==="cost"?e(gt,{state:n,t:m,locale:k}):null,e(jn,{state:n,config:a??B,t:m}),e(Qn,{state:n,config:a??B,t:m}),e(Pn,{state:n,api:o}),e(Tn,{state:n,api:o}),e("div",null,e("h3",{className:"cm-h"},m("historyDataTitle")),e("div",{className:"cm-buttons"},w?e(D,null,e("span",{className:"cm-hint"},m("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:I,disabled:N},m("apply")),e("button",{className:"cm-btn",onClick:()=>y(!1)},m("cancel"))):e("button",{className:"cm-btn",onClick:()=>y(!0),disabled:N},m("importLegacy")),c?e(D,null,e("span",{className:"cm-hint"},m("confirmReset")),e("button",{className:"cm-btn danger",onClick:K,disabled:N},m("confirmClear")),e("button",{className:"cm-btn",onClick:()=>b(!1)},m("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>b(!0),disabled:N},m("clearAllHistory"))),e("p",{className:"cm-note"},m("legacyImportNote")))):null,v==="display"?e(D,{key:"display"},n?.secretMigration?.pending?.length>0?e(Ia,{pending:n.secretMigration.pending,t:m}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,m("languageLabel")),e("select",{className:"cm-input",value:a?.locale??"auto",onChange:u=>Z("locale",u.target.value)},e("option",{value:"auto"},m("localeAuto")),e("option",{value:"zh"},m("localeZh")),e("option",{value:"en"},m("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},m("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},m("groupGeneral")),je?e("div",{className:"cm-field"},e("label",null,m("usagePositionLabel")),e("select",{className:"cm-input",value:a?.usage?.position??"cost",onChange:u=>{a!==null&&r({...a,usage:{...a.usage??{position:"cost"},position:u.target.value}})}},e("option",{value:"cost"},m("usagePositionCost")),e("option",{value:"general"},m("usagePositionGeneral")),e("option",{value:"section"},m("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,m("positionLabel")),e("select",{className:"cm-input",value:a?.position??"dock",onChange:u=>Z("position",u.target.value)},e("option",{value:"dock"},m("positionDock")),e("option",{value:"header"},m("positionHeader")),e("option",{value:"off"},m("off")))),e("div",{className:"cm-field"},e("label",null,m("sidebarLabel")),e("select",{className:"cm-input",value:a?.sidebar===!1?"off":"on",onChange:u=>Z("sidebar",u.target.value==="on")},e("option",{value:"on"},m("sidebarOn")),e("option",{value:"off"},m("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.showSessionId===!0,onChange:u=>Z("showSessionId",u.target.checked)}),e("span",null,m("showSessionIdLabel"))),e("div",{className:"cm-grid-group"},m("groupMoney")),e("div",{className:"cm-field"},e("label",null,m("currencyLabel")),e("select",{className:"cm-input",value:a?.currency??"CNY",onChange:u=>{const C=Ln[u.target.value];C!==void 0&&a!==null&&r({...a,currency:u.target.value,...C})}},e("option",{value:"CNY"},m("currencyCny")),e("option",{value:"USD"},m("currencyUsd")),e("option",{value:"EUR"},m("currencyEur")))),e("div",{className:"cm-field"},e("label",null,m("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:a?.symbol??"",onChange:u=>Z("symbol",u.target.value)})),e("div",{className:"cm-field"},e("label",null,m("rateLabel")),oe({value:a?.exchangeRate??1,emptyMode:"ignore"},u=>Z("exchangeRate",u))),e("div",{className:"cm-field"},e("label",null,m("decimalsLabel")),oe({value:a?.decimals??2},u=>Z("decimals",Math.min(10,Math.floor(u))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.hideOfficialBalance===!0,onChange:u=>Z("hideOfficialBalance",u.target.checked)}),e("span",null,m("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.hideTodayCost===!0,onChange:u=>Z("hideTodayCost",u.target.checked)}),e("span",null,m("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},m("groupSidebar")),e("div",{className:"cm-field"},e("label",null,m("balanceDisplayLabel")),e("select",{className:"cm-input",value:a?.balance?.display??"both",onChange:u=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5},display:u.target.value}})}},...De(m))),e("div",{className:"cm-field"},e("label",null,m("refreshIntervalLabel")),oe({value:a?.balance?.refreshMinutes??5},u=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(u)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.balance?.showProgressBar===!0,onChange:u=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:u.target.checked}})}}),e("span",null,m("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,m("balanceBudgetCapLabel")),oe({value:a?.balance?.budgetCap??""},u=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:u>0?u:null}})}),e("span",{className:"cm-hint"},m("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,m("barDirectionsTitle")),["balance","budget","go","plan"].map(u=>e("div",{className:"cm-dir-row",key:u},e("span",{className:"cm-dir-label"},m("barDirection_"+u)),e("select",{className:"cm-input",value:a?.barDirections?.[u]??(u==="balance"?"remaining":"used"),onChange:C=>{if(a===null)return;const R={balance:"remaining",budget:"used",go:"used",plan:"used"};r({...a,barDirections:{...a.barDirections??R,[u]:C.target.value}})}},e("option",{value:"remaining"},m("barDirectionRemaining")),e("option",{value:"used"},m("barDirectionUsed"))))),e("span",{className:"cm-hint"},m("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,m("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:a?.customBalance?.display??B.customBalance?.display??"both",onChange:u=>{a!==null&&r({...a,customBalance:{...a.customBalance??B.customBalance??{},display:u.target.value}})}},...De(m))),e("div",{className:"cm-field"},e("label",null,m("customBalanceRefreshInterval")),oe({value:a?.customBalance?.refreshMinutes??B.customBalance?.refreshMinutes??15},u=>{a!==null&&r({...a,customBalance:{...a.customBalance??B.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(u)))}})})),e("div",{className:"cm-field"},e("label",null,m("goQuotaDisplayLabel")),e("select",{className:"cm-input",value:a?.goQuota?.display??"both",onChange:u=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:""},display:u.target.value}})}},...De(m))),e("div",{className:"cm-field"},e("label",null,m("goMainLabel")),e("select",{className:"cm-input",value:a?.goQuota?.main??"rolling",onChange:u=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling"},main:u.target.value}})}},e("option",{value:"rolling"},m("goWindowRolling")),e("option",{value:"weekly"},m("goWindowWeekly")),e("option",{value:"monthly"},m("goWindowMonthly")))),e("div",{className:"cm-field"},e("label",null,m("goQuotaRefreshIntervalLabel")),e("div",{className:"cm-range-row"},e("input",{className:"cm-range",type:"range",min:"1",max:"60",step:"1",value:Math.min(60,Math.max(1,Math.floor(Number(a?.goQuota?.refreshMinutes)||15))),onChange:u=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:""},refreshMinutes:Math.min(60,Math.max(1,Math.floor(Number(u.target.value)||15)))}})}}),e("span",{className:"cm-range-value"},`${Math.min(60,Math.max(1,Math.floor(Number(a?.goQuota?.refreshMinutes)||15)))} ${m("goQuotaRefreshMinutesUnit")}`))),e("div",{className:"cm-field"},e("label",null,m("goQuotaKeyLabel"))),e(Me,{target:"goQuota",configured:B.goQuota?.keyConfigured===!0,source:B.goQuota?.keySource,t:m,api:o,placeholder:"sk-…"}),e("div",{className:"cm-grid-group"},m("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.quotaStrip?.enabled===!0,onChange:u=>{a!==null&&r({...a,quotaStrip:{...a.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:u.target.checked,promptSeen:!0}})}}),e("span",null,m("quotaStripEnable")))),a?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([u,C])=>e("label",{key:u,className:"cm-check"},e("input",{type:"checkbox",checked:a.quotaStrip[u]!==!1,onChange:R=>{a!==null&&r({...a,quotaStrip:{...a.quotaStrip,[u]:R.target.checked}})}}),e("span",null,m(C)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},m("quotaStripNote"))),e("div",{className:"cm-grid-group"},m("groupCorner")),e("div",{className:"cm-field"},e("label",null,m("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.corner?.enabled===!0,onChange:u=>{a!==null&&r({...a,corner:{...a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:u.target.checked}})}}),e("span",null,m("cornerEnabledLabel"))),a?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([u,C])=>e("label",{key:u,className:"cm-check"},e("input",{type:"checkbox",checked:a.corner[u]!==!1,onChange:R=>{a!==null&&r({...a,corner:{...a.corner,[u]:R.target.checked}})}}),e("span",null,m(C)))):null),e("div",{className:"cm-grid-group"},m("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.goQuota?.detail!==!1,onChange:u=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:u.target.checked}})}}),e("span",null,m("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.budget?.detail!==!1,onChange:u=>{a!==null&&r({...a,budget:{...a.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:u.target.checked}})}}),e("span",null,m("budgetDetailLabel"))))),e("p",{className:"cm-note"},m("badgeNote")))):null,v==="pricing"?e(D,{key:"pricing"},e(On,{state:n,draft:a,setDraft:r,t:m}),e("div",null,Te(M,()=>g(!M),m("priceTableTitle")),M?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},m("priceTableNote")),e("p",{className:"cm-hint"},m("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},m("deepseekMountedHeader")),ne,e(ft,{key:"__default__",modelId:m("defaultModelId"),entry:a?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:a,setDraft:r,t:m}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:m("newModelPlaceholder"),value:f,onChange:u=>A(u.target.value)}),e("button",{className:"cm-btn small",onClick:q,disabled:f.trim().length===0},m("addModel"))),(()=>{const u=a?.priceTableDisplay??B.priceTableDisplay??{},C=a?.prices?.providers??{},R=W=>Object.keys(C[W]?.models??{}).filter(ae=>u[W+":"+ae]===!0),z=Object.keys(C).filter(W=>R(W).length>0).sort((W,ae)=>W.localeCompare(ae));return z.length===0?null:z.map(W=>e("div",{key:W},e("div",{className:"cm-catalog-vendor"},(Yt[W]??W)+" · "+m("mountedSuffix")),R(W).sort().map(ae=>e(Xt,{key:W+":"+ae,provider:W,modelId:ae,entry:C[W].models[ae],draft:a,setDraft:r,t:m}))))})()):null),(()=>{const u=a?.priceOverrides??B.priceOverrides??{},C=a?.prices??B.prices,R=n.today.byProviderModel??{},z={prices:C,priceMatch:a?.priceMatch??B.priceMatch},W=Object.keys(R).filter(F=>{if(u[F]!==void 0)return!1;const V=F.indexOf(":"),fe=(V>0?F.slice(0,V):"deepseek").toLowerCase(),bt=V>0?F.slice(V+1):F;return Xe(fe,bt,z).matched!==!0}),ae=[...new Set([...W,...Object.keys(u)])],pe=n.month?.byProviderModel??{},ye=Object.keys(pe).filter(F=>{if(u[F]!==void 0)return!1;const V=F.indexOf(":"),fe=(V>0?F.slice(0,V):"deepseek").toLowerCase(),bt=V>0?F.slice(V+1):F;return Xe(fe,bt,z).matched===!0}).sort(),xe=[{value:"__local__",label:m("overrideTargetLocal")},{value:"deepseek:__default__",label:m("overrideTargetDefault")},...Object.keys(C.models??{}).map(F=>({value:"deepseek:"+F,label:"DeepSeek · "+F})),...Object.entries(C.providers??{}).flatMap(([F,V])=>Object.keys(V?.models??{}).map(fe=>({value:F+":"+fe,label:F+" · "+fe})))],Ce=(F,V)=>{if(a===null)return;const fe={...a.priceOverrides??{}};V===""?delete fe[F]:fe[F]=V,r({...a,priceOverrides:fe})};return e("div",null,e("h3",{className:"cm-h"},m("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:a?.priceMatch==="exact"?"exact":"auto",onChange:F=>Z("priceMatch",F.target.value)},e("option",{value:"auto"},m("priceMatchAuto")),e("option",{value:"exact"},m("priceMatchExact")))),e("p",{className:"cm-note"},m("priceMatchNote")),ae.length>0?e(D,null,e("h3",{className:"cm-h"},m("unmatchedTitle")),e("p",{className:"cm-hint"},m("unmatchedHint")),ae.map(F=>e("div",{key:F,className:"cm-match-row"},e("span",null,$t(F)),e("select",{className:"cm-input",value:u[F]??"",onChange:V=>Ce(F,V.target.value)},e("option",{value:""},"—"),xe.map(V=>e("option",{key:V.value,value:V.value},V.label))),u[F]!==void 0?e("button",{className:"cm-btn small",onClick:()=>Ce(F,"")},m("overrideRemove")):null))):e("p",{className:"cm-hint"},m("overrideNone")),ye.length>0?e(D,null,e("h3",{className:"cm-h"},m("matchedTitle")),e("p",{className:"cm-hint"},m("matchedHint")),ye.map(F=>e("div",{key:F,className:"cm-match-row"},e("span",null,$t(F)),e("select",{className:"cm-input",value:"",onChange:V=>{V.target.value!==""&&Ce(F,V.target.value)}},e("option",{value:""},m("matchedKeepAuto")),xe.map(V=>e("option",{key:V.value,value:V.value},V.label)))))):null)})(),e(En,{state:n,draft:a,setDraft:r,t:m}),e("div",null,e("h3",{className:"cm-h"},m("dataSync")),e("div",{className:"cm-field"},e("label",null,m("pricingCurrencyLabel")),e("select",{className:"cm-input",value:a?.pricingCurrency==="CNY"?"CNY":"USD",onChange:u=>Z("pricingCurrency",u.target.value)},e("option",{value:"USD"},m("pricingCurrencyUsd")),e("option",{value:"CNY"},m("pricingCurrencyCny"))),e("p",{className:"cm-note"},m("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},d?e(D,null,e("span",{className:"cm-hint"},m("confirmFetch")),e("button",{className:"cm-btn",onClick:E,disabled:N},m("apply")),e("button",{className:"cm-btn",onClick:()=>h(!1)},m("cancel"))):e("button",{className:"cm-btn",onClick:()=>h(!0),disabled:N},m("syncFromDocs"))),e("p",{className:"cm-note"},m("lastSync",{time:B.fetchedAt!==null?new Date(B.fetchedAt).toLocaleString():m("neverSynced")})+m("source",{source:B.priceSource==="official"?m("sourceOfficial"):m("sourceBundled")})),e("p",{className:"cm-note"},m("syncScopeNote")))):null)}const $n=["remote"];async function Zn(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(Sa);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const n=t.get("remote.costMeter");if(n===void 0)return;const a=Ha({status:"loading",error:null,state:null}),r=()=>G(H(a.getSnapshot().state?.config?.locale)),l=async(u,C)=>{const R=await n[u](...C??[]);if(R===null||typeof R!="object"||R.ok!==!0)throw new Error(R?.error?.message??r()("rpcFailed",{method:u}));return R.value};let i=!1;const d=async()=>{if(i)return;i=!0;const u=a.getSnapshot();try{const C=await l("getState");a.set({status:"ready",error:null,state:C})}catch(C){a.set({status:"error",error:C?.message??String(C),state:u.state})}finally{i=!1}};t.effect(()=>t.on("connection/reset",()=>{d()}),"cost-meter: reconnect reload");const h=setInterval(()=>{document.hidden||d()},6e4);t.effect(()=>()=>{clearInterval(h)},"cost-meter: poll timer");const c=()=>{document.visibilityState==="visible"&&d()};document.addEventListener("visibilitychange",c),t.effect(()=>()=>{document.removeEventListener("visibilitychange",c)},"cost-meter: visibility reload");const b={reload:d,updateConfig:async u=>{const C=await l("updateConfig",[u]);return a.set({status:"ready",error:null,state:C}),C},fetchPrices:async()=>{const u=await n.fetchPrices();if(u===null||typeof u!="object"||u.ok!==!0)throw new Error(u?.error?.message??r()("rpcSyncFailed"));return u.value.state!==void 0&&a.set({status:"ready",error:null,state:u.value.state}),u.value},resetHistory:async()=>{const u=await l("resetHistory");return a.set({status:"ready",error:null,state:u}),u},importLegacyHistory:async()=>{const u=await n.importLegacyHistory();if(u===null||typeof u!="object"||u.ok!==!0)throw new Error(u?.error?.message??u?.value?.message??r()("legacyImportFailed",{message:"RPC failed"}));return u.value.state!==void 0&&a.set({status:"ready",error:null,state:u.value.state}),u.value},getDaySessions:async u=>l("getDaySessions",[u]),getTopSessions:async(u,C,R)=>l("getTopSessions",[u,C,R]),refreshBalance:async()=>{const u=await n.refreshBalance();if(u===null||typeof u!="object"||u.ok!==!0)throw new Error(u?.error?.message??r()("rpcBalanceFailed"));return u.value.state!==void 0&&a.set({status:"ready",error:null,state:u.value.state}),u.value},refreshGoQuota:async()=>{const u=await n.refreshGoQuota();if(u===null||typeof u!="object"||u.ok!==!0)throw new Error(u?.error?.message??r()("rpcSyncFailed"));return u.value.state!==void 0&&a.set({status:"ready",error:null,state:u.value.state}),u.value},refreshGatewayQuota:async(u=null)=>{const C=u==null?await n.refreshGatewayQuota():await n.refreshGatewayQuota(u);if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??r()("rpcSyncFailed"));return C.value.state!==void 0&&a.set({status:"ready",error:null,state:C.value.state}),C.value},refreshCustomBalance:async(u=null)=>{const C=u==null?await n.refreshCustomBalance():await n.refreshCustomBalance(u);if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??r()("rpcSyncFailed"));return C.value.state!==void 0&&a.set({status:"ready",error:null,state:C.value.state}),C.value},refreshCodingPlan:async u=>{const C=await n.refreshCodingPlan(u);if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??r()("rpcSyncFailed"));return C.value.state!==void 0&&a.set({status:"ready",error:null,state:C.value.state}),C.value},setCredential:async(u,C)=>{const R=await n.setCredential(u,C);if(R===null||typeof R!="object"||R.ok!==!0)throw new Error(R?.error?.message??R?.value?.message??r()("rpcSyncFailed"));return R.value.state!==void 0&&a.set({status:"ready",error:null,state:R.value.state}),R.value},clearCredential:async u=>{const C=await n.clearCredential(u);if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??r()("rpcSyncFailed"));return C.value.state!==void 0&&a.set({status:"ready",error:null,state:C.value.state}),C.value}};d();const w=t.get("slots");if(w===void 0)return;const y=()=>({hooks:{cost:a},api:b}),f=()=>({gen:0,dispose:null}),A=(u,C,R,z,W=!0)=>{u.dispose!==null&&(u.dispose(),u.dispose=null),u.gen+=1;const ae=u.gen;W&&w.inject(C,()=>{if(u.gen!==ae)return;const pe=typeof R=="function"?R():w.register(R,z);if(u.gen!==ae){pe();return}return u.dispose=pe,()=>{u.dispose===pe&&(u.dispose=null),pe()}})},N=f(),P=u=>{const C=u==="header"?"conversation.session.header.actions":"conversation.composer.dock";A(N,C,u==="header"?{name:C,id:"cost-meter",order:-5,inject:y}:{name:C,id:"cost-meter",order:5,inject:y},u==="header"?Qa:qa,u!=="off")},M=f(),g=u=>{A(M,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:y},An,u)},v=f(),x=u=>{A(v,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:y},Xa,u)};w.inject("conversation.input.dock",()=>w.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:y},vn)),w.inject("sidebar.footer.action",()=>w.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:y},xn)),w.inject("sidebar.footer.action",()=>w.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:y},Cn));const p=f(),S=u=>{A(p,"sidebar.footer.action",()=>w.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:y},en),null,u)};window.cmPeakAlertPreview=u=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(ct,{detail:{kind:u==="offpeak"?"offpeak":"peak"}}))};const T=f(),L=u=>{A(T,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:u==="en"?Ne.en.sectionLabel:Ne.zh.sectionLabel,inject:y},Jn,!0)},U=f(),k=u=>{A(U,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:y},gt,u)},m=f(),B=(u,C)=>{A(m,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:C==="en"?Ne.en.usageSectionLabel:Ne.zh.usageSectionLabel,inject:y},gt,u)};let E=null,K=null,I=null,Z=null,q=null,ne=null;const ve=()=>{const u=a.getSnapshot().state,C=u?.config?.position??"dock",R=u?.config?.sidebar!==!1&&u?.config?.hideTodayCost!==!0,z=u?.config?.balance?.display??"both",W=(z==="sidebar"||z==="both")&&u?.config?.hideOfficialBalance!==!0,ae=R||W,pe=u?.config?.corner?.enabled===!0,ye=H(u?.config?.locale),xe=u?.config?.usage?.position??"cost";C!==E&&(P(C),E=C),ae!==K&&(g(ae),K=ae),pe!==I&&(x(pe),I=pe);const Ce=u?.config?.peakEnabled===!0;Ce!==ne&&(S(Ce),ne=Ce),ye!==Z&&(L(ye),Z=ye),xe!==q?(je&&(k(xe==="general"),B(xe==="section",ye)),q=xe):je&&xe==="section"&&ye!==Z&&B(!0,ye)};ve();const Se=a.subscribe(ve);return()=>{Se()}}return Ve.apply=Zn,Ve.inject=$n,yt.exports}});
2
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:ht=>{var yt={exports:{}},Ve=yt.exports;Object.defineProperty(Ve,Symbol.toStringTag,{value:"Module"});const Re=ht("react"),{Tooltip:X}=ht("@deepseek-ai/dsh-client-ui-primitives"),je=!1,na=["/* dsh-cost-meter: 会话费用徽章与设置页 */",".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{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-foot-rail:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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-corner-chip:hover{background:var(--dsw-alias-interactive-bg-hover)}",".cm-corner-chip.warn{color:var(--dsw-alias-state-warn-primary)}",".cm-corner-chip.over{color:var(--dsw-alias-state-error-primary)}",".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:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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{color:var(--dsw-alias-state-warn-primary)}",".cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}",".cm-qchip.over{color:var(--dsw-alias-state-error-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(0.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:translateX(-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 rgba(0,0,0,.18);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{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:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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:hover{background:var(--dsw-alias-interactive-bg-hover)}",".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:0.88;background:var(--dsw-alias-state-business-primary)}",".cm-btn.danger{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-msg.err{color:var(--dsw-alias-state-error-primary)}",".cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}",".cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1);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 rgba(0,0,0,.22);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{from{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}","@keyframes cm-peak-alert-in-center{from{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-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-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}",".cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}",".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{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3));border-color:transparent}",".cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3));border-color:transparent}",".cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3));border-color:transparent}",".cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary);border-color:transparent}",".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:translateX(-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-strip.peak .cm-peak-chip{color:#ff9800}",".cm-peak-strip.off .cm-peak-chip{color:var(--dsw-alias-state-business-primary)}",".cm-peak-strip.weekend .cm-peak-chip{color:#34a853}",".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:translateX(-50%);transition:left .4s ease;z-index:2;border-radius:2px}",'.cm-peak-classic-marker::after{content:"";position:absolute;top:-7px;left:50%;transform:translateX(-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-classic.peak .cm-peak-classic-chip{color:#ff9800}",".cm-peak-classic.off .cm-peak-classic-chip{color:var(--dsw-alias-state-business-primary)}",".cm-peak-classic.weekend .cm-peak-classic-chip{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.peak .cm-peak-rail-label{color:#ff9800}",".cm-peak-rail.off .cm-peak-rail-label{color:var(--dsw-alias-state-business-primary)}",".cm-peak-rail.weekend .cm-peak-rail-label{color:#34a853}",".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.peak .cm-peak-rail-classic-label{color:#ff9800}",".cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}",".cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}",".cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{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}",".cm-mstats-bar.cost{background:#ff9800;border-radius:999px}",".cm-mstats-bar.hit{background:#34a853;border-radius:999px}",".cm-mstats-bar.value{background:#a142f4;border-radius:999px}",".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{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}",".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{border-radius:0 999px 999px 0}",".cm-bbox-bar.segments.rev .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}",".cm-bbox-bar.segments.rev .cm-bbox-fill:last-child{border-radius:0 999px 999px 0}",".cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}",".cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child{border-radius:0 999px 999px 0}",".cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}",".cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 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-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}",".cm-bal-link{flex:none;display:inline-flex;align-items:center;padding:1px 5px;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{background:var(--dsw-alias-state-warn-primary)}",".cm-bbox.over .cm-bbox-fill{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-rail{color:var(--dsw-alias-state-warn-primary)}",".cm-bbox.over .cm-bbox-rail{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-section.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}",".cm-bbox-section.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}",".cm-bbox-section.warn .cm-bbox-fill{background:var(--dsw-alias-state-warn-primary)}",".cm-bbox-section.over .cm-bbox-fill{background:var(--dsw-alias-state-error-primary)}",".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%,100%{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-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.warn .cm-bbox-label,.cm-mm-row.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}",".cm-mm-row.over .cm-bbox-label,.cm-mm-row.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}",".cm-mm-row.warn .cm-bbox-fill{background:var(--dsw-alias-state-warn-primary)}",".cm-mm-row.over .cm-bbox-fill{background:var(--dsw-alias-state-error-primary)}",".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-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}",".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:wrap}",".cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:1 1 100%;min-width:0;max-width:100%;width:auto}",".cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0}","@media (max-width:640px){.cm-cards{grid-template-columns:1fr}.cm-grid{grid-template-columns:1fr}.cm-budget-controls{grid-template-columns:1fr}}"].join(`
3
+ `),kt="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(kt)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=kt,t.textContent=na,document.head.appendChild(t)}const Se={zh:{sessionCostTitle:"本会话费用(按每次调用实际时刻精确计费)",sessionDetailTokens:"输入 {input} · 缓存 {cache} · 输出 {output}",sessionDetailCache:"缓存:读 {read} · 写 {write}(写入按命中价计费)",cost:"费用 {amount}",sessionLine:"本会话 {amount} · 输入 {input} · 缓存 {cache} · 输出 {output}",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 余额",customBalanceMultiNote:"支持配置多个自定义提供商(最多 8 条),每条独立的请求与解析规则、独立开关与显示位置、独立刷新间隔;升级前的单条配置已自动迁移为第 1 条。",customBalanceAdd:"添加配置",aliyunBalanceAdd:"添加千问 / 阿里云余额",aliyunBalanceNote:"查询阿里云中国站资金账户可用金,按接口币种显示。使用 RAM AccessKey(需 bss:DescribeBillingAccount 权限),不是千问模型 API Key;共享同一组阿里云凭据。前两项必填,Security Token 仅 STS 临时凭据需要。密钥只存入凭据库。",customBalanceRemove:"删除",customBalanceEmpty:"尚未配置自定义 Provider 余额,点击「添加配置」新建。",customBalanceConfigNote:"配置自定义 Provider 的余额查询请求与解析规则。请求头支持 {{ENV_VAR}} 占位符,从 DSH 凭据库或环境变量解析;extract 规则支持点路径、数字常量与 add / subtract / divide 运算(NewApi 等 quota 端点用 divide 按 500000 换算美元)。",customBalanceLabelZh:"中文名称",customBalanceLabelEn:"英文名称",customBalanceUrl:"请求 URL",customBalanceMethod:"请求方法",customBalanceHeaders:"请求头 (JSON)",customBalanceExtract:"解析规则 (JSON)",customBalanceDisplayLabel:"自定义余额显示位置",customBalanceRefreshInterval:"刷新间隔 (分钟)",customBalanceUnitLabel:"余额币种",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:"启用",customBalanceOpenConfig:"展开配置",customBalanceCollapseConfig:"收起配置",customBalanceLine:"剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}",customBalanceRemaining:"剩余 {amount}",refreshCustomBalance:"刷新自定义余额",customBalanceRefreshFailed:"自定义余额刷新失败:{message}",goQuotaTitle:"OpenCode Go 订阅额度",goQuotaRowLabel:"Go",goWindowRolling:"滚动 5 小时",goWindowWeekly:"本周",goWindowMonthly:"本月",goResetAt:"重置:{time}",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:"未查询额度",enableGoQuota:"启用 OpenCode Go 额度",codingPlansTitle:"Coding Plan 额度",codingPlansNote:"按厂商查询 coding plan 订阅额度(各家独立开关与凭据)。凭据只发送到对应厂商的官方端点;Key 留空时按环境变量与 CLI 登录态自动发现。",codingPlansOpen:"展开 Coding Plan 额度配置",codingPlansCollapse:"折叠 Coding Plan 额度",codingPlansCollapsedHint:"默认收起;展开后可为各家启用、填 Key 并查询额度,展开/收起状态会被记住。",codingPlanAnthropic:"Anthropic(Claude Pro/Max)",codingPlanZai:"Z.ai / 智谱 GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"打开 DeepSeek 充值页(platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) 周额度",enableCodingPlan:"启用额度查询",codingPlanDisplayLabel:"显示位置",codingPlanDisplayNote:"选「主页面侧边栏 / 两者」后,该厂商额度以图框卡片常驻侧边栏(与 Go 额度/余额同款,收起窄栏显示百分比)。",codingPlanKeyLabel:"API Key(可选,留空自动发现)",codingPlanRefreshIntervalLabel:"刷新间隔(分钟)",refreshCodingPlan:"刷新",codingPlanNotQueried:"未查询额度",gatewayQuotaTitle:"CLIProxyAPI 网关额度",gatewayQuotaNote:"只读查询网关 Provider 额度;Management Key 仅写入凭据库。",gatewaySourceAdd:"添加来源",gatewaySourceRemove:"删除来源",gatewaySourceEmpty:"尚未配置网关来源",gatewaySourceEnabled:"启用来源",gatewaySourceLabel:"来源名称",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"显示位置",gatewaySourceAllowlist:"允许的 Host",gatewaySourceCredential:"Management Key(只写)",gatewaySourceStatus:"状态",gatewaySourceUnsupported:"不支持的 Provider",gatewaySourceUnknown:"未知",gatewaySourceNoAccounts:"未发现账号",gatewaySourceRefreshing:"刷新中…",gatewaySourceFetchedAt:"抓取于 {time}",codingPlanDisabledNote:"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。",goQuotaDisabledNote:"未启用额度。开启后将读取 OpenCode Go 订阅额度(滚动 5 小时 / 本周 / 本月)并显示在侧边栏图框、设置页与右下角;没有 Go 订阅时会在这里提示原因。",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:"周末全谷",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:"侧边栏显示",sidebarStyleLabel:"侧边栏进度条样式",sidebarStyleStandard:"标准",sidebarStyleCompact:"紧凑(两列)",restorePriceMatches:"恢复已移除的模型 ({count})",removePriceMatchHint:"移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按自动匹配规则计价。",groupCorner:"右下角角标",groupDetail:"图框详细信息",catalogTitle:"拓展价格表",catalogNote:"内置各厂商、按模型家族分类的参考价格目录(只读)。挂载 = 把条目复制进上方可编辑价格表并参与计费;DeepSeek 模型可取消挂载(回退默认价,目录中仍可重新挂载)。",catalogOpen:"展开拓展价格表",catalogCollapse:"收起拓展价格表",mountBtn:"挂载",unmountBtn:"取消挂载",mountedTag:"已挂载",catalogUnpriced:"未核价",catalogDeepseekNote:"DeepSeek 模型支持峰谷两档;取消挂载后按默认价计费且不再被自动匹配命中。",modelStatsTitle:"按模型统计(token 与费用)",modelStatsToday:"今日",modelStatsHistory:"近 90 天",modelStatsCostH:"费用排行",modelStatsTokensH:"Token 消耗",modelStatsHitH:"缓存命中率",modelStatsHitUnreported:"未上报?",modelStatsHitUnreportedTip:"该模型累计多次长上下文调用而缓存命中恒为 0:大概率是中转/代理层剥掉了用量里的缓存字段(或中转请求导致缓存真实未命中),命中率无法统计,且金额按全未命中价计(为上界)。直连官方 API 可恢复准确的缓存命中与更低的金额。",modelStatsValueH:"性价比 · 每美元 token 数",modelStatsInput:"输入",modelStatsCache:"缓存",modelStatsOutput:"输出",modelStatsEmpty:"该时段暂无用量数据。",modelStatsBlended:"综合单价 {price}/M",modelStatsNote:"口径:缓存命中率 = 缓存读 ÷ (缓存读 + 非缓存输入);「未上报?」= 用量疑似未含缓存字段(常见于中转/代理链路),命中率无法统计且金额按全未命中价计(上界);综合单价 = 费用 ÷ 总 token × 1M(USD/M tokens);性价比 = 总 token ÷ 费用,越高越好;费用为账本按每次调用实际时刻计费的美元值。",modelStatsLegacy:"未分模型(早期数据 · 按当时记录计费)",sessionLineSplit:"本会话 {amount}(API)· Plan 等值 {planAmount} · 输入 {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%/满窗取可信采样段差分(短段波动大,标注「精度受限」)。5 小时窗滚动,周/月按本地日历。",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 照常统计、费用按 0 计,历史金额即时归零。写入后该行转入上方手动指定区。",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",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:"千问 Token Plan 无 API 额度查询端点(额度仅控制台可见):按官方 Credits 抵扣率由本地账本估算当前计费周期用量,实际消耗以控制台为准;内置表覆盖的模型自动折算,其余模型不计入,可在上方手动指定抵扣率。",scnetPlanCreditsLabel:"月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)",scnetPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",scnetLocalNote:"SCNet 无 API 额度查询端点:按官方 Credits 抵扣表(2026-08-11 生效)由本地账本估算当前计费周期用量,实际消耗以控制台账单为准;抵扣表覆盖的模型自动折算,其余模型不计入。",volcengineAccessKeyIdLabel:"火山引擎 AccessKey ID",volcengineSecretAccessKeyLabel:"火山引擎 SecretAccessKey",volcengineNote:"火山方舟管控面需 AK/SK 签名(非 ARK_API_KEY Bearer):在火山引擎控制台 IAM 创建子用户并授予 ArkReadOnlyAccess + BillingCenterReadOnlyAccess,填写 AccessKeyID 与 SecretAccessKey;也可在环境变量导出 VOLC_ACCESSKEY / VOLC_SECRETKEY 自动发现(官方 SDK 约定);凭据仅发往 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} 次",cardsFootnote:"口径说明:金额为最近一次落盘快照(2 秒防抖;正常关闭会先强制落盘再退出),与官方实时账单存在分钟级时差属预期;tokens 列为输入+输出+缓存+推理的合计——推理 tokens 由 API 单独上报且不计费(官方账单将其并入「输出」列展示),对账请以金额为准。",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:"会话徽章为按每次调用实际时刻精确计费(含峰谷档位;峰谷时代分界 2026-08-16 16:00 UTC 之前按当时基础价),与账本当日/月度/累计同口径。输入/缓存/输出 token 分开统计,缓存读写按命中价计费。",priceTableTitle:"价格表(美元 / 1M tokens)",pricingCurrencyLabel:"官方价格币种",pricingCurrencyUsd:"美元(英文官方页)",pricingCurrencyCny:"人民币(中文官方页)",pricingCurrencyNote:"决定「从官方文档同步价格」抓取哪个语言的官方页。切换并同步后,历史账目会按新价目整体重算(日志覆盖不全的会话保持原口径),历史与官方账单同基准;重算在后台进行,完成后有提示。",priceTableNote:"「谷时/峰时」为峰谷计价生效后的价格;分界 2026-08-16 16:00 UTC 之前的调用按当时基础价(legacyBase)计费;缓存写入按缓存命中价格计费(与官方规则一致)。无缓存折扣的模型(如 Anthropic/Gemini 等)可只填输入与输出价,命中价自动取未命中价。所有设置修改后自动保存。",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} · Input {input} · Cache {cache} · Output {output}",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:"Budget is disabled. Once enabled, this panel shows the budget limit, the amount used and the used percentage (converted to the display currency); the period can be today / this month / all time / a custom date 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",customBalanceMultiNote:"Configure multiple custom providers (up to 8): each entry has its own request & extract rules, enable switch, display position and refresh interval; your previous single entry was migrated to #1 automatically.",customBalanceAdd:"Add entry",aliyunBalanceAdd:"Add Qianwen / Alibaba Cloud balance",aliyunBalanceNote:"Queries available funds for an Alibaba Cloud China account in the returned currency. Uses shared RAM AccessKey credentials with bss:DescribeBillingAccount permission, not a Qianwen model API key. The first two fields are required; Security Token is only for temporary STS credentials. Secrets stay in the credential store.",customBalanceRemove:"Remove",customBalanceEmpty:'No custom provider balance configured yet — click "Add entry" to create one.',customBalanceConfigNote:"Configure the balance query request and extract rules. Headers support {{ENV_VAR}} placeholders resolved from DSH credentials or environment variables; extract rules accept dot paths, numeric constants, and add / subtract / divide operations (use divide with 500000 for NewApi-style quota endpoints).",customBalanceLabelZh:"Chinese name",customBalanceLabelEn:"English name",customBalanceUrl:"Request URL",customBalanceMethod:"HTTP method",customBalanceHeaders:"Headers (JSON)",customBalanceExtract:"Extract rules (JSON)",customBalanceDisplayLabel:"Custom balance display",customBalanceRefreshInterval:"Refresh interval (minutes)",customBalanceUnitLabel:"Balance currency",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:"Values support {{VAR_NAME}} placeholders resolved from the DSH credential store or env, never written to disk. The name follows <ROUTE>_API_KEY, where <ROUTE> is the Models-page Provider ID uppercased with non-alphanumerics replaced by underscores, e.g. openai→OPENAI_API_KEY, abc23-d→ABC23_D_API_KEY; sharing a name shares the same 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",customBalanceOpenConfig:"Expand config",customBalanceCollapseConfig:"Collapse config",customBalanceLine:"Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}",customBalanceRemaining:"Remaining {amount}",refreshCustomBalance:"Refresh custom balance",customBalanceRefreshFailed:"Custom balance refresh failed: {message}",goQuotaTitle:"OpenCode Go subscription quota",goQuotaRowLabel:"Go",goWindowRolling:"Rolling 5h",goWindowWeekly:"Weekly",goWindowMonthly:"Monthly",goResetAt:"Resets: {time}",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 are still stored in plaintext in the local ledger and could not be migrated automatically. Export the matching environment variables and restart:",budgetDetailLabel:"Budget box details",refreshGoQuota:"Refresh quota",goQuotaNotQueried:"Quota not queried",enableGoQuota:"Enable OpenCode Go quota",codingPlansTitle:"Coding plan quotas",codingPlansNote:"Query coding plan subscription quotas per vendor (independent enable switch and credentials per vendor). Credentials are only sent to the vendor's official endpoint; leave the key empty to auto-detect from environment variables and CLI logins.",codingPlansOpen:"Expand Coding Plan quotas",codingPlansCollapse:"Collapse Coding Plan quotas",codingPlansCollapsedHint:"Collapsed by default; expand to enable providers, enter keys and query quotas. The open/closed state is remembered.",codingPlanAnthropic:"Anthropic (Claude Pro/Max)",codingPlanZai:"Z.ai / Zhipu GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"Open DeepSeek top-up page (platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) weekly quota",enableCodingPlan:"Enable quota queries",codingPlanDisplayLabel:"Display position",codingPlanDisplayNote:`With "Main sidebar / Both" selected, this vendor's quota shows as a card in the sidebar (same box style as the Go quota / balance; the collapsed rail shows percentages).`,codingPlanKeyLabel:"API key (optional; empty = auto-detect)",codingPlanRefreshIntervalLabel:"Refresh interval (minutes)",refreshCodingPlan:"Refresh",codingPlanNotQueried:"Quota not queried",gatewayQuotaTitle:"CLIProxyAPI gateway quotas",gatewayQuotaNote:"Read-only gateway provider quotas; management keys are write-only.",gatewaySourceAdd:"Add source",gatewaySourceRemove:"Remove source",gatewaySourceEmpty:"No gateway source configured",gatewaySourceEnabled:"Enable 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",gatewaySourceRefreshing:"Refreshing…",gatewaySourceFetchedAt:"fetched {time}",codingPlanDisabledNote:"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.",goQuotaDisabledNote:"Quota disabled. Enable it to read the OpenCode Go subscription quota (rolling 5h / weekly / monthly) and show it in the sidebar box, Settings page and bottom-right corner; if you have no Go subscription, the reason will be shown here.",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",weekendRuleNote:"From Aug 23, 2026 00:00 (Beijing time), weekends (Saturday & Sunday) are billed entirely at off-peak prices; charges before that still follow the previous rules.",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",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:"A built-in, read-only reference catalog grouped by vendor and model family. Mounting copies an entry into the editable price table above so it is used for billing; DeepSeek models can be unmounted (they fall back to the default price and can be re-mounted here).",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)",modelStatsToday:"Today",modelStatsHistory:"Last 90 days",modelStatsCostH:"Cost ranking",modelStatsTokensH:"Token usage",modelStatsHitH:"Cache hit rate",modelStatsHitUnreported:"unreported?",modelStatsHitUnreportedTip:"This model has many long-context calls but zero cache hits: most likely a relay/proxy strips the cache fields from usage (or the relay genuinely breaks the prefix cache). The hit rate cannot be computed and the cost is priced as all-cache-miss (an upper bound). Connecting directly to the official API restores accurate cache hits and lower costs.",modelStatsValueH:"Value · tokens per USD",modelStatsInput:"Input",modelStatsCache:"Cache",modelStatsOutput:"Output",modelStatsEmpty:"No usage data for this period.",modelStatsBlended:"blended {price}/M",modelStatsNote:'Cache hit rate = cache reads ÷ (reads + non-cached input); "unreported?" = usage carries no cache fields (common behind relays), cost priced as all-miss (upper bound); blended = cost ÷ tokens × 1M; value = tokens ÷ cost (higher better). Costs are USD as billed.',billingClassLabel:"Billing class",billingClassPlan:"Plan subscription",modelStatsLegacy:"Unattributed (early data · billed as recorded)",sessionLineSplit:"This session {amount} (API) · Plan equiv. {planAmount} · 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:'Scope: amounts are catalog-price equivalents — plans consume quota, budget counts API only. Estimates cover dsh-made calls only; server "used %" covers the whole account. Per-1%/full-window from trustworthy sample deltas (short segments fluctuate, tagged low-precision). 5h window rolling, week/month local calendar.',catalogDisplayLabel:"Show directly in Cost settings",catalogDisplayHint:"Only decides whether this model's price card appears directly in the Cost settings price table; mounting and billing are unaffected. When hidden, the mounted model stays editable inside the expanded vendor section of this catalog.",priceTableDisplayHint:"Use the per-model “Show directly in Cost settings” toggle in the extended price catalog below to choose which models appear here; DeepSeek models default to direct display, third-party models default to the catalog once mounted.",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 override → strip date/version suffix → prefix → family similarity. Unmatched DeepSeek ids fall back to the default price; other providers stay unpriced.",unmatchedTitle:"Recently seen models without a price hit",unmatchedHint:"No price entry hit under the current match mode (incl. cross-vendor fallback), or fell back to the DeepSeek default. Pick which entry each bills against (saved as a manual override); “Default price” = DeepSeek default. Local-runtime models (lmstudio / ollama / vLLM / …) are zero-cost automatically; assign an entry here to bill them.",overrideTargetDefault:"DeepSeek default price",overrideRemove:"Remove",overrideTargetLocal:"Local model (zero cost)",matchedTitle:"Models matched this month",matchedHint:"These models already auto-matched a price entry. Pick a target to re-map them, or pick “Local model (zero cost)” to mark them as local — tokens are still counted, cost is 0, and their historical amounts are zeroed immediately. Overridden rows move to the manual list above.",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)",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:"Qwen Token Plan exposes no API quota endpoint (usage is console-only): the current billing period is estimated from the local ledger using official credits rates; actual consumption is subject to the console. Models covered by the built-in table are converted automatically; others can be assigned a rate above.",scnetPlanCreditsLabel:"Monthly credits quota (Basic 60,000 / Standard 240,000 / Pro 600,000)",scnetPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",scnetLocalNote:"SCNet exposes no API quota endpoint: usage for the current billing period is estimated from the local ledger using the official credits deduction table (effective 2026-08-11); actual consumption is subject to the SCNet console. Only models covered by the table are counted.",volcengineAccessKeyIdLabel:"Volcengine AccessKey ID",volcengineSecretAccessKeyLabel:"Volcengine SecretAccessKey",volcengineNote:"Volcano Ark control-plane requires AK/SK HMAC signature (not ARK_API_KEY Bearer): create an IAM sub-user with ArkReadOnlyAccess + BillingCenterReadOnlyAccess and enter AccessKeyID and SecretAccessKey; or export VOLC_ACCESSKEY / VOLC_SECRETKEY (official SDK env) for auto-discovery; credentials are only sent 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}",cardsFootnote:"Amounts reflect the latest ledger snapshot (2s debounce; clean shutdown flushes first), so minute-level lag vs the live official bill is expected. Token columns sum input+output+cache+reasoning; reasoning tokens are unbilled (the official bill folds them into output) — reconcile by amount.",timezoneHint:"Timezone notice: today/this-month key by the host's timezone {host}, which differs from this browser ({browser}) — calls after your local midnight land on the previous day (not lost). 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 subscription quotas (OpenCode Go / coding plans) as one compact strip above the input box. Enable it now? You can change this 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 the official balance / custom balance / coding-plan box in the sidebar to fetch the latest data immediately — no need to wait for the auto-refresh interval or open Settings. While refreshing the box pulses; on failure the previous value is kept and the reason appears in the hover tooltip.",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:"The session badge is billed exactly at each call's actual time (peak/off-peak tiers; calls before the 2026-08-16 16:00 UTC boundary are billed at the base prices of that era), consistent with the ledger's today/month/all-time figures. Input/cache/output tokens are counted separately; cache reads and writes are billed at the cache-hit price.",priceTableTitle:"Price table (USD / 1M tokens)",pricingCurrencyLabel:"Official price currency",pricingCurrencyUsd:"USD (English official page)",pricingCurrencyCny:"CNY (Chinese official page)",pricingCurrencyNote:'Which language of the official pricing page "Sync" fetches. After re-syncing, history is re-costed on the new table (sessions without full log coverage keep their basis); the recompute runs in the background.',priceTableNote:"Off-peak/peak prices apply after the 2026-08-16 16:00 UTC boundary; earlier calls use the legacy base prices. Cache writes bill at the hit price. Models without a cache discount need only input+output. Auto-saved.",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:'Sync scope: "Sync prices from official docs" only updates DeepSeek official prices (incl. peak/off-peak tiers). Third-party catalog prices (z-ai / Kimi / Qwen / Volcano etc.) change only per plugin release; to adjust, mount them in the extended catalog and edit, or match by model name.',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 is imported automatically once on first launch; this button re-runs it manually (e.g. after copying in old logs). Costs are estimated with the current price catalog; cleaned logs cannot be replayed, and for a session spanning the install moment its pre-install usage is not counted.",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 sa(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function F(t){return t==="zh"||t==="en"?t:sa()}function V(t){const s=t==="zh"?Se.zh:Se.en;return(o,n)=>{let a=s[o]??Se.en[o]??o;if(n)for(const r of Object.keys(n))a=a.split("{"+r+"}").join(String(n[r]));return a}}const He={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustom"};function J(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function W(t,s){return(typeof t!="number"||!Number.isFinite(t))&&J(s,"number"),t}function Ye(t,s){return typeof t!="string"&&J(s,"string"),t}const Ue=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function oa(t,s){return typeof t!="boolean"&&J(s,"boolean"),t}function qe(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const n of Object.keys(t)){const a=t[n];if(a===null||typeof a!="object"||Array.isArray(a))continue;const r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:0;o[n]={input:r(a.input),output:r(a.output),cacheRead:r(a.cacheRead),cacheWrite:r(a.cacheWrite),reasoning:r(a.reasoning),cost:r(a.cost),apiCost:a.apiCost===void 0?r(a.cost):r(a.apiCost)}}return o}function la(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object"),{id:Ye(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:"",input:W(t.input,s+".input"),output:W(t.output,s+".output"),cacheRead:W(t.cacheRead,s+".cacheRead"),cacheWrite:W(t.cacheWrite,s+".cacheWrite"),reasoning:t.reasoning===void 0?0:W(t.reasoning,s+".reasoning"),calls:W(t.calls,s+".calls"),cost:W(t.cost,s+".cost"),apiCost:t.apiCost===void 0?void 0:W(t.apiCost,s+".apiCost"),byModel:qe(t.byModel,s+".byModel"),byProviderModel:qe(t.byProviderModel,s+".byProviderModel")}}function Ie(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object");const o={date:Ye(t.date,s+".date"),input:W(t.input,s+".input"),output:W(t.output,s+".output"),cacheRead:W(t.cacheRead,s+".cacheRead"),cacheWrite:W(t.cacheWrite,s+".cacheWrite"),reasoning:t.reasoning===void 0?0:W(t.reasoning,s+".reasoning"),calls:W(t.calls,s+".calls"),cost:W(t.cost,s+".cost"),apiCost:t.apiCost===void 0?void 0:W(t.apiCost,s+".apiCost"),byModel:qe(t.byModel,s+".byModel"),byProviderModel:qe(t.byProviderModel,s+".byProviderModel"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||J(s+".sessions","array"),o.sessions=t.sessions.map((n,a)=>la(n,s+".sessions["+a+"]"))),o}function wt(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object");const o={cacheHit:W(t.cacheHit,s+".cacheHit"),cacheMiss:W(t.cacheMiss,s+".cacheMiss"),output:W(t.output,s+".output")};return t.offPeak!==void 0&&(o.offPeak={cacheHit:W(t.offPeak.cacheHit,s+".offPeak.cacheHit"),cacheMiss:W(t.offPeak.cacheMiss,s+".offPeak.cacheMiss"),output:W(t.offPeak.output,s+".offPeak.output")}),t.peak!==void 0&&(o.peak={cacheHit:W(t.peak.cacheHit,s+".peak.cacheHit"),cacheMiss:W(t.peak.cacheMiss,s+".peak.cacheMiss"),output:W(t.peak.output,s+".peak.output")}),t.legacyBase!==void 0&&(o.legacyBase={cacheHit:W(t.legacyBase.cacheHit,s+".legacyBase.cacheHit"),cacheMiss:W(t.legacyBase.cacheMiss,s+".legacyBase.cacheMiss"),output:W(t.legacyBase.output,s+".legacyBase.output")}),t.legacy!==void 0&&(o.legacy=oa(t.legacy,s+".legacy")),o}function ra(t,s){const o=a=>a==null?void 0:{...a.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:a.enabled===!0,label:typeof a.label=="string"?a.label:"",labelEn:typeof a.labelEn=="string"?a.labelEn:"",display:Ue(a.display,["sidebar","settings","off"],"both"),unit:a.unit==="CNY"||a.unit==="EUR"?a.unit:"USD",refreshMinutes:typeof a.refreshMinutes=="number"&&Number.isFinite(a.refreshMinutes)?a.refreshMinutes:15,request:a.request&&typeof a.request=="object"?a.request:{url:""},extract:a.extract&&typeof a.extract=="object"?a.extract:{},allowedHosts:Array.isArray(a?.allowedHosts)?a.allowedHosts.filter(r=>typeof r=="string"):[]};(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object");const n={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const a of Object.keys(t.prices.models))n[a]=wt(t.prices.models[a],s+".prices.models."+a);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,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(a=>typeof a=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:W(t.decimals,s+".decimals"),exchangeRate:W(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((a,r)=>({start:W(a.start,s+".peakWindows["+r+"].start"),end:W(a.end,s+".peakWindows["+r+"].end")})):[],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 a={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[r,l]of Object.entries(t.priceOverrides))typeof r=="string"&&typeof l=="string"&&(a[r]=l);return a})(),priceTableDisplay:(()=>{const a={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[r,l]of Object.entries(t.priceTableDisplay))typeof r=="string"&&(a[r]=l===!0);return a})(),codingPlans:(()=>{const a={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const r of Object.keys(t.codingPlans)){const l=t.codingPlans[r];l===null||typeof l!="object"||Array.isArray(l)||(a[r]={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:"",...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 a})(),prices:{models:n,default:wt(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:W(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:Ye(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:Ue(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:Ue(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 a=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(a)?a.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:Ue(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(i=>typeof i=="string").map(i=>i.toLowerCase()).filter(i=>$e.includes(i)))]:$e,allowedHosts:Array.isArray(l.allowedHosts)?l.allowedHosts.filter(i=>typeof i=="string").slice(0,16):[],allowInsecureHttp:l.allowInsecureHttp===!0,keyVar:typeof l.keyVar=="string"?l.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(r=>r!==null&&typeof r=="object").slice(0,8).map(o).filter(Boolean);const a=o(t.customBalance);return a?[a]:[]})(),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 a=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},r=(l,i)=>a[l]==="remaining"||a[l]==="used"?a[l]:i;return{balance:r("balance","remaining"),budget:r("budget","used"),go:r("go","used"),plan:r("plan","used")}})(),planBilling:{providers:(()=>{const a={};if(t.planBilling?.providers!==null&&typeof t.planBilling?.providers=="object"&&!Array.isArray(t.planBilling.providers))for(const[r,l]of Object.entries(t.planBilling.providers))typeof r=="string"&&(l==="auto"||l==="plan"||l==="api")&&(a[r]=l);return a})(),models:(()=>{const a={};if(t.planBilling?.models!==null&&typeof t.planBilling?.models=="object"&&!Array.isArray(t.planBilling.models))for(const[r,l]of Object.entries(t.planBilling.models))typeof r=="string"&&r.length>0&&(l==="plan"||l==="api")&&(a[r]=l);return a})()}}}const he=t=>typeof t=="number"&&Number.isFinite(t)?t:null,te=t=>he(t)??0,ia={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},ca={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},vt=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function ua(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object"),{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,currency:typeof t.currency=="string"?t.currency:"",totalBalance:te(t.totalBalance),grantedBalance:te(t.grantedBalance),toppedUpBalance:te(t.toppedUpBalance)}}function Je(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&J(s,"object"),{percent:te(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function da(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object"),{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,rolling:t.rolling===void 0||t.rolling===null?null:Je(t.rolling,s+".rolling"),weekly:t.weekly===void 0||t.weekly===null?null:Je(t.weekly,s+".weekly"),monthly:t.monthly===void 0||t.monthly===null?null:Je(t.monthly,s+".monthly")}}function xt(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object"),{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,label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:te(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 ma=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),pa=new Set(["off","loading","ok","partial","stale","error"]),$e=["antigravity","claude","codex","kimi","xai","workbuddy"],Nt={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function fa(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object");const o=(l,i="")=>typeof l=="string"?l:i,n=l=>he(l),a=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{id:o(l.id),label:o(l.label),...n(l.percent)===null?{}:{percent:n(l.percent)},resetsAt:o(l.resetsAt),periodHours:n(l.periodHours),scope:o(l.scope)}:null,r=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{unit:o(l.unit,"credits"),used:n(l.used),remaining:n(l.remaining),limit:n(l.limit),fetchedAt:o(l.fetchedAt),packages:Array.isArray(l.packages)?l.packages.filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).map(i=>({id:o(i.id),label:o(i.label),used:n(i.used),remaining:n(i.remaining),limit:n(i.limit),startsAt:o(i.startsAt),resetsAt:o(i.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:pa.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:n(t.fetchedAt)??0,attemptedAt:n(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:ma.has(l.status)?l.status:"unknown",message:o(l.message),plan:o(l.plan),windows:Array.isArray(l.windows)?l.windows.map(a).filter(Boolean):[],credits:r(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,n]of Object.entries(t.providers)){if(n===null||typeof n!="object"||Array.isArray(n))continue;const a={},r={};if(n.windows!==null&&typeof n.windows=="object"&&!Array.isArray(n.windows))for(const[l,i]of Object.entries(n.windows))i===null||typeof i!="object"||Array.isArray(i)||(a[l]={percent:te(i.percent),resetsAt:typeof i.resetsAt=="string"?i.resetsAt:"",localTokens:te(i.localTokens),localCost:te(i.localCost),method:i.method==="sample"||i.method==="live"?i.method:"none",sampleAt:he(i.sampleAt),confidence:i.confidence==="high"||i.confidence==="low"?i.confidence:null,per1Tokens:he(i.per1Tokens),per1Cost:he(i.per1Cost),fullTokens:he(i.fullTokens),fullCost:he(i.fullCost),sampleCount:te(i.sampleCount)});if(n.intervals!==null&&typeof n.intervals=="object"&&!Array.isArray(n.intervals))for(const[l,i]of Object.entries(n.intervals))Array.isArray(i)&&(r[l]=i.filter(d=>d!==null&&typeof d=="object"&&!Array.isArray(d)).map(d=>({t0:te(d.t0),t1:te(d.t1),tokens:te(d.tokens),cost:te(d.cost),pct:te(d.pct),per1Tokens:te(d.per1Tokens),per1Cost:te(d.per1Cost)})));s[o]={windows:a,intervals:r}}return{generatedAt:te(t.generatedAt),providers:s}}function St(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object"),{today:Ie(t.today,s+".today"),month:Ie(t.month,s+".month"),total:Ie(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?ia:ua(t.balance,s+".balance"),goQuota:t.goQuota==null?ca:da(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?vt():xt(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,n)=>xt(o,s+".customBalances["+n+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,n)=>fa(o,s+".gatewayQuotas["+n+"]")):[],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,n])=>[o,{configured:n.configured===!0,source:typeof n.source=="string"?n.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,n)=>Ie(o,s+".history["+n+"]")):[],config:ra(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 ba(t,s){(t===null||typeof t!="object"||Array.isArray(t))&&J(s,"object");const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=St(t.state,s+".state")),o}function ie(t){return{parse:t}}const Ze=ie(St),ha=ie(t=>((t===null||typeof t!="object"||Array.isArray(t))&&J("patch","object"),t)),ye=ie(ba),ya=ie(t=>(typeof t!="string"&&J("provider","string"),t)),ka=ie(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&J("index","0-7 integer"),t}),wa=ie(t=>(typeof t!="string"&&J("date","string"),t)),va=ie(t=>((t===null||typeof t!="object"||Array.isArray(t))&&J("day","object"),t)),xa=ie(t=>(Number.isFinite(Number(t))||J("limit","number"),Number(t))),Ct=ie(t=>(typeof t!="string"&&J("sort","string"),t)),Na=ie(t=>((t===null||typeof t!="object"||Array.isArray(t))&&J("topSessions","object"),t)),At=ie(t=>(typeof t!="string"&&J("target","string"),t)),Sa=ie(t=>(typeof t!="string"&&J("value","string"),t)),Ca={package:"dsh-cost-meter",descriptors:[{id:"dsh-cost-meter#costMeter/getState",service:"costMeter",namespace:"costMeter",method:"getState",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#CostState",schema:Ze}},{id:"dsh-cost-meter#costMeter/updateConfig",service:"costMeter",namespace:"costMeter",method:"updateConfig",invocation:{kind:"direct"},parameters:[{name:"patch",wire:"patch",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#ConfigPatch",schema:ha}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#CostState",schema:Ze}},{id:"dsh-cost-meter#costMeter/fetchPrices",service:"costMeter",namespace:"costMeter",method:"fetchPrices",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/refreshBalance",service:"costMeter",namespace:"costMeter",method:"refreshBalance",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/refreshGoQuota",service:"costMeter",namespace:"costMeter",method:"refreshGoQuota",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/refreshCustomBalance",service:"costMeter",namespace:"costMeter",method:"refreshCustomBalance",invocation:{kind:"direct"},parameters:[{name:"index",wire:"index",source:"json",acceptsUndefined:!0,codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CustomBalanceIndex",schema:ka}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/refreshCodingPlan",service:"costMeter",namespace:"costMeter",method:"refreshCodingPlan",invocation:{kind:"direct"},parameters:[{name:"provider",wire:"provider",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CodingPlanProvider",schema:ya}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/refreshGatewayQuota",service:"costMeter",namespace:"costMeter",method:"refreshGatewayQuota",invocation:{kind:"direct"},parameters:[{name:"sourceId",wire:"sourceId",source:"json",acceptsUndefined:!0,codec:{mode:"strict",typeSymbol:"dsh-cost-meter#GatewayQuotaSourceId",schema:ie(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&J("sourceId","gateway source id"),t})}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/resetHistory",service:"costMeter",namespace:"costMeter",method:"resetHistory",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#CostState",schema:Ze}},{id:"dsh-cost-meter#costMeter/importLegacyHistory",service:"costMeter",namespace:"costMeter",method:"importLegacyHistory",invocation:{kind:"direct"},parameters:[],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/getDaySessions",service:"costMeter",namespace:"costMeter",method:"getDaySessions",invocation:{kind:"direct"},parameters:[{name:"date",wire:"date",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#DayKey",schema:wa}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#DayRecord",schema:va}},{id:"dsh-cost-meter#costMeter/getTopSessions",service:"costMeter",namespace:"costMeter",method:"getTopSessions",invocation:{kind:"direct"},parameters:[{name:"limit",wire:"limit",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#SessionLimit",schema:xa}},{name:"sort",wire:"sort",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#SessionSort",schema:Ct},acceptsUndefined:!0},{name:"dir",wire:"dir",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#SessionSortDir",schema:Ct},acceptsUndefined:!0}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#TopSessions",schema:Na}},{id:"dsh-cost-meter#costMeter/setCredential",service:"costMeter",namespace:"costMeter",method:"setCredential",invocation:{kind:"direct"},parameters:[{name:"target",wire:"target",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CredentialTarget",schema:At}},{name:"value",wire:"value",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CredentialValue",schema:Sa}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}},{id:"dsh-cost-meter#costMeter/clearCredential",service:"costMeter",namespace:"costMeter",method:"clearCredential",invocation:{kind:"direct"},parameters:[{name:"target",wire:"target",source:"json",codec:{mode:"strict",typeSymbol:"dsh-cost-meter#CredentialTarget",schema:At}}],result:{mode:"strict",typeSymbol:"dsh-cost-meter#FetchPricesResult",schema:ye}}]};function Aa(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 Pt(t){if(t===null||typeof t!="object")return;const s=l=>{const i=t[l];return typeof i=="number"&&Number.isFinite(i)&&i>=0?i:void 0},o=s("cacheMiss")??s("input")??0,a={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},r=s("reasoning");return r!==void 0&&(a.reasoning=r),a}function Pa(t){const s=Pt(t);if(s===void 0)return null;for(const o of["offPeak","peak","legacyBase"]){const n=Pt(t[o]);n!==void 0&&(s[o]=n)}return s}const Mt=Date.parse("2026-08-22T16:00:00Z");function Qe(t){if(!Number.isFinite(t)||t<Mt)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const n=o===6?s:s-1;return{start:Math.max(n*864e5-8*36e5,Mt),end:(n+2)*864e5-8*36e5}}function Tt(t,s,o){if(!Array.isArray(o)||o.length===0||Qe(t)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(a=>{const r=Number(a.start),l=Number(a.end);return!Number.isFinite(r)||!Number.isFinite(l)?!1:r<l?n>=r&&n<l:n>=r||n<l})}const Ma=Date.parse("2026-08-16T16:00:00Z");function Bt(t,s,o){const n=t??{cacheHit:0,cacheMiss:0,output:0},a=l=>({cacheHit:l.cacheHit,cacheMiss:l.cacheMiss,output:l.output,reasoning:l.reasoning??0});if(Number.isFinite(s)&&s<Ma){const l=n.legacyBase;return a(l===void 0?n:l)}if(o?.enabled!==!0)return a(n);const r=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(Tt(s,r,o.windows)){const l=n.peak;return a(l===void 0?n:l)}if(r!==void 0&&s>=r){const l=n.offPeak;return a(l===void 0?n:l)}return a(n)}function Rt(t,s){const o=Math.max(0,Number(t.input)||0),n=Math.max(0,Number(t.output)||0),a=Math.max(0,Number(t.cacheRead)||0),r=Math.max(0,Number(t.cacheWrite)||0),l=Math.max(0,Number(t.reasoning)||0);return(o*s.cacheMiss+n*s.output+(a+r)*s.cacheHit+l*(s.reasoning??0))/1e6}function Dt(t,s,o){const n=Number(t);if(!Number.isFinite(n)||n<0||n===0)return 0;if(s!=="CNY")return n;const a=Number(o);return!Number.isFinite(a)||a<=0?n:n/a}function ae(t,s){const o=t?.barDirections,n=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return n;const a=o[s];return a==="remaining"||a==="used"?a:n}function pe(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),n=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:n,label:n}}function ce(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",n=Number(s?.decimals),a=Math.max(0,Math.min(10,Number.isFinite(n)?Math.floor(n):2));let r=a;t>0&&t<Math.pow(10,-a)&&(r=a+2);const l=t.toFixed(r),i=l.includes(".")?l.replace(/0+$/,"").replace(/\.$/,""):l;return o+i}function $(t,s){const o=Number(s?.exchangeRate),n=t*(Number.isFinite(o)&&o>0?o:1);return ce(n,s)}function U(t){const s=Math.max(0,Number(t)||0),o=n=>n>=100?String(Math.round(n)):String(Math.round(n*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 Ce(t,s){if(typeof t!="string"||t.length===0)return null;const o=Array.isArray(s)?s.filter(N=>typeof N=="string"&&N.length>0):[];if(o.length===0)return null;const n=N=>String(N).toLowerCase().replace(/[-@]\d{4}-?\d{2}-?\d{2}$/,"").replace(/[-@]v\d+(\.\d+)*$/,""),a=o.find(N=>N===t);if(a!==void 0)return a;const r=ue(t);if(r.length===0)return null;const l=o.find(N=>ue(N)===r);if(l!==void 0)return l;let i=null,d=0;for(const N of o){const A=ue(N);if(!(A.length<4||A===r)&&r.includes(A)&&A.length>d){const P=r.indexOf(A);if(/^\d{1,2}$/.test(r.slice(P+A.length)))continue;i=N,d=A.length}}if(i!==null)return i;const h=n(t),u=o.find(N=>n(N)===h);if(u!==void 0)return u;let b=null;for(const N of o){const A=n(N);if(A.length===0||A===h)continue;const P=h.slice(A.length);if(h.startsWith(A)&&/^[-_./:]/.test(P)){if(/^\d{1,2}$/.test(P.replace(/^[-_./:]+/,"")))continue;(b===null||n(b).length<A.length)&&(b=N)}}if(b!==null)return b;const w=N=>n(N).split(/[-_./:]+/).filter(Boolean),k=w(t);if(k.length<2)return null;let p=null,C=0;for(const N of o){const A=w(N);let P=0;for(;P<k.length&&P<A.length&&k[P]===A[P];)P+=1;P<k.length&&P<A.length&&/^\d+$/.test(k[P])&&/^\d+$/.test(A[P])||P>=2&&P===A.length&&P<k.length&&k.slice(P).every(g=>/^\d{1,2}$/.test(g))||P>=2&&P<k.length&&P<A.length&&(/^\d{1,2}$/.test(k[P])&&/^[a-z]/.test(A[P])||/^\d{1,2}$/.test(A[P])&&/^[a-z]/.test(k[P]))||P>=2&&(P>C||P===C&&p!==null&&N.length<p.length)&&(p=N,C=P)}return p}const Ta=new Set(["lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),Ba=["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 Ra(t,s){if(typeof t=="string"&&Ta.has(t))return!0;const o=typeof s=="string"?s.toLowerCase():"";return Ba.some(n=>o.startsWith(n))}function Xe(t,s,o){const n=o?.prices??{},a=o?.priceMatch==="exact"?"exact":"auto",r=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 i=l,d=s;const h=r[l+":"+s];if(h==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof h=="string"&&h.length>0){const w=h.indexOf(":");if(w>0&&h.slice(w+1).length>0?(i=h.slice(0,w).trim().toLowerCase(),d=h.slice(w+1)):d=h,i==="deepseek"&&d==="__default__")return{entry:n.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}if(Ra(i,d))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(i==="deepseek"||i.includes("deepseek")){const w=n.models??{},k=w[d]!==void 0?d:a==="auto"?Ce(d,Object.keys(w)):null;if(k!==null)return{entry:w[k],priced:!0,billingMode:"deepseek-peak",matched:!0};if(a==="auto"){let p=null,C=-1,N="flat";for(const[A,P]of Object.entries(n.providers??{})){const g=P?.models??{},v=Ce(d,Object.keys(g));if(v===null||g[v]?.unpriced===!0)continue;const m=(v===d||ue(v)===ue(d)?1e3:0)+ue(v).length;m>C&&(p=g[v],C=m,N=g[v]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(p!==null)return{entry:p,priced:!0,billingMode:N,matched:!0}}return{entry:n.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}const u=n.providers?.[i]?.models??{},b=u[d]!==void 0?d:a==="auto"?Ce(d,Object.keys(u)):null;if(b!==null)return{entry:u[b],priced:u[b]?.unpriced!==!0,billingMode:"flat",matched:!0};if(a==="auto"){const w=n.models??{},k=Ce(d,Object.keys(w));if(k!==null)return{entry:w[k],priced:!0,billingMode:"deepseek-peak",matched:!0};let p=null,C=-1,N="flat";for(const[A,P]of Object.entries(n.providers??{})){if(A===i)continue;const g=P?.models??{},v=Ce(d,Object.keys(g));if(v===null||g[v]?.unpriced===!0)continue;const m=(v===d||ue(v)===ue(d)?1e3:0)+ue(v).length;m>C&&(p=g[v],C=m,N=g[v]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(p!==null)return{entry:p,priced:!0,billingMode:N,matched:!0}}if(l!=="deepseek"&&!l.includes("deepseek")&&typeof h=="string"&&h.length>0&&!h.includes(":")){const w=n.models??{},k=w[h]!==void 0?h:a==="auto"?Ce(h,Object.keys(w)):null;if(k!==null)return{entry:w[k],priced:!0,billingMode:"deepseek-peak",matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function Da(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,n=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&n===0}function Lt(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:tt(t,s).total}function La(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 z(t,s){return s!==null&&typeof s=="object"&&s.showTotalWithPlan===!0?Number(t?.cost)||0:La(t)}const Oa={go:["go","zen","opencode","opencode-go"]},Ot=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","go"];function Ea(t){const s=String(t??"").trim().toLowerCase();if(s.length===0)return null;for(const[o,n]of Object.entries(Oa))if(n.includes(s))return o;return Ot.includes(s)?s:null}function ja(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const n of Ot)n!=="go"&&o[n]?.enabled===!0&&s.add(n);return t?.goQuota?.enabled===!0&&s.add("go"),s}function Ha(t,s,o){const n=String(t??"").trim().toLowerCase();if(n.length>0&&n!=="deepseek"&&!n.includes("deepseek"))return!1;const a=ue(s);if(a.length===0)return!1;const r=o?.prices,l=r?.models??{};for(const i of Object.keys(l))if(ue(i)===a)return!1;for(const i of Object.values(r?.providers??{}))for(const d of Object.keys(i?.models??{}))if(ue(d)===a)return!0;return!1}function et(t,s,o){let n=Ea(t);if(n===null&&Ha(t,s,o)&&(n="go"),n===null)return"api";const a=o?.planBilling?.models;if(a!==null&&typeof a=="object"){const l=a[t+":"+s];if(l==="plan"||l==="api")return l;const i=a[n+":"+s];if(i==="plan"||i==="api")return i}const r=o?.planBilling?.providers?.[n];return r==="plan"||r==="api"?r:ja(o).has(n)?"plan":"api"}function tt(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows},n=Date.now(),a=t.byProviderModel??t.byModel??{};let r=0,l=0;for(const b of Object.keys(a)){const w=b.indexOf(":"),k=w>0?b.slice(0,w):"deepseek",p=w>0?b.slice(w+1):b,C=Xe(k,p,s);if(C.priced){const N=Rt(a[b],Bt(Pa(C.entry),n,{...o,enabled:C.billingMode==="deepseek-peak"&&o.enabled})),A=Dt(N,C.billingMode==="deepseek-peak"&&s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);r+=A,et(k,p,s)==="api"&&(l+=A)}}const i={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const b of Object.keys(a))i.input+=a[b].input??0,i.output+=a[b].output??0,i.cacheRead+=a[b].cacheRead??0,i.cacheWrite+=a[b].cacheWrite??0,i.reasoning+=a[b].reasoning??0;const d={input:Math.max(0,(t.input??0)-i.input),output:Math.max(0,(t.output??0)-i.output),cacheRead:Math.max(0,(t.cacheRead??0)-i.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-i.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-i.reasoning)},h=Rt(d,Bt(Aa("default",s.prices),n,o)),u=Dt(h,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return r+=u,l+=u,{total:r,api:l}}function Et(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const n of Object.keys(o)){const a=n.indexOf(":"),r=a>0?n.slice(0,a):"deepseek",l=a>0?n.slice(a+1):n;if(et(r,l,s)==="plan")return!0}return!1}function jt(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function at(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),n=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(n>0?":"+String(n).padStart(2,"0"):"")}function Ua(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const n=-new Date().getTimezoneOffset();if(n===o)return null;const a=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:a?a+" ("+at(o)+")":at(o),browserLabel:at(n)}}function qa(t){let s=t;const o=new Set;return{getSnapshot:()=>s,subscribe:n=>(o.add(n),()=>{o.delete(n)}),set:n=>{if(n!==s){s=n;for(const a of[...o])a()}}}}const{createElement:e,Fragment:j,useState:O,useEffect:oe,useRef:Ae}=Re;function Pe({target:t,configured:s,source:o,t:n,api:a,placeholder:r,disabled:l}){const[i,d]=O(""),[h,u]=O(!1),[b,w]=O(null),k=l===!0||h,p=async()=>{const N=i.trim();if(!(N.length===0||k)){u(!0),w(null);try{const A=await a.setCredential(t,N);d(""),w({kind:"ok",text:A?.message??n("credentialSave")})}catch(A){w({kind:"err",text:String(A?.message??A)})}finally{u(!1)}}},C=async()=>{if(!k){u(!0),w(null);try{const N=await a.clearCredential(t);d(""),w({kind:"ok",text:N?.message??n("credentialClear")})}catch(N){w({kind:"err",text:String(N?.message??N)})}finally{u(!1)}}};return e("div",{className:"cm-field"},e("input",{className:"cm-input",type:"password",value:i,placeholder:typeof r=="string"?r:"",disabled:k,autoComplete:"off",onChange:N=>d(N.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:p,disabled:k||i.trim().length===0},n(h?"credentialSaving":"credentialSave")),s===!0?e("button",{className:"cm-btn small",onClick:C,disabled:k},n("credentialClear")):null),e("span",{className:"cm-hint"},s===!0?n("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):n("credentialNotConfigured")),e("span",{className:"cm-hint"},n("credentialInputHint")),Ee(b))}function Ia({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 nt({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 st(t,s){const o=Ae(!1),n=Ae(""),a=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(r=>String(r??0)).join("|"):"";oe(()=>{if(!o.current){o.current=!0,n.current=a;return}if(a===""||a===n.current)return;n.current=a;const r=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(r)},[a])}function Qa(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?t.useCost(h=>h):void 0;st(t,s);const n=o?.state?.config;if(!s||!n||jt(s)+(s?.output??0)===0)return null;const a=V(F(n.locale));let r=0,l=Lt(s,n);if(n.showTotalWithPlan!==!0&&Et(s,n)){const h=tt(s,n);r=Math.max(0,h.total-h.api),r>0&&(l=h.api)}const i=jt(s),d=[a("sessionCostTitle"),a("sessionDetailTokens",{input:U(s?.input??0),cache:U((s?.cacheRead??0)+(s?.cacheWrite??0)),output:U(s?.output??0)}),a("sessionDetailCache",{read:U(s?.cacheRead??0),write:U(s?.cacheWrite??0)}),a("cost",{amount:$(l,n)}),...r>0?[a("sessionDetailPlan",{amount:$(r,n)})]:[]].join("; ");return e(X,{label:d,side:"top",delayMs:500},e("div",{className:"cm-chip"},r>0?a("costChipPlan",{amount:$(l,n)}):a("cost",{amount:$(l,n)})))}function Fa(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?t.useCost(u=>u):void 0;st(t,s);const n=o?.state?.config;if(!s||!n)return null;const a=s.input??0,r=(s.cacheRead??0)+(s.cacheWrite??0),l=s.output??0;if(a+r+l===0)return null;const i=V(F(n.locale));let d=0,h=Lt(s,n);if(n.showTotalWithPlan!==!0&&Et(s,n)){const u=tt(s,n);d=Math.max(0,u.total-u.api),d>0&&(h=u.api)}return e("div",{className:"cm-root"},d>0?i("sessionLineSplit",{amount:$(h,n),planAmount:$(d,n),input:U(a),cache:U(r),output:U(l)}):i("sessionLine",{amount:$(h,n),input:U(a),cache:U(r),output:U(l)}))}const _a={USD:"$",CNY:"¥",EUR:"€"};function ke(t,s,o){const n=typeof o=="string"?o.toUpperCase():"",a=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return ce(t,{symbol:_a[n]??a,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function Ht(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const n=Number(s?.maxBudget);return Number.isFinite(n)&&n>0?n:null}function Wa(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 n=0;for(const[a,r]of Object.entries(o)){const l=a.indexOf(":");let i=l>=0?a.slice(0,l):a;i.startsWith("llm-")&&(i=i.slice(4)),!(i!=="deepseek"&&i!=="deepseek-official")&&(n+=Number(r?.cost)||0)}return n}function Ut(t,s,o,n,a=null){const r=o==="official"?Wa(t):Number(t.today?.cost)||0;if(o==="custom"){if(Ft(s,n,a)==="USD")return r;const d=Number(s?.exchangeRate);return r*(Number.isFinite(d)&&d>0?d:1)}const l=Number(s?.exchangeRate);return r*(Number.isFinite(l)&&l>0?l:1)}function qt({remaining:t,spend:s,todayUsed:o,cap:n}){if(n===null||n<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const a=Math.max(0,Number(t)||0),r=Math.max(0,Number(s)||0),l=Math.max(0,Math.min(r,Number(o)||0)),i=Math.max(0,r-l),d=Math.max(0,Math.min(100,a/n*100)),h=Math.max(0,Math.min(100-d,l/n*100)),u=Math.max(0,Math.min(100-d-h,i/n*100));return{remainingPct:d,todayPct:h,spentPct:u,hasCap:!0,pastSpend:i,today:l}}function ot(t,s,o=null,n=null){const a=o??t.customBalance,r=Ht(s,a),l=Number(a?.remaining)||0,i=Number(a?.spend)||0,d=Ut(t,s,"custom",a,n);return{cap:r,...qt({remaining:l,spend:i,todayUsed:d,cap:r})}}function za(t,s){const o=t.balance,n=Ht(s,null),a=Number(o?.totalBalance)||0,r=Ut(t,s,"official",null),l=n!==null?Math.max(0,n-a):0;return{cap:n,...qt({remaining:a,spend:l,todayUsed:r,cap:n})}}function lt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:n,todayPct:a,spentPct:r}=s,l=[];n>0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:n+"%"}})),a>0&&l.push(e("div",{className:"cm-bbox-seg-today",style:{width:a+"%"}})),r>0&&l.push(e("div",{className:"cm-bbox-seg-spent",style:{width:r+"%"}})),l.length===0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const i=o==="used"?[...l].reverse():l;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...i)}function It(t,s,o,n,a){const r=[t("balanceBarRemaining",{amount:n})];return o.today>0&&r.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&r.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),a!==null&&a>0&&r.push(t("balanceBudgetCapLabel")+": "+s(a)),r.join(" · ")}function we(t){const[s,o]=O(!1),[n,a]=O(null);return{busy:s,err:n,run:()=>{s||typeof t!="function"||(o(!0),a(null),Promise.resolve().then(t).catch(l=>{a(l?.message??String(l))}).finally(()=>{o(!1)}))}}}const de=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function fe(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const Ga="https://platform.deepseek.com/usage";function Qt(t){return e("a",{className:"cm-bal-link",href:Ga,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},"↗")}function Ka(t){const{state:s,wide:o,api:n}=t,a=s.balance,r=V(F(s.config?.locale)),l=we(n?()=>n.refreshBalance():null);if(!a||a.status==="off")return null;if(a.status==="error")return e(X,{label:[r("balanceQueryFailed",{message:a.message||r("unknownError")}),...fe(r,l)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(l.busy?" busy":""),...de(l.busy,l.run)},o?e(j,null,r("balance")," ",e("span",{className:"cm-num"},r("queryFailed"))):"⚠"));const i=[r("balanceTitle"),r("totalBalance",{amount:ke(a.totalBalance,s.config,a.currency)}),r("grantedToppedUp",{granted:ke(a.grantedBalance,s.config,a.currency),toppedUp:ke(a.toppedUpBalance,s.config,a.currency)}),r("updatedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...fe(r,l)].join("; ");return e(X,{label:i,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(l.busy?" busy":""),...de(l.busy,l.run)},o?e(j,null,r("balance")," ",e("span",{className:"cm-num"},ke(a.totalBalance,s.config,a.currency))," ",Qt(r),s.reconcile?.ok===!1?" ⚠":""):e(nt,{size:16})))}function Va(t){const{state:s,wide:o,api:n}=t,a=s.config,r=s.balance,l=V(F(a?.locale)),i=we(n?()=>n.refreshBalance():null);if(!r||r.status!=="ok")return null;const d=za(s,a),h=ke(r.totalBalance,a,r.currency),u=k=>ke(k,a,r.currency),b=[l("balanceTitle"),It(l,u,d,h,d.cap),l("grantedToppedUp",{granted:ke(r.grantedBalance,a,r.currency),toppedUp:ke(r.toppedUpBalance,a,r.currency)}),l("updatedAt",{time:r.fetchedAt>0?new Date(r.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...fe(l,i)].join("; "),w=e(j,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},l("balance")),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},h),Qt(l)),e(lt,{segments:d,direction:ae(a,"balance")}));return e(X,{label:b,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(i.busy?" busy":""),...de(i.busy,i.run)},o?w:e("div",{className:"cm-bbox-rail cm-num"},Math.round(d.remainingPct)+"%")))}function Fe(t,s){const o=typeof t?.label=="string"?t.label:"",n=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?n||o||"Custom balance":o||n||"自定义余额"}function Ft(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const n=o?.unit??t?.customBalance?.unit;return n==="CNY"||n==="EUR"||n==="USD"?n:s?.unit==="CNY"||s?.unit==="EUR"?s.unit:"USD"}function ve(t,s,o,n){const a=Ft(s,o,n),r=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4))),l=a==="CNY"?"¥":a==="EUR"?"€":"$",i=Number(t);if(!Number.isFinite(i))return"—";let d=i.toFixed(r);return d.includes(".")&&(d=d.replace(/0+$/,"").replace(/\.$/,"")),l+d}function rt(t,s,o,n,a=null){const r=ve(t.remaining,s,t,a),l=w=>ve(w,s,t,a);if(n&&s.balance?.showProgressBar===!0){const w=ot(n,s,t,a);return[It(o,l,w,r,w.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const i=t.spend!==null?ve(t.spend,s,t,a):"—",d=t.maxBudget!==null?ve(t.maxBudget,s,t,a):"—",h=Number(s?.balance?.budgetCap),u=Number.isFinite(h)&&h>0?o("balanceBudgetCapLabel")+": "+ve(h,s,t,a):"",b=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:r,spend:i,maxBudget:d,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:r});return u?b+" · "+u:b}function Ya(t,s,o,n,a){const r=Fe(a??s.customBalance??{},F(s?.locale)),l=ve(n.remaining,s,n,a),i=ot(t,s,n,a);return{level:"ok",rail:Math.round(i.remainingPct)+"%",body:e(j,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},r),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},l)),e(lt,{segments:i,direction:ae(s,"balance")}))}}function it(t,s){const o=s?.customBalances??[],n=Array.isArray(t?.customBalances)?t.customBalances:[],a=[];return o.forEach((r,l)=>{if(r?.enabled!==!0||r.display!=="sidebar"&&r.display!=="both")return;const i=n.find(d=>d.index===l)??(n.length===1&&o.length===1?n[0]:null);a.push({index:l,entry:r,snapshot:i})}),a.length===0&&n.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&a.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),a}function Ja(t){const{state:s,wide:o,api:n}=t,a=s.config,r=V(F(a?.locale)),l=it(s,a);return l.length===0?null:e(j,null,l.map(({index:i,entry:d,snapshot:h})=>e($a,{key:"cb-"+i,state:s,wide:o,api:n,t:r,index:i,entry:d,snapshot:h})))}function $a(t){const{state:s,wide:o,api:n,t:a,index:r,entry:l,snapshot:i}=t,d=s.config;if(i==null||i.status!=="ok")return null;const h=we(n?()=>n.refreshCustomBalance(r):null),u=Ya(s,d,a,i,l),b=[rt(i,d,a,s,l),...fe(a,h)].join(" · ");return e(X,{label:b,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(u.level==="ok"?"":" "+u.level)+(o?"":" rail")+(h.busy?" busy":""),...de(h.busy,h.run)},o?u.body:e("div",{className:"cm-bbox-rail cm-num"},u.rail)))}function Za(t){const{state:s,wide:o,api:n}=t,a=s.config,r=V(F(a?.locale)),l=it(s,a);return l.length===0?null:e(j,null,l.map(({index:i,entry:d,snapshot:h})=>e(Xa,{key:"cbr-"+i,state:s,wide:o,api:n,t:r,index:i,entry:d,snapshot:h})))}function Xa(t){const{state:s,wide:o,api:n,t:a,index:r,entry:l,snapshot:i}=t,d=s.config,h=i??vt(r);if(h.status==="off")return null;const u=we(n?()=>n.refreshCustomBalance(r):null),b=Fe(l??d.customBalance??{},F(d?.locale));if(h.status==="error")return e(X,{label:[h.message||a("unknownError"),...fe(a,u)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(u.busy?" busy":""),...de(u.busy,u.run)},o?e(j,null,b," ",e("span",{className:"cm-num"},a("queryFailed"))):"⚠"));const w=ve(h.remaining,d,h,l),k=[rt(h,d,a,s,l),...fe(a,u)].join(" · ");return e(X,{label:k,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(u.busy?" busy":""),...de(u.busy,u.run)},o?e(j,null,b," ",e("span",{className:"cm-num"},w)):e(nt,{size:16})))}function en(t){const o=(t.useCost?t.useCost(p=>p):void 0)?.state;if(!o)return null;const n=o.config,a=V(F(n?.locale)),r=n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},l=o.goQuota,i=n?.goQuota?.enabled!==!1&&l?.status==="ok",d=p=>p!==null&&typeof p?.percent=="number"?Math.round(Math.max(0,Math.min(100,p.percent))):null,h=[],u=(p,C,N,A)=>{if(!p||!i)return;const P=d(C);if(P===null)return;const g=typeof C.resetsAt=="string"&&C.resetsAt.length>0?a("goResetAt",{time:new Date(C.resetsAt).toLocaleString()}):"";h.push({key:N,text:a(N)+" "+P+"%",tip:a(A)+": "+P+"%"+(g?" · "+g:""),level:P>=100?"over":P>=80?"warn":"ok"})},b=n?.goQuota?.main==="weekly"||n?.goQuota?.main==="monthly"?n.goQuota.main:"rolling",w=[b,...["rolling","weekly","monthly"].filter(p=>p!==b)],k=p=>p==="rolling"?["goRolling",l?.rolling,"goShortRolling","cornerGoRolling"]:p==="weekly"?["goWeekly",l?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",l?.monthly,"goShortMonthly","cornerGoMonthly"];for(const p of w){const[C,N,A,P]=k(p);u(r[C]===!0,N,A,P)}if(r.budget===!0){const p=n.budget??{enabled:!1,amount:100,period:"month"};if(p.enabled===!0){const C=Number(n.exchangeRate),A=(o.budgetUsed??(p.period==="day"?z(o.today,n):p.period==="all"?z(o.total,n):z(o.month,n)))*(Number.isFinite(C)&&C>0?C:1),P=Math.max(0,Number(p.amount)||0),g=P>0?Math.min(999,A/P*100):null;if(g!==null){const v=g>=100?"over":g>=80?"warn":"ok";h.push({key:"budget",text:a("budgetShort")+" "+g.toFixed(1)+"%",tip:a("budgetOf",{period:a(He[p.period]??"periodMonth")})+" · "+a("usedOf",{used:ce(A,n),amount:ce(P,n)}),level:v})}}}return h.length===0?null:e("div",{className:"cm-corner"},h.map(p=>e(X,{key:p.key,label:p.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(p.level==="ok"?"":" "+p.level)},p.text))))}function _e(t,s){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const o=(d,h)=>{const u=new Date(t);return u.setUTCDate(u.getUTCDate()+d),u.setUTCHours(h,0,0,0),u.getTime()},n=[];for(let d=-4;d<=4;d+=1)for(const h of s){const u=Number(h?.start),b=Number(h?.end);if(!Number.isFinite(u)||!Number.isFinite(b))continue;const w={at:o(d,u),intoPeak:!0},k={at:o(b<=u?d+1:d,b),intoPeak:!1};Qe(w.at)===null&&n.push(w),Qe(k.at)===null&&n.push(k)}let a=null,r=null;for(const d of n)d.at<=t&&(a===null||d.at>a.at)&&(a=d),d.at>t&&(r===null||d.at<r.at)&&(r=d);const l=Qe(t);return l!==null?r===null?null:{inPeak:!1,weekend:!0,prevAtMs:l.start,nextAtMs:r.at,nextIntoPeak:r.intoPeak}:a===null||r===null?null:{inPeak:Tt(t,void 0,s),weekend:!1,prevAtMs:a.at,nextAtMs:r.at,nextIntoPeak:r.intoPeak}}function We(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 n=Array.isArray(t.peakWindows)?t.peakWindows:[];return _e(s,n)}function ze(t){return t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function ge(t,s,o){const n=Math.max(0,t.nextAtMs-s),a=Math.max(1,Math.ceil(n/6e4)),r=Math.floor(a/60),l=a%60;return r>0?l>0?o("countdownHourMinute",{h:r,m:l}):o("countdownHoursOnly",{h:r}):o("countdownMinute",{m:a})}const ct="cm-peak-alert-preview";let _t=0;function tn(t){const s=t.useCost?t.useCost(C=>C):void 0,o=s?.state?.config,[n,a]=O(Date.now()),[r,l]=O(null),[i,d]=O(null);if(oe(()=>{const C=window.setInterval(()=>a(Date.now()),1e4);return()=>window.clearInterval(C)},[]),oe(()=>{const C=N=>{const A=N.detail?.kind==="offpeak"?"offpeak":"peak";d(A);const P=s?.state?.config;if(P?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const g=V(F(P.locale));try{new Notification(g(A==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+g("peakAlertPreviewTag"),{body:g("peakAlertBody",{time:g("countdownMinute",{m:2}),phase:g(A==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(ct,C),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(ct,C),window.__cmPeakAlertLive=!1}},[]),oe(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const C=_e(n,Array.isArray(o.peakWindows)?o.peakWindows:[]);if(C===null)return;const N=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",A=C.nextIntoPeak===!0;if(N!=="both"&&N!==(A?"peak":"offpeak"))return;const P=Number(o.peakAlertAhead),g=(Number.isFinite(P)&&P>=1?P:2)*6e4;if(n<C.nextAtMs-g||n>=C.nextAtMs||_t===C.nextAtMs)return;const v=V(F(o.locale));_t=C.nextAtMs;try{new Notification(v(A?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:v("peakAlertBody",{time:ge(C,n,v),phase:v(A?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[n]),!o||o.peakEnabled!==!0)return null;let h=null;if(o.peakAlertEnabled===!0){const C=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(C)&&n<C)){const N=_e(n,Array.isArray(o.peakWindows)?o.peakWindows:[]);if(N!==null){const A=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",P=Number(o.peakAlertAhead),g=(Number.isFinite(P)&&P>=1?P:2)*6e4;(A==="both"||A===(N.nextIntoPeak?"peak":"offpeak"))&&n>=N.nextAtMs-g&&n<N.nextAtMs&&r!==N.nextAtMs&&(h=N)}}}let u=null,b=!1,w=null;if(h!==null)u=h,b=h.nextIntoPeak===!0,w=()=>l(h.nextAtMs);else if(i!==null)u={nextAtMs:n+2*6e4,nextIntoPeak:i==="peak"},b=i==="peak",w=()=>d(null);else return null;const k=V(F(o.locale)),p=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+p+" "+(b?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},k(b?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},k(b?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},k("peakAlertBody",{time:ge(u,n,k),phase:k(b?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:w},k("peakAlertBtn"))))}function an(t){const{config:s,t:o}=t,[n,a]=O(Date.now());oe(()=>{const d=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const r=We(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:ge(r,n,o)}):o("nextOffPeakIn",{time:ge(r,n,o)});return e(X,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(r.weekend?"weekend":r.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:r.weekend?"50%":r.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(l.chip)+" · "+i)))}function nn(t){const{config:s,t:o}=t,[n,a]=O(Date.now());oe(()=>{const d=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const r=We(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:ge(r,n,o)}):o("nextOffPeakIn",{time:ge(r,n,o)});return e(X,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(r.weekend?"weekend":r.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:r.weekend?"50%":r.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)+" · "+i)))}function ut(t,s,o){return e(s?.peakStyle==="classic"?nn:an,{config:s,t:o})}function sn(t){const{config:s,t:o}=t,[n,a]=O(Date.now());oe(()=>{const h=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(h)},[]);const r=We(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:ge(r,n,o)}):o("nextOffPeakIn",{time:ge(r,n,o)}),d=[o(l.notice),i];return e(X,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(r.weekend?"weekend":r.inPeak?"peak":"off"),"aria-label":d.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:r.weekend?"50%":r.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(l.short))))}function on(t){const{config:s,t:o}=t,[n,a]=O(Date.now());oe(()=>{const h=window.setInterval(()=>a(Date.now()),3e4);return()=>window.clearInterval(h)},[]);const r=We(s,n);if(r===null)return null;const l=ze(r),i=r.nextIntoPeak?o("nextPeakIn",{time:ge(r,n,o)}):o("nextOffPeakIn",{time:ge(r,n,o)}),d=[o(l.notice),i];return e(X,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(r.weekend?"weekend":r.inPeak?"peak":"off"),"aria-label":d.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:r.weekend?"50%":r.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(l.short))))}function ln(t,s,o){return e(s?.peakStyle==="classic"?on:sn,{config:s,t:o})}function Wt(t,s,o){const n=t.today,a=s.budget??{enabled:!1,amount:100,period:"month"},r=Number(s.exchangeRate),i=(t.budgetUsed??(a.period==="day"?z(t.today,s):a.period==="all"?z(t.total,s):z(t.month,s)))*(Number.isFinite(r)&&r>0?r:1),d=Math.max(0,Number(a.amount)||0),h=d>0?Math.min(999,i/d*100):null,u=pe(h===null?null:Math.min(100,h),ae(s,"budget")),b=z(n,s)*(Number.isFinite(r)&&r>0?r:1),w=d>0?Math.min(999,b/d*100):null,k=a.detail!==!1;return{level:h===null?"ok":h>=100?"over":h>=80?"warn":"ok",rail:u.label===null?"—":Math.round(u.label)+"%",body:e(j,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("budget")),e("span",{className:"cm-bbox-pct cm-num"},u.label===null?"—":u.label.toFixed(1)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:u.width+"%"}})),k?e(j,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},o("todayShare",{amount:$(z(n,s),s),pct:w===null?"—":w.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:ce(i,s),amount:ce(d,s)}))):null,ut(t,s,o))}}function zt(t,s,o){const n=t.goQuota,a=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",r=n[a],l=r!==null&&typeof r?.percent=="number"?Math.max(0,Math.min(100,Number(r.percent)||0)):0,i=k=>k!==null&&typeof k?.percent=="number"?Math.round(Math.max(0,Math.min(100,k.percent)))+"%":"—",d=k=>o(k==="rolling"?"goShortRolling":k==="weekly"?"goShortWeekly":"goShortMonthly"),h=["rolling","weekly","monthly"].filter(k=>k!==a),u=r!==null&&typeof r?.resetsAt=="string"&&r.resetsAt.length>0?o("goResetAt",{time:new Date(r.resetsAt).toLocaleString()}):"",b=s?.goQuota?.detail!==!1,w=pe(l,ae(s,"go"));return{level:l>=100?"over":l>=80?"warn":"ok",rail:w.label===null?"—":Math.round(w.label)+"%",body:e(j,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+d(a)),e("span",{className:"cm-bbox-pct cm-num"},w.label===null?"—":Math.round(w.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:w.width+"%"}})),b?e(j,null,e("div",{className:"cm-bbox-line cm-num"},h.map(k=>d(k)+" "+i(n[k])).join(" · ")),u?e("div",{className:"cm-bbox-line"},u):null):null)}}function rn(t){const{state:s,wide:o}=t,n=s.goQuota,a=V(F(s.config?.locale));if(!n||n.status!=="ok")return null;const r=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(n[r]===null||typeof n[r]?.percent!="number")return null;const l=zt(s,s.config,a),i=[a("goQuotaTitle"),a("goWindowRolling")+": "+(n.rolling===null?"—":Math.round(n.rolling.percent)+"%"),a("goWindowWeekly")+": "+(n.weekly===null?"—":Math.round(n.weekly.percent)+"%"),a("goWindowMonthly")+": "+(n.monthly===null?"—":Math.round(n.monthly.percent)+"%"+(n.monthly!==null&&typeof n.monthly.resetsAt=="string"&&n.monthly.resetsAt.length>0?" · "+a("goResetAt",{time:new Date(n.monthly.resetsAt).toLocaleString()}):"")),a("goQuotaFetchedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e(X,{label:i,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 cn(t){return t===null||typeof t!="object"||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function De(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function Ge(t,s){return!t||typeof t.resetsAt!="string"||t.resetsAt.length===0?"":s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})}function Le(t,s,o){const n=cn(s),a=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",r=pe(n,o);return{level:a,pct:n,label:r.label,row:e("div",{className:"cm-mm-row"+(a==="ok"?"":" "+a)},e("span",{className:"cm-bbox-label",title:t},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r.label===null?"—":r.label+"%"))}}function Gt(t){const{five:s,seven:o,fetchedAt:n,t:a,wide:r,refresh:l,direction:i="used"}=t,d=Le(a("codingPlanRemain5h"),s,i),h=Le(a("codingPlanRemain7d"),o,i),u=d.level==="over"||h.level==="over"?"over":d.level==="warn"||h.level==="warn"?"warn":"ok",b=(C,N,A)=>{const P=A.pct===null?"—":A.pct+"%",g=Ge(N,a);return C+" "+P+(g?" · "+g:"")},w=[a("codingPlanMinimaxTitle"),b(a("codingPlanRemain5h"),s,d),b(a("codingPlanRemain7d"),o,h),n>0?a("goQuotaFetchedAt",{time:new Date(n).toLocaleTimeString()}):null,...l?fe(a,l):[]].filter(Boolean).join("; "),k=e(j,null,e("div",{className:"cm-mm-title"},a("codingPlanMinimaxTitle")),d.row,h.row),p=e(j,null,e("div",{className:"cm-bbox-rail cm-num"},d.pct===null?"—":d.pct+"%"),e("div",{className:"cm-bbox-rail cm-num"},h.pct===null?"—":h.pct+"%"));return e(X,{label:w,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm"+(u==="ok"?"":" "+u)+(r===!1?" rail":"")+(l?" clickable"+(l.busy?" busy":""):""),...l?de(l.busy,l.run):{}},r===!1?p:k))}function un(t){const{state:s,wide:o,api:n}=t,a=s.codingPlans?.minimax,r=V(F(s.config?.locale)),l=we(n?()=>n.refreshCodingPlan("minimax"):null);if(!a||a.status!=="ok")return null;const{five:i,seven:d}=De(a.windows);return i==null&&d==null?null:e(Gt,{five:i,seven:d,fetchedAt:a.fetchedAt,t:r,wide:o,refresh:l,direction:ae(s.config,"plan")})}const dn="/plugins/dsh-openai-codex/auth/status",mn=168*3600;function pn(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(i=>i!==null&&typeof i=="object"&&i.id==="codex");if(!o||!Array.isArray(o.windows))return null;const n=o.windows.find(i=>i!==null&&typeof i=="object"&&Number(i.windowSeconds)===mn);if(!n||typeof n.remainingPercent!="number"||!Number.isFinite(Number(n.remainingPercent)))return null;const a=Math.max(0,Math.min(100,Math.round((100-Number(n.remainingPercent))*10)/10)),r=Number(n.resetAt),l=Number.isFinite(r)&&r>0?new Date(r*1e3).toISOString():"";return{weekly:{percent:a,resetsAt:l}}}const Z={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},fn=t=>(Z.listeners.push(t),()=>{Z.listeners=Z.listeners.filter(s=>s!==t)}),gn=()=>{for(const t of Z.listeners)try{t()}catch{}};async function Ke(t=!1){if(Z.inFlight!==null)return Z.inFlight;if(!t&&Z.fetchedAt>0&&Date.now()-Z.fetchedAt<5*6e4)return;const s=(async()=>{try{const o=await fetch(dn,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(o.ok){const a=pn(await o.json().catch(()=>null));a!==null&&(n=a)}Z.status=Object.keys(n).length>0?"ok":"unavailable",Z.windows=n}catch{Z.status="unavailable"}finally{Z.fetchedAt=Date.now(),Z.inFlight=null,gn()}})();return Z.inFlight=s,s}Ke(!1);function bn(){const[t,s]=O(()=>({status:Z.status,windows:Z.windows,fetchedAt:Z.fetchedAt}));return oe(()=>{let o=!0;const a=fn(()=>{o&&s({status:Z.status,windows:Z.windows,fetchedAt:Z.fetchedAt})});return Ke(!1),()=>{o=!1,a()}},[]),t}function hn(t){const{state:s,wide:o}=t,n=V(F(s.config?.locale)),a=bn(),r=we(()=>Ke(!0));if(a.status!=="ok")return null;const l=a.windows.weekly??null;if(l===null)return null;const i=ae(s.config,"plan"),d=Le(n("goShortWeekly"),l,i),h=[n("codexQuotaTitle"),d.label===null?"—":d.label+"%",Ge(l,n),a.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()}):null,...fe(n,r)].filter(Boolean).join("; "),u=e(j,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),d.row),b=e("div",{className:"cm-bbox-rail cm-num"},d.label===null?"—":d.label+"%");return e(X,{label:h,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm clickable"+(d.level==="ok"?"":" "+d.level)+(o===!1?" rail":"")+(r.busy?" busy":""),...de(r.busy,r.run)},o===!1?b:u))}function dt(t,s){return t==="fiveHour"||t==="5h"?"5h":t==="weekly"||t==="week"||t==="7d"?t==="7d"?"7d":s("goShortWeekly"):t==="monthly"||t==="month"?s("goShortMonthly"):t==="daily"||t==="day"?s("goShortDaily"):String(t).replace(/_/g," ")}function yn(t){const{id:s,state:o,wide:n,api:a}=t,r=o.codingPlans?.[s],l=V(F(o.config?.locale)),i=we(a?()=>a.refreshCodingPlan(s):null),d=Te.find(g=>g.id===s);if(!d||!r||r.status!=="ok")return null;const h=r.windows!==null&&typeof r.windows=="object"?r.windows:{},u=Object.entries(h);if(u.length===0)return null;const b=g=>g!==null&&typeof g=="object"&&typeof g.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(g.percent)||0))):null,w=ae(o.config,"plan"),k=u.map(([g,v])=>{const x=b(v);if(x===null)return e("div",{key:g,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof v?.text=="string"?v.text:"—"));const m=x>=100?"over":x>=80?"warn":"ok",S=pe(x,w);return e("div",{key:g,className:"cm-mm-row wide"+(m==="ok"?"":" "+m)},e("span",{className:"cm-bbox-label"},dt(g,l)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:S.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},S.label===null?"—":S.label+"%"))}),p=u.map(([g,v])=>{const x=b(v),m=typeof v?.resetsAt=="string"&&v.resetsAt.length>0?" · "+l("goResetAt",{time:new Date(v.resetsAt).toLocaleString()}):"",S=x===null?typeof v?.text=="string"?v.text:"—":x+"%";return dt(g,l)+" "+S+m});r.fetchedAt>0&&p.push(l("goQuotaFetchedAt",{time:new Date(r.fetchedAt).toLocaleTimeString()})),p.push(...fe(l,i));const C=[l(d.labelKey),...p].join("; "),N=u.map(([,g])=>b(g)).filter(g=>g!==null),A=N.some(g=>g>=100)?"over":N.some(g=>g>=80)?"warn":"ok",P=N.length>0?N.slice(0,2).map(g=>g+"%").join(" "):typeof u[0][1]?.text=="string"?u[0][1].text:"—";return e(X,{label:C,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm clickable"+(A==="ok"?"":" "+A)+(n===!1?" rail":"")+(i.busy?" busy":""),...de(i.busy,i.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},P):e(j,null,e("div",{className:"cm-mm-title"},l(d.labelKey)),...k)))}function kn(t){const{source:s,snapshot:o,state:n,wide:a,api:r}=t,l=V(F(n.config?.locale)),i=we(r?()=>r.refreshGatewayQuota(s.id):null),d=ae(n.config,"plan"),h=o.accounts.length>1,u=v=>h?(Nt[v.provider]??v.provider)+" · ":"",b=[];for(const v of o.accounts){if(b.length>=4)break;for(const x of v.windows){if(b.length>=4)break;const m=x.label||x.id||l("gatewaySourceUnknown");b.push({win:x,name:u(v)+m,view:Le(m,x,d)})}v.windows.length===0&&v.credits!=null&&b.push({win:null,name:u(v)+(v.credits.unit||"credits"),text:(v.credits.used??"—")+" / "+(v.credits.limit??"—")})}if(b.length===0)return null;const w=b.some(v=>v.view?.level==="over")?"over":b.some(v=>v.view?.level==="warn")?"warn":"ok",k=b.map(v=>{if(v.text!=null)return v.name+" "+v.text;const x=Ge(v.win,l);return v.name+" "+(v.view.pct===null?"—":v.view.pct+"%")+(x?" · "+x:"")});o.fetchedAt>0&&k.push(l("goQuotaFetchedAt",{time:new Date(o.fetchedAt).toLocaleTimeString()})),k.push(...fe(l,i));const p=[s.label||s.id,...k].join("; "),C=b.map((v,x)=>v.text!=null?e("div",{key:x,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},v.name),e("span",{className:"cm-mm-text cm-num"},v.text)):e(j,{key:x},v.view.row)),N=e(j,null,e("div",{className:"cm-mm-title"},s.label||s.id),...C),A=b.filter(v=>v.view).map(v=>v.view.pct).filter(v=>v!==null),P=A.length>0?A.slice(0,2).map(v=>v+"%").join(" "):b[0].text??"—",g=e("div",{className:"cm-bbox-rail cm-num"},P);return e(X,{label:p,side:"right",delayMs:300},e("div",{className:"cm-bbox cm-mm clickable"+(w==="ok"?"":" "+w)+(a===!1?" rail":"")+(i.busy?" busy":""),...de(i.busy,i.run)},a===!1?g:N))}function wn(t,s,o,n){const a=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],r=[];for(const l of s.gatewayQuotas?.sources??[]){if(l.enabled===!1||l.display!=="sidebar"&&l.display!=="both")continue;const i=a.find(d=>d.id===l.id);!i||i.status!=="ok"&&i.status!=="partial"&&i.status!=="stale"||i.accounts.length===0||r.push(e(kn,{source:l,snapshot:i,state:t,wide:o,api:n}))}return r}const vn={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen"};function xn(t){const s=t.useCost?t.useCost(p=>p):void 0,[o,n]=O(null),[a,r]=O({}),l=s?.state,i=t.api;if(!l)return null;const d=l.config,h=d.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(h.enabled!==!0)return null;const u=V(F(d?.locale)),b=[];if(h.budget!==!1){const p=d.budget??{enabled:!1,amount:100,period:"month"};if(p.enabled===!0){const C=Number(d.exchangeRate),A=(l.budgetUsed??(p.period==="day"?z(l.today,d):p.period==="all"?z(l.total,d):z(l.month,d)))*(Number.isFinite(C)&&C>0?C:1),P=Math.max(0,Number(p.amount)||0);if(P>0){const g=Math.min(999,A/P*100),v=g>=100?"over":g>=80?"warn":"ok";b.push({key:"budget",label:u("budgetShort"),level:v,tip:u("budgetOf",{period:u(He[p.period]??"periodMonth")})+" · "+u("usedOf",{used:ce(A,d),amount:ce(P,d)})+" · "+g.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(pe(Math.min(100,g),ae(d,"budget")).width)}]})}}}if(h.go!==!1){const p=l.goQuota;if(d?.goQuota?.enabled!==!1&&p?.status==="ok"){const C=d.goQuota.main==="weekly"||d.goQuota.main==="monthly"?d.goQuota.main:"rolling",N=C==="rolling"?p.rolling:C==="weekly"?p.weekly:p.monthly;if(N!==null&&typeof N=="object"&&typeof N.percent=="number"){const A=Math.max(0,Math.min(100,Math.round(Number(N.percent)||0))),P=A>=100?"over":A>=80?"warn":"ok",g=typeof N.resetsAt=="string"&&N.resetsAt.length>0?" · "+u("goResetAt",{time:new Date(N.resetsAt).toLocaleString()}):"";b.push({key:"go",label:"Go "+u(C==="rolling"?"goShortRolling":C==="weekly"?"goShortWeekly":"goShortMonthly"),level:P,tip:"Go: "+A+"%"+g,segs:[{name:"main",pct:Math.round(pe(A,ae(d,"go")).width)}]})}}}if(h.plans!==!1)for(const p of Te){const C=l.codingPlans?.[p.id];if(d.codingPlans?.[p.id]?.enabled!==!0||!C||C.status!=="ok")continue;const N=C.windows!==null&&typeof C.windows=="object"?C.windows:{},A=Object.entries(N);if(A.length===0)continue;const P=vn[p.id]??p.id,g=[],v=[];let x=0,m=0;for(const[S,M]of A){const R=dt(S,u),H=typeof M?.resetsAt=="string"&&M.resetsAt.length>0?" · "+u("goResetAt",{time:new Date(M.resetsAt).toLocaleString()}):"",T=M!==null&&typeof M=="object"&&typeof M.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(M.percent)||0))):null;if(v.push(R+" "+(T===null?typeof M?.text=="string"?M.text:"—":T+"%")+H),T===null){g.push({name:S,pct:null,text:typeof M?.text=="string"?M.text:"—"});continue}m>=2||(m+=1,g.push({name:S,pct:Math.round(pe(T,ae(d,"plan")).width)}),x=Math.max(x,T>=100?2:T>=80?1:0))}C.fetchedAt>0&&v.push(u("goQuotaFetchedAt",{time:new Date(C.fetchedAt).toLocaleTimeString()})),g.length!==0&&b.push({key:p.id,label:P,level:["ok","warn","over"][x],tip:v.join("; "),segs:g})}const w=Z.status==="ok"?Z.windows.weekly??null:null;if(w!==null&&typeof w.percent=="number"){const p=Math.max(0,Math.min(100,Math.round(Number(w.percent)||0))),C=typeof w.resetsAt=="string"&&w.resetsAt.length>0?" · "+u("goResetAt",{time:new Date(w.resetsAt).toLocaleString()}):"";b.push({key:"codex",label:"Codex",level:p>=100?"over":p>=80?"warn":"ok",tip:u("codexQuotaTitle")+": "+p+"%"+C,segs:[{name:"weekly",pct:Math.round(pe(p,ae(d,"plan")).width)}]})}if(b.length===0)return null;const k=p=>{o!==null||!i||(n(p),r(C=>({...C,[p]:null})),Promise.resolve().then(()=>p==="budget"?i.reload():p==="go"?i.refreshGoQuota():p==="codex"?Ke(!0):i.refreshCodingPlan(p)).catch(C=>{r(N=>({...N,[p]:C?.message??String(C)}))}).finally(()=>n(null)))};return e("div",{className:"cm-qstrip"},b.map(p=>{const C=o===p.key,N=a[p.key],A=[e("span",{className:"cm-qlabel",key:"l"},p.label)];C?A.push(e("span",{className:"cm-qtext",key:"busy"},u("refreshing"))):p.segs.forEach((g,v)=>{v>0&&A.push(e("span",{className:"cm-qsep",key:"sep"+v,"aria-hidden":"true"})),g.pct===null?A.push(e("span",{className:"cm-qtext",key:g.name},g.text)):A.push(e("span",{className:"cm-qseg",key:g.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:g.pct+"%"}})),e("span",null,g.pct+"%")))});const P=[p.tip];return!C&&i&&P.push(u("clickToRefresh")),C&&P.push(u("refreshing")),N&&P.push("⚠ "+u("balanceRefreshFailed",{message:N})),e(X,{key:p.key,label:P.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(i?" action":"")+(p.level==="ok"?"":" "+p.level),...i?de(C,()=>k(p.key)):{}},A))}))}function Nn(t){const s=t.useCost?t.useCost(i=>i):void 0,o=Ae(!1),n=s?.state;if(!n)return null;const a=n.config;if(a.quotaStrip?.promptSeen===!0)return null;const r=V(F(a?.locale)),l=i=>{if(o.current===!0)return;o.current=!0;const d=a.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...d,enabled:i,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":r("quotaStripGuideTitle")},e("h4",null,r("quotaStripGuideTitle")),e("p",null,r("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>l(!1)},r("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>l(!0)},r("quotaStripGuideOn"))))}const Kt="dsh-cost-meter:balance-click-hint-seen",Sn=()=>{try{return window.localStorage.getItem(Kt)==="1"}catch{return!1}},Cn=()=>{try{window.localStorage.setItem(Kt,"1")}catch{}};function An(t){const s=t.useCost?t.useCost(k=>k):void 0,o=Ae(!1),[n,a]=O(!1),[r]=O(Sn),l=s?.state;if(!l)return null;const i=l.config,d=i.balance?.display==="sidebar"||i.balance?.display==="both",h=(i?.customBalances??[]).some(k=>k?.enabled===!0&&(k.display==="sidebar"||k.display==="both"))||i.customBalance?.enabled===!0&&(i.customBalance?.display==="sidebar"||i.customBalance?.display==="both"),u=Te.some(k=>{const p=i.codingPlans?.[k.id];return p?.enabled===!0&&(p.display==="sidebar"||p.display==="both")});if(n||r||i.balance?.clickHintSeen===!0||!d&&!h&&!u||i.quotaStrip?.promptSeen!==!0)return null;const b=V(F(i?.locale)),w=()=>{o.current!==!0&&(a(!0),o.current=!0,Cn(),t.api.updateConfig({balance:{...i.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,a(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":b("balanceClickGuideTitle")},e("h4",null,b("balanceClickGuideTitle")),e("p",null,b("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:w},b("balanceClickGuideOk"))))}function Vt(t){const{state:s,wide:o}=t,n=s.today,a=s.config,r=V(F(a?.locale)),l=a.budget??{enabled:!1,amount:100,period:"month"},i=Number(a.exchangeRate),h=(s.budgetUsed??(l.period==="day"?z(s.today,a):l.period==="all"?z(s.total,a):z(s.month,a)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(l.amount)||0),b=u>0?Math.min(999,h/u*100):null,w=b===null?"ok":b>=100?"over":b>=80?"warn":"ok";if(l.enabled===!0){const p=z(n,a),C=p*(Number.isFinite(i)&&i>0?i:1),N=u>0?Math.min(999,C/u*100):null,A=[r("budgetOf",{period:r(He[l.period]??"periodMonth")}),r("usedOf",{used:ce(h,a),amount:ce(u,a)})+" · "+(b===null?"—":b.toFixed(1)+"%"),...a.hideTodayCost===!0?[]:[r("todayShare",{amount:$(p,a),pct:N===null?"—":N.toFixed(1)+"%"})],r("monthTotal",{month:$(z(s.month,a),a),total:$(z(s.total,a),a)})].join("; "),P=Wt(s,a,r);return e(X,{label:A,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(w==="ok"?"":" "+w)+(o?"":" rail")},o?P.body:e("div",{className:"cm-bbox-rail cm-num"},P.rail)))}const k=[r("todayCostTitle"),r("callsTokens",{calls:n.calls,input:U(n.input),cache:U(n.cacheRead+n.cacheWrite),output:U(n.output)}),r("monthCost",{amount:$(z(s.month,a),a)}),r("totalCost",{amount:$(z(s.total,a),a)})].join("; ");return e(X,{label:k,side:"right",delayMs:300},e(j,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(j,null,r("today")," ",e("span",{className:"cm-num"},$(z(n,a),a))):e(nt,{size:16})),o?ut(s,a,r):null))}function Pn(t){const s=t.useCost?t.useCost(S=>S):void 0;let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}st(t,o);const n=s?.state,a=!!t.wide,r=Ae(null);if(oe(()=>{const S=r.current,M=S?.parentElement;if(!S||!M)return;const R=()=>{a?M.firstElementChild!==S&&M.insertBefore(S,M.firstElementChild):M.lastElementChild!==S&&M.appendChild(S)};R();const H=new MutationObserver(()=>{S.isConnected&&R()});return H.observe(M,{childList:!0}),a?(M.style.flexDirection="",M.style.flexWrap="",M.style.alignItems="",M.style.gap=""):(M.style.flexDirection="column",M.style.flexWrap="nowrap",M.style.alignItems="center",M.style.gap="6px"),()=>{H.disconnect(),a||(M.style.flexDirection="",M.style.flexWrap="",M.style.alignItems="",M.style.gap="")}},[a,n]),!n)return null;const l=n.config,i=V(F(l?.locale)),d=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,u=it(n,l).length>0,b=d&&l.balance?.showProgressBar===!0&&n.balance?.status==="ok",w=u&&l.balance?.showProgressBar===!0,k=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",p=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&n.goQuota?.status==="ok"&&n.goQuota?.[k]!==null,C=Te.map(S=>S.id).filter(S=>{const M=l.codingPlans?.[S];if(M?.enabled!==!0||M.display!=="sidebar"&&M.display!=="both")return!1;const R=n.codingPlans?.[S];if(R?.status!=="ok")return!1;const H=R.windows!==null&&typeof R.windows=="object"?R.windows:{};return Object.keys(H).length>0}),N=C.length>0,A=wn(n,l,a,t.api),P=Z.status==="ok"&&Z.windows.weekly!==null,g=(l.budget??{}).enabled===!0,v=l.sidebar!==!1&&l.hideTodayCost!==!0;if(!d&&!u&&!p&&!N&&!P&&!g&&!v&&A.length===0)return null;const x=a&&l.sidebarStyle==="compact",m=[];if(b?m.push(e(Va,{state:n,wide:a,api:t.api})):d&&m.push(e(Ka,{state:n,wide:a,api:t.api})),w?m.push(e(Ja,{state:n,wide:a,api:t.api})):u&&m.push(e(Za,{state:n,wide:a,api:t.api})),N&&m.push(...C.map(S=>S==="minimax"?e(un,{state:n,wide:a,api:t.api}):e(yn,{id:S,state:n,wide:a,api:t.api}))),m.push(...A),P&&m.push(e(hn,{state:n,wide:a,api:t.api})),p&&g&&a){const S=zt(n,l,i),M=Wt(n,l,i),R=S.level==="over"||M.level==="over"?"over":S.level==="warn"||M.level==="warn"?"warn":"ok";m.push(e("div",{className:"cm-bbox cm-bbox-pair"+(R==="ok"?"":" "+R)},e("div",{className:"cm-bbox-section"+(S.level==="ok"?"":" "+S.level)},S.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(M.level==="ok"?"":" "+M.level)},M.body)))}else p&&m.push(e(rn,{state:n,wide:a})),g&&m.push(e(Vt,{state:n,wide:a}));return!g&&v&&m.push(e(Vt,{state:n,wide:a})),a||m.push(ln(n,l,i)),e("div",{ref:r,className:"cm-footer-stack"+(a?"":" rail")+(x?" compact":"")},...m)}function mt(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))}const Me=(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 Mn(t){const{state:s,api:o}=t,n=V(F(s.config?.locale)),[a,r]=O(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Me(a,()=>r(!a),n("history"))),a?e("div",{className:"cm-collapse-body"},e(Tn,{state:s,api:o})):null)}function Tn(t){const{state:s,api:o}=t,n=V(F(s.config?.locale)),[a,r]=O(null),[l,i]=O({}),[d,h]=O(()=>new Set),u=s.history??[];if(u.length===0)return e("p",{className:"cm-empty"},n("noHistory"));const b=k=>{if(a===k){r(null);return}r(k),!(l[k]!==void 0||d.has(k))&&(h(p=>{const C=new Set(p);return C.add(k),C}),o.getDaySessions(k).then(p=>i(C=>({...C,[k]:Array.isArray(p?.sessions)?p.sessions:[]}))).catch(()=>i(p=>({...p,[k]:"error"}))).finally(()=>h(p=>{const C=new Set(p);return C.delete(k),C})))},w=k=>k.map(p=>e("tr",{key:p.id},pt(p,s.config?.showSessionId===!0,n),e("td",{className:"num"},String(p.calls)),e("td",{className:"num"},U(p.input)),e("td",{className:"num"},U(p.cacheRead+p.cacheWrite)),e("td",{className:"num"},U(p.output)),e("td",{className:"num"},$(z(p,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},n("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("colDate")),e("th",{className:"num"},n("colCalls")),e("th",{className:"num"},n("colInTok")),e("th",{className:"num"},n("colCacheTok")),e("th",{className:"num"},n("colOutTok")),e("th",{className:"num"},n("colCost")))),e("tbody",null,u.flatMap(k=>{const p=e("tr",{key:k.date,className:"cm-row-click",onClick:()=>b(k.date)},e("td",null,(a===k.date?"▾ ":"▸ ")+k.date),e("td",{className:"num"},String(k.calls)),e("td",{className:"num"},U(k.input)),e("td",{className:"num"},U(k.cacheRead+k.cacheWrite)),e("td",{className:"num"},U(k.output)),e("td",{className:"num"},$(z(k,s.config),s.config)));if(a!==k.date)return[p];const C=l[k.date],N=d.has(k.date)&&C===void 0?e("p",{className:"cm-empty"},n("historySessionsLoading")):C==="error"?e("p",{className:"cm-empty"},n("historySessionsError")):!Array.isArray(C)||C.length===0?e("p",{className:"cm-empty"},n("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("colSession")),e("th",{className:"num"},n("colCalls")),e("th",{className:"num"},n("colInTok")),e("th",{className:"num"},n("colCacheTok")),e("th",{className:"num"},n("colOutTok")),e("th",{className:"num"},n("colCost")))),e("tbody",null,w(C)));return[p,e("tr",{key:k.date+"-sessions"},e("td",{colSpan:6},N))]}))))}function Bn(t){const{state:s,api:o}=t,n=V(F(s.config?.locale)),[a,r]=O(!1),[l,i]=O(100),[d,h]=O("cost-desc"),[u,b]=O(null),[w,k]=O(!1),[p,C]=O(!1),N=Re.useRef(0),A=(x,m)=>{const[S,M]=m==="recent"?["recent","desc"]:m.split("-"),R=++N.current;k(!0),C(!1),o.getTopSessions(x,S,M).then(H=>{R===N.current&&b(Array.isArray(H?.sessions)?H.sessions:[])}).catch(()=>{R===N.current&&C(!0)}).finally(()=>{R===N.current&&k(!1)})},P=()=>{r(x=>{const m=!x;return m&&u===null&&!w&&A(l,d),m})},g=x=>{i(x),(a||u!==null)&&A(x,d)},v=x=>{h(x),(a||u!==null)&&A(l,x)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Me(a,P,n("sessionRankTitle"))),a?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},n("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,n("sessionRankSort")),e("select",{className:"cm-input",value:d,onChange:x=>v(x.target.value)},e("option",{value:"cost-desc"},n("sessionSortCostDesc")),e("option",{value:"cost-asc"},n("sessionSortCostAsc")),e("option",{value:"time-desc"},n("sessionSortTimeDesc")),e("option",{value:"time-asc"},n("sessionSortTimeAsc")),e("option",{value:"recent"},n("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,n("sessionRankLimit")),e("select",{className:"cm-input",value:String(l),onChange:x=>g(Number(x.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),w?e("p",{className:"cm-empty"},n("sessionRankLoading")):p?e("p",{className:"cm-empty"},n("sessionRankError")):u===null||u.length===0?e("p",{className:"cm-empty"},n("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("colDate")),e("th",null,n("colSession")),e("th",{className:"num"},n("colCalls")),e("th",{className:"num"},n("colInTok")),e("th",{className:"num"},n("colCacheTok")),e("th",{className:"num"},n("colOutTok")),e("th",{className:"num"},n("colCost")))),e("tbody",null,u.map(x=>e("tr",{key:x.date+":"+x.id},e("td",null,x.date),pt(x,s.config?.showSessionId===!0,n),e("td",{className:"num"},String(x.calls)),e("td",{className:"num"},U(x.input)),e("td",{className:"num"},U((x.cacheRead??0)+(x.cacheWrite??0))),e("td",{className:"num"},U(x.output)),e("td",{className:"num"},$(z(x,s.config),s.config)))))))):null)}function Rn(t){const{state:s}=t,o=V(F(s.config?.locale)),n=s.today.sessions??[];if(n.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const a=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,n.map(r=>e("tr",{key:r.id},pt(r,a,o),e("td",{className:"num"},String(r.calls)),e("td",{className:"num"},U(r.input)),e("td",{className:"num"},U(r.cacheRead+r.cacheWrite)),e("td",{className:"num"},U(r.output)),e("td",{className:"num"},$(z(r,s.config),s.config)))))))}function pt(t,s,o){const n=typeof t.title=="string"?t.title.trim():"",a=String(t.id).slice(0,14)+"…",r=n.length>0?n:a,l=n.length>0?n+" · "+t.id:t.id;return e("td",{title:l},e("div",{className:"cm-sess-title"+(n.length===0?" cm-sess-id":"")},r),s&&n.length>0?e("div",{className:"cm-sess-id"},a):null)}const Dn={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function Ln(t){const{state:s,draft:o,setDraft:n,t:a}=t,r=s.config,l=o?.budget??r.budget,i=Number(r.exchangeRate),h=(s.budgetUsed??(l.period==="day"?z(s.today,r):l.period==="all"?z(s.total,r):z(s.month,r)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(l.amount)||0),b=l.enabled&&u>0?Math.min(999,h/u*100):null,w=b===null?"ok":b>=100?"over":b>=80?"warn":"ok",k=(N,A)=>{o!==null&&n({...o,budget:{...o.budget??r.budget,[N]:A}})},p=l.period==="custom"?l.customStart+" → "+(l.customEnd??a("periodDay")):null,C=l.enabled&&b!==null?a("budgetStatus",{period:a(He[l.period]??"periodMonth"),amount:ce(u,r),used:ce(h,r),pct:b.toFixed(1)})+(w==="over"?a("overLimit"):w==="warn"?a("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:l.enabled===!0,onChange:N=>k("enabled",N.target.checked)}),e("span",null,a("enableBudget")))),l.enabled?e(j,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(w==="ok"?"":w),style:{width:(b===null?0:Math.min(100,b))+"%"}})),e("div",{className:"cm-budget-line"+(w==="over"?" over":"")+" cm-num"},C),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,a("budgetAmountLabel")),le({value:l.amount},N=>k("amount",N))),e("div",{className:"cm-field"},e("label",null,a("budgetPeriodLabel")),e("select",{className:"cm-input",value:l.period,onChange:N=>k("period",N.target.value)},e("option",{value:"day"},a("periodDay")),e("option",{value:"month"},a("periodMonth")),e("option",{value:"all"},a("periodAll")),e("option",{value:"custom"},a("periodCustomRange")))),l.period==="custom"?e(j,null,e("div",{className:"cm-field"},e("label",null,a("startDate")),e("input",{className:"cm-input",type:"date",value:l.customStart??"",onChange:N=>k("customStart",N.target.value===""?null:N.target.value)})),e("div",{className:"cm-field"},e("label",null,a("endDate")),e("input",{className:"cm-input",type:"date",value:l.customEnd??"",onChange:N=>k("customEnd",N.target.value===""?null:N.target.value)}))):null),p!==null?e("p",{className:"cm-hint"},a("rangeText",{range:p})):null):e("p",{className:"cm-note"},a("budgetDisabledNote")))}function On(t){const{state:s,draft:o,setDraft:n,t:a}=t,r=s.config,l=(u,b)=>{o!==null&&n({...o,[u]:b})},i=o===null?r:{...r,...o},d=(()=>{if(i.peakEnabled!==!0)return a("peakOff");const u=Date.parse(i.peakEffectiveAt||""),b=Date.now();if(Number.isFinite(u)&&b<u)return a("peakNotEffective",{time:new Date(u).toLocaleString()});const w=i.peakWindows??[],k=_e(b,w);return k===null?a("offPeakActive"):k.weekend===!0?a("weekendAllOffPeak"):k.inPeak?a("peakActive"):a("offPeakActive")})(),h=(i.peakWindows?.length??0)>0?a("peakSummary",{windows:i.peakWindows.map(u=>u.start+":00-"+u.end+":00").join(F(i.locale)==="zh"?"、":", "),time:i.peakEffectiveAt||a("unknown"),status:d}):a("noPeakWindows",{status:d});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:u=>l("peakEnabled",u.target.checked)}),e("span",null,a("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:u=>l("peakNotice",u.target.checked)}),e("span",null,a("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,a("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:u=>l("peakStyle",u.target.value)},e("option",{value:"compact"},a("peakStyleCompact")),e("option",{value:"classic"},a("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:u=>l("peakAlertEnabled",u.target.checked)}),e("span",null,a("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,a("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:u=>{const b=Number(u.target.value);Number.isInteger(b)&&b>=1&&b<=30&&l("peakAlertAhead",b)}})),e("div",{className:"cm-field"},e("label",null,a("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:u=>l("peakAlertTarget",u.target.value)},e("option",{value:"both"},a("peakAlertTargetBoth")),e("option",{value:"peak"},a("peakAlertTargetPeak")),e("option",{value:"offpeak"},a("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,a("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:u=>l("peakAlertPosition",u.target.value)},e("option",{value:"corner"},a("peakAlertPositionCorner")),e("option",{value:"center"},a("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:u=>{l("peakAlertWebNotify",u.target.checked),u.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,a("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},a("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,a("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},a("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},a("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?ut(s,i,a):e("p",{className:"cm-hint"},a("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},h),e("p",{className:"cm-hint"},a("weekendRuleNote")))}function le(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:n=>{const a=n.target.value;if(a===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const r=Number(a);Number.isFinite(r)&&r>=0&&s(r)}})}function ft(t){const{modelId:s,entry:o,isDefault:n,draft:a,setDraft:r,t:l}=t,i=(u,b,w)=>{if(w===null){if(n){const x=a.prices.default??{cacheHit:0,cacheMiss:0,output:0},m={...x[u]??{}};delete m[b];const S={...x};Object.keys(m).length>0?S[u]=m:delete S[u],r({...a,prices:{...a.prices,default:S}});return}const A={...a.prices.models},P=A[s]??{cacheHit:0,cacheMiss:0,output:0},g={...P[u]??{}};delete g[b];const v={...P};Object.keys(g).length>0?v[u]=g:delete v[u],A[s]=v,r({...a,prices:{...a.prices,models:A}});return}const k=Math.max(0,w);if(n){let P={...a.prices.default??{cacheHit:0,cacheMiss:0,output:0}};if(u==="base")P[b]=k;else{const g={...P[u]??{},[b]:k};P={...P,[u]:g}}r({...a,prices:{...a.prices,default:P}});return}const p={...a.prices.models},C=p[s]??{cacheHit:0,cacheMiss:0,output:0};let N={...C};if(u==="base")N[b]=k;else{const A={...C[u]??{},[b]:k};N={...C,[u]:A}}p[s]=N,r({...a,prices:{...a.prices,models:p}})},d=()=>{const u={...a.prices.models};delete u[s],r({...a,prices:{...a.prices,models:u}})},h=(u,b)=>{const w=b==="base"?o:o[b]??null,k=b==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:b},e("span",null,u),le({value:w?.cacheHit??null,emptyMode:k},p=>i(b,"cacheHit",p)),le({value:w?.cacheMiss??null,emptyMode:k},p=>i(b,"cacheMiss",p)),le({value:w?.output??null,emptyMode:k},p=>i(b,"output",p)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(j,null,o?.legacy===!0?e("span",{className:"cm-price-legacy"},l("legacyModel")):null,n?e("span",{className:"cm-price-legacy"},l("defaultFallback")):null,n?null:e("button",{className:"cm-btn small danger",onClick:d},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"))),h(l("tierBase"),"base"),h(l("tierOffPeak"),"offPeak"),h(l("tierPeak"),"peak"))}const Yt={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 En(t,s){if(t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");const o=a=>"$"+String(a),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?o(t.cacheMiss)+"/"+o(n.cacheMiss)+" in · "+o(t.output)+"/"+o(n.output)+" out":o(t.cacheMiss??t.input??0)+" in · "+o(t.output??0)+" out"}function jn(t){const{state:s,draft:o,setDraft:n,t:a}=t,[r,l]=O(!1),[i,d]=O({}),h=s.priceCatalog;if(h===null||typeof h!="object")return null;const u=o?.prices??s.config.prices,b=o?.priceTableDisplay??s.config.priceTableDisplay??{},w=(m,S)=>{const M=b[m+":"+S];return typeof M=="boolean"?M:m==="deepseek"},k=(m,S,M)=>{o!==null&&n({...o,priceTableDisplay:{...b,[m+":"+S]:M}})},p=(m,S)=>m==="deepseek"?u.models?.[S]!==void 0:u.providers?.[m]?.models?.[S]!==void 0,C=(m,S,M)=>{if(o===null)return;const R=JSON.parse(JSON.stringify(M));if(m==="deepseek"){n({...o,prices:{...o.prices,models:{...o.prices.models,[S]:R}}});return}const H={...o.prices.providers??{}},T=H[m]??{};H[m]={...T,models:{...T.models??{},[S]:R}},n({...o,prices:{...o.prices,providers:H}})},N=(m,S)=>{if(o===null)return;if(m==="deepseek"){const H={...o.prices.models};delete H[S],n({...o,prices:{...o.prices,models:H}});return}const M={...o.prices.providers??{}},R=M[m];if(R!==void 0&&R.models!==void 0){const H={...R.models};delete H[S],M[m]={...R,models:H},n({...o,prices:{...o.prices,providers:M}})}},A=Object.keys(h).sort((m,S)=>m==="deepseek"?-1:S==="deepseek"?1:m.localeCompare(S)),P=m=>Object.values(h[m]).reduce((S,M)=>S+Object.keys(M).length,0),g=new Set(Object.values(h.deepseek??{}).flatMap(m=>Object.keys(m))),v=Object.keys(u.models??{}).filter(m=>!g.has(m)).sort(),x=(m,S,M)=>{const R=p(m,S),H=w(m,S),T=R?e("label",{className:"cm-check cm-vendor-display",title:a("catalogDisplayHint")},e("input",{type:"checkbox",checked:H,onChange:f=>k(m,S,f.target.checked)}),e("span",null,a("catalogDisplayLabel"))):null;if(R&&!H&&o!==null){const f=m==="deepseek"?e(ft,{key:S,modelId:S,entry:u.models[S],isDefault:!1,draft:o,setDraft:n,t:a}):e(Xt,{key:S,provider:m,modelId:S,entry:u.providers?.[m]?.models?.[S],draft:o,setDraft:n,t:a});return e("div",{key:S,className:"cm-catalog-mounted"},T,f)}return e("div",{key:S,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},S),e("span",{className:"cm-catalog-price"},En(M,a)),R?e("span",{className:"cm-catalog-tag"},a("mountedTag")):null,T,e("button",{className:"cm-btn small",disabled:!R&&M?.unpriced===!0,onClick:()=>R?N(m,S):C(m,S,M)},a(R?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>l(m=>!m)},a(r?"catalogCollapse":"catalogOpen"))),r?e(j,null,e("p",{className:"cm-note"},a("catalogNote")),A.map(m=>{const S=i[m]===!0;return e("div",{key:m},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>d(M=>({...M,[m]:!S}))},e("span",null,(S?"▾ ":"▸ ")+(Yt[m]??m)+" · "+P(m))),S?e(j,null,m==="deepseek"?e("p",{className:"cm-hint"},a("catalogDeepseekNote")):null,Object.keys(h[m]).sort().map(M=>e("div",{key:M},e("div",{className:"cm-catalog-family"},M),Object.keys(h[m][M]).sort().map(R=>x(m,R,h[m][M][R])))),m==="deepseek"&&v.length>0?e("div",null,e("div",{className:"cm-catalog-family"},a("catalogCustomModels")),v.map(M=>x("deepseek",M,null))):null):null)})):null)}const Jt=t=>t==="zen"?"go":t,$t=t=>{const s=t.indexOf(":");return s<=0?t:Jt(t.slice(0,s).toLowerCase())+t.slice(s)};function Hn(t){const{state:s,config:o,t:n,initialTab:a}=t,[r,l]=O(a==="history"?"history":"today"),[i,d]=O(!1),h=g=>{if(g===null||typeof g!="object")return{};if(g.byProviderModel&&Object.keys(g.byProviderModel).length>0)return g.byProviderModel;if(g.byModel&&Object.keys(g.byModel).length>0)return g.byModel;const v={};if(Array.isArray(g.sessions))for(const x of g.sessions){if(x===null||typeof x!="object")continue;const m=typeof x.provider=="string"&&x.provider.length>0?x.provider:"deepseek",S=typeof x.model=="string"&&x.model.length>0?x.model:"unknown",M=m+":"+S,R=v[M]??(v[M]={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0,cost:0}),H=T=>typeof T=="number"&&Number.isFinite(T)&&T>=0?T:0;R.input+=H(x.input),R.output+=H(x.output),R.cacheRead+=H(x.cacheRead),R.cacheWrite+=H(x.cacheWrite),R.reasoning+=H(x.reasoning),R.cost+=H(x.cost)}if(Object.keys(v).length>0)return v;if(Number(g.cost)>0||Number(g.input)>0||Number(g.output)>0){const x=m=>typeof m=="number"&&Number.isFinite(m)&&m>=0?m:0;return{"deepseek:legacy":{input:x(g.input),output:x(g.output),cacheRead:x(g.cacheRead),cacheWrite:x(g.cacheWrite),reasoning:x(g.reasoning),cost:x(g.cost)}}}return{}},b=(g=>{const v={},x=m=>{for(const S of Object.keys(m??{})){const M=m[S];if(M===null||typeof M!="object")continue;const R=v[S]??(v[S]={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0,cost:0,calls:0});R.input+=Number(M.input)||0,R.output+=Number(M.output)||0,R.cacheRead+=Number(M.cacheRead)||0,R.cacheWrite+=Number(M.cacheWrite)||0,R.reasoning+=Number(M.reasoning)||0,R.cost+=Number(M.cost)||0,R.calls+=Number(M.calls)||0}};if(g==="today")x(h(s.today));else for(const m of s.history??[])x(h(m));return Object.entries(v).map(([m,S])=>{const M=m.indexOf(":"),R=(M>0?m.slice(0,M):"deepseek").toLowerCase(),H=M>0?m.slice(M+1):m,T=S.input+S.output+S.cacheRead+S.cacheWrite+S.reasoning,f=S.cacheRead+S.input;return{label:m==="deepseek:legacy"?n("modelStatsLegacy"):R==="deepseek"||R===""?H:Jt(R)+":"+H,...S,tokens:T,cls:et(R,H,o),hitRate:f>0?S.cacheRead/f:null,cacheUnreported:Da(S),blended:T>0&&S.cost>0?S.cost/T*1e6:null,perUsd:S.cost>0?T/S.cost:null}}).filter(m=>m.tokens>0||m.cost>0)})(r).sort((g,v)=>v.cost-g.cost||v.tokens-g.tokens),w=g=>(Math.max(0,Math.min(1,g))*100).toFixed(1)+"%",k=b.reduce((g,v)=>Math.max(g,v.cost),0),p=b.reduce((g,v)=>Math.max(g,v.tokens),0),C=b.reduce((g,v)=>Math.max(g,v.perUsd??0),0),N=(g,v)=>e("button",{className:"cm-mstats-tab"+(r===g?" active":""),onClick:()=>l(g)},v),A=g=>g.cls==="plan"?e("span",{className:"cm-plan-tag",title:n("billingClassLabel")},n("billingClassPlan")):null,P=(g,v,x,m,S)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name"},g,S??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+x,style:{width:w(v)}})),e("span",{className:"cm-mstats-val"},m));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Me(i,()=>d(!i),n("modelStatsTitle"))),i?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},N("today",n("modelStatsToday")),N("history",n("modelStatsHistory"))),b.length===0?e("p",{className:"cm-note"},n("modelStatsEmpty")):e(j,null,e("div",{className:"cm-mstats-h"},n("modelStatsCostH")),b.map(g=>e(j,{key:"c:"+g.label},P(g.label,k>0?g.cost/k:0,"cost",$(g.cost,o),e(j,null,A(g),g.cacheUnreported?e("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},n("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),n("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),n("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),n("modelStatsOutput"))),[...b].sort((g,v)=>v.tokens-g.tokens).map(g=>e("div",{className:"cm-mstats-row",key:"t:"+g.label},e("span",{className:"cm-mstats-name"},g.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:w(p>0?g.input/p:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:w(p>0?(g.cacheRead+g.cacheWrite)/p:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:w(p>0?(g.output+g.reasoning)/p:0)}})),e("span",{className:"cm-mstats-val"},U(g.tokens)))),e("div",{className:"cm-mstats-h"},n("modelStatsHitH")),[...b].sort((g,v)=>(v.hitRate??-1)-(g.hitRate??-1)).map(g=>e(j,{key:"h:"+g.label},P(g.label,g.hitRate??0,"hit",g.cacheUnreported?n("modelStatsHitUnreported"):g.hitRate===null?"—":(g.hitRate*100).toFixed(1)+"%",g.cacheUnreported?e("span",{className:"cm-plan-tag",title:n("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},n("modelStatsValueH")),[...b].sort((g,v)=>(v.perUsd??-1)-(g.perUsd??-1)).map(g=>e(j,{key:"v:"+g.label},P(g.label,C>0?(g.perUsd??0)/C:0,"value",g.perUsd===null?"—":U(g.perUsd)+" tok/$"+(g.blended!==null?" · "+n("modelStatsBlended",{price:"$"+g.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},n("modelStatsNote")))):null)}function Un(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 qn(t,s){if(t==="go")return"OpenCode Go";const o=Te.find(n=>n.id===t);return o!==void 0?s(o.labelKey):t}const Zt=["fiveHour","weekly","monthly","daily"];function In(t,s){const o=new Map,n=a=>{const r=new Date(a),l=i=>String(i).padStart(2,"0");if(s==="monthly")return r.getFullYear()+"-"+l(r.getMonth()+1);if(s==="weekly"){const i=new Date(r.getFullYear(),r.getMonth(),r.getDate()-(r.getDay()+6)%7);return i.getFullYear()+"-"+l(i.getMonth()+1)+"-"+l(i.getDate())}return r.getFullYear()+"-"+l(r.getMonth()+1)+"-"+l(r.getDate())};for(const a of Object.values(t??{}))for(const r of a??[]){if(r===null||typeof r!="object"||!(r.tokens>0)&&!(r.cost>0))continue;const l=n(Number(r.t1)||Number(r.t0)),i=o.get(l)??{key:l,tokens:0,cost:0,pct:0,intervals:0};i.tokens+=Number(r.tokens)||0,i.cost+=Number(r.cost)||0,i.pct+=Number(r.pct)||0,i.intervals+=1,o.set(l,i)}return[...o.values()].map(a=>({...a,per1Tokens:a.pct>0?a.tokens/a.pct:null,fullTokens:a.pct>0?a.tokens/a.pct*100:null})).sort((a,r)=>a.key<r.key?-1:a.key>r.key?1:0)}function Qn(t){const{state:s,config:o,t:n}=t,[a,r]=O(!1),[l,i]=O("daily"),d=F(o?.locale),h=s?.planStats,u=h!=null&&typeof h.providers=="object"?h.providers:{},b=Object.keys(u).sort(),w=m=>$(Number(m)||0,o??s?.config),k=m=>m.method==="none"||m.per1Tokens===null?"—":U(m.per1Tokens)+" tok · "+w(m.per1Cost),p=m=>m.method==="none"||m.fullTokens===null?"—":U(m.fullTokens)+" tok · "+w(m.fullCost),C=m=>m.method==="sample"?n("planStatsMethodSample"):m.method==="live"?n("planStatsMethodLive"):n("planStatsMethodNone"),N=m=>{let S=C(m);return m.method==="sample"&&Number(m.sampleAt)>0&&(S=n("planStatsMethodSampleAt",{method:S,time:new Date(Number(m.sampleAt)).toLocaleString(d==="en"?"en-US":"zh-CN")})),(m.method==="sample"||m.method==="live")&&m.confidence==="low"&&(S+=" · "+n("planStatsConfidenceLow")),S},A=([m,S,M])=>e("tr",{key:S+":"+m},e("td",null,Un(m,d)),e("td",{className:"num"},Math.round(M.percent*10)/10+"%"),e("td",{className:"num"},U(M.localTokens)+" tok · "+w(M.localCost)),e("td",{className:"num"},k(M)),e("td",{className:"num"},p(M)),e("td",{className:"num cm-plan-reset"},M.resetsAt.length>0?n("planStatsResets",{time:new Date(M.resetsAt).toLocaleString(d==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},N(M))),P=a?b.flatMap(m=>Object.entries(u[m]?.intervals??{})).map(([m,S])=>({winKey:m,list:S})):[],g=In(Object.fromEntries(P.map(m=>[m.winKey,m.list])),l),v=g.reduce((m,S)=>Math.max(m,S.fullTokens??0),0),x=(m,S)=>e("button",{key:m,className:"cm-mstats-tab"+(l===m?" active":""),onClick:()=>i(m)},S);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Me(a,()=>r(!a),n("planStatsTitle"))),a?e("div",{className:"cm-collapse-body"},b.length===0?e("p",{className:"cm-empty"},n("planStatsEmpty")):e(j,null,b.map(m=>{const S=u[m]?.windows??{},M=[...Zt.filter(R=>S[R]!==void 0).map(R=>[R,m,S[R]]),...Object.keys(S).filter(R=>!Zt.includes(R)).map(R=>[R,m,S[R]])];return e("div",{key:m,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},qn(m,n),e("span",{className:"cm-plan-updated"},(()=>{const R=Number(u[m]?.generatedAt)||Number(h?.generatedAt)||0;return R>0?new Date(R).toLocaleTimeString(d==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,n("planStatsWindow")),e("th",{className:"num"},n("planStatsPercent")),e("th",null,n("planStatsLocal")),e("th",null,n("planStatsPer1")),e("th",null,n("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,M.map(A))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},n("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},x("daily",n("planStatsDaily")),x("weekly",n("planStatsWeekly")),x("monthly",n("planStatsMonthly"))),g.length===0?e("p",{className:"cm-note"},n("planStatsCurveEmpty")):e(j,null,[...g].reverse().map(m=>e("div",{className:"cm-mstats-row",key:m.key},e("span",{className:"cm-mstats-name"},m.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(v>0?(m.fullTokens??0)/v*100:0).toFixed(1)+"%"}})),e(X,{label:n("planStatsBarTip",{date:m.key,full:m.fullTokens===null?"—":U(m.fullTokens),per1:m.per1Tokens===null?"—":U(m.per1Tokens),tokens:U(m.tokens),cost:w(m.cost),intervals:m.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},m.fullTokens===null?"—":U(m.fullTokens)))))),e("p",{className:"cm-note"},n("planStatsNote")))):null)}function Xt(t){const{provider:s,modelId:o,entry:n,draft:a,setDraft:r,t:l}=t,i=u=>{const b={...a.prices.providers??{}},w=b[s]??{};b[s]={...w,models:u},r({...a,prices:{...a.prices,providers:b}})},d=(u,b)=>{if(a===null)return;const w={...(a.prices.providers??{})[s]?.models??{}};w[o]={...w[o]??{},[u]:Math.max(0,b)},i(w)},h=()=>{if(a===null)return;const u={...(a.prices.providers??{})[s]?.models??{}};delete u[o],i(u)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(j,null,n?.unpriced===!0?e("span",{className:"cm-price-legacy"},l("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:h},l("unmountBtn")))),n?.unpriced===!0?null:e(j,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"),le({value:n?.input??null,emptyMode:"ignore"},u=>d("input",u)),le({value:n?.cachedInput??null,emptyMode:"ignore"},u=>d("cachedInput",u)),le({value:n?.output??null,emptyMode:"ignore"},u=>d("output",u)))))}const Oe=t=>[e("option",{value:"sidebar"},t("balanceSidebar")),e("option",{value:"settings"},t("balanceSettings")),e("option",{value:"both"},t("balanceBoth")),e("option",{value:"off"},t("off"))],Ee=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function Fn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(!1),[d,h]=O(null),u=s.balance,b=s.config,w=s.reconcile,k=(a?.balance??b.balance??{}).reconcile!==!1,p=P=>{a===null||typeof r!="function"||r({...a,balance:{...a.balance??b.balance??{},reconcile:P.target.checked}})},C=async()=>{if(!l){i(!0),h(null);try{const P=await o.refreshBalance();h({kind:P.ok?"ok":"err",text:P.message})}catch(P){h({kind:"err",text:n("balanceRefreshFailed",{message:P?.message??String(P)})})}finally{i(!1)}}},N=P=>ke(P,b,u?.currency),A=u.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,n("balanceLine",{total:N(u.totalBalance),granted:N(u.grantedBalance),toppedUp:N(u.toppedUpBalance),time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},n("balanceQueryFailedHint",{message:u.message||n("unknownError")})):e("div",{className:"cm-bal-line"},n("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("accountBalance")),e("button",{className:"cm-btn small",onClick:C,disabled:l},n(l?"refreshing":"refreshBalance"))),A,w!==void 0&&w.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+w.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:k,onChange:p}),n("reconcileLabel")),Ee(d))}function _n(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,l=s.config,i=a?.customBalances??l.customBalances??[],d=w=>{a!==null&&r({...a,customBalances:w,...w.length===0?{customBalance:{...l.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},h=(w,k)=>{d(i.map((p,C)=>C===w?{...p,...k}:p))},u=w=>{d(i.filter((k,p)=>p!==w))},b=(w="custom")=>{i.length>=8||d([...i,{...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:[]}])};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("customBalanceTitle")),e("button",{className:"cm-btn small",onClick:()=>b(),disabled:i.length>=8},n("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>b("aliyun"),disabled:i.length>=8},n("aliyunBalanceAdd"))),e("p",{className:"cm-note"},n("customBalanceMultiNote")),i.length===0?e("p",{className:"cm-hint"},n("customBalanceEmpty")):i.map((w,k)=>e(Wn,{key:"cbe-"+k,state:s,api:o,t:n,entry:w,index:k,canRemove:!0,onPatch:p=>h(k,p),onRemove:()=>u(k)})))}function Wn(t){const{state:s,api:o,t:n,entry:a,index:r,canRemove:l,onPatch:i,onRemove:d}=t,h=a.adapter==="aliyun",[u,b]=O(!1),[w,k]=O(null),[p,C]=O(!1),[N,A]=O(()=>JSON.stringify(a.request?.headers??{},null,2)),[P,g]=O(()=>JSON.stringify(a.extract??{},null,2)),[v,x]=O(()=>(a.allowedHosts??[]).join(", ")),[m,S]=O({headers:"",extract:""}),M=Ae(!1),R=s.config,T=(Array.isArray(s.customBalances)?s.customBalances:[]).find(y=>y.index===r)??null,f=a.enabled===!0,L=()=>{C(y=>!y)};oe(()=>{p&&!M.current&&(A(JSON.stringify(a.request?.headers??{},null,2)),g(JSON.stringify(a.extract??{},null,2)),x((a.allowedHosts??[]).join(", ")),S({headers:"",extract:""})),M.current=p},[p]);const Y=(y,B)=>i({[y]:B}),re=(y,B)=>i({request:{...a.request??{},[y]:B}}),D=(()=>{if(h)return["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"];const y=new Set,B=[];for(const G of Object.values(a.request?.headers??{}))if(typeof G=="string")for(const Q of G.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g))y.has(Q[1])||(y.add(Q[1]),B.push(Q[1]));return B})(),E=y=>{A(y);try{const B=JSON.parse(y);if(B===null||typeof B!="object"||Array.isArray(B))throw new Error("invalid");if(Object.values(B).some(G=>typeof G!="string"))throw new Error("invalid");S(G=>({...G,headers:""})),re("headers",B)}catch{S(B=>({...B,headers:n("customBalanceInvalidJson")}))}},_=y=>{x(y);const B=y.split(/[\s,;]+/).map(G=>G.trim()).filter(G=>G.length>0);Y("allowedHosts",B)},I=y=>{g(y);try{const B=JSON.parse(y);if(B===null||typeof B!="object"||Array.isArray(B))throw new Error("invalid");S(G=>({...G,extract:""})),Y("extract",B)}catch{S(B=>({...B,extract:n("customBalanceInvalidJson")}))}},ee=async()=>{const y=(R.customBalances??[])[r];if(!(u||y?.enabled!==!0)){b(!0),k(null);try{const B=await o.refreshCustomBalance(r);k({kind:B.ok?"ok":"err",text:B.message})}catch(B){k({kind:"err",text:n("customBalanceRefreshFailed",{message:B?.message??String(B)})})}finally{b(!1)}}},ne=T!==null&&T.status==="ok"?e(j,null,R.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(lt,{segments:ot(s,R,T,a),direction:ae(R,"balance")}),e("div",{className:"cm-bal-line"},rt(T,R,n,s,a))):e("div",{className:"cm-bal-line"},n("customBalanceRemaining",{amount:ve(T.remaining,R,T,a)}))):T!==null&&T.status==="error"?e("div",{className:"cm-bal-line err"},T.message||n("unknownError")):e("div",{className:"cm-bal-line"},T?.message||n("balanceNotQueried")),c=p?e(j,null,e("p",{className:"cm-note"},n(h?"aliyunBalanceNote":"customBalanceConfigNote")),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("customBalanceLabelZh")),e("input",{className:"cm-input",value:a.label??"",onChange:y=>Y("label",y.target.value)})),e("div",{className:"cm-field"},e("label",null,n("customBalanceLabelEn")),e("input",{className:"cm-input",value:a.labelEn??"",onChange:y=>Y("labelEn",y.target.value)})),!h&&e("div",{className:"cm-field"},e("label",null,n("customBalanceUnitLabel")),e("select",{className:"cm-input",value:a.unit==="CNY"||a.unit==="EUR"?a.unit:"USD",onChange:y=>Y("unit",y.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"))),e("div",{className:"cm-field"},e("label",null,n("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:a.display??"both",onChange:y=>Y("display",y.target.value)},...Oe(n))),e("div",{className:"cm-field"},e("label",null,n("customBalanceRefreshInterval")),le({value:a.refreshMinutes??15},y=>Y("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(y)))))),!h&&e("div",{className:"cm-field"},e("label",null,n("customBalanceMethod")),e("select",{className:"cm-input",value:a.request?.method??"GET",onChange:y=>re("method",y.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceUrl")),e("input",{className:"cm-input",value:a.request?.url??"",placeholder:"https://example.com/key/info",onChange:y=>re("url",y.target.value)})),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceHeaders")),e("span",{className:"cm-hint"},n("customBalanceHeadersVarNote")),e("textarea",{className:"cm-input",rows:5,value:N,onChange:y=>E(y.target.value)}),m.headers?e("span",{className:"cm-hint err"},m.headers):null),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceCredentialsTitle")),D.length>0?e(j,null,!h&&e("span",{className:"cm-hint"},n("customBalanceCredentialsHint")),D.map(y=>e(Pe,{key:"cb-var-"+y,target:"customVar:"+y,configured:(s.customVarStatus?.[y]?.configured??!1)===!0,source:s.customVarStatus?.[y]?.source??"",t:n,api:o,placeholder:"{{"+y+"}}"}))):e("span",{className:"cm-hint"},n("customBalanceNoPlaceholders"))),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:v,placeholder:"api.example.com, relay.example.org",onChange:y=>_(y.target.value)}),e("span",{className:"cm-hint"},n("customBalanceAllowedHostsHint"))),!h&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,n("customBalanceExtract")),e("textarea",{className:"cm-input",rows:8,value:P,onChange:y=>I(y.target.value)}),m.extract?e("span",{className:"cm-hint err"},m.extract):null))):e("p",{className:"cm-note cm-collapsed-note"},Fe(a,F(R?.locale))||n("customBalanceTitle"));return e("div",{className:"cm-budget",style:{marginTop:"10px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},`#${r+1} · `+(Fe(a,F(R?.locale))||n("customBalanceTitle"))),e("button",{className:"cm-toggle-btn",onClick:L},n(p?"customBalanceCollapseConfig":"customBalanceOpenConfig")),e("button",{className:"cm-btn small",onClick:ee,disabled:u||f===!1},n(u?"refreshing":"refreshCustomBalance")),l?e("button",{className:"cm-btn small",onClick:d},n("customBalanceRemove")):null),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:f===!0,onChange:y=>Y("enabled",y.target.checked)}),e("span",null,n("enable"))),ne,c,Ee(w))}function zn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(!1),[d,h]=O(null),u=s.goQuota,b=s.config,w=a?.goQuota?.enabled??b.goQuota?.enabled??!0,k=(x,m)=>{a!==null&&r({...a,goQuota:{...a.goQuota??b.goQuota,[x]:m}})},p=async()=>{if(!(l||w===!1)){i(!0),h(null);try{const x=await o.refreshGoQuota();h({kind:x.ok?"ok":"err",text:x.message})}catch(x){h({kind:"err",text:n("syncFailed",{message:x?.message??String(x)})})}finally{i(!1)}}},C=b.goQuota?.main==="weekly"||b.goQuota?.main==="monthly"?b.goQuota.main:"rolling",N=[C,...["rolling","weekly","monthly"].filter(x=>x!==C)],A=x=>x==="rolling"?"goWindowRolling":x==="weekly"?"goWindowWeekly":"goWindowMonthly",P=x=>x==="rolling"?u.rolling:x==="weekly"?u.weekly:u.monthly,g=(x,m,S)=>{const M=m!==null&&typeof m=="object"&&typeof m.percent=="number",R=M?Math.max(0,Math.min(100,Number(m.percent)||0)):null,H=pe(R,ae(b,"go")),T=M&&typeof m.resetsAt=="string"&&m.resetsAt.length>0?n("goResetAt",{time:new Date(m.resetsAt).toLocaleString()}):"";return e("div",{className:"cm-go-row"+(S?" main":"")},e("span",{className:"cm-go-label"},n(x)),e("div",{className:"cm-go-bar"},R===null?null:e("div",{className:"cm-go-fill",style:{width:H.width+"%"}})),e("span",{className:"cm-go-num"},H.label===null?"—":n("goQuotaPercent",{percent:String(Math.round(H.label))})),T?e("span",{className:"cm-go-reset"},T):null)},v=w===!1?e("p",{className:"cm-note"},n("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},N.map(x=>g(A(x),P(x),x===C)),e("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||n("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},n("goQuotaNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("goQuotaTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:w===!0,onChange:x=>k("enabled",x.target.checked)}),e("span",null,n("enableGoQuota"))),e("button",{className:"cm-btn small",onClick:p,disabled:l||w===!1},n(l?"refreshing":"refreshGoQuota"))),v,Ee(d))}const Gn=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const n="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(a=>a===n||a.startsWith(n+"_"))??n};function Kn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(null),[d,h]=O({}),[u,b]=O({}),w=s.config,p=(a??w).gatewayQuotas?.sources??[],C=Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[],N=T=>{a!==null&&r({...a,gatewayQuotas:{...a.gatewayQuotas??w.gatewayQuotas??{},sources:T}})},A=(T,f)=>N(p.map((L,Y)=>Y===T?{...L,...f}:L)),P=T=>b(f=>({...f,[T]:f[T]!==!0})),g=async T=>{if(l!==null)return;const f=(w.gatewayQuotas?.sources??[]).find(L=>L.id===T);if(!(!f||f.enabled!==!0||f.display==="off")){i(T),h(L=>({...L,[T]:null}));try{const L=await o.refreshGatewayQuota(T);h(Y=>({...Y,[T]:{kind:L.ok?"ok":"err",text:L.message}}))}catch(L){h(Y=>({...Y,[T]:{kind:"err",text:L?.message??String(L)}}))}finally{i(null)}}},v=()=>{if(p.length>=4)return;const T="gateway-"+Date.now().toString(36);b(f=>({...f,[T]:!0})),N([...p,{id:T,type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:$e,allowedHosts:[],allowInsecureHttp:!1}])},x=(T,f,L)=>e("div",{className:"cm-field"},e("label",null,T),e("input",{className:"cm-input",value:f??"",onChange:L})),m=(T,f)=>{const L=Le(T?.label||T?.id||n("gatewaySourceUnknown"),T,ae(w,"plan"));return e(j,{key:T?.id||f},L.row,T?.resetsAt?e("div",{className:"cm-note"},Ge(T,n)):null)},S=T=>e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},T.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(T.used??"—")+" / "+(T.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(T.remaining??"—")+" remaining")),M=T=>T==null?null:e(j,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},T.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(T.used??"—")+" / "+(T.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(T.remaining??"—")+" remaining")),(T.packages??[]).map(S)),R=(T,f)=>e("div",{key:T.id||f,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Nt[T.provider]??T.provider??n("gatewaySourceUnknown"))+" · "+(T.label||n("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},T.status)),T.plan?e("div",{className:"cm-note"},T.plan):null,T.windows.length>0?e("div",{className:"cm-go-list"},T.windows.map(m)):null,M(T.credits),T.message?e("div",{className:"cm-note"},T.message):null),H=(T,f)=>{const L=C.find(D=>D.id===T.id)??{id:T.id,status:"off",accounts:[],unsupportedProviders:[]},Y=Gn(T,s.customVarStatus),re=u[T.id]===!0;return e("div",{key:T.id||f,className:"cm-budget"},e("div",{className:"cm-budget-head"},Me(re,()=>P(T.id),T.label||T.id||n("gatewayQuotaTitle")),re?null:e("span",{className:"cm-hint"},L.status??n("gatewaySourceUnknown")),e("button",{className:"cm-btn small",onClick:()=>g(T.id),disabled:l!==null||T.enabled!==!0},l===T.id?n("gatewaySourceRefreshing"):n("refreshGoQuota")),e("button",{className:"cm-btn small",onClick:()=>N(p.filter((D,E)=>E!==f))},n("gatewaySourceRemove"))),re?e("div",{className:"cm-collapse-body"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:T.enabled===!0,onChange:D=>A(f,{enabled:D.target.checked})}),n("gatewaySourceEnabled")),e("div",{className:"cm-grid"},x(n("gatewaySourceLabel"),T.label,D=>A(f,{label:D.target.value})),x(n("gatewaySourceBaseURL"),T.baseURL,D=>A(f,{baseURL:D.target.value})),e("div",{className:"cm-field"},e("label",null,n("gatewaySourceDisplay")),e("select",{className:"cm-input",value:T.display??"both",onChange:D=>A(f,{display:D.target.value})},...Oe(n))),x(n("gatewaySourceAllowlist"),(T.allowedHosts??[]).join(", "),D=>A(f,{allowedHosts:D.target.value.split(/[\s,;]+/).filter(Boolean)}))),Y?e("div",{className:"cm-field"},e("label",null,n("gatewaySourceCredential")),e(Pe,{target:"customVar:"+Y,configured:s.customVarStatus?.[Y]?.configured===!0,source:s.customVarStatus?.[Y]?.source??"",t:n,api:o,placeholder:Y})):null,e("div",{className:"cm-note"},n("gatewaySourceStatus")+": "+(L.status??n("gatewaySourceUnknown"))+(L.serverVersion?" · "+L.serverVersion:"")+(L.fetchedAt>0?" · "+n("gatewaySourceFetchedAt",{time:new Date(L.fetchedAt).toLocaleTimeString()}):"")+(L.message?" · "+L.message:"")),L.unsupportedProviders.length>0?e("div",{className:"cm-note"},n("gatewaySourceUnsupported")+": "+L.unsupportedProviders.join(", ")):null,L.accounts.length>0?L.accounts.map(R):e("div",{className:"cm-bal-line"},n("gatewaySourceNoAccounts")),d[T.id]?e("div",{className:"cm-msg "+d[T.id].kind},d[T.id].text):null):null)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("gatewayQuotaTitle")),e("button",{className:"cm-btn small",onClick:v,disabled:p.length>=4},n("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>o.refreshGatewayQuota(),disabled:l!==null||p.length===0},n(l===null?"refreshGoQuota":"gatewaySourceRefreshing"))),e("p",{className:"cm-note"},n("gatewayQuotaNote")),p.length===0?e("p",{className:"cm-hint"},n("gatewaySourceEmpty")):p.map(H))}const Te=[{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"}],ea="dsh-cost-meter.codingPlans.open";function Vn(){try{return window.localStorage.getItem(ea)==="1"}catch{return!1}}function Yn(t){const{state:s,api:o,t:n,draft:a,setDraft:r}=t,[l,i]=O(null),[d,h]=O({}),[u,b]=O(Vn),w=()=>{b(D=>{const E=!D;try{window.localStorage.setItem(ea,E?"1":"0")}catch{}return E})},k=s.codingPlans??{},p=s.config,C=D=>a?.codingPlans?.[D]??p.codingPlans?.[D]??{},N=D=>k[D]??{status:"off",message:"",fetchedAt:0,windows:{}},A=(D,E,_)=>{if(a===null)return;const I=a.codingPlans??p.codingPlans??{};r({...a,codingPlans:{...I,[D]:{...I[D]??{},[E]:_}}})},[P,g]=O(""),[v,x]=O({}),m=D=>D?.rates!==null&&typeof D?.rates=="object"&&!Array.isArray(D.rates)?D.rates:{},S=["input","cachedInput","output"],M=D=>v[D]??m(C("qwen"))[D]??{},R=D=>S.every(E=>Number.isFinite(Number(D[E]))&&Number(D[E])>0),H=(D,E,_)=>{if(a===null)return;const I={...M(D),[E]:String(_)};x(y=>({...y,[D]:I}));const ee=S.every(y=>String(I[y]??"").trim()==="");if(!ee&&!R(I))return;const ne=a.codingPlans??p.codingPlans??{},c={...(ne.qwen??{}).rates??{}};ee?delete c[D]:c[D]=Object.fromEntries(S.map(y=>[y,Number(I[y])])),r({...a,codingPlans:{...ne,qwen:{...ne.qwen??{},rates:c}}})},T=D=>{a!==null&&x(E=>({...E,[D]:E[D]??m(C("qwen"))[D]??{}}))},f=D=>{if(a===null)return;x(I=>{const ee={...I};return delete ee[D],ee});const E=a.codingPlans??p.codingPlans??{},_={...(E.qwen??{}).rates??{}};delete _[D],r({...a,codingPlans:{...E,qwen:{...E.qwen??{},rates:_}}})},L=async D=>{if(l===null){i(D),h(E=>({...E,[D]:null}));try{const E=await o.refreshCodingPlan(D);h(_=>({..._,[D]:{kind:E.ok?"ok":"err",text:E.message}}))}catch(E){h(_=>({..._,[D]:{kind:"err",text:n("syncFailed",{message:E?.message??String(E)})}}))}finally{i(null)}}},Y=(D,E)=>{if(typeof E?.percent!="number")return e("div",{className:"cm-go-row"},e("span",{className:"cm-go-label"},D.replace(/_/g," ")),e("span",{className:"cm-go-num"},typeof E?.text=="string"?E.text:"—"));const _=E?Math.max(0,Math.min(100,Number(E.percent)||0)):0,I=pe(_,ae(p,"plan")),ee=E&&typeof E.resetsAt=="string"&&E.resetsAt.length>0?n("goResetAt",{time:new Date(E.resetsAt).toLocaleString()}):"";return e("div",{className:"cm-go-row"},e("span",{className:"cm-go-label"},D.replace(/_/g," ")),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:I.width+"%"}})),e("span",{className:"cm-go-num"},n("goQuotaPercent",{percent:String(Math.round(I.label))})),ee?e("span",{className:"cm-go-reset"},ee):null)},re=({id:D,labelKey:E})=>{const _=C(D),I=N(D),ee=_.enabled===!0,ne=I.windows!==null&&typeof I.windows=="object"?I.windows:{},c=ee===!1?e("p",{className:"cm-note"},n("codingPlanDisabledNote")):I.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(ne).length>0?D==="minimax"&&(De(ne).five!=null||De(ne).seven!=null)?e(Gt,{five:De(ne).five,seven:De(ne).seven,fetchedAt:I.fetchedAt,t:n,wide:!0,direction:ae(p,"plan")}):Object.entries(ne).map(([y,B])=>Y(y,B)):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried")),e("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:I.fetchedAt>0?new Date(I.fetchedAt).toLocaleTimeString():"—"}))):I.status==="error"?e("div",{className:"cm-bal-line err"},I.message||n("unknownError")):I.status==="off"&&I.message?e("p",{className:"cm-note"},I.message):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried"));return e("div",{key:D,className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n(E)),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:ee,onChange:y=>A(D,"enabled",y.target.checked)}),e("span",null,n("enableCodingPlan"))),e("button",{className:"cm-btn small",onClick:()=>{L(D)},disabled:l!==null||ee===!1},n(l===D?"refreshing":"refreshCodingPlan"))),ee?e("div",{className:"cm-field"},e("label",null,n("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof _.display=="string"?_.display:D==="minimax"?"both":"settings",onChange:y=>A(D,"display",y.target.value)},e("option",{value:"sidebar"},n("balanceSidebar")),e("option",{value:"settings"},n("balanceSettings")),e("option",{value:"both"},n("balanceBoth")),e("option",{value:"off"},n("off"))),e("span",{className:"cm-hint"},n("codingPlanDisplayNote"))):null,ee&&D!=="scnet"&&D!=="qwen"?e("div",{className:"cm-field"},e("label",null,n("codingPlanRefreshIntervalLabel")),le({value:typeof _.refreshMinutes=="number"&&Number.isFinite(_.refreshMinutes)&&_.refreshMinutes>0?_.refreshMinutes:15},y=>{A(D,"refreshMinutes",Math.min(1440,Math.max(1,Math.floor(y))))})):null,ee?D==="scnet"||D==="qwen"?e(j,null,e("div",{className:"cm-field"},e("label",null,n(D==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof _.planCredits=="number"&&Number.isFinite(_.planCredits)&&_.planCredits>0?_.planCredits:D==="qwen"?5e5:24e4,onChange:y=>{const B=Number(y.target.value);Number.isFinite(B)&&B>0&&A(D,"planCredits",Math.floor(B))}})),e("div",{className:"cm-field"},e("label",null,n(D==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof _.planStart=="string"?_.planStart:"",onChange:y=>A(D,"planStart",y.target.value)})),D==="qwen"?e(j,null,e("div",{className:"cm-field"},e("label",null,n("qwenRatesLabel"))),[...new Set([...Object.keys(m(_)),...Object.keys(v)])].sort().map(y=>e("div",{key:y,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},y),S.map(B=>e("input",{key:B,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:M(y)[B]??"",placeholder:n("qwenRate_"+B),"aria-label":y+" · "+n("qwenRate_"+B),onChange:G=>{const Q=G.target.value;H(y,B,Q)}})),e("button",{className:"cm-btn small",onClick:()=>f(y)},n("overrideRemove")),y in v&&!R(M(y))?e("span",{className:"cm-note"},n("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:n("qwenRatesModelPlaceholder"),value:P,onChange:y=>g(y.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const y=P.trim();y.length!==0&&(T(y),g(""))},disabled:P.trim().length===0},n("qwenRatesAdd")))):null,e("p",{className:"cm-note"},n(D==="qwen"?"qwenLocalNote":"scnetLocalNote"))):D==="volcengine"?e(j,null,e("div",{className:"cm-field"},e("label",null,n("volcengineAccessKeyIdLabel"))),e(Pe,{target:"codingPlans.volcengine.ak",configured:I.keyConfigured===!0,source:I.keySource,t:n,api:o,placeholder:n("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,n("volcengineSecretAccessKeyLabel"))),e(Pe,{target:"codingPlans.volcengine.sk",configured:I.keyConfigured===!0,source:I.keySource,t:n,api:o,placeholder:n("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},n("volcengineNote"))):e(j,null,e("div",{className:"cm-field"},e("label",null,n("codingPlanKeyLabel"))),e(Pe,{target:"codingPlans."+D,configured:I.keyConfigured===!0,source:I.keySource,t:n,api:o,placeholder:"sk-…"})):null,c,d[D]!=null?e("div",{className:"cm-msg "+d[D].kind},d[D].text):null)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("codingPlansTitle")),e("button",{className:"cm-toggle-btn",onClick:w},n(u?"codingPlansCollapse":"codingPlansOpen"))),u?e(j,null,e("p",{className:"cm-note"},n("codingPlansNote")),Te.map(re)):e("p",{className:"cm-note cm-collapsed-note"},n("codingPlansCollapsedHint")))}const Jn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ta=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function gt(t){const s=t.useCost?t.useCost(v=>v):void 0,o=t.state??s?.state;if(!o)return null;const n=o.config,a=F(n?.locale),r=t.t??V(a),l=Array.isArray(o.history)?o.history:[];if(l.length===0)return e("div",null,e("h3",{className:"cm-h"},r("usageTitle")),e("p",{className:"cm-empty"},r("usageEmpty")));const i=o.meta?.dayKey??"",d=new Map(l.map(v=>[v.date,v])),h=v=>{const x=m=>String(m).padStart(2,"0");return v.getFullYear()+"-"+x(v.getMonth()+1)+"-"+x(v.getDate())},u=new Date;u.setHours(0,0,0,0);const b=new Date(u);b.setDate(b.getDate()+(6-(u.getDay()+6)%7));const w=26,k=[],p=[];let C=-1;for(let v=w-1;v>=0;v-=1){for(let m=0;m<7;m+=1){const S=new Date(b);S.setDate(S.getDate()-(v*7+(6-m)));const M=d.get(h(S));k.push(M!==void 0?{day:M,tokens:ta(M)}:{day:{date:h(S)},tokens:0})}const x=new Date(b);x.setDate(x.getDate()-(v*7+6)),p.push(x.getMonth()!==C?a==="en"?Jn[x.getMonth()]:String(x.getMonth()+1)+"月":""),C=x.getMonth()}const N=Math.max(...k.map(v=>v.tokens),1),A=v=>{const x=v/N;return x<.25?1:x<.5?2:x<.75?3:4},P=v=>{const{day:x,tokens:m}=v,S="cm-ug-cell"+(m>0?" l"+A(m):"")+(x.date===i?" today":""),M=r("usageDay",{date:x.date,tokens:U(m),input:U(x.input??0),cache:U((x.cacheRead??0)+(x.cacheWrite??0)),output:U(x.output??0),calls:x.calls??0,cost:$(z(x,n),n)});return e(X,{key:x.date,label:M,side:"top",delayMs:200},e("div",{className:S}))},g=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},r("usageTitle")),e("div",{className:"cm-ug-total"},r("usageTotal",{tokens:U(ta(g)),input:U(g.input??0),cache:U((g.cacheRead??0)+(g.cacheWrite??0)),output:U(g.output??0),calls:g.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+w+",1fr)"}},k.map(P)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+w+",1fr)"}},p.map((v,x)=>e("span",{key:"m"+String(x),className:"cm-ug-monthc"},v))))}function $n(t){const s=t.useCost?t.useCost(c=>c):void 0,o=t.api,n=s?.state??null,[a,r]=O(null),[l,i]=O(null),[d,h]=O(!1),[u,b]=O(!1),[w,k]=O(!1),[p,C]=O(""),[N,A]=O(!1),[P,g]=O(!1),[v,x]=O("overview"),[m,S]=O({status:"idle",at:0,error:null}),M=Re.useRef(null),R=Re.useRef(null),H=Re.useRef(null);oe(()=>{if(n!==null){const c=JSON.stringify(n.config);r(y=>{const B=y!==null&&JSON.stringify(y)!==M.current;return B||(R.current=n.config,H.current=n.config),B?y:JSON.parse(c)}),M.current=c}},[n]),oe(()=>{a!==null&&H.current===null&&R.current!==null&&(H.current=R.current)},[a]),oe(()=>{if(a===null||o===void 0)return;const c=JSON.stringify(a);if(c===M.current)return;S(B=>B.status==="saving"?B:{...B,status:"saving"});const y=setTimeout(()=>{const B={},G=H.current??R.current;if(G!==null&&typeof G=="object")for(const Q of Object.keys(a))JSON.stringify(a[Q])!==JSON.stringify(G[Q])&&(B[Q]=a[Q]);if(Object.keys(B).length===0){M.current=c,S({status:"saved",at:Date.now(),error:null});return}o.updateConfig(B).then(()=>{M.current=c,G!==null&&typeof G=="object"&&(H.current={...G,...B}),S({status:"saved",at:Date.now(),error:null})},Q=>{S({status:"error",at:0,error:Q?.message??String(Q)})})},600);return()=>{clearTimeout(y)}},[a,o]),oe(()=>{s?.status==="error"&&s.error&&i({kind:"err",text:f("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const T=F((a??n?.config)?.locale),f=V(T);if(s===void 0||n===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?f("readingLedger"):f("ledgerUnavailable")));const L=n.config,Y=async()=>{if(!N){A(!0),i(null);try{const c=await o.fetchPrices();if(i({kind:c.ok?"ok":"err",text:c.message}),c.ok&&c.state&&typeof c.state.config=="object"){const y=JSON.stringify(c.state.config);r(JSON.parse(y)),M.current=y}}catch(c){i({kind:"err",text:f("syncFailed",{message:c?.message??String(c)})})}finally{A(!1),h(!1)}}},re=async()=>{if(!N){A(!0);try{await o.resetHistory(),i({kind:"ok",text:f("historyCleared")})}catch(c){i({kind:"err",text:f("clearFailed",{message:c?.message??String(c)})})}finally{A(!1),b(!1)}}},D=async()=>{if(!N){A(!0),i(null);try{const c=await o.importLegacyHistory();i({kind:"ok",text:c.message})}catch(c){i({kind:"err",text:f("legacyImportFailed",{message:c?.message??String(c)})})}finally{A(!1),k(!1)}}},E=(c,y)=>{a!==null&&r({...a,[c]:y})},_=()=>{if(a===null)return;const c=p.trim().toLowerCase();if(c.length===0||!/^[a-z0-9_.-]+$/.test(c)||a?.prices.models[c]!==void 0)return;const y={...a.prices.models,[c]:{cacheHit:0,cacheMiss:0,output:0}};r({...a,prices:{...a.prices,models:y}}),C("")},I=a===null?[]:Object.keys(a.prices.models).filter(c=>{const B=(a?.priceTableDisplay??L.priceTableDisplay??{})["deepseek:"+c];return typeof B=="boolean"?B:!0}).map(c=>e(ft,{key:c,modelId:c,entry:a.prices.models[c]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:a,setDraft:r,t:f})),ee=[["overview",f("tabOverview")],["quotas",f("tabQuotas")],["usage",f("tabUsage")],["pricing",f("tabPricing")],["display",f("tabDisplay")]],ne=m.status==="saving"?e("span",{className:"cm-hint"},f("saving")):m.status==="error"?e("span",{className:"cm-msg err"},f("autoSaveFailed",{message:m.error??""})):e("span",{className:"cm-hint"},m.status==="saved"?f("autoSavedAt",{time:new Date(m.at).toLocaleTimeString()}):f("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},ee.map(([c,y])=>e("button",{key:c,type:"button",role:"tab","aria-selected":String(v===c),className:"cm-tab"+(v===c?" active":""),onClick:()=>x(c)},y))),ne),Ee(l),v==="overview"?e(j,{key:"overview"},e("div",{className:"cm-cards"},L.hideTodayCost===!0?null:e(mt,{title:f("cardToday"),value:$(z(n.today,L),L),sub:f("callsTokens",{calls:n.today.calls,input:U(n.today.input),cache:U(n.today.cacheRead+n.today.cacheWrite),output:U(n.today.output)})}),e(mt,{title:f("cardMonth"),value:$(z(n.month,L),L),sub:f("callsTokens",{calls:n.month.calls,input:U(n.month.input),cache:U(n.month.cacheRead+n.month.cacheWrite),output:U(n.month.output)})}),e(mt,{title:f("cardTotal"),value:$(z(n.total,L),L),sub:f("cardTotalSub",{calls:n.total.calls})})),e("p",{className:"cm-note",key:"cards-footnote"},f("cardsFootnote")),(()=>{const c=Ua(n);return c!==null?e("p",{className:"cm-note",key:"tz-hint"},f("timezoneHint",{host:c.hostLabel,browser:c.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:f("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(a??L).showTotalWithPlan===!0,onChange:c=>{const y=a??L;y!=null&&r({...y,showTotalWithPlan:c.target.checked})}}),e("span",null,f("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},f("todaySessions")),e(Rn,{state:n,t:f})),e(Ln,{state:n,draft:a,setDraft:r,t:f}),(L.balance?.display==="settings"||L.balance?.display==="both")&&L.hideOfficialBalance!==!0?e(Fn,{state:n,api:o,t:f,draft:a,setDraft:r}):null):null,v==="quotas"?e(j,{key:"quotas"},e(Kn,{state:n,api:o,t:f,draft:a,setDraft:r}),e(zn,{state:n,api:o,t:f,draft:a,setDraft:r}),e(Yn,{state:n,api:o,t:f,draft:a,setDraft:r}),e(_n,{state:n,api:o,t:f,draft:a,setDraft:r})):null,v==="usage"?e(j,{key:"usage"},!je||(L.usage?.position??"cost")==="cost"?e(gt,{state:n,t:f,locale:T}):null,e(Hn,{state:n,config:a??L,t:f}),e(Qn,{state:n,config:a??L,t:f}),e(Mn,{state:n,api:o}),e(Bn,{state:n,api:o}),e("div",null,e("h3",{className:"cm-h"},f("historyDataTitle")),e("div",{className:"cm-buttons"},w?e(j,null,e("span",{className:"cm-hint"},f("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:D,disabled:N},f("apply")),e("button",{className:"cm-btn",onClick:()=>k(!1)},f("cancel"))):e("button",{className:"cm-btn",onClick:()=>k(!0),disabled:N},f("importLegacy")),u?e(j,null,e("span",{className:"cm-hint"},f("confirmReset")),e("button",{className:"cm-btn danger",onClick:re,disabled:N},f("confirmClear")),e("button",{className:"cm-btn",onClick:()=>b(!1)},f("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>b(!0),disabled:N},f("clearAllHistory"))),e("p",{className:"cm-note"},f("legacyImportNote")))):null,v==="display"?e(j,{key:"display"},n?.secretMigration?.pending?.length>0?e(Ia,{pending:n.secretMigration.pending,t:f}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,f("languageLabel")),e("select",{className:"cm-input",value:a?.locale??"auto",onChange:c=>E("locale",c.target.value)},e("option",{value:"auto"},f("localeAuto")),e("option",{value:"zh"},f("localeZh")),e("option",{value:"en"},f("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},f("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},f("groupGeneral")),je?e("div",{className:"cm-field"},e("label",null,f("usagePositionLabel")),e("select",{className:"cm-input",value:a?.usage?.position??"cost",onChange:c=>{a!==null&&r({...a,usage:{...a.usage??{position:"cost"},position:c.target.value}})}},e("option",{value:"cost"},f("usagePositionCost")),e("option",{value:"general"},f("usagePositionGeneral")),e("option",{value:"section"},f("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,f("positionLabel")),e("select",{className:"cm-input",value:a?.position??"dock",onChange:c=>E("position",c.target.value)},e("option",{value:"dock"},f("positionDock")),e("option",{value:"header"},f("positionHeader")),e("option",{value:"off"},f("off")))),e("div",{className:"cm-field"},e("label",null,f("sidebarLabel")),e("select",{className:"cm-input",value:a?.sidebar===!1?"off":"on",onChange:c=>E("sidebar",c.target.value==="on")},e("option",{value:"on"},f("sidebarOn")),e("option",{value:"off"},f("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.showSessionId===!0,onChange:c=>E("showSessionId",c.target.checked)}),e("span",null,f("showSessionIdLabel"))),e("div",{className:"cm-grid-group"},f("groupMoney")),e("div",{className:"cm-field"},e("label",null,f("currencyLabel")),e("select",{className:"cm-input",value:a?.currency??"CNY",onChange:c=>{const y=Dn[c.target.value];y!==void 0&&a!==null&&r({...a,currency:c.target.value,...y})}},e("option",{value:"CNY"},f("currencyCny")),e("option",{value:"USD"},f("currencyUsd")),e("option",{value:"EUR"},f("currencyEur")))),e("div",{className:"cm-field"},e("label",null,f("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:a?.symbol??"",onChange:c=>E("symbol",c.target.value)})),e("div",{className:"cm-field"},e("label",null,f("rateLabel")),le({value:a?.exchangeRate??1,emptyMode:"ignore"},c=>E("exchangeRate",c))),e("div",{className:"cm-field"},e("label",null,f("decimalsLabel")),le({value:a?.decimals??2},c=>E("decimals",Math.min(10,Math.floor(c))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.hideOfficialBalance===!0,onChange:c=>E("hideOfficialBalance",c.target.checked)}),e("span",null,f("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.hideTodayCost===!0,onChange:c=>E("hideTodayCost",c.target.checked)}),e("span",null,f("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},f("groupSidebar")),e("div",{className:"cm-field"},e("label",null,f("sidebarStyleLabel")),e("select",{className:"cm-input",value:a?.sidebarStyle??"standard",onChange:c=>E("sidebarStyle",c.target.value)},e("option",{value:"standard"},f("sidebarStyleStandard")),e("option",{value:"compact"},f("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,f("balanceDisplayLabel")),e("select",{className:"cm-input",value:a?.balance?.display??"both",onChange:c=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5},display:c.target.value}})}},...Oe(f))),e("div",{className:"cm-field"},e("label",null,f("refreshIntervalLabel")),le({value:a?.balance?.refreshMinutes??5},c=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(c)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.balance?.showProgressBar===!0,onChange:c=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:c.target.checked}})}}),e("span",null,f("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,f("balanceBudgetCapLabel")),le({value:a?.balance?.budgetCap??""},c=>{a!==null&&r({...a,balance:{...a.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:c>0?c:null}})}),e("span",{className:"cm-hint"},f("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,f("barDirectionsTitle")),["balance","budget","go","plan"].map(c=>e("div",{className:"cm-dir-row",key:c},e("span",{className:"cm-dir-label"},f("barDirection_"+c)),e("select",{className:"cm-input",value:a?.barDirections?.[c]??(c==="balance"?"remaining":"used"),onChange:y=>{if(a===null)return;const B={balance:"remaining",budget:"used",go:"used",plan:"used"};r({...a,barDirections:{...a.barDirections??B,[c]:y.target.value}})}},e("option",{value:"remaining"},f("barDirectionRemaining")),e("option",{value:"used"},f("barDirectionUsed"))))),e("span",{className:"cm-hint"},f("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,f("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:a?.customBalance?.display??L.customBalance?.display??"both",onChange:c=>{a!==null&&r({...a,customBalance:{...a.customBalance??L.customBalance??{},display:c.target.value}})}},...Oe(f))),e("div",{className:"cm-field"},e("label",null,f("customBalanceRefreshInterval")),le({value:a?.customBalance?.refreshMinutes??L.customBalance?.refreshMinutes??15},c=>{a!==null&&r({...a,customBalance:{...a.customBalance??L.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(c)))}})})),e("div",{className:"cm-field"},e("label",null,f("goQuotaDisplayLabel")),e("select",{className:"cm-input",value:a?.goQuota?.display??"both",onChange:c=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:""},display:c.target.value}})}},...Oe(f))),e("div",{className:"cm-field"},e("label",null,f("goMainLabel")),e("select",{className:"cm-input",value:a?.goQuota?.main??"rolling",onChange:c=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling"},main:c.target.value}})}},e("option",{value:"rolling"},f("goWindowRolling")),e("option",{value:"weekly"},f("goWindowWeekly")),e("option",{value:"monthly"},f("goWindowMonthly")))),e("div",{className:"cm-field"},e("label",null,f("goQuotaRefreshIntervalLabel")),e("div",{className:"cm-range-row"},e("input",{className:"cm-range",type:"range",min:"1",max:"60",step:"1",value:Math.min(60,Math.max(1,Math.floor(Number(a?.goQuota?.refreshMinutes)||15))),onChange:c=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:""},refreshMinutes:Math.min(60,Math.max(1,Math.floor(Number(c.target.value)||15)))}})}}),e("span",{className:"cm-range-value"},`${Math.min(60,Math.max(1,Math.floor(Number(a?.goQuota?.refreshMinutes)||15)))} ${f("goQuotaRefreshMinutesUnit")}`))),e("div",{className:"cm-field"},e("label",null,f("goQuotaKeyLabel"))),e(Pe,{target:"goQuota",configured:L.goQuota?.keyConfigured===!0,source:L.goQuota?.keySource,t:f,api:o,placeholder:"sk-…"}),e("div",{className:"cm-grid-group"},f("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.quotaStrip?.enabled===!0,onChange:c=>{a!==null&&r({...a,quotaStrip:{...a.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:c.target.checked,promptSeen:!0}})}}),e("span",null,f("quotaStripEnable")))),a?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([c,y])=>e("label",{key:c,className:"cm-check"},e("input",{type:"checkbox",checked:a.quotaStrip[c]!==!1,onChange:B=>{a!==null&&r({...a,quotaStrip:{...a.quotaStrip,[c]:B.target.checked}})}}),e("span",null,f(y)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},f("quotaStripNote"))),e("div",{className:"cm-grid-group"},f("groupCorner")),e("div",{className:"cm-field"},e("label",null,f("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.corner?.enabled===!0,onChange:c=>{a!==null&&r({...a,corner:{...a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:c.target.checked}})}}),e("span",null,f("cornerEnabledLabel"))),a?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([c,y])=>e("label",{key:c,className:"cm-check"},e("input",{type:"checkbox",checked:a.corner[c]!==!1,onChange:B=>{a!==null&&r({...a,corner:{...a.corner,[c]:B.target.checked}})}}),e("span",null,f(y)))):null),e("div",{className:"cm-grid-group"},f("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.goQuota?.detail!==!1,onChange:c=>{a!==null&&r({...a,goQuota:{...a.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:c.target.checked}})}}),e("span",null,f("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:a?.budget?.detail!==!1,onChange:c=>{a!==null&&r({...a,budget:{...a.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:c.target.checked}})}}),e("span",null,f("budgetDetailLabel"))))),e("p",{className:"cm-note"},f("badgeNote")))):null,v==="pricing"?e(j,{key:"pricing"},e(On,{state:n,draft:a,setDraft:r,t:f}),e("div",null,Me(P,()=>g(!P),f("priceTableTitle")),P?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},f("priceTableNote")),e("p",{className:"cm-hint"},f("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},f("deepseekMountedHeader")),I,e(ft,{key:"__default__",modelId:f("defaultModelId"),entry:a?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:a,setDraft:r,t:f}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:f("newModelPlaceholder"),value:p,onChange:c=>C(c.target.value)}),e("button",{className:"cm-btn small",onClick:_,disabled:p.trim().length===0},f("addModel"))),(()=>{const c=a?.priceTableDisplay??L.priceTableDisplay??{},y=a?.prices?.providers??{},B=Q=>Object.keys(y[Q]?.models??{}).filter(se=>c[Q+":"+se]===!0),G=Object.keys(y).filter(Q=>B(Q).length>0).sort((Q,se)=>Q.localeCompare(se));return G.length===0?null:G.map(Q=>e("div",{key:Q},e("div",{className:"cm-catalog-vendor"},(Yt[Q]??Q)+" · "+f("mountedSuffix")),B(Q).sort().map(se=>e(Xt,{key:Q+":"+se,provider:Q,modelId:se,entry:y[Q].models[se],draft:a,setDraft:r,t:f}))))})()):null),(()=>{const c=a?.priceOverrides??L.priceOverrides??{},y=a?.priceMatchDismissed??L.priceMatchDismissed??[],B=a?.prices??L.prices,G=n.today.byProviderModel??{},Q={prices:B,priceMatch:a?.priceMatch??L.priceMatch},se=Object.keys(G).filter(q=>{if(y.includes(q)||c[q]!==void 0)return!1;const K=q.indexOf(":"),be=(K>0?q.slice(0,K):"deepseek").toLowerCase(),bt=K>0?q.slice(K+1):q;return Xe(be,bt,Q).matched!==!0}),me=[...new Set([...se,...Object.keys(c)])].filter(q=>!y.includes(q)),xe=n.month?.byProviderModel??{},Ne=Object.keys(xe).filter(q=>{if(y.includes(q)||c[q]!==void 0)return!1;const K=q.indexOf(":"),be=(K>0?q.slice(0,K):"deepseek").toLowerCase(),bt=K>0?q.slice(K+1):q;return Xe(be,bt,Q).matched===!0}).sort(),Be=[{value:"__local__",label:f("overrideTargetLocal")},{value:"deepseek:__default__",label:f("overrideTargetDefault")},...Object.keys(B.models??{}).map(q=>({value:"deepseek:"+q,label:"DeepSeek · "+q})),...Object.entries(B.providers??{}).flatMap(([q,K])=>Object.keys(K?.models??{}).map(be=>({value:q+":"+be,label:q+" · "+be})))],aa=(q,K)=>{if(a===null)return;const be={...a.priceOverrides??{}};K===""?delete be[q]:be[q]=K,r({...a,priceOverrides:be})},es=q=>{if(a===null)return;const K={...a.priceOverrides??{}};delete K[q],r({...a,priceOverrides:K,priceMatchDismissed:[...new Set([...y,q])]})};return e("div",null,e("h3",{className:"cm-h"},f("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:a?.priceMatch==="exact"?"exact":"auto",onChange:q=>E("priceMatch",q.target.value)},e("option",{value:"auto"},f("priceMatchAuto")),e("option",{value:"exact"},f("priceMatchExact")))),e("p",{className:"cm-note"},f("priceMatchNote")),me.length>0?e(j,null,e("h3",{className:"cm-h"},f("unmatchedTitle")),e("p",{className:"cm-hint"},f("unmatchedHint")),me.map(q=>e("div",{key:q,className:"cm-match-row"},e("span",null,$t(q)),e("select",{className:"cm-input",value:c[q]??"",onChange:K=>aa(q,K.target.value)},e("option",{value:""},"—"),Be.map(K=>e("option",{key:K.value,value:K.value},K.label))),e("button",{className:"cm-btn small",title:f("removePriceMatchHint"),onClick:()=>es(q)},f("overrideRemove"))))):e("p",{className:"cm-hint"},f("overrideNone")),y.length>0?e("button",{className:"cm-btn small",onClick:()=>E("priceMatchDismissed",[])},f("restorePriceMatches",{count:y.length})):null,Ne.length>0?e(j,null,e("h3",{className:"cm-h"},f("matchedTitle")),e("p",{className:"cm-hint"},f("matchedHint")),Ne.map(q=>e("div",{key:q,className:"cm-match-row"},e("span",null,$t(q)),e("select",{className:"cm-input",value:"",onChange:K=>{K.target.value!==""&&aa(q,K.target.value)}},e("option",{value:""},f("matchedKeepAuto")),Be.map(K=>e("option",{key:K.value,value:K.value},K.label)))))):null)})(),e(jn,{state:n,draft:a,setDraft:r,t:f}),e("div",null,e("h3",{className:"cm-h"},f("dataSync")),e("div",{className:"cm-field"},e("label",null,f("pricingCurrencyLabel")),e("select",{className:"cm-input",value:a?.pricingCurrency==="CNY"?"CNY":"USD",onChange:c=>E("pricingCurrency",c.target.value)},e("option",{value:"USD"},f("pricingCurrencyUsd")),e("option",{value:"CNY"},f("pricingCurrencyCny"))),e("p",{className:"cm-note"},f("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},d?e(j,null,e("span",{className:"cm-hint"},f("confirmFetch")),e("button",{className:"cm-btn",onClick:Y,disabled:N},f("apply")),e("button",{className:"cm-btn",onClick:()=>h(!1)},f("cancel"))):e("button",{className:"cm-btn",onClick:()=>h(!0),disabled:N},f("syncFromDocs"))),e("p",{className:"cm-note"},f("lastSync",{time:L.fetchedAt!==null?new Date(L.fetchedAt).toLocaleString():f("neverSynced")})+f("source",{source:L.priceSource==="official"?f("sourceOfficial"):f("sourceBundled")})),e("p",{className:"cm-note"},f("syncScopeNote")))):null)}const Zn=["remote"];async function Xn(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(Ca);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const n=t.get("remote.costMeter");if(n===void 0)return;const a=qa({status:"loading",error:null,state:null}),r=()=>V(F(a.getSnapshot().state?.config?.locale)),l=async(c,y)=>{const B=await n[c](...y??[]);if(B===null||typeof B!="object"||B.ok!==!0)throw new Error(B?.error?.message??r()("rpcFailed",{method:c}));return B.value};let i=!1;const d=async()=>{if(i)return;i=!0;const c=a.getSnapshot();try{const y=await l("getState");a.set({status:"ready",error:null,state:y})}catch(y){a.set({status:"error",error:y?.message??String(y),state:c.state})}finally{i=!1}};t.effect(()=>t.on("connection/reset",()=>{d()}),"cost-meter: reconnect reload");const h=setInterval(()=>{document.hidden||d()},6e4);t.effect(()=>()=>{clearInterval(h)},"cost-meter: poll timer");const u=()=>{document.visibilityState==="visible"&&d()};document.addEventListener("visibilitychange",u),t.effect(()=>()=>{document.removeEventListener("visibilitychange",u)},"cost-meter: visibility reload");const b={reload:d,updateConfig:async c=>{const y=await l("updateConfig",[c]);return a.set({status:"ready",error:null,state:y}),y},fetchPrices:async()=>{const c=await n.fetchPrices();if(c===null||typeof c!="object"||c.ok!==!0)throw new Error(c?.error?.message??r()("rpcSyncFailed"));return c.value.state!==void 0&&a.set({status:"ready",error:null,state:c.value.state}),c.value},resetHistory:async()=>{const c=await l("resetHistory");return a.set({status:"ready",error:null,state:c}),c},importLegacyHistory:async()=>{const c=await n.importLegacyHistory();if(c===null||typeof c!="object"||c.ok!==!0)throw new Error(c?.error?.message??c?.value?.message??r()("legacyImportFailed",{message:"RPC failed"}));return c.value.state!==void 0&&a.set({status:"ready",error:null,state:c.value.state}),c.value},getDaySessions:async c=>l("getDaySessions",[c]),getTopSessions:async(c,y,B)=>l("getTopSessions",[c,y,B]),refreshBalance:async()=>{const c=await n.refreshBalance();if(c===null||typeof c!="object"||c.ok!==!0)throw new Error(c?.error?.message??r()("rpcBalanceFailed"));return c.value.state!==void 0&&a.set({status:"ready",error:null,state:c.value.state}),c.value},refreshGoQuota:async()=>{const c=await n.refreshGoQuota();if(c===null||typeof c!="object"||c.ok!==!0)throw new Error(c?.error?.message??r()("rpcSyncFailed"));return c.value.state!==void 0&&a.set({status:"ready",error:null,state:c.value.state}),c.value},refreshGatewayQuota:async(c=null)=>{const y=c==null?await n.refreshGatewayQuota():await n.refreshGatewayQuota(c);if(y===null||typeof y!="object"||y.ok!==!0)throw new Error(y?.error?.message??r()("rpcSyncFailed"));return y.value.state!==void 0&&a.set({status:"ready",error:null,state:y.value.state}),y.value},refreshCustomBalance:async(c=null)=>{const y=c==null?await n.refreshCustomBalance():await n.refreshCustomBalance(c);if(y===null||typeof y!="object"||y.ok!==!0)throw new Error(y?.error?.message??r()("rpcSyncFailed"));return y.value.state!==void 0&&a.set({status:"ready",error:null,state:y.value.state}),y.value},refreshCodingPlan:async c=>{const y=await n.refreshCodingPlan(c);if(y===null||typeof y!="object"||y.ok!==!0)throw new Error(y?.error?.message??r()("rpcSyncFailed"));return y.value.state!==void 0&&a.set({status:"ready",error:null,state:y.value.state}),y.value},setCredential:async(c,y)=>{const B=await n.setCredential(c,y);if(B===null||typeof B!="object"||B.ok!==!0)throw new Error(B?.error?.message??B?.value?.message??r()("rpcSyncFailed"));return B.value.state!==void 0&&a.set({status:"ready",error:null,state:B.value.state}),B.value},clearCredential:async c=>{const y=await n.clearCredential(c);if(y===null||typeof y!="object"||y.ok!==!0)throw new Error(y?.error?.message??y?.value?.message??r()("rpcSyncFailed"));return y.value.state!==void 0&&a.set({status:"ready",error:null,state:y.value.state}),y.value}};d();const w=t.get("slots");if(w===void 0)return;const k=()=>({hooks:{cost:a},api:b}),p=()=>({gen:0,dispose:null}),C=(c,y,B,G,Q=!0)=>{c.dispose!==null&&(c.dispose(),c.dispose=null),c.gen+=1;const se=c.gen;Q&&w.inject(y,()=>{if(c.gen!==se)return;const me=typeof B=="function"?B():w.register(B,G);if(c.gen!==se){me();return}return c.dispose=me,()=>{c.dispose===me&&(c.dispose=null),me()}})},N=p(),A=c=>{const y=c==="header"?"conversation.session.header.actions":"conversation.composer.dock";C(N,y,c==="header"?{name:y,id:"cost-meter",order:-5,inject:k}:{name:y,id:"cost-meter",order:5,inject:k},c==="header"?Qa:Fa,c!=="off")},P=p(),g=c=>{C(P,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:k},Pn,c)},v=p(),x=c=>{C(v,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:k},en,c)};w.inject("conversation.input.dock",()=>w.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:k},xn)),w.inject("sidebar.footer.action",()=>w.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:k},Nn)),w.inject("sidebar.footer.action",()=>w.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:k},An));const m=p(),S=c=>{C(m,"sidebar.footer.action",()=>w.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:k},tn),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 M=p(),R=c=>{C(M,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:c==="en"?Se.en.sectionLabel:Se.zh.sectionLabel,inject:k},$n,!0)},H=p(),T=c=>{C(H,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:k},gt,c)},f=p(),L=(c,y)=>{C(f,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:y==="en"?Se.en.usageSectionLabel:Se.zh.usageSectionLabel,inject:k},gt,c)};let Y=null,re=null,D=null,E=null,_=null,I=null;const ee=()=>{const c=a.getSnapshot().state,y=c?.config?.position??"dock",B=c?.config?.sidebar!==!1&&c?.config?.hideTodayCost!==!0,G=c?.config?.balance?.display??"both",Q=(G==="sidebar"||G==="both")&&c?.config?.hideOfficialBalance!==!0,se=B||Q,me=c?.config?.corner?.enabled===!0,xe=F(c?.config?.locale),Ne=c?.config?.usage?.position??"cost";y!==Y&&(A(y),Y=y),se!==re&&(g(se),re=se),me!==D&&(x(me),D=me);const Be=c?.config?.peakEnabled===!0;Be!==I&&(S(Be),I=Be),xe!==E&&(R(xe),E=xe),Ne!==_?(je&&(T(Ne==="general"),L(Ne==="section",xe)),_=Ne):je&&Ne==="section"&&xe!==E&&L(!0,xe)};ee();const ne=a.subscribe(ee);return()=>{ne()}}return Ve.apply=Xn,Ve.inject=Zn,yt.exports}});