dsh-cost-meter 1.8.12 → 1.8.13

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,6 +1,6 @@
1
1
  // This file is generated from the src/client/*.js fragments via `node scripts/build.mjs` (esbuild). Do not edit directly.
2
- window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:$e=>{var Zt={exports:{}},bt=Zt.exports;Object.defineProperty(bt,Symbol.toStringTag,{value:"Module"});const Be=$e("react"),{Tooltip:X}=$e("@deepseek-ai/dsh-client-ui-primitives"),Xe=!1,Ya='.cm-root{flex:0 1 auto;min-width:0;max-width:100%;text-align:center;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-chip{display:inline-flex;align-items:center;gap:4px;max-width:180px;padding:0 8px;height:22px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-foot{display:flex;align-items:center;gap:6px;height:32px;padding:0 8px;border-radius:8px;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden}.cm-foot:hover,.cm-foot-rail:hover,.cm-corner-chip:hover,.cm-qchip:hover,.cm-tab:hover,.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}.cm-foot-rail{width:100%;justify-content:center;padding:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-num{font-variant-numeric:tabular-nums}.cm-go-rail{font-size:11px;font-weight:700;color:var(--dsw-alias-label-primary)}.cm-go-list{display:flex;flex-direction:column;gap:10px}.cm-go-row{display:flex;align-items:center;gap:8px;font-size:12px}.cm-go-label{flex:none;width:88px;color:var(--dsw-alias-label-secondary)}.cm-go-bar{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-interactive-bg-hover);overflow:hidden}.cm-go-fill{height:100%;border-radius:3px;background:var(--dsw-alias-brand-primary)}.cm-go-num{flex:none;min-width:44px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.cm-go-reset{flex:none;max-width:230px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-go-time{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-go-row.main .cm-go-label{font-weight:600;color:var(--dsw-alias-label-primary)}.cm-corner{display:inline-flex;flex:0 1 auto;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;min-width:0;max-width:100%}.cm-corner-chip{display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:20px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums}.cm-qstrip{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:0 auto;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-qchip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:default}.cm-qchip .cm-qlabel{color:var(--dsw-alias-label-primary);font-weight:600}.cm-qchip .cm-qbar{display:block;width:44px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l1);overflow:hidden;flex:none}.cm-qchip .cm-qfill{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-state-ok-primary,#3ba272)}.cm-qchip .cm-qseg{display:inline-flex;align-items:center;gap:4px}.cm-qchip .cm-qsep{width:1px;height:12px;background:var(--dsw-alias-border-l1);flex:none}.cm-qchip .cm-qtext{color:var(--dsw-alias-label-secondary)}.cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}.cm-qchip.over .cm-qfill{background:var(--dsw-alias-state-error-primary)}.cm-qchip.action{cursor:pointer;user-select:none;outline:none}.cm-qchip.action:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-qchip.action:active{transform:translateY(.5px)}.cm-plan-provider{display:flex;flex-direction:column;gap:8px}.cm-plan-provider+.cm-plan-provider{margin-top:14px}.cm-plan-provider-name{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600}.cm-plan-updated{font-size:11px;font-weight:400;color:var(--dsw-alias-label-tertiary)}.cm-plan-tag{flex:none;margin-left:6px;padding:0 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);font-size:10px;line-height:16px;color:var(--dsw-alias-state-warn-primary)}.cm-plan-reset,.cm-plan-method{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-qguide{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:9999;max-width:440px;width:calc(100% - 32px);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 28px #0000002e;padding:14px 16px;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:8px}.cm-qguide h4{margin:0;font-size:13px;font-weight:600}.cm-qguide p{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}.cm-qguide .cm-buttons{display:flex;gap:8px;justify-content:flex-end}.cm-section{display:flex;flex-direction:column;gap:20px;padding:4px 2px 24px;font-size:13px;color:var(--dsw-alias-label-primary)}.cm-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.cm-cards-toggle{display:flex;align-items:center;gap:6px;margin:-6px 2px 0 auto;width:fit-content;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;user-select:none}.cm-cards-toggle:hover{color:var(--dsw-alias-label-primary)}.cm-cards-toggle input{margin:0;cursor:pointer}.cm-card,.cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1)}.cm-card-title{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0 0 8px}.cm-card-value{font-size:20px;line-height:28px;font-weight:600}.cm-card-sub{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-h{font-size:13px;font-weight:600;margin:0}.cm-collapse-h{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;margin:0;cursor:pointer;color:inherit;font:inherit;text-align:left}.cm-collapse-h:hover .cm-h{color:var(--dsw-alias-interactive-text-hover,var(--dsw-alias-label-primary))}.cm-caret{flex:none;width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid var(--dsw-alias-label-secondary);transform:rotate(-90deg);transition:transform .15s ease}.cm-caret.open{transform:rotate(0)}.cm-collapse-body{display:flex;flex-direction:column;gap:12px;margin-top:12px}.cm-toolbar{display:flex;justify-content:flex-end;align-items:center;gap:10px}.cm-toolbar .cm-field{flex-direction:row;align-items:center;gap:8px}.cm-toolbar .cm-field label{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-toolbar .cm-input{min-width:150px;padding:4px 10px}.cm-tabs-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;border-bottom:1px solid var(--dsh-alias-border-l1);padding-bottom:10px}.cm-tabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}.cm-tab{font:inherit;font-size:13px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:8px;padding:6px 14px;cursor:pointer;white-space:nowrap}.cm-tab.active{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary-inverted);font-weight:600}.cm-tabs-row .cm-msg{padding:2px 10px}.cm-note{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0}.cm-table{width:100%;border-collapse:collapse;font-size:12px}.cm-table th,.cm-table td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}.cm-table th{color:var(--dsw-alias-label-tertiary);font-weight:500}.cm-table td.num,.cm-table th.num{text-align:right;font-variant-numeric:tabular-nums}.cm-table tr:last-child td{border-bottom:none}.cm-table tr.cm-row-click{cursor:pointer}.cm-table tr.cm-row-click:hover td{background:var(--dsw-alias-bg-hover,rgba(127,127,127,.08))}.cm-sess-title{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-sess-id{font-size:11px;font-family:ui-monospace,Consolas,monospace;color:var(--dsw-alias-label-tertiary)}.cm-empty{font-size:12px;color:var(--dsw-alias-label-tertiary);padding:8px 0}.cm-scroll{max-height:320px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px}.cm-grid{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:12px}.cm-field{display:flex;flex-direction:column;gap:6px}.cm-field label{font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-input{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;outline:none}.cm-input:focus{border-color:var(--dsw-alias-state-business-primary)}.cm-input.narrow{max-width:120px}.cm-range-row{display:flex;align-items:center;gap:10px}.cm-range{flex:1;min-width:0;accent-color:var(--dsw-alias-state-business-primary)}.cm-range-value{flex:none;min-width:44px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-align:right}.cm-check{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}.cm-price-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:10px;background:var(--dsw-alias-bg-layer-1)}.cm-price-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-price-name{font-weight:600;font-size:13px}.cm-price-legacy{font-size:11px;color:var(--dsw-alias-label-tertiary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px}.cm-price-row{display:grid;grid-template-columns:52px 1fr 1fr 1fr;gap:8px;align-items:center}.cm-price-row span{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-price-row input{width:100%}.cm-buttons{display:flex;flex-wrap:wrap;gap:10px;align-items:center}.cm-btn{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-elevated-fill);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 14px;cursor:pointer}.cm-btn.cm-stat-entry{font-size:12px;line-height:20px;padding:0 6px;min-width:0;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex-shrink:0}@media(max-width:640px){.cm-stat-header{display:none}}.cm-btn.primary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-label-primary-inverted)}.cm-btn.primary:hover{opacity:.88;background:var(--dsw-alias-state-business-primary)}.cm-btn.danger,.cm-msg.err,.cm-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}.cm-btn.small{padding:3px 10px;font-size:12px}div:has(>[data-slot="conversation.composer.dock"] .cm-stat-entry){flex-wrap:nowrap;column-gap:6px}.cm-msg{font-size:12px;line-height:18px;padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1)}.cm-msg.ok{color:var(--dsw-alias-state-success-primary)}.cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-budget{display:flex;flex-direction:column;gap:10px}.cm-peak-alert{position:fixed;z-index:9999;width:340px;max-width:calc(100vw - 32px);padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:0 14px 36px #00000038;display:flex;flex-direction:column;gap:8px;font-size:12px;animation:cm-peak-alert-in .22s cubic-bezier(.2,.8,.2,1)}.cm-peak-alert.cm-peak-alert-corner{right:20px;bottom:20px}.cm-peak-alert.cm-peak-alert-center{top:50%;left:50%;transform:translate(-50%,-50%);animation-name:cm-peak-alert-in-center}.cm-peak-alert-peak{border-top:3px solid var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak{border-top:3px solid var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:600;letter-spacing:.4px;text-transform:uppercase}.cm-peak-alert-badge:before{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 4px color-mix(in srgb,currentColor 16%,transparent)}.cm-peak-alert-peak .cm-peak-alert-badge{color:var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak .cm-peak-alert-badge{color:var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-peak-alert-body{color:var(--dsw-alias-label-secondary);line-height:1.55}.cm-peak-alert-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}.cm-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}@keyframes cm-peak-alert-in{0%{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes cm-peak-alert-in-center{0%{opacity:0;transform:translate(-50%,calc(-50% + 10px))}to{opacity:1;transform:translate(-50%,-50%)}}.cm-budget-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-quota-name{flex:1;min-width:0}.cm-budget-bar{height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-budget-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary);transition:width .3s ease}.cm-ug{display:flex;flex-direction:column;gap:12px}.cm-ug-total{font-size:13px;color:var(--dsw-alias-label-primary)}.cm-ug-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,auto);gap:3px;width:100%}.cm-ug-cell{width:100%;aspect-ratio:1/1;border-radius:3px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);border:1px solid var(--dsw-alias-border-l1)}.cm-ug-cell.l1,.cm-ug-cell.l2,.cm-ug-cell.l3,.cm-ug-cell.l4{border-color:transparent}.cm-ug-cell.l1{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary)}.cm-ug-cell.today{outline:1px solid var(--dsw-alias-label-secondary);outline-offset:1px}.cm-ug-months{display:grid;grid-auto-flow:column;gap:3px;width:100%;font-size:10px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-ug-monthc{white-space:nowrap}.cm-budget-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-budget-line.over{color:var(--dsw-alias-state-error-primary)}.cm-peak-strip{display:flex;align-items:center;gap:6px;margin-top:4px;min-width:0}.cm-peak-track{position:relative;display:flex;flex:1;height:6px;min-width:0;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-segment{height:100%;flex:1}.cm-peak-high{background:#ff9800}.cm-peak-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-marker{position:absolute;top:0;left:50%;width:2px;height:100%;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2}.cm-peak-chip{font-size:11px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-classic{position:relative;display:flex;flex-direction:column;gap:5px;margin-top:6px;min-width:0}.cm-peak-classic .cm-peak-track{flex:none;height:8px}.cm-peak-classic-marker{position:absolute;top:0;left:50%;width:4px;height:12px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2;border-radius:2px}.cm-peak-classic-marker:after{content:"";position:absolute;top:-7px;left:50%;transform:translate(-50%);border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #ff9800}.cm-peak-classic.off .cm-peak-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic.off .cm-peak-classic-marker:after{border-top-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic-chip{align-self:flex-start;font-size:11px;font-weight:600;line-height:1.4;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 8px;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-strip.peak .cm-peak-chip,.cm-peak-classic.peak .cm-peak-classic-chip,.cm-peak-rail.peak .cm-peak-rail-label,.cm-peak-rail-classic.peak .cm-peak-rail-classic-label{color:#ff9800}.cm-peak-strip.off .cm-peak-chip,.cm-peak-classic.off .cm-peak-classic-chip,.cm-peak-rail.off .cm-peak-rail-label,.cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}.cm-peak-strip.weekend .cm-peak-chip,.cm-peak-classic.weekend .cm-peak-classic-chip,.cm-peak-rail.weekend .cm-peak-rail-label,.cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker{border-color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker:after{border-top-color:#34a853}.cm-peak-rail{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-track{position:relative;display:flex;flex-direction:column;width:6px;height:56px;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-segment{width:100%;flex:1}.cm-peak-rail-high{background:#ff9800}.cm-peak-rail-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-rail-marker{position:absolute;left:0;top:50%;width:100%;height:2px;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translateY(-50%);transition:top .4s ease;z-index:2}.cm-peak-rail-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-rail-classic{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-classic-track{position:relative;display:flex;flex-direction:column;width:14px;height:56px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-classic-segment{position:relative;width:100%;flex:1;overflow:hidden}.cm-peak-rail-classic-segment.peak{background:#ff9800;border-radius:999px 999px 0 0}.cm-peak-rail-classic-segment.off{background:var(--dsw-alias-state-business-primary);border-radius:0 0 999px 999px}.cm-peak-rail-classic-marker{position:absolute;left:50%;top:50%;width:12px;height:4px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%,-50%);transition:top .4s ease;z-index:2;border-radius:2px}.cm-peak-rail-classic.off .cm-peak-rail-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-rail-classic-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}.cm-grid-group{grid-column:1 / -1;margin-top:8px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:4px}.cm-grid-group:first-child{margin-top:0}.cm-peak-preview{margin-top:8px}.cm-toggle-btn{background:none;border:none;padding:0;font-size:12px;font-weight:600;color:var(--dsw-alias-state-business-primary);cursor:pointer}.cm-toggle-btn:hover{text-decoration:underline}.cm-collapsed-note{margin-top:4px}.cm-catalog-vendor{margin-top:10px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:2px;display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-vendor-toggle{cursor:pointer;user-select:none}.cm-vendor-toggle:hover{color:var(--dsw-alias-label-secondary)}.cm-vendor-display{display:inline-flex;align-items:center;gap:4px;font-weight:400;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}.cm-catalog-family{margin:6px 0 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}.cm-catalog-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px}.cm-catalog-mounted{display:flex;flex-direction:column;gap:4px;padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1)}.cm-catalog-id{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-catalog-price{color:var(--dsw-alias-label-secondary);white-space:nowrap;font-size:11px}.cm-catalog-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);white-space:nowrap}.cm-mstats-tabs{display:flex;gap:8px;margin-bottom:8px}.cm-mstats-tab{background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}.cm-mstats-tab.active{background:var(--dsw-alias-state-business-primary);border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-bg-base);font-weight:600}.cm-mstats-h{margin:10px 0 4px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}.cm-mstats-row{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:8px;align-items:center;font-size:11px;line-height:1.7}.cm-mstats-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-barbg{position:relative;height:10px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden;display:flex}.cm-mstats-bar{height:100%;min-width:0;border-radius:999px}.cm-mstats-bar.cost{background:#ff9800}.cm-mstats-bar.hit{background:#34a853}.cm-mstats-bar.value{background:#a142f4}.cm-mstats-seg{height:100%;min-width:0}.cm-mstats-seg.in{background:var(--dsw-alias-state-business-primary)}.cm-mstats-seg.cache{background:#ff9800}.cm-mstats-seg.out{background:#34a853}.cm-mstats-val{white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-legend{display:flex;gap:12px;font-size:10px;color:var(--dsw-alias-label-tertiary);margin:2px 0 4px}.cm-mstats-dot{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.cm-mstats-note{margin-top:10px;font-size:10px;line-height:1.6;color:var(--dsw-alias-label-tertiary)}.cm-match-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:12px;flex-wrap:wrap}.cm-match-row .cm-input{flex:1;min-width:160px}.cm-budget-controls{display:grid;grid-template-columns:repeat(2,minmax(180px,1fr));gap:12px}.cm-bbox{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:6px;min-width:148px;box-sizing:border-box}.cm-bbox.rail{padding:6px;min-width:0;width:40px;align-items:center;justify-content:center;border-radius:10px}.cm-bbox.warn{border-color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over{border-color:var(--dsw-alias-state-error-primary)}.cm-bbox-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-bbox-label,.cm-bbox-pct{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}.cm-bbox-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-bbox-bar.segments{display:flex;height:8px}.cm-bbox-bar.segments .cm-bbox-fill{flex:none;border-radius:0;height:100%}.cm-bbox-bar.segments .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments .cm-bbox-seg-today{flex:none;height:100%;background:#ff9800}.cm-bbox-bar.segments .cm-bbox-seg-spent{flex:none;height:100%;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-fill:first-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments.rev .cm-bbox-fill,.cm-bbox-bar.segments.rev .cm-bbox-fill:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}.cm-dir-row{display:flex;align-items:center;gap:8px;margin-top:6px}.cm-dir-label{flex:1 1 40%;font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-dir-row .cm-input{flex:1 1 60%;width:auto}.cm-bbox-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary)}.cm-balance-name{display:inline-flex;align-items:center;gap:4px;min-width:0}.cm-model-costs{font-size:12px}.cm-model-costs .cm-bal-label{white-space:nowrap}.cm-model-top{gap:4px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.cm-model-costs .cm-collapse-h{min-width:0;width:100%;white-space:nowrap}.cm-model-costs .cm-bbox-bar{margin-top:3px}.cm-bal-label{min-width:0;overflow:hidden;text-overflow:ellipsis}.cm-bal-amt{margin-left:auto;text-align:right;flex-shrink:0}.cm-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}.cm-bal-link{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:2px;border-radius:4px;font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary);text-decoration:none;outline:none}.cm-bal-link:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-interactive-bg-hover)}.cm-bal-link:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-bbox.warn .cm-bbox-fill,.cm-bbox .cm-bbox-section.warn .cm-bbox-fill,.cm-bbox .cm-mm-row.warn .cm-bbox-fill,.cm-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-fill,.cm-bbox-section.over .cm-bbox-fill,.cm-mm-row.over .cm-bbox-fill,.cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}.cm-bbox-line{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-bbox-rail{font-size:11px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct,.cm-bbox.warn .cm-bbox-rail,.cm-bbox .cm-bbox-section.warn .cm-bbox-pct,.cm-bbox .cm-mm-row.warn .cm-bbox-pct,.cm-mm-row.warn .cm-bbox-label,.cm-corner-chip.warn,.cm-qchip.warn,.cm-simple-summary.warn{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct,.cm-bbox.over .cm-bbox-rail,.cm-bbox-section.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-label,.cm-corner-chip.over,.cm-qchip.over,.cm-simple-summary.over{color:var(--dsw-alias-state-error-primary)}.cm-bbox-pair{display:flex;flex-direction:column;gap:0;padding:2px 10px}.cm-bbox-pair .cm-bbox-section{display:flex;flex-direction:column;gap:4px;padding:4px 0}.cm-bbox-pair .cm-bbox-bar{height:4px}.cm-bbox-divider{height:1px;background:var(--dsw-alias-border-l1);margin:0}.cm-bbox.clickable,.cm-foot.clickable{cursor:pointer}.cm-bbox.clickable:hover{border-color:var(--dsw-alias-state-business-primary)}.cm-bbox.clickable:focus-visible,.cm-foot.clickable:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}@keyframes cm-click-refresh-pulse{0%,to{opacity:.55}50%{opacity:1}}.cm-bbox.clickable.busy,.cm-foot.clickable.busy{animation:cm-click-refresh-pulse 1.1s ease-in-out infinite}.cm-mm{padding:8px 10px;gap:4px}.cm-mm-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-mm-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);grid-column:1/-1}.cm-gw-switcher{cursor:pointer;user-select:none;font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}.cm-gw-switcher:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.cm-gw-sub{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-mm-row{display:flex;align-items:center;gap:8px;padding:2px 0}.cm-mm-row .cm-bbox-label{flex:none;width:auto;min-width:22px;max-width:115px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;word-break:keep-all}.cm-mm-row .cm-bbox-bar{flex:1;min-width:40px;height:6px}.cm-mm-row .cm-bbox-pct{flex:none;min-width:2.4em;text-align:right;font-variant-numeric:tabular-nums}.cm-mm-row.wide .cm-bbox-label{width:auto;max-width:64px;flex:0 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-mm-row.wide .cm-mm-text{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-bal-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-bal-line.warn{color:var(--dsw-alias-state-warning-primary,#b45309)}:has(>.cm-footer-stack),:has(>[data-slot="sidebar.footer.action"]>.cm-footer-stack){flex-wrap:wrap}:has(>.cm-footer-stack.rail),:has(>[data-slot="sidebar.footer.action"]>.cm-footer-stack.rail){flex-direction:column;flex-wrap:nowrap;align-items:center;gap:6px}.cm-footer-stack{display:flex;flex:none;order:-1;flex-direction:column;gap:6px;width:100%;min-width:0;max-width:100%;align-items:stretch;box-sizing:border-box}.cm-footer-stack.rail{align-items:center;order:1}.cm-footer-stack .cm-bbox{width:100%;min-width:0}.cm-footer-stack .cm-foot{width:100%;box-sizing:border-box}.cm-footer-stack.compact .cm-bbox{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:2px;align-items:center}.cm-footer-stack.compact .cm-bbox>*{grid-column:1/-1}.cm-footer-stack.compact .cm-bbox>.cm-mm-row{grid-column:auto}.cm-footer-stack.compact .cm-mm-row{min-width:0;gap:4px;flex-wrap:nowrap}.cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:0 1 auto;min-width:0;max-width:45%;width:auto}.cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0;flex:1 1 0}.cm-footer-stack.simple{gap:0;max-height:38vh;max-height:min(38dvh,320px);overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.cm-footer-stack.simple>*{flex-shrink:0}.cm-footer-stack.simple:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}.cm-footer-stack.simple .cm-bbox{border:0;border-radius:0;padding:4px 8px;gap:2px;background:transparent;box-shadow:inset 0 -1px var(--dsw-alias-border-l1)}.cm-footer-stack.simple .cm-mm-title{font-size:11px;line-height:16px;margin:0}.cm-footer-stack.simple .cm-mm-row{gap:6px;min-height:16px;line-height:16px;margin:0;padding:0}.cm-footer-stack.simple .cm-mm-text{font-size:11px}.cm-footer-stack.simple>.cm-peak-strip,.cm-footer-stack.simple>.cm-peak-classic{margin:0;padding:4px 8px}.cm-simple-summary>span{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-footer-stack.simple .cm-bbox-pct{font-size:12px;line-height:18px}.cm-footer-stack.simple .cm-bbox-bar{height:4px}.cm-footer-stack.simple .cm-bbox-line{display:none}.cm-footer-stack.simple .cm-foot{height:26px;padding:0 8px}.cm-footer-stack.simple .cm-peak-classic{margin-top:2px;gap:2px}.cm-footer-stack.simple .cm-peak-classic-chip{padding:0 4px;border:0;background:transparent}.cm-simple-summary{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 8px;font-size:12px;font-weight:600;border-bottom:1px solid var(--dsw-alias-border-l1)}.cm-footer-stack.simple.rail{border:0;background:transparent}.cm-footer-stack.simple.rail .cm-bbox{padding:4px 2px}.cm-footer-stack.simple .cm-peak-rail-track,.cm-footer-stack.simple .cm-peak-rail-classic-track{height:28px}@media(max-width:640px){.cm-cards,.cm-grid,.cm-budget-controls{grid-template-columns:1fr}}',$t="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify($t)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=$t,t.textContent=Ya,document.head.appendChild(t)}const Va="sessionCostTitle|sessionDetailTokens|sessionDetailCache|cost|sessionLine|quotaUnlimited|pricingCnyHint|balanceQueryFailed|unknownError|balance|queryFailed|balanceTitle|reconcileLabel|totalBalance|grantedToppedUp|updatedAt|budgetOf|usedOf|todayShare|monthTotal|budget|todayCostTitle|todayTokensTitle|tokensUnit|callsTokens|monthCost|totalCost|today|sidebarTodayMetric|sidebarTodayCost|sidebarTodayTokens|periodDay|periodMonth|periodAll|periodCustomRange|noHistory|colDate|colCalls|colInTok|colCacheTok|colOutTok|colCost|noSessionsToday|colSession|enableBudget|budgetAmountLabel|budgetPeriodLabel|startDate|endDate|rangeText|budgetDisabledNote|budgetStatus|overLimit|nearLimit|legacyModel|defaultFallback|remove|tierBase|tierOffPeak|tierPeak|balanceApiKey|balanceKeyHint|balanceLine|balanceQueryFailedHint|balanceNotQueried|accountBalance|refreshing|refreshBalance|customBalanceTitle|customBalanceAdd|aliyunBalanceAdd|aliyunBalanceNote|customBalanceConfigNote|customBalanceLabelZh|customBalanceLabelEn|customBalanceUrl|customBalanceMethod|customBalanceHeaders|customBalanceBody|customBalanceBodyNote|customBalanceExtract|customBalanceDisplayLabel|customBalanceRefreshInterval|customBalanceUnitLabel|customBalanceConvert|customBalanceConvertNote|balanceBarRemaining|balanceBarToday|balanceBarSpent|balanceShowProgressBar|barDirectionsTitle|barDirectionsHint|barDirection_balance|barDirection_budget|barDirection_go|barDirection_plan|barDirectionRemaining|barDirectionUsed|balanceBudgetCapLabel|balanceBudgetCapHint|customBalanceInvalidJson|customBalanceHeadersVarNote|customBalanceAllowedHosts|customBalanceAllowedHostsHint|customBalanceCredentialsTitle|customBalanceCredentialsHint|customBalanceNoPlaceholders|enable|customBalanceLine|customBalanceRemaining|refreshCustomBalance|goQuotaTitle|goQuotaRowLabel|goWindowRolling|goWindowWeekly|goWindowMonthly|goResetAt|resetReached|resetDays|resetHours|resetMinutes|quotaUsed|quotaRemaining|goQuotaPercent|goQuotaFetchedAt|goQuotaDisplayLabel|goQuotaRefreshIntervalLabel|goQuotaRefreshMinutesUnit|goQuotaKeyLabel|goMainLabel|goDetailLabel|credentialConfiguredOf|credentialNotConfigured|credentialSave|credentialEdit|credentialClear|credentialSaving|credentialInputHint|secretMigrationPending|budgetDetailLabel|refreshGoQuota|goQuotaNotQueried|codingPlanAnthropic|codingPlanZai|codingPlanMinimax|codingPlanMinimaxTitle|minimaxOrigin|minimaxOriginNote|codingPlanRemain5h|codingPlanRemain7d|balanceRechargeLink|codexQuotaTitle|codexQuotaEnabled|codexQuotaSidebar|includeSubagentCost|gatewayQuotaEmpty|codingPlanDisplayLabel|codingPlanDisplayNote|codingPlanKeyLabel|codingPlanRefreshIntervalLabel|refreshCodingPlan|loginCodingPlan|loggingIn|codingPlanNotQueried|gatewayQuotaTitle|gatewaySourceAdd|gatewaySourceLabel|gatewaySourceBaseURL|gatewaySourceDisplay|gatewaySourceAllowlist|gatewaySourceCredential|gatewaySourceStatus|gatewaySourceUnsupported|gatewaySourceUnknown|gatewaySourceNoAccounts|gatewaySourceFetchedAt|gatewaySwitchAccount|gatewayOnlyGemini|refresh|quotaEnableFirst|quotaRefreshReady|quotaRemove|quotaSectionNote|codingPlanDisabledNote|goQuotaDisabledNote|cornerLabel|cornerEnabledLabel|cornerGoRolling|cornerGoWeekly|cornerGoMonthly|cornerBudget|goShortRolling|goShortWeekly|goShortMonthly|goShortDaily|budgetShort|ledgerReadFailed|readingLedger|ledgerUnavailable|syncFailed|historyCleared|clearFailed|peakOff|peakNotEffective|peakActive|peakNotice|offPeakActive|weekendAllOffPeak|weekendChip|weekendShort|holidayAllOffPeak|holidayChip|holidayShort|peakHolidaysLabel|weekendRuleNote|peakShort|offPeakShort|peakStyleLabel|peakStyleCompact|peakStyleClassic|peakAlertLabel|peakAlertAheadLabel|peakAlertTargetLabel|peakAlertTargetPeak|peakAlertTargetOffPeak|peakAlertTargetBoth|peakAlertTitlePeak|peakAlertTitleOffPeak|peakAlertBody|peakAlertPhasePeak|peakAlertPhaseOffPeak|peakAlertBtn|peakAlertBadgePeak|peakAlertBadgeOffPeak|peakAlertPositionLabel|peakAlertPositionCorner|peakAlertPositionCenter|peakAlertWebNotifyLabel|peakAlertWebNotifyHint|peakAlertPreviewLabel|peakAlertPreviewPeak|peakAlertPreviewOffPeak|peakAlertPreviewTag|peakPanelTitle|peakNoticeHiddenHint|groupGeneral|groupMoney|groupSidebar|sidebarSimple|sidebarSimpleNote|sidebarSimpleTitle|sidebarSimpleBody|sidebarSimpleOn|sidebarSimpleOff|sidebarSimpleError|closeGuide|todayBudget|sidebarStyleLabel|sidebarStyleStandard|sidebarStyleCompact|restorePriceMatches|removePriceMatchHint|groupCorner|groupDetail|catalogTitle|catalogNote|catalogOpen|catalogCollapse|mountBtn|unmountBtn|mountedTag|catalogUnpriced|catalogDeepseekNote|modelStatsTitle|modelsTitle|modelsCount|modelsOther|models_enabled|models_defaultOpen|models_remember|models_tokens|models_shares|models_dock|models_period|models_summary|models_position|models_topN|models_refreshSeconds|modelsTotal|modelsTop|modelsFirst|modelsAfter|modelsLast|modelStatsToday|modelStatsHistory|modelStatsCostH|modelStatsTokensH|modelStatsHitH|modelStatsHitUnreported|modelStatsHitUnreportedTip|modelStatsValueH|modelStatsInput|modelStatsCache|modelStatsOutput|modelStatsEmpty|modelStatsBlended|modelStatsNote|modelStatsLegacy|sessionLineSplit|costChipPlan|sessionDetailPlan|planStatsTitle|planStatsEmpty|planStatsWindow|planStatsPercent|planStatsLocal|planStatsPer1|planStatsFull|planStatsResets|planStatsMethodSample|planStatsMethodLive|planStatsMethodNone|planStatsMethodSampleAt|planStatsConfidenceLow|planStatsCurveTitle|planStatsDaily|planStatsWeekly|planStatsMonthly|planStatsCurveEmpty|planStatsBarTip|planStatsNote|billingClassLabel|billingClassPlan|billingClassAuto|billingClassApi|catalogDisplayLabel|catalogDisplayHint|priceTableDisplayHint|catalogCustomModels|priceMatchLabel|priceMatchAuto|priceMatchExact|priceMatchNote|unmatchedTitle|unmatchedHint|overrideTargetDefault|overrideRemove|overrideTargetLocal|matchedTitle|matchedHint|matchedKeepAuto|overrideNone|mountedSuffix|flatInput|flatCached|flatOutput|deepseekMountedHeader|codingPlanKimi|codingPlanOpenrouter|codingPlanSiliconflow|codingPlanCommandcode|codingPlanScnet|codingPlanVolcengine|codingPlanQwen|codingPlanMimo|mimoWindowPlan|mimoWindowCompensation|codingPlanWindowBalance|qwenSource|qwenSourceLocal|qwenSourceCli|qwenSourceBailian|qwenCliNote|qwenBailianNote|qwenPlanCreditsLabel|qwenPlanStartLabel|qwenRatesLabel|qwenRatesModelPlaceholder|qwenRatePlaceholder|qwenRate_input|qwenRate_cachedInput|qwenRate_output|qwenRateDraftNote|qwenRatesAdd|qwenLocalNote|scnetPlanCreditsLabel|scnetPlanStartLabel|scnetLocalNote|volcengineAccessKeyIdLabel|volcengineSecretAccessKeyLabel|volcengineNote|volcengineAccessKeyPlaceholder|volcengineSecretPlaceholder|countdownHoursOnly|countdownHourMinute|countdownMinute|nextOffPeakIn|nextPeakIn|peakSummary|noPeakWindows|unknown|cardToday|cardMonth|cardTotal|cardTotalSub|externalUsage|combinedUsage|externalStale|externalHistory|cardsFootnote|timezoneHint|todaySessions|historyExpandHint|historySessionsLoading|historyNoSessions|historySessionsError|sessionRankTitle|sessionRankHint|sessionRankEmpty|sessionRankLoading|sessionRankError|sessionRankLimit|showSessionIdLabel|cardsTogglePlanTotal|cardsTogglePlanTotalHint|hideOfficialBalanceLabel|hideTodayCostLabel|hideSessionCostHeader|hideSessionCostDock|hideTurnCost|sessionRankSort|sessionSortCostDesc|sessionSortCostAsc|sessionSortTimeDesc|sessionSortTimeAsc|sessionSortRecent|history|statisticsUpgrade|usageTitle|usageTotal|usageDay|usageEmpty|usageSectionLabel|usagePositionLabel|usagePositionCost|usagePositionGeneral|usagePositionSection|displaySettings|tabOverview|tabQuotas|tabUsage|tabPricing|tabDisplay|historyDataTitle|positionLabel|positionDock|positionHeader|off|quotaStripGroup|quotaStripEnable|quotaStripShowBudget|quotaStripShowGo|quotaStripShowPlans|quotaStripNote|quotaStripGuideTitle|quotaStripGuideBody|quotaStripGuideOn|quotaStripGuideOff|clickToRefresh|balanceClickGuideTitle|balanceClickGuideBody|balanceClickGuideOk|sidebarLabel|sidebarOn|currencyLabel|currencyCny|currencyUsd|currencyEur|symbolLabel|rateLabel|decimalsLabel|balanceDisplayLabel|balanceSidebar|balanceSettings|balanceBoth|refreshIntervalLabel|peakEnabledLabel|peakNoticeLabel|badgeNote|priceTableTitle|pricingCurrencyLabel|pricingCurrencyUsd|pricingCurrencyCny|pricingCurrencyNote|priceTableNote|datedPriceNote|defaultModelId|newModelPlaceholder|addModel|dataSync|saving|autoSaveFailed|autoSavedAt|autoSaveHint|confirmFetch|apply|cancel|syncFromDocs|syncScopeNote|confirmReset|importLegacy|confirmImportLegacy|legacyImportFailed|legacyImportNote|confirmClear|clearAllHistory|lastSync|neverSynced|source|sourceOfficial|sourceBundled|languageLabel|localeAuto|localeZh|localeEn|sectionLabel|rpcFailed|rpcSyncFailed|rpcBalanceFailed".split("|"),Ja="weekends and Chinese public holidays are off-peak|OpenCode Go|Coding Plan|显示位置|Token Plan|DeepSeek models use the default price|中国公众假期全天谷价|刷新间隔|峰时高价时段显著提示|display position|above the input|session details|以同一系统账号运行|拓展价格表|输入框上方|图框详细信息|official account balance|the DSH credential store|Refresh interval|display currency|off-peak pricing|refresh interval|cost is an upper bound|extended price catalog|Monthly credits quota|今日费用|会话明细|右下角显示|命中价格的模型|导入安装前历史|按基础价格计费|按显示币种|时价计费|本地账本|自动保存|自动匹配|自定义余额|Balance query failed|removed from sidebar|Strip includes|Token usage|as the same OS user|pre-install history|Cost settings|DeepSeek peak-hour|Go quota|qianwen auth login|subscription quota|主页面侧边栏|会话排行加载|余额查询失败|写入按命中价|官方账户余额|开启后侧边栏|清除全部历史|留空按自然月|留空自动发现|费用明细入口|Clear all history|Entering off-peak|Quota not queried|This month|billed exactly at|never echoed back|to refresh|all off-peak|local ledger|the official|会话费用|历史记录|取消挂载|同步价格|官方文档|峰谷时段|峰谷计价|手动指定|本地估算|法定假日|用量统计|直接显示|调用失败|额度数据|额度横条|Preview entering|Show Codex quota|historical rates|Plan start date|Volcano Ark|base prices are|call failed|coding plan|in Settings|off-peak prices|on the DSH host|prices from|session ranking|后显示额度|开始对话后|未查询额度|汇总在这里|现在开启吗|订阅起始日|额度百分比|quota data|the ledger|All time|Failed to|billed at".split("|"),Oe=Object.fromEntries([["zh",'本(按每次调用实际时刻精确计费)|输入 {input} · 缓存 {cache} · 输出 {output}|缓存:读 {read} · 写 {write}(计费)|费用 {amount}|本会话 {amount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}|无限制|当前人民币金额来自美元价格 × 汇率 {rate}。对照官方人民币账单,请选择 CNY,再;同步会更新历史费用。|:{message}|未知错误|余额|查询失败|DeepSeek 开放平台账户余额|官方余额变动与交叉对账(偏差超阈时提示)|总余额 {amount}|赠送 {granted} · 充值 {toppedUp}|更新时间 {time}|预算({period})|已用 {used} / {amount}|今日 {amount} · 占预算 {pct}|本月 {month} · 累计 {total}|预算|(按官方价格精确计费)|今日 Token 用量|tokens|调用 {calls} 次 · 输入 {input} · 缓存 {cache} · 输出 {output}|本月 {amount}|累计 {amount}|今日|侧边栏今日显示|费用|Token 用量|今日|本月|累计|自定义区间|暂无。,费用将按天。|日期|调用|输入 tok|缓存 tok|输出 tok|费用|今日暂无会话记录。|会话|启用预算|预算额度()|预算周期|开始日期|结束日期(留空 = 今日)|统计区间:{range}|启用预算、已用金额及比例(换算);可选今日、本月、累计或自定义周期。|{period}预算 {amount} · 已用 {used} · {pct}%|(已超出)|(接近上限)|旧模型|默认回退|移除|基础|谷时|峰时|余额专用 API Key|优先使用此开放平台 Key;未配置时读取已登录官方账号余额,其次沿用模型凭据。|总余额 {total} · 赠送 {granted} · 充值 {toppedUp} · 更新于 {time}|:{message}|未查询余额||刷新中…|刷新余额|自定义 Provider 余额|添加配置|添加千问 / 阿里云余额|查询阿里云中国站可用金。RAM AccessKey 需 bss:DescribeBillingAccount 权限。前两项必填;STS 才需 Security Token。密钥存凭据库。|extract 支持点路径、数值和 add/subtract/divide 运算;NewApi quota 除以 500000 得到美元。|中文名称|英文名称|请求 URL|请求方法|请求头 (JSON)|请求体 (JSON)|留空不发送;JSON 原文保存并发送。默认 Content-Type 为 application/json,可在请求头覆盖。|解析规则 (JSON)|| (分钟)|余额原币种|折算(USD 余额)|使用显示汇率与精度;余额币种保持端点原币种。其他币种及积分不折算。|余额 {amount}|当日已用 {amount}|已用 {amount}|余额进度条 (蓝=余额,橙=当日,灰=已用)|进度条方向|各组进度条可独立选择填充方向:「剩余方向」满条起步、随消耗递减;「已用方向」空条起步、随消耗填满。|余额条(官方/自定义)|预算条|Go 额度条|Plan / Codex 额度条|剩余方向(满 → 空)|已用方向(空 → 满)|额度上限 (可选)|留空则优先使用 API 返回的 max_budget;仍无则显示整条浅蓝|JSON 格式无效|{{VAR_NAME}} 从凭据库或环境变量读取。<ROUTE>_API_KEY 中 ROUTE 为大写 Provider ID,符号改下划线,如 openai→OPENAI_API_KEY。同名共用密钥。|凭据白名单 (逗号分隔)|请求头带密钥时仅放行列表内主机,留空则放行并警告,防导入他人配置外带密钥。|凭据输入|为上方 {{VAR}} 占位符存入密钥(write-only,只写凭据库,不回显):|请求头还没有 {{VAR}} 占位符:填入如 "Authorization": "Bearer {{MY_API_KEY}}" 后这里会出现凭据输入框。|启用|剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}|剩余 {amount}|刷新| 订阅额度|Go|滚动 5 小时|本周|本月|重置:{time}|已到重置时间|剩余 {d}天{h}小时|剩余 {h}小时{m}分|剩余 {m}分钟|已用 {pct}%|剩余 {pct}%|{percent}%|更新于 {time}|Go 额度|Go 额度(分钟)|分钟| API Key(可选,)|Go 额度主档位|Go |已配置(来源:{source})|未配置|保存|编辑凭据|清除|保存中…|密钥只写入 DSH 凭据库,不保存在账本里,也不会回显。|以下密钥仍在,未迁入凭据库。请导出对应环境变量后重启:|预算|刷新额度||Anthropic(Claude Pro/Max)|Z.ai / 智谱 GLM |MiniMax |MiniMax Plan|查询域名(HTTPS)|留空自动选择官方站点。填写后 Key 仅发往该域名;使用可信地址,不含路径。|5h|7d|打开 DeepSeek 充值页(platform.deepseek.com/usage)|ChatGPT (Codex) 周额度|显示 Codex 额度(需安装并登录 dsh-openai-codex)|在侧栏显示 Codex 额度(关闭后仍保留会话额度条)|本包含子代理|暂无||选「 / 两者」卡片;窄栏显示百分比。|API Key(可选,)|(分钟)|刷新|登录|登录中…||CLIProxyAPI 网关额度|添加来源|来源名称|Base URL||允许的 Host|Management Key(只写)|状态|不支持的 Provider|未知|未发现账号|抓取于 {time}|切换账号 (当前: {account})|只显示 Gemini 额度|刷新|先勾选启用这一项|启用并保存后可刷新|删除|勾选启用后会排到最上面;点名称可展开该项自己的配置。最多 8 条,网关来源最多 4 条。|未启用。开启后将按查询该厂商的  额度并显示在这里。|开启后读取  的滚动 5 小时、周、月额度,显示在侧栏、设置页及右下角;无订阅时提示原因。|(dock)|在  额度 / 预算|滚动 5 小时额度|本周额度|本月额度|预算已用%|5h|周|月|日|预算|账本读取失败:{message}|正在读取账本…|账本不可用|同步失败:{message}|已清除。|清除失败:{message}|已关闭,|尚未生效(生效时间:{time}),当前|当前处于峰时段,按峰|当前为 DeepSeek 峰时高价时段,按峰|当前处于谷时段,按谷|周末时段——全谷价(周六及周日全天按谷)|周末时段——全谷价|周末全谷|——全天谷价|——全谷价|假日|(北京日期,逗号分隔)|自 2026-08-23 北京时间 00:00 起,周末和;调休上班的周末仍按谷价。|峰时|平价|条样式|简洁(单行紧凑)|经典(分段与胶囊芯片)|峰/谷切换前弹窗提醒|提前提醒(分钟,1-30)|提醒类型|进入峰时|进入谷时|峰和谷|即将进入峰时|即将进入谷时|约 {time} 后计费档位切换为{phase}价,请注意本时段调用成本。|峰时|谷时|知道了|峰价提醒|谷价提醒|弹窗位置|右下角|屏幕中心|同步发送系统通知|开关后请在浏览器地址栏允许通知权限,才能在页面最小化/切走时收到提醒。|预览弹窗|预览 进入峰|预览 进入谷|(预览)|与提示|提示已隐藏:需启用并开启「」。|常规|金额与币种|侧边栏显示|简化侧栏显示|精简卡片,保留金额、额度和悬停详情;高度最多占屏幕 38%,超出可滚动。关闭后恢复。|试试更轻巧的侧栏|简化显示可以为会话列表留出更多空间。要?之后可在「设置 → 费用 → 显示」中切换。|开启简化显示|保留当前显示|设置未能保存。可重试,或关闭提示后在设置中调整。|关闭提示|今日 / {period}预算|侧边栏进度条样式|标准|紧凑(两列)|恢复已移除的模型 ({count})|移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按规则计价。|右下角角标|||按厂商和模型分类的参考价。挂载后可编辑并计费;DeepSeek 后用默认价。|展开|收起|挂载||已挂载|未核价|DeepSeek 后按默认价计费。|按模型统计(token 与费用)|侧栏模型花费|{n} 模型|其它|显示模型花费卡片|默认展开|记住展开状态|显示 Token|显示费用占比条| Top-1 模型|默认周期|收起摘要|卡片位置|模型行数(1–10)|(10–60 秒)|周期总额与模型数|Top-1 模型与金额|顶部|余额之后|底部|今日|近 90 天|费用排行|Token 消耗|缓存命中率|未上报?|长调用无缓存命中:代理可能移除缓存字段。金额按全未命中计,是上界;可直连核对。|性价比 · 每美元 token 数|输入|缓存|输出|该时段暂无用量数据。|综合单价 {price}/M|命中率=缓存读÷(缓存读+普通输入);「未上报?」表示缓存字段可能缺失,金额为上界。单价=费用÷token×1M;性价比=token÷费用。|未分模型(早期数据 · 按当时记录计费)|本会话 {amount}(API)· Plan 等值 {planAmount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}|费用 {amount}(+Plan)|Plan 订阅额度消耗(等值){amount}| (每 1% 与满窗估算)|尚无  ;请在「额度」页开启并刷新厂商。|窗口|已用 %|本周期实际()|每 1% 额度 ≈|满窗 100% ≈|重置 {time}|采样差分|当前用量折算|样本不足|{method}(基准 {time})|读数精度受限|Plan 用量曲线(按采样区间聚合)|每日|每周|每月|采样不足:至少两次成功刷新,且发生变化。|{date}:满窗估计 ≈ {full}(每 1% ≈ {per1})· 实际 {tokens} / {cost} · {intervals} 个采样区间|金额是目录价等值;订阅耗额度,预算只计 API。估算仅含 dsh 调用;服务端百分比含全账号。短时样本精度有限;5h 滚动,周/月按本地日历。|计费方式|Plan 订阅|自动|API 按量|在费用设置|仅控制是否在费用价格表;不影响挂载和计费。隐藏的已挂载模型仍可在拓展表编辑。|可逐模型切换。DeepSeek 默认,第三方默认在拓展表。|手动新增模型|未知模型名|自动(去后缀 / 前缀 / 家族相似)|仅精确匹配|优先;只接受同名及日期、版本、上下文后缀。未命中的 DeepSeek 用默认价,其他渠道不计价。|最近出现但未|这些模型没有价格。可;「默认价」使用 DeepSeek 默认价。本地推理默认零费用。|DeepSeek 默认价|移除|本地模型(零消耗)|本月已|这些模型价格。可改选价格或零费用;token 仍统计。保存后移入区。|保持自动命中|暂无手动匹配覆盖。|已挂载(参与计费)|输入|缓存|输出|DeepSeek 价格表(已挂载)|Kimi / Moonshot|OpenRouter|SiliconFlow 硅基流动|CommandCode|SCNet 超算互联网 |火山方舟  |千问 Qwen |小米 MiMo |套餐积分|补偿积分|余额|额度来源||官方 CLI|百炼 CLI|CLI 模式需在 DSH 主机安装 @qianwenai/qianwen-cli,并 。|百炼 CLI:在 DSH 主机安装 bailian-cli。登录按钮会在该主机打开授权浏览器;远程或无界面主机请 bl auth login --console。|月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)|(可选,格式 YYYY-MM-DD;)|Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)|模型名,如 qwen3.8-max-preview|费率|输入|缓存读|输出|待填齐三项正数后;全部清空恢复内置表。|添加|Credits ,以控制台为准。只计 qwen 及 qwen/qianwen-tokenplan 订阅渠道,含 llm- 前缀;不计按量 API。表外模型需设抵扣率。|月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)|(可选,格式 YYYY-MM-DD;)|优先用 24 小时内的控制台快照,否则按和官方 Credits 表估算。其他工具和表外模型不计入。|火山引擎 AccessKey ID|火山引擎 SecretAccessKey|火山方舟需 AK/SK、ArkReadOnlyAccess 和 BillingCenterReadOnlyAccess;可填凭据或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。只连接 open.volcengineapi.com。|AK...|SK...|{h}小时|{h}小时{m}分|{m}分钟|{time}后进入平价|{time}后进入高峰|峰时段(UTC):{windows};生效时间:{time}。{status}|未配置。{status}|未知||本月费用|累计费用|自账本建立以来 · 调用 {calls} 次|外部用量|DSH + 外部合计|外部快照超过 24 小时未更新|近期每日记录|金额取最近快照,可能比官方账单晚几分钟。tokens 含输入、输出、缓存和推理;推理并入输出计费。以金额对账。|今日/本月按宿主时区 {host},浏览器为 {browser}。时区不同会影响日界和对账;可将 dsh 改为本地时区。|今日会话|点击日期行可展开当日|加载中…|该日无(早期数据或会话日志已清理)|加载失败|按会话统计(全部历史)|跨天合并,子代理按开关归并。仅列选定条数,累计费用包含全部对话。|暂无会话数据|中…|失败|显示条数|会话列表附显会话 ID|金额含 Plan 总额|开启后所有金额按含 Plan 订阅等值的总费用展示;关闭(默认)仅计真金白银 API 渠道|隐藏(与设置页不再显示官方余额)|隐藏今日消耗金额(/预算明细/概览卡片不再显示)|隐藏标题栏|隐藏输入框下方|隐藏每轮回复后的本轮费用|排序|费用 高→低|费用 低→高|时间 新→旧|时间 旧→新|实时顺序||计费统计需要 DSH 0.2.0-rc.2 或更新版本的模块加载器。|Token |累计 {tokens} tokens · 输入 {input} · 缓存 {cache} · 输出 {output} · {calls} 次调用|{date}:共 {tokens} tokens(输入 {input} · 缓存 {cache} · 输出 {output})· {calls} 次调用 · {cost}|暂无历史数据,每日用量会|用量|Token 位置|费用设置|通用设置|独立分节(用量)|显示设置|概览|额度|用量|价格|显示|历史数据||输入区下方|会话标题栏|关闭||启用(一条横排显示)|横条含预算已用%|横条含 Go 额度|横条含  额度|横条悬停可见各窗口重置时刻与更新时间;无可用时自动隐藏。|新增:|在显示预算及 / 。?可在「设置 → 显示设置」修改。|开启横条|暂不开启|点击立即刷新|新增:余额图框点击刷新|点击侧边栏余额或  图框即可刷新;刷新时图框闪烁,失败时保留原值并在悬停提示中说明原因。|知道了|当日费用显示|侧边栏底部|货币单位|人民币 CNY|美元 USD|欧元 EUR|货币符号|汇率(1 美元 = ? 目标币种)|小数位数|余额||设置页|两者都显示|余额(分钟)|启用 DeepSeek 价格|(侧边栏预算框/;设置页峰谷面板内预览)|会话按调用时价格计费(含峰谷与历史档位)。输入、输出、缓存读写分开统计;独立缓存写入价与长上下文档位按配置生效。|价格表(美元 / 1M tokens)|官方价格币种|美元(英文官方页)|人民币(中文官方页)|决定所用的官方页语言。切换并同步后后台重算历史;日志不全的会话保留原价。完成后提示。|按调用时间计价:Flash 自 9 月 10 日北京 12:00 用新价,V4 Pro 自 9 月 14 日同刻用 Flash 价;此前用历史价。工作日 09–12、14–18 峰价翻倍;周末及。缓存。|这里显示当前适用价格。手工编辑会取消此条后续预定调价,已发生的历史价格仍保留。|default(未匹配模型时回退)|新模型 ID(如 deepseek-v4-pro)|添加模型|数据与同步|保存中…|失败:{message}|已 {time}|配置修改后|确认用价格覆盖价格表?|应用|取消|从|官方同步只更新 DeepSeek 价格(含峰谷);z-ai/Kimi/Qwen/Volcano 等第三方价格随版本更新,也可在或模型名匹配中调整。|确认?||确认导入?将回放全部会话日志,只补账本缺失的日期与会话,不影响已有记录。|失败:{message}|首次启动自动导入旧记录;拷入日志后可重跑。按当前价格回推;已删除日志无法回放,跨安装时刻的会话不计此前用量。|确认清除||最近同步:{time}|从未(使用内置价格)|;来源:{source}||内置默认|界面语言|跟随 DSH(自动)|简体中文|English|费用|{method} |同步|余额刷新'],["en",`Cost of this session ( each call time)|Input {input} · Cache {cache} · Output {output}|Cache: read {read} · write {write} (writes  the hit price)|Cost {amount}|This session {amount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}|Unlimited|CNY totals use USD prices × {rate}. To compare official CNY bills, select CNY, then sync prices; syncing also updates historical costs.|: {message}|Unknown error|Balance|Query failed|DeepSeek open-platform account balance|Cross-check official balance changes against the  (warn when they diverge)|Total {amount}|Granted {granted} · Topped-up {toppedUp}|Updated {time}|Budget ({period})|Used {used} / {amount}|Today {amount} · {pct} of budget| {month} ·  {total}|Budget|Today's cost ( official prices)|Today's token usage|tokens|Calls {calls} · Input {input} · Cache {cache} · Output {output}| {amount}| {amount}|Today|Sidebar today display|Cost||Today|||Custom range|No history yet. Once you start chatting, costs are aggregated here per day.|Date|Calls|In tok|Cache tok|Out tok|Cost|No sessions recorded today.|Session|Enable budget|Budget amount (in )|Budget period|Start date|End date (empty = today)|Range: {range}|Enable a budget to see its limit, used amount and percentage in the . Choose today, month, all time or a custom range.|{period} budget {amount} · Used {used} · {pct}%| (over limit)| (near limit)|Legacy|Default fallback|Remove|Base|Off-peak|Peak|Balance API key|This Open Platform key takes priority; otherwise the signed-in  is read, then model credentials.|Total {total} · Granted {granted} · Topped-up {toppedUp} · Updated {time}|: {message}|Balance not queried|Account balance|Refreshing…|Refresh balance|Custom provider balance|Add entry|Add Qianwen / Alibaba Cloud balance|Shows Alibaba Cloud China funds. RAM AccessKey needs bss:DescribeBillingAccount. The first two fields are required; Security Token is for STS. Secrets stay in the credential store.|Extract accepts paths, numbers and add/subtract/divide. Divide NewApi quota by 500000 for USD.|Chinese name|English name|Request URL|HTTP method|Headers (JSON)|Request body (JSON)|Blank sends no body; JSON text is saved and sent as entered. Content-Type defaults to application/json; headers can override it.|Extract rules (JSON)|Custom balance display| (minutes)|Source currency|Convert USD balance to |Uses the display rate and precision. Keep the source currency; other currencies and credits stay unchanged.|Balance {amount}|Today {amount}|Spent {amount}|Balance progress bar (blue=balance, orange=today, gray=spent)|Progress bar direction|Each group of bars can independently choose its fill direction: "Remaining" starts full and drains with usage; "Used" starts empty and fills up.|Balance bars (official/custom)|Budget bar| bar|Plan / Codex quota bars|Remaining (full → empty)|Used (empty → full)|Budget cap (optional)|Leave empty to use API max_budget; if still missing, show full light-blue bar|Invalid JSON|{{VAR_NAME}} reads a credential or environment variable. <ROUTE>_API_KEY uses an uppercase Provider ID with underscores, such as openai→OPENAI_API_KEY. Names can share a key.|Allowed hosts (comma-separated)|When headers carry credentials only listed hosts are allowed; leave empty to allow with a warning. Protects keys when importing someone else's config.|Credential input|Store the key for each {{VAR}} placeholder above (write-only: stored in , ):|No {{VAR}} placeholders in the headers yet — add e.g. "Authorization": "Bearer {{MY_API_KEY}}" and a credential input will appear here.|Enable|Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}|Remaining {amount}|Refresh custom balance| |Go|Rolling 5h|Weekly|Monthly|Resets: {time}|Reset time reached|{d}d {h}h left|{h}h {m}m left|{m}m left|{pct}% used|{pct}% remaining|{percent}%|Updated {time}| |  (minutes)|min| API key (optional; empty = auto-detect)| primary window|Go box details|Configured (source: {source})|Not configured|Save|Edit credential|Clear|Saving…|The key is written to  only — it is never saved in  and .|These credentials remain in the . Export the matching environment variables and restart:|Budget box details|Refresh quota||Anthropic (Claude Pro/Max)|Z.ai / Zhipu GLM |MiniMax |MiniMax Plan|Quota origin (HTTPS)|Empty: official sites. Otherwise the Key is sent only to this origin. Use a trusted address without a path.|5h|7d|Open DeepSeek top-up page (platform.deepseek.com/usage)|ChatGPT (Codex) weekly quota| (requires signed-in dsh-openai-codex)| in sidebar (keep the conversation strip when hidden)|Include subagents in session cost|No |Display position|“Main sidebar / Both” shows a quota card; the narrow rail shows percentages.|API key (optional; empty = auto-detect)| (minutes)|Refresh|Login|Signing in…||CLIProxyAPI gateway quotas|Add source|Source label|Base URL|Display|Allowed hosts|Management key (write-only)|Status|Unsupported providers|Unknown|No accounts|fetched {time}|Switch account (current: {account})|Gemini quota only|Refresh|Enable this item first|Enable and save a  |Remove|Enabled items move to the top; click a name to expand its own settings. Up to 8 custom balances and 4 gateway sources.|Disabled. Enable it to query this vendor's  quota on the  and show it here.|Enable  rolling 5h, weekly and monthly quotas in the sidebar, Settings and bottom-right corner. Missing subscriptions show a reason.|Bottom-right (dock) display|Show  quota / budget at the bottom-right|Rolling-5h quota|Weekly quota|Monthly quota|Budget used %|5h|Wk|Mo|Daily|Budget|Ledger read failed: {message}|Reading ledger…|Ledger unavailable|Sync failed: {message}|History cleared.|Clear failed: {message}|Peak/ is off;  used|Not yet effective (effective at {time});  currently used|Peak hour now; peak prices apply| pricing is active; current calls are  peak prices|Off-peak now;  apply|Weekend —  (Sat & Sun   all day)|Weekend — |Weekend|Chinese public holiday — off-peak all day|Public holiday — |Holiday|Public holidays (Beijing dates, comma separated)|Since Aug 23, 2026 (Beijing time),  all day, including work-shift weekends.|Peak|Off-peak|Peak period strip style|Compact (one-line)|Classic (segments & chip)|Popup alert before peak/off-peak switch|Lead time (minutes, 1-30)|Alert type|Entering peak||Both|Entering peak hours soon| hours soon|Billing switches to {phase} pricing in about {time}; mind your call costs in this window.|peak|off-peak|Got it|Peak alert|Off-peak alert|Popup position|Bottom-right|Screen center|Also send a system notification|When enabled, allow notification permission in the browser address bar so you get alerted even when the page is minimized or backgrounded.|Preview the popup| peak| off-peak| (preview)|Peak/ & notice|Notice hidden: enable peak/ and the “prominent notice” toggle.|General|Money & currency|Sidebar display|Simplify the sidebar|Condense cards but keep amounts, quotas and hover details. Height is capped at 38% of the viewport with scrolling. Turn off to restore.|A lighter sidebar|Simple display leaves more room for conversations. Enable it now? You can change it  → Cost → Display anytime.|Enable simple display|Keep current display|Settings could not be saved. Retry or dismiss this guide and change them later .|Dismiss guide|Today / {period} budget|Sidebar progress style|Standard|Compact (2 columns)|Restore removed models ({count})|Remove clears the override and hides the row until restored. Usage records are kept; automatic price matching applies.|Corner chips|Box details|Extended price catalog|Reference prices by vendor and model. Mount to edit and bill; unmounted DeepSeek uses its default price.|Expand |Collapse |Mount|Unmount|Mounted|Unpriced|Unmounted .|Per-model statistics (tokens & cost)|Sidebar model costs|{n} models|Other|Show model cost card|Expand by default|Remember expansion|Show tokens|Show cost shares|Top model in corner dock|Default period|Collapsed summary|Card position|Model rows (1–10)| (10–60 seconds)|Period total and model count|Top model and cost|Top|After balances|Bottom|Today|Last 90 days|Cost ranking||Cache hit rate|unreported?|Zero cache hits on long calls may mean a relay removed cache fields. All-miss ; check with the direct API.|Value · tokens per USD|Input|Cache|Output|No usage data for this period.|blended {price}/M|Hit rate = cache reads ÷ (reads + uncached input). “Unreported?” means cache data may be missing, so . Unit price = cost ÷ tokens × 1M; value = tokens ÷ cost.|Unattributed (early data · billed as recorded)|This session {amount} (API) · Plan equiv. {planAmount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}|Cost {amount} (+Plan)|Plan  usage (equiv.) {amount}| usage stats (per-1% & full-window estimates)|No   yet. Enable and refresh a provider under Quotas.|Window|Used %|This period actual ()|Per 1% quota ≈|Full window (100%) ≈|resets {time}|sample delta|current usage ratio|not enough samples|{method} (as of {time})|low reading precision|Plan usage curves (aggregated from sample intervals)|Daily|Weekly|Monthly|Not enough samples: refresh successfully twice with a quota percentage change.|{date}: full-window est. ≈ {full} (per 1% ≈ {per1}) · actual {tokens} / {cost} · {intervals} sample interval(s)|Amounts are catalog-price equivalents. Plans use quota; budgets count API only. Estimates cover dsh calls, while server percentages cover the account. Short samples are less precise. 5h rolls; week/month use local dates.|Billing class|Plan subscription|Auto|API usage|Show directly in |Controls direct display in ; mounting and billing stay unchanged. Hidden models remain editable in this catalog.|Choose where each model appears. DeepSeek shows directly; other vendors default to the catalog.|Custom models|Auto-match unknown model names|Auto (strip suffix / prefix / family similarity)|Exact match only|Manual overrides take priority. Auto-match accepts only the same name or date, version and context suffixes. Unknown ; other providers stay unpriced.|Recently seen models without a price hit|These models have no price. Assign one manually; “Default price” uses DeepSeek defaults. Local inference costs zero until assigned.|DeepSeek default price|Remove|Local model (zero cost)|Models matched this month|These models matched automatically. Choose another price or zero cost; tokens still count. Saved overrides move to the manual list.|Keep auto match|No manual match overrides.|Mounted (billed)|Input|Cached|Output|DeepSeek price table (mounted)|Kimi / Moonshot|OpenRouter|SiliconFlow|CommandCode|SCNet | |Qwen  (qianwenai.com)|Xiaomi MiMo |Plan credits|Compensation|Balance|Quota source|Local estimate|Official CLI|Bailian CLI|Install @qianwenai/qianwen-cli  and run  .|Install bailian-cli . Login opens that host’s browser; for a remote or headless host, run bl auth login --console .| (personal Lite 50K / Standard 500K; see your plan page)| (optional, YYYY-MM-DD; empty = calendar month)|Credits rate overrides (optional; credits deducted per 1M tokens; empty = built-in table)|Model name, e.g. qwen3.8-max-preview|rate|Input|Cached input|Output|Enter all three positive rates to save automatically; clear all to restore the built-in table.|Add|Local Credits estimate; console is authoritative. Counts qwen and qwen/qianwen-tokenplan subscription routes, including llm- prefix. Excludes pay-as-you-go API. Add rates for other models.| for local estimates (Basic 60,000 / Standard 240,000 / Pro 600,000)| (optional, YYYY-MM-DD; empty = calendar month)|Uses console snapshots newer than 24h, then estimates from local records and official Credits rates. Other tools and unlisted models are excluded.|Volcengine AccessKey ID|Volcengine SecretAccessKey| needs AK/SK, ArkReadOnlyAccess and BillingCenterReadOnlyAccess. Enter credentials or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Only open.volcengineapi.com is contacted.|AK...|SK...|{h}h|{h}h {m}m|{m}m|Off-peak in {time}|Peak in {time}|Peak hours (UTC): {windows}; effective: {time}. {status}|No peak windows configured. {status}|unknown|Today|||Since  was created · Calls {calls}|External usage|DSH + external total|External snapshot has not been updated for 24 hours|Recent daily records|Amounts use the latest snapshot and may lag  bill by minutes. Tokens include input, output, cache and reasoning; reasoning is billed with output. Reconcile by amount.|Today/month use host timezone {host}; this browser uses {browser}. Different day boundaries affect reconciliation. Set dsh to your local timezone to align.|Today's sessions|Click a date row to expand its |Loading …|No  for this day (early data or session logs cleaned)| load |By session (all history)|Days combined; subagents follow settings. Selected rows shown; cumulative costs include every conversation.|No session data yet|Loading …| load |Rows|Show session IDs in session lists|Include plan totals|When on, every amount shows total equivalent cost including plan subscriptions; off (default) counts real-money API channels only|Hide  (balance UI  and settings)|Hide today's cost (today's amount , budget details and overview card)|Hide header cost details|Hide composer cost details|Hide turn cost summaries|Sort|Cost high→low|Cost low→high|Time new→old|Time old→new|Recent order|History|Cost statistics requires the module loader from DSH 0.2.0-rc.2 or newer.| stats|All-time {tokens} tokens · input {input} · cache {cache} · output {output} · {calls} calls|{date}: {tokens} tokens (input {input} · cache {cache} · output {output}) · {calls} calls · {cost}|No history yet — daily usage will accumulate here|Usage| stats position||General settings|Own section (Usage)|Display settings|Overview|Quotas|Usage|Pricing|Display|History data|Session cost |Below the composer|Session title bar|Off|Quota strip |Enable the quota strip (one row  box)| budget used %| the |  quotas|Hover a chip for reset times and the last refresh; the strip hides itself when there is no .|New: quota strip |Show budget and /coding-plan percentages  box. Enable now? Change it anytime  → Display.|Enable the strip|Not now|Click  now|New: click the balance box |Click a sidebar balance or plan box . It pulses while loading; on failure it keeps the old value and shows the reason on hover.|Got it|Today cost display|Sidebar footer|Currency|Chinese Yuan (CNY)|US Dollar (USD)|Euro (EUR)|Currency symbol|Exchange rate (1 USD = ? target currency)|Decimal places|Balance |Main sidebar|Settings page|Both|Balance  (minutes)|Use  prices|Prominent notice during peak hours (sidebar budget box, today's cost; previewed in the Settings peak panel)|Session cost uses call-time prices, including peak and . Input, output, cache reads and writes are separate; configured cache-write and long-context rates apply.|Price table (USD / 1M tokens)|Official price currency|USD (English official page)|CNY (Chinese official page)|Selects  pricing-page language. Sync then recalculates history in the background; sessions without full logs keep their earlier basis.|Call-time prices: Flash changes Sep 10 04:00 UTC; V4 Pro uses Flash  Sep 14 04:00 UTC. Earlier calls retain history. Mon–Fri peaks 01–04 and 06–10 UTC cost 2×; . Cache writes use hit rates.|Current rates are shown here. Editing cancels any future scheduled change for this entry; earlier  are retained.|default (fallback for unmatched models)|New model ID (e.g. deepseek-v4-pro)|Add model|Data & sync|Saving…|Auto-save failed: {message}|Auto-saved {time}|Settings are auto-saved|Overwrite the price table with   docs?|Apply|Cancel|Sync  official docs|Official sync updates DeepSeek prices (including peak rates). Third-party prices (z-ai/Kimi/Qwen/Volcano) follow releases; edit in the extended catalog or model matching.|?|Import |Confirm import? Replays all session logs and only fills dates/sessions missing from ; existing records are untouched.| import : {message}|Pre-install history imports at first launch; rerun after copying old logs. Costs use current prices. Deleted logs cannot replay; sessions spanning installation exclude earlier usage.|Confirm clear||Last sync: {time}|Never (bundled prices)|; Source: {source}|Official docs|Bundled|Language|Follow DSH (auto)|Simplified Chinese|English|Cost|{method} |Sync |Balance refresh `]].map(([t,s])=>{const o=s.replace(/[-]/g,a=>Ja[a.charCodeAt(0)-57344]).split("|");return[t,Object.fromEntries(Va.map((a,n)=>[a,o[n]]).filter(([,a])=>a!=="\0"))]}));function Xt(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function Ee(t){const s=typeof t=="string"?t.toLowerCase().split(/[-_]/)[0]:"";return s==="zh"||s==="en"?s:null}function _(t){const s=typeof t=="string"?t:t?.locale;return s==="zh"||s==="en"?s:Ee(t?.activeLocale)||Xt()}function G(t){const s=t==="zh"?Oe.zh:Oe.en;return(o,a)=>{let n=s[o]??Oe.en[o]??o;if(a)for(const l of Object.keys(a))n=n.split("{"+l+"}").join(String(a[l]));return n}}const qe={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustomRange"};function ue(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function ge(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&ue(s,"object"),t}function ae(t,s){return(typeof t!="number"||!Number.isFinite(t))&&ue(s,"number"),t}function re(t,s){return typeof t!="string"&&ue(s,"string"),t}const et=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function ea(t,s=!1){return t===null||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([o,a])=>s?o.length>0&&["plan","api"].includes(a):["auto","plan","api"].includes(a)))}function Me(t,s){return typeof t!="boolean"&&ue(s,"boolean"),t}const Ie=(t,s,o)=>Object.fromEntries(s.map(a=>[a,o(t[a])]));function ta(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const a of Object.keys(t)){const n=t[a];if(n===null||typeof n!="object"||Array.isArray(n))continue;const l=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0;o[a]={...Ie(n,["input","output","cacheRead","cacheWrite","reasoning","cost"],l),apiCost:n.apiCost===void 0?l(n.cost):l(n.apiCost)}}return o}function aa(t,s){ge(t,s);const o={reasoning:t.reasoning===void 0?0:ae(t.reasoning,s+".reasoning"),apiCost:t.apiCost===void 0?void 0:ae(t.apiCost,s+".apiCost"),byModel:ta(t.byModel,s+".byModel"),byProviderModel:ta(t.byProviderModel,s+".byProviderModel")};for(const a of["input","output","cacheRead","cacheWrite","calls","cost"])o[a]=ae(t[a],s+"."+a);return o}function na(t){return(Array.isArray(t)?t:ue("rows","array")).map(s=>({provider:re(s.provider,"provider"),model:re(s.model,"model"),bucket:re(s.bucket,"bucket"),tokens:ae(s.tokens,"tokens"),rate:ae(s.rate,"rate"),cost:ae(s.cost,"cost"),priced:Me(s.priced,"priced"),plan:Me(s.plan,"plan")}))}function gt(t,s){return{...aa(t,s),id:re(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:""}}function he(t,s){const o={...aa(t,s),date:re(t.date,s+".date"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||ue(s+".sessions","array"),o.sessions=t.sessions.map((a,n)=>gt(a,s+".sessions["+n+"]"))),o}function ht(t,s,o=["cacheWrite","reasoning"]){const a={};for(const n of["cacheHit","cacheMiss","output"])a[n]=ae(t[n],s+"."+n);for(const n of o)t[n]!==void 0&&(a[n]=ae(t[n],s+"."+n));return a}function yt(t,s){ge(t,s);const o=ht(t,s);for(const a of["offPeak","peak","legacyBase","longContext"])t[a]!==void 0&&(o[a]=ht(t[a],s+"."+a,["cacheWrite","reasoning","aboveInputTokens"]));t.cny!==void 0&&(o.cny=ht(t.cny,s+".cny")),t.legacy!==void 0&&(o.legacy=Me(t.legacy,s+".legacy")),t.rateHistory!==void 0&&((!Array.isArray(t.rateHistory)||t.rateHistory.length>16)&&ue(s+".rateHistory","price history"),o.rateHistory=t.rateHistory.map((a,n)=>((!a||typeof a.before!="string"||!Number.isFinite(Date.parse(a.before)))&&ue(s+".rateHistory","dated price"),{...yt({...a,rateHistory:void 0},s+".rateHistory."+n),before:a.before})));for(const a of["billingMode","sourceUrl","checkedAt","notes"])typeof t[a]=="string"&&(o[a]=t[a]);return o}function Za(t,s){const o=n=>n==null?void 0:{...n.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:n.enabled===!0,label:typeof n.label=="string"?n.label:"",labelEn:typeof n.labelEn=="string"?n.labelEn:"",display:et(n.display,["sidebar","settings","off"],"both"),unit:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",convertToDisplayCurrency:n.convertToDisplayCurrency===!0,refreshMinutes:typeof n.refreshMinutes=="number"&&Number.isFinite(n.refreshMinutes)?n.refreshMinutes:15,request:n.request&&typeof n.request=="object"?n.request:{url:""},extract:n.extract&&typeof n.extract=="object"?n.extract:{},allowedHosts:Array.isArray(n?.allowedHosts)?n.allowedHosts.filter(l=>typeof l=="string"):[]};ge(t,s);const a={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const n of Object.keys(t.prices.models))a[n]=yt(t.prices.models[n],s+".prices.models."+n);return{locale:t.locale==="zh"||t.locale==="en"||t.locale==="auto"?t.locale:"auto",position:t.position==="header"||t.position==="off"?t.position:"dock",sidebar:t.sidebar!==!1,showSessionId:t.showSessionId===!0,hideOfficialBalance:t.hideOfficialBalance===!0,hideTodayCost:t.hideTodayCost===!0,...Ie(t,["hideSessionCostHeader","hideSessionCostDock","hideTurnCost"],n=>n===!0),sidebarTodayMetric:t.sidebarTodayMetric==="tokens"?"tokens":"cost",showTotalWithPlan:t.showTotalWithPlan===!0,sidebarSimple:t.sidebarSimple===!0,sidebarSimplePromptSeen:t.sidebarSimplePromptSeen===!0,sidebarModels:Object.fromEntries(Object.entries(Wt).map(([n,l])=>[n,t.sidebarModels?.[n]??l])),codexQuotaEnabled:t.codexQuotaEnabled===!0,codexQuotaSidebar:t.codexQuotaSidebar!==!1,includeSubagentCost:t.includeSubagentCost===!0,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(n=>typeof n=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:ae(t.decimals,s+".decimals"),exchangeRate:ae(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((n,l)=>({start:ae(n.start,s+".peakWindows["+l+"].start"),end:ae(n.end,s+".peakWindows["+l+"].end")})):[],peakHolidays:Array.isArray(t.peakHolidays)?t.peakHolidays.filter(n=>typeof n=="string"):[],peakNotice:t.peakNotice!==!1,peakAlertEnabled:t.peakAlertEnabled!==!1,peakAlertAhead:Number.isFinite(t.peakAlertAhead)&&t.peakAlertAhead>=1&&t.peakAlertAhead<=30?t.peakAlertAhead:2,peakAlertTarget:t.peakAlertTarget==="peak"||t.peakAlertTarget==="offpeak"?t.peakAlertTarget:"both",peakAlertPosition:t.peakAlertPosition==="center"?"center":"corner",peakAlertWebNotify:t.peakAlertWebNotify===!0,peakStyle:t.peakStyle==="classic"?"classic":"compact",priceMatch:t.priceMatch==="exact"?"exact":"auto",priceOverrides:(()=>{const n={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[l,i]of Object.entries(t.priceOverrides))typeof l=="string"&&typeof i=="string"&&(n[l]=i);return n})(),priceTableDisplay:(()=>{const n={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[l,i]of Object.entries(t.priceTableDisplay))typeof l=="string"&&(n[l]=i===!0);return n})(),codingPlans:(()=>{const n={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const l of Object.keys(t.codingPlans)){const i=t.codingPlans[l];i===null||typeof i!="object"||Array.isArray(i)||(n[l]={enabled:i.enabled===!0,display:i.display==="sidebar"||i.display==="both"||i.display==="off"?i.display:"settings",refreshMinutes:typeof i.refreshMinutes=="number"&&Number.isFinite(i.refreshMinutes)?i.refreshMinutes:15,apiKey:typeof i.apiKey=="string"?i.apiKey:"",...l==="minimax"?{baseUrl:typeof i.baseUrl=="string"?i.baseUrl:""}:{},...l==="qwen"?{quotaSource:["cli","bailian"].includes(i.quotaSource)?i.quotaSource:"local"}:{},...typeof i.planCredits=="number"&&Number.isFinite(i.planCredits)&&i.planCredits>0?{planCredits:i.planCredits}:{},...typeof i.planStart=="string"?{planStart:i.planStart}:{},...i.rates!==null&&typeof i.rates=="object"&&!Array.isArray(i.rates)?{rates:i.rates}:{},...typeof i.accessKeyId=="string"?{accessKeyId:i.accessKeyId}:{},...typeof i.secretAccessKey=="string"?{secretAccessKey:i.secretAccessKey}:{}})}return n})(),prices:{models:a,default:yt(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:ae(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:re(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:et(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:et(t.goQuota?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.goQuota?.refreshMinutes=="number"&&Number.isFinite(t.goQuota.refreshMinutes)?t.goQuota.refreshMinutes:15,apiKey:typeof t.goQuota?.apiKey=="string"?t.goQuota.apiKey:"",main:t.goQuota?.main==="weekly"||t.goQuota?.main==="monthly"?t.goQuota.main:"rolling",detail:t.goQuota?.detail!==!1},customBalance:o(t.customBalance),gatewayQuotas:(()=>{const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(n)?n.slice(0,4).filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).map(i=>({id:typeof i.id=="string"?i.id.slice(0,48):"",type:"cliproxyapi",label:typeof i.label=="string"?i.label.slice(0,80):"",baseURL:typeof i.baseURL=="string"?i.baseURL:"",enabled:i.enabled!==!1,display:et(i.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof i.refreshMinutes=="number"&&Number.isFinite(i.refreshMinutes)?Math.min(1440,Math.max(1,Math.floor(i.refreshMinutes))):15,includeProviders:Array.isArray(i.includeProviders)?[...new Set(i.includeProviders.filter(r=>typeof r=="string").map(r=>r.toLowerCase()).filter(r=>xt.includes(r)))]:xt,allowedHosts:Array.isArray(i.allowedHosts)?i.allowedHosts.filter(r=>typeof r=="string").slice(0,16):[],allowInsecureHttp:i.allowInsecureHttp===!0,antigravityOnlyGemini:i.antigravityOnlyGemini===!0,keyVar:typeof i.keyVar=="string"?i.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(l=>l!==null&&typeof l=="object").slice(0,8).map(o).filter(Boolean);const n=o(t.customBalance);return n?[n]:[]})(),corner:{enabled:t.corner?.enabled===!0,goRolling:t.corner?.goRolling!==!1,goWeekly:t.corner?.goWeekly!==!1,goMonthly:t.corner?.goMonthly!==!1,budget:t.corner?.budget!==!1},quotaStrip:{enabled:t.quotaStrip?.enabled===!0,budget:t.quotaStrip?.budget!==!1,go:t.quotaStrip?.go!==!1,plans:t.quotaStrip?.plans!==!1,promptSeen:t.quotaStrip?.promptSeen===!0},usage:{position:t.usage?.position==="general"||t.usage?.position==="section"?t.usage.position:"cost"},barDirections:(()=>{const n=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},l=(i,r)=>n[i]==="remaining"||n[i]==="used"?n[i]:r;return{balance:l("balance","remaining"),budget:l("budget","used"),go:l("go","used"),plan:l("plan","used")}})(),planBilling:{providers:ea(t.planBilling?.providers),models:ea(t.planBilling?.models,!0)}}}const je=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Pe=t=>je(t)??0,$a={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},Xa={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},sa=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function kt(t,s){return ge(t,s),{status:t.status==="ok"||t.status==="error"?t.status:"off",message:typeof t.message=="string"?t.message:"",fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:0}}function en(t,s){return{...kt(t,s),keyConfigured:t.keyConfigured===!0,keySource:typeof t.keySource=="string"?t.keySource:"",currency:typeof t.currency=="string"?t.currency:"",totalBalance:Pe(t.totalBalance),grantedBalance:Pe(t.grantedBalance),toppedUpBalance:Pe(t.toppedUpBalance)}}function wt(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&ue(s,"object"),{percent:Pe(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function tn(t,s){return{...kt(t,s),rolling:wt(t.rolling,s+".rolling"),weekly:wt(t.weekly,s+".weekly"),monthly:wt(t.monthly,s+".monthly")}}function oa(t,s){return{...kt(t,s),label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:Pe(t.remaining),maxBudget:je(t.maxBudget),spend:je(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const an=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),nn=new Set(["off","loading","ok","partial","stale","error"]),xt=["antigravity","claude","codex","kimi","xai","workbuddy"],la={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function sn(t,s){ge(t,s);const o=(i,r="")=>typeof i=="string"?i:r,a=i=>je(i),n=i=>i!==null&&typeof i=="object"&&!Array.isArray(i)?{id:o(i.id),label:o(i.label),...a(i.percent)===null?{}:{percent:a(i.percent)},resetsAt:o(i.resetsAt),periodHours:a(i.periodHours),scope:o(i.scope)}:null,l=i=>i!==null&&typeof i=="object"&&!Array.isArray(i)?{unit:o(i.unit,"credits"),used:a(i.used),remaining:a(i.remaining),limit:a(i.limit),fetchedAt:o(i.fetchedAt),packages:Array.isArray(i.packages)?i.packages.filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)).map(r=>({id:o(r.id),label:o(r.label),used:a(r.used),remaining:a(r.remaining),limit:a(r.limit),startsAt:o(r.startsAt),resetsAt:o(r.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:nn.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:a(t.fetchedAt)??0,attemptedAt:a(t.attemptedAt)??0,serverVersion:o(t.serverVersion),keyConfigured:t.keyConfigured===!0,keySource:o(t.keySource,"none"),accounts:Array.isArray(t.accounts)?t.accounts.filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).slice(0,16).map(i=>({id:o(i.id),provider:o(i.provider,"unknown"),label:o(i.label,"unknown"),status:an.has(i.status)?i.status:"unknown",message:o(i.message),plan:o(i.plan),windows:Array.isArray(i.windows)?i.windows.map(n).filter(Boolean):[],credits:l(i.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(i=>typeof i=="string").slice(0,32):[]}}function on(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};if(t.providers!==null&&typeof t.providers=="object"&&!Array.isArray(t.providers))for(const[o,a]of Object.entries(t.providers)){if(a===null||typeof a!="object"||Array.isArray(a))continue;const n={},l={};if(a.windows!==null&&typeof a.windows=="object"&&!Array.isArray(a.windows))for(const[i,r]of Object.entries(a.windows))r===null||typeof r!="object"||Array.isArray(r)||(n[i]={...Ie(r,["percent","localTokens","localCost","sampleCount"],Pe),...Ie(r,["sampleAt","per1Tokens","per1Cost","fullTokens","fullCost"],je),resetsAt:typeof r.resetsAt=="string"?r.resetsAt:"",method:r.method==="sample"||r.method==="live"?r.method:"none",confidence:r.confidence==="high"||r.confidence==="low"?r.confidence:null});if(a.intervals!==null&&typeof a.intervals=="object"&&!Array.isArray(a.intervals))for(const[i,r]of Object.entries(a.intervals))Array.isArray(r)&&(l[i]=r.filter(u=>u!==null&&typeof u=="object"&&!Array.isArray(u)).map(u=>Ie(u,["t0","t1","tokens","cost","pct","per1Tokens","per1Cost"],Pe)));s[o]={windows:n,intervals:l}}return{generatedAt:Pe(t.generatedAt),providers:s}}function ia(t,s){return ge(t,s),{today:he(t.today,s+".today"),month:he(t.month,s+".month"),total:he(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?$a:en(t.balance,s+".balance"),goQuota:t.goQuota==null?Xa:tn(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?sa():oa(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,a)=>oa(o,s+".customBalances["+a+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,a)=>sn(o,s+".gatewayQuotas["+a+"]")):[],customVarStatus:t.customVarStatus!==null&&typeof t.customVarStatus=="object"&&!Array.isArray(t.customVarStatus)?Object.fromEntries(Object.entries(t.customVarStatus).filter(([,o])=>o!==null&&typeof o=="object").map(([o,a])=>[o,{configured:a.configured===!0,source:typeof a.source=="string"?a.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:on(t.planStats),history:Array.isArray(t.history)?t.history.map((o,a)=>he(o,s+".history["+a+"]")):[],externalUsage:t.externalUsage&&Array.isArray(t.externalUsage.sources)?{fetchedAt:Number(t.externalUsage.fetchedAt)||0,stale:t.externalUsage.stale===!0,sources:t.externalUsage.sources.map(o=>({source:String(o.source),today:he(o.today,s+".external.today"),month:he(o.month,s+".external.month"),total:he(o.total,s+".external.total"),history:(o.history??[]).map(a=>he(a,s+".external.history"))})),combined:Object.fromEntries(["today","month","total","history"].map(o=>[o,o==="history"?(t.externalUsage.combined.history??[]).map(a=>he(a,s+".external.history")):he(t.externalUsage.combined[o],s+".external."+o)]))}:null,config:Za(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:{...Ee(t.meta?.locale)?{locale:Ee(t.meta.locale)}:{},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 ln(t,s){ge(t,s);const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=ia(t.state,s+".state")),o}function le(t){return{parse:t}}const vt=le(ia),rn=le(t=>ge(t,"patch")),cn=le(ln),Nt=le(t=>re(t,"provider")),dn=le(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&ue("index","0-7 integer"),t}),un=le(t=>re(t,"date")),mn=le(t=>ge(t,"day")),pn=le(t=>(Number.isFinite(Number(t))||ue("limit","number"),Number(t))),ra=le(t=>re(t,"sort")),fn=le(t=>ge(t,"topSessions")),ca=le(t=>re(t,"target")),bn=le(t=>re(t,"value")),ve=(t,s)=>({mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:s,create:()=>s}),ce=(t,s,o,a=!1)=>({name:t,wire:t,source:"json",codec:ve(s,o),...a?{acceptsUndefined:!0}:{}}),gn={package:"dsh-cost-meter",descriptors:[{method:"getState",result:ve("CostState",vt)},{method:"updateConfig",parameters:[ce("patch","ConfigPatch",rn)],result:ve("CostState",vt)},{method:"fetchPrices"},{method:"refreshBalance"},{method:"refreshGoQuota"},{method:"refreshCustomBalance",parameters:[ce("index","CustomBalanceIndex",dn,!0)]},{method:"refreshCodingPlan",parameters:[ce("provider","CodingPlanProvider",Nt)]},{method:"loginCodingPlan",parameters:[ce("provider","CodingPlanProvider",Nt)]},{method:"refreshGatewayQuota",parameters:[ce("sourceId","GatewayQuotaSourceId",le(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&ue("sourceId","gateway source id"),t}),!0)]},{method:"resetHistory",result:ve("CostState",vt)},{method:"importLegacyHistory"},{method:"getDaySessions",parameters:[ce("date","DayKey",un)],result:ve("DayRecord",mn)},{method:"getSessionCost",parameters:[ce("sessionId","SessionId",Nt)],result:ve("SessionCost",le(t=>({own:gt(t.own,"own"),subagents:gt(t.subagents,"subagents"),found:Me(t.found,"found"),subagentCount:ae(t.subagentCount,"subagentCount")})))},{id:"dsh-cost-meter#costMeter/getTurnCost",service:"costMeter",namespace:"costMeter",method:"getTurnCost",invocation:{kind:"direct"},parameters:[ce("sessionId","SessionId",le(t=>re(t,"sessionId"))),...["startSeq","endSeq"].map(t=>ce(t,"TurnSeq",le(s=>((!Number.isSafeInteger(s)||s<0)&&ue(t,"nonnegative integer"),s))))],result:ve("TurnCost",le(t=>({found:Me(t.found,"found"),cost:ae(t.cost,"cost"),apiCost:ae(t.apiCost,"apiCost"),rows:na(t.rows),calls:(Array.isArray(t.calls)?t.calls:ue("calls","array")).map(s=>({kind:re(s.kind,"kind"),provider:re(s.provider,"provider"),model:re(s.model,"model"),atMs:ae(s.atMs,"atMs"),cost:ae(s.cost,"cost"),apiCost:ae(s.apiCost,"apiCost"),plan:Me(s.plan,"plan"),priced:Me(s.priced,"priced"),longContext:Me(s.longContext,"longContext"),rows:na(s.rows)}))})))},{method:"getTopSessions",parameters:[ce("limit","SessionLimit",pn),ce("sort","SessionSort",ra,!0),ce("dir","SessionSortDir",ra,!0)],result:ve("TopSessions",fn)},{method:"setCredential",parameters:[ce("target","CredentialTarget",ca),ce("value","CredentialValue",bn)]},{method:"clearCredential",parameters:[ce("target","CredentialTarget",ca)]}].map(t=>({id:"dsh-cost-meter#costMeter/"+t.method,service:"costMeter",namespace:"costMeter",invocation:{kind:"direct"},parameters:[],result:ve("FetchPricesResult",cn),...t}))};function hn(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 Ue(t){if(t===null||typeof t!="object")return;const s=i=>{const r=t[i];return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0},o=s("cacheMiss")??s("input")??0,n={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},l=s("reasoning");return l!==void 0&&(n.reasoning=l),s("cacheWrite")!==void 0&&(n.cacheWrite=s("cacheWrite")),n}function yn(t){const s=Ue(t);if(s===void 0)return null;t.billingMode==="utc-peak"&&(s.billingMode="utc-peak");for(const o of["offPeak","peak","legacyBase"]){const a=Ue(t[o]);a!==void 0&&(s[o]=a)}return Number.isFinite(t.longContext?.aboveInputTokens)&&t.longContext.aboveInputTokens>0&&(s.longContext={...Ue(t.longContext),aboveInputTokens:t.longContext.aboveInputTokens}),Array.isArray(t.rateHistory)&&(s.rateHistory=t.rateHistory.slice(0,16).map(o=>{const a={...Ue(o),before:o.before};for(const n of["offPeak","peak"]){const l=Ue(o[n]);l!==void 0&&(a[n]=l)}return a})),s}function tt(t,s=Date.now()){if(!t||!Number.isFinite(s)||!Array.isArray(t.rateHistory))return t;let o=null,a=1/0;for(const i of t.rateHistory){const r=Date.parse(i.before);s<r&&r<a&&(o=i,a=r)}if(!o)return t;const{before:n,...l}=o;return{...t,...l}}const St=Date.parse("2026-08-22T16:00:00Z");function da(t){if(!Number.isFinite(t)||t<St)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const a=o===6?s:s-1;return{start:Math.max(a*864e5-8*36e5,St),end:(a+2)*864e5-8*36e5}}function ua(t,s){if(!Number.isFinite(t)||t<St||!Array.isArray(s))return null;const o=Math.floor((t+8*36e5)/864e5);return s.includes(new Date(o*864e5).toISOString().slice(0,10))?{start:o*864e5-8*36e5,end:(o+1)*864e5-8*36e5}:null}const kn=(t,s)=>ua(t,s)??da(t);function at(t,s,o,a){if(!Array.isArray(o)||o.length===0||kn(t,a)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(l=>{const i=Number(l.start),r=Number(l.end);return!Number.isFinite(i)||!Number.isFinite(r)?!1:i<r?n>=i&&n<r:n>=i||n<r})}const wn=Date.parse("2026-08-16T16:00:00Z");function ma(t,s,o){const a=tt(t,s)??{cacheHit:0,cacheMiss:0,output:0},n=i=>({cacheHit:i.cacheHit,cacheMiss:i.cacheMiss,output:i.output,reasoning:i.reasoning??0,...i.cacheWrite===void 0?{}:{cacheWrite:i.cacheWrite},...i.longContext===void 0?{}:{longContext:i.longContext}});if(a.billingMode==="utc-peak"){if(o?.enabled!==!0||!Number.isFinite(s))return n(a);const i=new Date(s),r=i.getUTCDay(),u=i.getUTCHours(),d=r>0&&r<6&&(u>=1&&u<4||u>=6&&u<10);return n((d?a.peak:a.offPeak)??a)}if(Number.isFinite(s)&&s<wn){const i=a.legacyBase;return n(i===void 0?a:i)}if(o?.enabled!==!0)return n(a);const l=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(at(s,l,o.windows,o.holidays)){const i=a.peak;return n(i===void 0?a:i)}if(l!==void 0&&s>=l){const i=a.offPeak;return n(i===void 0?a:i)}return n(a)}function pa(t,s){const o=Math.max(0,Number(t.input)||0),a=Math.max(0,Number(t.output)||0),n=Math.max(0,Number(t.cacheRead)||0),l=Math.max(0,Number(t.cacheWrite)||0),i=Math.max(0,Number(t.reasoning)||0);return s.longContext&&o+n+l>s.longContext.aboveInputTokens&&(s=s.longContext),(o*s.cacheMiss+a*s.output+n*s.cacheHit+l*(s.cacheWrite??s.cacheHit)+i*(s.reasoning??0))/1e6}function fa(t,s,o){const a=Number(t);if(!Number.isFinite(a)||a<0||a===0)return 0;if(s!=="CNY")return a;const n=Number(o);return!Number.isFinite(n)||n<=0?a:a/n}function ie(t,s){const o=t?.barDirections,a=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return a;const n=o[s];return n==="remaining"||n==="used"?n:a}function fe(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),a=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:a,label:a}}const ba=(t,s)=>t.toFixed(s).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1");function me(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",a=Number(s?.decimals),n=Math.max(0,Math.min(10,Number.isFinite(a)?Math.floor(a):2));let l=n;return t>0&&t<Math.pow(10,-n)&&(l=n+2),o+ba(t,l)}function Y(t,s){const o=Number(s?.exchangeRate),a=t*(Number.isFinite(o)&&o>0?o:1);return me(a,s)}function q(t){const s=Math.max(0,Number(t)||0),o=a=>a>=100?String(Math.round(a)):String(Math.round(a*10)/10);return s<1e3?String(Math.round(s)):s>=999500?o(s/1e6)+"M":s<1e6?o(s/1e3)+"K":o(s/1e6)+"M"}function Ct(t){return String(t??"").normalize("NFKC").toLowerCase().replace(/[((]\s*(?:go|zen)\s*[))]/g," ").trim()}function ye(t){return Ct(t).replace(/[^\p{L}\p{N}]+/gu,"")}function xn(t){return Ct(t).replace(/[-_./:@](?:\d{4}-?\d{2}-?\d{2}|v\d+(?:\.\d+)*|\d+k|latest)$/,"")}function At(t,s,o=t){if(typeof t!="string"||t.length===0)return null;const a=Array.isArray(s)?s.filter(i=>typeof i=="string"&&i.length>0):[],n=a.find(i=>i===o);if(n!==void 0)return n;let l=t.normalize("NFKC").trim();if(/[:((]\s*(?:free|online)\b/i.test(l))return null;for(;;){const i=ye(l);if(i.length===0)return null;const r=a.filter(d=>ye(d)===i);if(r.length>0)return r.length===1?r[0]:null;const u=xn(l);if(u===l.toLowerCase())return null;l=u}}const Mt=new Set(["openrouter","opencode-zen","opencode-go","zen","opencode"]),nt={openai:/^(?:gpt|o\d|codex)/i,anthropic:/^claude/i,google:/^gemini/i,deepseek:/^deepseek/i,moonshot:/^kimi/i,"z-ai":/^glm/i,xai:/^grok/i,alibaba:/^qwen/i,minimax:/^minimax/i,tencent:/^(?:hunyuan|hy\d)/i,xiaomi:/^mimo/i,upstage:/^solar/i,nvidia:/^nemotron/i,mistral:/^mistral/i,meta:/^(?:muse|llama)/i,meituan:/^longcat/i};function Pt(t){return["deepseek-peak","utc-peak"].includes(t?.billingMode)?t.billingMode:"flat"}function He(t,s,o,a,n){if(typeof t!="string")return null;if(Object.hasOwn(s,t))return t;if(a!=="auto")return null;let l=t.normalize("NFKC").trim().replace(/^models\/(?=gemini)/i,"google/");const i=l.search(/[/:]/);if(i>0){const r=l.slice(0,i).trim().toLowerCase(),u=l.slice(i+1).trim();if(Object.hasOwn(nt,r)&&(r===o||(o==="opencode-zen"||o==="opencode-go")&&(nt[r].test(u)||At(u,Object.keys(r==="deepseek"?n?.models??{}:n?.providers?.[r]?.models??{}))!==null)))l=u;else if(Object.hasOwn(nt,r))return null}return At(l,Object.keys(s),t)}const vn=new Set(["local","lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),Nn=["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 Sn(t,s){if(typeof t=="string"&&vn.has(t))return!0;const o=typeof s=="string"?Ct(s):"";return Nn.some(a=>o.startsWith(a))}function Cn(t,s,o,a){if(t!=="deepseek"&&!t.includes("deepseek")&&typeof s=="string"&&s.length>0&&s!=="__local__"&&!s.includes(":")){const n=o.models??{},l=Object.hasOwn(n,s)?s:a==="auto"?At(s,Object.keys(n)):null;if(l!==null&&n[l]?.unpriced!==!0)return{entry:n[l],priced:!0,billingMode:"deepseek-peak",matched:!0}}return null}function An(t,s,o){const a=o?.prices??{},n=o?.priceMatch==="exact"?"exact":"auto",l=o?.priceOverrides&&typeof o.priceOverrides=="object"?o.priceOverrides:{};let i=String(t??"").trim().toLowerCase();i.startsWith("llm-")&&(i=i.slice(4)),i===""&&(i="deepseek");let r=i,u=s;const d=l[i+":"+s];if(d==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof d=="string"&&d.length>0){const f=d.indexOf(":");if(f>0&&d.slice(f+1).length>0?(r=d.slice(0,f).trim().toLowerCase(),u=d.slice(f+1)):u=d,r==="deepseek"&&u==="__default__")return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:a.default?.unpriced!==!0,billingMode:"deepseek-peak",matched:!1}}if(["zen","opencode"].includes(r)){const f=He(u,a.providers?.[r]?.models??{},"opencode-go",n,a);f===null?r="opencode-go":u=f}if(Sn(r,u))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(r==="openrouter"){const f=a.providers?.openrouter?.models??{},b=Object.hasOwn(f,u)?f[u]:null;return{entry:b,priced:b!==null&&b.unpriced!==!0,billingMode:"flat",matched:b!==null}}if(r==="deepseek"||r.includes("deepseek")){const f=a.models??{},b=He(u,f,"deepseek",n,a);if(b!==null)return f[b]?.unpriced===!0?{entry:null,priced:!1,billingMode:"flat",matched:!0}:{entry:f[b],priced:!0,billingMode:"deepseek-peak",matched:!0};if(n==="auto"){let g=null,h=-1,x=!1,S="flat";for(const[T,N]of Object.entries(a.providers??{})){if(Mt.has(T))continue;const m=N?.models??{},v=He(u,m,T,n,a);if(v===null)continue;const y=+(v===u||ye(v)===ye(u));y>h?(g=m[v],h=y,x=!1,S=Pt(m[v])):y===h&&(x=!0)}if(x)return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(g!==null)return{entry:g,priced:g.unpriced!==!0,billingMode:S,matched:!0}}return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:a.default?.unpriced!==!0,billingMode:"deepseek-peak",matched:!1}}const c=a.providers?.[r]?.models??{},p=He(u,c,r,n,a);if(p!==null)return{entry:c[p],priced:c[p]?.unpriced!==!0,billingMode:Pt(c[p]),matched:!0};if(Mt.has(r))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(Object.hasOwn(nt,r))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(n==="auto"){let f=null,b=-1,g=!1,h="flat";for(const[x,S]of[["deepseek",{models:a.models??{}}],...Object.entries(a.providers??{})]){if(x===r||Mt.has(x))continue;const T=S?.models??{},N=He(u,T,x,n,a);if(N===null)continue;const m=+(N===u||ye(N)===ye(u));m>b?(f=T[N],b=m,g=!1,h=x==="deepseek"?"deepseek-peak":Pt(T[N])):m===b&&(g=!0)}if(g)return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(f!==null)return{entry:f,priced:f.unpriced!==!0,billingMode:h,matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function Tt(t,s,o){let a=An(t,s,o);if(!a.priced){const n=String(t??"").trim().toLowerCase().replace(/^llm-/,"")||"deepseek";a=Cn(n,o?.priceOverrides?.[n+":"+s],o?.prices??{},o?.priceMatch==="exact"?"exact":"auto")??a}return a.priced&&o?.prices?.currency==="CNY"&&a.entry?.cny?{...a,entry:a.entry.cny,currency:"CNY"}:{...a,currency:a.priced&&a.billingMode==="deepseek-peak"&&o?.prices?.currency==="CNY"?"CNY":"USD"}}function Mn(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,a=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&a===0}function st(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:ha(t,s).total}function Qe(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:Qe(t)}const Pn={go:["go","zen","opencode","opencode-go"],qwen:["qwen","qwen-tokenplan","qianwen-tokenplan","qwen-token-plan","qianwen-token-plan"],scnet:["scnet","scnet-tokenplan","scnet-token-plan"],mimo:["mimo","xiaomimimo","mimo-token-plan","xiaomi-token-plan","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","xiaomi-token-plan-ams"]},ga=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","mimo","go"];function Tn(t){const s=String(t??"").trim().toLowerCase().replace(/^llm-/,"");if(s.length===0)return null;for(const[o,a]of Object.entries(Pn))if(a.includes(s))return o;return ga.includes(s)?s:null}function On(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const a of ga)a!=="go"&&o[a]?.enabled===!0&&s.add(a);return t?.goQuota?.enabled===!0&&s.add("go"),s}const Dn=new Set(["grok-4.5","glm-5.3","glm-5.3-flash","glm-5.2","glm-5.1","gpt-5.6-luna","kimi-k3","kimi-k2.7-code","kimi-k2.6","mimo-v2.6-flash","mimo-v2.6-pro","mimo-v2.5","mimo-v2.5-pro","minimax-m3","minimax-m2.7","qwen3.8-max","qwen3.7-max","qwen3.7-plus","qwen3.6-plus","hy3","longcat-2.0","muse-spark-1.2-contributor"].map(ye));function Bn(t,s,o){const a=String(t??"").trim().toLowerCase();if(a.length>0&&a!=="deepseek"&&!a.includes("deepseek"))return!1;const n=ye(s);if(n.length===0||!Dn.has(n))return!1;const l=o?.prices,i=l?.models??{};for(const r of Object.keys(i))if(ye(r)===n)return!1;for(const r of Object.keys(l?.providers?.["opencode-go"]?.models??{}))if(ye(r)===n)return!0;return!1}function Fe(t,s,o){let a=Tn(t);a===null&&Bn(t,s,o)&&(a="go");const n=o?.planBilling?.models;if(n!==null&&typeof n=="object"){const i=n[t+":"+s];if(i==="plan"||i==="api")return i;if(a!==null){const r=n[a+":"+s];if(r==="plan"||r==="api")return r}}if(a===null)return"api";const l=o?.planBilling?.providers?.[a];return l==="plan"||l==="api"?l:On(o).has(a)?"plan":"api"}function ha(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows,holidays:s.peakHolidays},a=Date.now(),n=t.byProviderModel??t.byModel??{};let l=0,i=0;for(const p of Object.keys(n)){const f=p.indexOf(":"),b=f>0?p.slice(0,f):"deepseek",g=f>0?p.slice(f+1):p,h=Tt(b,g,s);if(h.priced){const x=pa(n[p],ma(yn(h.entry),a,{...o,enabled:["deepseek-peak","utc-peak"].includes(h.billingMode)&&o.enabled})),S=fa(x,h.currency,s.exchangeRate);l+=S,Fe(b,g,s)==="api"&&(i+=S)}}const r={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const p of Object.keys(n))r.input+=n[p].input??0,r.output+=n[p].output??0,r.cacheRead+=n[p].cacheRead??0,r.cacheWrite+=n[p].cacheWrite??0,r.reasoning+=n[p].reasoning??0;const u={input:Math.max(0,(t.input??0)-r.input),output:Math.max(0,(t.output??0)-r.output),cacheRead:Math.max(0,(t.cacheRead??0)-r.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-r.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-r.reasoning)},d=pa(u,ma(hn("default",s.prices),a,o)),c=fa(d,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return l+=c,i+=c,{total:l,api:i}}function ya(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const a of Object.keys(o)){const n=a.indexOf(":"),l=n>0?a.slice(0,n):"deepseek",i=n>0?a.slice(n+1):a;if(Fe(l,i,s)==="plan")return!0}return!1}function Ot(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function ka(t,s){if(t?.apiCost!==void 0)return Qe(t);if(!ya(t,s))return st(t,s);let o=0;for(const[a,n]of Object.entries(t.byProviderModel??{})){if(!Number.isFinite(n.cost))return ha(t,s).api;const l=a.indexOf(":");Fe(a.slice(0,l),a.slice(l+1),s)==="plan"&&(o+=n.cost)}return Math.max(0,st(t,s)-o)}function Dt(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),a=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(a>0?":"+String(a).padStart(2,"0"):"")}function Rn(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const a=-new Date().getTimezoneOffset();if(a===o)return null;const n=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:n?n+" ("+Dt(o)+")":Dt(o),browserLabel:Dt(a)}}function Ln(t,s=o=>o){let o=s(t);const a=new Set;return{getSnapshot:()=>o,subscribe:n=>(a.add(n),()=>{a.delete(n)}),set:n=>{if(n=s(n),n!==o){o=n;for(const l of[...a])l()}}}}const{createElement:e,Fragment:L,useState:B,useEffect:ee,useRef:Ne}=Be;function De({target:t,configured:s,source:o,t:a,api:n,placeholder:l,disabled:i}){const[r,u]=B(""),[d,c]=B(!1),[p,f]=B(!1),[b,g]=B(null),h=Ne(!1),x=i===!0||p,S=async()=>{const m=r.trim();if(!(m.length===0||x||h.current)){h.current=!0,f(!0),g(null);try{const v=await n.setCredential(t,m);u(""),c(!1),g({kind:"ok",text:v?.message??a("credentialSave")})}catch(v){g({kind:"err",text:String(v?.message??v)})}finally{h.current=!1,f(!1)}}},T=async()=>{if(!(x||h.current)){h.current=!0,f(!0),g(null);try{const m=await n.clearCredential(t);u(""),c(!1),g({kind:"ok",text:m?.message??a("credentialClear")})}catch(m){g({kind:"err",text:String(m?.message??m)})}finally{h.current=!1,f(!1)}}},N=()=>{u(""),c(!1)};return e("div",{className:"cm-field"},d?e("form",{className:"cm-field",autoComplete:"off",onSubmit:m=>{m.preventDefault(),S()}},e("input",{className:"cm-input",type:"password",name:"cm-credential-"+t,autoFocus:!0,value:r,placeholder:typeof l=="string"?l:"",disabled:x,autoComplete:"new-password","data-lpignore":"true","data-1p-ignore":"true","data-bwignore":"true","aria-label":a("credentialInputHint"),onChange:m=>u(m.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",type:"submit",disabled:x||r.trim().length===0},a(p?"credentialSaving":"credentialSave")),e("button",{className:"cm-btn small",type:"button",onClick:N,disabled:p},a("cancel")))):e("button",{className:"cm-btn small",type:"button",onClick:()=>c(!0),disabled:x},a("credentialEdit")),s===!0?e("button",{className:"cm-btn small",type:"button",onClick:T,disabled:x},a("credentialClear")):null,e("span",{className:"cm-hint"},s===!0?a("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):a("credentialNotConfigured")),e("span",{className:"cm-hint"},a("credentialInputHint")),Yt(b))}function En({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 ot({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 wa(t,s){const o=Ne(!1),a=Ne(""),n=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(l=>String(l??0)).join("|"):"";ee(()=>{if(!o.current){o.current=!0,a.current=n;return}if(n===""||n===a.current)return;a.current=n;const l=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(l)},[n])}function qn(t,s,o,a){const n=s?s.own:t;if(!o||!s?.subagentCount)return n;const l=s.subagents,i={...n};for(const r of["input","output","cacheRead","cacheWrite","reasoning","calls","cost"])i[r]=(n?.[r]??0)+(l?.[r]??0);i.apiCost=ka(n,a)+Qe(l);for(const r of["byModel","byProviderModel"]){i[r]={...n?.[r]};for(const[u,d]of Object.entries(l?.[r]??{})){const c={...i[r][u]};c.apiCost=Qe(c)+Qe(d);for(const p of["input","output","cacheRead","cacheWrite","reasoning","calls","cost"])c[p]=(c[p]??0)+(d[p]??0);i[r][u]=c}}return i}function xa(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?.(r=>r)?.state,a=o?.config,[n,l]=B(null);wa(t,s),ee(()=>{if(!t.sessionId||!t.api?.getSessionCost)return;let r=!0,u=!1;const d=async()=>{if(!u){u=!0;try{const p=await t.api.getSessionCost(t.sessionId);r&&l({id:t.sessionId,include:a?.includeSubagentCost===!0,value:p})}catch{}finally{u=!1}}};d();const c=a?.includeSubagentCost===!0?setInterval(d,1e4):null;return()=>{r=!1,c!==null&&clearInterval(c)}},[t.sessionId,o?.meta?.now,s,a?.includeSubagentCost]);const i=n&&n.id===t.sessionId&&n.include===(a?.includeSubagentCost===!0)?n.value:null;return{usage:qn(s,i,a?.includeSubagentCost===!0,a),config:a}}function va(t,s){let o=0,a=st(t,s);if(s.showTotalWithPlan!==!0&&(t.apiCost!==void 0||ya(t,s))){const n={total:st(t,s),api:ka(t,s)};o=Math.max(0,n.total-n.api),o>0&&(a=n.api)}return{cost:a,planPart:o}}function Na(t,s){return Object.entries(t?.byProviderModel??{}).filter(([,o])=>o.input||o.output||o.cacheRead||o.cacheWrite||o.reasoning).map(([o,a])=>o+" "+Y(a.cost,s)).join("; ")}function In(t){const s=t.useCost?.(h=>h)?.state?.config,[o,a]=B(null),[n,l]=B(""),i=t.turn?.start?.seq,r=t.turn?.end?.seq,u=t.sessionId,d=JSON.stringify([s?.prices,s?.priceOverrides,s?.priceMatch,s?.planBilling,s?.codingPlans,s?.goQuota?.enabled,s?.peakEnabled,s?.peakEffectiveAt,s?.peakWindows,s?.peakHolidays,s?.exchangeRate]);if(ee(()=>{let h=!0;if(a(null),l(""),!(s?.hideTurnCost||!u||i==null||r==null))return t.api.getTurnCost(u,i,r).then(x=>{h&&a(x)},x=>{h&&l(String(x.message??x))}),()=>{h=!1}},[u,i,r,d,s?.hideTurnCost]),!s||s.hideTurnCost||i==null||r==null)return null;const c=_(s)==="en",p=c?{input:"Input",output:"Output",cacheRead:"Cache read",cacheWrite:"Cache write",reasoning:"Reasoning"}:{input:"输入",output:"输出",cacheRead:"缓存读取",cacheWrite:"缓存写入",reasoning:"推理"},f=h=>Y(h,{...s,decimals:Math.max(8,s.decimals??2)}),b=c?{model:"Model call",compaction:"Context compaction",search:"Native search"}:{model:"模型调用",compaction:"上下文压缩",search:"原生搜索"},g=(h,x)=>e("div",{key:x,style:{marginBottom:4,overflowWrap:"anywhere"}},h.provider+":"+h.model+" · "+p[h.bucket]+(h.plan?" (Plan)":"")+": "+h.tokens.toLocaleString()+" × "+(h.priced?f(h.rate):"?")+" / 1,000,000 ≈ "+(h.priced?f(h.cost):"?"),h.priced?h.bucket==="reasoning"&&h.rate===0?c?" (no separate charge)":"(不单独收费)":"":c?" (price unavailable)":"(未配置价格)");return e("details",{className:"cm-note",style:{fontSize:12,marginTop:6}},e("summary",{style:{cursor:"pointer"}},c?"Turn cost":"本轮费用",o?.found?" ≈ "+f(s.showTotalWithPlan?o.cost:o.apiCost)+(o.rows.some(h=>!h.priced)?c?" + unpriced usage":" + 未定价用量":""):n?" ⚠":""),n?e("div",{role:"alert"},n):o?o.found?e(L,null,e("p",null,c?"Estimated from recorded usage and configured prices; rates per 1M tokens.":"按已记录用量和配置价格估算;单价单位为每百万 Token。"),e("p",null,"API ≈ "+f(o.apiCost)+" · Plan ≈ "+f(o.cost-o.apiCost)+(c?" (equivalent)":"(等值)")),o.rows.map(g),e("details",null,e("summary",{style:{cursor:"pointer"}},(c?"Individual calls":"逐次调用明细")+" ("+o.calls.length+")"),o.calls.map((h,x)=>e("details",{key:x,style:{margin:"6px 0"}},e("summary",{style:{cursor:"pointer",overflowWrap:"anywhere"}},"#"+(x+1)+" "+b[h.kind]+" · "+h.provider+":"+h.model+" · "+new Date(h.atMs).toLocaleTimeString()+" · "+(h.plan?"Plan ":"API ")+(h.priced?"≈ "+f(h.cost):c?"price unavailable":"未配置价格")+(h.longContext?c?" · long context":" · 长上下文价格":"")),h.rows.map(g))))):c?"Complete usage records unavailable":"没有完整用量记录":c?"Loading…":"加载中…")}function jn(t){const{usage:s,config:o}=xa(t);if(!s||!o||Ot(s)+(s?.output??0)===0)return null;const a=G(_(o)),{cost:n,planPart:l}=va(s,o),i=[a("sessionCostTitle"),a("sessionDetailTokens",{input:q(s?.input??0),cache:q((s?.cacheRead??0)+(s?.cacheWrite??0)),output:q(s?.output??0)}),a("sessionDetailCache",{read:q(s?.cacheRead??0),write:q(s?.cacheWrite??0)}),a("cost",{amount:Y(n,o)}),...l>0?[a("sessionDetailPlan",{amount:Y(l,o)})]:[],Na(s,o)].filter(Boolean).join("; ");return e(X,{label:i,side:"top",delayMs:500},e("div",{className:"cm-chip"},l>0?a("costChipPlan",{amount:Y(n,o)}):a("cost",{amount:Y(n,o)})))}function Un(t){const{usage:s,config:o}=xa(t);if(!s||!o)return null;const a=s.input??0,n=(s.cacheRead??0)+(s.cacheWrite??0),l=s.output??0;if(a+n+l===0)return null;const i=G(_(o)),{cost:r,planPart:u}=va(s,o),d=Ot(s)>0?((s.cacheRead??0)/Ot(s)*100).toFixed(1)+"%":"—";return e("div",{className:"cm-root",title:Na(s,o)},i(u>0?"sessionLineSplit":"sessionLine",{amount:Y(r,o),planAmount:Y(u,o),hitRate:d,input:q(a),cache:q(n),output:q(l)}))}const Hn={USD:"$",CNY:"¥",EUR:"€"};function Se(t,s,o){const a=typeof o=="string"?o.toUpperCase():"",n=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return me(t,{symbol:Hn[a]??n,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function Sa(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const a=Number(s?.maxBudget);return Number.isFinite(a)&&a>0?a:null}function Qn(t){const s=t.today,o=s?.byProviderModel;if(o===null||typeof o!="object"||Object.keys(o).length===0)return Number(s?.cost)||0;let a=0;for(const[n,l]of Object.entries(o)){const i=n.indexOf(":");let r=i>=0?n.slice(0,i):n;r.startsWith("llm-")&&(r=r.slice(4)),/^deepseek(?:-official|-account)?$/.test(r)&&(a+=Number(l?.cost)||0)}return a}function Ca(t,s,o,a,n=null){const l=o==="official"?Qn(t):Number(t.today?.cost)||0,i=o==="custom"?_e(s,a,n):t.balance?.currency;if(i==="USD")return l;if(i==="CREDITS")return 0;const r=Number(s?.exchangeRate);return l*(Number.isFinite(r)&&r>0?r:1)}function Aa({remaining:t,spend:s,todayUsed:o,cap:a}){if(a===null||a<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const n=Math.max(0,Number(t)||0),l=Math.max(0,Number(s)||0),i=Math.max(0,Math.min(l,Number(o)||0)),r=Math.max(0,l-i),u=Math.max(0,Math.min(100,n/a*100)),d=Math.max(0,Math.min(100-u,i/a*100)),c=Math.max(0,Math.min(100-u-d,r/a*100));return{remainingPct:u,todayPct:d,spentPct:c,hasCap:!0,pastSpend:r,today:i}}function Bt(t,s,o=null,a=null){const n=o??t.customBalance,l=Sa(_e(s,n,a)==="CREDITS"?null:s,n),i=Number(n?.remaining)||0,r=Number(n?.spend)||0,u=Ca(t,s,"custom",n,a);return{cap:l,...Aa({remaining:i,spend:r,todayUsed:u,cap:l})}}function Fn(t,s){const o=t.balance,a=Sa(s,null),n=Number(o?.totalBalance)||0,l=Ca(t,s,"official",null),i=a!==null?Math.max(0,a-n):0;return{cap:a,...Aa({remaining:n,spend:i,todayUsed:l,cap:a})}}function Rt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:a,todayPct:n,spentPct:l}=s,i=[];a>0&&i.push(e("div",{className:"cm-bbox-fill",style:{width:a+"%"}})),n>0&&i.push(e("div",{className:"cm-bbox-seg-today",style:{width:n+"%"}})),l>0&&i.push(e("div",{className:"cm-bbox-seg-spent",style:{width:l+"%"}})),i.length===0&&i.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const r=o==="used"?[...i].reverse():i;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...r)}function Ma(t,s,o,a,n){const l=[t("balanceBarRemaining",{amount:a})];return o.today>0&&l.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&l.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),n!==null&&n>0&&l.push(t("balanceBudgetCapLabel")+": "+s(n)),l.join(" · ")}function Te(t){const[s,o]=B(!1),[a,n]=B(null);return{busy:s,err:a,run:()=>{s||typeof t!="function"||(o(!0),n(null),Promise.resolve().then(t).catch(i=>{n(i?.message??String(i))}).finally(()=>{o(!1)}))}}}const be=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function ke(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const _n="https://platform.deepseek.com/usage";function Pa(t){return e("a",{className:"cm-bal-link",href:_n,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},e("svg",{width:14,height:14,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},e("path",{d:"M8 4H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4M11 3h6v6M9 11l8-8"})))}function Wn(t){const{state:s,wide:o,api:a}=t,n=s.balance,l=G(_(s.config)),i=Te(a?()=>a.refreshBalance():null);if(!n||n.status==="off")return null;if(n.status==="error")return e(X,{label:[l("balanceQueryFailed",{message:n.message||l("unknownError")}),...ke(l,i)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(i.busy?" busy":""),...be(i.busy,i.run)},o?e(L,null,l("balance")," ",e("span",{className:"cm-num"},l("queryFailed"))):"⚠"));const r=[l("balanceTitle"),l("totalBalance",{amount:Se(n.totalBalance,s.config,n.currency)}),l("grantedToppedUp",{granted:Se(n.grantedBalance,s.config,n.currency),toppedUp:Se(n.toppedUpBalance,s.config,n.currency)}),l("updatedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ke(l,i)].join("; ");return e(X,{label:r,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(i.busy?" busy":""),...be(i.busy,i.run)},o?e(L,null,e("span",{className:"cm-balance-name"},l("balance"),Pa(l)),e("span",{className:"cm-num cm-bal-amt"},Se(n.totalBalance,s.config,n.currency)),s.reconcile?.ok===!1?" ⚠":""):e(ot,{size:16})))}function zn(t){const{state:s,wide:o,api:a}=t,n=s.config,l=s.balance,i=G(_(n)),r=Te(a?()=>a.refreshBalance():null);if(!l||l.status!=="ok")return null;const u=Fn(s,n),d=Se(l.totalBalance,n,l.currency),c=b=>Se(b,n,l.currency),p=[i("balanceTitle"),Ma(i,c,u,d,u.cap),i("grantedToppedUp",{granted:Se(l.grantedBalance,n,l.currency),toppedUp:Se(l.toppedUpBalance,n,l.currency)}),i("updatedAt",{time:l.fetchedAt>0?new Date(l.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ke(i,r)].join("; "),f=e(L,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-balance-name"},e("span",{className:"cm-bbox-label"},i("balance")),Pa(i)),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},d)),e(Rt,{segments:u,direction:ie(n,"balance")}));return e(X,{label:p,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(r.busy?" busy":""),...be(r.busy,r.run)},o?f:e("div",{className:"cm-bbox-rail cm-num"},Math.round(u.remainingPct)+"%")))}function Lt(t,s){const o=typeof t?.label=="string"?t.label:"",a=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?a||o||"Custom balance":o||a||"自定义余额"}function _e(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const a=o?.unit??t?.customBalance?.unit;return["CNY","EUR","USD","CREDITS"].includes(a)?a:["CNY","EUR","CREDITS"].includes(s?.unit)?s.unit:"USD"}function We(t,s,o,a){const n=_e(s,o,a),l=Number(t);if(!Number.isFinite(l))return"—";const i=s?.currency==="USD"?1:Number(s?.exchangeRate);if((a??s?.customBalance)?.convertToDisplayCurrency===!0&&n==="USD"&&Number.isFinite(i)&&i>0){const c=l*i;return Number.isFinite(c)?me(c,s):"—"}const r=n==="CREDITS",u=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4)));return(r?"":n==="CNY"?"¥":n==="EUR"?"€":"$")+ba(l,u)+(r?" Credits":"")}function Et(t,s,o,a,n=null){const l=We(t.remaining,s,t,n),i=f=>We(f,s,t,n);if(a&&s.balance?.showProgressBar===!0){const f=Bt(a,s,t,n);return[Ma(o,i,f,l,f.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const r=t.spend!==null?i(t.spend):"—",u=t.maxBudget!==null?i(t.maxBudget):"—",d=_e(s,t,n)==="CREDITS"?NaN:Number(s?.balance?.budgetCap),c=Number.isFinite(d)&&d>0?o("balanceBudgetCapLabel")+": "+i(d):"",p=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:l,spend:r,maxBudget:u,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:l});return c?p+" · "+c:p}function Kn(t,s,o,a,n){const l=Lt(n??s.customBalance??{},_(s)),i=We(a.remaining,s,a,n),r=Bt(t,s,a,n);return{level:"ok",rail:Math.round(r.remainingPct)+"%",body:e(L,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},l),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},i)),e(Rt,{segments:r,direction:ie(s,"balance")}))}}function qt(t,s){const o=s?.customBalances??[],a=Array.isArray(t?.customBalances)?t.customBalances:[],n=[];return o.forEach((l,i)=>{if(l?.enabled!==!0||l.display!=="sidebar"&&l.display!=="both")return;const r=a.find(u=>u.index===i)??(a.length===1&&o.length===1?a[0]:null);n.push({index:i,entry:l,snapshot:r})}),n.length===0&&a.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&n.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),n}function Gn(t){const{state:s,wide:o,api:a}=t,n=s.config,l=G(_(n)),i=qt(s,n);return i.length===0?null:e(L,null,i.map(({index:r,entry:u,snapshot:d})=>e(Yn,{key:"cb-"+r,state:s,wide:o,api:a,t:l,index:r,entry:u,snapshot:d})))}function Yn(t){const{state:s,wide:o,api:a,t:n,index:l,entry:i,snapshot:r}=t,u=s.config;if(r==null||r.status!=="ok")return null;const d=Te(a?()=>a.refreshCustomBalance(l):null),c=Kn(s,u,n,r,i),p=[Et(r,u,n,s,i),...ke(n,d)].join(" · ");return e(X,{label:p,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(d.busy?" busy":""),...be(d.busy,d.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function Vn(t){const{state:s,wide:o,api:a}=t,n=s.config,l=G(_(n)),i=qt(s,n);return i.length===0?null:e(L,null,i.map(({index:r,entry:u,snapshot:d})=>e(Jn,{key:"cbr-"+r,state:s,wide:o,api:a,t:l,index:r,entry:u,snapshot:d})))}function Jn(t){const{state:s,wide:o,api:a,t:n,index:l,entry:i,snapshot:r}=t,u=s.config,d=r??sa(l);if(d.status==="off")return null;const c=Te(a?()=>a.refreshCustomBalance(l):null),p=Lt(i??u.customBalance??{},_(u));if(d.status==="error")return e(X,{label:[d.message||n("unknownError"),...ke(n,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...be(c.busy,c.run)},o?e(L,null,e("span",{className:"cm-bal-label",title:p},p),e("span",{className:"cm-num cm-bal-amt"},n("queryFailed"))):"⚠"));const f=We(d.remaining,u,d,i),b=[Et(d,u,n,s,i),...ke(n,c)].join(" · ");return e(X,{label:b,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...be(c.busy,c.run)},o?e(L,null,e("span",{className:"cm-bal-label",title:p},p),e("span",{className:"cm-num cm-bal-amt"},f)):e(ot,{size:16})))}function Zn(t){const o=(t.useCost?t.useCost(g=>g):void 0)?.state;if(!o)return null;const a=o.config,n=G(_(a)),l=a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},i=o.goQuota,r=a?.goQuota?.enabled!==!1&&i?.status==="ok",u=g=>g!==null&&typeof g?.percent=="number"?Math.round(Math.max(0,Math.min(100,g.percent))):null,d=[];if(a.sidebarModels?.dock){const g=ja(o,a.sidebarModels.period,n);g.length&&d.push({key:"model-top",text:e(L,null,e("span",{className:"cm-bal-label"},g[0].label),e("span",{className:"cm-bal-amt"},Y(g[0].cost,a))),tip:g[0].label+" "+Y(g[0].cost,a),level:"ok"})}const c=(g,h,x,S)=>{if(!l.enabled||!g||!r)return;const T=u(h);if(T===null)return;const N=typeof h.resetsAt=="string"&&h.resetsAt.length>0?n("goResetAt",{time:new Date(h.resetsAt).toLocaleString()}):"";d.push({key:x,text:n(x)+" "+T+"%",tip:n(S)+": "+T+"%"+(N?" · "+N:""),level:T>=100?"over":T>=80?"warn":"ok"})},p=a?.goQuota?.main==="weekly"||a?.goQuota?.main==="monthly"?a.goQuota.main:"rolling",f=[p,...["rolling","weekly","monthly"].filter(g=>g!==p)],b=g=>g==="rolling"?["goRolling",i?.rolling,"goShortRolling","cornerGoRolling"]:g==="weekly"?["goWeekly",i?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",i?.monthly,"goShortMonthly","cornerGoMonthly"];for(const g of f){const[h,x,S,T]=b(g);c(l[h]===!0,x,S,T)}if(l.enabled&&l.budget===!0){const g=a.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const h=Number(a.exchangeRate),S=(o.budgetUsed??(g.period==="day"?z(o.today,a):g.period==="all"?z(o.total,a):z(o.month,a)))*(Number.isFinite(h)&&h>0?h:1),T=Math.max(0,Number(g.amount)||0),N=T>0?Math.min(999,S/T*100):null;if(N!==null){const m=N>=100?"over":N>=80?"warn":"ok";d.push({key:"budget",text:n("budgetShort")+" "+N.toFixed(1)+"%",tip:n("budgetOf",{period:n(qe[g.period]??"periodMonth")})+" · "+n("usedOf",{used:me(S,a),amount:me(T,a)}),level:m})}}}return d.length===0?null:e("div",{className:"cm-corner"},d.map(g=>e(X,{key:g.key,label:g.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(g.key==="model-top"?" cm-model-top":"")+(g.level==="ok"?"":" "+g.level)},g.text))))}function lt(t,s,o){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const a=(f,b)=>{const g=new Date(t);return g.setUTCDate(g.getUTCDate()+f),g.setUTCHours(b,0,0,0),g.getTime()},n=new Set,l=Math.max(12,Math.min(380,(Array.isArray(o)?o.length:0)+7));for(let f=-l;f<=l;f+=1){n.add(a(f,16));for(const b of s){const g=Number(b?.start),h=Number(b?.end);!Number.isFinite(g)||!Number.isFinite(h)||(n.add(a(f,g)),n.add(a(h<=g?f+1:f,h)))}}const i=[...n].sort((f,b)=>f-b).flatMap(f=>{const b=at(f-1,void 0,s,o),g=at(f,void 0,s,o);return b===g?[]:[{at:f,intoPeak:g}]});let r=null,u=null;for(const f of i)f.at<=t&&(r===null||f.at>r.at)&&(r=f),f.at>t&&(u===null||f.at<u.at)&&(u=f);const d=ua(t,o),c=d??da(t);return c!==null?u===null?null:{inPeak:!1,weekend:d===null,...d?{holiday:!0}:{},prevAtMs:c.start,nextAtMs:u.at,nextIntoPeak:u.intoPeak}:r===null||u===null?null:{inPeak:at(t,void 0,s,o),weekend:!1,prevAtMs:r.at,nextAtMs:u.at,nextIntoPeak:u.intoPeak}}function it(t,s){if(!t||t.peakNotice===!1||t.peakEnabled!==!0)return null;const o=Date.parse(t.peakEffectiveAt||"");if(Number.isFinite(o)&&s<o)return null;const a=Array.isArray(t.peakWindows)?t.peakWindows:[];return lt(s,a,t.peakHolidays)}function rt(t){return t.holiday===!0?{short:"holidayShort",chip:"holidayChip",notice:"holidayAllOffPeak"}:t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function we(t,s,o){const a=Math.max(0,t.nextAtMs-s),n=Math.max(1,Math.ceil(a/6e4)),l=Math.floor(n/60),i=n%60;return l>0?i>0?o("countdownHourMinute",{h:l,m:i}):o("countdownHoursOnly",{h:l}):o("countdownMinute",{m:n})}const It="cm-peak-alert-preview";let Ta=0;function $n(t){const s=t.useCost?t.useCost(h=>h):void 0,o=s?.state?.config,[a,n]=B(Date.now()),[l,i]=B(null),[r,u]=B(null);if(ee(()=>{const h=window.setInterval(()=>n(Date.now()),1e4);return()=>window.clearInterval(h)},[]),ee(()=>{const h=x=>{const S=x.detail?.kind==="offpeak"?"offpeak":"peak";u(S);const T=s?.state?.config;if(T?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const N=G(_(T));try{new Notification(N(S==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+N("peakAlertPreviewTag"),{body:N("peakAlertBody",{time:N("countdownMinute",{m:2}),phase:N(S==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(It,h),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(It,h),window.__cmPeakAlertLive=!1}},[]),ee(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const h=lt(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(h===null)return;const x=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",S=h.nextIntoPeak===!0;if(x!=="both"&&x!==(S?"peak":"offpeak"))return;const T=Number(o.peakAlertAhead),N=(Number.isFinite(T)&&T>=1?T:2)*6e4;if(a<h.nextAtMs-N||a>=h.nextAtMs||Ta===h.nextAtMs)return;const m=G(_(o));Ta=h.nextAtMs;try{new Notification(m(S?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:m("peakAlertBody",{time:we(h,a,m),phase:m(S?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[a]),!o||o.peakEnabled!==!0)return null;let d=null;if(o.peakAlertEnabled===!0){const h=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(h)&&a<h)){const x=lt(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(x!==null){const S=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",T=Number(o.peakAlertAhead),N=(Number.isFinite(T)&&T>=1?T:2)*6e4;(S==="both"||S===(x.nextIntoPeak?"peak":"offpeak"))&&a>=x.nextAtMs-N&&a<x.nextAtMs&&l!==x.nextAtMs&&(d=x)}}}let c=null,p=!1,f=null;if(d!==null)c=d,p=d.nextIntoPeak===!0,f=()=>i(d.nextAtMs);else if(r!==null)c={nextAtMs:a+2*6e4,nextIntoPeak:r==="peak"},p=r==="peak",f=()=>u(null);else return null;const b=G(_(o)),g=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+g+" "+(p?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},b(p?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},b(p?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},b("peakAlertBody",{time:we(c,a,b),phase:b(p?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:f},b("peakAlertBtn"))))}function Xn(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)});return e(X,{label:o(i.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(l.weekend||l.holiday?"weekend":l.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:l.weekend||l.holiday?"50%":l.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(i.chip)+" · "+r)))}function es(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)});return e(X,{label:o(i.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(l.weekend||l.holiday?"weekend":l.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:l.weekend||l.holiday?"50%":l.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(i.chip)+" · "+r)))}function ct(t,s,o){return e(s?.peakStyle==="classic"?es:Xn,{config:s,t:o})}function ts(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)}),u=[o(i.notice),r];return e(X,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(l.weekend||l.holiday?"weekend":l.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-track"},e("div",{className:"cm-peak-rail-segment cm-peak-rail-high"}),e("div",{className:"cm-peak-rail-segment cm-peak-rail-low"}),e("div",{className:"cm-peak-rail-marker",style:{top:l.weekend||l.holiday?"50%":l.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(i.short))))}function as(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)}),u=[o(i.notice),r];return e(X,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(l.weekend||l.holiday?"weekend":l.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-classic-track"},e("div",{className:"cm-peak-rail-classic-segment peak"}),e("div",{className:"cm-peak-rail-classic-segment off"}),e("div",{className:"cm-peak-rail-classic-marker",style:{top:l.weekend||l.holiday?"50%":l.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(i.short))))}function ns(t,s,o){return e(s?.peakStyle==="classic"?as:ts,{config:s,t:o})}function Oa(t,s,o){const a=t.today,n=s.budget??{enabled:!1,amount:100,period:"month"},l=Number(s.exchangeRate),r=(t.budgetUsed??(n.period==="day"?z(t.today,s):n.period==="all"?z(t.total,s):z(t.month,s)))*(Number.isFinite(l)&&l>0?l:1),u=Math.max(0,Number(n.amount)||0),d=u>0?Math.min(999,r/u*100):null,c=fe(d===null?null:Math.min(100,d),ie(s,"budget")),p=z(a,s)*(Number.isFinite(l)&&l>0?l:1),f=u>0?Math.min(999,p/u*100):null,b=n.detail!==!1;return{level:d===null?"ok":d>=100?"over":d>=80?"warn":"ok",rail:c.label===null?"—":Math.round(c.label)+"%",body:e(L,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+"%"}})),b?e(L,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},s.sidebarTodayMetric==="tokens"?o("today")+" "+Ft(a,s,o):o("todayShare",{amount:Y(z(a,s),s),pct:f===null?"—":f.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:me(r,s),amount:me(u,s)}))):null,ct(t,s,o))}}function Da(t,s,o){const a=t.goQuota,n=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",l=a[n],i=l!==null&&typeof l?.percent=="number"?Math.max(0,Math.min(100,Number(l.percent)||0)):0,r=b=>b!==null&&typeof b?.percent=="number"?Math.round(Math.max(0,Math.min(100,b.percent)))+"%":"—",u=b=>o(b==="rolling"?"goShortRolling":b==="weekly"?"goShortWeekly":"goShortMonthly"),d=["rolling","weekly","monthly"].filter(b=>b!==n),c=l!==null&&typeof l?.resetsAt=="string"&&l.resetsAt.length>0?o("goResetAt",{time:new Date(l.resetsAt).toLocaleString()}):"",p=s?.goQuota?.detail!==!1,f=fe(i,ie(s,"go"));return{level:i>=100?"over":i>=80?"warn":"ok",rail:f.label===null?"—":Math.round(f.label)+"%",body:e(L,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+u(n)),e("span",{className:"cm-bbox-pct cm-num"},f.label===null?"—":Math.round(f.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:f.width+"%"}})),p?e(L,null,e("div",{className:"cm-bbox-line cm-num"},d.map(b=>u(b)+" "+r(a[b])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function ss(t){const{state:s,wide:o}=t,a=s.goQuota,n=G(_(s.config));if(!a||a.status!=="ok")return null;const l=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(a[l]===null||typeof a[l]?.percent!="number")return null;const i=Da(s,s.config,n),r=[n("goQuotaTitle"),n("goWindowRolling")+": "+(a.rolling===null?"—":Math.round(a.rolling.percent)+"%"),n("goWindowWeekly")+": "+(a.weekly===null?"—":Math.round(a.weekly.percent)+"%"),n("goWindowMonthly")+": "+(a.monthly===null?"—":Math.round(a.monthly.percent)+"%"+(a.monthly!==null&&typeof a.monthly.resetsAt=="string"&&a.monthly.resetsAt.length>0?" · "+n("goResetAt",{time:new Date(a.monthly.resetsAt).toLocaleString()}):"")),n("goQuotaFetchedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e(X,{label:r,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(i.level==="ok"?"":" "+i.level)+(o?"":" rail")},o?i.body:e("div",{className:"cm-bbox-rail cm-num"},i.rail)))}function os(t){return t===null||typeof t!="object"||t.unlimited||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function ze(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function Ba(t,s,o=Date.now()){if(typeof t!="string"||!t)return"";const a=Date.parse(t);if(!Number.isFinite(a))return"";const n=a-o;if(n<=0)return s("resetReached");const l=Math.ceil(n/6e4),i=Math.floor(l/1440),r=Math.floor(l%1440/60),u=l%60;return i>0?s("resetDays",{d:i,h:r}):r>0?s("resetHours",{h:r,m:u}):s("resetMinutes",{m:u})}function Ke(t,s,o=Date.now()){const a=Ba(t?.resetsAt,s,o);return a?s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})+" ("+a+")":""}function dt(t,s,o){return t===null?"—":o(s==="remaining"?"quotaRemaining":"quotaUsed",{pct:t})}function ut(t){const[,s]=B(0),o=()=>s(Date.now());return ee(()=>{if(!t)return;const a=setInterval(o,6e4);return()=>clearInterval(a)},[t]),{onMouseEnter:o,onFocus:o}}function Ge(t,s,o,a){const n=os(s),l=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",i=fe(n,o),r=s?.unlimited?"∞":i.label===null?"—":i.label+"%";return{level:l,pct:n,text:r,label:i.label,row:e("div",{className:"cm-mm-row"+(l==="ok"?"":" "+l)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:i.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r))}}function Ra(t){const{five:s,seven:o,fetchedAt:a,t:n,wide:l,refresh:i,direction:r="used"}=t,u=ut(s?.resetsAt),d=Ba(s?.resetsAt,n),c=Ge(n("codingPlanRemain5h"),s,r,n),p=Ge(n("codingPlanRemain7d"),o,r,n),f=c.level==="over"||p.level==="over"?"over":c.level==="warn"||p.level==="warn"?"warn":"ok",b=(S,T,N)=>{const m=T?.unlimited?n("quotaUnlimited"):dt(N.label,r,n),v=Ke(T,n);return S+" "+m+(v?" · "+v:"")},g=[n("codingPlanMinimaxTitle"),b(n("codingPlanRemain5h"),s,c),b(n("codingPlanRemain7d"),o,p),a>0?n("goQuotaFetchedAt",{time:new Date(a).toLocaleTimeString()}):null,...i?ke(n,i):[]].filter(Boolean).join(`
3
- `),h=e(L,null,e("div",{className:"cm-mm-title"},n("codingPlanMinimaxTitle")),c.row,p.row,d?e("div",{className:"cm-mm-reset"},"5h · "+d):null),x=e(L,null,e("div",{className:"cm-bbox-rail cm-num"},c.text),e("div",{className:"cm-bbox-rail cm-num"},p.text));return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},g),side:"right",delayMs:300},e("div",{...u,className:"cm-bbox cm-mm"+(f==="ok"?"":" "+f)+(l===!1?" rail":"")+(i?" clickable"+(i.busy?" busy":""):""),...i?be(i.busy,i.run):{}},l===!1?x:h))}function ls(t){const{state:s,wide:o,api:a}=t,n=s.codingPlans?.minimax,l=G(_(s.config)),i=Te(a?()=>a.refreshCodingPlan("minimax"):null);if(!n||n.status!=="ok")return null;const{five:r,seven:u}=ze(n.windows);return r==null&&u==null?null:e(Ra,{five:r,seven:u,fetchedAt:n.fetchedAt,t:l,wide:o,refresh:i,direction:ie(s.config,"plan")})}const is="/plugins/dsh-openai-codex/auth/status",rs=168*3600;function cs(t){if(t===null||typeof t!="object"||t.status!=="signed-in")return null;const s=t.usage!==null&&typeof t.usage=="object"?t.usage.rateLimits:null;if(!Array.isArray(s))return null;const o=s.find(r=>r!==null&&typeof r=="object"&&r.id==="codex");if(!o||!Array.isArray(o.windows))return null;const a=o.windows.find(r=>r!==null&&typeof r=="object"&&Number(r.windowSeconds)===rs);if(!a||typeof a.remainingPercent!="number"||!Number.isFinite(Number(a.remainingPercent)))return null;const n=Math.max(0,Math.min(100,Math.round((100-Number(a.remainingPercent))*10)/10)),l=Number(a.resetAt),i=Number.isFinite(l)&&l>0?new Date(l*1e3).toISOString():"";return{weekly:{percent:n,resetsAt:i}}}const $={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},ds=t=>($.listeners.push(t),()=>{$.listeners=$.listeners.filter(s=>s!==t)}),us=()=>{for(const t of $.listeners)try{t()}catch{}};async function jt(t=!1,s=!1){if(!s)return;if($.inFlight!==null)return $.inFlight;if(!t&&$.fetchedAt>0&&Date.now()-$.fetchedAt<5*6e4)return;const o=(async()=>{try{const a=await fetch(is,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(a.ok){const l=cs(await a.json().catch(()=>null));l!==null&&(n=l)}$.status=Object.keys(n).length>0?"ok":"unavailable",$.windows=n}catch{$.status="unavailable"}finally{$.fetchedAt=Date.now(),$.inFlight=null,us()}})();return $.inFlight=o,o}function Ut(t){const[s,o]=B(()=>({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt}));return ee(()=>{if(!t)return;let a=!0;const n=()=>{a&&o({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt})},l=ds(n);return n(),jt(!1,!0),()=>{a=!1,l()}},[t]),s}function ms(t){const s=ut(),{state:o,wide:a}=t,n=G(_(o.config)),l=o.config?.codexQuotaEnabled===!0&&o.config?.codexQuotaSidebar!==!1,i=Ut(l),r=Te(()=>jt(!0,l));if(!l||i.status!=="ok")return null;const u=i.windows.weekly??null;if(u===null)return null;const d=ie(o.config,"plan"),c=Ge(n("goShortWeekly"),u,d,n),p=[n("codexQuotaTitle"),dt(c.label,d,n),Ke(u,n),i.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()}):null,...ke(n,r)].filter(Boolean).join(`
4
- `),f=e(L,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),c.row),b=e("div",{className:"cm-bbox-rail cm-num"},c.label===null?"—":c.label+"%");return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},p),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(c.level==="ok"?"":" "+c.level)+(a===!1?" rail":"")+(r.busy?" busy":""),...be(r.busy,r.run)},a===!1?b:f))}function Ht(t,s){return t==="fiveHour"||t==="5h"?"5h":t==="weekly"||t==="week"||t==="7d"?t==="7d"?"7d":s("goShortWeekly"):t==="monthly"||t==="month"?s("goShortMonthly"):t==="daily"||t==="day"?s("goShortDaily"):t==="plan"?s("mimoWindowPlan"):t==="compensation"?s("mimoWindowCompensation"):t==="balance"?s("codingPlanWindowBalance"):String(t).replace(/_/g," ")}function ps(t){const s=ut(),{id:o,state:a,wide:n,api:l}=t,i=a.codingPlans?.[o],r=G(_(a.config)),u=Te(l?()=>l.refreshCodingPlan(o):null),d=Le.find(m=>m.id===o);if(!d||!i||i.status!=="ok")return null;const c=i.windows!==null&&typeof i.windows=="object"?i.windows:{},p=Object.entries(c);if(p.length===0)return null;const f=m=>m!==null&&typeof m=="object"&&typeof m.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(m.percent)||0))):null,b=ie(a.config,"plan"),g=p.map(([m,v])=>{const y=f(v);if(y===null)return e("div",{key:m,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof v?.text=="string"?v.text:"—"));const O=y>=100?"over":y>=80?"warn":"ok",P=fe(y,b);return e("div",{key:m,className:"cm-mm-row wide"+(O==="ok"?"":" "+O)},e("span",{className:"cm-bbox-label"},Ht(m,r)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:P.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},P.label===null?"—":P.label+"%"))}),h=p.map(([m,v])=>{const y=f(v),O=Ke(v,r),P=y===null?typeof v?.text=="string"?v.text:"—":dt(fe(y,b).label,b,r);return Ht(m,r)+" "+P+(O?" · "+O:"")});i.fetchedAt>0&&h.push(r("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()})),h.push(...ke(r,u));const x=[r(d.labelKey),...h].join(`
5
- `),S=p.map(([,m])=>f(m)).filter(m=>m!==null),T=S.some(m=>m>=100)?"over":S.some(m=>m>=80)?"warn":"ok",N=S.length>0?S.slice(0,2).map(m=>fe(m,b).label+"%").join(" "):typeof p[0][1]?.text=="string"?p[0][1].text:"—";return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},x),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(T==="ok"?"":" "+T)+(n===!1?" rail":"")+(u.busy?" busy":""),...be(u.busy,u.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},N):e(L,null,e("div",{className:"cm-mm-title"},r(d.labelKey)),...g)))}const La=t=>{try{return window.localStorage?.getItem?.("cm.gw."+t)??""}catch{return""}},fs=(t,s)=>{try{window.localStorage?.setItem?.("cm.gw."+t,s)}catch{}};function bs(t){const s=ut(),{source:o,snapshot:a,state:n,wide:l,api:i}=t,r=G(_(n.config)),[u,d]=B(()=>({source:o.id,id:La(o.id)})),c=Te(i?()=>i.refreshGatewayQuota(o.id):null),p=ie(n.config,"plan"),f=a.accounts.length>1,b=u.source===o.id?u.id:La(o.id),g=a.accounts.findIndex(M=>M.id===b),h=g>=0?g:Math.max(0,a.accounts.findIndex(M=>M.windows.length>0||M.credits!=null)),x=a.accounts[h]??a.accounts[0],S=x?.label||x?.id||"",T=M=>f?(la[M.provider]??M.provider)+" · ":"",N=f&&x?[x]:a.accounts,m=[];for(const M of N){if(m.length>=4)break;for(const U of M.windows){if(m.length>=4)break;const D=T(M)+(U.label||U.id||r("gatewaySourceUnknown"));m.push({win:U,name:D,view:Ge(D,U,p,r)})}M.windows.length===0&&M.credits!=null&&m.push({win:null,name:T(M)+(M.credits.unit||"credits"),text:(M.credits.used??"—")+" / "+(M.credits.limit??"—")})}m.length===0&&m.push({name:r("gatewayQuotaEmpty"),text:"—"});const v=m.some(M=>M.view?.level==="over")?"over":m.some(M=>M.view?.level==="warn")?"warn":"ok",y=m.map(M=>{if(M.text!=null)return M.name+" "+M.text;const U=Ke(M.win,r);return M.name+" "+dt(M.view.label,p,r)+(U?" · "+U:"")});a.fetchedAt>0&&y.push(r("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()})),y.push(...ke(r,c));const P=[f&&S?`${o.label||o.id} (${h+1}/${a.accounts.length} · ${S})`:o.label||o.id,...y].join(`
6
- `),R=m.map((M,U)=>M.text!=null?e("div",{key:U,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.name),e("span",{className:"cm-mm-text cm-num"},M.text)):e(L,{key:U},M.view.row)),A=M=>{if(!M.key||M.key==="Enter"||M.key===" "){M.stopPropagation(),M.preventDefault?.();const U=a.accounts[(h+1)%a.accounts.length];fs(o.id,U.id),d({source:o.id,id:U.id})}},I=f?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:S||h+1}),onClick:A,onKeyDown:A,role:"button",tabIndex:0},`${h+1}/${a.accounts.length} ⇄`):null,k=f?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),I):e("div",{className:"cm-mm-title"},o.label||o.id),j=f&&S?e("div",{className:"cm-gw-sub"},S):null,Ce=e(L,null,k,j,...R),de=m.filter(M=>M.view).map(M=>M.view.label).filter(M=>M!==null),Ae=de.length>0?de.slice(0,2).map(M=>M+"%").join(" "):m[0].text??"—",J=e("div",{className:"cm-bbox-rail cm-num"},Ae);return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},P),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(v==="ok"?"":" "+v)+(l===!1?" rail":"")+(c.busy?" busy":""),...be(c.busy,c.run)},l===!1?e(L,null,J,I):Ce))}function gs(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],l=[];for(const i of s.gatewayQuotas?.sources??[]){if(i.enabled===!1||i.display!=="sidebar"&&i.display!=="both")continue;const r=n.find(u=>u.id===i.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||l.push(e(bs,{source:i,snapshot:r,state:t,wide:o,api:a}))}return l}const hs={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function ys(t){const s=t.useCost?t.useCost(g=>g):void 0;Ut(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=B(null),[n,l]=B({}),i=s?.state,r=t.api;if(!i)return null;const u=i.config,d=u.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(d.enabled!==!0)return null;const c=G(_(u)),p=[];if(d.budget!==!1){const g=u.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const h=Number(u.exchangeRate),S=(i.budgetUsed??(g.period==="day"?z(i.today,u):g.period==="all"?z(i.total,u):z(i.month,u)))*(Number.isFinite(h)&&h>0?h:1),T=Math.max(0,Number(g.amount)||0);if(T>0){const N=Math.min(999,S/T*100),m=N>=100?"over":N>=80?"warn":"ok";p.push({key:"budget",label:c("budgetShort"),level:m,tip:c("budgetOf",{period:c(qe[g.period]??"periodMonth")})+" · "+c("usedOf",{used:me(S,u),amount:me(T,u)})+" · "+N.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(fe(Math.min(100,N),ie(u,"budget")).width)}]})}}}if(d.go!==!1){const g=i.goQuota;if(u?.goQuota?.enabled!==!1&&g?.status==="ok"){const h=u.goQuota.main==="weekly"||u.goQuota.main==="monthly"?u.goQuota.main:"rolling",x=h==="rolling"?g.rolling:h==="weekly"?g.weekly:g.monthly;if(x!==null&&typeof x=="object"&&typeof x.percent=="number"){const S=Math.max(0,Math.min(100,Math.round(Number(x.percent)||0))),T=S>=100?"over":S>=80?"warn":"ok",N=typeof x.resetsAt=="string"&&x.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(x.resetsAt).toLocaleString()}):"";p.push({key:"go",label:"Go "+c(h==="rolling"?"goShortRolling":h==="weekly"?"goShortWeekly":"goShortMonthly"),level:T,tip:"Go: "+S+"%"+N,segs:[{name:"main",pct:Math.round(fe(S,ie(u,"go")).width)}]})}}}if(d.plans!==!1)for(const g of Le){const h=i.codingPlans?.[g.id];if(u.codingPlans?.[g.id]?.enabled!==!0||!h||h.status!=="ok")continue;const x=h.windows!==null&&typeof h.windows=="object"?h.windows:{},S=Object.entries(x);if(S.length===0)continue;const T=hs[g.id]??g.id,N=[],m=[];let v=0,y=0;for(const[O,P]of S){const R=Ht(O,c),A=typeof P?.resetsAt=="string"&&P.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(P.resetsAt).toLocaleString()}):"",I=P!==null&&typeof P=="object"&&typeof P.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(P.percent)||0))):null;if(m.push(R+" "+(I===null?typeof P?.text=="string"?P.text:"—":I+"%")+A),I===null){N.push({name:O,pct:null,text:typeof P?.text=="string"?P.text:"—"});continue}y>=2||(y+=1,N.push({name:O,pct:Math.round(fe(I,ie(u,"plan")).width)}),v=Math.max(v,I>=100?2:I>=80?1:0))}h.fetchedAt>0&&m.push(c("goQuotaFetchedAt",{time:new Date(h.fetchedAt).toLocaleTimeString()})),N.length!==0&&p.push({key:g.id,label:T,level:["ok","warn","over"][v],tip:m.join("; "),segs:N})}const f=u.codexQuotaEnabled===!0&&$.status==="ok"?$.windows.weekly??null:null;if(f!==null&&typeof f.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(f.percent)||0))),h=typeof f.resetsAt=="string"&&f.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(f.resetsAt).toLocaleString()}):"";p.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+h,segs:[{name:"weekly",pct:Math.round(fe(g,ie(u,"plan")).width)}]})}if(p.length===0)return null;const b=g=>{o!==null||!r||(a(g),l(h=>({...h,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?jt(!0,u.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(h=>{l(x=>({...x,[g]:h?.message??String(h)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},p.map(g=>{const h=o===g.key,x=n[g.key],S=[e("span",{className:"cm-qlabel",key:"l"},g.label)];h?S.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((N,m)=>{m>0&&S.push(e("span",{className:"cm-qsep",key:"sep"+m,"aria-hidden":"true"})),N.pct===null?S.push(e("span",{className:"cm-qtext",key:N.name},N.text)):S.push(e("span",{className:"cm-qseg",key:N.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:N.pct+"%"}})),e("span",null,N.pct+"%")))});const T=[g.tip];return!h&&r&&T.push(c("clickToRefresh")),h&&T.push(c("refreshing")),x&&T.push("⚠ "+c("balanceRefreshFailed",{message:x})),e(X,{key:g.key,label:T.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?be(h,()=>b(g.key)):{}},S))}))}const Ea="dsh-cost-meter:simple-guide-dismissed";function Qt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Ea)==="1"}catch{return!1}}function ks(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Ne(!1),[a,n]=B(!1),[l,i]=B(!1),[r,u]=B(!1),d=s?.state?.config;if(!d||r||Qt(d))return null;const c=G(_(d)),p=()=>{u(!0);try{window.localStorage.setItem(Ea,"1")}catch{}},f=async b=>{if(!o.current){o.current=!0,n(!0),i(!1);try{if((await t.api.updateConfig({sidebarSimple:b,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==b)throw new Error;p()}catch{i(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),p())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:p},"×")),e("p",null,c("sidebarSimpleBody")),l?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>f(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>f(!0)},c("sidebarSimpleOn"))))}function ws(t){const s=t.useCost?t.useCost(r=>r):void 0,o=Ne(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Qt(n)||n.quotaStrip?.promptSeen===!0)return null;const l=G(_(n)),i=r=>{if(o.current===!0)return;o.current=!0;const u=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...u,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":l("quotaStripGuideTitle")},e("h4",null,l("quotaStripGuideTitle")),e("p",null,l("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>i(!1)},l("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>i(!0)},l("quotaStripGuideOn"))))}const qa="dsh-cost-meter:balance-click-hint-seen",xs=()=>{try{return window.localStorage.getItem(qa)==="1"}catch{return!1}},vs=()=>{try{window.localStorage.setItem(qa,"1")}catch{}};function Ns(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Ne(!1),[a,n]=B(!1),[l]=B(xs),i=s?.state;if(!i)return null;const r=i.config,u=r.balance?.display==="sidebar"||r.balance?.display==="both",d=(r?.customBalances??[]).some(b=>b?.enabled===!0&&(b.display==="sidebar"||b.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Le.some(b=>{const g=r.codingPlans?.[b.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||l||r.balance?.clickHintSeen===!0||!u&&!d&&!c||!Qt(r)||r.quotaStrip?.promptSeen!==!0)return null;const p=G(_(r)),f=()=>{o.current!==!0&&(n(!0),o.current=!0,vs(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":p("balanceClickGuideTitle")},e("h4",null,p("balanceClickGuideTitle")),e("p",null,p("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:f},p("balanceClickGuideOk"))))}function Ft(t,s,o){return s.sidebarTodayMetric==="tokens"?q(["input","output","cacheRead","cacheWrite","reasoning"].reduce((a,n)=>a+(Number(t?.[n])||0),0))+" "+o("tokensUnit"):Y(z(t,s),s)}function _t(t){const{state:s,wide:o}=t,a=s.today,n=s.config,l=G(_(n)),i=Ft(a,n,l),r=n.budget??{enabled:!1,amount:100,period:"month"},u=Number(n.exchangeRate),c=(s.budgetUsed??(r.period==="day"?z(s.today,n):r.period==="all"?z(s.total,n):z(s.month,n)))*(Number.isFinite(u)&&u>0?u:1),p=Math.max(0,Number(r.amount)||0),f=p>0?Math.min(999,c/p*100):null,b=f===null?"ok":f>=100?"over":f>=80?"warn":"ok";if(r.enabled===!0){const x=z(a,n)*(Number.isFinite(u)&&u>0?u:1),S=p>0?Math.min(999,x/p*100):null,T=[l("budgetOf",{period:l(qe[r.period]??"periodMonth")}),l("usedOf",{used:me(c,n),amount:me(p,n)})+" · "+(f===null?"—":f.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[n.sidebarTodayMetric==="tokens"?l("today")+" "+i:l("todayShare",{amount:i,pct:S===null?"—":S.toFixed(1)+"%"})],l("monthTotal",{month:Y(z(s.month,n),n),total:Y(z(s.total,n),n)})].join("; ");if(t.summary===!0)return e(X,{label:T,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(b==="ok"?"":" "+b),tabIndex:0},e("span",null,l("todayBudget",{period:l(qe[r.period]??"periodMonth")})),e("span",{className:"cm-num"},i+" / "+me(p,n))));const N=Oa(s,n,l);return e(X,{label:T,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(b==="ok"?"":" "+b)+(o?"":" rail")},o?N.body:e("div",{className:"cm-bbox-rail cm-num"},N.rail)))}const g=[n.sidebarTodayMetric==="tokens"?l("todayTokensTitle"):l("todayCostTitle"),l("callsTokens",{calls:a.calls,input:q(a.input),cache:q(a.cacheRead+a.cacheWrite),output:q(a.output)}),l("monthCost",{amount:Y(z(s.month,n),n)}),l("totalCost",{amount:Y(z(s.total,n),n)})].join("; ");return e(X,{label:g,side:"right",delayMs:300},e(L,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(L,null,l("today")," ",e("span",{className:"cm-num"},i)):e(ot,{size:16})),o?ct(s,n,l):null))}function Ss(t){const s=t.useCost?t.useCost(A=>A):void 0;Ut(s?.state?.config?.codexQuotaEnabled===!0&&s?.state?.config?.codexQuotaSidebar!==!1);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}wa(t,o);const a=s?.state,n=!!t.wide;if(!a)return null;const l=a.config,i=G(_(l)),r=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,d=qt(a,l).length>0,c=r&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",p=d&&l.balance?.showProgressBar===!0,f=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",b=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[f]!==null,g=Le.map(A=>A.id).filter(A=>{const I=l.codingPlans?.[A];if(I?.enabled!==!0||I.display!=="sidebar"&&I.display!=="both")return!1;const k=a.codingPlans?.[A];if(k?.status!=="ok")return!1;const j=k.windows!==null&&typeof k.windows=="object"?k.windows:{};return Object.keys(j).length>0}),h=g.length>0,x=gs(a,l,n,t.api),S=l.codexQuotaEnabled===!0&&l.codexQuotaSidebar!==!1&&$.status==="ok"&&$.windows.weekly!==null,T=(l.budget??{}).enabled===!0,N=l.sidebar!==!1&&l.hideTodayCost!==!0,m=l.sidebarModels?.enabled===!0;if(!m&&!r&&!d&&!b&&!h&&!S&&!T&&!N&&x.length===0)return null;const v=l.sidebarSimple===!0,y=!v&&n&&l.sidebarStyle==="compact",O=v&&n&&N&&T,P=[];O?P.push(e(_t,{state:a,wide:n,summary:!0})):v&&n&&N&&P.push(e("div",{className:"cm-simple-summary"},e("span",null,i("today")),e("span",{className:"cm-num"},Ft(a.today,l,i)))),c?P.push(e(zn,{state:a,wide:n,api:t.api})):r&&P.push(e(Wn,{state:a,wide:n,api:t.api})),p?P.push(e(Gn,{state:a,wide:n,api:t.api})):d&&P.push(e(Vn,{state:a,wide:n,api:t.api}));const R=P.length;if(h&&P.push(...g.map(A=>A==="minimax"?e(ls,{state:a,wide:n,api:t.api}):e(ps,{id:A,state:a,wide:n,api:t.api}))),P.push(...x),S&&P.push(e(ms,{state:a,wide:n,api:t.api})),b&&T&&n&&!v){const A=Da(a,l,i),I=Oa(a,l,i),k=A.level==="over"||I.level==="over"?"over":A.level==="warn"||I.level==="warn"?"warn":"ok";P.push(e("div",{className:"cm-bbox cm-bbox-pair"+(k==="ok"?"":" "+k)},e("div",{className:"cm-bbox-section"+(A.level==="ok"?"":" "+A.level)},A.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(I.level==="ok"?"":" "+I.level)},I.body)))}else b&&P.push(e(ss,{state:a,wide:n})),T&&!O&&P.push(e(_t,{state:a,wide:n}));return!T&&N&&!(v&&n)&&P.push(e(_t,{state:a,wide:n})),v&&n&&N&&P.push(ct(a,l,i)),n||P.push(ns(a,l,i)),m&&P.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?R:P.length,0,e(Cs,{key:"models",state:a,wide:n})),e("div",{...v?{tabIndex:0,role:"region","aria-label":i("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(y?" compact":"")+(v?" simple":"")},...P)}const Wt={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Ia="dsh-cost-meter:models-open";function ja(t,s,o){return Fa(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:Gt(a.key),cost:z(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function Cs({state:t,wide:s}){const o={...Wt,...t.config.sidebarModels},a=G(_(t.config)),n=()=>{try{const S=o.remember?window.localStorage.getItem(Ia):null;if(S!==null)return S==="1"}catch{}return o.defaultOpen},[l,i]=B(n),[r,u]=B(o.period);ee(()=>u(o.period),[o.period]),ee(()=>i(n()),[o.defaultOpen,o.remember]);const d=ja(t,r,a),c=d.reduce((S,T)=>S+T.cost,0),p=S=>Y(S,t.config),f=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+p(c)+" · "+a("modelsCount",{n:d.length}),b=o.summary==="top"&&d.length?d[0].label+" "+p(d[0].cost):f,g=o.summary==="top"&&d.length?e(L,null,e("span",{className:"cm-bal-label"},d[0].label),e("span",{className:"cm-bal-amt"},p(d[0].cost))):e("span",{className:"cm-bal-label"},b),h=()=>{i(!l);try{o.remember&&window.localStorage.setItem(Ia,l?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:b+" · "+f},s?g:e(ot,{size:16}));const x=d.slice(0,o.topN);return d.length>o.topN&&x.push(d.slice(o.topN).reduce((S,T)=>{for(const N of["cost","input","output","cacheRead","cacheWrite"])S[N]+=T[N];return S},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(l),title:f,onClick:h},e("span",{className:"cm-caret"+(l?" open":"")}),g),l?e(L,null,e("div",{className:"cm-buttons"},["today","history"].map(S=>e("button",{key:S,type:"button",className:"cm-mstats-tab"+(r===S?" active":""),"aria-pressed":r===S,onClick:()=>u(S)},a(S==="today"?"modelStatsToday":"modelStatsHistory")))),x.length?x.map(S=>e("div",{key:S.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:S.label},S.label),e("span",{className:"cm-num cm-bal-amt"},p(S.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?S.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?S.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+q(S.input)+" · "+a("modelStatsCache")+" "+q(S.cacheRead+S.cacheWrite)+" · "+a("modelStatsOutput")+" "+q(S.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function As({draft:t,setDraft:s,t:o}){const a={...Wt,...t?.sidebarModels},n=(i,r)=>{t&&s({...t,sidebarModels:{...a,[i]:r}})},l=(i,r)=>e("div",{className:"cm-field",key:i},e("label",null,o("models_"+i)),e("select",{className:"cm-input",value:a[i],onChange:u=>n(i,u.target.value)},r.map(([u,d])=>e("option",{key:u,value:u},o(d)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(i=>e("label",{key:i,className:"cm-check"},e("input",{type:"checkbox",checked:a[i],onChange:r=>n(i,r.target.checked)}),o("models_"+i))),l("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),l("summary",[["total","modelsTotal"],["top","modelsTop"]]),l("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(i=>e("div",{key:i,className:"cm-field"},e("label",null,o("models_"+i)),ne({value:a[i]},r=>n(i,Math.max(i==="topN"?1:10,Math.min(i==="topN"?10:60,Math.floor(r))))))))}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))}function Ua(t){const[s,o]=B(null),[a,n]=B(""),[l,i]=B(0);return ee(()=>{let r=!0;return n(""),t.api.loadStatistics().then(u=>{r&&o(()=>u)},u=>{r&&n(String(u.message??u))}),()=>{r=!1}},[t.api,l]),s?e(s,{...t,formatMoneyUsd:Y,formatTokens:q,resolveLocale:_}):e("p",{role:a?"alert":"status"},a||"…",a?e("button",{className:"cm-btn",onClick:()=>i(r=>r+1)},"↻"):null)}function Ms(t){const s=t.useCost?.(c=>c),o=s?.state,[a,n]=B(null),l=Be.useRef(null),i=o?.config[t.entryPosition==="header"?"hideSessionCostHeader":"hideSessionCostDock"]===!0,r=!i&&!!t.sessionId&&a===t.sessionId;if(ee(()=>{r&&l.current?.showModal()},[r]),ee(()=>{n(null)},[t.sessionId,i]),!t.sessionId||i)return null;const u=_(o?.config)==="en",d=u?"Conversation cost details":"本会话费用明细";return e(L,null,e("button",{type:"button",className:"cm-btn cm-stat-entry cm-stat-"+(t.entryPosition||"dock"),title:d,"aria-label":d,"aria-haspopup":"dialog",onClick:()=>n(t.sessionId)},u?"Cost details":"费用明细"),r?e("dialog",{ref:l,role:"dialog","aria-label":d,onCancel:()=>n(null),style:{width:"min(1160px,94vw)",maxHeight:"90vh",padding:24,borderRadius:16,border:"1px solid var(--dsw-alias-border-l1)",color:"var(--dsw-alias-label-primary)",background:"var(--dsw-alias-bg-base,#fff)"}},e("button",{type:"button",className:"cm-btn",autoFocus:!0,"aria-label":u?"Close":"关闭",onClick:()=>n(null),style:{float:"right"}},"×"),o?e(Ua,{key:t.sessionId,state:o,api:t.api,sessionId:t.sessionId}):e("p",{role:s?.error?"alert":"status"},s?.error||(u?"Loading…":"加载中…"),e("button",{type:"button",className:"cm-btn",onClick:()=>t.api.reload()},u?"Retry":"重试"))):null)}function Ps({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=d=>Y(z(d,a),a),l=d=>s("callsTokens",{calls:d.calls,input:q(d.input),cache:q(d.cacheRead+d.cacheWrite),output:q(d.output)}),i=(d,c)=>({calls:d.calls+c.calls,input:d.input+c.input,output:d.output+c.output,cacheRead:d.cacheRead+c.cacheRead,cacheWrite:d.cacheWrite+c.cacheWrite,cost:z(d,a)+c.cost,apiCost:z(d,a)+c.cost}),r=(d,c)=>e("tr",{key:d},e("td",null,d),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},q(c.input)),e("td",{className:"num"},q(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},q(c.output)),e("td",{className:"num"},n(c))),u=d=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,d)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((d,c)=>{const p=i(t[d],o.combined[d]);return e(mt,{key:d,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(p),sub:l(p)})})),...o.sources.map(d=>e("details",{key:d.source},e("summary",null,d.source+" · "+s("cardToday")+" "+n(d.today)+" · "+s("cardMonth")+" "+n(d.month)+" · "+l(d.today)),u(["today","month","total"].map((c,p)=>r(s(["cardToday","cardMonth","cardTotal"][p]),d[c]))),e("p",{className:"cm-note"},s("externalHistory")),u(d.history.map(c=>r(c.date,c))))))}const Re=(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 Ts(t){const{state:s,api:o}=t,a=G(_(s.config)),[n,l]=B(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(n,()=>l(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(Os,{state:s,api:o})):null)}function Os(t){const{state:s,api:o}=t,a=G(_(s.config)),[n,l]=B(null),[i,r]=B({}),[u,d]=B(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const p=b=>{if(n===b){l(null);return}l(b),!(i[b]!==void 0||u.has(b))&&(d(g=>{const h=new Set(g);return h.add(b),h}),o.getDaySessions(b).then(g=>r(h=>({...h,[b]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[b]:"error"}))).finally(()=>d(g=>{const h=new Set(g);return h.delete(b),h})))},f=b=>b.map(g=>e("tr",{key:g.id},zt(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},q(g.input)),e("td",{className:"num"},q(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},q(g.output)),e("td",{className:"num"},Y(z(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(b=>{const g=e("tr",{key:b.date,className:"cm-row-click",onClick:()=>p(b.date)},e("td",null,(n===b.date?"▾ ":"▸ ")+b.date),e("td",{className:"num"},String(b.calls)),e("td",{className:"num"},q(b.input)),e("td",{className:"num"},q(b.cacheRead+b.cacheWrite)),e("td",{className:"num"},q(b.output)),e("td",{className:"num"},Y(z(b,s.config),s.config)));if(n!==b.date)return[g];const h=i[b.date],x=u.has(b.date)&&h===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):h==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(h)||h.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,f(h)));return[g,e("tr",{key:b.date+"-sessions"},e("td",{colSpan:6},x))]}))))}function Ds(t){const{state:s,api:o}=t,a=G(_(s.config)),[n,l]=B(!1),[i,r]=B(100),[u,d]=B("cost-desc"),[c,p]=B(null),[f,b]=B(!1),[g,h]=B(!1),x=Be.useRef(0),S=(v,y)=>{const[O,P]=y==="recent"?["recent","desc"]:y.split("-"),R=++x.current;b(!0),h(!1),o.getTopSessions(v,O,P).then(A=>{R===x.current&&p(Array.isArray(A?.sessions)?A.sessions:[])}).catch(()=>{R===x.current&&h(!0)}).finally(()=>{R===x.current&&b(!1)})},T=()=>{l(v=>{const y=!v;return y&&c===null&&!f&&S(i,u),y})},N=v=>{r(v),(n||c!==null)&&S(v,u)},m=v=>{d(v),(n||c!==null)&&S(i,v)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(n,T,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:u,onChange:v=>m(v.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(i),onChange:v=>N(Number(v.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),f?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(v=>e("tr",{key:v.date+":"+v.id},e("td",null,v.date),zt(v,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(v.calls)),e("td",{className:"num"},q(v.input)),e("td",{className:"num"},q((v.cacheRead??0)+(v.cacheWrite??0))),e("td",{className:"num"},q(v.output)),e("td",{className:"num"},Y(z(v,s.config),s.config)))))))):null)}function Bs(t){const{state:s}=t,o=G(_(s.config)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(l=>e("tr",{key:l.id},zt(l,n,o),e("td",{className:"num"},String(l.calls)),e("td",{className:"num"},q(l.input)),e("td",{className:"num"},q(l.cacheRead+l.cacheWrite)),e("td",{className:"num"},q(l.output)),e("td",{className:"num"},Y(z(l,s.config),s.config)))))))}function zt(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",l=a.length>0?a:n,i=a.length>0?a+" · "+t.id:t.id;return e("td",{title:i},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},l),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const Rs={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function Ls(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=o?.budget??l.budget,r=Number(l.exchangeRate),d=(s.budgetUsed??(i.period==="day"?z(s.today,l):i.period==="all"?z(s.total,l):z(s.month,l)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(i.amount)||0),p=i.enabled&&c>0?Math.min(999,d/c*100):null,f=p===null?"ok":p>=100?"over":p>=80?"warn":"ok",b=(x,S)=>{o!==null&&a({...o,budget:{...o.budget??l.budget,[x]:S}})},g=i.period==="custom"?i.customStart+" → "+(i.customEnd??n("periodDay")):null,h=i.enabled&&p!==null?n("budgetStatus",{period:n(qe[i.period]??"periodMonth"),amount:me(c,l),used:me(d,l),pct:p.toFixed(1)})+(f==="over"?n("overLimit"):f==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:i.enabled===!0,onChange:x=>b("enabled",x.target.checked)}),e("span",null,n("enableBudget")))),i.enabled?e(L,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(f==="ok"?"":f),style:{width:(p===null?0:Math.min(100,p))+"%"}})),e("div",{className:"cm-budget-line"+(f==="over"?" over":"")+" cm-num"},h),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ne({value:i.amount},x=>b("amount",x))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:i.period,onChange:x=>b("period",x.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),i.period==="custom"?e(L,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:i.customStart??"",onChange:x=>b("customStart",x.target.value===""?null:x.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:i.customEnd??"",onChange:x=>b("customEnd",x.target.value===""?null:x.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function Es(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=(c,p)=>{o!==null&&a({...o,[c]:p})},r=o===null?l:{...l,...o},u=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),p=Date.now();if(Number.isFinite(c)&&p<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const f=r.peakWindows??[],b=lt(p,f,r.peakHolidays);return b===null?n("offPeakActive"):b.holiday===!0?n("holidayAllOffPeak"):b.weekend===!0?n("weekendAllOffPeak"):b.inPeak?n("peakActive"):n("offPeakActive")})(),d=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(_(r)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:u}):n("noPeakWindows",{status:u});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>i("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>i("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>i("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>i("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const p=Number(c.target.value);Number.isInteger(p)&&p>=1&&p<=30&&i("peakAlertAhead",p)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>i("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>i("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{i("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?ct(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},d),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>i("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ne(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const l=Number(n);Number.isFinite(l)&&l>=0&&s(l)}})}function Kt(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:l,t:i}=t,r=tt(o),u=f=>{const b={...tt(f)};if(Array.isArray(f.rateHistory)){const g=f.rateHistory.filter(h=>Date.parse(h.before)<=Date.now());g.length>0?b.rateHistory=g:delete b.rateHistory}return b},d=(f,b,g)=>{if(g===null){if(a){const O=u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),P={...O[f]??{}};delete P[b];const R={...O};Object.keys(P).length>0?R[f]=P:delete R[f],l({...n,prices:{...n.prices,default:R}});return}const N={...n.prices.models},m=u(N[s]??{cacheHit:0,cacheMiss:0,output:0}),v={...m[f]??{}};delete v[b];const y={...m};Object.keys(v).length>0?y[f]=v:delete y[f],N[s]=y,l({...n,prices:{...n.prices,models:N}});return}const h=Math.max(0,g);if(a){let m={...u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(f==="base")m[b]=h;else{const v={...m[f]??{},[b]:h};m={...m,[f]:v}}l({...n,prices:{...n.prices,default:m}});return}const x={...n.prices.models},S=u(x[s]??{cacheHit:0,cacheMiss:0,output:0});let T={...S};if(f==="base")T[b]=h;else{const N={...S[f]??{},[b]:h};T={...S,[f]:N}}x[s]=T,l({...n,prices:{...n.prices,models:x}})},c=()=>{const f={...n.prices.models};delete f[s],l({...n,prices:{...n.prices,models:f}})},p=(f,b)=>{const g=b==="base"?r:r[b]??null,h=b==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:b},e("span",null,f),ne({value:g?.cacheHit??null,emptyMode:h},x=>d(b,"cacheHit",x)),ne({value:g?.cacheMiss??null,emptyMode:h},x=>d(b,"cacheMiss",x)),ne({value:g?.output??null,emptyMode:h},x=>d(b,"output",x)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(L,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},i("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},i("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},i("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatCached")),e("span",null,i("flatInput")),e("span",null,i("flatOutput"))),p(i("tierBase"),"base"),p(i("tierOffPeak"),"offPeak"),p(i("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},i("datedPriceNote")):null)}const Ha={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 qs(t,s,o="USD"){if(t=tt(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");o==="CNY"&&t.cny&&(t=t.cny);const a=l=>(o==="CNY"?"¥":"$")+String(l),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function Is(t){const{state:s,draft:o,setDraft:a,t:n}=t,[l,i]=B(!1),[r,u]=B({}),d=s.priceCatalog;if(d===null||typeof d!="object")return null;const c=o?.prices??s.config.prices,p=o?.priceTableDisplay??s.config.priceTableDisplay??{},f=(y,O)=>{const P=p[y+":"+O];return typeof P=="boolean"?P:y==="deepseek"},b=(y,O,P)=>{o!==null&&a({...o,priceTableDisplay:{...p,[y+":"+O]:P}})},g=(y,O)=>y==="deepseek"?c.models?.[O]!==void 0:c.providers?.[y]?.models?.[O]!==void 0,h=(y,O,P)=>{if(o===null)return;const R=JSON.parse(JSON.stringify(P));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[O]:R}}});return}const A={...o.prices.providers??{}},I=A[y]??{};A[y]={...I,models:{...I.models??{},[O]:R}},a({...o,prices:{...o.prices,providers:A}})},x=(y,O)=>{if(o===null)return;if(y==="deepseek"){const A={...o.prices.models};delete A[O],a({...o,prices:{...o.prices,models:A}});return}const P={...o.prices.providers??{}},R=P[y];if(R!==void 0&&R.models!==void 0){const A={...R.models};delete A[O],P[y]={...R,models:A},a({...o,prices:{...o.prices,providers:P}})}},S=Object.keys(d).sort((y,O)=>y==="deepseek"?-1:O==="deepseek"?1:y.localeCompare(O)),T=y=>Object.values(d[y]).reduce((O,P)=>O+Object.keys(P).length,0),N=new Set(Object.values(d.deepseek??{}).flatMap(y=>Object.keys(y))),m=Object.keys(c.models??{}).filter(y=>!N.has(y)).sort(),v=(y,O,P)=>{const R=g(y,O),A=f(y,O),I=R?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:A,onChange:k=>b(y,O,k.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(R&&!A&&o!==null){const k=y==="deepseek"?e(Kt,{key:O,modelId:O,entry:c.models[O],isDefault:!1,draft:o,setDraft:a,t:n}):e(Wa,{key:O,provider:y,modelId:O,entry:c.providers?.[y]?.models?.[O],draft:o,setDraft:a,t:n});return e("div",{key:O,className:"cm-catalog-mounted"},I,k)}return e("div",{key:O,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},O),e("span",{className:"cm-catalog-price"},qs(P,n,y==="deepseek"||P?.cny?c.currency:"USD")),R?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,I,e("button",{className:"cm-btn small",disabled:!R&&P?.unpriced===!0,onClick:()=>R?x(y,O):h(y,O,P)},n(R?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>i(y=>!y)},n(l?"catalogCollapse":"catalogOpen"))),l?e(L,null,e("p",{className:"cm-note"},n("catalogNote")),S.map(y=>{const O=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>u(P=>({...P,[y]:!O}))},e("span",null,(O?"▾ ":"▸ ")+(Ha[y]??y)+" · "+T(y))),O?e(L,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(d[y]).sort().map(P=>e("div",{key:P},e("div",{className:"cm-catalog-family"},P),Object.keys(d[y][P]).sort().map(R=>v(y,R,d[y][P][R])))),y==="deepseek"&&m.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),m.map(P=>v("deepseek",P,null))):null):null)})):null)}const Qa=t=>t==="zen"?"go":t,Gt=t=>{const s=t.indexOf(":");return s<=0?t:Qa(t.slice(0,s).toLowerCase())+t.slice(s)};function Fa(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],l=d=>Number.isFinite(Number(d))&&Number(d)>0?Number(d):0,i=(d,c,p)=>{if(!p||typeof p!="object")return;const f=d[c]??(d[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)f[g]+=l(p[g]);const b=c.indexOf(":");f.apiCost+=l(p.apiCost??(Fe(b>0?c.slice(0,b):"deepseek",b>0?c.slice(b+1):c,s)==="plan"?0:p.cost))},r=d=>{if(!d||typeof d!="object")return{};if(d.byProviderModel&&Object.keys(d.byProviderModel).length)return d.byProviderModel;if(d.byModel&&Object.keys(d.byModel).length)return Object.fromEntries(Object.entries(d.byModel).map(([p,f])=>[p.includes(":")?p:"deepseek:"+p,f]));const c={};for(const p of Array.isArray(d.sessions)?d.sessions:[])if(!(!p||typeof p!="object"))if(p.byProviderModel&&Object.keys(p.byProviderModel).length)for(const[f,b]of Object.entries(p.byProviderModel))i(c,f,b);else i(c,(p.provider||"deepseek")+":"+(p.model||"unknown"),p);return Object.keys(c).length?c:n.some(p=>l(d[p])>0)?{"deepseek:legacy":d}:{}};return(d=>{const c={},p=f=>{for(const[b,g]of Object.entries(f??{}))i(c,b,g)};if(d==="today")p(r(t.today));else{const f=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const b of t.history??[]){const g=Date.parse(b.date+"T00:00:00Z");g<=f&&g>=f-76896e5&&p(r(b))}}return Object.entries(c).map(([f,b])=>{const g=f.indexOf(":"),h=(g>0?f.slice(0,g):"deepseek").toLowerCase(),x=g>0?f.slice(g+1):f,S=b.input+b.output+b.cacheRead+b.cacheWrite+b.reasoning,T=b.cacheRead+b.input;return{label:f==="deepseek:legacy"?o("modelStatsLegacy"):h==="deepseek"||h===""?x:Qa(h)+":"+x,key:f,...b,tokens:S,cls:Fe(h,x,s),hitRate:T>0?b.cacheRead/T:null,cacheUnreported:Mn(b),blended:S>0&&b.cost>0?b.cost/S*1e6:null,perUsd:b.cost>0?S/b.cost:null}}).filter(f=>f.tokens>0||f.cost>0)})(a).sort((d,c)=>c.cost-d.cost||c.tokens-d.tokens)}function js(t){const{state:s,config:o,t:a,initialTab:n,draft:l,setDraft:i}=t,[r,u]=B(n==="history"?"history":"today"),[d,c]=B(!1),p=Fa(s,o,a,r),f=m=>(Math.max(0,Math.min(1,m))*100).toFixed(1)+"%",b=p.reduce((m,v)=>Math.max(m,v.cost),0),g=p.reduce((m,v)=>Math.max(m,v.tokens),0),h=p.reduce((m,v)=>Math.max(m,v.perUsd??0),0),x=(m,v)=>e("button",{className:"cm-mstats-tab"+(r===m?" active":""),onClick:()=>u(m)},v),S=m=>m.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,T=m=>e("select",{className:"cm-input",title:a("billingClassLabel"),value:o.planBilling?.models?.[m.key]??"auto",disabled:l===null,onChange:v=>{const y={...l.planBilling?.models??{}};v.target.value==="auto"?delete y[m.key]:y[m.key]=v.target.value,i({...l,planBilling:{...l.planBilling,models:y}})}},e("option",{value:"auto"},a("billingClassAuto")),e("option",{value:"plan"},a("billingClassPlan")),e("option",{value:"api"},a("billingClassApi"))),N=(m,v,y,O,P)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:m},m,P??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+y,style:{width:f(v)}})),e("span",{className:"cm-mstats-val"},O));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(d,()=>c(!d),a("modelStatsTitle"))),d?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},x("today",a("modelStatsToday")),x("history",a("modelStatsHistory"))),p.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(L,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),p.map(m=>e(L,{key:"c:"+m.label},N(m.label,b>0?m.cost/b:0,"cost",Y(m.cost,o),e(L,null,S(m),T(m),m.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...p].sort((m,v)=>v.tokens-m.tokens).map(m=>e("div",{className:"cm-mstats-row",key:"t:"+m.label},e("span",{className:"cm-mstats-name",title:m.label},m.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:f(g>0?m.input/g:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:f(g>0?(m.cacheRead+m.cacheWrite)/g:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:f(g>0?(m.output+m.reasoning)/g:0)}})),e("span",{className:"cm-mstats-val"},q(m.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...p].sort((m,v)=>(v.hitRate??-1)-(m.hitRate??-1)).map(m=>e(L,{key:"h:"+m.label},N(m.label,m.hitRate??0,"hit",m.cacheUnreported?a("modelStatsHitUnreported"):m.hitRate===null?"—":(m.hitRate*100).toFixed(1)+"%",m.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...p].sort((m,v)=>(v.perUsd??-1)-(m.perUsd??-1)).map(m=>e(L,{key:"v:"+m.label},N(m.label,h>0?(m.perUsd??0)/h:0,"value",m.perUsd===null?"—":q(m.perUsd)+" tok/$"+(m.blended!==null?" · "+a("modelStatsBlended",{price:"$"+m.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function Us(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 Hs(t,s){if(t==="go")return"OpenCode Go";const o=Le.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const _a=["fiveHour","weekly","monthly","daily"];function Qs(t,s){const o=new Map,a=n=>{const l=new Date(n),i=r=>String(r).padStart(2,"0");if(s==="monthly")return l.getFullYear()+"-"+i(l.getMonth()+1);if(s==="weekly"){const r=new Date(l.getFullYear(),l.getMonth(),l.getDate()-(l.getDay()+6)%7);return r.getFullYear()+"-"+i(r.getMonth()+1)+"-"+i(r.getDate())}return l.getFullYear()+"-"+i(l.getMonth()+1)+"-"+i(l.getDate())};for(const n of Object.values(t??{}))for(const l of n??[]){if(l===null||typeof l!="object"||!(l.tokens>0)&&!(l.cost>0))continue;const i=a(Number(l.t1)||Number(l.t0)),r=o.get(i)??{key:i,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(l.tokens)||0,r.cost+=Number(l.cost)||0,r.pct+=Number(l.pct)||0,r.intervals+=1,o.set(i,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,l)=>n.key<l.key?-1:n.key>l.key?1:0)}function Fs(t){const{state:s,config:o,t:a}=t,[n,l]=B(!1),[i,r]=B("daily"),u=_(o),d=s?.planStats,c=d!=null&&typeof d.providers=="object"?d.providers:{},p=Object.keys(c).sort(),f=y=>Y(Number(y)||0,o??s?.config),b=y=>y.method==="none"||y.per1Tokens===null?"—":q(y.per1Tokens)+" tok · "+f(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":q(y.fullTokens)+" tok · "+f(y.fullCost),h=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),x=y=>{let O=h(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(O=a("planStatsMethodSampleAt",{method:O,time:new Date(Number(y.sampleAt)).toLocaleString(u==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(O+=" · "+a("planStatsConfidenceLow")),O},S=([y,O,P])=>e("tr",{key:O+":"+y},e("td",null,Us(y,u)),e("td",{className:"num"},Math.round(P.percent*10)/10+"%"),e("td",{className:"num"},q(P.localTokens)+" tok · "+f(P.localCost)),e("td",{className:"num"},b(P)),e("td",{className:"num"},g(P)),e("td",{className:"num cm-plan-reset"},P.resetsAt.length>0?a("planStatsResets",{time:new Date(P.resetsAt).toLocaleString(u==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},x(P))),T=n?p.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,O])=>({winKey:y,list:O})):[],N=Qs(Object.fromEntries(T.map(y=>[y.winKey,y.list])),i),m=N.reduce((y,O)=>Math.max(y,O.fullTokens??0),0),v=(y,O)=>e("button",{key:y,className:"cm-mstats-tab"+(i===y?" active":""),onClick:()=>r(y)},O);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(n,()=>l(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},p.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(L,null,p.map(y=>{const O=c[y]?.windows??{},P=[..._a.filter(R=>O[R]!==void 0).map(R=>[R,y,O[R]]),...Object.keys(O).filter(R=>!_a.includes(R)).map(R=>[R,y,O[R]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},Hs(y,a),e("span",{className:"cm-plan-updated"},(()=>{const R=Number(c[y]?.generatedAt)||Number(d?.generatedAt)||0;return R>0?new Date(R).toLocaleTimeString(u==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,P.map(S))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},v("daily",a("planStatsDaily")),v("weekly",a("planStatsWeekly")),v("monthly",a("planStatsMonthly"))),N.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(L,null,[...N].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(m>0?(y.fullTokens??0)/m*100:0).toFixed(1)+"%"}})),e(X,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":q(y.fullTokens),per1:y.per1Tokens===null?"—":q(y.per1Tokens),tokens:q(y.tokens),cost:f(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":q(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Wa(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:l,t:i}=t,r=p=>{const f={...n.prices.providers??{}},b=f[s]??{};f[s]={...b,models:p},l({...n,prices:{...n.prices,providers:f}})},u=(p,f)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}};b[o]={...b[o]??{},[p]:Math.max(0,f)},r(b)},d=(p,f)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}},g=b[o]??{};b[o]={...g,cny:{...g.cny,[p]:Math.max(0,f)}},r(b)},c=()=>{if(n===null)return;const p={...(n.prices.providers??{})[s]?.models??{}};delete p[o],r(p)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(L,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},i("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:c},i("unmountBtn")))),a?.unpriced===!0?null:e(L,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatInput")),e("span",null,i("flatCached")),e("span",null,i("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ne({value:a?.input??null,emptyMode:"ignore"},p=>u("input",p)),ne({value:a?.cachedInput??null,emptyMode:"ignore"},p=>u("cachedInput",p)),ne({value:a?.output??null,emptyMode:"ignore"},p=>u("output",p))),a?.cny?e("div",{className:"cm-price-row"},e("span",null,"CNY"),ne({value:a.cny.cacheMiss,emptyMode:"ignore"},p=>d("cacheMiss",p)),ne({value:a.cny.cacheHit,emptyMode:"ignore"},p=>d("cacheHit",p)),ne({value:a.cny.output,emptyMode:"ignore"},p=>d("output",p))):null))}const Ye=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Yt=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function _s(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r,u]=Ve(a,()=>o.refreshBalance()),d=s.balance,c=s.config,p=s.reconcile,f=(n?.balance??c.balance??{}).reconcile!==!1,b=x=>{n===null||typeof l!="function"||l({...n,balance:{...n.balance??c.balance??{},reconcile:x.target.checked}})},g=x=>Se(x,c,d?.currency),h=d.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:g(d.totalBalance),granted:g(d.grantedBalance),toppedUp:g(d.toppedUpBalance),time:d.fetchedAt>0?new Date(d.fetchedAt).toLocaleTimeString():"—"}))):d.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:d.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:u,disabled:i},a(i?"refreshing":"refreshBalance"))),h,e("label",null,a("balanceApiKey")),e(De,{target:"balance",configured:d.keyConfigured,source:d.keySource,t:a,api:o,placeholder:"sk-…"}),e("p",{className:"cm-hint"},a("balanceKeyHint")),p!==void 0&&p.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+p.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:f,onChange:b}),a("reconcileLabel")),Yt(r))}function pt(t){const{name:s,enabled:o,saved:a,busy:n,open:l,statusNode:i,configNode:r,errorMsg:u,onToggle:d,onRefresh:c,onLogin:p,loginRequired:f,onRemove:b,onToggleOpen:g,t:h}=t,x=r!=null,S=f?p:c,T=h(n===!0?f?"loggingIn":"refreshing":f?"loginCodingPlan":"refresh");return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":h("enable")+": "+s,checked:o===!0,onChange:N=>d(N.target.checked)})),e("div",{className:"cm-quota-name"},x?Re(l===!0,g,s):e("h3",{className:"cm-h"},s)),b?e("button",{className:"cm-btn small",onClick:b},h("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:S,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?h("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?h("quotaRefreshReady"):h(f?"loginCodingPlan":"refresh")},T)),i,x&&l===!0?e("div",{className:"cm-collapse-body"},r):null,u!=null?e("div",{className:"cm-msg "+u.kind},u.text):null)}function Ve(t,s){const[o,a]=B(!1),[n,l]=B(null),i=Ne(!1);return[o,n,async()=>{if(!i.current){i.current=!0,a(!0),l(null);try{const u=await s();l({kind:u.ok?"ok":"err",text:u.message})}catch(u){l({kind:"err",text:t("syncFailed",{message:u?.message??String(u)})})}finally{i.current=!1,a(!1)}}}]}const Ws=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},za=(t,s,o,a,n,l=s)=>{if(typeof o?.percent!="number")return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const i=Math.max(0,Math.min(100,Number(o.percent)||0)),r=fe(i,a),u=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),u?e("span",{className:"cm-go-reset"},u):null)};function zs(t){const{state:s,api:o,t:a,entry:n,index:l,canRemove:i,onPatch:r,onRemove:u}=t,d=n.adapter==="aliyun",[c,p]=B(!1),f=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[b,g]=B(f),[h,x]=B(()=>(n.allowedHosts??[]).join(", ")),[S,T]=B({}),N=Ne(!1),m=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(D=>D.index===l)??null,O=n.enabled===!0,P=()=>{p(D=>!D)};ee(()=>{c&&!N.current&&(g(f()),x((n.allowedHosts??[]).join(", ")),T({})),N.current=c},[c]);const R=(D,K)=>r({[D]:K}),A=(D,K)=>r({request:{...n.request??{},[D]:K}}),I=d?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(D=>typeof D=="string"?[...D.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(K=>K[1]):[]))],k=(D,K)=>{g(w=>({...w,[D]:K}));try{const w=D==="body",E=w&&!K.trim()?void 0:JSON.parse(K);if(!w&&(E===null||typeof E!="object"||Array.isArray(E)))throw new Error("invalid");if(D==="headers"&&Object.values(E).some(F=>typeof F!="string"))throw new Error("invalid");T(F=>({...F,[D]:""})),D==="extract"?R(D,E):A(D,w?E===void 0?void 0:K:E)}catch{T(w=>({...w,[D]:a("customBalanceInvalidJson")}))}},j=(D,K,w,E)=>!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(K)),E&&e("span",{className:"cm-hint"},a(E)),e("textarea",{className:"cm-input",rows:w,value:b[D],onChange:F=>k(D,F.target.value)}),S[D]?e("span",{className:"cm-hint err"},S[D]):null),Ce=D=>{x(D);const K=D.split(/[\s,;]+/).map(w=>w.trim()).filter(w=>w.length>0);R("allowedHosts",K)},[de,Ae,J]=Ve(a,()=>(m.customBalances??[])[l]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(l)),M=y!==null&&y.status==="ok"?e(L,null,m.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(Rt,{segments:Bt(s,m,y,n),direction:ie(m,"balance")}),e("div",{className:"cm-bal-line"},Et(y,m,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:We(y.remaining,m,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),U=e(L,null,e("p",{className:"cm-note"},a(d?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:_e(m,y,n)!=="USD",onChange:D=>R("convertToDisplayCurrency",D.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([D,K])=>e("div",{key:D,className:"cm-field"},e("label",null,a(K)),e("input",{className:"cm-input",value:n[D]??"",onChange:w=>R(D,w.target.value)}))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:D=>R("unit",D.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:D=>R("display",D.target.value)},...Ye(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ne({value:n.refreshMinutes??15},D=>R("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D)))))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:D=>A("method",D.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:D=>A("url",D.target.value)})),j("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&j("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),I.length>0?e(L,null,!d&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),I.map(D=>e(De,{key:"cb-var-"+D,target:"customVar:"+D,configured:(s.customVarStatus?.[D]?.configured??!1)===!0,source:s.customVarStatus?.[D]?.source??"",t:a,api:o,placeholder:"{{"+D+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:h,placeholder:"api.example.com, relay.example.org",onChange:D=>Ce(D.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),j("extract","customBalanceExtract",8)));return e(pt,{name:`#${l+1} · `+(Lt(n,_(m))||a("customBalanceTitle")),enabled:O,saved:JSON.stringify(n)===JSON.stringify(m.customBalances?.[l])?m.customBalances[l]:null,busy:de,open:c,statusNode:M,configNode:U,errorMsg:Ae,onToggle:D=>R("enabled",D),onRefresh:J,onRemove:i?u:null,onToggleOpen:P,t:a})}function Ka({config:t,draft:s,setDraft:o,t:a,api:n}){const l=s?.goQuota??t.goQuota,i=(r,u)=>{s&&o({...s,goQuota:{...l,[r]:u}})};return e(L,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,u])=>e("div",{key:r,className:"cm-field"},e("label",null,a(u)),e("select",{className:"cm-input",value:l[r],onChange:d=>i(r,d.target.value)},r==="display"?Ye(a):["rolling","weekly","monthly"].map((d,c)=>e("option",{key:d,value:d},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ne({value:l.refreshMinutes},r=>i("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function Ks(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r]=B(!1),u=s.goQuota,d=s.config,c=n?.goQuota?.enabled??d.goQuota?.enabled??!0,p=(m,v)=>{n!==null&&l({...n,goQuota:{...n.goQuota??d.goQuota,[m]:v}})},[f,b,g]=Ve(a,()=>o.refreshGoQuota()),h=d.goQuota?.main==="weekly"||d.goQuota?.main==="monthly"?d.goQuota.main:"rolling",x=[h,...["rolling","weekly","monthly"].filter(m=>m!==h)],S=m=>m==="rolling"?"goWindowRolling":m==="weekly"?"goWindowWeekly":"goWindowMonthly",T=m=>m==="rolling"?u.rolling:m==="weekly"?u.weekly:u.monthly,N=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},x.map(m=>za(a,a(S(m)),T(m),ie(d,"go"),m===h)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||a("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(pt,{name:a("goQuotaTitle"),enabled:c,saved:d.goQuota,busy:f,open:i,statusNode:N,errorMsg:b,configNode:e(Ka,{config:d,draft:n,setDraft:l,t:a,api:o}),onToggleOpen:()=>r(m=>!m),onToggle:m=>p("enabled",m),onRefresh:g,t:a})}const Gs=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Ys(t){const{state:s,api:o,t:a,draft:n,setDraft:l,index:i}=t,r=s.config,d=(n??r).gatewayQuotas?.sources??[],c=d[i]??{},f=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(A=>A.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},b=Gs(c,s.customVarStatus),[g,h]=B(!1),[x,S,T]=Ve(a,()=>o.refreshGatewayQuota(c.id)),N=A=>{n!==null&&l({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:A}})},m=A=>N(d.map((I,k)=>k===i?{...I,...A}:I)),v=(A,I,k)=>e("div",{className:"cm-field"},e("label",null,A),e("input",{className:"cm-input",value:I??"",onChange:k})),y=(A,I)=>{const k=Ge(A?.label||A?.id||a("gatewaySourceUnknown"),A,ie(r,"plan"),a);return e(L,{key:A?.id||I},k.row,A?.resetsAt?e("div",{className:"cm-note"},Ke(A,a)):null)},O=(A,I)=>e("div",{key:A.id||I,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},A.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),P=A=>A==null?null:e(L,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},A.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),(A.packages??[]).map(O)),R=(A,I)=>e("div",{key:A.id||I,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(la[A.provider]??A.provider??a("gatewaySourceUnknown"))+" · "+(A.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},A.status)),A.plan?e("div",{className:"cm-note"},A.plan):null,A.windows.length>0?e("div",{className:"cm-go-list"},A.windows.map(y)):null,P(A.credits),A.message?e("div",{className:"cm-note"},A.message):null);return e(pt,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(A=>A.id===c.id),busy:x,open:g,errorMsg:S,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(f.status??a("gatewaySourceUnknown"))+(f.serverVersion?" · "+f.serverVersion:"")+(f.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(f.fetchedAt).toLocaleTimeString()}):"")+(f.message?" · "+f.message:"")),configNode:e(L,null,e("div",{className:"cm-grid"},v(a("gatewaySourceLabel"),c.label,A=>m({label:A.target.value})),v(a("gatewaySourceBaseURL"),c.baseURL,A=>m({baseURL:A.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:A=>m({display:A.target.value})},...Ye(a))),v(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),A=>m({allowedHosts:A.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:A=>m({antigravityOnlyGemini:A.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),b?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+b,configured:s.customVarStatus?.[b]?.configured===!0,source:s.customVarStatus?.[b]?.source??"",t:a,api:o,placeholder:b})):null,f.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+f.unsupportedProviders.join(", ")):null,f.accounts.length>0?f.accounts.map(R):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:A=>m({enabled:A}),onRefresh:T,onRemove:()=>N(d.filter((A,I)=>I!==i)),onToggleOpen:()=>h(A=>!A),t:a})}const Le=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function Vs(t){const{state:s,api:o,t:a,draft:n,setDraft:l,planId:i,labelKey:r}=t,u=s.config,d=s.codingPlans??{},c=n?.codingPlans?.[i]??u.codingPlans?.[i]??{},p=d[i]??{status:"off",message:"",fetchedAt:0,windows:{}},f=c.enabled===!0,[b,g]=B(!1),h=i==="qwen"&&u.codingPlans?.qwen?.quotaSource==="bailian"&&c.quotaSource==="bailian"&&p.quotaSource==="bailian"&&p.loginRequired===!0,[x,S,T]=Ve(a,()=>h?o.loginCodingPlan(i):o.refreshCodingPlan(i)),N=(M,U)=>{if(n===null)return;const D=n.codingPlans??u.codingPlans??{};l({...n,codingPlans:{...D,[i]:{...D[i]??{},[M]:U}}})},[m,v]=B(""),[y,O]=B({}),P=M=>M?.rates!==null&&typeof M?.rates=="object"&&!Array.isArray(M.rates)?M.rates:{},R=["input","cachedInput","output"],A=M=>y[M]??P(c)[M]??{},I=M=>R.every(U=>Number.isFinite(Number(M[U]))&&Number(M[U])>0),k=(M,U,D)=>{if(n===null)return;const K={...A(M),[U]:String(D)};O(te=>({...te,[M]:K}));const w=R.every(te=>String(K[te]??"").trim()==="");if(!w&&!I(K))return;const E=n.codingPlans??u.codingPlans??{},F={...(E.qwen??{}).rates??{}};w?delete F[M]:F[M]=Object.fromEntries(R.map(te=>[te,Number(K[te])])),l({...n,codingPlans:{...E,qwen:{...E.qwen??{},rates:F}}})},j=M=>{n!==null&&O(U=>({...U,[M]:U[M]??P(c)[M]??{}}))},Ce=M=>{if(n===null)return;O(K=>{const w={...K};return delete w[M],w});const U=n.codingPlans??u.codingPlans??{},D={...(U.qwen??{}).rates??{}};delete D[M],l({...n,codingPlans:{...U,qwen:{...U.qwen??{},rates:D}}})},de=p.windows!==null&&typeof p.windows=="object"?p.windows:{},Ae=f===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):p.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(de).length>0?i==="minimax"&&(ze(de).five!=null||ze(de).seven!=null)?e(Ra,{five:ze(de).five,seven:ze(de).seven,fetchedAt:p.fetchedAt,t:a,wide:!0,direction:ie(u,"plan")}):Object.entries(de).map(([M,U])=>za(a,M.replace(/_/g," "),U,ie(u,"plan"),!1,M)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:p.fetchedAt>0?new Date(p.fetchedAt).toLocaleTimeString():"—"}))):p.status==="error"?e("div",{className:"cm-bal-line err"},p.message||a("unknownError")):p.status==="off"&&p.message?e("p",{className:"cm-note"},p.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),J=e(L,null,i==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:M=>N("baseUrl",M.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,i==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:M=>N("quotaSource",M.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:i==="minimax"?"both":"settings",onChange:M=>N("display",M.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),i!=="scnet"&&(i!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ne({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},M=>{N("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(M))))})):null,i==="scnet"||i==="qwen"&&(c.quotaSource??"local")==="local"?e(L,null,e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:i==="qwen"?5e5:24e4,onChange:M=>{const U=Number(M.target.value);Number.isFinite(U)&&U>0&&N("planCredits",Math.floor(U))}})),e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:M=>N("planStart",M.target.value)})),i==="qwen"?e(L,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(P(c)),...Object.keys(y)])].sort().map(M=>e("div",{key:M,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},M),R.map(U=>e("input",{key:U,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:A(M)[U]??"",placeholder:a("qwenRate_"+U),"aria-label":M+" · "+a("qwenRate_"+U),onChange:D=>{const K=D.target.value;k(M,U,K)}})),e("button",{className:"cm-btn small",onClick:()=>Ce(M)},a("overrideRemove")),M in y&&!I(A(M))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:m,onChange:M=>v(M.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const M=m.trim();M.length!==0&&(j(M),v(""))},disabled:m.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(i==="qwen"?"qwenLocalNote":"scnetLocalNote"))):i==="qwen"?null:i==="volcengine"?e(L,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:p.keyConfigured===!0,source:p.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:p.keyConfigured===!0,source:p.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(L,null,e("div",{className:"cm-field"},e("label",null,i==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+i,configured:p.keyConfigured===!0,source:p.keySource,t:a,api:o,placeholder:i==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(pt,{name:a(r),enabled:f,saved:u.codingPlans?.[i],busy:x,open:b,errorMsg:S,statusNode:Ae,configNode:J,onToggle:M=>N("enabled",M),onRefresh:T,onLogin:T,loginRequired:h,onToggleOpen:()=>g(M=>!M),t:a})}function Js(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,i=s.config,r=n??i,u=r.codingPlans??{},d=r.gatewayQuotas?.sources??[],c=n?.customBalances??i.customBalances??[],p=N=>{n!==null&&l({...n,customBalances:N,...N.length===0?{customBalance:{...i.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},f=Ne({next:0,keys:[]}).current;for(;f.keys.length<c.length;)f.keys.push(f.next++);f.keys.length=c.length;const b=N=>{f.keys.splice(N,1),p(c.filter((m,v)=>v!==N))},g=(N,m)=>p(c.map((v,y)=>y===N?{...v,...m}:v)),h=(N="custom")=>{c.length>=8||p([...c,{...N==="aliyun"?{adapter:N}:{},enabled:!1,label:N==="aliyun"?"千问 / 阿里云":"",labelEn:N==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:N==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:N==="aliyun"?"https://business.aliyuncs.com/":"",method:N==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},x=()=>{d.length>=4||n===null||l({...n,gatewayQuotas:{...n.gatewayQuotas??i.gatewayQuotas??{},sources:[...d,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:xt,allowedHosts:[],allowInsecureHttp:!1}]}})},S=[...d.map((N,m)=>({kind:"gateway",key:"gw-"+(N.id??m),index:m,enabled:N.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Le.map(N=>({kind:"plan",key:"plan-"+N.id,planId:N.id,labelKey:N.labelKey,enabled:u[N.id]?.enabled===!0})),...c.map((N,m)=>({kind:"custom",key:"cb-"+f.keys[m],index:m,enabled:N.enabled===!0}))],T=N=>N.kind==="plan"?e(Vs,{key:N.key,planId:N.planId,labelKey:N.labelKey,state:s,api:o,t:a,draft:n,setDraft:l}):N.kind==="go"?e(Ks,{key:N.key,state:s,api:o,t:a,draft:n,setDraft:l}):N.kind==="gateway"?e(Ys,{key:N.key,index:N.index,state:s,api:o,t:a,draft:n,setDraft:l}):e(zs,{key:N.key,state:s,api:o,t:a,entry:c[N.index],index:N.index,canRemove:!0,onPatch:m=>g(N.index,m),onRemove:()=>b(N.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ws(S).map(T)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:x,disabled:d.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>h(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>h("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const Zs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ga=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function Vt(t){const s=t.useCost?t.useCost(m=>m):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=_(a),l=t.t??G(n),i=Array.isArray(o.history)?o.history:[];if(i.length===0)return e("div",null,e("h3",{className:"cm-h"},l("usageTitle")),e("p",{className:"cm-empty"},l("usageEmpty")));const r=o.meta?.dayKey??"",u=new Map(i.map(m=>[m.date,m])),d=m=>{const v=y=>String(y).padStart(2,"0");return m.getFullYear()+"-"+v(m.getMonth()+1)+"-"+v(m.getDate())},c=new Date;c.setHours(0,0,0,0);const p=new Date(c);p.setDate(p.getDate()+(6-(c.getDay()+6)%7));const f=26,b=[],g=[];let h=-1;for(let m=f-1;m>=0;m-=1){for(let y=0;y<7;y+=1){const O=new Date(p);O.setDate(O.getDate()-(m*7+(6-y)));const P=u.get(d(O));b.push(P!==void 0?{day:P,tokens:Ga(P)}:{day:{date:d(O)},tokens:0})}const v=new Date(p);v.setDate(v.getDate()-(m*7+6)),g.push(v.getMonth()!==h?n==="en"?Zs[v.getMonth()]:String(v.getMonth()+1)+"月":""),h=v.getMonth()}const x=Math.max(...b.map(m=>m.tokens),1),S=m=>{const v=m/x;return v<.25?1:v<.5?2:v<.75?3:4},T=m=>{const{day:v,tokens:y}=m,O="cm-ug-cell"+(y>0?" l"+S(y):"")+(v.date===r?" today":""),P=l("usageDay",{date:v.date,tokens:q(y),input:q(v.input??0),cache:q((v.cacheRead??0)+(v.cacheWrite??0)),output:q(v.output??0),calls:v.calls??0,cost:Y(z(v,a),a)});return e(X,{key:v.date,label:P,side:"top",delayMs:200},e("div",{className:O}))},N=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},l("usageTitle")),e("div",{className:"cm-ug-total"},l("usageTotal",{tokens:q(Ga(N)),input:q(N.input??0),cache:q((N.cacheRead??0)+(N.cacheWrite??0)),output:q(N.output??0),calls:N.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+f+",1fr)"}},b.map(T)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+f+",1fr)"}},g.map((m,v)=>e("span",{key:"m"+String(v),className:"cm-ug-monthc"},m))))}function $s(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.api,a=s?.state??null,[n,l]=B(null),[i,r]=B(null),[u,d]=B(!1),[c,p]=B(!1),[f,b]=B(!1),[g,h]=B(""),[x,S]=B(!1),[T,N]=B(!1),[m,v]=B("overview"),[y,O]=B({status:"idle",at:0,error:null}),P=Be.useRef(null),R=Be.useRef(null),A=Be.useRef(null);ee(()=>{if(a!==null){const w=JSON.stringify(a.config);l(E=>{const F=E!==null&&JSON.stringify(E)!==P.current;return F||(R.current=a.config,A.current=a.config),F?{...E,activeLocale:a.config.activeLocale}:JSON.parse(w)}),P.current=w}},[a]),ee(()=>{n!==null&&A.current===null&&R.current!==null&&(A.current=R.current)},[n]),ee(()=>{if(n===null||o===void 0)return;const w=JSON.stringify(n);if(w===P.current)return;O(F=>F.status==="saving"?F:{...F,status:"saving"});const E=setTimeout(()=>{const F={},te=A.current??R.current;if(te!==null&&typeof te=="object")for(const V of Object.keys(n))V!=="activeLocale"&&JSON.stringify(n[V])!==JSON.stringify(te[V])&&(F[V]=n[V]);if(Object.keys(F).length===0){P.current=w,O({status:"saved",at:Date.now(),error:null});return}o.updateConfig(F).then(()=>{P.current=w,te!==null&&typeof te=="object"&&(A.current={...te,...F}),O({status:"saved",at:Date.now(),error:null})},V=>{O({status:"error",at:0,error:V?.message??String(V)})})},600);return()=>{clearTimeout(E)}},[n,o]),ee(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:k("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const I=_({...n??a?.config,activeLocale:s?.locale}),k=G(I);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?k("readingLedger"):k("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},k("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},k("refresh")));const j=a.config,Ce=async()=>{if(!x){S(!0),r(null);try{const w=await o.fetchPrices();if(r({kind:w.ok?"ok":"err",text:w.message}),w.ok&&w.state&&typeof w.state.config=="object"){const E=JSON.stringify(w.state.config);l(JSON.parse(E)),P.current=E}}catch(w){r({kind:"err",text:k("syncFailed",{message:w?.message??String(w)})})}finally{S(!1),d(!1)}}},de=async()=>{if(!x){S(!0);try{await o.resetHistory(),r({kind:"ok",text:k("historyCleared")})}catch(w){r({kind:"err",text:k("clearFailed",{message:w?.message??String(w)})})}finally{S(!1),p(!1)}}},Ae=async()=>{if(!x){S(!0),r(null);try{const w=await o.importLegacyHistory();r({kind:"ok",text:w.message})}catch(w){r({kind:"err",text:k("legacyImportFailed",{message:w?.message??String(w)})})}finally{S(!1),b(!1)}}},J=(w,E)=>{n!==null&&l({...n,[w]:E})},M=()=>{if(n===null)return;const w=g.trim().toLowerCase();if(w.length===0||!/^[a-z0-9_.-]+$/.test(w)||n?.prices.models[w]!==void 0)return;const E={...n.prices.models,[w]:{cacheHit:0,cacheMiss:0,output:0}};l({...n,prices:{...n.prices,models:E}}),h("")},U=n===null?[]:Object.keys(n.prices.models).filter(w=>{const F=(n?.priceTableDisplay??j.priceTableDisplay??{})["deepseek:"+w];return typeof F=="boolean"?F:!0}).map(w=>e(Kt,{key:w,modelId:w,entry:n.prices.models[w]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:l,t:k})),D=[["overview",k("tabOverview")],["statistics",I==="en"?"Cost statistics":"计费统计"],["quotas",k("tabQuotas")],["usage",k("tabUsage")],["pricing",k("tabPricing")],["display",k("tabDisplay")]],K=y.status==="saving"?e("span",{className:"cm-hint"},k("saving")):y.status==="error"?e("span",{className:"cm-msg err"},k("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?k("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):k("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},D.map(([w,E])=>e("button",{key:w,type:"button",role:"tab","aria-selected":String(m===w),className:"cm-tab"+(m===w?" active":""),onClick:()=>v(w)},E))),K),Yt(i),m==="statistics"?e(Ua,{state:a,api:o}):null,m==="overview"?e(L,{key:"overview"},e("div",{className:"cm-cards"},j.hideTodayCost===!0?null:e(mt,{title:k("cardToday"),value:Y(z(a.today,j),j),sub:k("callsTokens",{calls:a.today.calls,input:q(a.today.input),cache:q(a.today.cacheRead+a.today.cacheWrite),output:q(a.today.output)})}),e(mt,{title:k("cardMonth"),value:Y(z(a.month,j),j),sub:k("callsTokens",{calls:a.month.calls,input:q(a.month.input),cache:q(a.month.cacheRead+a.month.cacheWrite),output:q(a.month.output)})}),e(mt,{title:k("cardTotal"),value:Y(z(a.total,j),j),sub:k("cardTotalSub",{calls:a.total.calls})})),e(Ps,{state:a,t:k}),e("p",{className:"cm-note",key:"cards-footnote"},k("cardsFootnote")),(()=>{const w=Rn(a);return w!==null?e("p",{className:"cm-note",key:"tz-hint"},k("timezoneHint",{host:w.hostLabel,browser:w.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:k("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??j).showTotalWithPlan===!0,onChange:w=>{const E=n??j;E!=null&&l({...E,showTotalWithPlan:w.target.checked})}}),e("span",null,k("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},k("todaySessions")),e(Bs,{state:a,t:k})),e(Ls,{state:a,draft:n,setDraft:l,t:k}),(j.balance?.display==="settings"||j.balance?.display==="both")&&j.hideOfficialBalance!==!0?e(_s,{state:a,api:o,t:k,draft:n,setDraft:l}):null):null,m==="quotas"?e(Js,{key:"quotas",state:a,api:o,t:k,draft:n,setDraft:l}):null,m==="usage"?e(L,{key:"usage"},!Xe||(j.usage?.position??"cost")==="cost"?e(Vt,{state:a,t:k,locale:I}):null,e(js,{state:a,config:n??j,t:k,draft:n,setDraft:l}),e(Fs,{state:a,config:n??j,t:k}),e(Ts,{state:a,api:o}),e(Ds,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},k("historyDataTitle")),e("div",{className:"cm-buttons"},f?e(L,null,e("span",{className:"cm-hint"},k("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:Ae,disabled:x},k("apply")),e("button",{className:"cm-btn",onClick:()=>b(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>b(!0),disabled:x},k("importLegacy")),c?e(L,null,e("span",{className:"cm-hint"},k("confirmReset")),e("button",{className:"cm-btn danger",onClick:de,disabled:x},k("confirmClear")),e("button",{className:"cm-btn",onClick:()=>p(!1)},k("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>p(!0),disabled:x},k("clearAllHistory"))),e("p",{className:"cm-note"},k("legacyImportNote")))):null,m==="display"?e(L,{key:"display"},e(As,{draft:n,setDraft:l,t:k}),a?.secretMigration?.pending?.length>0?e(En,{pending:a.secretMigration.pending,t:k}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,k("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:w=>J("locale",w.target.value)},e("option",{value:"auto"},k("localeAuto")),e("option",{value:"zh"},k("localeZh")),e("option",{value:"en"},k("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},k("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},k("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled","codexQuotaSidebar"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:E=>J(w,E.target.checked)}),e("span",null,k(w)))),Xe?e("div",{className:"cm-field"},e("label",null,k("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:w=>{n!==null&&l({...n,usage:{...n.usage??{position:"cost"},position:w.target.value}})}},e("option",{value:"cost"},k("usagePositionCost")),e("option",{value:"general"},k("usagePositionGeneral")),e("option",{value:"section"},k("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,k("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:w=>J("position",w.target.value)},e("option",{value:"dock"},k("positionDock")),e("option",{value:"header"},k("positionHeader")),e("option",{value:"off"},k("off")))),e("div",{className:"cm-field"},e("label",null,k("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:w=>J("sidebar",w.target.value==="on")},e("option",{value:"on"},k("sidebarOn")),e("option",{value:"off"},k("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:w=>J("showSessionId",w.target.checked)}),e("span",null,k("showSessionIdLabel"))),...["hideSessionCostHeader","hideSessionCostDock","hideTurnCost"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:E=>J(w,E.target.checked)}),e("span",null,k(w)))),e("div",{className:"cm-grid-group"},k("groupMoney")),e("div",{className:"cm-field"},e("label",null,k("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:w=>{const E=Rs[w.target.value];E!==void 0&&n!==null&&l({...n,currency:w.target.value,...E})}},e("option",{value:"CNY"},k("currencyCny")),e("option",{value:"USD"},k("currencyUsd")),e("option",{value:"EUR"},k("currencyEur")))),e("div",{className:"cm-field"},e("label",null,k("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:w=>J("symbol",w.target.value)})),e("div",{className:"cm-field"},e("label",null,k("rateLabel")),ne({value:n?.exchangeRate??1,emptyMode:"ignore"},w=>J("exchangeRate",w))),e("div",{className:"cm-field"},e("label",null,k("decimalsLabel")),ne({value:n?.decimals??2},w=>J("decimals",Math.min(10,Math.floor(w))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:w=>J("hideOfficialBalance",w.target.checked)}),e("span",null,k("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:w=>J("hideTodayCost",w.target.checked)}),e("span",null,k("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},k("groupSidebar")),e("div",{className:"cm-field"},e("label",null,k("sidebarTodayMetric")),e("select",{className:"cm-input",value:n?.sidebarTodayMetric??"cost",onChange:w=>J("sidebarTodayMetric",w.target.value)},e("option",{value:"cost"},k("sidebarTodayCost")),e("option",{value:"tokens"},k("sidebarTodayTokens")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:w=>{n&&l({...n,sidebarSimple:w.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,k("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,k("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:w=>J("sidebarStyle",w.target.value)},e("option",{value:"standard"},k("sidebarStyleStandard")),e("option",{value:"compact"},k("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,k("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:w.target.value}})}},...Ye(k))),e("div",{className:"cm-field"},e("label",null,k("refreshIntervalLabel")),ne({value:n?.balance?.refreshMinutes??5},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:w.target.checked}})}}),e("span",null,k("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,k("balanceBudgetCapLabel")),ne({value:n?.balance?.budgetCap??""},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:w>0?w:null}})}),e("span",{className:"cm-hint"},k("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,k("barDirectionsTitle")),["balance","budget","go","plan"].map(w=>e("div",{className:"cm-dir-row",key:w},e("span",{className:"cm-dir-label"},k("barDirection_"+w)),e("select",{className:"cm-input",value:n?.barDirections?.[w]??(w==="balance"?"remaining":"used"),onChange:E=>{if(n===null)return;const F={balance:"remaining",budget:"used",go:"used",plan:"used"};l({...n,barDirections:{...n.barDirections??F,[w]:E.target.value}})}},e("option",{value:"remaining"},k("barDirectionRemaining")),e("option",{value:"used"},k("barDirectionUsed"))))),e("span",{className:"cm-hint"},k("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,k("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??j.customBalance?.display??"both",onChange:w=>{n!==null&&l({...n,customBalance:{...n.customBalance??j.customBalance??{},display:w.target.value}})}},...Ye(k))),e("div",{className:"cm-field"},e("label",null,k("customBalanceRefreshInterval")),ne({value:n?.customBalance?.refreshMinutes??j.customBalance?.refreshMinutes??15},w=>{n!==null&&l({...n,customBalance:{...n.customBalance??j.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e(Ka,{config:j,draft:n,setDraft:l,t:k,api:o}),e("div",{className:"cm-grid-group"},k("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:w=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:w.target.checked,promptSeen:!0}})}}),e("span",null,k("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([w,E])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[w]!==!1,onChange:F=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip,[w]:F.target.checked}})}}),e("span",null,k(E)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("quotaStripNote"))),e("div",{className:"cm-grid-group"},k("groupCorner")),e("div",{className:"cm-field"},e("label",null,k("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:w=>{n!==null&&l({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:w.target.checked}})}}),e("span",null,k("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([w,E])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[w]!==!1,onChange:F=>{n!==null&&l({...n,corner:{...n.corner,[w]:F.target.checked}})}}),e("span",null,k(E)))):null),e("div",{className:"cm-grid-group"},k("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:w=>{n!==null&&l({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:w.target.checked}})}}),e("span",null,k("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:w=>{n!==null&&l({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:w.target.checked}})}}),e("span",null,k("budgetDetailLabel"))))),e("p",{className:"cm-note"},k("badgeNote")))):null,m==="pricing"?e(L,{key:"pricing"},e(Es,{state:a,draft:n,setDraft:l,t:k}),e("div",null,Re(T,()=>N(!T),k("priceTableTitle")),T?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},k("priceTableNote")),e("p",{className:"cm-hint"},k("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},k("deepseekMountedHeader")),U,e(Kt,{key:"__default__",modelId:k("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:l,t:k}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:k("newModelPlaceholder"),value:g,onChange:w=>h(w.target.value)}),e("button",{className:"cm-btn small",onClick:M,disabled:g.trim().length===0},k("addModel"))),(()=>{const w=n?.priceTableDisplay??j.priceTableDisplay??{},E=n?.prices?.providers??{},F=V=>Object.keys(E[V]?.models??{}).filter(pe=>w[V+":"+pe]===!0),te=Object.keys(E).filter(V=>F(V).length>0).sort((V,pe)=>V.localeCompare(pe));return te.length===0?null:te.map(V=>e("div",{key:V},e("div",{className:"cm-catalog-vendor"},(Ha[V]??V)+" · "+k("mountedSuffix")),F(V).sort().map(pe=>e(Wa,{key:V+":"+pe,provider:V,modelId:pe,entry:E[V].models[pe],draft:n,setDraft:l,t:k}))))})()):null),(()=>{const w=n?.priceOverrides??j.priceOverrides??{},E=n?.priceMatchDismissed??j.priceMatchDismissed??[],F=n?.prices??j.prices,te=a.today.byProviderModel??{},V={prices:F,priceMatch:n?.priceMatch??j.priceMatch},pe=Object.keys(te).filter(H=>{if(E.includes(H)||w[H]!==void 0)return!1;const W=H.indexOf(":"),se=(W>0?H.slice(0,W):"deepseek").toLowerCase(),xe=W>0?H.slice(W+1):H;return Tt(se,xe,V).matched!==!0}),Je=[...new Set([...pe,...Object.keys(w)])].filter(H=>!E.includes(H)),ft=a.month?.byProviderModel??{},C=Object.keys(ft).filter(H=>{if(E.includes(H)||w[H]!==void 0)return!1;const W=H.indexOf(":"),se=(W>0?H.slice(0,W):"deepseek").toLowerCase(),xe=W>0?H.slice(W+1):H;return Tt(se,xe,V).matched===!0}).sort(),Q=[{value:"__local__",label:k("overrideTargetLocal")},{value:"deepseek:__default__",label:k("overrideTargetDefault")},...Object.keys(F.models??{}).map(H=>({value:"deepseek:"+H,label:"DeepSeek · "+H})),...Object.entries(F.providers??{}).flatMap(([H,W])=>Object.keys(W?.models??{}).map(se=>({value:H+":"+se,label:H+" · "+se})))],Z=(H,W)=>{if(n===null)return;const se={...n.priceOverrides??{}};W===""?delete se[H]:se[H]=W,l({...n,priceOverrides:se})},oe=H=>{if(n===null)return;const W={...n.priceOverrides??{}};delete W[H],l({...n,priceOverrides:W,priceMatchDismissed:[...new Set([...E,H])]})};return e("div",null,e("h3",{className:"cm-h"},k("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:H=>J("priceMatch",H.target.value)},e("option",{value:"auto"},k("priceMatchAuto")),e("option",{value:"exact"},k("priceMatchExact")))),e("p",{className:"cm-note"},k("priceMatchNote")),Je.length>0?e(L,null,e("h3",{className:"cm-h"},k("unmatchedTitle")),e("p",{className:"cm-hint"},k("unmatchedHint")),Je.map(H=>e("div",{key:H,className:"cm-match-row"},e("span",null,Gt(H)),e("select",{className:"cm-input",value:w[H]??"",onChange:W=>Z(H,W.target.value)},e("option",{value:""},"—"),Q.map(W=>e("option",{key:W.value,value:W.value},W.label))),e("button",{className:"cm-btn small",title:k("removePriceMatchHint"),onClick:()=>oe(H)},k("overrideRemove"))))):e("p",{className:"cm-hint"},k("overrideNone")),E.length>0?e("button",{className:"cm-btn small",onClick:()=>J("priceMatchDismissed",[])},k("restorePriceMatches",{count:E.length})):null,C.length>0?e(L,null,e("h3",{className:"cm-h"},k("matchedTitle")),e("p",{className:"cm-hint"},k("matchedHint")),C.map(H=>e("div",{key:H,className:"cm-match-row"},e("span",null,Gt(H)),e("select",{className:"cm-input",value:"",onChange:W=>{W.target.value!==""&&Z(H,W.target.value)}},e("option",{value:""},k("matchedKeepAuto")),Q.map(W=>e("option",{key:W.value,value:W.value},W.label)))))):null)})(),e(Is,{state:a,draft:n,setDraft:l,t:k}),e("div",null,e("h3",{className:"cm-h"},k("dataSync")),(n??j).currency==="CNY"&&(n??j).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},k("pricingCnyHint",{rate:(n??j).exchangeRate}),(n??j).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:x,onClick:()=>J("pricingCurrency","CNY")},k("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,k("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:w=>J("pricingCurrency",w.target.value)},e("option",{value:"USD"},k("pricingCurrencyUsd")),e("option",{value:"CNY"},k("pricingCurrencyCny"))),e("p",{className:"cm-note"},k("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},u?e(L,null,e("span",{className:"cm-hint"},k("confirmFetch")),e("button",{className:"cm-btn",onClick:Ce,disabled:x},k("apply")),e("button",{className:"cm-btn",onClick:()=>d(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>d(!0),disabled:x},k("syncFromDocs"))),e("p",{className:"cm-note"},k("lastSync",{time:j.fetchedAt!==null?new Date(j.fetchedAt).toLocaleString():k("neverSynced")})+k("source",{source:j.priceSource==="official"?k("sourceOfficial"):k("sourceBundled")})),e("p",{className:"cm-note"},k("syncScopeNote")))):null)}const Xs=["remote"];async function eo(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(gn);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=()=>{try{return Ee(t.get("locale")?.getSnapshot?.().active)}catch{return null}},l=Ln({status:"loading",error:null,state:null},C=>{const Q=n()||Ee(C.state?.meta?.locale)||Xt();return{...C,locale:Q,...C.state?{state:{...C.state,config:{...C.state.config,activeLocale:Q}}}:{}}}),i=()=>G(_(l.getSnapshot().state?.config||{activeLocale:l.getSnapshot().locale})),r=async(C,Q)=>{const Z=await a[C](...Q??[]);if(Z===null||typeof Z!="object"||Z.ok!==!0)throw new Error(Z?.error?.message??i()("rpcFailed",{method:C}));return Z.value};let u=Date.now(),d=!1,c=!0,p=1;const f=async()=>{if(!c||d)return;d=!0,u=Date.now();const C=l.getSnapshot();C.state===null&&l.set({...C,status:"loading"});try{const Q=await r("getState");if(!c)return;p=1,l.set({status:"ready",error:null,state:Q})}catch(Q){if(!c)return;C.state===null&&(u=Date.now()),p=Math.min(p*2,60),l.set({status:"error",error:Q?.message??String(Q),state:C.state})}finally{d=!1}};t.effect(()=>t.on("connection/reset",()=>{f()}),"cost-meter: reconnect reload");const b=setInterval(()=>{const C=l.getSnapshot().state,Q=C?.config.sidebarModels,Z=C?Q?.enabled||Q?.dock?Q.refreshSeconds:60:p;!document.hidden&&Date.now()-u>=(Z||60)*1e3&&f()},1e3);t.effect(()=>()=>{c=!1,clearInterval(b)},"cost-meter: poll timer");const g=()=>{c&&t.fiber?.uid!==null&&l.set(l.getSnapshot())},h=C=>C.effect(()=>{g();const Q=C.get("locale")?.subscribe?.(g);return()=>{Q?.(),g()}},"cost-meter: DSH locale");typeof t.inject=="function"?t.inject(["locale"],h):n()&&h(t),t.effect(()=>t.on("locale/change",g),"cost-meter: locale change"),window.addEventListener?.("languagechange",g),t.effect(()=>()=>window.removeEventListener?.("languagechange",g),"cost-meter: browser locale");const x=()=>{document.visibilityState==="visible"&&f()};document.addEventListener("visibilitychange",x),t.effect(()=>()=>{document.removeEventListener("visibilitychange",x)},"cost-meter: visibility reload");const S=async(C,Q="rpcSyncFailed",Z=!1)=>{const oe=await C;if(oe===null||typeof oe!="object"||oe.ok!==!0)throw new Error(oe?.error?.message??(Z?oe?.value?.message:void 0)??i()(Q));return oe.value.state!==void 0&&l.set({status:"ready",error:null,state:oe.value.state}),oe.value};let T=null;const N={loadStatistics:()=>(T||(T=(typeof $e.async=="function"?$e.async("./client.statistics.js").then(C=>C.mount(t)):Promise.reject(new Error(i()("statisticsUpgrade")))).catch(C=>{throw T=null,C})),T),reload:f,updateConfig:async C=>{const{activeLocale:Q,...Z}=C,oe=await r("updateConfig",[Z]);return l.set({status:"ready",error:null,state:oe}),oe},fetchPrices:async()=>S(a.fetchPrices()),resetHistory:async()=>{const C=await r("resetHistory");return l.set({status:"ready",error:null,state:C}),C},importLegacyHistory:async()=>{const C=await a.importLegacyHistory();if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??i()("legacyImportFailed",{message:"RPC failed"}));return C.value.state!==void 0&&l.set({status:"ready",error:null,state:C.value.state}),C.value},getDaySessions:async C=>r("getDaySessions",[C]),getSessionCost:async C=>r("getSessionCost",[C]),getTurnCost:async(C,Q,Z)=>r("getTurnCost",[C,Q,Z]),getTopSessions:async(C,Q,Z)=>r("getTopSessions",[C,Q,Z]),refreshBalance:async()=>S(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>S(a.refreshGoQuota()),refreshGatewayQuota:async(C=null)=>S(C==null?a.refreshGatewayQuota():a.refreshGatewayQuota(C)),refreshCustomBalance:async(C=null)=>S(C==null?a.refreshCustomBalance():a.refreshCustomBalance(C)),refreshCodingPlan:async C=>S(a.refreshCodingPlan(C)),loginCodingPlan:async C=>S(a.loginCodingPlan(C)),setCredential:async(C,Q)=>S(a.setCredential(C,Q),"rpcSyncFailed",!0),clearCredential:async C=>S(a.clearCredential(C),"rpcSyncFailed",!0)};f();const m=t.get("slots");if(m===void 0)return;const v=()=>({hooks:{cost:l},api:N});for(const[C,Q]of[["header","conversation.session.header.actions"],["dock","conversation.composer.dock"]])m.inject(Q,()=>m.register({name:Q,id:"cost-meter-statistics",order:1,inject:()=>({...v(),entryPosition:C})},Ms));m.inject("conversation.chat.turnTail",()=>m.register({name:"conversation.chat.turnTail",id:"cost-meter-turn",order:10,inject:v},In));const y=()=>({gen:0,dispose:null}),O=(C,Q,Z,oe,H=!0)=>{C.dispose!==null&&(C.dispose(),C.dispose=null),C.gen+=1;const W=C.gen;H&&m.inject(Q,()=>{if(C.gen!==W)return;const se=typeof Z=="function"?Z():m.register(Z,oe);if(C.gen!==W){se();return}return C.dispose=se,()=>{C.dispose===se&&(C.dispose=null),se()}})},P=y(),R=C=>{const Q=C==="header"?"conversation.session.header.actions":"conversation.composer.dock";O(P,Q,C==="header"?{name:Q,id:"cost-meter",order:-5,inject:v}:{name:Q,id:"cost-meter",order:5,inject:v},C==="header"?jn:Un,C!=="off")},A=y(),I=C=>{O(A,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:v},Ss,C)},k=y(),j=C=>{O(k,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:v},Zn,C)};m.inject("conversation.input.dock",()=>m.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:v},ys)),m.inject("sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:v},ks)),m.inject("sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:v},ws)),m.inject("sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:v},Ns));const Ce=y(),de=C=>{O(Ce,"sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:v},$n),null,C)};window.cmPeakAlertPreview=C=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(It,{detail:{kind:C==="offpeak"?"offpeak":"peak"}}))};const Ae=y(),J=C=>{O(Ae,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:C==="en"?Oe.en.sectionLabel:Oe.zh.sectionLabel,inject:v},$s,!0)},M=y(),U=C=>{O(M,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:v},Vt,C)},D=y(),K=(C,Q)=>{O(D,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:Q==="en"?Oe.en.usageSectionLabel:Oe.zh.usageSectionLabel,inject:v},Vt,C)};let w=null,E=null,F=null,te=null,V=null,pe=null;const Je=()=>{const C=l.getSnapshot().state,Q=C?.config?.position??"dock",Z=C?.config?.sidebar!==!1&&C?.config?.hideTodayCost!==!0,oe=C?.config?.balance?.display??"both",H=(oe==="sidebar"||oe==="both")&&C?.config?.hideOfficialBalance!==!0,W=Z||H||C?.config?.codexQuotaEnabled===!0||C?.config?.sidebarModels?.enabled===!0,se=C?.config?.corner?.enabled===!0||C?.config?.sidebarModels?.dock===!0,xe=_(C?.config||{activeLocale:l.getSnapshot().locale}),Ze=C?.config?.usage?.position??"cost";Q!==w&&(R(Q),w=Q),W!==E&&(I(W),E=W),se!==F&&(j(se),F=se);const Jt=C?.config?.peakEnabled===!0;Jt!==pe&&(de(Jt),pe=Jt),xe!==te&&(J(xe),te=xe),Ze!==V?(Xe&&(U(Ze==="general"),K(Ze==="section",xe)),V=Ze):Xe&&Ze==="section"&&xe!==te&&K(!0,xe)};Je();const ft=l.subscribe(Je);return t.effect(()=>()=>{ft()},"cost-meter: slot sync"),ft}return bt.apply=eo,bt.inject=Xs,Zt.exports}});
2
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:$e=>{var Zt={exports:{}},bt=Zt.exports;Object.defineProperty(bt,Symbol.toStringTag,{value:"Module"});const Be=$e("react"),{Tooltip:X}=$e("@deepseek-ai/dsh-client-ui-primitives"),Xe=!1,Ya='.cm-root{flex:0 1 auto;min-width:0;max-width:100%;text-align:center;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-chip{display:inline-flex;align-items:center;gap:4px;max-width:180px;padding:0 8px;height:22px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-foot{display:flex;align-items:center;gap:6px;height:32px;padding:0 8px;border-radius:8px;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden}.cm-foot:hover,.cm-foot-rail:hover,.cm-corner-chip:hover,.cm-qchip:hover,.cm-tab:hover,.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}.cm-foot-rail{width:100%;justify-content:center;padding:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-num{font-variant-numeric:tabular-nums}.cm-go-rail{font-size:11px;font-weight:700;color:var(--dsw-alias-label-primary)}.cm-go-list{display:flex;flex-direction:column;gap:10px}.cm-go-row{display:flex;align-items:center;gap:8px;font-size:12px}.cm-go-label{flex:none;width:88px;color:var(--dsw-alias-label-secondary)}.cm-go-bar{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-interactive-bg-hover);overflow:hidden}.cm-go-fill{height:100%;border-radius:3px;background:var(--dsw-alias-brand-primary)}.cm-go-num{flex:none;min-width:44px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.cm-go-reset{flex:none;max-width:230px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-go-time{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-go-row.main .cm-go-label{font-weight:600;color:var(--dsw-alias-label-primary)}.cm-corner{display:inline-flex;flex:0 1 auto;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;min-width:0;max-width:100%}.cm-corner-chip{display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:20px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums}.cm-qstrip{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:0 auto;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-qchip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:default}.cm-qchip .cm-qlabel{color:var(--dsw-alias-label-primary);font-weight:600}.cm-qchip .cm-qbar{display:block;width:44px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l1);overflow:hidden;flex:none}.cm-qchip .cm-qfill{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-state-ok-primary,#3ba272)}.cm-qchip .cm-qseg{display:inline-flex;align-items:center;gap:4px}.cm-qchip .cm-qsep{width:1px;height:12px;background:var(--dsw-alias-border-l1);flex:none}.cm-qchip .cm-qtext{color:var(--dsw-alias-label-secondary)}.cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}.cm-qchip.over .cm-qfill{background:var(--dsw-alias-state-error-primary)}.cm-qchip.action{cursor:pointer;user-select:none;outline:none}.cm-qchip.action:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-qchip.action:active{transform:translateY(.5px)}.cm-plan-provider{display:flex;flex-direction:column;gap:8px}.cm-plan-provider+.cm-plan-provider{margin-top:14px}.cm-plan-provider-name{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600}.cm-plan-updated{font-size:11px;font-weight:400;color:var(--dsw-alias-label-tertiary)}.cm-plan-tag{flex:none;margin-left:6px;padding:0 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);font-size:10px;line-height:16px;color:var(--dsw-alias-state-warn-primary)}.cm-plan-reset,.cm-plan-method{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-qguide{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:9999;max-width:440px;width:calc(100% - 32px);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 28px #0000002e;padding:14px 16px;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:8px}.cm-qguide h4{margin:0;font-size:13px;font-weight:600}.cm-qguide p{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}.cm-qguide .cm-buttons{display:flex;gap:8px;justify-content:flex-end}.cm-section{display:flex;flex-direction:column;gap:20px;padding:4px 2px 24px;font-size:13px;color:var(--dsw-alias-label-primary)}.cm-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.cm-cards-toggle{display:flex;align-items:center;gap:6px;margin:-6px 2px 0 auto;width:fit-content;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;user-select:none}.cm-cards-toggle:hover{color:var(--dsw-alias-label-primary)}.cm-cards-toggle input{margin:0;cursor:pointer}.cm-card,.cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1)}.cm-card-title{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0 0 8px}.cm-card-value{font-size:20px;line-height:28px;font-weight:600}.cm-card-sub{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-h{font-size:13px;font-weight:600;margin:0}.cm-collapse-h{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;margin:0;cursor:pointer;color:inherit;font:inherit;text-align:left}.cm-collapse-h:hover .cm-h{color:var(--dsw-alias-interactive-text-hover,var(--dsw-alias-label-primary))}.cm-caret{flex:none;width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid var(--dsw-alias-label-secondary);transform:rotate(-90deg);transition:transform .15s ease}.cm-caret.open{transform:rotate(0)}.cm-collapse-body{display:flex;flex-direction:column;gap:12px;margin-top:12px}.cm-toolbar{display:flex;justify-content:flex-end;align-items:center;gap:10px}.cm-toolbar .cm-field{flex-direction:row;align-items:center;gap:8px}.cm-toolbar .cm-field label{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-toolbar .cm-input{min-width:150px;padding:4px 10px}.cm-tabs-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;border-bottom:1px solid var(--dsh-alias-border-l1);padding-bottom:10px}.cm-tabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}.cm-tab{font:inherit;font-size:13px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:8px;padding:6px 14px;cursor:pointer;white-space:nowrap}.cm-tab.active{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary-inverted);font-weight:600}.cm-tabs-row .cm-msg{padding:2px 10px}.cm-note{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0}.cm-table{width:100%;border-collapse:collapse;font-size:12px}.cm-table th,.cm-table td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}.cm-table th{color:var(--dsw-alias-label-tertiary);font-weight:500}.cm-table td.num,.cm-table th.num{text-align:right;font-variant-numeric:tabular-nums}.cm-table tr:last-child td{border-bottom:none}.cm-table tr.cm-row-click{cursor:pointer}.cm-table tr.cm-row-click:hover td{background:var(--dsw-alias-bg-hover,rgba(127,127,127,.08))}.cm-sess-title{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-sess-id{font-size:11px;font-family:ui-monospace,Consolas,monospace;color:var(--dsw-alias-label-tertiary)}.cm-empty{font-size:12px;color:var(--dsw-alias-label-tertiary);padding:8px 0}.cm-scroll{max-height:320px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px}.cm-grid{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:12px}.cm-field{display:flex;flex-direction:column;gap:6px}.cm-field label{font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-input{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;outline:none}.cm-input:focus{border-color:var(--dsw-alias-state-business-primary)}.cm-input.narrow{max-width:120px}.cm-range-row{display:flex;align-items:center;gap:10px}.cm-range{flex:1;min-width:0;accent-color:var(--dsw-alias-state-business-primary)}.cm-range-value{flex:none;min-width:44px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-align:right}.cm-check{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}.cm-price-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:10px;background:var(--dsw-alias-bg-layer-1)}.cm-price-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-price-name{font-weight:600;font-size:13px}.cm-price-legacy{font-size:11px;color:var(--dsw-alias-label-tertiary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px}.cm-price-row{display:grid;grid-template-columns:52px 1fr 1fr 1fr;gap:8px;align-items:center}.cm-price-row span{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-price-row input{width:100%}.cm-buttons{display:flex;flex-wrap:wrap;gap:10px;align-items:center}.cm-btn{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-elevated-fill);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 14px;cursor:pointer}.cm-btn.cm-stat-entry{font-size:12px;line-height:20px;padding:0 6px;min-width:0;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex-shrink:0}@media(max-width:640px){.cm-stat-header{display:none}}.cm-btn.primary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-label-primary-inverted)}.cm-btn.primary:hover{opacity:.88;background:var(--dsw-alias-state-business-primary)}.cm-btn.danger,.cm-msg.err,.cm-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}.cm-btn.small{padding:3px 10px;font-size:12px}div:has(>[data-slot="conversation.composer.dock"] .cm-stat-entry){flex-wrap:nowrap;column-gap:6px}.cm-msg{font-size:12px;line-height:18px;padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1)}.cm-msg.ok{color:var(--dsw-alias-state-success-primary)}.cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-budget{display:flex;flex-direction:column;gap:10px}.cm-peak-alert{position:fixed;z-index:9999;width:340px;max-width:calc(100vw - 32px);padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:0 14px 36px #00000038;display:flex;flex-direction:column;gap:8px;font-size:12px;animation:cm-peak-alert-in .22s cubic-bezier(.2,.8,.2,1)}.cm-peak-alert.cm-peak-alert-corner{right:20px;bottom:20px}.cm-peak-alert.cm-peak-alert-center{top:50%;left:50%;transform:translate(-50%,-50%);animation-name:cm-peak-alert-in-center}.cm-peak-alert-peak{border-top:3px solid var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak{border-top:3px solid var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:600;letter-spacing:.4px;text-transform:uppercase}.cm-peak-alert-badge:before{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 4px color-mix(in srgb,currentColor 16%,transparent)}.cm-peak-alert-peak .cm-peak-alert-badge{color:var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak .cm-peak-alert-badge{color:var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-peak-alert-body{color:var(--dsw-alias-label-secondary);line-height:1.55}.cm-peak-alert-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}.cm-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}@keyframes cm-peak-alert-in{0%{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes cm-peak-alert-in-center{0%{opacity:0;transform:translate(-50%,calc(-50% + 10px))}to{opacity:1;transform:translate(-50%,-50%)}}.cm-budget-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-quota-name{flex:1;min-width:0}.cm-budget-bar{height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-budget-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary);transition:width .3s ease}.cm-ug{display:flex;flex-direction:column;gap:12px}.cm-ug-total{font-size:13px;color:var(--dsw-alias-label-primary)}.cm-ug-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,auto);gap:3px;width:100%}.cm-ug-cell{width:100%;aspect-ratio:1/1;border-radius:3px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);border:1px solid var(--dsw-alias-border-l1)}.cm-ug-cell.l1,.cm-ug-cell.l2,.cm-ug-cell.l3,.cm-ug-cell.l4{border-color:transparent}.cm-ug-cell.l1{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary)}.cm-ug-cell.today{outline:1px solid var(--dsw-alias-label-secondary);outline-offset:1px}.cm-ug-months{display:grid;grid-auto-flow:column;gap:3px;width:100%;font-size:10px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-ug-monthc{white-space:nowrap}.cm-budget-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-budget-line.over{color:var(--dsw-alias-state-error-primary)}.cm-peak-strip{display:flex;align-items:center;gap:6px;margin-top:4px;min-width:0}.cm-peak-track{position:relative;display:flex;flex:1;height:6px;min-width:0;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-segment{height:100%;flex:1}.cm-peak-high{background:#ff9800}.cm-peak-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-marker{position:absolute;top:0;left:50%;width:2px;height:100%;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2}.cm-peak-chip{font-size:11px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-classic{position:relative;display:flex;flex-direction:column;gap:5px;margin-top:6px;min-width:0}.cm-peak-classic .cm-peak-track{flex:none;height:8px}.cm-peak-classic-marker{position:absolute;top:0;left:50%;width:4px;height:12px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2;border-radius:2px}.cm-peak-classic-marker:after{content:"";position:absolute;top:-7px;left:50%;transform:translate(-50%);border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #ff9800}.cm-peak-classic.off .cm-peak-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic.off .cm-peak-classic-marker:after{border-top-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic-chip{align-self:flex-start;font-size:11px;font-weight:600;line-height:1.4;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 8px;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-strip.peak .cm-peak-chip,.cm-peak-classic.peak .cm-peak-classic-chip,.cm-peak-rail.peak .cm-peak-rail-label,.cm-peak-rail-classic.peak .cm-peak-rail-classic-label{color:#ff9800}.cm-peak-strip.off .cm-peak-chip,.cm-peak-classic.off .cm-peak-classic-chip,.cm-peak-rail.off .cm-peak-rail-label,.cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}.cm-peak-strip.weekend .cm-peak-chip,.cm-peak-classic.weekend .cm-peak-classic-chip,.cm-peak-rail.weekend .cm-peak-rail-label,.cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker{border-color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker:after{border-top-color:#34a853}.cm-peak-rail{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-track{position:relative;display:flex;flex-direction:column;width:6px;height:56px;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-segment{width:100%;flex:1}.cm-peak-rail-high{background:#ff9800}.cm-peak-rail-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-rail-marker{position:absolute;left:0;top:50%;width:100%;height:2px;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translateY(-50%);transition:top .4s ease;z-index:2}.cm-peak-rail-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-rail-classic{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-classic-track{position:relative;display:flex;flex-direction:column;width:14px;height:56px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-classic-segment{position:relative;width:100%;flex:1;overflow:hidden}.cm-peak-rail-classic-segment.peak{background:#ff9800;border-radius:999px 999px 0 0}.cm-peak-rail-classic-segment.off{background:var(--dsw-alias-state-business-primary);border-radius:0 0 999px 999px}.cm-peak-rail-classic-marker{position:absolute;left:50%;top:50%;width:12px;height:4px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%,-50%);transition:top .4s ease;z-index:2;border-radius:2px}.cm-peak-rail-classic.off .cm-peak-rail-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-rail-classic-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}.cm-grid-group{grid-column:1 / -1;margin-top:8px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:4px}.cm-grid-group:first-child{margin-top:0}.cm-peak-preview{margin-top:8px}.cm-toggle-btn{background:none;border:none;padding:0;font-size:12px;font-weight:600;color:var(--dsw-alias-state-business-primary);cursor:pointer}.cm-toggle-btn:hover{text-decoration:underline}.cm-collapsed-note{margin-top:4px}.cm-catalog-vendor{margin-top:10px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:2px;display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-vendor-toggle{cursor:pointer;user-select:none}.cm-vendor-toggle:hover{color:var(--dsw-alias-label-secondary)}.cm-vendor-display{display:inline-flex;align-items:center;gap:4px;font-weight:400;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}.cm-catalog-family{margin:6px 0 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}.cm-catalog-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px}.cm-catalog-mounted{display:flex;flex-direction:column;gap:4px;padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1)}.cm-catalog-id{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-catalog-price{color:var(--dsw-alias-label-secondary);white-space:nowrap;font-size:11px}.cm-catalog-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);white-space:nowrap}.cm-mstats-tabs{display:flex;gap:8px;margin-bottom:8px}.cm-mstats-tab{background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}.cm-mstats-tab.active{background:var(--dsw-alias-state-business-primary);border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-bg-base);font-weight:600}.cm-mstats-h{margin:10px 0 4px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}.cm-mstats-row{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:8px;align-items:center;font-size:11px;line-height:1.7}.cm-mstats-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-barbg{position:relative;height:10px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden;display:flex}.cm-mstats-bar{height:100%;min-width:0;border-radius:999px}.cm-mstats-bar.cost{background:#ff9800}.cm-mstats-bar.hit{background:#34a853}.cm-mstats-bar.value{background:#a142f4}.cm-mstats-seg{height:100%;min-width:0}.cm-mstats-seg.in{background:var(--dsw-alias-state-business-primary)}.cm-mstats-seg.cache{background:#ff9800}.cm-mstats-seg.out{background:#34a853}.cm-mstats-val{white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-legend{display:flex;gap:12px;font-size:10px;color:var(--dsw-alias-label-tertiary);margin:2px 0 4px}.cm-mstats-dot{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.cm-mstats-note{margin-top:10px;font-size:10px;line-height:1.6;color:var(--dsw-alias-label-tertiary)}.cm-match-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:12px;flex-wrap:wrap}.cm-match-row .cm-input{flex:1;min-width:160px}.cm-budget-controls{display:grid;grid-template-columns:repeat(2,minmax(180px,1fr));gap:12px}.cm-bbox{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:6px;min-width:148px;box-sizing:border-box}.cm-bbox.rail{padding:6px;min-width:0;width:40px;align-items:center;justify-content:center;border-radius:10px}.cm-bbox.warn{border-color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over{border-color:var(--dsw-alias-state-error-primary)}.cm-bbox-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-bbox-label,.cm-bbox-pct{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}.cm-bbox-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-bbox-bar.segments{display:flex;height:8px}.cm-bbox-bar.segments .cm-bbox-fill{flex:none;border-radius:0;height:100%}.cm-bbox-bar.segments .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments .cm-bbox-seg-today{flex:none;height:100%;background:#ff9800}.cm-bbox-bar.segments .cm-bbox-seg-spent{flex:none;height:100%;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-fill:first-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments.rev .cm-bbox-fill,.cm-bbox-bar.segments.rev .cm-bbox-fill:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}.cm-dir-row{display:flex;align-items:center;gap:8px;margin-top:6px}.cm-dir-label{flex:1 1 40%;font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-dir-row .cm-input{flex:1 1 60%;width:auto}.cm-bbox-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary)}.cm-balance-name{display:inline-flex;align-items:center;gap:4px;min-width:0}.cm-model-costs{font-size:12px}.cm-model-costs .cm-bal-label{white-space:nowrap}.cm-model-top{gap:4px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.cm-model-costs .cm-collapse-h{min-width:0;width:100%;white-space:nowrap}.cm-model-costs .cm-bbox-bar{margin-top:3px}.cm-bal-label{min-width:0;overflow:hidden;text-overflow:ellipsis}.cm-bal-amt{margin-left:auto;text-align:right;flex-shrink:0}.cm-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}.cm-bal-link{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:2px;border-radius:4px;font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary);text-decoration:none;outline:none}.cm-bal-link:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-interactive-bg-hover)}.cm-bal-link:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-bbox.warn .cm-bbox-fill,.cm-bbox .cm-bbox-section.warn .cm-bbox-fill,.cm-bbox .cm-mm-row.warn .cm-bbox-fill,.cm-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-fill,.cm-bbox-section.over .cm-bbox-fill,.cm-mm-row.over .cm-bbox-fill,.cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}.cm-bbox-line{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-bbox-rail{font-size:11px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct,.cm-bbox.warn .cm-bbox-rail,.cm-bbox .cm-bbox-section.warn .cm-bbox-pct,.cm-bbox .cm-mm-row.warn .cm-bbox-pct,.cm-mm-row.warn .cm-bbox-label,.cm-corner-chip.warn,.cm-qchip.warn,.cm-simple-summary.warn{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct,.cm-bbox.over .cm-bbox-rail,.cm-bbox-section.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-label,.cm-corner-chip.over,.cm-qchip.over,.cm-simple-summary.over{color:var(--dsw-alias-state-error-primary)}.cm-bbox-pair{display:flex;flex-direction:column;gap:0;padding:2px 10px}.cm-bbox-pair .cm-bbox-section{display:flex;flex-direction:column;gap:4px;padding:4px 0}.cm-bbox-pair .cm-bbox-bar{height:4px}.cm-bbox-divider{height:1px;background:var(--dsw-alias-border-l1);margin:0}.cm-bbox.clickable,.cm-foot.clickable{cursor:pointer}.cm-bbox.clickable:hover{border-color:var(--dsw-alias-state-business-primary)}.cm-bbox.clickable:focus-visible,.cm-foot.clickable:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}@keyframes cm-click-refresh-pulse{0%,to{opacity:.55}50%{opacity:1}}.cm-bbox.clickable.busy,.cm-foot.clickable.busy{animation:cm-click-refresh-pulse 1.1s ease-in-out infinite}.cm-mm{padding:8px 10px;gap:4px}.cm-mm-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-mm-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);grid-column:1/-1}.cm-gw-switcher{cursor:pointer;user-select:none;font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}.cm-gw-switcher:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.cm-gw-sub{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-mm-row{display:flex;align-items:center;gap:8px;padding:2px 0}.cm-mm-row .cm-bbox-label{flex:none;width:auto;min-width:22px;max-width:115px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;word-break:keep-all}.cm-mm-row .cm-bbox-bar{flex:1;min-width:40px;height:6px}.cm-mm-row .cm-bbox-pct{flex:none;min-width:2.4em;text-align:right;font-variant-numeric:tabular-nums}.cm-mm-row.wide .cm-bbox-label{width:auto;max-width:64px;flex:0 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-mm-row.wide .cm-mm-text{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-bal-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-bal-line.warn{color:var(--dsw-alias-state-warning-primary,#b45309)}:has(>.cm-footer-stack),:has(>[data-slot="sidebar.footer.action"]>.cm-footer-stack){flex-wrap:wrap}:has(>.cm-footer-stack.rail),:has(>[data-slot="sidebar.footer.action"]>.cm-footer-stack.rail){flex-direction:column;flex-wrap:nowrap;align-items:center;gap:6px}.cm-footer-stack{display:flex;flex:none;order:-1;flex-direction:column;gap:6px;width:100%;min-width:0;max-width:100%;align-items:stretch;box-sizing:border-box}.cm-footer-stack.rail{align-items:center;order:1}.cm-footer-stack .cm-bbox{width:100%;min-width:0}.cm-footer-stack .cm-foot{width:100%;box-sizing:border-box}.cm-footer-stack.compact .cm-bbox{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:2px;align-items:center}.cm-footer-stack.compact .cm-bbox>*{grid-column:1/-1}.cm-footer-stack.compact .cm-bbox>.cm-mm-row{grid-column:auto}.cm-footer-stack.compact .cm-mm-row{min-width:0;gap:4px;flex-wrap:nowrap}.cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:0 1 auto;min-width:0;max-width:45%;width:auto}.cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0;flex:1 1 0}.cm-footer-stack.simple{gap:0;max-height:38vh;max-height:min(38dvh,320px);overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.cm-footer-stack.simple>*{flex-shrink:0}.cm-footer-stack.simple:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}.cm-footer-stack.simple .cm-bbox{border:0;border-radius:0;padding:4px 8px;gap:2px;background:transparent;box-shadow:inset 0 -1px var(--dsw-alias-border-l1)}.cm-footer-stack.simple .cm-mm-title{font-size:11px;line-height:16px;margin:0}.cm-footer-stack.simple .cm-mm-row{gap:6px;min-height:16px;line-height:16px;margin:0;padding:0}.cm-footer-stack.simple .cm-mm-text{font-size:11px}.cm-footer-stack.simple>.cm-peak-strip,.cm-footer-stack.simple>.cm-peak-classic{margin:0;padding:4px 8px}.cm-simple-summary>span{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-footer-stack.simple .cm-bbox-pct{font-size:12px;line-height:18px}.cm-footer-stack.simple .cm-bbox-bar{height:4px}.cm-footer-stack.simple .cm-bbox-line{display:none}.cm-footer-stack.simple .cm-foot{height:26px;padding:0 8px}.cm-footer-stack.simple .cm-peak-classic{margin-top:2px;gap:2px}.cm-footer-stack.simple .cm-peak-classic-chip{padding:0 4px;border:0;background:transparent}.cm-simple-summary{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 8px;font-size:12px;font-weight:600;border-bottom:1px solid var(--dsw-alias-border-l1)}.cm-footer-stack.simple.rail{border:0;background:transparent}.cm-footer-stack.simple.rail .cm-bbox{padding:4px 2px}.cm-footer-stack.simple .cm-peak-rail-track,.cm-footer-stack.simple .cm-peak-rail-classic-track{height:28px}@media(max-width:640px){.cm-cards,.cm-grid,.cm-budget-controls{grid-template-columns:1fr}}',$t="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify($t)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=$t,t.textContent=Ya,document.head.appendChild(t)}const Va="sessionCostTitle|sessionDetailTokens|sessionDetailCache|cost|sessionLine|sessionLineCompact|sessionCostCompact|quotaUnlimited|pricingCnyHint|balanceQueryFailed|unknownError|balance|queryFailed|balanceTitle|reconcileLabel|totalBalance|grantedToppedUp|updatedAt|budgetOf|usedOf|todayShare|monthTotal|budget|todayCostTitle|todayTokensTitle|tokensUnit|callsTokens|monthCost|totalCost|today|sidebarTodayMetric|sidebarTodayCost|sidebarTodayTokens|periodDay|periodMonth|periodAll|periodCustomRange|noHistory|colDate|colCalls|colInTok|colCacheTok|colOutTok|colCost|noSessionsToday|colSession|enableBudget|budgetAmountLabel|budgetPeriodLabel|startDate|endDate|rangeText|budgetDisabledNote|budgetStatus|overLimit|nearLimit|legacyModel|defaultFallback|remove|tierBase|tierOffPeak|tierPeak|balanceApiKey|balanceKeyHint|balanceLine|balanceQueryFailedHint|balanceNotQueried|accountBalance|refreshing|refreshBalance|customBalanceTitle|customBalanceAdd|aliyunBalanceAdd|aliyunBalanceNote|customBalanceConfigNote|customBalanceLabelZh|customBalanceLabelEn|customBalanceUrl|customBalanceMethod|customBalanceHeaders|customBalanceBody|customBalanceBodyNote|customBalanceExtract|customBalanceDisplayLabel|customBalanceRefreshInterval|customBalanceUnitLabel|customBalanceConvert|customBalanceConvertNote|balanceBarRemaining|balanceBarToday|balanceBarSpent|balanceShowProgressBar|barDirectionsTitle|barDirectionsHint|barDirection_balance|barDirection_budget|barDirection_go|barDirection_plan|barDirectionRemaining|barDirectionUsed|balanceBudgetCapLabel|balanceBudgetCapHint|customBalanceInvalidJson|customBalanceHeadersVarNote|customBalanceAllowedHosts|customBalanceAllowedHostsHint|customBalanceCredentialsTitle|customBalanceCredentialsHint|customBalanceNoPlaceholders|enable|customBalanceLine|customBalanceRemaining|refreshCustomBalance|goQuotaTitle|goQuotaRowLabel|goWindowRolling|goWindowWeekly|goWindowMonthly|goResetAt|resetReached|resetDays|resetHours|resetMinutes|quotaUsed|quotaRemaining|goQuotaPercent|goQuotaFetchedAt|goQuotaDisplayLabel|goQuotaRefreshIntervalLabel|goQuotaRefreshMinutesUnit|goQuotaKeyLabel|goMainLabel|goDetailLabel|credentialConfiguredOf|credentialNotConfigured|credentialSave|credentialEdit|credentialClear|credentialSaving|credentialInputHint|secretMigrationPending|budgetDetailLabel|refreshGoQuota|goQuotaNotQueried|codingPlanAnthropic|codingPlanZai|codingPlanMinimax|codingPlanMinimaxTitle|minimaxOrigin|minimaxOriginNote|codingPlanRemain5h|codingPlanRemain7d|balanceRechargeLink|codexQuotaTitle|codexQuotaEnabled|codexQuotaSidebar|includeSubagentCost|gatewayQuotaEmpty|codingPlanDisplayLabel|codingPlanDisplayNote|codingPlanKeyLabel|codingPlanRefreshIntervalLabel|refreshCodingPlan|loginCodingPlan|loggingIn|codingPlanNotQueried|gatewayQuotaTitle|gatewaySourceAdd|gatewaySourceLabel|gatewaySourceBaseURL|gatewaySourceDisplay|gatewaySourceAllowlist|gatewaySourceCredential|gatewaySourceStatus|gatewaySourceUnsupported|gatewaySourceUnknown|gatewaySourceNoAccounts|gatewaySourceFetchedAt|gatewaySwitchAccount|gatewayOnlyGemini|refresh|quotaEnableFirst|quotaRefreshReady|quotaRemove|quotaSectionNote|codingPlanDisabledNote|goQuotaDisabledNote|cornerLabel|cornerEnabledLabel|cornerGoRolling|cornerGoWeekly|cornerGoMonthly|cornerBudget|goShortRolling|goShortWeekly|goShortMonthly|goShortDaily|budgetShort|ledgerReadFailed|readingLedger|ledgerUnavailable|syncFailed|historyCleared|clearFailed|peakOff|peakNotEffective|peakActive|peakNotice|offPeakActive|weekendAllOffPeak|weekendChip|weekendShort|holidayAllOffPeak|holidayChip|holidayShort|peakHolidaysLabel|weekendRuleNote|peakShort|offPeakShort|peakStyleLabel|peakStyleCompact|peakStyleClassic|peakAlertLabel|peakAlertAheadLabel|peakAlertTargetLabel|peakAlertTargetPeak|peakAlertTargetOffPeak|peakAlertTargetBoth|peakAlertTitlePeak|peakAlertTitleOffPeak|peakAlertBody|peakAlertPhasePeak|peakAlertPhaseOffPeak|peakAlertBtn|peakAlertBadgePeak|peakAlertBadgeOffPeak|peakAlertPositionLabel|peakAlertPositionCorner|peakAlertPositionCenter|peakAlertWebNotifyLabel|peakAlertWebNotifyHint|peakAlertPreviewLabel|peakAlertPreviewPeak|peakAlertPreviewOffPeak|peakAlertPreviewTag|peakPanelTitle|peakNoticeHiddenHint|groupGeneral|groupMoney|groupSidebar|sidebarSimple|sidebarSimpleNote|sidebarSimpleTitle|sidebarSimpleBody|sidebarSimpleOn|sidebarSimpleOff|sidebarSimpleError|closeGuide|todayBudget|sidebarStyleLabel|sidebarStyleStandard|sidebarStyleCompact|restorePriceMatches|removePriceMatchHint|groupCorner|groupDetail|catalogTitle|catalogNote|catalogOpen|catalogCollapse|mountBtn|unmountBtn|mountedTag|catalogUnpriced|catalogDeepseekNote|modelStatsTitle|modelsTitle|modelsCount|modelsOther|models_enabled|models_defaultOpen|models_remember|models_tokens|models_shares|models_dock|models_period|models_summary|models_position|models_topN|models_refreshSeconds|modelsTotal|modelsTop|modelsFirst|modelsAfter|modelsLast|modelStatsToday|modelStatsHistory|modelStatsCostH|modelStatsTokensH|modelStatsHitH|modelStatsHitUnreported|modelStatsHitUnreportedTip|modelStatsValueH|modelStatsInput|modelStatsCache|modelStatsOutput|modelStatsEmpty|modelStatsBlended|modelStatsNote|modelStatsLegacy|sessionLineSplit|sessionLineSplitCompact|costChipPlan|sessionDetailPlan|planStatsTitle|planStatsEmpty|planStatsWindow|planStatsPercent|planStatsLocal|planStatsPer1|planStatsFull|planStatsResets|planStatsMethodSample|planStatsMethodLive|planStatsMethodNone|planStatsMethodSampleAt|planStatsConfidenceLow|planStatsCurveTitle|planStatsDaily|planStatsWeekly|planStatsMonthly|planStatsCurveEmpty|planStatsBarTip|planStatsNote|billingClassLabel|billingClassPlan|billingClassAuto|billingClassApi|catalogDisplayLabel|catalogDisplayHint|priceTableDisplayHint|catalogCustomModels|priceMatchLabel|priceMatchAuto|priceMatchExact|priceMatchNote|unmatchedTitle|unmatchedHint|overrideTargetDefault|overrideRemove|overrideTargetLocal|matchedTitle|matchedHint|matchedKeepAuto|overrideNone|mountedSuffix|flatInput|flatCached|flatOutput|deepseekMountedHeader|codingPlanKimi|codingPlanOpenrouter|codingPlanSiliconflow|codingPlanCommandcode|codingPlanScnet|codingPlanVolcengine|codingPlanQwen|codingPlanMimo|mimoWindowPlan|mimoWindowCompensation|codingPlanWindowBalance|qwenSource|qwenSourceLocal|qwenSourceCli|qwenSourceBailian|qwenCliNote|qwenBailianNote|qwenPlanCreditsLabel|qwenPlanStartLabel|qwenRatesLabel|qwenRatesModelPlaceholder|qwenRatePlaceholder|qwenRate_input|qwenRate_cachedInput|qwenRate_output|qwenRateDraftNote|qwenRatesAdd|qwenLocalNote|scnetPlanCreditsLabel|scnetPlanStartLabel|scnetLocalNote|volcengineAccessKeyIdLabel|volcengineSecretAccessKeyLabel|volcengineNote|volcengineAccessKeyPlaceholder|volcengineSecretPlaceholder|countdownHoursOnly|countdownHourMinute|countdownMinute|nextOffPeakIn|nextPeakIn|peakSummary|noPeakWindows|unknown|cardToday|cardMonth|cardTotal|cardTotalSub|externalUsage|combinedUsage|externalStale|externalHistory|cardsFootnote|timezoneHint|todaySessions|historyExpandHint|historySessionsLoading|historyNoSessions|historySessionsError|sessionRankTitle|sessionRankHint|sessionRankEmpty|sessionRankLoading|sessionRankError|sessionRankLimit|showSessionIdLabel|cardsTogglePlanTotal|cardsTogglePlanTotalHint|hideOfficialBalanceLabel|hideTodayCostLabel|hideSessionCostHeader|hideSessionCostDock|hideTurnCost|sessionRankSort|sessionSortCostDesc|sessionSortCostAsc|sessionSortTimeDesc|sessionSortTimeAsc|sessionSortRecent|history|statisticsUpgrade|usageTitle|usageTotal|usageDay|usageEmpty|usageSectionLabel|usagePositionLabel|usagePositionCost|usagePositionGeneral|usagePositionSection|displaySettings|tabOverview|tabQuotas|tabUsage|tabPricing|tabDisplay|historyDataTitle|positionLabel|positionDock|positionHeader|off|quotaStripGroup|quotaStripEnable|quotaStripShowBudget|quotaStripShowGo|quotaStripShowPlans|quotaStripNote|quotaStripGuideTitle|quotaStripGuideBody|quotaStripGuideOn|quotaStripGuideOff|clickToRefresh|balanceClickGuideTitle|balanceClickGuideBody|balanceClickGuideOk|sidebarLabel|sidebarOn|currencyLabel|currencyCny|currencyUsd|currencyEur|symbolLabel|rateLabel|decimalsLabel|balanceDisplayLabel|balanceSidebar|balanceSettings|balanceBoth|refreshIntervalLabel|peakEnabledLabel|peakNoticeLabel|badgeNote|priceTableTitle|pricingCurrencyLabel|pricingCurrencyUsd|pricingCurrencyCny|pricingCurrencyNote|priceTableNote|datedPriceNote|defaultModelId|newModelPlaceholder|addModel|dataSync|saving|autoSaveFailed|autoSavedAt|autoSaveHint|confirmFetch|apply|cancel|syncFromDocs|syncScopeNote|confirmReset|importLegacy|confirmImportLegacy|legacyImportFailed|legacyImportNote|confirmClear|clearAllHistory|lastSync|neverSynced|source|sourceOfficial|sourceBundled|languageLabel|localeAuto|localeZh|localeEn|sectionLabel|rpcFailed|rpcSyncFailed|rpcBalanceFailed".split("|"),Ja="weekends and Chinese public holidays are off-peak|OpenCode Go|Coding Plan|显示位置|Token Plan|DeepSeek models use the default price|中国公众假期全天谷价|刷新间隔|峰时高价时段显著提示|display position|above the input|session details|以同一系统账号运行|拓展价格表|输入框上方|图框详细信息|official account balance|the DSH credential store|Refresh interval|display currency|off-peak pricing|refresh interval|cost is an upper bound|extended price catalog|Monthly credits quota|This session|今日费用|会话明细|右下角显示|命中价格的模型|导入安装前历史|按基础价格计费|按显示币种|时价计费|本地账本|自动保存|自动匹配|自定义余额|Balance query failed|removed from sidebar|Strip includes|Token usage|as the same OS user|pre-install history|Cost settings|DeepSeek peak-hour|Go quota|qianwen auth login|subscription quota|主页面侧边栏|会话排行加载|余额查询失败|写入按命中价|官方账户余额|开启后侧边栏|清除全部历史|留空按自然月|留空自动发现|费用明细入口|Clear all history|Entering off-peak|Quota not queried|This month|billed exactly at|never echoed back|to refresh|all off-peak|local ledger|the official|会话费用|历史记录|取消挂载|同步价格|官方文档|峰谷时段|峰谷计价|手动指定|本地估算|法定假日|用量统计|直接显示|调用失败|额度数据|额度横条|Preview entering|Show Codex quota|historical rates|Plan start date|Volcano Ark|base prices are|call failed|coding plan|in Settings|off-peak prices|on the DSH host|prices from|session ranking|后显示额度|开始对话后|未查询额度|汇总在这里|现在开启吗|订阅起始日|输入区下方|额度百分比|quota data|the ledger|All time|Failed to|billed at".split("|"),Oe=Object.fromEntries([["zh",'本(按每次调用实际时刻精确计费)|输入 {input} · 缓存 {cache} · 输出 {output}|缓存:读 {read} · 写 {write}(计费)|费用 {amount}|本会话 {amount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}|本会话 {amount}|只显示金额(悬停可见完整分项)|无限制|当前人民币金额来自美元价格 × 汇率 {rate}。对照官方人民币账单,请选择 CNY,再;同步会更新历史费用。|:{message}|未知错误|余额|查询失败|DeepSeek 开放平台账户余额|官方余额变动与交叉对账(偏差超阈时提示)|总余额 {amount}|赠送 {granted} · 充值 {toppedUp}|更新时间 {time}|预算({period})|已用 {used} / {amount}|今日 {amount} · 占预算 {pct}|本月 {month} · 累计 {total}|预算|(按官方价格精确计费)|今日 Token 用量|tokens|调用 {calls} 次 · 输入 {input} · 缓存 {cache} · 输出 {output}|本月 {amount}|累计 {amount}|今日|侧边栏今日显示|费用|Token 用量|今日|本月|累计|自定义区间|暂无。,费用将按天。|日期|调用|输入 tok|缓存 tok|输出 tok|费用|今日暂无会话记录。|会话|启用预算|预算额度()|预算周期|开始日期|结束日期(留空 = 今日)|统计区间:{range}|启用预算、已用金额及比例(换算);可选今日、本月、累计或自定义周期。|{period}预算 {amount} · 已用 {used} · {pct}%|(已超出)|(接近上限)|旧模型|默认回退|移除|基础|谷时|峰时|余额专用 API Key|优先使用此开放平台 Key;未配置时读取已登录官方账号余额,其次沿用模型凭据。|总余额 {total} · 赠送 {granted} · 充值 {toppedUp} · 更新于 {time}|:{message}|未查询余额||刷新中…|刷新余额|自定义 Provider 余额|添加配置|添加千问 / 阿里云余额|查询阿里云中国站可用金。RAM AccessKey 需 bss:DescribeBillingAccount 权限。前两项必填;STS 才需 Security Token。密钥存凭据库。|extract 支持点路径、数值和 add/subtract/divide 运算;NewApi quota 除以 500000 得到美元。|中文名称|英文名称|请求 URL|请求方法|请求头 (JSON)|请求体 (JSON)|留空不发送;JSON 原文保存并发送。默认 Content-Type 为 application/json,可在请求头覆盖。|解析规则 (JSON)|| (分钟)|余额原币种|折算(USD 余额)|使用显示汇率与精度;余额币种保持端点原币种。其他币种及积分不折算。|余额 {amount}|当日已用 {amount}|已用 {amount}|余额进度条 (蓝=余额,橙=当日,灰=已用)|进度条方向|各组进度条可独立选择填充方向:「剩余方向」满条起步、随消耗递减;「已用方向」空条起步、随消耗填满。|余额条(官方/自定义)|预算条|Go 额度条|Plan / Codex 额度条|剩余方向(满 → 空)|已用方向(空 → 满)|额度上限 (可选)|留空则优先使用 API 返回的 max_budget;仍无则显示整条浅蓝|JSON 格式无效|{{VAR_NAME}} 从凭据库或环境变量读取。<ROUTE>_API_KEY 中 ROUTE 为大写 Provider ID,符号改下划线,如 openai→OPENAI_API_KEY。同名共用密钥。|凭据白名单 (逗号分隔)|请求头带密钥时仅放行列表内主机,留空则放行并警告,防导入他人配置外带密钥。|凭据输入|为上方 {{VAR}} 占位符存入密钥(write-only,只写凭据库,不回显):|请求头还没有 {{VAR}} 占位符:填入如 "Authorization": "Bearer {{MY_API_KEY}}" 后这里会出现凭据输入框。|启用|剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}|剩余 {amount}|刷新| 订阅额度|Go|滚动 5 小时|本周|本月|重置:{time}|已到重置时间|剩余 {d}天{h}小时|剩余 {h}小时{m}分|剩余 {m}分钟|已用 {pct}%|剩余 {pct}%|{percent}%|更新于 {time}|Go 额度|Go 额度(分钟)|分钟| API Key(可选,)|Go 额度主档位|Go |已配置(来源:{source})|未配置|保存|编辑凭据|清除|保存中…|密钥只写入 DSH 凭据库,不保存在账本里,也不会回显。|以下密钥仍在,未迁入凭据库。请导出对应环境变量后重启:|预算|刷新额度||Anthropic(Claude Pro/Max)|Z.ai / 智谱 GLM |MiniMax |MiniMax Plan|查询域名(HTTPS)|留空自动选择官方站点。填写后 Key 仅发往该域名;使用可信地址,不含路径。|5h|7d|打开 DeepSeek 充值页(platform.deepseek.com/usage)|ChatGPT (Codex) 周额度|显示 Codex 额度(需安装并登录 dsh-openai-codex)|在侧栏显示 Codex 额度(关闭后仍保留会话额度条)|本包含子代理|暂无||选「 / 两者」卡片;窄栏显示百分比。|API Key(可选,)|(分钟)|刷新|登录|登录中…||CLIProxyAPI 网关额度|添加来源|来源名称|Base URL||允许的 Host|Management Key(只写)|状态|不支持的 Provider|未知|未发现账号|抓取于 {time}|切换账号 (当前: {account})|只显示 Gemini 额度|刷新|先勾选启用这一项|启用并保存后可刷新|删除|勾选启用后会排到最上面;点名称可展开该项自己的配置。最多 8 条,网关来源最多 4 条。|未启用。开启后将按查询该厂商的  额度并显示在这里。|开启后读取  的滚动 5 小时、周、月额度,显示在侧栏、设置页及右下角;无订阅时提示原因。|(dock)|在  额度 / 预算|滚动 5 小时额度|本周额度|本月额度|预算已用%|5h|周|月|日|预算|账本读取失败:{message}|正在读取账本…|账本不可用|同步失败:{message}|已清除。|清除失败:{message}|已关闭,|尚未生效(生效时间:{time}),当前|当前处于峰时段,按峰|当前为 DeepSeek 峰时高价时段,按峰|当前处于谷时段,按谷|周末时段——全谷价(周六及周日全天按谷)|周末时段——全谷价|周末全谷|——全天谷价|——全谷价|假日|(北京日期,逗号分隔)|自 2026-08-23 北京时间 00:00 起,周末和;调休上班的周末仍按谷价。|峰时|平价|条样式|简洁(单行紧凑)|经典(分段与胶囊芯片)|峰/谷切换前弹窗提醒|提前提醒(分钟,1-30)|提醒类型|进入峰时|进入谷时|峰和谷|即将进入峰时|即将进入谷时|约 {time} 后计费档位切换为{phase}价,请注意本时段调用成本。|峰时|谷时|知道了|峰价提醒|谷价提醒|弹窗位置|右下角|屏幕中心|同步发送系统通知|开关后请在浏览器地址栏允许通知权限,才能在页面最小化/切走时收到提醒。|预览弹窗|预览 进入峰|预览 进入谷|(预览)|与提示|提示已隐藏:需启用并开启「」。|常规|金额与币种|侧边栏显示|简化侧栏显示|精简卡片,保留金额、额度和悬停详情;高度最多占屏幕 38%,超出可滚动。关闭后恢复。|试试更轻巧的侧栏|简化显示可以为会话列表留出更多空间。要?之后可在「设置 → 费用 → 显示」中切换。|开启简化显示|保留当前显示|设置未能保存。可重试,或关闭提示后在设置中调整。|关闭提示|今日 / {period}预算|侧边栏进度条样式|标准|紧凑(两列)|恢复已移除的模型 ({count})|移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按规则计价。|右下角角标|||按厂商和模型分类的参考价。挂载后可编辑并计费;DeepSeek 后用默认价。|展开|收起|挂载||已挂载|未核价|DeepSeek 后按默认价计费。|按模型统计(token 与费用)|侧栏模型花费|{n} 模型|其它|显示模型花费卡片|默认展开|记住展开状态|显示 Token|显示费用占比条| Top-1 模型|默认周期|收起摘要|卡片位置|模型行数(1–10)|(10–60 秒)|周期总额与模型数|Top-1 模型与金额|顶部|余额之后|底部|今日|近 90 天|费用排行|Token 消耗|缓存命中率|未上报?|长调用无缓存命中:代理可能移除缓存字段。金额按全未命中计,是上界;可直连核对。|性价比 · 每美元 token 数|输入|缓存|输出|该时段暂无用量数据。|综合单价 {price}/M|命中率=缓存读÷(缓存读+普通输入);「未上报?」表示缓存字段可能缺失,金额为上界。单价=费用÷token×1M;性价比=token÷费用。|未分模型(早期数据 · 按当时记录计费)|本会话 {amount}(API)· Plan 等值 {planAmount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}|本会话 {amount}(API)· Plan 等值 {planAmount}|费用 {amount}(+Plan)|Plan 订阅额度消耗(等值){amount}| (每 1% 与满窗估算)|尚无  ;请在「额度」页开启并刷新厂商。|窗口|已用 %|本周期实际()|每 1% 额度 ≈|满窗 100% ≈|重置 {time}|采样差分|当前用量折算|样本不足|{method}(基准 {time})|读数精度受限|Plan 用量曲线(按采样区间聚合)|每日|每周|每月|采样不足:至少两次成功刷新,且发生变化。|{date}:满窗估计 ≈ {full}(每 1% ≈ {per1})· 实际 {tokens} / {cost} · {intervals} 个采样区间|金额是目录价等值;订阅耗额度,预算只计 API。估算仅含 dsh 调用;服务端百分比含全账号。短时样本精度有限;5h 滚动,周/月按本地日历。|计费方式|Plan 订阅|自动|API 按量|在费用设置|仅控制是否在费用价格表;不影响挂载和计费。隐藏的已挂载模型仍可在拓展表编辑。|可逐模型切换。DeepSeek 默认,第三方默认在拓展表。|手动新增模型|未知模型名|自动(去后缀 / 前缀 / 家族相似)|仅精确匹配|优先;只接受同名及日期、版本、上下文后缀。未命中的 DeepSeek 用默认价,其他渠道不计价。|最近出现但未|这些模型没有价格。可;「默认价」使用 DeepSeek 默认价。本地推理默认零费用。|DeepSeek 默认价|移除|本地模型(零消耗)|本月已|这些模型价格。可改选价格或零费用;token 仍统计。保存后移入区。|保持自动命中|暂无手动匹配覆盖。|已挂载(参与计费)|输入|缓存|输出|DeepSeek 价格表(已挂载)|Kimi / Moonshot|OpenRouter|SiliconFlow 硅基流动|CommandCode|SCNet 超算互联网 |火山方舟  |千问 Qwen |小米 MiMo |套餐积分|补偿积分|余额|额度来源||官方 CLI|百炼 CLI|CLI 模式需在 DSH 主机安装 @qianwenai/qianwen-cli,并 。|百炼 CLI:在 DSH 主机安装 bailian-cli。登录按钮会在该主机打开授权浏览器;远程或无界面主机请 bl auth login --console。|月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)|(可选,格式 YYYY-MM-DD;)|Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)|模型名,如 qwen3.8-max-preview|费率|输入|缓存读|输出|待填齐三项正数后;全部清空恢复内置表。|添加|Credits ,以控制台为准。只计 qwen 及 qwen/qianwen-tokenplan 订阅渠道,含 llm- 前缀;不计按量 API。表外模型需设抵扣率。|月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)|(可选,格式 YYYY-MM-DD;)|优先用 24 小时内的控制台快照,否则按和官方 Credits 表估算。其他工具和表外模型不计入。|火山引擎 AccessKey ID|火山引擎 SecretAccessKey|火山方舟需 AK/SK、ArkReadOnlyAccess 和 BillingCenterReadOnlyAccess;可填凭据或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。只连接 open.volcengineapi.com。|AK...|SK...|{h}小时|{h}小时{m}分|{m}分钟|{time}后进入平价|{time}后进入高峰|峰时段(UTC):{windows};生效时间:{time}。{status}|未配置。{status}|未知||本月费用|累计费用|自账本建立以来 · 调用 {calls} 次|外部用量|DSH + 外部合计|外部快照超过 24 小时未更新|近期每日记录|金额取最近快照,可能比官方账单晚几分钟。tokens 含输入、输出、缓存和推理;推理并入输出计费。以金额对账。|今日/本月按宿主时区 {host},浏览器为 {browser}。时区不同会影响日界和对账;可将 dsh 改为本地时区。|今日会话|点击日期行可展开当日|加载中…|该日无(早期数据或会话日志已清理)|加载失败|按会话统计(全部历史)|跨天合并,子代理按开关归并。仅列选定条数,累计费用包含全部对话。|暂无会话数据|中…|失败|显示条数|会话列表附显会话 ID|金额含 Plan 总额|开启后所有金额按含 Plan 订阅等值的总费用展示;关闭(默认)仅计真金白银 API 渠道|隐藏(与设置页不再显示官方余额)|隐藏今日消耗金额(/预算明细/概览卡片不再显示)|隐藏标题栏|隐藏输入框下方|隐藏每轮回复后的本轮费用|排序|费用 高→低|费用 低→高|时间 新→旧|时间 旧→新|实时顺序||计费统计需要 DSH 0.2.0-rc.2 或更新版本的模块加载器。|Token |累计 {tokens} tokens · 输入 {input} · 缓存 {cache} · 输出 {output} · {calls} 次调用|{date}:共 {tokens} tokens(输入 {input} · 缓存 {cache} · 输出 {output})· {calls} 次调用 · {cost}|暂无历史数据,每日用量会|用量|Token 位置|费用设置|通用设置|独立分节(用量)|显示设置|概览|额度|用量|价格|显示|历史数据|||会话标题栏|关闭||启用(一条横排显示)|横条含预算已用%|横条含 Go 额度|横条含  额度|横条悬停可见各窗口重置时刻与更新时间;无可用时自动隐藏。|新增:|在显示预算及 / 。?可在「设置 → 显示设置」修改。|开启横条|暂不开启|点击立即刷新|新增:余额图框点击刷新|点击侧边栏余额或  图框即可刷新;刷新时图框闪烁,失败时保留原值并在悬停提示中说明原因。|知道了|当日费用显示|侧边栏底部|货币单位|人民币 CNY|美元 USD|欧元 EUR|货币符号|汇率(1 美元 = ? 目标币种)|小数位数|余额||设置页|两者都显示|余额(分钟)|启用 DeepSeek 价格|(侧边栏预算框/;设置页峰谷面板内预览)|会话按调用时价格计费(含峰谷与历史档位)。输入、输出、缓存读写分开统计;独立缓存写入价与长上下文档位按配置生效。|价格表(美元 / 1M tokens)|官方价格币种|美元(英文官方页)|人民币(中文官方页)|决定所用的官方页语言。切换并同步后后台重算历史;日志不全的会话保留原价。完成后提示。|按调用时间计价:Flash 自 9 月 10 日北京 12:00 用新价,V4 Pro 自 9 月 14 日同刻用 Flash 价;此前用历史价。工作日 09–12、14–18 峰价翻倍;周末及。缓存。|这里显示当前适用价格。手工编辑会取消此条后续预定调价,已发生的历史价格仍保留。|default(未匹配模型时回退)|新模型 ID(如 deepseek-v4-pro)|添加模型|数据与同步|保存中…|失败:{message}|已 {time}|配置修改后|确认用价格覆盖价格表?|应用|取消|从|官方同步只更新 DeepSeek 价格(含峰谷);z-ai/Kimi/Qwen/Volcano 等第三方价格随版本更新,也可在或模型名匹配中调整。|确认?||确认导入?将回放全部会话日志,只补账本缺失的日期与会话,不影响已有记录。|失败:{message}|首次启动自动导入旧记录;拷入日志后可重跑。按当前价格回推;已删除日志无法回放,跨安装时刻的会话不计此前用量。|确认清除||最近同步:{time}|从未(使用内置价格)|;来源:{source}||内置默认|界面语言|跟随 DSH(自动)|简体中文|English|费用|{method} |同步|余额刷新'],["en",`Cost of this session ( each call time)|Input {input} · Cache {cache} · Output {output}|Cache: read {read} · write {write} (writes  the hit price)|Cost {amount}| {amount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}| {amount}|Amount only below the composer (full split on hover)|Unlimited|CNY totals use USD prices × {rate}. To compare official CNY bills, select CNY, then sync prices; syncing also updates historical costs.|: {message}|Unknown error|Balance|Query failed|DeepSeek open-platform account balance|Cross-check official balance changes against the  (warn when they diverge)|Total {amount}|Granted {granted} · Topped-up {toppedUp}|Updated {time}|Budget ({period})|Used {used} / {amount}|Today {amount} · {pct} of budget| {month} ·  {total}|Budget|Today's cost ( official prices)|Today's token usage|tokens|Calls {calls} · Input {input} · Cache {cache} · Output {output}| {amount}| {amount}|Today|Sidebar today display|Cost||Today|||Custom range|No history yet. Once you start chatting, costs are aggregated here per day.|Date|Calls|In tok|Cache tok|Out tok|Cost|No sessions recorded today.|Session|Enable budget|Budget amount (in )|Budget period|Start date|End date (empty = today)|Range: {range}|Enable a budget to see its limit, used amount and percentage in the . Choose today, month, all time or a custom range.|{period} budget {amount} · Used {used} · {pct}%| (over limit)| (near limit)|Legacy|Default fallback|Remove|Base|Off-peak|Peak|Balance API key|This Open Platform key takes priority; otherwise the signed-in  is read, then model credentials.|Total {total} · Granted {granted} · Topped-up {toppedUp} · Updated {time}|: {message}|Balance not queried|Account balance|Refreshing…|Refresh balance|Custom provider balance|Add entry|Add Qianwen / Alibaba Cloud balance|Shows Alibaba Cloud China funds. RAM AccessKey needs bss:DescribeBillingAccount. The first two fields are required; Security Token is for STS. Secrets stay in the credential store.|Extract accepts paths, numbers and add/subtract/divide. Divide NewApi quota by 500000 for USD.|Chinese name|English name|Request URL|HTTP method|Headers (JSON)|Request body (JSON)|Blank sends no body; JSON text is saved and sent as entered. Content-Type defaults to application/json; headers can override it.|Extract rules (JSON)|Custom balance display| (minutes)|Source currency|Convert USD balance to |Uses the display rate and precision. Keep the source currency; other currencies and credits stay unchanged.|Balance {amount}|Today {amount}|Spent {amount}|Balance progress bar (blue=balance, orange=today, gray=spent)|Progress bar direction|Each group of bars can independently choose its fill direction: "Remaining" starts full and drains with usage; "Used" starts empty and fills up.|Balance bars (official/custom)|Budget bar| bar|Plan / Codex quota bars|Remaining (full → empty)|Used (empty → full)|Budget cap (optional)|Leave empty to use API max_budget; if still missing, show full light-blue bar|Invalid JSON|{{VAR_NAME}} reads a credential or environment variable. <ROUTE>_API_KEY uses an uppercase Provider ID with underscores, such as openai→OPENAI_API_KEY. Names can share a key.|Allowed hosts (comma-separated)|When headers carry credentials only listed hosts are allowed; leave empty to allow with a warning. Protects keys when importing someone else's config.|Credential input|Store the key for each {{VAR}} placeholder above (write-only: stored in , ):|No {{VAR}} placeholders in the headers yet — add e.g. "Authorization": "Bearer {{MY_API_KEY}}" and a credential input will appear here.|Enable|Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}|Remaining {amount}|Refresh custom balance| |Go|Rolling 5h|Weekly|Monthly|Resets: {time}|Reset time reached|{d}d {h}h left|{h}h {m}m left|{m}m left|{pct}% used|{pct}% remaining|{percent}%|Updated {time}| |  (minutes)|min| API key (optional; empty = auto-detect)| primary window|Go box details|Configured (source: {source})|Not configured|Save|Edit credential|Clear|Saving…|The key is written to  only — it is never saved in  and .|These credentials remain in the . Export the matching environment variables and restart:|Budget box details|Refresh quota||Anthropic (Claude Pro/Max)|Z.ai / Zhipu GLM |MiniMax |MiniMax Plan|Quota origin (HTTPS)|Empty: official sites. Otherwise the Key is sent only to this origin. Use a trusted address without a path.|5h|7d|Open DeepSeek top-up page (platform.deepseek.com/usage)|ChatGPT (Codex) weekly quota| (requires signed-in dsh-openai-codex)| in sidebar (keep the conversation strip when hidden)|Include subagents in session cost|No |Display position|“Main sidebar / Both” shows a quota card; the narrow rail shows percentages.|API key (optional; empty = auto-detect)| (minutes)|Refresh|Login|Signing in…||CLIProxyAPI gateway quotas|Add source|Source label|Base URL|Display|Allowed hosts|Management key (write-only)|Status|Unsupported providers|Unknown|No accounts|fetched {time}|Switch account (current: {account})|Gemini quota only|Refresh|Enable this item first|Enable and save a  |Remove|Enabled items move to the top; click a name to expand its own settings. Up to 8 custom balances and 4 gateway sources.|Disabled. Enable it to query this vendor's  quota on the  and show it here.|Enable  rolling 5h, weekly and monthly quotas in the sidebar, Settings and bottom-right corner. Missing subscriptions show a reason.|Bottom-right (dock) display|Show  quota / budget at the bottom-right|Rolling-5h quota|Weekly quota|Monthly quota|Budget used %|5h|Wk|Mo|Daily|Budget|Ledger read failed: {message}|Reading ledger…|Ledger unavailable|Sync failed: {message}|History cleared.|Clear failed: {message}|Peak/ is off;  used|Not yet effective (effective at {time});  currently used|Peak hour now; peak prices apply| pricing is active; current calls are  peak prices|Off-peak now;  apply|Weekend —  (Sat & Sun   all day)|Weekend — |Weekend|Chinese public holiday — off-peak all day|Public holiday — |Holiday|Public holidays (Beijing dates, comma separated)|Since Aug 23, 2026 (Beijing time),  all day, including work-shift weekends.|Peak|Off-peak|Peak period strip style|Compact (one-line)|Classic (segments & chip)|Popup alert before peak/off-peak switch|Lead time (minutes, 1-30)|Alert type|Entering peak||Both|Entering peak hours soon| hours soon|Billing switches to {phase} pricing in about {time}; mind your call costs in this window.|peak|off-peak|Got it|Peak alert|Off-peak alert|Popup position|Bottom-right|Screen center|Also send a system notification|When enabled, allow notification permission in the browser address bar so you get alerted even when the page is minimized or backgrounded.|Preview the popup| peak| off-peak| (preview)|Peak/ & notice|Notice hidden: enable peak/ and the “prominent notice” toggle.|General|Money & currency|Sidebar display|Simplify the sidebar|Condense cards but keep amounts, quotas and hover details. Height is capped at 38% of the viewport with scrolling. Turn off to restore.|A lighter sidebar|Simple display leaves more room for conversations. Enable it now? You can change it  → Cost → Display anytime.|Enable simple display|Keep current display|Settings could not be saved. Retry or dismiss this guide and change them later .|Dismiss guide|Today / {period} budget|Sidebar progress style|Standard|Compact (2 columns)|Restore removed models ({count})|Remove clears the override and hides the row until restored. Usage records are kept; automatic price matching applies.|Corner chips|Box details|Extended price catalog|Reference prices by vendor and model. Mount to edit and bill; unmounted DeepSeek uses its default price.|Expand |Collapse |Mount|Unmount|Mounted|Unpriced|Unmounted .|Per-model statistics (tokens & cost)|Sidebar model costs|{n} models|Other|Show model cost card|Expand by default|Remember expansion|Show tokens|Show cost shares|Top model in corner dock|Default period|Collapsed summary|Card position|Model rows (1–10)| (10–60 seconds)|Period total and model count|Top model and cost|Top|After balances|Bottom|Today|Last 90 days|Cost ranking||Cache hit rate|unreported?|Zero cache hits on long calls may mean a relay removed cache fields. All-miss ; check with the direct API.|Value · tokens per USD|Input|Cache|Output|No usage data for this period.|blended {price}/M|Hit rate = cache reads ÷ (reads + uncached input). “Unreported?” means cache data may be missing, so . Unit price = cost ÷ tokens × 1M; value = tokens ÷ cost.|Unattributed (early data · billed as recorded)| {amount} (API) · Plan equiv. {planAmount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}| {amount} (API) · Plan equiv. {planAmount}|Cost {amount} (+Plan)|Plan  usage (equiv.) {amount}| usage stats (per-1% & full-window estimates)|No   yet. Enable and refresh a provider under Quotas.|Window|Used %|This period actual ()|Per 1% quota ≈|Full window (100%) ≈|resets {time}|sample delta|current usage ratio|not enough samples|{method} (as of {time})|low reading precision|Plan usage curves (aggregated from sample intervals)|Daily|Weekly|Monthly|Not enough samples: refresh successfully twice with a quota percentage change.|{date}: full-window est. ≈ {full} (per 1% ≈ {per1}) · actual {tokens} / {cost} · {intervals} sample interval(s)|Amounts are catalog-price equivalents. Plans use quota; budgets count API only. Estimates cover dsh calls, while server percentages cover the account. Short samples are less precise. 5h rolls; week/month use local dates.|Billing class|Plan subscription|Auto|API usage|Show directly in |Controls direct display in ; mounting and billing stay unchanged. Hidden models remain editable in this catalog.|Choose where each model appears. DeepSeek shows directly; other vendors default to the catalog.|Custom models|Auto-match unknown model names|Auto (strip suffix / prefix / family similarity)|Exact match only|Manual overrides take priority. Auto-match accepts only the same name or date, version and context suffixes. Unknown ; other providers stay unpriced.|Recently seen models without a price hit|These models have no price. Assign one manually; “Default price” uses DeepSeek defaults. Local inference costs zero until assigned.|DeepSeek default price|Remove|Local model (zero cost)|Models matched this month|These models matched automatically. Choose another price or zero cost; tokens still count. Saved overrides move to the manual list.|Keep auto match|No manual match overrides.|Mounted (billed)|Input|Cached|Output|DeepSeek price table (mounted)|Kimi / Moonshot|OpenRouter|SiliconFlow|CommandCode|SCNet | |Qwen  (qianwenai.com)|Xiaomi MiMo |Plan credits|Compensation|Balance|Quota source|Local estimate|Official CLI|Bailian CLI|Install @qianwenai/qianwen-cli  and run  .|Install bailian-cli . Login opens that host’s browser; for a remote or headless host, run bl auth login --console .| (personal Lite 50K / Standard 500K; see your plan page)| (optional, YYYY-MM-DD; empty = calendar month)|Credits rate overrides (optional; credits deducted per 1M tokens; empty = built-in table)|Model name, e.g. qwen3.8-max-preview|rate|Input|Cached input|Output|Enter all three positive rates to save automatically; clear all to restore the built-in table.|Add|Local Credits estimate; console is authoritative. Counts qwen and qwen/qianwen-tokenplan subscription routes, including llm- prefix. Excludes pay-as-you-go API. Add rates for other models.| for local estimates (Basic 60,000 / Standard 240,000 / Pro 600,000)| (optional, YYYY-MM-DD; empty = calendar month)|Uses console snapshots newer than 24h, then estimates from local records and official Credits rates. Other tools and unlisted models are excluded.|Volcengine AccessKey ID|Volcengine SecretAccessKey| needs AK/SK, ArkReadOnlyAccess and BillingCenterReadOnlyAccess. Enter credentials or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Only open.volcengineapi.com is contacted.|AK...|SK...|{h}h|{h}h {m}m|{m}m|Off-peak in {time}|Peak in {time}|Peak hours (UTC): {windows}; effective: {time}. {status}|No peak windows configured. {status}|unknown|Today|||Since  was created · Calls {calls}|External usage|DSH + external total|External snapshot has not been updated for 24 hours|Recent daily records|Amounts use the latest snapshot and may lag  bill by minutes. Tokens include input, output, cache and reasoning; reasoning is billed with output. Reconcile by amount.|Today/month use host timezone {host}; this browser uses {browser}. Different day boundaries affect reconciliation. Set dsh to your local timezone to align.|Today's sessions|Click a date row to expand its |Loading …|No  for this day (early data or session logs cleaned)| load |By session (all history)|Days combined; subagents follow settings. Selected rows shown; cumulative costs include every conversation.|No session data yet|Loading …| load |Rows|Show session IDs in session lists|Include plan totals|When on, every amount shows total equivalent cost including plan subscriptions; off (default) counts real-money API channels only|Hide  (balance UI  and settings)|Hide today's cost (today's amount , budget details and overview card)|Hide header cost details|Hide composer cost details|Hide turn cost summaries|Sort|Cost high→low|Cost low→high|Time new→old|Time old→new|Recent order|History|Cost statistics requires the module loader from DSH 0.2.0-rc.2 or newer.| stats|All-time {tokens} tokens · input {input} · cache {cache} · output {output} · {calls} calls|{date}: {tokens} tokens (input {input} · cache {cache} · output {output}) · {calls} calls · {cost}|No history yet — daily usage will accumulate here|Usage| stats position||General settings|Own section (Usage)|Display settings|Overview|Quotas|Usage|Pricing|Display|History data|Session cost |Below the composer|Session title bar|Off|Quota strip |Enable the quota strip (one row  box)| budget used %| the |  quotas|Hover a chip for reset times and the last refresh; the strip hides itself when there is no .|New: quota strip |Show budget and /coding-plan percentages  box. Enable now? Change it anytime  → Display.|Enable the strip|Not now|Click  now|New: click the balance box |Click a sidebar balance or plan box . It pulses while loading; on failure it keeps the old value and shows the reason on hover.|Got it|Today cost display|Sidebar footer|Currency|Chinese Yuan (CNY)|US Dollar (USD)|Euro (EUR)|Currency symbol|Exchange rate (1 USD = ? target currency)|Decimal places|Balance |Main sidebar|Settings page|Both|Balance  (minutes)|Use  prices|Prominent notice during peak hours (sidebar budget box, today's cost; previewed in the Settings peak panel)|Session cost uses call-time prices, including peak and . Input, output, cache reads and writes are separate; configured cache-write and long-context rates apply.|Price table (USD / 1M tokens)|Official price currency|USD (English official page)|CNY (Chinese official page)|Selects  pricing-page language. Sync then recalculates history in the background; sessions without full logs keep their earlier basis.|Call-time prices: Flash changes Sep 10 04:00 UTC; V4 Pro uses Flash  Sep 14 04:00 UTC. Earlier calls retain history. Mon–Fri peaks 01–04 and 06–10 UTC cost 2×; . Cache writes use hit rates.|Current rates are shown here. Editing cancels any future scheduled change for this entry; earlier  are retained.|default (fallback for unmatched models)|New model ID (e.g. deepseek-v4-pro)|Add model|Data & sync|Saving…|Auto-save failed: {message}|Auto-saved {time}|Settings are auto-saved|Overwrite the price table with   docs?|Apply|Cancel|Sync  official docs|Official sync updates DeepSeek prices (including peak rates). Third-party prices (z-ai/Kimi/Qwen/Volcano) follow releases; edit in the extended catalog or model matching.|?|Import |Confirm import? Replays all session logs and only fills dates/sessions missing from ; existing records are untouched.| import : {message}|Pre-install history imports at first launch; rerun after copying old logs. Costs use current prices. Deleted logs cannot replay; sessions spanning installation exclude earlier usage.|Confirm clear||Last sync: {time}|Never (bundled prices)|; Source: {source}|Official docs|Bundled|Language|Follow DSH (auto)|Simplified Chinese|English|Cost|{method} |Sync |Balance refresh `]].map(([t,s])=>{const o=s.replace(/[-]/g,a=>Ja[a.charCodeAt(0)-57344]).split("|");return[t,Object.fromEntries(Va.map((a,n)=>[a,o[n]]).filter(([,a])=>a!=="\0"))]}));function Xt(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function Ee(t){const s=typeof t=="string"?t.toLowerCase().split(/[-_]/)[0]:"";return s==="zh"||s==="en"?s:null}function _(t){const s=typeof t=="string"?t:t?.locale;return s==="zh"||s==="en"?s:Ee(t?.activeLocale)||Xt()}function G(t){const s=t==="zh"?Oe.zh:Oe.en;return(o,a)=>{let n=s[o]??Oe.en[o]??o;if(a)for(const l of Object.keys(a))n=n.split("{"+l+"}").join(String(a[l]));return n}}const Ie={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustomRange"};function ue(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function ge(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&ue(s,"object"),t}function ae(t,s){return(typeof t!="number"||!Number.isFinite(t))&&ue(s,"number"),t}function re(t,s){return typeof t!="string"&&ue(s,"string"),t}const et=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function ea(t,s=!1){return t===null||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([o,a])=>s?o.length>0&&["plan","api"].includes(a):["auto","plan","api"].includes(a)))}function Me(t,s){return typeof t!="boolean"&&ue(s,"boolean"),t}const qe=(t,s,o)=>Object.fromEntries(s.map(a=>[a,o(t[a])]));function ta(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const a of Object.keys(t)){const n=t[a];if(n===null||typeof n!="object"||Array.isArray(n))continue;const l=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:0;o[a]={...qe(n,["input","output","cacheRead","cacheWrite","reasoning","cost"],l),apiCost:n.apiCost===void 0?l(n.cost):l(n.apiCost)}}return o}function aa(t,s){ge(t,s);const o={reasoning:t.reasoning===void 0?0:ae(t.reasoning,s+".reasoning"),apiCost:t.apiCost===void 0?void 0:ae(t.apiCost,s+".apiCost"),byModel:ta(t.byModel,s+".byModel"),byProviderModel:ta(t.byProviderModel,s+".byProviderModel")};for(const a of["input","output","cacheRead","cacheWrite","calls","cost"])o[a]=ae(t[a],s+"."+a);return o}function na(t){return(Array.isArray(t)?t:ue("rows","array")).map(s=>({provider:re(s.provider,"provider"),model:re(s.model,"model"),bucket:re(s.bucket,"bucket"),tokens:ae(s.tokens,"tokens"),rate:ae(s.rate,"rate"),cost:ae(s.cost,"cost"),priced:Me(s.priced,"priced"),plan:Me(s.plan,"plan")}))}function gt(t,s){return{...aa(t,s),id:re(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:""}}function he(t,s){const o={...aa(t,s),date:re(t.date,s+".date"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||ue(s+".sessions","array"),o.sessions=t.sessions.map((a,n)=>gt(a,s+".sessions["+n+"]"))),o}function ht(t,s,o=["cacheWrite","reasoning"]){const a={};for(const n of["cacheHit","cacheMiss","output"])a[n]=ae(t[n],s+"."+n);for(const n of o)t[n]!==void 0&&(a[n]=ae(t[n],s+"."+n));return a}function yt(t,s){ge(t,s);const o=ht(t,s);for(const a of["offPeak","peak","legacyBase","longContext"])t[a]!==void 0&&(o[a]=ht(t[a],s+"."+a,["cacheWrite","reasoning","aboveInputTokens"]));t.cny!==void 0&&(o.cny=ht(t.cny,s+".cny")),t.legacy!==void 0&&(o.legacy=Me(t.legacy,s+".legacy")),t.rateHistory!==void 0&&((!Array.isArray(t.rateHistory)||t.rateHistory.length>16)&&ue(s+".rateHistory","price history"),o.rateHistory=t.rateHistory.map((a,n)=>((!a||typeof a.before!="string"||!Number.isFinite(Date.parse(a.before)))&&ue(s+".rateHistory","dated price"),{...yt({...a,rateHistory:void 0},s+".rateHistory."+n),before:a.before})));for(const a of["billingMode","sourceUrl","checkedAt","notes"])typeof t[a]=="string"&&(o[a]=t[a]);return o}function Za(t,s){const o=n=>n==null?void 0:{...n.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:n.enabled===!0,label:typeof n.label=="string"?n.label:"",labelEn:typeof n.labelEn=="string"?n.labelEn:"",display:et(n.display,["sidebar","settings","off"],"both"),unit:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",convertToDisplayCurrency:n.convertToDisplayCurrency===!0,refreshMinutes:typeof n.refreshMinutes=="number"&&Number.isFinite(n.refreshMinutes)?n.refreshMinutes:15,request:n.request&&typeof n.request=="object"?n.request:{url:""},extract:n.extract&&typeof n.extract=="object"?n.extract:{},allowedHosts:Array.isArray(n?.allowedHosts)?n.allowedHosts.filter(l=>typeof l=="string"):[]};ge(t,s);const a={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const n of Object.keys(t.prices.models))a[n]=yt(t.prices.models[n],s+".prices.models."+n);return{locale:t.locale==="zh"||t.locale==="en"||t.locale==="auto"?t.locale:"auto",position:t.position==="header"||t.position==="off"?t.position:"dock",sidebar:t.sidebar!==!1,showSessionId:t.showSessionId===!0,hideOfficialBalance:t.hideOfficialBalance===!0,hideTodayCost:t.hideTodayCost===!0,...qe(t,["hideSessionCostHeader","hideSessionCostDock","hideTurnCost"],n=>n===!0),sessionCostCompact:t.sessionCostCompact===!0,sidebarTodayMetric:t.sidebarTodayMetric==="tokens"?"tokens":"cost",showTotalWithPlan:t.showTotalWithPlan===!0,sidebarSimple:t.sidebarSimple===!0,sidebarSimplePromptSeen:t.sidebarSimplePromptSeen===!0,sidebarModels:Object.fromEntries(Object.entries(Wt).map(([n,l])=>[n,t.sidebarModels?.[n]??l])),codexQuotaEnabled:t.codexQuotaEnabled===!0,codexQuotaSidebar:t.codexQuotaSidebar!==!1,includeSubagentCost:t.includeSubagentCost===!0,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(n=>typeof n=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:ae(t.decimals,s+".decimals"),exchangeRate:ae(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((n,l)=>({start:ae(n.start,s+".peakWindows["+l+"].start"),end:ae(n.end,s+".peakWindows["+l+"].end")})):[],peakHolidays:Array.isArray(t.peakHolidays)?t.peakHolidays.filter(n=>typeof n=="string"):[],peakNotice:t.peakNotice!==!1,peakAlertEnabled:t.peakAlertEnabled!==!1,peakAlertAhead:Number.isFinite(t.peakAlertAhead)&&t.peakAlertAhead>=1&&t.peakAlertAhead<=30?t.peakAlertAhead:2,peakAlertTarget:t.peakAlertTarget==="peak"||t.peakAlertTarget==="offpeak"?t.peakAlertTarget:"both",peakAlertPosition:t.peakAlertPosition==="center"?"center":"corner",peakAlertWebNotify:t.peakAlertWebNotify===!0,peakStyle:t.peakStyle==="classic"?"classic":"compact",priceMatch:t.priceMatch==="exact"?"exact":"auto",priceOverrides:(()=>{const n={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[l,i]of Object.entries(t.priceOverrides))typeof l=="string"&&typeof i=="string"&&(n[l]=i);return n})(),priceTableDisplay:(()=>{const n={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[l,i]of Object.entries(t.priceTableDisplay))typeof l=="string"&&(n[l]=i===!0);return n})(),codingPlans:(()=>{const n={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const l of Object.keys(t.codingPlans)){const i=t.codingPlans[l];i===null||typeof i!="object"||Array.isArray(i)||(n[l]={enabled:i.enabled===!0,display:i.display==="sidebar"||i.display==="both"||i.display==="off"?i.display:"settings",refreshMinutes:typeof i.refreshMinutes=="number"&&Number.isFinite(i.refreshMinutes)?i.refreshMinutes:15,apiKey:typeof i.apiKey=="string"?i.apiKey:"",...l==="minimax"?{baseUrl:typeof i.baseUrl=="string"?i.baseUrl:""}:{},...l==="qwen"?{quotaSource:["cli","bailian"].includes(i.quotaSource)?i.quotaSource:"local"}:{},...typeof i.planCredits=="number"&&Number.isFinite(i.planCredits)&&i.planCredits>0?{planCredits:i.planCredits}:{},...typeof i.planStart=="string"?{planStart:i.planStart}:{},...i.rates!==null&&typeof i.rates=="object"&&!Array.isArray(i.rates)?{rates:i.rates}:{},...typeof i.accessKeyId=="string"?{accessKeyId:i.accessKeyId}:{},...typeof i.secretAccessKey=="string"?{secretAccessKey:i.secretAccessKey}:{}})}return n})(),prices:{models:a,default:yt(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:ae(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:re(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:et(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:et(t.goQuota?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.goQuota?.refreshMinutes=="number"&&Number.isFinite(t.goQuota.refreshMinutes)?t.goQuota.refreshMinutes:15,apiKey:typeof t.goQuota?.apiKey=="string"?t.goQuota.apiKey:"",main:t.goQuota?.main==="weekly"||t.goQuota?.main==="monthly"?t.goQuota.main:"rolling",detail:t.goQuota?.detail!==!1},customBalance:o(t.customBalance),gatewayQuotas:(()=>{const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(n)?n.slice(0,4).filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).map(i=>({id:typeof i.id=="string"?i.id.slice(0,48):"",type:"cliproxyapi",label:typeof i.label=="string"?i.label.slice(0,80):"",baseURL:typeof i.baseURL=="string"?i.baseURL:"",enabled:i.enabled!==!1,display:et(i.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof i.refreshMinutes=="number"&&Number.isFinite(i.refreshMinutes)?Math.min(1440,Math.max(1,Math.floor(i.refreshMinutes))):15,includeProviders:Array.isArray(i.includeProviders)?[...new Set(i.includeProviders.filter(r=>typeof r=="string").map(r=>r.toLowerCase()).filter(r=>xt.includes(r)))]:xt,allowedHosts:Array.isArray(i.allowedHosts)?i.allowedHosts.filter(r=>typeof r=="string").slice(0,16):[],allowInsecureHttp:i.allowInsecureHttp===!0,antigravityOnlyGemini:i.antigravityOnlyGemini===!0,keyVar:typeof i.keyVar=="string"?i.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(l=>l!==null&&typeof l=="object").slice(0,8).map(o).filter(Boolean);const n=o(t.customBalance);return n?[n]:[]})(),corner:{enabled:t.corner?.enabled===!0,goRolling:t.corner?.goRolling!==!1,goWeekly:t.corner?.goWeekly!==!1,goMonthly:t.corner?.goMonthly!==!1,budget:t.corner?.budget!==!1},quotaStrip:{enabled:t.quotaStrip?.enabled===!0,budget:t.quotaStrip?.budget!==!1,go:t.quotaStrip?.go!==!1,plans:t.quotaStrip?.plans!==!1,promptSeen:t.quotaStrip?.promptSeen===!0},usage:{position:t.usage?.position==="general"||t.usage?.position==="section"?t.usage.position:"cost"},barDirections:(()=>{const n=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},l=(i,r)=>n[i]==="remaining"||n[i]==="used"?n[i]:r;return{balance:l("balance","remaining"),budget:l("budget","used"),go:l("go","used"),plan:l("plan","used")}})(),planBilling:{providers:ea(t.planBilling?.providers),models:ea(t.planBilling?.models,!0)}}}const je=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Pe=t=>je(t)??0,$a={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},Xa={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},sa=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function kt(t,s){return ge(t,s),{status:t.status==="ok"||t.status==="error"?t.status:"off",message:typeof t.message=="string"?t.message:"",fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:0}}function en(t,s){return{...kt(t,s),keyConfigured:t.keyConfigured===!0,keySource:typeof t.keySource=="string"?t.keySource:"",currency:typeof t.currency=="string"?t.currency:"",totalBalance:Pe(t.totalBalance),grantedBalance:Pe(t.grantedBalance),toppedUpBalance:Pe(t.toppedUpBalance)}}function wt(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&ue(s,"object"),{percent:Pe(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function tn(t,s){return{...kt(t,s),rolling:wt(t.rolling,s+".rolling"),weekly:wt(t.weekly,s+".weekly"),monthly:wt(t.monthly,s+".monthly")}}function oa(t,s){return{...kt(t,s),label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:Pe(t.remaining),maxBudget:je(t.maxBudget),spend:je(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const an=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),nn=new Set(["off","loading","ok","partial","stale","error"]),xt=["antigravity","claude","codex","kimi","xai","workbuddy"],la={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function sn(t,s){ge(t,s);const o=(i,r="")=>typeof i=="string"?i:r,a=i=>je(i),n=i=>i!==null&&typeof i=="object"&&!Array.isArray(i)?{id:o(i.id),label:o(i.label),...a(i.percent)===null?{}:{percent:a(i.percent)},resetsAt:o(i.resetsAt),periodHours:a(i.periodHours),scope:o(i.scope)}:null,l=i=>i!==null&&typeof i=="object"&&!Array.isArray(i)?{unit:o(i.unit,"credits"),used:a(i.used),remaining:a(i.remaining),limit:a(i.limit),fetchedAt:o(i.fetchedAt),packages:Array.isArray(i.packages)?i.packages.filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)).map(r=>({id:o(r.id),label:o(r.label),used:a(r.used),remaining:a(r.remaining),limit:a(r.limit),startsAt:o(r.startsAt),resetsAt:o(r.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:nn.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:a(t.fetchedAt)??0,attemptedAt:a(t.attemptedAt)??0,serverVersion:o(t.serverVersion),keyConfigured:t.keyConfigured===!0,keySource:o(t.keySource,"none"),accounts:Array.isArray(t.accounts)?t.accounts.filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).slice(0,16).map(i=>({id:o(i.id),provider:o(i.provider,"unknown"),label:o(i.label,"unknown"),status:an.has(i.status)?i.status:"unknown",message:o(i.message),plan:o(i.plan),windows:Array.isArray(i.windows)?i.windows.map(n).filter(Boolean):[],credits:l(i.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(i=>typeof i=="string").slice(0,32):[]}}function on(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};if(t.providers!==null&&typeof t.providers=="object"&&!Array.isArray(t.providers))for(const[o,a]of Object.entries(t.providers)){if(a===null||typeof a!="object"||Array.isArray(a))continue;const n={},l={};if(a.windows!==null&&typeof a.windows=="object"&&!Array.isArray(a.windows))for(const[i,r]of Object.entries(a.windows))r===null||typeof r!="object"||Array.isArray(r)||(n[i]={...qe(r,["percent","localTokens","localCost","sampleCount"],Pe),...qe(r,["sampleAt","per1Tokens","per1Cost","fullTokens","fullCost"],je),resetsAt:typeof r.resetsAt=="string"?r.resetsAt:"",method:r.method==="sample"||r.method==="live"?r.method:"none",confidence:r.confidence==="high"||r.confidence==="low"?r.confidence:null});if(a.intervals!==null&&typeof a.intervals=="object"&&!Array.isArray(a.intervals))for(const[i,r]of Object.entries(a.intervals))Array.isArray(r)&&(l[i]=r.filter(d=>d!==null&&typeof d=="object"&&!Array.isArray(d)).map(d=>qe(d,["t0","t1","tokens","cost","pct","per1Tokens","per1Cost"],Pe)));s[o]={windows:n,intervals:l}}return{generatedAt:Pe(t.generatedAt),providers:s}}function ia(t,s){return ge(t,s),{today:he(t.today,s+".today"),month:he(t.month,s+".month"),total:he(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?$a:en(t.balance,s+".balance"),goQuota:t.goQuota==null?Xa:tn(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?sa():oa(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,a)=>oa(o,s+".customBalances["+a+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,a)=>sn(o,s+".gatewayQuotas["+a+"]")):[],customVarStatus:t.customVarStatus!==null&&typeof t.customVarStatus=="object"&&!Array.isArray(t.customVarStatus)?Object.fromEntries(Object.entries(t.customVarStatus).filter(([,o])=>o!==null&&typeof o=="object").map(([o,a])=>[o,{configured:a.configured===!0,source:typeof a.source=="string"?a.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:on(t.planStats),history:Array.isArray(t.history)?t.history.map((o,a)=>he(o,s+".history["+a+"]")):[],externalUsage:t.externalUsage&&Array.isArray(t.externalUsage.sources)?{fetchedAt:Number(t.externalUsage.fetchedAt)||0,stale:t.externalUsage.stale===!0,sources:t.externalUsage.sources.map(o=>({source:String(o.source),today:he(o.today,s+".external.today"),month:he(o.month,s+".external.month"),total:he(o.total,s+".external.total"),history:(o.history??[]).map(a=>he(a,s+".external.history"))})),combined:Object.fromEntries(["today","month","total","history"].map(o=>[o,o==="history"?(t.externalUsage.combined.history??[]).map(a=>he(a,s+".external.history")):he(t.externalUsage.combined[o],s+".external."+o)]))}:null,config:Za(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:{...Ee(t.meta?.locale)?{locale:Ee(t.meta.locale)}:{},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 ln(t,s){ge(t,s);const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=ia(t.state,s+".state")),o}function le(t){return{parse:t}}const vt=le(ia),rn=le(t=>ge(t,"patch")),cn=le(ln),Nt=le(t=>re(t,"provider")),dn=le(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&ue("index","0-7 integer"),t}),un=le(t=>re(t,"date")),mn=le(t=>ge(t,"day")),pn=le(t=>(Number.isFinite(Number(t))||ue("limit","number"),Number(t))),ra=le(t=>re(t,"sort")),fn=le(t=>ge(t,"topSessions")),ca=le(t=>re(t,"target")),bn=le(t=>re(t,"value")),ve=(t,s)=>({mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:s,create:()=>s}),ce=(t,s,o,a=!1)=>({name:t,wire:t,source:"json",codec:ve(s,o),...a?{acceptsUndefined:!0}:{}}),gn={package:"dsh-cost-meter",descriptors:[{method:"getState",result:ve("CostState",vt)},{method:"updateConfig",parameters:[ce("patch","ConfigPatch",rn)],result:ve("CostState",vt)},{method:"fetchPrices"},{method:"refreshBalance"},{method:"refreshGoQuota"},{method:"refreshCustomBalance",parameters:[ce("index","CustomBalanceIndex",dn,!0)]},{method:"refreshCodingPlan",parameters:[ce("provider","CodingPlanProvider",Nt)]},{method:"loginCodingPlan",parameters:[ce("provider","CodingPlanProvider",Nt)]},{method:"refreshGatewayQuota",parameters:[ce("sourceId","GatewayQuotaSourceId",le(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&ue("sourceId","gateway source id"),t}),!0)]},{method:"resetHistory",result:ve("CostState",vt)},{method:"importLegacyHistory"},{method:"getDaySessions",parameters:[ce("date","DayKey",un)],result:ve("DayRecord",mn)},{method:"getSessionCost",parameters:[ce("sessionId","SessionId",Nt)],result:ve("SessionCost",le(t=>({own:gt(t.own,"own"),subagents:gt(t.subagents,"subagents"),found:Me(t.found,"found"),subagentCount:ae(t.subagentCount,"subagentCount")})))},{id:"dsh-cost-meter#costMeter/getTurnCost",service:"costMeter",namespace:"costMeter",method:"getTurnCost",invocation:{kind:"direct"},parameters:[ce("sessionId","SessionId",le(t=>re(t,"sessionId"))),...["startSeq","endSeq"].map(t=>ce(t,"TurnSeq",le(s=>((!Number.isSafeInteger(s)||s<0)&&ue(t,"nonnegative integer"),s))))],result:ve("TurnCost",le(t=>({found:Me(t.found,"found"),cost:ae(t.cost,"cost"),apiCost:ae(t.apiCost,"apiCost"),rows:na(t.rows),calls:(Array.isArray(t.calls)?t.calls:ue("calls","array")).map(s=>({kind:re(s.kind,"kind"),provider:re(s.provider,"provider"),model:re(s.model,"model"),atMs:ae(s.atMs,"atMs"),cost:ae(s.cost,"cost"),apiCost:ae(s.apiCost,"apiCost"),plan:Me(s.plan,"plan"),priced:Me(s.priced,"priced"),longContext:Me(s.longContext,"longContext"),rows:na(s.rows)}))})))},{method:"getTopSessions",parameters:[ce("limit","SessionLimit",pn),ce("sort","SessionSort",ra,!0),ce("dir","SessionSortDir",ra,!0)],result:ve("TopSessions",fn)},{method:"setCredential",parameters:[ce("target","CredentialTarget",ca),ce("value","CredentialValue",bn)]},{method:"clearCredential",parameters:[ce("target","CredentialTarget",ca)]}].map(t=>({id:"dsh-cost-meter#costMeter/"+t.method,service:"costMeter",namespace:"costMeter",invocation:{kind:"direct"},parameters:[],result:ve("FetchPricesResult",cn),...t}))};function hn(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 Ue(t){if(t===null||typeof t!="object")return;const s=i=>{const r=t[i];return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0},o=s("cacheMiss")??s("input")??0,n={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},l=s("reasoning");return l!==void 0&&(n.reasoning=l),s("cacheWrite")!==void 0&&(n.cacheWrite=s("cacheWrite")),n}function yn(t){const s=Ue(t);if(s===void 0)return null;t.billingMode==="utc-peak"&&(s.billingMode="utc-peak");for(const o of["offPeak","peak","legacyBase"]){const a=Ue(t[o]);a!==void 0&&(s[o]=a)}return Number.isFinite(t.longContext?.aboveInputTokens)&&t.longContext.aboveInputTokens>0&&(s.longContext={...Ue(t.longContext),aboveInputTokens:t.longContext.aboveInputTokens}),Array.isArray(t.rateHistory)&&(s.rateHistory=t.rateHistory.slice(0,16).map(o=>{const a={...Ue(o),before:o.before};for(const n of["offPeak","peak"]){const l=Ue(o[n]);l!==void 0&&(a[n]=l)}return a})),s}function tt(t,s=Date.now()){if(!t||!Number.isFinite(s)||!Array.isArray(t.rateHistory))return t;let o=null,a=1/0;for(const i of t.rateHistory){const r=Date.parse(i.before);s<r&&r<a&&(o=i,a=r)}if(!o)return t;const{before:n,...l}=o;return{...t,...l}}const St=Date.parse("2026-08-22T16:00:00Z");function da(t){if(!Number.isFinite(t)||t<St)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const a=o===6?s:s-1;return{start:Math.max(a*864e5-8*36e5,St),end:(a+2)*864e5-8*36e5}}function ua(t,s){if(!Number.isFinite(t)||t<St||!Array.isArray(s))return null;const o=Math.floor((t+8*36e5)/864e5);return s.includes(new Date(o*864e5).toISOString().slice(0,10))?{start:o*864e5-8*36e5,end:(o+1)*864e5-8*36e5}:null}const kn=(t,s)=>ua(t,s)??da(t);function at(t,s,o,a){if(!Array.isArray(o)||o.length===0||kn(t,a)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(l=>{const i=Number(l.start),r=Number(l.end);return!Number.isFinite(i)||!Number.isFinite(r)?!1:i<r?n>=i&&n<r:n>=i||n<r})}const wn=Date.parse("2026-08-16T16:00:00Z");function ma(t,s,o){const a=tt(t,s)??{cacheHit:0,cacheMiss:0,output:0},n=i=>({cacheHit:i.cacheHit,cacheMiss:i.cacheMiss,output:i.output,reasoning:i.reasoning??0,...i.cacheWrite===void 0?{}:{cacheWrite:i.cacheWrite},...i.longContext===void 0?{}:{longContext:i.longContext}});if(a.billingMode==="utc-peak"){if(o?.enabled!==!0||!Number.isFinite(s))return n(a);const i=new Date(s),r=i.getUTCDay(),d=i.getUTCHours(),u=r>0&&r<6&&(d>=1&&d<4||d>=6&&d<10);return n((u?a.peak:a.offPeak)??a)}if(Number.isFinite(s)&&s<wn){const i=a.legacyBase;return n(i===void 0?a:i)}if(o?.enabled!==!0)return n(a);const l=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(at(s,l,o.windows,o.holidays)){const i=a.peak;return n(i===void 0?a:i)}if(l!==void 0&&s>=l){const i=a.offPeak;return n(i===void 0?a:i)}return n(a)}function pa(t,s){const o=Math.max(0,Number(t.input)||0),a=Math.max(0,Number(t.output)||0),n=Math.max(0,Number(t.cacheRead)||0),l=Math.max(0,Number(t.cacheWrite)||0),i=Math.max(0,Number(t.reasoning)||0);return s.longContext&&o+n+l>s.longContext.aboveInputTokens&&(s=s.longContext),(o*s.cacheMiss+a*s.output+n*s.cacheHit+l*(s.cacheWrite??s.cacheHit)+i*(s.reasoning??0))/1e6}function fa(t,s,o){const a=Number(t);if(!Number.isFinite(a)||a<0||a===0)return 0;if(s!=="CNY")return a;const n=Number(o);return!Number.isFinite(n)||n<=0?a:a/n}function ie(t,s){const o=t?.barDirections,a=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return a;const n=o[s];return n==="remaining"||n==="used"?n:a}function fe(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),a=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:a,label:a}}const ba=(t,s)=>t.toFixed(s).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1");function me(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",a=Number(s?.decimals),n=Math.max(0,Math.min(10,Number.isFinite(a)?Math.floor(a):2));let l=n;return t>0&&t<Math.pow(10,-n)&&(l=n+2),o+ba(t,l)}function Y(t,s){const o=Number(s?.exchangeRate),a=t*(Number.isFinite(o)&&o>0?o:1);return me(a,s)}function I(t){const s=Math.max(0,Number(t)||0),o=a=>a>=100?String(Math.round(a)):String(Math.round(a*10)/10);return s<1e3?String(Math.round(s)):s>=999500?o(s/1e6)+"M":s<1e6?o(s/1e3)+"K":o(s/1e6)+"M"}function Ct(t){return String(t??"").normalize("NFKC").toLowerCase().replace(/[((]\s*(?:go|zen)\s*[))]/g," ").trim()}function ye(t){return Ct(t).replace(/[^\p{L}\p{N}]+/gu,"")}function xn(t){return Ct(t).replace(/[-_./:@](?:\d{4}-?\d{2}-?\d{2}|v\d+(?:\.\d+)*|\d+k|latest)$/,"")}function At(t,s,o=t){if(typeof t!="string"||t.length===0)return null;const a=Array.isArray(s)?s.filter(i=>typeof i=="string"&&i.length>0):[],n=a.find(i=>i===o);if(n!==void 0)return n;let l=t.normalize("NFKC").trim();if(/[:((]\s*(?:free|online)\b/i.test(l))return null;for(;;){const i=ye(l);if(i.length===0)return null;const r=a.filter(u=>ye(u)===i);if(r.length>0)return r.length===1?r[0]:null;const d=xn(l);if(d===l.toLowerCase())return null;l=d}}const Mt=new Set(["openrouter","opencode-zen","opencode-go","zen","opencode"]),nt={openai:/^(?:gpt|o\d|codex)/i,anthropic:/^claude/i,google:/^gemini/i,deepseek:/^deepseek/i,moonshot:/^kimi/i,"z-ai":/^glm/i,xai:/^grok/i,alibaba:/^qwen/i,minimax:/^minimax/i,tencent:/^(?:hunyuan|hy\d)/i,xiaomi:/^mimo/i,upstage:/^solar/i,nvidia:/^nemotron/i,mistral:/^mistral/i,meta:/^(?:muse|llama)/i,meituan:/^longcat/i};function Pt(t){return["deepseek-peak","utc-peak"].includes(t?.billingMode)?t.billingMode:"flat"}function He(t,s,o,a,n){if(typeof t!="string")return null;if(Object.hasOwn(s,t))return t;if(a!=="auto")return null;let l=t.normalize("NFKC").trim().replace(/^models\/(?=gemini)/i,"google/");const i=l.search(/[/:]/);if(i>0){const r=l.slice(0,i).trim().toLowerCase(),d=l.slice(i+1).trim();if(Object.hasOwn(nt,r)&&(r===o||(o==="opencode-zen"||o==="opencode-go")&&(nt[r].test(d)||At(d,Object.keys(r==="deepseek"?n?.models??{}:n?.providers?.[r]?.models??{}))!==null)))l=d;else if(Object.hasOwn(nt,r))return null}return At(l,Object.keys(s),t)}const vn=new Set(["local","lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),Nn=["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 Sn(t,s){if(typeof t=="string"&&vn.has(t))return!0;const o=typeof s=="string"?Ct(s):"";return Nn.some(a=>o.startsWith(a))}function Cn(t,s,o,a){if(t!=="deepseek"&&!t.includes("deepseek")&&typeof s=="string"&&s.length>0&&s!=="__local__"&&!s.includes(":")){const n=o.models??{},l=Object.hasOwn(n,s)?s:a==="auto"?At(s,Object.keys(n)):null;if(l!==null&&n[l]?.unpriced!==!0)return{entry:n[l],priced:!0,billingMode:"deepseek-peak",matched:!0}}return null}function An(t,s,o){const a=o?.prices??{},n=o?.priceMatch==="exact"?"exact":"auto",l=o?.priceOverrides&&typeof o.priceOverrides=="object"?o.priceOverrides:{};let i=String(t??"").trim().toLowerCase();i.startsWith("llm-")&&(i=i.slice(4)),i===""&&(i="deepseek");let r=i,d=s;const u=l[i+":"+s];if(u==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof u=="string"&&u.length>0){const f=u.indexOf(":");if(f>0&&u.slice(f+1).length>0?(r=u.slice(0,f).trim().toLowerCase(),d=u.slice(f+1)):d=u,r==="deepseek"&&d==="__default__")return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:a.default?.unpriced!==!0,billingMode:"deepseek-peak",matched:!1}}if(["zen","opencode"].includes(r)){const f=He(d,a.providers?.[r]?.models??{},"opencode-go",n,a);f===null?r="opencode-go":d=f}if(Sn(r,d))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(r==="openrouter"){const f=a.providers?.openrouter?.models??{},b=Object.hasOwn(f,d)?f[d]:null;return{entry:b,priced:b!==null&&b.unpriced!==!0,billingMode:"flat",matched:b!==null}}if(r==="deepseek"||r.includes("deepseek")){const f=a.models??{},b=He(d,f,"deepseek",n,a);if(b!==null)return f[b]?.unpriced===!0?{entry:null,priced:!1,billingMode:"flat",matched:!0}:{entry:f[b],priced:!0,billingMode:"deepseek-peak",matched:!0};if(n==="auto"){let g=null,h=-1,x=!1,S="flat";for(const[T,N]of Object.entries(a.providers??{})){if(Mt.has(T))continue;const m=N?.models??{},v=He(d,m,T,n,a);if(v===null)continue;const y=+(v===d||ye(v)===ye(d));y>h?(g=m[v],h=y,x=!1,S=Pt(m[v])):y===h&&(x=!0)}if(x)return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(g!==null)return{entry:g,priced:g.unpriced!==!0,billingMode:S,matched:!0}}return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:a.default?.unpriced!==!0,billingMode:"deepseek-peak",matched:!1}}const c=a.providers?.[r]?.models??{},p=He(d,c,r,n,a);if(p!==null)return{entry:c[p],priced:c[p]?.unpriced!==!0,billingMode:Pt(c[p]),matched:!0};if(Mt.has(r))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(Object.hasOwn(nt,r))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(n==="auto"){let f=null,b=-1,g=!1,h="flat";for(const[x,S]of[["deepseek",{models:a.models??{}}],...Object.entries(a.providers??{})]){if(x===r||Mt.has(x))continue;const T=S?.models??{},N=He(d,T,x,n,a);if(N===null)continue;const m=+(N===d||ye(N)===ye(d));m>b?(f=T[N],b=m,g=!1,h=x==="deepseek"?"deepseek-peak":Pt(T[N])):m===b&&(g=!0)}if(g)return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(f!==null)return{entry:f,priced:f.unpriced!==!0,billingMode:h,matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function Tt(t,s,o){let a=An(t,s,o);if(!a.priced){const n=String(t??"").trim().toLowerCase().replace(/^llm-/,"")||"deepseek";a=Cn(n,o?.priceOverrides?.[n+":"+s],o?.prices??{},o?.priceMatch==="exact"?"exact":"auto")??a}return a.priced&&o?.prices?.currency==="CNY"&&a.entry?.cny?{...a,entry:a.entry.cny,currency:"CNY"}:{...a,currency:a.priced&&a.billingMode==="deepseek-peak"&&o?.prices?.currency==="CNY"?"CNY":"USD"}}function Mn(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,a=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&a===0}function st(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:ha(t,s).total}function Qe(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:Qe(t)}const Pn={go:["go","zen","opencode","opencode-go"],qwen:["qwen","qwen-tokenplan","qianwen-tokenplan","qwen-token-plan","qianwen-token-plan"],scnet:["scnet","scnet-tokenplan","scnet-token-plan"],mimo:["mimo","xiaomimimo","mimo-token-plan","xiaomi-token-plan","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","xiaomi-token-plan-ams"]},ga=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","mimo","go"];function Tn(t){const s=String(t??"").trim().toLowerCase().replace(/^llm-/,"");if(s.length===0)return null;for(const[o,a]of Object.entries(Pn))if(a.includes(s))return o;return ga.includes(s)?s:null}function On(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const a of ga)a!=="go"&&o[a]?.enabled===!0&&s.add(a);return t?.goQuota?.enabled===!0&&s.add("go"),s}const Dn=new Set(["grok-4.5","glm-5.3","glm-5.3-flash","glm-5.2","glm-5.1","gpt-5.6-luna","kimi-k3","kimi-k2.7-code","kimi-k2.6","mimo-v2.6-flash","mimo-v2.6-pro","mimo-v2.5","mimo-v2.5-pro","minimax-m3","minimax-m2.7","qwen3.8-max","qwen3.7-max","qwen3.7-plus","qwen3.6-plus","hy3","longcat-2.0","muse-spark-1.2-contributor"].map(ye));function Bn(t,s,o){const a=String(t??"").trim().toLowerCase();if(a.length>0&&a!=="deepseek"&&!a.includes("deepseek"))return!1;const n=ye(s);if(n.length===0||!Dn.has(n))return!1;const l=o?.prices,i=l?.models??{};for(const r of Object.keys(i))if(ye(r)===n)return!1;for(const r of Object.keys(l?.providers?.["opencode-go"]?.models??{}))if(ye(r)===n)return!0;return!1}function Fe(t,s,o){let a=Tn(t);a===null&&Bn(t,s,o)&&(a="go");const n=o?.planBilling?.models;if(n!==null&&typeof n=="object"){const i=n[t+":"+s];if(i==="plan"||i==="api")return i;if(a!==null){const r=n[a+":"+s];if(r==="plan"||r==="api")return r}}if(a===null)return"api";const l=o?.planBilling?.providers?.[a];return l==="plan"||l==="api"?l:On(o).has(a)?"plan":"api"}function ha(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows,holidays:s.peakHolidays},a=Date.now(),n=t.byProviderModel??t.byModel??{};let l=0,i=0;for(const p of Object.keys(n)){const f=p.indexOf(":"),b=f>0?p.slice(0,f):"deepseek",g=f>0?p.slice(f+1):p,h=Tt(b,g,s);if(h.priced){const x=pa(n[p],ma(yn(h.entry),a,{...o,enabled:["deepseek-peak","utc-peak"].includes(h.billingMode)&&o.enabled})),S=fa(x,h.currency,s.exchangeRate);l+=S,Fe(b,g,s)==="api"&&(i+=S)}}const r={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const p of Object.keys(n))r.input+=n[p].input??0,r.output+=n[p].output??0,r.cacheRead+=n[p].cacheRead??0,r.cacheWrite+=n[p].cacheWrite??0,r.reasoning+=n[p].reasoning??0;const d={input:Math.max(0,(t.input??0)-r.input),output:Math.max(0,(t.output??0)-r.output),cacheRead:Math.max(0,(t.cacheRead??0)-r.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-r.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-r.reasoning)},u=pa(d,ma(hn("default",s.prices),a,o)),c=fa(u,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return l+=c,i+=c,{total:l,api:i}}function ya(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const a of Object.keys(o)){const n=a.indexOf(":"),l=n>0?a.slice(0,n):"deepseek",i=n>0?a.slice(n+1):a;if(Fe(l,i,s)==="plan")return!0}return!1}function Ot(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function ka(t,s){if(t?.apiCost!==void 0)return Qe(t);if(!ya(t,s))return st(t,s);let o=0;for(const[a,n]of Object.entries(t.byProviderModel??{})){if(!Number.isFinite(n.cost))return ha(t,s).api;const l=a.indexOf(":");Fe(a.slice(0,l),a.slice(l+1),s)==="plan"&&(o+=n.cost)}return Math.max(0,st(t,s)-o)}function Dt(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),a=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(a>0?":"+String(a).padStart(2,"0"):"")}function Rn(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const a=-new Date().getTimezoneOffset();if(a===o)return null;const n=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:n?n+" ("+Dt(o)+")":Dt(o),browserLabel:Dt(a)}}function Ln(t,s=o=>o){let o=s(t);const a=new Set;return{getSnapshot:()=>o,subscribe:n=>(a.add(n),()=>{a.delete(n)}),set:n=>{if(n=s(n),n!==o){o=n;for(const l of[...a])l()}}}}const{createElement:e,Fragment:L,useState:B,useEffect:ee,useRef:Ne}=Be;function De({target:t,configured:s,source:o,t:a,api:n,placeholder:l,disabled:i}){const[r,d]=B(""),[u,c]=B(!1),[p,f]=B(!1),[b,g]=B(null),h=Ne(!1),x=i===!0||p,S=async()=>{const m=r.trim();if(!(m.length===0||x||h.current)){h.current=!0,f(!0),g(null);try{const v=await n.setCredential(t,m);d(""),c(!1),g({kind:"ok",text:v?.message??a("credentialSave")})}catch(v){g({kind:"err",text:String(v?.message??v)})}finally{h.current=!1,f(!1)}}},T=async()=>{if(!(x||h.current)){h.current=!0,f(!0),g(null);try{const m=await n.clearCredential(t);d(""),c(!1),g({kind:"ok",text:m?.message??a("credentialClear")})}catch(m){g({kind:"err",text:String(m?.message??m)})}finally{h.current=!1,f(!1)}}},N=()=>{d(""),c(!1)};return e("div",{className:"cm-field"},u?e("form",{className:"cm-field",autoComplete:"off",onSubmit:m=>{m.preventDefault(),S()}},e("input",{className:"cm-input",type:"password",name:"cm-credential-"+t,autoFocus:!0,value:r,placeholder:typeof l=="string"?l:"",disabled:x,autoComplete:"new-password","data-lpignore":"true","data-1p-ignore":"true","data-bwignore":"true","aria-label":a("credentialInputHint"),onChange:m=>d(m.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",type:"submit",disabled:x||r.trim().length===0},a(p?"credentialSaving":"credentialSave")),e("button",{className:"cm-btn small",type:"button",onClick:N,disabled:p},a("cancel")))):e("button",{className:"cm-btn small",type:"button",onClick:()=>c(!0),disabled:x},a("credentialEdit")),s===!0?e("button",{className:"cm-btn small",type:"button",onClick:T,disabled:x},a("credentialClear")):null,e("span",{className:"cm-hint"},s===!0?a("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):a("credentialNotConfigured")),e("span",{className:"cm-hint"},a("credentialInputHint")),Yt(b))}function En({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 ot({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 wa(t,s){const o=Ne(!1),a=Ne(""),n=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(l=>String(l??0)).join("|"):"";ee(()=>{if(!o.current){o.current=!0,a.current=n;return}if(n===""||n===a.current)return;a.current=n;const l=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(l)},[n])}function In(t,s,o,a){const n=s?s.own:t;if(!o||!s?.subagentCount)return n;const l=s.subagents,i={...n};for(const r of["input","output","cacheRead","cacheWrite","reasoning","calls","cost"])i[r]=(n?.[r]??0)+(l?.[r]??0);i.apiCost=ka(n,a)+Qe(l);for(const r of["byModel","byProviderModel"]){i[r]={...n?.[r]};for(const[d,u]of Object.entries(l?.[r]??{})){const c={...i[r][d]};c.apiCost=Qe(c)+Qe(u);for(const p of["input","output","cacheRead","cacheWrite","reasoning","calls","cost"])c[p]=(c[p]??0)+(u[p]??0);i[r][d]=c}}return i}function xa(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?.(r=>r)?.state,a=o?.config,[n,l]=B(null);wa(t,s),ee(()=>{if(!t.sessionId||!t.api?.getSessionCost)return;let r=!0,d=!1;const u=async()=>{if(!d){d=!0;try{const p=await t.api.getSessionCost(t.sessionId);r&&l({id:t.sessionId,include:a?.includeSubagentCost===!0,value:p})}catch{}finally{d=!1}}};u();const c=a?.includeSubagentCost===!0?setInterval(u,1e4):null;return()=>{r=!1,c!==null&&clearInterval(c)}},[t.sessionId,o?.meta?.now,s,a?.includeSubagentCost]);const i=n&&n.id===t.sessionId&&n.include===(a?.includeSubagentCost===!0)?n.value:null;return{usage:In(s,i,a?.includeSubagentCost===!0,a),config:a}}function va(t,s){let o=0,a=st(t,s);if(s.showTotalWithPlan!==!0&&(t.apiCost!==void 0||ya(t,s))){const n={total:st(t,s),api:ka(t,s)};o=Math.max(0,n.total-n.api),o>0&&(a=n.api)}return{cost:a,planPart:o}}function Na(t,s){return Object.entries(t?.byProviderModel??{}).filter(([,o])=>o.input||o.output||o.cacheRead||o.cacheWrite||o.reasoning).map(([o,a])=>o+" "+Y(a.cost,s)).join("; ")}function qn(t){const s=t.useCost?.(h=>h)?.state?.config,[o,a]=B(null),[n,l]=B(""),i=t.turn?.start?.seq,r=t.turn?.end?.seq,d=t.sessionId,u=JSON.stringify([s?.prices,s?.priceOverrides,s?.priceMatch,s?.planBilling,s?.codingPlans,s?.goQuota?.enabled,s?.peakEnabled,s?.peakEffectiveAt,s?.peakWindows,s?.peakHolidays,s?.exchangeRate]);if(ee(()=>{let h=!0;if(a(null),l(""),!(s?.hideTurnCost||!d||i==null||r==null))return t.api.getTurnCost(d,i,r).then(x=>{h&&a(x)},x=>{h&&l(String(x.message??x))}),()=>{h=!1}},[d,i,r,u,s?.hideTurnCost]),!s||s.hideTurnCost||i==null||r==null)return null;const c=_(s)==="en",p=c?{input:"Input",output:"Output",cacheRead:"Cache read",cacheWrite:"Cache write",reasoning:"Reasoning"}:{input:"输入",output:"输出",cacheRead:"缓存读取",cacheWrite:"缓存写入",reasoning:"推理"},f=h=>Y(h,{...s,decimals:Math.max(8,s.decimals??2)}),b=c?{model:"Model call",compaction:"Context compaction",search:"Native search"}:{model:"模型调用",compaction:"上下文压缩",search:"原生搜索"},g=(h,x)=>e("div",{key:x,style:{marginBottom:4,overflowWrap:"anywhere"}},h.provider+":"+h.model+" · "+p[h.bucket]+(h.plan?" (Plan)":"")+": "+h.tokens.toLocaleString()+" × "+(h.priced?f(h.rate):"?")+" / 1,000,000 ≈ "+(h.priced?f(h.cost):"?"),h.priced?h.bucket==="reasoning"&&h.rate===0?c?" (no separate charge)":"(不单独收费)":"":c?" (price unavailable)":"(未配置价格)");return e("details",{className:"cm-note",style:{fontSize:12,marginTop:6}},e("summary",{style:{cursor:"pointer"}},c?"Turn cost":"本轮费用",o?.found?" ≈ "+f(s.showTotalWithPlan?o.cost:o.apiCost)+(o.rows.some(h=>!h.priced)?c?" + unpriced usage":" + 未定价用量":""):n?" ⚠":""),n?e("div",{role:"alert"},n):o?o.found?e(L,null,e("p",null,c?"Estimated from recorded usage and configured prices; rates per 1M tokens.":"按已记录用量和配置价格估算;单价单位为每百万 Token。"),e("p",null,"API ≈ "+f(o.apiCost)+" · Plan ≈ "+f(o.cost-o.apiCost)+(c?" (equivalent)":"(等值)")),o.rows.map(g),e("details",null,e("summary",{style:{cursor:"pointer"}},(c?"Individual calls":"逐次调用明细")+" ("+o.calls.length+")"),o.calls.map((h,x)=>e("details",{key:x,style:{margin:"6px 0"}},e("summary",{style:{cursor:"pointer",overflowWrap:"anywhere"}},"#"+(x+1)+" "+b[h.kind]+" · "+h.provider+":"+h.model+" · "+new Date(h.atMs).toLocaleTimeString()+" · "+(h.plan?"Plan ":"API ")+(h.priced?"≈ "+f(h.cost):c?"price unavailable":"未配置价格")+(h.longContext?c?" · long context":" · 长上下文价格":"")),h.rows.map(g))))):c?"Complete usage records unavailable":"没有完整用量记录":c?"Loading…":"加载中…")}function jn(t){const{usage:s,config:o}=xa(t);if(!s||!o||Ot(s)+(s?.output??0)===0)return null;const a=G(_(o)),{cost:n,planPart:l}=va(s,o),i=[a("sessionCostTitle"),a("sessionDetailTokens",{input:I(s?.input??0),cache:I((s?.cacheRead??0)+(s?.cacheWrite??0)),output:I(s?.output??0)}),a("sessionDetailCache",{read:I(s?.cacheRead??0),write:I(s?.cacheWrite??0)}),a("cost",{amount:Y(n,o)}),...l>0?[a("sessionDetailPlan",{amount:Y(l,o)})]:[],Na(s,o)].filter(Boolean).join("; ");return e(X,{label:i,side:"top",delayMs:500},e("div",{className:"cm-chip"},l>0?a("costChipPlan",{amount:Y(n,o)}):a("cost",{amount:Y(n,o)})))}function Un(t){const{usage:s,config:o}=xa(t);if(!s||!o)return null;const a=s.input??0,n=(s.cacheRead??0)+(s.cacheWrite??0),l=s.output??0;if(a+n+l===0)return null;const i=G(_(o)),{cost:r,planPart:d}=va(s,o),u=Ot(s)>0?((s.cacheRead??0)/Ot(s)*100).toFixed(1)+"%":"—",c={amount:Y(r,o),planAmount:Y(d,o),hitRate:u,input:I(a),cache:I(n),output:I(l)},p=i(d>0?"sessionLineSplit":"sessionLine",c),f=Na(s,o),b=o.sessionCostCompact===!0;return e("div",{className:"cm-root",title:b?[p,f].filter(Boolean).join("; "):f},b?i(d>0?"sessionLineSplitCompact":"sessionLineCompact",c):p)}const Hn={USD:"$",CNY:"¥",EUR:"€"};function Se(t,s,o){const a=typeof o=="string"?o.toUpperCase():"",n=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return me(t,{symbol:Hn[a]??n,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function Sa(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const a=Number(s?.maxBudget);return Number.isFinite(a)&&a>0?a:null}function Qn(t){const s=t.today,o=s?.byProviderModel;if(o===null||typeof o!="object"||Object.keys(o).length===0)return Number(s?.cost)||0;let a=0;for(const[n,l]of Object.entries(o)){const i=n.indexOf(":");let r=i>=0?n.slice(0,i):n;r.startsWith("llm-")&&(r=r.slice(4)),/^deepseek(?:-official|-account)?$/.test(r)&&(a+=Number(l?.cost)||0)}return a}function Ca(t,s,o,a,n=null){const l=o==="official"?Qn(t):Number(t.today?.cost)||0,i=o==="custom"?_e(s,a,n):t.balance?.currency;if(i==="USD")return l;if(i==="CREDITS")return 0;const r=Number(s?.exchangeRate);return l*(Number.isFinite(r)&&r>0?r:1)}function Aa({remaining:t,spend:s,todayUsed:o,cap:a}){if(a===null||a<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const n=Math.max(0,Number(t)||0),l=Math.max(0,Number(s)||0),i=Math.max(0,Math.min(l,Number(o)||0)),r=Math.max(0,l-i),d=Math.max(0,Math.min(100,n/a*100)),u=Math.max(0,Math.min(100-d,i/a*100)),c=Math.max(0,Math.min(100-d-u,r/a*100));return{remainingPct:d,todayPct:u,spentPct:c,hasCap:!0,pastSpend:r,today:i}}function Bt(t,s,o=null,a=null){const n=o??t.customBalance,l=Sa(_e(s,n,a)==="CREDITS"?null:s,n),i=Number(n?.remaining)||0,r=Number(n?.spend)||0,d=Ca(t,s,"custom",n,a);return{cap:l,...Aa({remaining:i,spend:r,todayUsed:d,cap:l})}}function Fn(t,s){const o=t.balance,a=Sa(s,null),n=Number(o?.totalBalance)||0,l=Ca(t,s,"official",null),i=a!==null?Math.max(0,a-n):0;return{cap:a,...Aa({remaining:n,spend:i,todayUsed:l,cap:a})}}function Rt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:a,todayPct:n,spentPct:l}=s,i=[];a>0&&i.push(e("div",{className:"cm-bbox-fill",style:{width:a+"%"}})),n>0&&i.push(e("div",{className:"cm-bbox-seg-today",style:{width:n+"%"}})),l>0&&i.push(e("div",{className:"cm-bbox-seg-spent",style:{width:l+"%"}})),i.length===0&&i.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const r=o==="used"?[...i].reverse():i;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...r)}function Ma(t,s,o,a,n){const l=[t("balanceBarRemaining",{amount:a})];return o.today>0&&l.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&l.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),n!==null&&n>0&&l.push(t("balanceBudgetCapLabel")+": "+s(n)),l.join(" · ")}function Te(t){const[s,o]=B(!1),[a,n]=B(null);return{busy:s,err:a,run:()=>{s||typeof t!="function"||(o(!0),n(null),Promise.resolve().then(t).catch(i=>{n(i?.message??String(i))}).finally(()=>{o(!1)}))}}}const be=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function ke(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const _n="https://platform.deepseek.com/usage";function Pa(t){return e("a",{className:"cm-bal-link",href:_n,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},e("svg",{width:14,height:14,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},e("path",{d:"M8 4H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4M11 3h6v6M9 11l8-8"})))}function Wn(t){const{state:s,wide:o,api:a}=t,n=s.balance,l=G(_(s.config)),i=Te(a?()=>a.refreshBalance():null);if(!n||n.status==="off")return null;if(n.status==="error")return e(X,{label:[l("balanceQueryFailed",{message:n.message||l("unknownError")}),...ke(l,i)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(i.busy?" busy":""),...be(i.busy,i.run)},o?e(L,null,l("balance")," ",e("span",{className:"cm-num"},l("queryFailed"))):"⚠"));const r=[l("balanceTitle"),l("totalBalance",{amount:Se(n.totalBalance,s.config,n.currency)}),l("grantedToppedUp",{granted:Se(n.grantedBalance,s.config,n.currency),toppedUp:Se(n.toppedUpBalance,s.config,n.currency)}),l("updatedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ke(l,i)].join("; ");return e(X,{label:r,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(i.busy?" busy":""),...be(i.busy,i.run)},o?e(L,null,e("span",{className:"cm-balance-name"},l("balance"),Pa(l)),e("span",{className:"cm-num cm-bal-amt"},Se(n.totalBalance,s.config,n.currency)),s.reconcile?.ok===!1?" ⚠":""):e(ot,{size:16})))}function zn(t){const{state:s,wide:o,api:a}=t,n=s.config,l=s.balance,i=G(_(n)),r=Te(a?()=>a.refreshBalance():null);if(!l||l.status!=="ok")return null;const d=Fn(s,n),u=Se(l.totalBalance,n,l.currency),c=b=>Se(b,n,l.currency),p=[i("balanceTitle"),Ma(i,c,d,u,d.cap),i("grantedToppedUp",{granted:Se(l.grantedBalance,n,l.currency),toppedUp:Se(l.toppedUpBalance,n,l.currency)}),i("updatedAt",{time:l.fetchedAt>0?new Date(l.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ke(i,r)].join("; "),f=e(L,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-balance-name"},e("span",{className:"cm-bbox-label"},i("balance")),Pa(i)),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},u)),e(Rt,{segments:d,direction:ie(n,"balance")}));return e(X,{label:p,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(r.busy?" busy":""),...be(r.busy,r.run)},o?f:e("div",{className:"cm-bbox-rail cm-num"},Math.round(d.remainingPct)+"%")))}function Lt(t,s){const o=typeof t?.label=="string"?t.label:"",a=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?a||o||"Custom balance":o||a||"自定义余额"}function _e(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const a=o?.unit??t?.customBalance?.unit;return["CNY","EUR","USD","CREDITS"].includes(a)?a:["CNY","EUR","CREDITS"].includes(s?.unit)?s.unit:"USD"}function We(t,s,o,a){const n=_e(s,o,a),l=Number(t);if(!Number.isFinite(l))return"—";const i=s?.currency==="USD"?1:Number(s?.exchangeRate);if((a??s?.customBalance)?.convertToDisplayCurrency===!0&&n==="USD"&&Number.isFinite(i)&&i>0){const c=l*i;return Number.isFinite(c)?me(c,s):"—"}const r=n==="CREDITS",d=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4)));return(r?"":n==="CNY"?"¥":n==="EUR"?"€":"$")+ba(l,d)+(r?" Credits":"")}function Et(t,s,o,a,n=null){const l=We(t.remaining,s,t,n),i=f=>We(f,s,t,n);if(a&&s.balance?.showProgressBar===!0){const f=Bt(a,s,t,n);return[Ma(o,i,f,l,f.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const r=t.spend!==null?i(t.spend):"—",d=t.maxBudget!==null?i(t.maxBudget):"—",u=_e(s,t,n)==="CREDITS"?NaN:Number(s?.balance?.budgetCap),c=Number.isFinite(u)&&u>0?o("balanceBudgetCapLabel")+": "+i(u):"",p=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:l,spend:r,maxBudget:d,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:l});return c?p+" · "+c:p}function Kn(t,s,o,a,n){const l=Lt(n??s.customBalance??{},_(s)),i=We(a.remaining,s,a,n),r=Bt(t,s,a,n);return{level:"ok",rail:Math.round(r.remainingPct)+"%",body:e(L,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},l),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},i)),e(Rt,{segments:r,direction:ie(s,"balance")}))}}function It(t,s){const o=s?.customBalances??[],a=Array.isArray(t?.customBalances)?t.customBalances:[],n=[];return o.forEach((l,i)=>{if(l?.enabled!==!0||l.display!=="sidebar"&&l.display!=="both")return;const r=a.find(d=>d.index===i)??(a.length===1&&o.length===1?a[0]:null);n.push({index:i,entry:l,snapshot:r})}),n.length===0&&a.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&n.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),n}function Gn(t){const{state:s,wide:o,api:a}=t,n=s.config,l=G(_(n)),i=It(s,n);return i.length===0?null:e(L,null,i.map(({index:r,entry:d,snapshot:u})=>e(Yn,{key:"cb-"+r,state:s,wide:o,api:a,t:l,index:r,entry:d,snapshot:u})))}function Yn(t){const{state:s,wide:o,api:a,t:n,index:l,entry:i,snapshot:r}=t,d=s.config;if(r==null||r.status!=="ok")return null;const u=Te(a?()=>a.refreshCustomBalance(l):null),c=Kn(s,d,n,r,i),p=[Et(r,d,n,s,i),...ke(n,u)].join(" · ");return e(X,{label:p,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(u.busy?" busy":""),...be(u.busy,u.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function Vn(t){const{state:s,wide:o,api:a}=t,n=s.config,l=G(_(n)),i=It(s,n);return i.length===0?null:e(L,null,i.map(({index:r,entry:d,snapshot:u})=>e(Jn,{key:"cbr-"+r,state:s,wide:o,api:a,t:l,index:r,entry:d,snapshot:u})))}function Jn(t){const{state:s,wide:o,api:a,t:n,index:l,entry:i,snapshot:r}=t,d=s.config,u=r??sa(l);if(u.status==="off")return null;const c=Te(a?()=>a.refreshCustomBalance(l):null),p=Lt(i??d.customBalance??{},_(d));if(u.status==="error")return e(X,{label:[u.message||n("unknownError"),...ke(n,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...be(c.busy,c.run)},o?e(L,null,e("span",{className:"cm-bal-label",title:p},p),e("span",{className:"cm-num cm-bal-amt"},n("queryFailed"))):"⚠"));const f=We(u.remaining,d,u,i),b=[Et(u,d,n,s,i),...ke(n,c)].join(" · ");return e(X,{label:b,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...be(c.busy,c.run)},o?e(L,null,e("span",{className:"cm-bal-label",title:p},p),e("span",{className:"cm-num cm-bal-amt"},f)):e(ot,{size:16})))}function Zn(t){const o=(t.useCost?t.useCost(g=>g):void 0)?.state;if(!o)return null;const a=o.config,n=G(_(a)),l=a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},i=o.goQuota,r=a?.goQuota?.enabled!==!1&&i?.status==="ok",d=g=>g!==null&&typeof g?.percent=="number"?Math.round(Math.max(0,Math.min(100,g.percent))):null,u=[];if(a.sidebarModels?.dock){const g=ja(o,a.sidebarModels.period,n);g.length&&u.push({key:"model-top",text:e(L,null,e("span",{className:"cm-bal-label"},g[0].label),e("span",{className:"cm-bal-amt"},Y(g[0].cost,a))),tip:g[0].label+" "+Y(g[0].cost,a),level:"ok"})}const c=(g,h,x,S)=>{if(!l.enabled||!g||!r)return;const T=d(h);if(T===null)return;const N=typeof h.resetsAt=="string"&&h.resetsAt.length>0?n("goResetAt",{time:new Date(h.resetsAt).toLocaleString()}):"";u.push({key:x,text:n(x)+" "+T+"%",tip:n(S)+": "+T+"%"+(N?" · "+N:""),level:T>=100?"over":T>=80?"warn":"ok"})},p=a?.goQuota?.main==="weekly"||a?.goQuota?.main==="monthly"?a.goQuota.main:"rolling",f=[p,...["rolling","weekly","monthly"].filter(g=>g!==p)],b=g=>g==="rolling"?["goRolling",i?.rolling,"goShortRolling","cornerGoRolling"]:g==="weekly"?["goWeekly",i?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",i?.monthly,"goShortMonthly","cornerGoMonthly"];for(const g of f){const[h,x,S,T]=b(g);c(l[h]===!0,x,S,T)}if(l.enabled&&l.budget===!0){const g=a.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const h=Number(a.exchangeRate),S=(o.budgetUsed??(g.period==="day"?z(o.today,a):g.period==="all"?z(o.total,a):z(o.month,a)))*(Number.isFinite(h)&&h>0?h:1),T=Math.max(0,Number(g.amount)||0),N=T>0?Math.min(999,S/T*100):null;if(N!==null){const m=N>=100?"over":N>=80?"warn":"ok";u.push({key:"budget",text:n("budgetShort")+" "+N.toFixed(1)+"%",tip:n("budgetOf",{period:n(Ie[g.period]??"periodMonth")})+" · "+n("usedOf",{used:me(S,a),amount:me(T,a)}),level:m})}}}return u.length===0?null:e("div",{className:"cm-corner"},u.map(g=>e(X,{key:g.key,label:g.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(g.key==="model-top"?" cm-model-top":"")+(g.level==="ok"?"":" "+g.level)},g.text))))}function lt(t,s,o){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const a=(f,b)=>{const g=new Date(t);return g.setUTCDate(g.getUTCDate()+f),g.setUTCHours(b,0,0,0),g.getTime()},n=new Set,l=Math.max(12,Math.min(380,(Array.isArray(o)?o.length:0)+7));for(let f=-l;f<=l;f+=1){n.add(a(f,16));for(const b of s){const g=Number(b?.start),h=Number(b?.end);!Number.isFinite(g)||!Number.isFinite(h)||(n.add(a(f,g)),n.add(a(h<=g?f+1:f,h)))}}const i=[...n].sort((f,b)=>f-b).flatMap(f=>{const b=at(f-1,void 0,s,o),g=at(f,void 0,s,o);return b===g?[]:[{at:f,intoPeak:g}]});let r=null,d=null;for(const f of i)f.at<=t&&(r===null||f.at>r.at)&&(r=f),f.at>t&&(d===null||f.at<d.at)&&(d=f);const u=ua(t,o),c=u??da(t);return c!==null?d===null?null:{inPeak:!1,weekend:u===null,...u?{holiday:!0}:{},prevAtMs:c.start,nextAtMs:d.at,nextIntoPeak:d.intoPeak}:r===null||d===null?null:{inPeak:at(t,void 0,s,o),weekend:!1,prevAtMs:r.at,nextAtMs:d.at,nextIntoPeak:d.intoPeak}}function it(t,s){if(!t||t.peakNotice===!1||t.peakEnabled!==!0)return null;const o=Date.parse(t.peakEffectiveAt||"");if(Number.isFinite(o)&&s<o)return null;const a=Array.isArray(t.peakWindows)?t.peakWindows:[];return lt(s,a,t.peakHolidays)}function rt(t){return t.holiday===!0?{short:"holidayShort",chip:"holidayChip",notice:"holidayAllOffPeak"}:t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function we(t,s,o){const a=Math.max(0,t.nextAtMs-s),n=Math.max(1,Math.ceil(a/6e4)),l=Math.floor(n/60),i=n%60;return l>0?i>0?o("countdownHourMinute",{h:l,m:i}):o("countdownHoursOnly",{h:l}):o("countdownMinute",{m:n})}const qt="cm-peak-alert-preview";let Ta=0;function $n(t){const s=t.useCost?t.useCost(h=>h):void 0,o=s?.state?.config,[a,n]=B(Date.now()),[l,i]=B(null),[r,d]=B(null);if(ee(()=>{const h=window.setInterval(()=>n(Date.now()),1e4);return()=>window.clearInterval(h)},[]),ee(()=>{const h=x=>{const S=x.detail?.kind==="offpeak"?"offpeak":"peak";d(S);const T=s?.state?.config;if(T?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const N=G(_(T));try{new Notification(N(S==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+N("peakAlertPreviewTag"),{body:N("peakAlertBody",{time:N("countdownMinute",{m:2}),phase:N(S==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(qt,h),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(qt,h),window.__cmPeakAlertLive=!1}},[]),ee(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const h=lt(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(h===null)return;const x=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",S=h.nextIntoPeak===!0;if(x!=="both"&&x!==(S?"peak":"offpeak"))return;const T=Number(o.peakAlertAhead),N=(Number.isFinite(T)&&T>=1?T:2)*6e4;if(a<h.nextAtMs-N||a>=h.nextAtMs||Ta===h.nextAtMs)return;const m=G(_(o));Ta=h.nextAtMs;try{new Notification(m(S?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:m("peakAlertBody",{time:we(h,a,m),phase:m(S?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[a]),!o||o.peakEnabled!==!0)return null;let u=null;if(o.peakAlertEnabled===!0){const h=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(h)&&a<h)){const x=lt(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(x!==null){const S=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",T=Number(o.peakAlertAhead),N=(Number.isFinite(T)&&T>=1?T:2)*6e4;(S==="both"||S===(x.nextIntoPeak?"peak":"offpeak"))&&a>=x.nextAtMs-N&&a<x.nextAtMs&&l!==x.nextAtMs&&(u=x)}}}let c=null,p=!1,f=null;if(u!==null)c=u,p=u.nextIntoPeak===!0,f=()=>i(u.nextAtMs);else if(r!==null)c={nextAtMs:a+2*6e4,nextIntoPeak:r==="peak"},p=r==="peak",f=()=>d(null);else return null;const b=G(_(o)),g=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+g+" "+(p?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},b(p?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},b(p?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},b("peakAlertBody",{time:we(c,a,b),phase:b(p?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:f},b("peakAlertBtn"))))}function Xn(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)});return e(X,{label:o(i.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(l.weekend||l.holiday?"weekend":l.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:l.weekend||l.holiday?"50%":l.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(i.chip)+" · "+r)))}function es(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)});return e(X,{label:o(i.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(l.weekend||l.holiday?"weekend":l.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:l.weekend||l.holiday?"50%":l.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(i.chip)+" · "+r)))}function ct(t,s,o){return e(s?.peakStyle==="classic"?es:Xn,{config:s,t:o})}function ts(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)}),d=[o(i.notice),r];return e(X,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(l.weekend||l.holiday?"weekend":l.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:l.weekend||l.holiday?"50%":l.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(i.short))))}function as(t){const{config:s,t:o}=t,[a,n]=B(Date.now());ee(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const l=it(s,a);if(l===null)return null;const i=rt(l),r=l.nextIntoPeak?o("nextPeakIn",{time:we(l,a,o)}):o("nextOffPeakIn",{time:we(l,a,o)}),d=[o(i.notice),r];return e(X,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(l.weekend||l.holiday?"weekend":l.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:l.weekend||l.holiday?"50%":l.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(i.short))))}function ns(t,s,o){return e(s?.peakStyle==="classic"?as:ts,{config:s,t:o})}function Oa(t,s,o){const a=t.today,n=s.budget??{enabled:!1,amount:100,period:"month"},l=Number(s.exchangeRate),r=(t.budgetUsed??(n.period==="day"?z(t.today,s):n.period==="all"?z(t.total,s):z(t.month,s)))*(Number.isFinite(l)&&l>0?l:1),d=Math.max(0,Number(n.amount)||0),u=d>0?Math.min(999,r/d*100):null,c=fe(u===null?null:Math.min(100,u),ie(s,"budget")),p=z(a,s)*(Number.isFinite(l)&&l>0?l:1),f=d>0?Math.min(999,p/d*100):null,b=n.detail!==!1;return{level:u===null?"ok":u>=100?"over":u>=80?"warn":"ok",rail:c.label===null?"—":Math.round(c.label)+"%",body:e(L,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+"%"}})),b?e(L,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},s.sidebarTodayMetric==="tokens"?o("today")+" "+Ft(a,s,o):o("todayShare",{amount:Y(z(a,s),s),pct:f===null?"—":f.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:me(r,s),amount:me(d,s)}))):null,ct(t,s,o))}}function Da(t,s,o){const a=t.goQuota,n=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",l=a[n],i=l!==null&&typeof l?.percent=="number"?Math.max(0,Math.min(100,Number(l.percent)||0)):0,r=b=>b!==null&&typeof b?.percent=="number"?Math.round(Math.max(0,Math.min(100,b.percent)))+"%":"—",d=b=>o(b==="rolling"?"goShortRolling":b==="weekly"?"goShortWeekly":"goShortMonthly"),u=["rolling","weekly","monthly"].filter(b=>b!==n),c=l!==null&&typeof l?.resetsAt=="string"&&l.resetsAt.length>0?o("goResetAt",{time:new Date(l.resetsAt).toLocaleString()}):"",p=s?.goQuota?.detail!==!1,f=fe(i,ie(s,"go"));return{level:i>=100?"over":i>=80?"warn":"ok",rail:f.label===null?"—":Math.round(f.label)+"%",body:e(L,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+d(n)),e("span",{className:"cm-bbox-pct cm-num"},f.label===null?"—":Math.round(f.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:f.width+"%"}})),p?e(L,null,e("div",{className:"cm-bbox-line cm-num"},u.map(b=>d(b)+" "+r(a[b])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function ss(t){const{state:s,wide:o}=t,a=s.goQuota,n=G(_(s.config));if(!a||a.status!=="ok")return null;const l=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(a[l]===null||typeof a[l]?.percent!="number")return null;const i=Da(s,s.config,n),r=[n("goQuotaTitle"),n("goWindowRolling")+": "+(a.rolling===null?"—":Math.round(a.rolling.percent)+"%"),n("goWindowWeekly")+": "+(a.weekly===null?"—":Math.round(a.weekly.percent)+"%"),n("goWindowMonthly")+": "+(a.monthly===null?"—":Math.round(a.monthly.percent)+"%"+(a.monthly!==null&&typeof a.monthly.resetsAt=="string"&&a.monthly.resetsAt.length>0?" · "+n("goResetAt",{time:new Date(a.monthly.resetsAt).toLocaleString()}):"")),n("goQuotaFetchedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e(X,{label:r,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(i.level==="ok"?"":" "+i.level)+(o?"":" rail")},o?i.body:e("div",{className:"cm-bbox-rail cm-num"},i.rail)))}function os(t){return t===null||typeof t!="object"||t.unlimited||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function ze(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function Ba(t,s,o=Date.now()){if(typeof t!="string"||!t)return"";const a=Date.parse(t);if(!Number.isFinite(a))return"";const n=a-o;if(n<=0)return s("resetReached");const l=Math.ceil(n/6e4),i=Math.floor(l/1440),r=Math.floor(l%1440/60),d=l%60;return i>0?s("resetDays",{d:i,h:r}):r>0?s("resetHours",{h:r,m:d}):s("resetMinutes",{m:d})}function Ke(t,s,o=Date.now()){const a=Ba(t?.resetsAt,s,o);return a?s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})+" ("+a+")":""}function dt(t,s,o){return t===null?"—":o(s==="remaining"?"quotaRemaining":"quotaUsed",{pct:t})}function ut(t){const[,s]=B(0),o=()=>s(Date.now());return ee(()=>{if(!t)return;const a=setInterval(o,6e4);return()=>clearInterval(a)},[t]),{onMouseEnter:o,onFocus:o}}function Ge(t,s,o,a){const n=os(s),l=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",i=fe(n,o),r=s?.unlimited?"∞":i.label===null?"—":i.label+"%";return{level:l,pct:n,text:r,label:i.label,row:e("div",{className:"cm-mm-row"+(l==="ok"?"":" "+l)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:i.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r))}}function Ra(t){const{five:s,seven:o,fetchedAt:a,t:n,wide:l,refresh:i,direction:r="used"}=t,d=ut(s?.resetsAt),u=Ba(s?.resetsAt,n),c=Ge(n("codingPlanRemain5h"),s,r,n),p=Ge(n("codingPlanRemain7d"),o,r,n),f=c.level==="over"||p.level==="over"?"over":c.level==="warn"||p.level==="warn"?"warn":"ok",b=(S,T,N)=>{const m=T?.unlimited?n("quotaUnlimited"):dt(N.label,r,n),v=Ke(T,n);return S+" "+m+(v?" · "+v:"")},g=[n("codingPlanMinimaxTitle"),b(n("codingPlanRemain5h"),s,c),b(n("codingPlanRemain7d"),o,p),a>0?n("goQuotaFetchedAt",{time:new Date(a).toLocaleTimeString()}):null,...i?ke(n,i):[]].filter(Boolean).join(`
3
+ `),h=e(L,null,e("div",{className:"cm-mm-title"},n("codingPlanMinimaxTitle")),c.row,p.row,u?e("div",{className:"cm-mm-reset"},"5h · "+u):null),x=e(L,null,e("div",{className:"cm-bbox-rail cm-num"},c.text),e("div",{className:"cm-bbox-rail cm-num"},p.text));return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},g),side:"right",delayMs:300},e("div",{...d,className:"cm-bbox cm-mm"+(f==="ok"?"":" "+f)+(l===!1?" rail":"")+(i?" clickable"+(i.busy?" busy":""):""),...i?be(i.busy,i.run):{}},l===!1?x:h))}function ls(t){const{state:s,wide:o,api:a}=t,n=s.codingPlans?.minimax,l=G(_(s.config)),i=Te(a?()=>a.refreshCodingPlan("minimax"):null);if(!n||n.status!=="ok")return null;const{five:r,seven:d}=ze(n.windows);return r==null&&d==null?null:e(Ra,{five:r,seven:d,fetchedAt:n.fetchedAt,t:l,wide:o,refresh:i,direction:ie(s.config,"plan")})}const is="/plugins/dsh-openai-codex/auth/status",rs=168*3600;function cs(t){if(t===null||typeof t!="object"||t.status!=="signed-in")return null;const s=t.usage!==null&&typeof t.usage=="object"?t.usage.rateLimits:null;if(!Array.isArray(s))return null;const o=s.find(r=>r!==null&&typeof r=="object"&&r.id==="codex");if(!o||!Array.isArray(o.windows))return null;const a=o.windows.find(r=>r!==null&&typeof r=="object"&&Number(r.windowSeconds)===rs);if(!a||typeof a.remainingPercent!="number"||!Number.isFinite(Number(a.remainingPercent)))return null;const n=Math.max(0,Math.min(100,Math.round((100-Number(a.remainingPercent))*10)/10)),l=Number(a.resetAt),i=Number.isFinite(l)&&l>0?new Date(l*1e3).toISOString():"";return{weekly:{percent:n,resetsAt:i}}}const $={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},ds=t=>($.listeners.push(t),()=>{$.listeners=$.listeners.filter(s=>s!==t)}),us=()=>{for(const t of $.listeners)try{t()}catch{}};async function jt(t=!1,s=!1){if(!s)return;if($.inFlight!==null)return $.inFlight;if(!t&&$.fetchedAt>0&&Date.now()-$.fetchedAt<5*6e4)return;const o=(async()=>{try{const a=await fetch(is,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(a.ok){const l=cs(await a.json().catch(()=>null));l!==null&&(n=l)}$.status=Object.keys(n).length>0?"ok":"unavailable",$.windows=n}catch{$.status="unavailable"}finally{$.fetchedAt=Date.now(),$.inFlight=null,us()}})();return $.inFlight=o,o}function Ut(t){const[s,o]=B(()=>({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt}));return ee(()=>{if(!t)return;let a=!0;const n=()=>{a&&o({status:$.status,windows:$.windows,fetchedAt:$.fetchedAt})},l=ds(n);return n(),jt(!1,!0),()=>{a=!1,l()}},[t]),s}function ms(t){const s=ut(),{state:o,wide:a}=t,n=G(_(o.config)),l=o.config?.codexQuotaEnabled===!0&&o.config?.codexQuotaSidebar!==!1,i=Ut(l),r=Te(()=>jt(!0,l));if(!l||i.status!=="ok")return null;const d=i.windows.weekly??null;if(d===null)return null;const u=ie(o.config,"plan"),c=Ge(n("goShortWeekly"),d,u,n),p=[n("codexQuotaTitle"),dt(c.label,u,n),Ke(d,n),i.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()}):null,...ke(n,r)].filter(Boolean).join(`
4
+ `),f=e(L,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),c.row),b=e("div",{className:"cm-bbox-rail cm-num"},c.label===null?"—":c.label+"%");return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},p),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(c.level==="ok"?"":" "+c.level)+(a===!1?" rail":"")+(r.busy?" busy":""),...be(r.busy,r.run)},a===!1?b:f))}function Ht(t,s){return t==="fiveHour"||t==="5h"?"5h":t==="weekly"||t==="week"||t==="7d"?t==="7d"?"7d":s("goShortWeekly"):t==="monthly"||t==="month"?s("goShortMonthly"):t==="daily"||t==="day"?s("goShortDaily"):t==="plan"?s("mimoWindowPlan"):t==="compensation"?s("mimoWindowCompensation"):t==="balance"?s("codingPlanWindowBalance"):String(t).replace(/_/g," ")}function ps(t){const s=ut(),{id:o,state:a,wide:n,api:l}=t,i=a.codingPlans?.[o],r=G(_(a.config)),d=Te(l?()=>l.refreshCodingPlan(o):null),u=Le.find(m=>m.id===o);if(!u||!i||i.status!=="ok")return null;const c=i.windows!==null&&typeof i.windows=="object"?i.windows:{},p=Object.entries(c);if(p.length===0)return null;const f=m=>m!==null&&typeof m=="object"&&typeof m.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(m.percent)||0))):null,b=ie(a.config,"plan"),g=p.map(([m,v])=>{const y=f(v);if(y===null)return e("div",{key:m,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof v?.text=="string"?v.text:"—"));const O=y>=100?"over":y>=80?"warn":"ok",P=fe(y,b);return e("div",{key:m,className:"cm-mm-row wide"+(O==="ok"?"":" "+O)},e("span",{className:"cm-bbox-label"},Ht(m,r)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:P.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},P.label===null?"—":P.label+"%"))}),h=p.map(([m,v])=>{const y=f(v),O=Ke(v,r),P=y===null?typeof v?.text=="string"?v.text:"—":dt(fe(y,b).label,b,r);return Ht(m,r)+" "+P+(O?" · "+O:"")});i.fetchedAt>0&&h.push(r("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()})),h.push(...ke(r,d));const x=[r(u.labelKey),...h].join(`
5
+ `),S=p.map(([,m])=>f(m)).filter(m=>m!==null),T=S.some(m=>m>=100)?"over":S.some(m=>m>=80)?"warn":"ok",N=S.length>0?S.slice(0,2).map(m=>fe(m,b).label+"%").join(" "):typeof p[0][1]?.text=="string"?p[0][1].text:"—";return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},x),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(T==="ok"?"":" "+T)+(n===!1?" rail":"")+(d.busy?" busy":""),...be(d.busy,d.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},N):e(L,null,e("div",{className:"cm-mm-title"},r(u.labelKey)),...g)))}const La=t=>{try{return window.localStorage?.getItem?.("cm.gw."+t)??""}catch{return""}},fs=(t,s)=>{try{window.localStorage?.setItem?.("cm.gw."+t,s)}catch{}};function bs(t){const s=ut(),{source:o,snapshot:a,state:n,wide:l,api:i}=t,r=G(_(n.config)),[d,u]=B(()=>({source:o.id,id:La(o.id)})),c=Te(i?()=>i.refreshGatewayQuota(o.id):null),p=ie(n.config,"plan"),f=a.accounts.length>1,b=d.source===o.id?d.id:La(o.id),g=a.accounts.findIndex(M=>M.id===b),h=g>=0?g:Math.max(0,a.accounts.findIndex(M=>M.windows.length>0||M.credits!=null)),x=a.accounts[h]??a.accounts[0],S=x?.label||x?.id||"",T=M=>f?(la[M.provider]??M.provider)+" · ":"",N=f&&x?[x]:a.accounts,m=[];for(const M of N){if(m.length>=4)break;for(const U of M.windows){if(m.length>=4)break;const D=T(M)+(U.label||U.id||r("gatewaySourceUnknown"));m.push({win:U,name:D,view:Ge(D,U,p,r)})}M.windows.length===0&&M.credits!=null&&m.push({win:null,name:T(M)+(M.credits.unit||"credits"),text:(M.credits.used??"—")+" / "+(M.credits.limit??"—")})}m.length===0&&m.push({name:r("gatewayQuotaEmpty"),text:"—"});const v=m.some(M=>M.view?.level==="over")?"over":m.some(M=>M.view?.level==="warn")?"warn":"ok",y=m.map(M=>{if(M.text!=null)return M.name+" "+M.text;const U=Ke(M.win,r);return M.name+" "+dt(M.view.label,p,r)+(U?" · "+U:"")});a.fetchedAt>0&&y.push(r("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()})),y.push(...ke(r,c));const P=[f&&S?`${o.label||o.id} (${h+1}/${a.accounts.length} · ${S})`:o.label||o.id,...y].join(`
6
+ `),R=m.map((M,U)=>M.text!=null?e("div",{key:U,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},M.name),e("span",{className:"cm-mm-text cm-num"},M.text)):e(L,{key:U},M.view.row)),A=M=>{if(!M.key||M.key==="Enter"||M.key===" "){M.stopPropagation(),M.preventDefault?.();const U=a.accounts[(h+1)%a.accounts.length];fs(o.id,U.id),u({source:o.id,id:U.id})}},q=f?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:S||h+1}),onClick:A,onKeyDown:A,role:"button",tabIndex:0},`${h+1}/${a.accounts.length} ⇄`):null,k=f?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),q):e("div",{className:"cm-mm-title"},o.label||o.id),j=f&&S?e("div",{className:"cm-gw-sub"},S):null,Ce=e(L,null,k,j,...R),de=m.filter(M=>M.view).map(M=>M.view.label).filter(M=>M!==null),Ae=de.length>0?de.slice(0,2).map(M=>M+"%").join(" "):m[0].text??"—",J=e("div",{className:"cm-bbox-rail cm-num"},Ae);return e(X,{label:e("span",{style:{whiteSpace:"pre-line"}},P),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(v==="ok"?"":" "+v)+(l===!1?" rail":"")+(c.busy?" busy":""),...be(c.busy,c.run)},l===!1?e(L,null,J,q):Ce))}function gs(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],l=[];for(const i of s.gatewayQuotas?.sources??[]){if(i.enabled===!1||i.display!=="sidebar"&&i.display!=="both")continue;const r=n.find(d=>d.id===i.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||l.push(e(bs,{source:i,snapshot:r,state:t,wide:o,api:a}))}return l}const hs={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function ys(t){const s=t.useCost?t.useCost(g=>g):void 0;Ut(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=B(null),[n,l]=B({}),i=s?.state,r=t.api;if(!i)return null;const d=i.config,u=d.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(u.enabled!==!0)return null;const c=G(_(d)),p=[];if(u.budget!==!1){const g=d.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const h=Number(d.exchangeRate),S=(i.budgetUsed??(g.period==="day"?z(i.today,d):g.period==="all"?z(i.total,d):z(i.month,d)))*(Number.isFinite(h)&&h>0?h:1),T=Math.max(0,Number(g.amount)||0);if(T>0){const N=Math.min(999,S/T*100),m=N>=100?"over":N>=80?"warn":"ok";p.push({key:"budget",label:c("budgetShort"),level:m,tip:c("budgetOf",{period:c(Ie[g.period]??"periodMonth")})+" · "+c("usedOf",{used:me(S,d),amount:me(T,d)})+" · "+N.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(fe(Math.min(100,N),ie(d,"budget")).width)}]})}}}if(u.go!==!1){const g=i.goQuota;if(d?.goQuota?.enabled!==!1&&g?.status==="ok"){const h=d.goQuota.main==="weekly"||d.goQuota.main==="monthly"?d.goQuota.main:"rolling",x=h==="rolling"?g.rolling:h==="weekly"?g.weekly:g.monthly;if(x!==null&&typeof x=="object"&&typeof x.percent=="number"){const S=Math.max(0,Math.min(100,Math.round(Number(x.percent)||0))),T=S>=100?"over":S>=80?"warn":"ok",N=typeof x.resetsAt=="string"&&x.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(x.resetsAt).toLocaleString()}):"";p.push({key:"go",label:"Go "+c(h==="rolling"?"goShortRolling":h==="weekly"?"goShortWeekly":"goShortMonthly"),level:T,tip:"Go: "+S+"%"+N,segs:[{name:"main",pct:Math.round(fe(S,ie(d,"go")).width)}]})}}}if(u.plans!==!1)for(const g of Le){const h=i.codingPlans?.[g.id];if(d.codingPlans?.[g.id]?.enabled!==!0||!h||h.status!=="ok")continue;const x=h.windows!==null&&typeof h.windows=="object"?h.windows:{},S=Object.entries(x);if(S.length===0)continue;const T=hs[g.id]??g.id,N=[],m=[];let v=0,y=0;for(const[O,P]of S){const R=Ht(O,c),A=typeof P?.resetsAt=="string"&&P.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(P.resetsAt).toLocaleString()}):"",q=P!==null&&typeof P=="object"&&typeof P.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(P.percent)||0))):null;if(m.push(R+" "+(q===null?typeof P?.text=="string"?P.text:"—":q+"%")+A),q===null){N.push({name:O,pct:null,text:typeof P?.text=="string"?P.text:"—"});continue}y>=2||(y+=1,N.push({name:O,pct:Math.round(fe(q,ie(d,"plan")).width)}),v=Math.max(v,q>=100?2:q>=80?1:0))}h.fetchedAt>0&&m.push(c("goQuotaFetchedAt",{time:new Date(h.fetchedAt).toLocaleTimeString()})),N.length!==0&&p.push({key:g.id,label:T,level:["ok","warn","over"][v],tip:m.join("; "),segs:N})}const f=d.codexQuotaEnabled===!0&&$.status==="ok"?$.windows.weekly??null:null;if(f!==null&&typeof f.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(f.percent)||0))),h=typeof f.resetsAt=="string"&&f.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(f.resetsAt).toLocaleString()}):"";p.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+h,segs:[{name:"weekly",pct:Math.round(fe(g,ie(d,"plan")).width)}]})}if(p.length===0)return null;const b=g=>{o!==null||!r||(a(g),l(h=>({...h,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?jt(!0,d.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(h=>{l(x=>({...x,[g]:h?.message??String(h)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},p.map(g=>{const h=o===g.key,x=n[g.key],S=[e("span",{className:"cm-qlabel",key:"l"},g.label)];h?S.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((N,m)=>{m>0&&S.push(e("span",{className:"cm-qsep",key:"sep"+m,"aria-hidden":"true"})),N.pct===null?S.push(e("span",{className:"cm-qtext",key:N.name},N.text)):S.push(e("span",{className:"cm-qseg",key:N.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:N.pct+"%"}})),e("span",null,N.pct+"%")))});const T=[g.tip];return!h&&r&&T.push(c("clickToRefresh")),h&&T.push(c("refreshing")),x&&T.push("⚠ "+c("balanceRefreshFailed",{message:x})),e(X,{key:g.key,label:T.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?be(h,()=>b(g.key)):{}},S))}))}const Ea="dsh-cost-meter:simple-guide-dismissed";function Qt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Ea)==="1"}catch{return!1}}function ks(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Ne(!1),[a,n]=B(!1),[l,i]=B(!1),[r,d]=B(!1),u=s?.state?.config;if(!u||r||Qt(u))return null;const c=G(_(u)),p=()=>{d(!0);try{window.localStorage.setItem(Ea,"1")}catch{}},f=async b=>{if(!o.current){o.current=!0,n(!0),i(!1);try{if((await t.api.updateConfig({sidebarSimple:b,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==b)throw new Error;p()}catch{i(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),p())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:p},"×")),e("p",null,c("sidebarSimpleBody")),l?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>f(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>f(!0)},c("sidebarSimpleOn"))))}function ws(t){const s=t.useCost?t.useCost(r=>r):void 0,o=Ne(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Qt(n)||n.quotaStrip?.promptSeen===!0)return null;const l=G(_(n)),i=r=>{if(o.current===!0)return;o.current=!0;const d=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...d,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":l("quotaStripGuideTitle")},e("h4",null,l("quotaStripGuideTitle")),e("p",null,l("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>i(!1)},l("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>i(!0)},l("quotaStripGuideOn"))))}const Ia="dsh-cost-meter:balance-click-hint-seen",xs=()=>{try{return window.localStorage.getItem(Ia)==="1"}catch{return!1}},vs=()=>{try{window.localStorage.setItem(Ia,"1")}catch{}};function Ns(t){const s=t.useCost?t.useCost(b=>b):void 0,o=Ne(!1),[a,n]=B(!1),[l]=B(xs),i=s?.state;if(!i)return null;const r=i.config,d=r.balance?.display==="sidebar"||r.balance?.display==="both",u=(r?.customBalances??[]).some(b=>b?.enabled===!0&&(b.display==="sidebar"||b.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Le.some(b=>{const g=r.codingPlans?.[b.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||l||r.balance?.clickHintSeen===!0||!d&&!u&&!c||!Qt(r)||r.quotaStrip?.promptSeen!==!0)return null;const p=G(_(r)),f=()=>{o.current!==!0&&(n(!0),o.current=!0,vs(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":p("balanceClickGuideTitle")},e("h4",null,p("balanceClickGuideTitle")),e("p",null,p("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:f},p("balanceClickGuideOk"))))}function Ft(t,s,o){return s.sidebarTodayMetric==="tokens"?I(["input","output","cacheRead","cacheWrite","reasoning"].reduce((a,n)=>a+(Number(t?.[n])||0),0))+" "+o("tokensUnit"):Y(z(t,s),s)}function _t(t){const{state:s,wide:o}=t,a=s.today,n=s.config,l=G(_(n)),i=Ft(a,n,l),r=n.budget??{enabled:!1,amount:100,period:"month"},d=Number(n.exchangeRate),c=(s.budgetUsed??(r.period==="day"?z(s.today,n):r.period==="all"?z(s.total,n):z(s.month,n)))*(Number.isFinite(d)&&d>0?d:1),p=Math.max(0,Number(r.amount)||0),f=p>0?Math.min(999,c/p*100):null,b=f===null?"ok":f>=100?"over":f>=80?"warn":"ok";if(r.enabled===!0){const x=z(a,n)*(Number.isFinite(d)&&d>0?d:1),S=p>0?Math.min(999,x/p*100):null,T=[l("budgetOf",{period:l(Ie[r.period]??"periodMonth")}),l("usedOf",{used:me(c,n),amount:me(p,n)})+" · "+(f===null?"—":f.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[n.sidebarTodayMetric==="tokens"?l("today")+" "+i:l("todayShare",{amount:i,pct:S===null?"—":S.toFixed(1)+"%"})],l("monthTotal",{month:Y(z(s.month,n),n),total:Y(z(s.total,n),n)})].join("; ");if(t.summary===!0)return e(X,{label:T,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(b==="ok"?"":" "+b),tabIndex:0},e("span",null,l("todayBudget",{period:l(Ie[r.period]??"periodMonth")})),e("span",{className:"cm-num"},i+" / "+me(p,n))));const N=Oa(s,n,l);return e(X,{label:T,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(b==="ok"?"":" "+b)+(o?"":" rail")},o?N.body:e("div",{className:"cm-bbox-rail cm-num"},N.rail)))}const g=[n.sidebarTodayMetric==="tokens"?l("todayTokensTitle"):l("todayCostTitle"),l("callsTokens",{calls:a.calls,input:I(a.input),cache:I(a.cacheRead+a.cacheWrite),output:I(a.output)}),l("monthCost",{amount:Y(z(s.month,n),n)}),l("totalCost",{amount:Y(z(s.total,n),n)})].join("; ");return e(X,{label:g,side:"right",delayMs:300},e(L,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(L,null,l("today")," ",e("span",{className:"cm-num"},i)):e(ot,{size:16})),o?ct(s,n,l):null))}function Ss(t){const s=t.useCost?t.useCost(A=>A):void 0;Ut(s?.state?.config?.codexQuotaEnabled===!0&&s?.state?.config?.codexQuotaSidebar!==!1);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}wa(t,o);const a=s?.state,n=!!t.wide;if(!a)return null;const l=a.config,i=G(_(l)),r=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,u=It(a,l).length>0,c=r&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",p=u&&l.balance?.showProgressBar===!0,f=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",b=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[f]!==null,g=Le.map(A=>A.id).filter(A=>{const q=l.codingPlans?.[A];if(q?.enabled!==!0||q.display!=="sidebar"&&q.display!=="both")return!1;const k=a.codingPlans?.[A];if(k?.status!=="ok")return!1;const j=k.windows!==null&&typeof k.windows=="object"?k.windows:{};return Object.keys(j).length>0}),h=g.length>0,x=gs(a,l,n,t.api),S=l.codexQuotaEnabled===!0&&l.codexQuotaSidebar!==!1&&$.status==="ok"&&$.windows.weekly!==null,T=(l.budget??{}).enabled===!0,N=l.sidebar!==!1&&l.hideTodayCost!==!0,m=l.sidebarModels?.enabled===!0;if(!m&&!r&&!u&&!b&&!h&&!S&&!T&&!N&&x.length===0)return null;const v=l.sidebarSimple===!0,y=!v&&n&&l.sidebarStyle==="compact",O=v&&n&&N&&T,P=[];O?P.push(e(_t,{state:a,wide:n,summary:!0})):v&&n&&N&&P.push(e("div",{className:"cm-simple-summary"},e("span",null,i("today")),e("span",{className:"cm-num"},Ft(a.today,l,i)))),c?P.push(e(zn,{state:a,wide:n,api:t.api})):r&&P.push(e(Wn,{state:a,wide:n,api:t.api})),p?P.push(e(Gn,{state:a,wide:n,api:t.api})):u&&P.push(e(Vn,{state:a,wide:n,api:t.api}));const R=P.length;if(h&&P.push(...g.map(A=>A==="minimax"?e(ls,{state:a,wide:n,api:t.api}):e(ps,{id:A,state:a,wide:n,api:t.api}))),P.push(...x),S&&P.push(e(ms,{state:a,wide:n,api:t.api})),b&&T&&n&&!v){const A=Da(a,l,i),q=Oa(a,l,i),k=A.level==="over"||q.level==="over"?"over":A.level==="warn"||q.level==="warn"?"warn":"ok";P.push(e("div",{className:"cm-bbox cm-bbox-pair"+(k==="ok"?"":" "+k)},e("div",{className:"cm-bbox-section"+(A.level==="ok"?"":" "+A.level)},A.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(q.level==="ok"?"":" "+q.level)},q.body)))}else b&&P.push(e(ss,{state:a,wide:n})),T&&!O&&P.push(e(_t,{state:a,wide:n}));return!T&&N&&!(v&&n)&&P.push(e(_t,{state:a,wide:n})),v&&n&&N&&P.push(ct(a,l,i)),n||P.push(ns(a,l,i)),m&&P.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?R:P.length,0,e(Cs,{key:"models",state:a,wide:n})),e("div",{...v?{tabIndex:0,role:"region","aria-label":i("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(y?" compact":"")+(v?" simple":"")},...P)}const Wt={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},qa="dsh-cost-meter:models-open";function ja(t,s,o){return Fa(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:Gt(a.key),cost:z(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function Cs({state:t,wide:s}){const o={...Wt,...t.config.sidebarModels},a=G(_(t.config)),n=()=>{try{const S=o.remember?window.localStorage.getItem(qa):null;if(S!==null)return S==="1"}catch{}return o.defaultOpen},[l,i]=B(n),[r,d]=B(o.period);ee(()=>d(o.period),[o.period]),ee(()=>i(n()),[o.defaultOpen,o.remember]);const u=ja(t,r,a),c=u.reduce((S,T)=>S+T.cost,0),p=S=>Y(S,t.config),f=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+p(c)+" · "+a("modelsCount",{n:u.length}),b=o.summary==="top"&&u.length?u[0].label+" "+p(u[0].cost):f,g=o.summary==="top"&&u.length?e(L,null,e("span",{className:"cm-bal-label"},u[0].label),e("span",{className:"cm-bal-amt"},p(u[0].cost))):e("span",{className:"cm-bal-label"},b),h=()=>{i(!l);try{o.remember&&window.localStorage.setItem(qa,l?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:b+" · "+f},s?g:e(ot,{size:16}));const x=u.slice(0,o.topN);return u.length>o.topN&&x.push(u.slice(o.topN).reduce((S,T)=>{for(const N of["cost","input","output","cacheRead","cacheWrite"])S[N]+=T[N];return S},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(l),title:f,onClick:h},e("span",{className:"cm-caret"+(l?" open":"")}),g),l?e(L,null,e("div",{className:"cm-buttons"},["today","history"].map(S=>e("button",{key:S,type:"button",className:"cm-mstats-tab"+(r===S?" active":""),"aria-pressed":r===S,onClick:()=>d(S)},a(S==="today"?"modelStatsToday":"modelStatsHistory")))),x.length?x.map(S=>e("div",{key:S.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:S.label},S.label),e("span",{className:"cm-num cm-bal-amt"},p(S.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?S.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?S.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+I(S.input)+" · "+a("modelStatsCache")+" "+I(S.cacheRead+S.cacheWrite)+" · "+a("modelStatsOutput")+" "+I(S.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function As({draft:t,setDraft:s,t:o}){const a={...Wt,...t?.sidebarModels},n=(i,r)=>{t&&s({...t,sidebarModels:{...a,[i]:r}})},l=(i,r)=>e("div",{className:"cm-field",key:i},e("label",null,o("models_"+i)),e("select",{className:"cm-input",value:a[i],onChange:d=>n(i,d.target.value)},r.map(([d,u])=>e("option",{key:d,value:d},o(u)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(i=>e("label",{key:i,className:"cm-check"},e("input",{type:"checkbox",checked:a[i],onChange:r=>n(i,r.target.checked)}),o("models_"+i))),l("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),l("summary",[["total","modelsTotal"],["top","modelsTop"]]),l("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(i=>e("div",{key:i,className:"cm-field"},e("label",null,o("models_"+i)),ne({value:a[i]},r=>n(i,Math.max(i==="topN"?1:10,Math.min(i==="topN"?10:60,Math.floor(r))))))))}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))}function Ua(t){const[s,o]=B(null),[a,n]=B(""),[l,i]=B(0);return ee(()=>{let r=!0;return n(""),t.api.loadStatistics().then(d=>{r&&o(()=>d)},d=>{r&&n(String(d.message??d))}),()=>{r=!1}},[t.api,l]),s?e(s,{...t,formatMoneyUsd:Y,formatTokens:I,resolveLocale:_}):e("p",{role:a?"alert":"status"},a||"…",a?e("button",{className:"cm-btn",onClick:()=>i(r=>r+1)},"↻"):null)}function Ms(t){const s=t.useCost?.(c=>c),o=s?.state,[a,n]=B(null),l=Be.useRef(null),i=o?.config[t.entryPosition==="header"?"hideSessionCostHeader":"hideSessionCostDock"]===!0,r=!i&&!!t.sessionId&&a===t.sessionId;if(ee(()=>{r&&l.current?.showModal()},[r]),ee(()=>{n(null)},[t.sessionId,i]),!t.sessionId||i)return null;const d=_(o?.config)==="en",u=d?"Conversation cost details":"本会话费用明细";return e(L,null,e("button",{type:"button",className:"cm-btn cm-stat-entry cm-stat-"+(t.entryPosition||"dock"),title:u,"aria-label":u,"aria-haspopup":"dialog",onClick:()=>n(t.sessionId)},d?"Cost details":"费用明细"),r?e("dialog",{ref:l,role:"dialog","aria-label":u,onCancel:()=>n(null),style:{width:"min(1160px,94vw)",maxHeight:"90vh",padding:24,borderRadius:16,border:"1px solid var(--dsw-alias-border-l1)",color:"var(--dsw-alias-label-primary)",background:"var(--dsw-alias-bg-base,#fff)"}},e("button",{type:"button",className:"cm-btn",autoFocus:!0,"aria-label":d?"Close":"关闭",onClick:()=>n(null),style:{float:"right"}},"×"),o?e(Ua,{key:t.sessionId,state:o,api:t.api,sessionId:t.sessionId}):e("p",{role:s?.error?"alert":"status"},s?.error||(d?"Loading…":"加载中…"),e("button",{type:"button",className:"cm-btn",onClick:()=>t.api.reload()},d?"Retry":"重试"))):null)}function Ps({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=u=>Y(z(u,a),a),l=u=>s("callsTokens",{calls:u.calls,input:I(u.input),cache:I(u.cacheRead+u.cacheWrite),output:I(u.output)}),i=(u,c)=>({calls:u.calls+c.calls,input:u.input+c.input,output:u.output+c.output,cacheRead:u.cacheRead+c.cacheRead,cacheWrite:u.cacheWrite+c.cacheWrite,cost:z(u,a)+c.cost,apiCost:z(u,a)+c.cost}),r=(u,c)=>e("tr",{key:u},e("td",null,u),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},I(c.input)),e("td",{className:"num"},I(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},I(c.output)),e("td",{className:"num"},n(c))),d=u=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,u)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((u,c)=>{const p=i(t[u],o.combined[u]);return e(mt,{key:u,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(p),sub:l(p)})})),...o.sources.map(u=>e("details",{key:u.source},e("summary",null,u.source+" · "+s("cardToday")+" "+n(u.today)+" · "+s("cardMonth")+" "+n(u.month)+" · "+l(u.today)),d(["today","month","total"].map((c,p)=>r(s(["cardToday","cardMonth","cardTotal"][p]),u[c]))),e("p",{className:"cm-note"},s("externalHistory")),d(u.history.map(c=>r(c.date,c))))))}const Re=(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 Ts(t){const{state:s,api:o}=t,a=G(_(s.config)),[n,l]=B(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(n,()=>l(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(Os,{state:s,api:o})):null)}function Os(t){const{state:s,api:o}=t,a=G(_(s.config)),[n,l]=B(null),[i,r]=B({}),[d,u]=B(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const p=b=>{if(n===b){l(null);return}l(b),!(i[b]!==void 0||d.has(b))&&(u(g=>{const h=new Set(g);return h.add(b),h}),o.getDaySessions(b).then(g=>r(h=>({...h,[b]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[b]:"error"}))).finally(()=>u(g=>{const h=new Set(g);return h.delete(b),h})))},f=b=>b.map(g=>e("tr",{key:g.id},zt(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},I(g.input)),e("td",{className:"num"},I(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},I(g.output)),e("td",{className:"num"},Y(z(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(b=>{const g=e("tr",{key:b.date,className:"cm-row-click",onClick:()=>p(b.date)},e("td",null,(n===b.date?"▾ ":"▸ ")+b.date),e("td",{className:"num"},String(b.calls)),e("td",{className:"num"},I(b.input)),e("td",{className:"num"},I(b.cacheRead+b.cacheWrite)),e("td",{className:"num"},I(b.output)),e("td",{className:"num"},Y(z(b,s.config),s.config)));if(n!==b.date)return[g];const h=i[b.date],x=d.has(b.date)&&h===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):h==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(h)||h.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,f(h)));return[g,e("tr",{key:b.date+"-sessions"},e("td",{colSpan:6},x))]}))))}function Ds(t){const{state:s,api:o}=t,a=G(_(s.config)),[n,l]=B(!1),[i,r]=B(100),[d,u]=B("cost-desc"),[c,p]=B(null),[f,b]=B(!1),[g,h]=B(!1),x=Be.useRef(0),S=(v,y)=>{const[O,P]=y==="recent"?["recent","desc"]:y.split("-"),R=++x.current;b(!0),h(!1),o.getTopSessions(v,O,P).then(A=>{R===x.current&&p(Array.isArray(A?.sessions)?A.sessions:[])}).catch(()=>{R===x.current&&h(!0)}).finally(()=>{R===x.current&&b(!1)})},T=()=>{l(v=>{const y=!v;return y&&c===null&&!f&&S(i,d),y})},N=v=>{r(v),(n||c!==null)&&S(v,d)},m=v=>{u(v),(n||c!==null)&&S(i,v)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(n,T,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:d,onChange:v=>m(v.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(i),onChange:v=>N(Number(v.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),f?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(v=>e("tr",{key:v.date+":"+v.id},e("td",null,v.date),zt(v,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(v.calls)),e("td",{className:"num"},I(v.input)),e("td",{className:"num"},I((v.cacheRead??0)+(v.cacheWrite??0))),e("td",{className:"num"},I(v.output)),e("td",{className:"num"},Y(z(v,s.config),s.config)))))))):null)}function Bs(t){const{state:s}=t,o=G(_(s.config)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(l=>e("tr",{key:l.id},zt(l,n,o),e("td",{className:"num"},String(l.calls)),e("td",{className:"num"},I(l.input)),e("td",{className:"num"},I(l.cacheRead+l.cacheWrite)),e("td",{className:"num"},I(l.output)),e("td",{className:"num"},Y(z(l,s.config),s.config)))))))}function zt(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",l=a.length>0?a:n,i=a.length>0?a+" · "+t.id:t.id;return e("td",{title:i},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},l),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const Rs={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function Ls(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=o?.budget??l.budget,r=Number(l.exchangeRate),u=(s.budgetUsed??(i.period==="day"?z(s.today,l):i.period==="all"?z(s.total,l):z(s.month,l)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(i.amount)||0),p=i.enabled&&c>0?Math.min(999,u/c*100):null,f=p===null?"ok":p>=100?"over":p>=80?"warn":"ok",b=(x,S)=>{o!==null&&a({...o,budget:{...o.budget??l.budget,[x]:S}})},g=i.period==="custom"?i.customStart+" → "+(i.customEnd??n("periodDay")):null,h=i.enabled&&p!==null?n("budgetStatus",{period:n(Ie[i.period]??"periodMonth"),amount:me(c,l),used:me(u,l),pct:p.toFixed(1)})+(f==="over"?n("overLimit"):f==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:i.enabled===!0,onChange:x=>b("enabled",x.target.checked)}),e("span",null,n("enableBudget")))),i.enabled?e(L,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(f==="ok"?"":f),style:{width:(p===null?0:Math.min(100,p))+"%"}})),e("div",{className:"cm-budget-line"+(f==="over"?" over":"")+" cm-num"},h),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ne({value:i.amount},x=>b("amount",x))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:i.period,onChange:x=>b("period",x.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),i.period==="custom"?e(L,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:i.customStart??"",onChange:x=>b("customStart",x.target.value===""?null:x.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:i.customEnd??"",onChange:x=>b("customEnd",x.target.value===""?null:x.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function Es(t){const{state:s,draft:o,setDraft:a,t:n}=t,l=s.config,i=(c,p)=>{o!==null&&a({...o,[c]:p})},r=o===null?l:{...l,...o},d=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),p=Date.now();if(Number.isFinite(c)&&p<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const f=r.peakWindows??[],b=lt(p,f,r.peakHolidays);return b===null?n("offPeakActive"):b.holiday===!0?n("holidayAllOffPeak"):b.weekend===!0?n("weekendAllOffPeak"):b.inPeak?n("peakActive"):n("offPeakActive")})(),u=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(_(r)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:d}):n("noPeakWindows",{status:d});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>i("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>i("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>i("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>i("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const p=Number(c.target.value);Number.isInteger(p)&&p>=1&&p<=30&&i("peakAlertAhead",p)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>i("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>i("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{i("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?ct(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},u),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>i("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ne(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const l=Number(n);Number.isFinite(l)&&l>=0&&s(l)}})}function Kt(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:l,t:i}=t,r=tt(o),d=f=>{const b={...tt(f)};if(Array.isArray(f.rateHistory)){const g=f.rateHistory.filter(h=>Date.parse(h.before)<=Date.now());g.length>0?b.rateHistory=g:delete b.rateHistory}return b},u=(f,b,g)=>{if(g===null){if(a){const O=d(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),P={...O[f]??{}};delete P[b];const R={...O};Object.keys(P).length>0?R[f]=P:delete R[f],l({...n,prices:{...n.prices,default:R}});return}const N={...n.prices.models},m=d(N[s]??{cacheHit:0,cacheMiss:0,output:0}),v={...m[f]??{}};delete v[b];const y={...m};Object.keys(v).length>0?y[f]=v:delete y[f],N[s]=y,l({...n,prices:{...n.prices,models:N}});return}const h=Math.max(0,g);if(a){let m={...d(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(f==="base")m[b]=h;else{const v={...m[f]??{},[b]:h};m={...m,[f]:v}}l({...n,prices:{...n.prices,default:m}});return}const x={...n.prices.models},S=d(x[s]??{cacheHit:0,cacheMiss:0,output:0});let T={...S};if(f==="base")T[b]=h;else{const N={...S[f]??{},[b]:h};T={...S,[f]:N}}x[s]=T,l({...n,prices:{...n.prices,models:x}})},c=()=>{const f={...n.prices.models};delete f[s],l({...n,prices:{...n.prices,models:f}})},p=(f,b)=>{const g=b==="base"?r:r[b]??null,h=b==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:b},e("span",null,f),ne({value:g?.cacheHit??null,emptyMode:h},x=>u(b,"cacheHit",x)),ne({value:g?.cacheMiss??null,emptyMode:h},x=>u(b,"cacheMiss",x)),ne({value:g?.output??null,emptyMode:h},x=>u(b,"output",x)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(L,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},i("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},i("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},i("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatCached")),e("span",null,i("flatInput")),e("span",null,i("flatOutput"))),p(i("tierBase"),"base"),p(i("tierOffPeak"),"offPeak"),p(i("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},i("datedPriceNote")):null)}const Ha={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 Is(t,s,o="USD"){if(t=tt(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");o==="CNY"&&t.cny&&(t=t.cny);const a=l=>(o==="CNY"?"¥":"$")+String(l),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function qs(t){const{state:s,draft:o,setDraft:a,t:n}=t,[l,i]=B(!1),[r,d]=B({}),u=s.priceCatalog;if(u===null||typeof u!="object")return null;const c=o?.prices??s.config.prices,p=o?.priceTableDisplay??s.config.priceTableDisplay??{},f=(y,O)=>{const P=p[y+":"+O];return typeof P=="boolean"?P:y==="deepseek"},b=(y,O,P)=>{o!==null&&a({...o,priceTableDisplay:{...p,[y+":"+O]:P}})},g=(y,O)=>y==="deepseek"?c.models?.[O]!==void 0:c.providers?.[y]?.models?.[O]!==void 0,h=(y,O,P)=>{if(o===null)return;const R=JSON.parse(JSON.stringify(P));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[O]:R}}});return}const A={...o.prices.providers??{}},q=A[y]??{};A[y]={...q,models:{...q.models??{},[O]:R}},a({...o,prices:{...o.prices,providers:A}})},x=(y,O)=>{if(o===null)return;if(y==="deepseek"){const A={...o.prices.models};delete A[O],a({...o,prices:{...o.prices,models:A}});return}const P={...o.prices.providers??{}},R=P[y];if(R!==void 0&&R.models!==void 0){const A={...R.models};delete A[O],P[y]={...R,models:A},a({...o,prices:{...o.prices,providers:P}})}},S=Object.keys(u).sort((y,O)=>y==="deepseek"?-1:O==="deepseek"?1:y.localeCompare(O)),T=y=>Object.values(u[y]).reduce((O,P)=>O+Object.keys(P).length,0),N=new Set(Object.values(u.deepseek??{}).flatMap(y=>Object.keys(y))),m=Object.keys(c.models??{}).filter(y=>!N.has(y)).sort(),v=(y,O,P)=>{const R=g(y,O),A=f(y,O),q=R?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:A,onChange:k=>b(y,O,k.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(R&&!A&&o!==null){const k=y==="deepseek"?e(Kt,{key:O,modelId:O,entry:c.models[O],isDefault:!1,draft:o,setDraft:a,t:n}):e(Wa,{key:O,provider:y,modelId:O,entry:c.providers?.[y]?.models?.[O],draft:o,setDraft:a,t:n});return e("div",{key:O,className:"cm-catalog-mounted"},q,k)}return e("div",{key:O,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},O),e("span",{className:"cm-catalog-price"},Is(P,n,y==="deepseek"||P?.cny?c.currency:"USD")),R?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,q,e("button",{className:"cm-btn small",disabled:!R&&P?.unpriced===!0,onClick:()=>R?x(y,O):h(y,O,P)},n(R?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>i(y=>!y)},n(l?"catalogCollapse":"catalogOpen"))),l?e(L,null,e("p",{className:"cm-note"},n("catalogNote")),S.map(y=>{const O=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>d(P=>({...P,[y]:!O}))},e("span",null,(O?"▾ ":"▸ ")+(Ha[y]??y)+" · "+T(y))),O?e(L,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(u[y]).sort().map(P=>e("div",{key:P},e("div",{className:"cm-catalog-family"},P),Object.keys(u[y][P]).sort().map(R=>v(y,R,u[y][P][R])))),y==="deepseek"&&m.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),m.map(P=>v("deepseek",P,null))):null):null)})):null)}const Qa=t=>t==="zen"?"go":t,Gt=t=>{const s=t.indexOf(":");return s<=0?t:Qa(t.slice(0,s).toLowerCase())+t.slice(s)};function Fa(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],l=u=>Number.isFinite(Number(u))&&Number(u)>0?Number(u):0,i=(u,c,p)=>{if(!p||typeof p!="object")return;const f=u[c]??(u[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)f[g]+=l(p[g]);const b=c.indexOf(":");f.apiCost+=l(p.apiCost??(Fe(b>0?c.slice(0,b):"deepseek",b>0?c.slice(b+1):c,s)==="plan"?0:p.cost))},r=u=>{if(!u||typeof u!="object")return{};if(u.byProviderModel&&Object.keys(u.byProviderModel).length)return u.byProviderModel;if(u.byModel&&Object.keys(u.byModel).length)return Object.fromEntries(Object.entries(u.byModel).map(([p,f])=>[p.includes(":")?p:"deepseek:"+p,f]));const c={};for(const p of Array.isArray(u.sessions)?u.sessions:[])if(!(!p||typeof p!="object"))if(p.byProviderModel&&Object.keys(p.byProviderModel).length)for(const[f,b]of Object.entries(p.byProviderModel))i(c,f,b);else i(c,(p.provider||"deepseek")+":"+(p.model||"unknown"),p);return Object.keys(c).length?c:n.some(p=>l(u[p])>0)?{"deepseek:legacy":u}:{}};return(u=>{const c={},p=f=>{for(const[b,g]of Object.entries(f??{}))i(c,b,g)};if(u==="today")p(r(t.today));else{const f=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const b of t.history??[]){const g=Date.parse(b.date+"T00:00:00Z");g<=f&&g>=f-76896e5&&p(r(b))}}return Object.entries(c).map(([f,b])=>{const g=f.indexOf(":"),h=(g>0?f.slice(0,g):"deepseek").toLowerCase(),x=g>0?f.slice(g+1):f,S=b.input+b.output+b.cacheRead+b.cacheWrite+b.reasoning,T=b.cacheRead+b.input;return{label:f==="deepseek:legacy"?o("modelStatsLegacy"):h==="deepseek"||h===""?x:Qa(h)+":"+x,key:f,...b,tokens:S,cls:Fe(h,x,s),hitRate:T>0?b.cacheRead/T:null,cacheUnreported:Mn(b),blended:S>0&&b.cost>0?b.cost/S*1e6:null,perUsd:b.cost>0?S/b.cost:null}}).filter(f=>f.tokens>0||f.cost>0)})(a).sort((u,c)=>c.cost-u.cost||c.tokens-u.tokens)}function js(t){const{state:s,config:o,t:a,initialTab:n,draft:l,setDraft:i}=t,[r,d]=B(n==="history"?"history":"today"),[u,c]=B(!1),p=Fa(s,o,a,r),f=m=>(Math.max(0,Math.min(1,m))*100).toFixed(1)+"%",b=p.reduce((m,v)=>Math.max(m,v.cost),0),g=p.reduce((m,v)=>Math.max(m,v.tokens),0),h=p.reduce((m,v)=>Math.max(m,v.perUsd??0),0),x=(m,v)=>e("button",{className:"cm-mstats-tab"+(r===m?" active":""),onClick:()=>d(m)},v),S=m=>m.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,T=m=>e("select",{className:"cm-input",title:a("billingClassLabel"),value:o.planBilling?.models?.[m.key]??"auto",disabled:l===null,onChange:v=>{const y={...l.planBilling?.models??{}};v.target.value==="auto"?delete y[m.key]:y[m.key]=v.target.value,i({...l,planBilling:{...l.planBilling,models:y}})}},e("option",{value:"auto"},a("billingClassAuto")),e("option",{value:"plan"},a("billingClassPlan")),e("option",{value:"api"},a("billingClassApi"))),N=(m,v,y,O,P)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:m},m,P??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+y,style:{width:f(v)}})),e("span",{className:"cm-mstats-val"},O));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(u,()=>c(!u),a("modelStatsTitle"))),u?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},x("today",a("modelStatsToday")),x("history",a("modelStatsHistory"))),p.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(L,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),p.map(m=>e(L,{key:"c:"+m.label},N(m.label,b>0?m.cost/b:0,"cost",Y(m.cost,o),e(L,null,S(m),T(m),m.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...p].sort((m,v)=>v.tokens-m.tokens).map(m=>e("div",{className:"cm-mstats-row",key:"t:"+m.label},e("span",{className:"cm-mstats-name",title:m.label},m.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:f(g>0?m.input/g:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:f(g>0?(m.cacheRead+m.cacheWrite)/g:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:f(g>0?(m.output+m.reasoning)/g:0)}})),e("span",{className:"cm-mstats-val"},I(m.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...p].sort((m,v)=>(v.hitRate??-1)-(m.hitRate??-1)).map(m=>e(L,{key:"h:"+m.label},N(m.label,m.hitRate??0,"hit",m.cacheUnreported?a("modelStatsHitUnreported"):m.hitRate===null?"—":(m.hitRate*100).toFixed(1)+"%",m.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...p].sort((m,v)=>(v.perUsd??-1)-(m.perUsd??-1)).map(m=>e(L,{key:"v:"+m.label},N(m.label,h>0?(m.perUsd??0)/h:0,"value",m.perUsd===null?"—":I(m.perUsd)+" tok/$"+(m.blended!==null?" · "+a("modelStatsBlended",{price:"$"+m.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function Us(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 Hs(t,s){if(t==="go")return"OpenCode Go";const o=Le.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const _a=["fiveHour","weekly","monthly","daily"];function Qs(t,s){const o=new Map,a=n=>{const l=new Date(n),i=r=>String(r).padStart(2,"0");if(s==="monthly")return l.getFullYear()+"-"+i(l.getMonth()+1);if(s==="weekly"){const r=new Date(l.getFullYear(),l.getMonth(),l.getDate()-(l.getDay()+6)%7);return r.getFullYear()+"-"+i(r.getMonth()+1)+"-"+i(r.getDate())}return l.getFullYear()+"-"+i(l.getMonth()+1)+"-"+i(l.getDate())};for(const n of Object.values(t??{}))for(const l of n??[]){if(l===null||typeof l!="object"||!(l.tokens>0)&&!(l.cost>0))continue;const i=a(Number(l.t1)||Number(l.t0)),r=o.get(i)??{key:i,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(l.tokens)||0,r.cost+=Number(l.cost)||0,r.pct+=Number(l.pct)||0,r.intervals+=1,o.set(i,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,l)=>n.key<l.key?-1:n.key>l.key?1:0)}function Fs(t){const{state:s,config:o,t:a}=t,[n,l]=B(!1),[i,r]=B("daily"),d=_(o),u=s?.planStats,c=u!=null&&typeof u.providers=="object"?u.providers:{},p=Object.keys(c).sort(),f=y=>Y(Number(y)||0,o??s?.config),b=y=>y.method==="none"||y.per1Tokens===null?"—":I(y.per1Tokens)+" tok · "+f(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":I(y.fullTokens)+" tok · "+f(y.fullCost),h=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),x=y=>{let O=h(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(O=a("planStatsMethodSampleAt",{method:O,time:new Date(Number(y.sampleAt)).toLocaleString(d==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(O+=" · "+a("planStatsConfidenceLow")),O},S=([y,O,P])=>e("tr",{key:O+":"+y},e("td",null,Us(y,d)),e("td",{className:"num"},Math.round(P.percent*10)/10+"%"),e("td",{className:"num"},I(P.localTokens)+" tok · "+f(P.localCost)),e("td",{className:"num"},b(P)),e("td",{className:"num"},g(P)),e("td",{className:"num cm-plan-reset"},P.resetsAt.length>0?a("planStatsResets",{time:new Date(P.resetsAt).toLocaleString(d==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},x(P))),T=n?p.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,O])=>({winKey:y,list:O})):[],N=Qs(Object.fromEntries(T.map(y=>[y.winKey,y.list])),i),m=N.reduce((y,O)=>Math.max(y,O.fullTokens??0),0),v=(y,O)=>e("button",{key:y,className:"cm-mstats-tab"+(i===y?" active":""),onClick:()=>r(y)},O);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Re(n,()=>l(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},p.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(L,null,p.map(y=>{const O=c[y]?.windows??{},P=[..._a.filter(R=>O[R]!==void 0).map(R=>[R,y,O[R]]),...Object.keys(O).filter(R=>!_a.includes(R)).map(R=>[R,y,O[R]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},Hs(y,a),e("span",{className:"cm-plan-updated"},(()=>{const R=Number(c[y]?.generatedAt)||Number(u?.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,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,P.map(S))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},v("daily",a("planStatsDaily")),v("weekly",a("planStatsWeekly")),v("monthly",a("planStatsMonthly"))),N.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(L,null,[...N].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(m>0?(y.fullTokens??0)/m*100:0).toFixed(1)+"%"}})),e(X,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":I(y.fullTokens),per1:y.per1Tokens===null?"—":I(y.per1Tokens),tokens:I(y.tokens),cost:f(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":I(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Wa(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:l,t:i}=t,r=p=>{const f={...n.prices.providers??{}},b=f[s]??{};f[s]={...b,models:p},l({...n,prices:{...n.prices,providers:f}})},d=(p,f)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}};b[o]={...b[o]??{},[p]:Math.max(0,f)},r(b)},u=(p,f)=>{if(n===null)return;const b={...(n.prices.providers??{})[s]?.models??{}},g=b[o]??{};b[o]={...g,cny:{...g.cny,[p]:Math.max(0,f)}},r(b)},c=()=>{if(n===null)return;const p={...(n.prices.providers??{})[s]?.models??{}};delete p[o],r(p)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(L,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},i("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:c},i("unmountBtn")))),a?.unpriced===!0?null:e(L,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,i("flatInput")),e("span",null,i("flatCached")),e("span",null,i("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ne({value:a?.input??null,emptyMode:"ignore"},p=>d("input",p)),ne({value:a?.cachedInput??null,emptyMode:"ignore"},p=>d("cachedInput",p)),ne({value:a?.output??null,emptyMode:"ignore"},p=>d("output",p))),a?.cny?e("div",{className:"cm-price-row"},e("span",null,"CNY"),ne({value:a.cny.cacheMiss,emptyMode:"ignore"},p=>u("cacheMiss",p)),ne({value:a.cny.cacheHit,emptyMode:"ignore"},p=>u("cacheHit",p)),ne({value:a.cny.output,emptyMode:"ignore"},p=>u("output",p))):null))}const Ye=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Yt=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function _s(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r,d]=Ve(a,()=>o.refreshBalance()),u=s.balance,c=s.config,p=s.reconcile,f=(n?.balance??c.balance??{}).reconcile!==!1,b=x=>{n===null||typeof l!="function"||l({...n,balance:{...n.balance??c.balance??{},reconcile:x.target.checked}})},g=x=>Se(x,c,u?.currency),h=u.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:g(u.totalBalance),granted:g(u.grantedBalance),toppedUp:g(u.toppedUpBalance),time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:u.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:d,disabled:i},a(i?"refreshing":"refreshBalance"))),h,e("label",null,a("balanceApiKey")),e(De,{target:"balance",configured:u.keyConfigured,source:u.keySource,t:a,api:o,placeholder:"sk-…"}),e("p",{className:"cm-hint"},a("balanceKeyHint")),p!==void 0&&p.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+p.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:f,onChange:b}),a("reconcileLabel")),Yt(r))}function pt(t){const{name:s,enabled:o,saved:a,busy:n,open:l,statusNode:i,configNode:r,errorMsg:d,onToggle:u,onRefresh:c,onLogin:p,loginRequired:f,onRemove:b,onToggleOpen:g,t:h}=t,x=r!=null,S=f?p:c,T=h(n===!0?f?"loggingIn":"refreshing":f?"loginCodingPlan":"refresh");return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":h("enable")+": "+s,checked:o===!0,onChange:N=>u(N.target.checked)})),e("div",{className:"cm-quota-name"},x?Re(l===!0,g,s):e("h3",{className:"cm-h"},s)),b?e("button",{className:"cm-btn small",onClick:b},h("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:S,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?h("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?h("quotaRefreshReady"):h(f?"loginCodingPlan":"refresh")},T)),i,x&&l===!0?e("div",{className:"cm-collapse-body"},r):null,d!=null?e("div",{className:"cm-msg "+d.kind},d.text):null)}function Ve(t,s){const[o,a]=B(!1),[n,l]=B(null),i=Ne(!1);return[o,n,async()=>{if(!i.current){i.current=!0,a(!0),l(null);try{const d=await s();l({kind:d.ok?"ok":"err",text:d.message})}catch(d){l({kind:"err",text:t("syncFailed",{message:d?.message??String(d)})})}finally{i.current=!1,a(!1)}}}]}const Ws=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},za=(t,s,o,a,n,l=s)=>{if(typeof o?.percent!="number")return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const i=Math.max(0,Math.min(100,Number(o.percent)||0)),r=fe(i,a),d=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:l,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),d?e("span",{className:"cm-go-reset"},d):null)};function zs(t){const{state:s,api:o,t:a,entry:n,index:l,canRemove:i,onPatch:r,onRemove:d}=t,u=n.adapter==="aliyun",[c,p]=B(!1),f=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[b,g]=B(f),[h,x]=B(()=>(n.allowedHosts??[]).join(", ")),[S,T]=B({}),N=Ne(!1),m=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(D=>D.index===l)??null,O=n.enabled===!0,P=()=>{p(D=>!D)};ee(()=>{c&&!N.current&&(g(f()),x((n.allowedHosts??[]).join(", ")),T({})),N.current=c},[c]);const R=(D,K)=>r({[D]:K}),A=(D,K)=>r({request:{...n.request??{},[D]:K}}),q=u?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(D=>typeof D=="string"?[...D.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(K=>K[1]):[]))],k=(D,K)=>{g(w=>({...w,[D]:K}));try{const w=D==="body",E=w&&!K.trim()?void 0:JSON.parse(K);if(!w&&(E===null||typeof E!="object"||Array.isArray(E)))throw new Error("invalid");if(D==="headers"&&Object.values(E).some(F=>typeof F!="string"))throw new Error("invalid");T(F=>({...F,[D]:""})),D==="extract"?R(D,E):A(D,w?E===void 0?void 0:K:E)}catch{T(w=>({...w,[D]:a("customBalanceInvalidJson")}))}},j=(D,K,w,E)=>!u&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(K)),E&&e("span",{className:"cm-hint"},a(E)),e("textarea",{className:"cm-input",rows:w,value:b[D],onChange:F=>k(D,F.target.value)}),S[D]?e("span",{className:"cm-hint err"},S[D]):null),Ce=D=>{x(D);const K=D.split(/[\s,;]+/).map(w=>w.trim()).filter(w=>w.length>0);R("allowedHosts",K)},[de,Ae,J]=Ve(a,()=>(m.customBalances??[])[l]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(l)),M=y!==null&&y.status==="ok"?e(L,null,m.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(Rt,{segments:Bt(s,m,y,n),direction:ie(m,"balance")}),e("div",{className:"cm-bal-line"},Et(y,m,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:We(y.remaining,m,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),U=e(L,null,e("p",{className:"cm-note"},a(u?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:_e(m,y,n)!=="USD",onChange:D=>R("convertToDisplayCurrency",D.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([D,K])=>e("div",{key:D,className:"cm-field"},e("label",null,a(K)),e("input",{className:"cm-input",value:n[D]??"",onChange:w=>R(D,w.target.value)}))),!u&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:D=>R("unit",D.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:D=>R("display",D.target.value)},...Ye(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ne({value:n.refreshMinutes??15},D=>R("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D)))))),!u&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:D=>A("method",D.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!u&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:D=>A("url",D.target.value)})),j("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&j("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),q.length>0?e(L,null,!u&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),q.map(D=>e(De,{key:"cb-var-"+D,target:"customVar:"+D,configured:(s.customVarStatus?.[D]?.configured??!1)===!0,source:s.customVarStatus?.[D]?.source??"",t:a,api:o,placeholder:"{{"+D+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!u&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:h,placeholder:"api.example.com, relay.example.org",onChange:D=>Ce(D.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),j("extract","customBalanceExtract",8)));return e(pt,{name:`#${l+1} · `+(Lt(n,_(m))||a("customBalanceTitle")),enabled:O,saved:JSON.stringify(n)===JSON.stringify(m.customBalances?.[l])?m.customBalances[l]:null,busy:de,open:c,statusNode:M,configNode:U,errorMsg:Ae,onToggle:D=>R("enabled",D),onRefresh:J,onRemove:i?d:null,onToggleOpen:P,t:a})}function Ka({config:t,draft:s,setDraft:o,t:a,api:n}){const l=s?.goQuota??t.goQuota,i=(r,d)=>{s&&o({...s,goQuota:{...l,[r]:d}})};return e(L,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,d])=>e("div",{key:r,className:"cm-field"},e("label",null,a(d)),e("select",{className:"cm-input",value:l[r],onChange:u=>i(r,u.target.value)},r==="display"?Ye(a):["rolling","weekly","monthly"].map((u,c)=>e("option",{key:u,value:u},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ne({value:l.refreshMinutes},r=>i("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function Ks(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,[i,r]=B(!1),d=s.goQuota,u=s.config,c=n?.goQuota?.enabled??u.goQuota?.enabled??!0,p=(m,v)=>{n!==null&&l({...n,goQuota:{...n.goQuota??u.goQuota,[m]:v}})},[f,b,g]=Ve(a,()=>o.refreshGoQuota()),h=u.goQuota?.main==="weekly"||u.goQuota?.main==="monthly"?u.goQuota.main:"rolling",x=[h,...["rolling","weekly","monthly"].filter(m=>m!==h)],S=m=>m==="rolling"?"goWindowRolling":m==="weekly"?"goWindowWeekly":"goWindowMonthly",T=m=>m==="rolling"?d.rolling:m==="weekly"?d.weekly:d.monthly,N=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):d.status==="ok"?e("div",{className:"cm-go-list"},x.map(m=>za(a,a(S(m)),T(m),ie(u,"go"),m===h)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:d.fetchedAt>0?new Date(d.fetchedAt).toLocaleTimeString():"—"}))):d.status==="error"?e("div",{className:"cm-bal-line err"},d.message||a("unknownError")):d.status==="off"&&d.message?e("p",{className:"cm-note"},d.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(pt,{name:a("goQuotaTitle"),enabled:c,saved:u.goQuota,busy:f,open:i,statusNode:N,errorMsg:b,configNode:e(Ka,{config:u,draft:n,setDraft:l,t:a,api:o}),onToggleOpen:()=>r(m=>!m),onToggle:m=>p("enabled",m),onRefresh:g,t:a})}const Gs=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Ys(t){const{state:s,api:o,t:a,draft:n,setDraft:l,index:i}=t,r=s.config,u=(n??r).gatewayQuotas?.sources??[],c=u[i]??{},f=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(A=>A.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},b=Gs(c,s.customVarStatus),[g,h]=B(!1),[x,S,T]=Ve(a,()=>o.refreshGatewayQuota(c.id)),N=A=>{n!==null&&l({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:A}})},m=A=>N(u.map((q,k)=>k===i?{...q,...A}:q)),v=(A,q,k)=>e("div",{className:"cm-field"},e("label",null,A),e("input",{className:"cm-input",value:q??"",onChange:k})),y=(A,q)=>{const k=Ge(A?.label||A?.id||a("gatewaySourceUnknown"),A,ie(r,"plan"),a);return e(L,{key:A?.id||q},k.row,A?.resetsAt?e("div",{className:"cm-note"},Ke(A,a)):null)},O=(A,q)=>e("div",{key:A.id||q,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},A.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),P=A=>A==null?null:e(L,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},A.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(A.used??"—")+" / "+(A.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(A.remaining??"—")+" remaining")),(A.packages??[]).map(O)),R=(A,q)=>e("div",{key:A.id||q,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(la[A.provider]??A.provider??a("gatewaySourceUnknown"))+" · "+(A.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},A.status)),A.plan?e("div",{className:"cm-note"},A.plan):null,A.windows.length>0?e("div",{className:"cm-go-list"},A.windows.map(y)):null,P(A.credits),A.message?e("div",{className:"cm-note"},A.message):null);return e(pt,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(A=>A.id===c.id),busy:x,open:g,errorMsg:S,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(f.status??a("gatewaySourceUnknown"))+(f.serverVersion?" · "+f.serverVersion:"")+(f.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(f.fetchedAt).toLocaleTimeString()}):"")+(f.message?" · "+f.message:"")),configNode:e(L,null,e("div",{className:"cm-grid"},v(a("gatewaySourceLabel"),c.label,A=>m({label:A.target.value})),v(a("gatewaySourceBaseURL"),c.baseURL,A=>m({baseURL:A.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:A=>m({display:A.target.value})},...Ye(a))),v(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),A=>m({allowedHosts:A.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:A=>m({antigravityOnlyGemini:A.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),b?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+b,configured:s.customVarStatus?.[b]?.configured===!0,source:s.customVarStatus?.[b]?.source??"",t:a,api:o,placeholder:b})):null,f.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+f.unsupportedProviders.join(", ")):null,f.accounts.length>0?f.accounts.map(R):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:A=>m({enabled:A}),onRefresh:T,onRemove:()=>N(u.filter((A,q)=>q!==i)),onToggleOpen:()=>h(A=>!A),t:a})}const Le=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function Vs(t){const{state:s,api:o,t:a,draft:n,setDraft:l,planId:i,labelKey:r}=t,d=s.config,u=s.codingPlans??{},c=n?.codingPlans?.[i]??d.codingPlans?.[i]??{},p=u[i]??{status:"off",message:"",fetchedAt:0,windows:{}},f=c.enabled===!0,[b,g]=B(!1),h=i==="qwen"&&d.codingPlans?.qwen?.quotaSource==="bailian"&&c.quotaSource==="bailian"&&p.quotaSource==="bailian"&&p.loginRequired===!0,[x,S,T]=Ve(a,()=>h?o.loginCodingPlan(i):o.refreshCodingPlan(i)),N=(M,U)=>{if(n===null)return;const D=n.codingPlans??d.codingPlans??{};l({...n,codingPlans:{...D,[i]:{...D[i]??{},[M]:U}}})},[m,v]=B(""),[y,O]=B({}),P=M=>M?.rates!==null&&typeof M?.rates=="object"&&!Array.isArray(M.rates)?M.rates:{},R=["input","cachedInput","output"],A=M=>y[M]??P(c)[M]??{},q=M=>R.every(U=>Number.isFinite(Number(M[U]))&&Number(M[U])>0),k=(M,U,D)=>{if(n===null)return;const K={...A(M),[U]:String(D)};O(te=>({...te,[M]:K}));const w=R.every(te=>String(K[te]??"").trim()==="");if(!w&&!q(K))return;const E=n.codingPlans??d.codingPlans??{},F={...(E.qwen??{}).rates??{}};w?delete F[M]:F[M]=Object.fromEntries(R.map(te=>[te,Number(K[te])])),l({...n,codingPlans:{...E,qwen:{...E.qwen??{},rates:F}}})},j=M=>{n!==null&&O(U=>({...U,[M]:U[M]??P(c)[M]??{}}))},Ce=M=>{if(n===null)return;O(K=>{const w={...K};return delete w[M],w});const U=n.codingPlans??d.codingPlans??{},D={...(U.qwen??{}).rates??{}};delete D[M],l({...n,codingPlans:{...U,qwen:{...U.qwen??{},rates:D}}})},de=p.windows!==null&&typeof p.windows=="object"?p.windows:{},Ae=f===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):p.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(de).length>0?i==="minimax"&&(ze(de).five!=null||ze(de).seven!=null)?e(Ra,{five:ze(de).five,seven:ze(de).seven,fetchedAt:p.fetchedAt,t:a,wide:!0,direction:ie(d,"plan")}):Object.entries(de).map(([M,U])=>za(a,M.replace(/_/g," "),U,ie(d,"plan"),!1,M)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:p.fetchedAt>0?new Date(p.fetchedAt).toLocaleTimeString():"—"}))):p.status==="error"?e("div",{className:"cm-bal-line err"},p.message||a("unknownError")):p.status==="off"&&p.message?e("p",{className:"cm-note"},p.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),J=e(L,null,i==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:M=>N("baseUrl",M.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,i==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:M=>N("quotaSource",M.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:i==="minimax"?"both":"settings",onChange:M=>N("display",M.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),i!=="scnet"&&(i!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ne({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},M=>{N("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(M))))})):null,i==="scnet"||i==="qwen"&&(c.quotaSource??"local")==="local"?e(L,null,e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:i==="qwen"?5e5:24e4,onChange:M=>{const U=Number(M.target.value);Number.isFinite(U)&&U>0&&N("planCredits",Math.floor(U))}})),e("div",{className:"cm-field"},e("label",null,a(i==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:M=>N("planStart",M.target.value)})),i==="qwen"?e(L,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(P(c)),...Object.keys(y)])].sort().map(M=>e("div",{key:M,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},M),R.map(U=>e("input",{key:U,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:A(M)[U]??"",placeholder:a("qwenRate_"+U),"aria-label":M+" · "+a("qwenRate_"+U),onChange:D=>{const K=D.target.value;k(M,U,K)}})),e("button",{className:"cm-btn small",onClick:()=>Ce(M)},a("overrideRemove")),M in y&&!q(A(M))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:m,onChange:M=>v(M.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const M=m.trim();M.length!==0&&(j(M),v(""))},disabled:m.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(i==="qwen"?"qwenLocalNote":"scnetLocalNote"))):i==="qwen"?null:i==="volcengine"?e(L,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:p.keyConfigured===!0,source:p.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:p.keyConfigured===!0,source:p.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(L,null,e("div",{className:"cm-field"},e("label",null,i==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+i,configured:p.keyConfigured===!0,source:p.keySource,t:a,api:o,placeholder:i==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(pt,{name:a(r),enabled:f,saved:d.codingPlans?.[i],busy:x,open:b,errorMsg:S,statusNode:Ae,configNode:J,onToggle:M=>N("enabled",M),onRefresh:T,onLogin:T,loginRequired:h,onToggleOpen:()=>g(M=>!M),t:a})}function Js(t){const{state:s,api:o,t:a,draft:n,setDraft:l}=t,i=s.config,r=n??i,d=r.codingPlans??{},u=r.gatewayQuotas?.sources??[],c=n?.customBalances??i.customBalances??[],p=N=>{n!==null&&l({...n,customBalances:N,...N.length===0?{customBalance:{...i.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},f=Ne({next:0,keys:[]}).current;for(;f.keys.length<c.length;)f.keys.push(f.next++);f.keys.length=c.length;const b=N=>{f.keys.splice(N,1),p(c.filter((m,v)=>v!==N))},g=(N,m)=>p(c.map((v,y)=>y===N?{...v,...m}:v)),h=(N="custom")=>{c.length>=8||p([...c,{...N==="aliyun"?{adapter:N}:{},enabled:!1,label:N==="aliyun"?"千问 / 阿里云":"",labelEn:N==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:N==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:N==="aliyun"?"https://business.aliyuncs.com/":"",method:N==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},x=()=>{u.length>=4||n===null||l({...n,gatewayQuotas:{...n.gatewayQuotas??i.gatewayQuotas??{},sources:[...u,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:xt,allowedHosts:[],allowInsecureHttp:!1}]}})},S=[...u.map((N,m)=>({kind:"gateway",key:"gw-"+(N.id??m),index:m,enabled:N.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Le.map(N=>({kind:"plan",key:"plan-"+N.id,planId:N.id,labelKey:N.labelKey,enabled:d[N.id]?.enabled===!0})),...c.map((N,m)=>({kind:"custom",key:"cb-"+f.keys[m],index:m,enabled:N.enabled===!0}))],T=N=>N.kind==="plan"?e(Vs,{key:N.key,planId:N.planId,labelKey:N.labelKey,state:s,api:o,t:a,draft:n,setDraft:l}):N.kind==="go"?e(Ks,{key:N.key,state:s,api:o,t:a,draft:n,setDraft:l}):N.kind==="gateway"?e(Ys,{key:N.key,index:N.index,state:s,api:o,t:a,draft:n,setDraft:l}):e(zs,{key:N.key,state:s,api:o,t:a,entry:c[N.index],index:N.index,canRemove:!0,onPatch:m=>g(N.index,m),onRemove:()=>b(N.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ws(S).map(T)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:x,disabled:u.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>h(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>h("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const Zs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ga=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function Vt(t){const s=t.useCost?t.useCost(m=>m):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=_(a),l=t.t??G(n),i=Array.isArray(o.history)?o.history:[];if(i.length===0)return e("div",null,e("h3",{className:"cm-h"},l("usageTitle")),e("p",{className:"cm-empty"},l("usageEmpty")));const r=o.meta?.dayKey??"",d=new Map(i.map(m=>[m.date,m])),u=m=>{const v=y=>String(y).padStart(2,"0");return m.getFullYear()+"-"+v(m.getMonth()+1)+"-"+v(m.getDate())},c=new Date;c.setHours(0,0,0,0);const p=new Date(c);p.setDate(p.getDate()+(6-(c.getDay()+6)%7));const f=26,b=[],g=[];let h=-1;for(let m=f-1;m>=0;m-=1){for(let y=0;y<7;y+=1){const O=new Date(p);O.setDate(O.getDate()-(m*7+(6-y)));const P=d.get(u(O));b.push(P!==void 0?{day:P,tokens:Ga(P)}:{day:{date:u(O)},tokens:0})}const v=new Date(p);v.setDate(v.getDate()-(m*7+6)),g.push(v.getMonth()!==h?n==="en"?Zs[v.getMonth()]:String(v.getMonth()+1)+"月":""),h=v.getMonth()}const x=Math.max(...b.map(m=>m.tokens),1),S=m=>{const v=m/x;return v<.25?1:v<.5?2:v<.75?3:4},T=m=>{const{day:v,tokens:y}=m,O="cm-ug-cell"+(y>0?" l"+S(y):"")+(v.date===r?" today":""),P=l("usageDay",{date:v.date,tokens:I(y),input:I(v.input??0),cache:I((v.cacheRead??0)+(v.cacheWrite??0)),output:I(v.output??0),calls:v.calls??0,cost:Y(z(v,a),a)});return e(X,{key:v.date,label:P,side:"top",delayMs:200},e("div",{className:O}))},N=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},l("usageTitle")),e("div",{className:"cm-ug-total"},l("usageTotal",{tokens:I(Ga(N)),input:I(N.input??0),cache:I((N.cacheRead??0)+(N.cacheWrite??0)),output:I(N.output??0),calls:N.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+f+",1fr)"}},b.map(T)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+f+",1fr)"}},g.map((m,v)=>e("span",{key:"m"+String(v),className:"cm-ug-monthc"},m))))}function $s(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.api,a=s?.state??null,[n,l]=B(null),[i,r]=B(null),[d,u]=B(!1),[c,p]=B(!1),[f,b]=B(!1),[g,h]=B(""),[x,S]=B(!1),[T,N]=B(!1),[m,v]=B("overview"),[y,O]=B({status:"idle",at:0,error:null}),P=Be.useRef(null),R=Be.useRef(null),A=Be.useRef(null);ee(()=>{if(a!==null){const w=JSON.stringify(a.config);l(E=>{const F=E!==null&&JSON.stringify(E)!==P.current;return F||(R.current=a.config,A.current=a.config),F?{...E,activeLocale:a.config.activeLocale}:JSON.parse(w)}),P.current=w}},[a]),ee(()=>{n!==null&&A.current===null&&R.current!==null&&(A.current=R.current)},[n]),ee(()=>{if(n===null||o===void 0)return;const w=JSON.stringify(n);if(w===P.current)return;O(F=>F.status==="saving"?F:{...F,status:"saving"});const E=setTimeout(()=>{const F={},te=A.current??R.current;if(te!==null&&typeof te=="object")for(const V of Object.keys(n))V!=="activeLocale"&&JSON.stringify(n[V])!==JSON.stringify(te[V])&&(F[V]=n[V]);if(Object.keys(F).length===0){P.current=w,O({status:"saved",at:Date.now(),error:null});return}o.updateConfig(F).then(()=>{P.current=w,te!==null&&typeof te=="object"&&(A.current={...te,...F}),O({status:"saved",at:Date.now(),error:null})},V=>{O({status:"error",at:0,error:V?.message??String(V)})})},600);return()=>{clearTimeout(E)}},[n,o]),ee(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:k("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const q=_({...n??a?.config,activeLocale:s?.locale}),k=G(q);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?k("readingLedger"):k("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},k("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},k("refresh")));const j=a.config,Ce=async()=>{if(!x){S(!0),r(null);try{const w=await o.fetchPrices();if(r({kind:w.ok?"ok":"err",text:w.message}),w.ok&&w.state&&typeof w.state.config=="object"){const E=JSON.stringify(w.state.config);l(JSON.parse(E)),P.current=E}}catch(w){r({kind:"err",text:k("syncFailed",{message:w?.message??String(w)})})}finally{S(!1),u(!1)}}},de=async()=>{if(!x){S(!0);try{await o.resetHistory(),r({kind:"ok",text:k("historyCleared")})}catch(w){r({kind:"err",text:k("clearFailed",{message:w?.message??String(w)})})}finally{S(!1),p(!1)}}},Ae=async()=>{if(!x){S(!0),r(null);try{const w=await o.importLegacyHistory();r({kind:"ok",text:w.message})}catch(w){r({kind:"err",text:k("legacyImportFailed",{message:w?.message??String(w)})})}finally{S(!1),b(!1)}}},J=(w,E)=>{n!==null&&l({...n,[w]:E})},M=()=>{if(n===null)return;const w=g.trim().toLowerCase();if(w.length===0||!/^[a-z0-9_.-]+$/.test(w)||n?.prices.models[w]!==void 0)return;const E={...n.prices.models,[w]:{cacheHit:0,cacheMiss:0,output:0}};l({...n,prices:{...n.prices,models:E}}),h("")},U=n===null?[]:Object.keys(n.prices.models).filter(w=>{const F=(n?.priceTableDisplay??j.priceTableDisplay??{})["deepseek:"+w];return typeof F=="boolean"?F:!0}).map(w=>e(Kt,{key:w,modelId:w,entry:n.prices.models[w]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:l,t:k})),D=[["overview",k("tabOverview")],["statistics",q==="en"?"Cost statistics":"计费统计"],["quotas",k("tabQuotas")],["usage",k("tabUsage")],["pricing",k("tabPricing")],["display",k("tabDisplay")]],K=y.status==="saving"?e("span",{className:"cm-hint"},k("saving")):y.status==="error"?e("span",{className:"cm-msg err"},k("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?k("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):k("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},D.map(([w,E])=>e("button",{key:w,type:"button",role:"tab","aria-selected":String(m===w),className:"cm-tab"+(m===w?" active":""),onClick:()=>v(w)},E))),K),Yt(i),m==="statistics"?e(Ua,{state:a,api:o}):null,m==="overview"?e(L,{key:"overview"},e("div",{className:"cm-cards"},j.hideTodayCost===!0?null:e(mt,{title:k("cardToday"),value:Y(z(a.today,j),j),sub:k("callsTokens",{calls:a.today.calls,input:I(a.today.input),cache:I(a.today.cacheRead+a.today.cacheWrite),output:I(a.today.output)})}),e(mt,{title:k("cardMonth"),value:Y(z(a.month,j),j),sub:k("callsTokens",{calls:a.month.calls,input:I(a.month.input),cache:I(a.month.cacheRead+a.month.cacheWrite),output:I(a.month.output)})}),e(mt,{title:k("cardTotal"),value:Y(z(a.total,j),j),sub:k("cardTotalSub",{calls:a.total.calls})})),e(Ps,{state:a,t:k}),e("p",{className:"cm-note",key:"cards-footnote"},k("cardsFootnote")),(()=>{const w=Rn(a);return w!==null?e("p",{className:"cm-note",key:"tz-hint"},k("timezoneHint",{host:w.hostLabel,browser:w.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:k("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??j).showTotalWithPlan===!0,onChange:w=>{const E=n??j;E!=null&&l({...E,showTotalWithPlan:w.target.checked})}}),e("span",null,k("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},k("todaySessions")),e(Bs,{state:a,t:k})),e(Ls,{state:a,draft:n,setDraft:l,t:k}),(j.balance?.display==="settings"||j.balance?.display==="both")&&j.hideOfficialBalance!==!0?e(_s,{state:a,api:o,t:k,draft:n,setDraft:l}):null):null,m==="quotas"?e(Js,{key:"quotas",state:a,api:o,t:k,draft:n,setDraft:l}):null,m==="usage"?e(L,{key:"usage"},!Xe||(j.usage?.position??"cost")==="cost"?e(Vt,{state:a,t:k,locale:q}):null,e(js,{state:a,config:n??j,t:k,draft:n,setDraft:l}),e(Fs,{state:a,config:n??j,t:k}),e(Ts,{state:a,api:o}),e(Ds,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},k("historyDataTitle")),e("div",{className:"cm-buttons"},f?e(L,null,e("span",{className:"cm-hint"},k("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:Ae,disabled:x},k("apply")),e("button",{className:"cm-btn",onClick:()=>b(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>b(!0),disabled:x},k("importLegacy")),c?e(L,null,e("span",{className:"cm-hint"},k("confirmReset")),e("button",{className:"cm-btn danger",onClick:de,disabled:x},k("confirmClear")),e("button",{className:"cm-btn",onClick:()=>p(!1)},k("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>p(!0),disabled:x},k("clearAllHistory"))),e("p",{className:"cm-note"},k("legacyImportNote")))):null,m==="display"?e(L,{key:"display"},e(As,{draft:n,setDraft:l,t:k}),a?.secretMigration?.pending?.length>0?e(En,{pending:a.secretMigration.pending,t:k}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,k("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:w=>J("locale",w.target.value)},e("option",{value:"auto"},k("localeAuto")),e("option",{value:"zh"},k("localeZh")),e("option",{value:"en"},k("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},k("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},k("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled","codexQuotaSidebar"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:E=>J(w,E.target.checked)}),e("span",null,k(w)))),Xe?e("div",{className:"cm-field"},e("label",null,k("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:w=>{n!==null&&l({...n,usage:{...n.usage??{position:"cost"},position:w.target.value}})}},e("option",{value:"cost"},k("usagePositionCost")),e("option",{value:"general"},k("usagePositionGeneral")),e("option",{value:"section"},k("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,k("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:w=>J("position",w.target.value)},e("option",{value:"dock"},k("positionDock")),e("option",{value:"header"},k("positionHeader")),e("option",{value:"off"},k("off")))),e("div",{className:"cm-field"},e("label",null,k("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:w=>J("sidebar",w.target.value==="on")},e("option",{value:"on"},k("sidebarOn")),e("option",{value:"off"},k("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:w=>J("showSessionId",w.target.checked)}),e("span",null,k("showSessionIdLabel"))),...["hideSessionCostHeader","hideSessionCostDock","hideTurnCost","sessionCostCompact"].map(w=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[w]===!0,onChange:E=>J(w,E.target.checked)}),e("span",null,k(w)))),e("div",{className:"cm-grid-group"},k("groupMoney")),e("div",{className:"cm-field"},e("label",null,k("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:w=>{const E=Rs[w.target.value];E!==void 0&&n!==null&&l({...n,currency:w.target.value,...E})}},e("option",{value:"CNY"},k("currencyCny")),e("option",{value:"USD"},k("currencyUsd")),e("option",{value:"EUR"},k("currencyEur")))),e("div",{className:"cm-field"},e("label",null,k("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:w=>J("symbol",w.target.value)})),e("div",{className:"cm-field"},e("label",null,k("rateLabel")),ne({value:n?.exchangeRate??1,emptyMode:"ignore"},w=>J("exchangeRate",w))),e("div",{className:"cm-field"},e("label",null,k("decimalsLabel")),ne({value:n?.decimals??2},w=>J("decimals",Math.min(10,Math.floor(w))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:w=>J("hideOfficialBalance",w.target.checked)}),e("span",null,k("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:w=>J("hideTodayCost",w.target.checked)}),e("span",null,k("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},k("groupSidebar")),e("div",{className:"cm-field"},e("label",null,k("sidebarTodayMetric")),e("select",{className:"cm-input",value:n?.sidebarTodayMetric??"cost",onChange:w=>J("sidebarTodayMetric",w.target.value)},e("option",{value:"cost"},k("sidebarTodayCost")),e("option",{value:"tokens"},k("sidebarTodayTokens")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:w=>{n&&l({...n,sidebarSimple:w.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,k("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,k("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:w=>J("sidebarStyle",w.target.value)},e("option",{value:"standard"},k("sidebarStyleStandard")),e("option",{value:"compact"},k("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,k("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:w.target.value}})}},...Ye(k))),e("div",{className:"cm-field"},e("label",null,k("refreshIntervalLabel")),ne({value:n?.balance?.refreshMinutes??5},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:w.target.checked}})}}),e("span",null,k("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,k("balanceBudgetCapLabel")),ne({value:n?.balance?.budgetCap??""},w=>{n!==null&&l({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:w>0?w:null}})}),e("span",{className:"cm-hint"},k("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,k("barDirectionsTitle")),["balance","budget","go","plan"].map(w=>e("div",{className:"cm-dir-row",key:w},e("span",{className:"cm-dir-label"},k("barDirection_"+w)),e("select",{className:"cm-input",value:n?.barDirections?.[w]??(w==="balance"?"remaining":"used"),onChange:E=>{if(n===null)return;const F={balance:"remaining",budget:"used",go:"used",plan:"used"};l({...n,barDirections:{...n.barDirections??F,[w]:E.target.value}})}},e("option",{value:"remaining"},k("barDirectionRemaining")),e("option",{value:"used"},k("barDirectionUsed"))))),e("span",{className:"cm-hint"},k("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,k("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??j.customBalance?.display??"both",onChange:w=>{n!==null&&l({...n,customBalance:{...n.customBalance??j.customBalance??{},display:w.target.value}})}},...Ye(k))),e("div",{className:"cm-field"},e("label",null,k("customBalanceRefreshInterval")),ne({value:n?.customBalance?.refreshMinutes??j.customBalance?.refreshMinutes??15},w=>{n!==null&&l({...n,customBalance:{...n.customBalance??j.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(w)))}})})),e(Ka,{config:j,draft:n,setDraft:l,t:k,api:o}),e("div",{className:"cm-grid-group"},k("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:w=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:w.target.checked,promptSeen:!0}})}}),e("span",null,k("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([w,E])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[w]!==!1,onChange:F=>{n!==null&&l({...n,quotaStrip:{...n.quotaStrip,[w]:F.target.checked}})}}),e("span",null,k(E)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},k("quotaStripNote"))),e("div",{className:"cm-grid-group"},k("groupCorner")),e("div",{className:"cm-field"},e("label",null,k("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:w=>{n!==null&&l({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:w.target.checked}})}}),e("span",null,k("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([w,E])=>e("label",{key:w,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[w]!==!1,onChange:F=>{n!==null&&l({...n,corner:{...n.corner,[w]:F.target.checked}})}}),e("span",null,k(E)))):null),e("div",{className:"cm-grid-group"},k("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:w=>{n!==null&&l({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:w.target.checked}})}}),e("span",null,k("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:w=>{n!==null&&l({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:w.target.checked}})}}),e("span",null,k("budgetDetailLabel"))))),e("p",{className:"cm-note"},k("badgeNote")))):null,m==="pricing"?e(L,{key:"pricing"},e(Es,{state:a,draft:n,setDraft:l,t:k}),e("div",null,Re(T,()=>N(!T),k("priceTableTitle")),T?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},k("priceTableNote")),e("p",{className:"cm-hint"},k("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},k("deepseekMountedHeader")),U,e(Kt,{key:"__default__",modelId:k("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:l,t:k}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:k("newModelPlaceholder"),value:g,onChange:w=>h(w.target.value)}),e("button",{className:"cm-btn small",onClick:M,disabled:g.trim().length===0},k("addModel"))),(()=>{const w=n?.priceTableDisplay??j.priceTableDisplay??{},E=n?.prices?.providers??{},F=V=>Object.keys(E[V]?.models??{}).filter(pe=>w[V+":"+pe]===!0),te=Object.keys(E).filter(V=>F(V).length>0).sort((V,pe)=>V.localeCompare(pe));return te.length===0?null:te.map(V=>e("div",{key:V},e("div",{className:"cm-catalog-vendor"},(Ha[V]??V)+" · "+k("mountedSuffix")),F(V).sort().map(pe=>e(Wa,{key:V+":"+pe,provider:V,modelId:pe,entry:E[V].models[pe],draft:n,setDraft:l,t:k}))))})()):null),(()=>{const w=n?.priceOverrides??j.priceOverrides??{},E=n?.priceMatchDismissed??j.priceMatchDismissed??[],F=n?.prices??j.prices,te=a.today.byProviderModel??{},V={prices:F,priceMatch:n?.priceMatch??j.priceMatch},pe=Object.keys(te).filter(H=>{if(E.includes(H)||w[H]!==void 0)return!1;const W=H.indexOf(":"),se=(W>0?H.slice(0,W):"deepseek").toLowerCase(),xe=W>0?H.slice(W+1):H;return Tt(se,xe,V).matched!==!0}),Je=[...new Set([...pe,...Object.keys(w)])].filter(H=>!E.includes(H)),ft=a.month?.byProviderModel??{},C=Object.keys(ft).filter(H=>{if(E.includes(H)||w[H]!==void 0)return!1;const W=H.indexOf(":"),se=(W>0?H.slice(0,W):"deepseek").toLowerCase(),xe=W>0?H.slice(W+1):H;return Tt(se,xe,V).matched===!0}).sort(),Q=[{value:"__local__",label:k("overrideTargetLocal")},{value:"deepseek:__default__",label:k("overrideTargetDefault")},...Object.keys(F.models??{}).map(H=>({value:"deepseek:"+H,label:"DeepSeek · "+H})),...Object.entries(F.providers??{}).flatMap(([H,W])=>Object.keys(W?.models??{}).map(se=>({value:H+":"+se,label:H+" · "+se})))],Z=(H,W)=>{if(n===null)return;const se={...n.priceOverrides??{}};W===""?delete se[H]:se[H]=W,l({...n,priceOverrides:se})},oe=H=>{if(n===null)return;const W={...n.priceOverrides??{}};delete W[H],l({...n,priceOverrides:W,priceMatchDismissed:[...new Set([...E,H])]})};return e("div",null,e("h3",{className:"cm-h"},k("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:H=>J("priceMatch",H.target.value)},e("option",{value:"auto"},k("priceMatchAuto")),e("option",{value:"exact"},k("priceMatchExact")))),e("p",{className:"cm-note"},k("priceMatchNote")),Je.length>0?e(L,null,e("h3",{className:"cm-h"},k("unmatchedTitle")),e("p",{className:"cm-hint"},k("unmatchedHint")),Je.map(H=>e("div",{key:H,className:"cm-match-row"},e("span",null,Gt(H)),e("select",{className:"cm-input",value:w[H]??"",onChange:W=>Z(H,W.target.value)},e("option",{value:""},"—"),Q.map(W=>e("option",{key:W.value,value:W.value},W.label))),e("button",{className:"cm-btn small",title:k("removePriceMatchHint"),onClick:()=>oe(H)},k("overrideRemove"))))):e("p",{className:"cm-hint"},k("overrideNone")),E.length>0?e("button",{className:"cm-btn small",onClick:()=>J("priceMatchDismissed",[])},k("restorePriceMatches",{count:E.length})):null,C.length>0?e(L,null,e("h3",{className:"cm-h"},k("matchedTitle")),e("p",{className:"cm-hint"},k("matchedHint")),C.map(H=>e("div",{key:H,className:"cm-match-row"},e("span",null,Gt(H)),e("select",{className:"cm-input",value:"",onChange:W=>{W.target.value!==""&&Z(H,W.target.value)}},e("option",{value:""},k("matchedKeepAuto")),Q.map(W=>e("option",{key:W.value,value:W.value},W.label)))))):null)})(),e(qs,{state:a,draft:n,setDraft:l,t:k}),e("div",null,e("h3",{className:"cm-h"},k("dataSync")),(n??j).currency==="CNY"&&(n??j).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},k("pricingCnyHint",{rate:(n??j).exchangeRate}),(n??j).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:x,onClick:()=>J("pricingCurrency","CNY")},k("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,k("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:w=>J("pricingCurrency",w.target.value)},e("option",{value:"USD"},k("pricingCurrencyUsd")),e("option",{value:"CNY"},k("pricingCurrencyCny"))),e("p",{className:"cm-note"},k("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},d?e(L,null,e("span",{className:"cm-hint"},k("confirmFetch")),e("button",{className:"cm-btn",onClick:Ce,disabled:x},k("apply")),e("button",{className:"cm-btn",onClick:()=>u(!1)},k("cancel"))):e("button",{className:"cm-btn",onClick:()=>u(!0),disabled:x},k("syncFromDocs"))),e("p",{className:"cm-note"},k("lastSync",{time:j.fetchedAt!==null?new Date(j.fetchedAt).toLocaleString():k("neverSynced")})+k("source",{source:j.priceSource==="official"?k("sourceOfficial"):k("sourceBundled")})),e("p",{className:"cm-note"},k("syncScopeNote")))):null)}const Xs=["remote"];async function eo(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(gn);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=()=>{try{return Ee(t.get("locale")?.getSnapshot?.().active)}catch{return null}},l=Ln({status:"loading",error:null,state:null},C=>{const Q=n()||Ee(C.state?.meta?.locale)||Xt();return{...C,locale:Q,...C.state?{state:{...C.state,config:{...C.state.config,activeLocale:Q}}}:{}}}),i=()=>G(_(l.getSnapshot().state?.config||{activeLocale:l.getSnapshot().locale})),r=async(C,Q)=>{const Z=await a[C](...Q??[]);if(Z===null||typeof Z!="object"||Z.ok!==!0)throw new Error(Z?.error?.message??i()("rpcFailed",{method:C}));return Z.value};let d=Date.now(),u=!1,c=!0,p=1;const f=async()=>{if(!c||u)return;u=!0,d=Date.now();const C=l.getSnapshot();C.state===null&&l.set({...C,status:"loading"});try{const Q=await r("getState");if(!c)return;p=1,l.set({status:"ready",error:null,state:Q})}catch(Q){if(!c)return;C.state===null&&(d=Date.now()),p=Math.min(p*2,60),l.set({status:"error",error:Q?.message??String(Q),state:C.state})}finally{u=!1}};t.effect(()=>t.on("connection/reset",()=>{f()}),"cost-meter: reconnect reload");const b=setInterval(()=>{const C=l.getSnapshot().state,Q=C?.config.sidebarModels,Z=C?Q?.enabled||Q?.dock?Q.refreshSeconds:60:p;!document.hidden&&Date.now()-d>=(Z||60)*1e3&&f()},1e3);t.effect(()=>()=>{c=!1,clearInterval(b)},"cost-meter: poll timer");const g=()=>{c&&t.fiber?.uid!==null&&l.set(l.getSnapshot())},h=C=>C.effect(()=>{g();const Q=C.get("locale")?.subscribe?.(g);return()=>{Q?.(),g()}},"cost-meter: DSH locale");typeof t.inject=="function"?t.inject(["locale"],h):n()&&h(t),t.effect(()=>t.on("locale/change",g),"cost-meter: locale change"),window.addEventListener?.("languagechange",g),t.effect(()=>()=>window.removeEventListener?.("languagechange",g),"cost-meter: browser locale");const x=()=>{document.visibilityState==="visible"&&f()};document.addEventListener("visibilitychange",x),t.effect(()=>()=>{document.removeEventListener("visibilitychange",x)},"cost-meter: visibility reload");const S=async(C,Q="rpcSyncFailed",Z=!1)=>{const oe=await C;if(oe===null||typeof oe!="object"||oe.ok!==!0)throw new Error(oe?.error?.message??(Z?oe?.value?.message:void 0)??i()(Q));return oe.value.state!==void 0&&l.set({status:"ready",error:null,state:oe.value.state}),oe.value};let T=null;const N={loadStatistics:()=>(T||(T=(typeof $e.async=="function"?$e.async("./client.statistics.js").then(C=>C.mount(t)):Promise.reject(new Error(i()("statisticsUpgrade")))).catch(C=>{throw T=null,C})),T),reload:f,updateConfig:async C=>{const{activeLocale:Q,...Z}=C,oe=await r("updateConfig",[Z]);return l.set({status:"ready",error:null,state:oe}),oe},fetchPrices:async()=>S(a.fetchPrices()),resetHistory:async()=>{const C=await r("resetHistory");return l.set({status:"ready",error:null,state:C}),C},importLegacyHistory:async()=>{const C=await a.importLegacyHistory();if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??i()("legacyImportFailed",{message:"RPC failed"}));return C.value.state!==void 0&&l.set({status:"ready",error:null,state:C.value.state}),C.value},getDaySessions:async C=>r("getDaySessions",[C]),getSessionCost:async C=>r("getSessionCost",[C]),getTurnCost:async(C,Q,Z)=>r("getTurnCost",[C,Q,Z]),getTopSessions:async(C,Q,Z)=>r("getTopSessions",[C,Q,Z]),refreshBalance:async()=>S(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>S(a.refreshGoQuota()),refreshGatewayQuota:async(C=null)=>S(C==null?a.refreshGatewayQuota():a.refreshGatewayQuota(C)),refreshCustomBalance:async(C=null)=>S(C==null?a.refreshCustomBalance():a.refreshCustomBalance(C)),refreshCodingPlan:async C=>S(a.refreshCodingPlan(C)),loginCodingPlan:async C=>S(a.loginCodingPlan(C)),setCredential:async(C,Q)=>S(a.setCredential(C,Q),"rpcSyncFailed",!0),clearCredential:async C=>S(a.clearCredential(C),"rpcSyncFailed",!0)};f();const m=t.get("slots");if(m===void 0)return;const v=()=>({hooks:{cost:l},api:N});for(const[C,Q]of[["header","conversation.session.header.actions"],["dock","conversation.composer.dock"]])m.inject(Q,()=>m.register({name:Q,id:"cost-meter-statistics",order:1,inject:()=>({...v(),entryPosition:C})},Ms));m.inject("conversation.chat.turnTail",()=>m.register({name:"conversation.chat.turnTail",id:"cost-meter-turn",order:10,inject:v},qn));const y=()=>({gen:0,dispose:null}),O=(C,Q,Z,oe,H=!0)=>{C.dispose!==null&&(C.dispose(),C.dispose=null),C.gen+=1;const W=C.gen;H&&m.inject(Q,()=>{if(C.gen!==W)return;const se=typeof Z=="function"?Z():m.register(Z,oe);if(C.gen!==W){se();return}return C.dispose=se,()=>{C.dispose===se&&(C.dispose=null),se()}})},P=y(),R=C=>{const Q=C==="header"?"conversation.session.header.actions":"conversation.composer.dock";O(P,Q,C==="header"?{name:Q,id:"cost-meter",order:-5,inject:v}:{name:Q,id:"cost-meter",order:5,inject:v},C==="header"?jn:Un,C!=="off")},A=y(),q=C=>{O(A,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:v},Ss,C)},k=y(),j=C=>{O(k,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:v},Zn,C)};m.inject("conversation.input.dock",()=>m.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:v},ys)),m.inject("sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:v},ks)),m.inject("sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:v},ws)),m.inject("sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:v},Ns));const Ce=y(),de=C=>{O(Ce,"sidebar.footer.action",()=>m.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:v},$n),null,C)};window.cmPeakAlertPreview=C=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(qt,{detail:{kind:C==="offpeak"?"offpeak":"peak"}}))};const Ae=y(),J=C=>{O(Ae,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:C==="en"?Oe.en.sectionLabel:Oe.zh.sectionLabel,inject:v},$s,!0)},M=y(),U=C=>{O(M,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:v},Vt,C)},D=y(),K=(C,Q)=>{O(D,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:Q==="en"?Oe.en.usageSectionLabel:Oe.zh.usageSectionLabel,inject:v},Vt,C)};let w=null,E=null,F=null,te=null,V=null,pe=null;const Je=()=>{const C=l.getSnapshot().state,Q=C?.config?.position??"dock",Z=C?.config?.sidebar!==!1&&C?.config?.hideTodayCost!==!0,oe=C?.config?.balance?.display??"both",H=(oe==="sidebar"||oe==="both")&&C?.config?.hideOfficialBalance!==!0,W=Z||H||C?.config?.codexQuotaEnabled===!0||C?.config?.sidebarModels?.enabled===!0,se=C?.config?.corner?.enabled===!0||C?.config?.sidebarModels?.dock===!0,xe=_(C?.config||{activeLocale:l.getSnapshot().locale}),Ze=C?.config?.usage?.position??"cost";Q!==w&&(R(Q),w=Q),W!==E&&(q(W),E=W),se!==F&&(j(se),F=se);const Jt=C?.config?.peakEnabled===!0;Jt!==pe&&(de(Jt),pe=Jt),xe!==te&&(J(xe),te=xe),Ze!==V?(Xe&&(U(Ze==="general"),K(Ze==="section",xe)),V=Ze):Xe&&Ze==="section"&&xe!==te&&K(!0,xe)};Je();const ft=l.subscribe(Je);return t.effect(()=>()=>{ft()},"cost-meter: slot sync"),ft}return bt.apply=eo,bt.inject=Xs,Zt.exports}});