dsh-cost-meter 1.7.37 → 1.7.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/README.zh-CN.md +7 -6
- package/docs/external-usage.md +61 -0
- package/lib/aliyun-balance.js +7 -3
- package/lib/client.js +5 -5
- package/lib/custom-balance.js +5 -3
- package/lib/external-usage.js +111 -0
- package/lib/index.js +122 -44
- package/lib/store.js +3 -0
- package/lib/typert.host.js +9 -0
- package/lib/usage-dedup.js +9 -5
- package/package.json +3 -2
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:Ht=>{var Ut={exports:{}},it=Ut.exports;Object.defineProperty(it,Symbol.toStringTag,{value:"Module"});const Le=Ht("react"),{Tooltip:$}=Ht("@deepseek-ai/dsh-client-ui-primitives"),ze=!1,Ea='.cm-root{display:block;text-align:center;max-width:var(--dsh-chat-content-width,720px);width:100%;margin:0 auto;box-sizing:border-box;padding:4px calc(var(--dsh-composer-side-clearance,0px) + 16px) 0;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-chip{display:inline-flex;align-items:center;gap:4px;max-width:180px;padding:0 8px;height:22px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-foot{display:flex;align-items:center;gap:6px;height:32px;padding:0 8px;border-radius:8px;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden}.cm-foot:hover,.cm-foot-rail:hover,.cm-corner-chip:hover,.cm-qchip:hover,.cm-tab:hover,.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}.cm-foot-rail{width:100%;justify-content:center;padding:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-num{font-variant-numeric:tabular-nums}.cm-go-rail{font-size:11px;font-weight:700;color:var(--dsw-alias-label-primary)}.cm-go-list{display:flex;flex-direction:column;gap:10px}.cm-go-row{display:flex;align-items:center;gap:8px;font-size:12px}.cm-go-label{flex:none;width:88px;color:var(--dsw-alias-label-secondary)}.cm-go-bar{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-interactive-bg-hover);overflow:hidden}.cm-go-fill{height:100%;border-radius:3px;background:var(--dsw-alias-brand-primary)}.cm-go-num{flex:none;min-width:44px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.cm-go-reset{flex:none;max-width:230px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-go-time{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-go-row.main .cm-go-label{font-weight:600;color:var(--dsw-alias-label-primary)}.cm-corner{display:flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:2px auto 0;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-corner-chip{display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:20px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums}.cm-qstrip{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:0 auto;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-qchip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:default}.cm-qchip .cm-qlabel{color:var(--dsw-alias-label-primary);font-weight:600}.cm-qchip .cm-qbar{display:block;width:44px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l1);overflow:hidden;flex:none}.cm-qchip .cm-qfill{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-state-ok-primary,#3ba272)}.cm-qchip .cm-qseg{display:inline-flex;align-items:center;gap:4px}.cm-qchip .cm-qsep{width:1px;height:12px;background:var(--dsw-alias-border-l1);flex:none}.cm-qchip .cm-qtext{color:var(--dsw-alias-label-secondary)}.cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}.cm-qchip.over .cm-qfill{background:var(--dsw-alias-state-error-primary)}.cm-qchip.action{cursor:pointer;user-select:none;outline:none}.cm-qchip.action:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-qchip.action:active{transform:translateY(.5px)}.cm-plan-provider{display:flex;flex-direction:column;gap:8px}.cm-plan-provider+.cm-plan-provider{margin-top:14px}.cm-plan-provider-name{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600}.cm-plan-updated{font-size:11px;font-weight:400;color:var(--dsw-alias-label-tertiary)}.cm-plan-tag{flex:none;margin-left:6px;padding:0 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);font-size:10px;line-height:16px;color:var(--dsw-alias-state-warn-primary)}.cm-plan-reset,.cm-plan-method{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-qguide{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:9999;max-width:440px;width:calc(100% - 32px);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 28px #0000002e;padding:14px 16px;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:8px}.cm-qguide h4{margin:0;font-size:13px;font-weight:600}.cm-qguide p{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}.cm-qguide .cm-buttons{display:flex;gap:8px;justify-content:flex-end}.cm-section{display:flex;flex-direction:column;gap:20px;padding:4px 2px 24px;font-size:13px;color:var(--dsw-alias-label-primary)}.cm-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.cm-cards-toggle{display:flex;align-items:center;gap:6px;margin:-6px 2px 0 auto;width:fit-content;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;user-select:none}.cm-cards-toggle:hover{color:var(--dsw-alias-label-primary)}.cm-cards-toggle input{margin:0;cursor:pointer}.cm-card,.cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1)}.cm-card-title{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0 0 8px}.cm-card-value{font-size:20px;line-height:28px;font-weight:600}.cm-card-sub{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-h{font-size:13px;font-weight:600;margin:0}.cm-collapse-h{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;margin:0;cursor:pointer;color:inherit;font:inherit;text-align:left}.cm-collapse-h:hover .cm-h{color:var(--dsw-alias-interactive-text-hover,var(--dsw-alias-label-primary))}.cm-caret{flex:none;width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid var(--dsw-alias-label-secondary);transform:rotate(-90deg);transition:transform .15s ease}.cm-caret.open{transform:rotate(0)}.cm-collapse-body{display:flex;flex-direction:column;gap:12px;margin-top:12px}.cm-toolbar{display:flex;justify-content:flex-end;align-items:center;gap:10px}.cm-toolbar .cm-field{flex-direction:row;align-items:center;gap:8px}.cm-toolbar .cm-field label{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-toolbar .cm-input{min-width:150px;padding:4px 10px}.cm-tabs-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;border-bottom:1px solid var(--dsh-alias-border-l1);padding-bottom:10px}.cm-tabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}.cm-tab{font:inherit;font-size:13px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:8px;padding:6px 14px;cursor:pointer;white-space:nowrap}.cm-tab.active{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary-inverted);font-weight:600}.cm-tabs-row .cm-msg{padding:2px 10px}.cm-note{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0}.cm-table{width:100%;border-collapse:collapse;font-size:12px}.cm-table th,.cm-table td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}.cm-table th{color:var(--dsw-alias-label-tertiary);font-weight:500}.cm-table td.num,.cm-table th.num{text-align:right;font-variant-numeric:tabular-nums}.cm-table tr:last-child td{border-bottom:none}.cm-table tr.cm-row-click{cursor:pointer}.cm-table tr.cm-row-click:hover td{background:var(--dsw-alias-bg-hover,rgba(127,127,127,.08))}.cm-sess-title{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-sess-id{font-size:11px;font-family:ui-monospace,Consolas,monospace;color:var(--dsw-alias-label-tertiary)}.cm-empty{font-size:12px;color:var(--dsw-alias-label-tertiary);padding:8px 0}.cm-scroll{max-height:320px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px}.cm-grid{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:12px}.cm-field{display:flex;flex-direction:column;gap:6px}.cm-field label{font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-input{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;outline:none}.cm-input:focus{border-color:var(--dsw-alias-state-business-primary)}.cm-input.narrow{max-width:120px}.cm-range-row{display:flex;align-items:center;gap:10px}.cm-range{flex:1;min-width:0;accent-color:var(--dsw-alias-state-business-primary)}.cm-range-value{flex:none;min-width:44px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-align:right}.cm-check{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}.cm-price-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:10px;background:var(--dsw-alias-bg-layer-1)}.cm-price-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-price-name{font-weight:600;font-size:13px}.cm-price-legacy{font-size:11px;color:var(--dsw-alias-label-tertiary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px}.cm-price-row{display:grid;grid-template-columns:52px 1fr 1fr 1fr;gap:8px;align-items:center}.cm-price-row span{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-price-row input{width:100%}.cm-buttons{display:flex;flex-wrap:wrap;gap:10px;align-items:center}.cm-btn{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-elevated-fill);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 14px;cursor:pointer}.cm-btn.primary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-label-primary-inverted)}.cm-btn.primary:hover{opacity:.88;background:var(--dsw-alias-state-business-primary)}.cm-btn.danger,.cm-msg.err,.cm-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}.cm-btn.small{padding:3px 10px;font-size:12px}.cm-msg{font-size:12px;line-height:18px;padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1)}.cm-msg.ok{color:var(--dsw-alias-state-success-primary)}.cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-budget{display:flex;flex-direction:column;gap:10px}.cm-peak-alert{position:fixed;z-index:9999;width:340px;max-width:calc(100vw - 32px);padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:0 14px 36px #00000038;display:flex;flex-direction:column;gap:8px;font-size:12px;animation:cm-peak-alert-in .22s cubic-bezier(.2,.8,.2,1)}.cm-peak-alert.cm-peak-alert-corner{right:20px;bottom:20px}.cm-peak-alert.cm-peak-alert-center{top:50%;left:50%;transform:translate(-50%,-50%);animation-name:cm-peak-alert-in-center}.cm-peak-alert-peak{border-top:3px solid var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak{border-top:3px solid var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:600;letter-spacing:.4px;text-transform:uppercase}.cm-peak-alert-badge:before{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 4px color-mix(in srgb,currentColor 16%,transparent)}.cm-peak-alert-peak .cm-peak-alert-badge{color:var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak .cm-peak-alert-badge{color:var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-peak-alert-body{color:var(--dsw-alias-label-secondary);line-height:1.55}.cm-peak-alert-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}.cm-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}@keyframes cm-peak-alert-in{0%{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes cm-peak-alert-in-center{0%{opacity:0;transform:translate(-50%,calc(-50% + 10px))}to{opacity:1;transform:translate(-50%,-50%)}}.cm-budget-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-quota-name{flex:1;min-width:0}.cm-budget-bar{height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-budget-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary);transition:width .3s ease}.cm-ug{display:flex;flex-direction:column;gap:12px}.cm-ug-total{font-size:13px;color:var(--dsw-alias-label-primary)}.cm-ug-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,auto);gap:3px;width:100%}.cm-ug-cell{width:100%;aspect-ratio:1/1;border-radius:3px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);border:1px solid var(--dsw-alias-border-l1)}.cm-ug-cell.l1,.cm-ug-cell.l2,.cm-ug-cell.l3,.cm-ug-cell.l4{border-color:transparent}.cm-ug-cell.l1{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary)}.cm-ug-cell.today{outline:1px solid var(--dsw-alias-label-secondary);outline-offset:1px}.cm-ug-months{display:grid;grid-auto-flow:column;gap:3px;width:100%;font-size:10px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-ug-monthc{white-space:nowrap}.cm-budget-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-budget-line.over{color:var(--dsw-alias-state-error-primary)}.cm-peak-strip{display:flex;align-items:center;gap:6px;margin-top:4px;min-width:0}.cm-peak-track{position:relative;display:flex;flex:1;height:6px;min-width:0;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-segment{height:100%;flex:1}.cm-peak-high{background:#ff9800}.cm-peak-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-marker{position:absolute;top:0;left:50%;width:2px;height:100%;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2}.cm-peak-chip{font-size:11px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-classic{position:relative;display:flex;flex-direction:column;gap:5px;margin-top:6px;min-width:0}.cm-peak-classic .cm-peak-track{flex:none;height:8px}.cm-peak-classic-marker{position:absolute;top:0;left:50%;width:4px;height:12px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2;border-radius:2px}.cm-peak-classic-marker:after{content:"";position:absolute;top:-7px;left:50%;transform:translate(-50%);border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #ff9800}.cm-peak-classic.off .cm-peak-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic.off .cm-peak-classic-marker:after{border-top-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic-chip{align-self:flex-start;font-size:11px;font-weight:600;line-height:1.4;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 8px;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-strip.peak .cm-peak-chip,.cm-peak-classic.peak .cm-peak-classic-chip,.cm-peak-rail.peak .cm-peak-rail-label,.cm-peak-rail-classic.peak .cm-peak-rail-classic-label{color:#ff9800}.cm-peak-strip.off .cm-peak-chip,.cm-peak-classic.off .cm-peak-classic-chip,.cm-peak-rail.off .cm-peak-rail-label,.cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}.cm-peak-strip.weekend .cm-peak-chip,.cm-peak-classic.weekend .cm-peak-classic-chip,.cm-peak-rail.weekend .cm-peak-rail-label,.cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker{border-color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker:after{border-top-color:#34a853}.cm-peak-rail{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-track{position:relative;display:flex;flex-direction:column;width:6px;height:56px;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-segment{width:100%;flex:1}.cm-peak-rail-high{background:#ff9800}.cm-peak-rail-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-rail-marker{position:absolute;left:0;top:50%;width:100%;height:2px;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translateY(-50%);transition:top .4s ease;z-index:2}.cm-peak-rail-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-rail-classic{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-classic-track{position:relative;display:flex;flex-direction:column;width:14px;height:56px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-classic-segment{position:relative;width:100%;flex:1;overflow:hidden}.cm-peak-rail-classic-segment.peak{background:#ff9800;border-radius:999px 999px 0 0}.cm-peak-rail-classic-segment.off{background:var(--dsw-alias-state-business-primary);border-radius:0 0 999px 999px}.cm-peak-rail-classic-marker{position:absolute;left:50%;top:50%;width:12px;height:4px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%,-50%);transition:top .4s ease;z-index:2;border-radius:2px}.cm-peak-rail-classic.off .cm-peak-rail-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-rail-classic-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}.cm-grid-group{grid-column:1 / -1;margin-top:8px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:4px}.cm-grid-group:first-child{margin-top:0}.cm-peak-preview{margin-top:8px}.cm-toggle-btn{background:none;border:none;padding:0;font-size:12px;font-weight:600;color:var(--dsw-alias-state-business-primary);cursor:pointer}.cm-toggle-btn:hover{text-decoration:underline}.cm-collapsed-note{margin-top:4px}.cm-catalog-vendor{margin-top:10px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:2px;display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-vendor-toggle{cursor:pointer;user-select:none}.cm-vendor-toggle:hover{color:var(--dsw-alias-label-secondary)}.cm-vendor-display{display:inline-flex;align-items:center;gap:4px;font-weight:400;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}.cm-catalog-family{margin:6px 0 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}.cm-catalog-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px}.cm-catalog-mounted{display:flex;flex-direction:column;gap:4px;padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1)}.cm-catalog-id{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-catalog-price{color:var(--dsw-alias-label-secondary);white-space:nowrap;font-size:11px}.cm-catalog-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);white-space:nowrap}.cm-mstats-tabs{display:flex;gap:8px;margin-bottom:8px}.cm-mstats-tab{background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}.cm-mstats-tab.active{background:var(--dsw-alias-state-business-primary);border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-bg-base);font-weight:600}.cm-mstats-h{margin:10px 0 4px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}.cm-mstats-row{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:8px;align-items:center;font-size:11px;line-height:1.7}.cm-mstats-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-barbg{position:relative;height:10px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden;display:flex}.cm-mstats-bar{height:100%;min-width:0;border-radius:999px}.cm-mstats-bar.cost{background:#ff9800}.cm-mstats-bar.hit{background:#34a853}.cm-mstats-bar.value{background:#a142f4}.cm-mstats-seg{height:100%;min-width:0}.cm-mstats-seg.in{background:var(--dsw-alias-state-business-primary)}.cm-mstats-seg.cache{background:#ff9800}.cm-mstats-seg.out{background:#34a853}.cm-mstats-val{white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-legend{display:flex;gap:12px;font-size:10px;color:var(--dsw-alias-label-tertiary);margin:2px 0 4px}.cm-mstats-dot{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.cm-mstats-note{margin-top:10px;font-size:10px;line-height:1.6;color:var(--dsw-alias-label-tertiary)}.cm-match-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:12px;flex-wrap:wrap}.cm-match-row .cm-input{flex:1;min-width:160px}.cm-budget-controls{display:grid;grid-template-columns:repeat(2,minmax(180px,1fr));gap:12px}.cm-bbox{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:6px;min-width:148px;box-sizing:border-box}.cm-bbox.rail{padding:6px;min-width:0;width:40px;align-items:center;justify-content:center;border-radius:10px}.cm-bbox.warn{border-color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over{border-color:var(--dsw-alias-state-error-primary)}.cm-bbox-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-bbox-label,.cm-bbox-pct{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}.cm-bbox-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-bbox-bar.segments{display:flex;height:8px}.cm-bbox-bar.segments .cm-bbox-fill{flex:none;border-radius:0;height:100%}.cm-bbox-bar.segments .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments .cm-bbox-seg-today{flex:none;height:100%;background:#ff9800}.cm-bbox-bar.segments .cm-bbox-seg-spent{flex:none;height:100%;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-fill:first-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments.rev .cm-bbox-fill,.cm-bbox-bar.segments.rev .cm-bbox-fill:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}.cm-dir-row{display:flex;align-items:center;gap:8px;margin-top:6px}.cm-dir-label{flex:1 1 40%;font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-dir-row .cm-input{flex:1 1 60%;width:auto}.cm-bbox-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary)}.cm-balance-name{display:inline-flex;align-items:center;gap:4px;min-width:0}.cm-model-costs{font-size:12px}.cm-model-costs .cm-bal-label{white-space:nowrap}.cm-model-top{gap:4px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.cm-model-costs .cm-collapse-h{min-width:0;width:100%;white-space:nowrap}.cm-model-costs .cm-bbox-bar{margin-top:3px}.cm-bal-label{min-width:0;overflow:hidden;text-overflow:ellipsis}.cm-bal-amt{margin-left:auto;text-align:right;flex-shrink:0}.cm-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}.cm-bal-link{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:2px;border-radius:4px;font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary);text-decoration:none;outline:none}.cm-bal-link:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-interactive-bg-hover)}.cm-bal-link:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-bbox.warn .cm-bbox-fill,.cm-bbox .cm-bbox-section.warn .cm-bbox-fill,.cm-bbox .cm-mm-row.warn .cm-bbox-fill,.cm-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-fill,.cm-bbox-section.over .cm-bbox-fill,.cm-mm-row.over .cm-bbox-fill,.cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}.cm-bbox-line{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-bbox-rail{font-size:11px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct,.cm-bbox.warn .cm-bbox-rail,.cm-bbox .cm-bbox-section.warn .cm-bbox-pct,.cm-bbox .cm-mm-row.warn .cm-bbox-pct,.cm-mm-row.warn .cm-bbox-label,.cm-corner-chip.warn,.cm-qchip.warn,.cm-simple-summary.warn{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct,.cm-bbox.over .cm-bbox-rail,.cm-bbox-section.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-label,.cm-corner-chip.over,.cm-qchip.over,.cm-simple-summary.over{color:var(--dsw-alias-state-error-primary)}.cm-bbox-pair{display:flex;flex-direction:column;gap:0;padding:2px 10px}.cm-bbox-pair .cm-bbox-section{display:flex;flex-direction:column;gap:4px;padding:4px 0}.cm-bbox-pair .cm-bbox-bar{height:4px}.cm-bbox-divider{height:1px;background:var(--dsw-alias-border-l1);margin:0}.cm-bbox.clickable,.cm-foot.clickable{cursor:pointer}.cm-bbox.clickable:hover{border-color:var(--dsw-alias-state-business-primary)}.cm-bbox.clickable:focus-visible,.cm-foot.clickable:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}@keyframes cm-click-refresh-pulse{0%,to{opacity:.55}50%{opacity:1}}.cm-bbox.clickable.busy,.cm-foot.clickable.busy{animation:cm-click-refresh-pulse 1.1s ease-in-out infinite}.cm-mm{padding:8px 10px;gap:4px}.cm-mm-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-mm-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);grid-column:1/-1}.cm-gw-switcher{cursor:pointer;user-select:none;font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}.cm-gw-switcher:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.cm-gw-sub{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-mm-row{display:flex;align-items:center;gap:8px;padding:2px 0}.cm-mm-row .cm-bbox-label{flex:none;width:auto;min-width:22px;max-width:115px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;word-break:keep-all}.cm-mm-row .cm-bbox-bar{flex:1;min-width:40px;height:6px}.cm-mm-row .cm-bbox-pct{flex:none;min-width:2.4em;text-align:right;font-variant-numeric:tabular-nums}.cm-mm-row.wide .cm-bbox-label{width:auto;max-width:64px;flex:0 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-mm-row.wide .cm-mm-text{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-bal-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-bal-line.warn{color:var(--dsw-alias-state-warning-primary,#b45309)}.cm-footer-stack{display:flex;flex-direction:column;gap:6px;width:100%;align-items:stretch;box-sizing:border-box}.cm-footer-stack.rail{align-items:center}.cm-footer-stack .cm-bbox{width:100%;min-width:0}.cm-footer-stack .cm-foot{width:100%;box-sizing:border-box}.cm-footer-stack.compact .cm-bbox{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:2px;align-items:center}.cm-footer-stack.compact .cm-bbox>*{grid-column:1/-1}.cm-footer-stack.compact .cm-bbox>.cm-mm-row{grid-column:auto}.cm-footer-stack.compact .cm-mm-row{min-width:0;gap:4px;flex-wrap:nowrap}.cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:0 1 auto;min-width:0;max-width:45%;width:auto}.cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0;flex:1 1 0}.cm-footer-stack.simple{gap:0;max-height:38vh;max-height:min(38dvh,320px);overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.cm-footer-stack.simple>*{flex-shrink:0}.cm-footer-stack.simple:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}.cm-footer-stack.simple .cm-bbox{border:0;border-radius:0;padding:4px 8px;gap:2px;background:transparent;box-shadow:inset 0 -1px var(--dsw-alias-border-l1)}.cm-footer-stack.simple .cm-mm-title{font-size:11px;line-height:16px;margin:0}.cm-footer-stack.simple .cm-mm-row{gap:6px;min-height:16px;line-height:16px;margin:0;padding:0}.cm-footer-stack.simple .cm-mm-text{font-size:11px}.cm-footer-stack.simple>.cm-peak-strip,.cm-footer-stack.simple>.cm-peak-classic{margin:0;padding:4px 8px}.cm-simple-summary>span{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-footer-stack.simple .cm-bbox-pct{font-size:12px;line-height:18px}.cm-footer-stack.simple .cm-bbox-bar{height:4px}.cm-footer-stack.simple .cm-bbox-line{display:none}.cm-footer-stack.simple .cm-foot{height:26px;padding:0 8px}.cm-footer-stack.simple .cm-peak-classic{margin-top:2px;gap:2px}.cm-footer-stack.simple .cm-peak-classic-chip{padding:0 4px;border:0;background:transparent}.cm-simple-summary{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 8px;font-size:12px;font-weight:600;border-bottom:1px solid var(--dsw-alias-border-l1)}.cm-footer-stack.simple.rail{border:0;background:transparent}.cm-footer-stack.simple.rail .cm-bbox{padding:4px 2px}.cm-footer-stack.simple .cm-peak-rail-track,.cm-footer-stack.simple .cm-peak-rail-classic-track{height:28px}@media(max-width:640px){.cm-cards,.cm-grid,.cm-budget-controls{grid-template-columns:1fr}}',jt="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(jt)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=jt,t.textContent=Ea,document.head.appendChild(t)}const Me={zh:{sessionCostTitle:"本会话费用(按每次调用实际时刻精确计费)",sessionDetailTokens:"输入 {input} · 缓存 {cache} · 输出 {output}",sessionDetailCache:"缓存:读 {read} · 写 {write}(写入按命中价计费)",cost:"费用 {amount}",sessionLine:"本会话 {amount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",quotaUnlimited:"无限制",pricingCnyHint:"当前人民币金额来自美元价格 × 汇率 {rate}。对照官方人民币账单,请选择 CNY,再同步价格;同步会更新历史费用。",balanceQueryFailed:"余额查询失败:{message}",unknownError:"未知错误",balance:"余额",queryFailed:"查询失败",balanceTitle:"DeepSeek 开放平台账户余额",reconcileLabel:"官方余额变动与本地账本交叉对账(偏差超阈时提示)",totalBalance:"总余额 {amount}",grantedToppedUp:"赠送 {granted} · 充值 {toppedUp}",updatedAt:"更新时间 {time}",budgetOf:"预算({period})",usedOf:"已用 {used} / {amount}",todayShare:"今日 {amount} · 占预算 {pct}",monthTotal:"本月 {month} · 累计 {total}",budget:"预算",todayCostTitle:"今日费用(按官方价格精确计费)",callsTokens:"调用 {calls} 次 · 输入 {input} · 缓存 {cache} · 输出 {output}",monthCost:"本月 {amount}",totalCost:"累计 {amount}",today:"今日",periodDay:"今日",periodMonth:"本月",periodAll:"累计",periodCustomRange:"自定义区间",noHistory:"暂无历史记录。开始对话后,费用将按天汇总在这里。",colDate:"日期",colCalls:"调用",colInTok:"输入 tok",colCacheTok:"缓存 tok",colOutTok:"输出 tok",colCost:"费用",noSessionsToday:"今日暂无会话记录。",colSession:"会话",enableBudget:"启用预算",budgetAmountLabel:"预算额度(按显示币种)",budgetPeriodLabel:"预算周期",startDate:"开始日期",endDate:"结束日期(留空 = 今日)",rangeText:"统计区间:{range}",budgetDisabledNote:"未启用预算。启用后此处显示预算额度、已用金额与已用百分比(按当前币种换算);周期可选今日/本月/累计或自定义日期区间。",budgetStatus:"{period}预算 {amount} · 已用 {used} · {pct}%",overLimit:"(已超出)",nearLimit:"(接近上限)",legacyModel:"旧模型",defaultFallback:"默认回退",remove:"移除",tierBase:"基础",tierOffPeak:"谷时",tierPeak:"峰时",balanceRefreshFailed:"余额刷新失败:{message}",balanceLine:"总余额 {total} · 赠送 {granted} · 充值 {toppedUp} · 更新于 {time}",balanceQueryFailedHint:"余额查询失败:{message}(使用 设置→模型 中配置的 API Key)",balanceNotQueried:"未查询余额",accountBalance:"官方账户余额",refreshing:"刷新中…",refreshBalance:"刷新余额",customBalanceTitle:"自定义 Provider 余额",customBalanceAdd:"添加配置",aliyunBalanceAdd:"添加千问 / 阿里云余额",aliyunBalanceNote:"查询阿里云中国站资金账户可用金,按接口币种显示。使用 RAM AccessKey(需 bss:DescribeBillingAccount 权限),不是千问模型 API Key;共享同一组阿里云凭据。前两项必填,Security Token 仅 STS 临时凭据需要。密钥只存入凭据库。",customBalanceConfigNote:"extract 支持点路径、数值和 add/subtract/divide 运算;NewApi quota 除以 500000 得到美元。",customBalanceLabelZh:"中文名称",customBalanceLabelEn:"英文名称",customBalanceUrl:"请求 URL",customBalanceMethod:"请求方法",customBalanceHeaders:"请求头 (JSON)",customBalanceBody:"请求体 (JSON)",customBalanceBodyNote:"留空不发送;JSON 原文保存并发送。默认 Content-Type 为 application/json,可在请求头覆盖。",customBalanceExtract:"解析规则 (JSON)",customBalanceDisplayLabel:"自定义余额显示位置",customBalanceRefreshInterval:"刷新间隔 (分钟)",customBalanceUnitLabel:"余额原币种",customBalanceConvert:"按显示币种折算(USD 余额)",customBalanceConvertNote:"使用显示汇率与精度;余额币种保持端点原币种。其他币种及积分不折算。",balanceBarRemaining:"余额 {amount}",balanceBarToday:"当日已用 {amount}",balanceBarSpent:"已用 {amount}",balanceShowProgressBar:"余额进度条 (蓝=余额,橙=当日,灰=已用)",barDirectionsTitle:"进度条方向",barDirectionsHint:"各组进度条可独立选择填充方向:「剩余方向」满条起步、随消耗递减;「已用方向」空条起步、随消耗填满。",barDirection_balance:"余额条(官方/自定义)",barDirection_budget:"预算条",barDirection_go:"Go 额度条",barDirection_plan:"Plan / Codex 额度条",barDirectionRemaining:"剩余方向(满 → 空)",barDirectionUsed:"已用方向(空 → 满)",balanceBudgetCapLabel:"额度上限 (可选)",balanceBudgetCapHint:"留空则优先使用 API 返回的 max_budget;仍无则显示整条浅蓝",customBalanceInvalidJson:"JSON 格式无效",customBalanceHeadersVarNote:"值支持 {{VAR_NAME}} 占位符,从 DSH 凭据库/环境变量解析,不落盘。变量名参考 <ROUTE>_API_KEY:<ROUTE> 为模型页 Provider ID 大写、非字母数字换下划线,如 openai→OPENAI_API_KEY、abc23-d→ABC23_D_API_KEY;同名即共用同一把密钥。",customBalanceAllowedHosts:"凭据白名单 (逗号分隔)",customBalanceAllowedHostsHint:"请求头带密钥时仅放行列表内主机,留空则放行并警告,防导入他人配置外带密钥。",customBalanceCredentialsTitle:"凭据输入",customBalanceCredentialsHint:"为上方 {{VAR}} 占位符存入密钥(write-only,只写凭据库,不回显):",customBalanceNoPlaceholders:'请求头还没有 {{VAR}} 占位符:填入如 "Authorization": "Bearer {{MY_API_KEY}}" 后这里会出现凭据输入框。',enable:"启用",customBalanceLine:"剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}",customBalanceRemaining:"剩余 {amount}",refreshCustomBalance:"刷新自定义余额",goQuotaTitle:"OpenCode Go 订阅额度",goQuotaRowLabel:"Go",goWindowRolling:"滚动 5 小时",goWindowWeekly:"本周",goWindowMonthly:"本月",goResetAt:"重置:{time}",resetReached:"已到重置时间",resetDays:"剩余 {d}天{h}小时",resetHours:"剩余 {h}小时{m}分",resetMinutes:"剩余 {m}分钟",quotaUsed:"已用 {pct}%",quotaRemaining:"剩余 {pct}%",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"更新于 {time}",goQuotaDisplayLabel:"Go 额度显示位置",goQuotaRefreshIntervalLabel:"Go 额度刷新间隔(分钟)",goQuotaRefreshMinutesUnit:"分钟",goQuotaKeyLabel:"OpenCode Go API Key(可选,留空自动发现)",goMainLabel:"Go 额度主档位",goDetailLabel:"Go 图框详细信息",credentialConfiguredOf:"已配置(来源:{source})",credentialNotConfigured:"未配置",credentialSave:"保存",credentialClear:"清除",credentialSaving:"保存中…",credentialInputHint:"密钥只写入 DSH 凭据库,不保存在账本里,也不会回显。",secretMigrationPending:"以下密钥仍以明文留在本地账本,未能自动迁入凭据库。请导出对应环境变量后重启:",budgetDetailLabel:"预算图框详细信息",refreshGoQuota:"刷新额度",goQuotaNotQueried:"未查询额度",codingPlanAnthropic:"Anthropic(Claude Pro/Max)",codingPlanZai:"Z.ai / 智谱 GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"查询域名(HTTPS)",minimaxOriginNote:"留空自动选择官方站点。填写后 Key 仅发往该域名;使用可信地址,不含路径。",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"打开 DeepSeek 充值页(platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) 周额度",codexQuotaEnabled:"显示 Codex 额度(需安装并登录 dsh-openai-codex)",includeSubagentCost:"本会话费用包含子代理",gatewayQuotaEmpty:"暂无额度数据",codingPlanDisplayLabel:"显示位置",codingPlanDisplayNote:"选「主页面侧边栏 / 两者」后,该厂商额度以图框卡片常驻侧边栏(与 Go 额度/余额同款,收起窄栏显示百分比)。",codingPlanKeyLabel:"API Key(可选,留空自动发现)",codingPlanRefreshIntervalLabel:"刷新间隔(分钟)",refreshCodingPlan:"刷新",codingPlanNotQueried:"未查询额度",gatewayQuotaTitle:"CLIProxyAPI 网关额度",gatewaySourceAdd:"添加来源",gatewaySourceLabel:"来源名称",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"显示位置",gatewaySourceAllowlist:"允许的 Host",gatewaySourceCredential:"Management Key(只写)",gatewaySourceStatus:"状态",gatewaySourceUnsupported:"不支持的 Provider",gatewaySourceUnknown:"未知",gatewaySourceNoAccounts:"未发现账号",gatewaySourceFetchedAt:"抓取于 {time}",gatewaySwitchAccount:"切换账号 (当前: {account})",gatewayOnlyGemini:"只显示 Gemini 额度",refresh:"刷新",quotaEnableFirst:"先勾选启用这一项",quotaRefreshReady:"启用并保存显示位置后可刷新",quotaRemove:"删除",quotaSectionNote:"勾选启用后会排到最上面;点名称可展开该项自己的配置。自定义余额最多 8 条,网关来源最多 4 条。",codingPlanDisabledNote:"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。",goQuotaDisabledNote:"未启用额度。开启后将读取 OpenCode Go 订阅额度(滚动 5 小时 / 本周 / 本月)并显示在侧边栏图框、设置页与右下角;没有 Go 订阅时会在这里提示原因。",cornerLabel:"右下角显示(dock)",cornerEnabledLabel:"在右下角显示 OpenCode Go 额度 / 预算",cornerGoRolling:"滚动 5 小时额度",cornerGoWeekly:"本周额度",cornerGoMonthly:"本月额度",cornerBudget:"预算已用%",goShortRolling:"5h",goShortWeekly:"周",goShortMonthly:"月",goShortDaily:"日",budgetShort:"预算",ledgerReadFailed:"账本读取失败:{message}",readingLedger:"正在读取账本…",ledgerUnavailable:"账本不可用",syncFailed:"同步失败:{message}",historyCleared:"历史记录已清除。",clearFailed:"清除失败:{message}",peakOff:"峰谷计价已关闭,按基础价格计费",peakNotEffective:"尚未生效(生效时间:{time}),当前按基础价格计费",peakActive:"当前处于峰时段,按峰时价计费",peakNotice:"当前为 DeepSeek 峰时高价时段,按峰时价计费",offPeakActive:"当前处于谷时段,按谷时价计费",weekendAllOffPeak:"周末时段——全谷价(周六及周日全天按谷时价计费)",weekendChip:"周末时段——全谷价",weekendShort:"周末全谷",holidayAllOffPeak:"法定假日——全天谷价",holidayChip:"法定假日——全谷价",holidayShort:"假日",peakHolidaysLabel:"法定假日(北京日期,逗号分隔)",weekendRuleNote:"自 2026-08-23 北京时间 00:00 起,周末和中国公众假期全天谷价;调休上班的周末仍按谷价。",peakShort:"峰时",offPeakShort:"平价",peakStyleLabel:"峰谷时段条样式",peakStyleCompact:"简洁(单行紧凑)",peakStyleClassic:"经典(分段与胶囊芯片)",peakAlertLabel:"峰/谷切换前弹窗提醒",peakAlertAheadLabel:"提前提醒(分钟,1-30)",peakAlertTargetLabel:"提醒类型",peakAlertTargetPeak:"进入峰时",peakAlertTargetOffPeak:"进入谷时",peakAlertTargetBoth:"峰和谷",peakAlertTitlePeak:"即将进入峰时",peakAlertTitleOffPeak:"即将进入谷时",peakAlertBody:"约 {time} 后计费档位切换为{phase}价,请注意本时段调用成本。",peakAlertPhasePeak:"峰时",peakAlertPhaseOffPeak:"谷时",peakAlertBtn:"知道了",peakAlertBadgePeak:"峰价提醒",peakAlertBadgeOffPeak:"谷价提醒",peakAlertPositionLabel:"弹窗位置",peakAlertPositionCorner:"右下角",peakAlertPositionCenter:"屏幕中心",peakAlertWebNotifyLabel:"同步发送系统通知",peakAlertWebNotifyHint:"开关后请在浏览器地址栏允许通知权限,才能在页面最小化/切走时收到提醒。",peakAlertPreviewLabel:"预览弹窗",peakAlertPreviewPeak:"预览 进入峰",peakAlertPreviewOffPeak:"预览 进入谷",peakAlertPreviewTag:"(预览)",peakPanelTitle:"峰谷计价与提示",peakNoticeHiddenHint:"提示已隐藏:需启用峰谷计价并开启「峰时高价时段显著提示」。",groupGeneral:"常规",groupMoney:"金额与币种",groupSidebar:"侧边栏显示",sidebarSimple:"简化侧栏显示",sidebarSimpleNote:"压缩卡片和明细,保留金额、额度与悬停详情;面板最多占屏幕高度的 38%,超出后可滚动。关闭后恢复原有布局。",sidebarSimpleTitle:"试试更轻巧的侧栏",sidebarSimpleBody:"简化显示可以为会话列表留出更多空间。要现在开启吗?之后可在「设置 → 费用 → 显示」中切换。",sidebarSimpleOn:"开启简化显示",sidebarSimpleOff:"保留当前显示",sidebarSimpleError:"设置未能保存。可重试,或关闭提示后在设置中调整。",closeGuide:"关闭提示",todayBudget:"今日 / {period}预算",sidebarStyleLabel:"侧边栏进度条样式",sidebarStyleStandard:"标准",sidebarStyleCompact:"紧凑(两列)",restorePriceMatches:"恢复已移除的模型 ({count})",removePriceMatchHint:"移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按自动匹配规则计价。",groupCorner:"右下角角标",groupDetail:"图框详细信息",catalogTitle:"拓展价格表",catalogNote:"内置各厂商、按模型家族分类的参考价格目录(只读)。挂载 = 把条目复制进上方可编辑价格表并参与计费;DeepSeek 模型可取消挂载(回退默认价,目录中仍可重新挂载)。",catalogOpen:"展开拓展价格表",catalogCollapse:"收起拓展价格表",mountBtn:"挂载",unmountBtn:"取消挂载",mountedTag:"已挂载",catalogUnpriced:"未核价",catalogDeepseekNote:"DeepSeek 模型支持峰谷两档;取消挂载后按默认价计费且不再被自动匹配命中。",modelStatsTitle:"按模型统计(token 与费用)",modelsTitle:"侧栏模型花费",modelsCount:"{n} 模型",modelsOther:"其它",models_enabled:"显示模型花费卡片",models_defaultOpen:"默认展开",models_remember:"记住展开状态",models_tokens:"显示 Token",models_shares:"显示费用占比条",models_dock:"右下角显示 Top-1 模型",models_period:"默认周期",models_summary:"收起摘要",models_position:"卡片位置",models_topN:"模型行数(1–10)",models_refreshSeconds:"刷新间隔(10–60 秒)",modelsTotal:"周期总额与模型数",modelsTop:"Top-1 模型与金额",modelsFirst:"顶部",modelsAfter:"余额之后",modelsLast:"底部",modelStatsToday:"今日",modelStatsHistory:"近 90 天",modelStatsCostH:"费用排行",modelStatsTokensH:"Token 消耗",modelStatsHitH:"缓存命中率",modelStatsHitUnreported:"未上报?",modelStatsHitUnreportedTip:"长上下文调用始终无缓存命中:代理可能剥掉缓存字段或破坏缓存。命中率未知,按全未命中价估算金额上界;直连官方 API 可核对。",modelStatsValueH:"性价比 · 每美元 token 数",modelStatsInput:"输入",modelStatsCache:"缓存",modelStatsOutput:"输出",modelStatsEmpty:"该时段暂无用量数据。",modelStatsBlended:"综合单价 {price}/M",modelStatsNote:"口径:命中率 = 缓存读 ÷ (缓存读 + 非缓存输入);「未上报?」= 用量疑似无缓存字段(常见于中转/代理),金额按全未命中计(上界);单价 = 费用 ÷ 总 token × 1M(USD/M);性价比 = 总 token ÷ 费用(越高越好)。费用按调用时美元价计。",modelStatsLegacy:"未分模型(早期数据 · 按当时记录计费)",sessionLineSplit:"本会话 {amount}(API)· Plan 等值 {planAmount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",costChipPlan:"费用 {amount}(+Plan)",sessionDetailPlan:"Plan 订阅额度消耗(等值){amount}",planStatsTitle:"Token Plan 用量统计(每 1% 与满窗估算)",planStatsEmpty:"暂无已启用的 Coding Plan 额度数据;在「额度」标签启用并成功刷新后,这里会显示各窗口的每 1% 额度与满窗用量估算。",planStatsWindow:"窗口",planStatsPercent:"已用 %",planStatsLocal:"本周期实际(本地账本)",planStatsPer1:"每 1% 额度 ≈",planStatsFull:"满窗 100% ≈",planStatsResets:"重置 {time}",planStatsMethodSample:"采样差分",planStatsMethodLive:"当前用量折算",planStatsMethodNone:"样本不足",planStatsMethodSampleAt:"{method}(基准 {time})",planStatsConfidenceLow:"读数精度受限",planStatsCurveTitle:"Plan 用量曲线(按采样区间聚合)",planStatsDaily:"每日",planStatsWeekly:"每周",planStatsMonthly:"每月",planStatsCurveEmpty:"采样区间尚不足(至少两次成功刷新且百分比有变化),曲线会在持续使用后逐步成形。",planStatsBarTip:"{date}:满窗估计 ≈ {full}(每 1% ≈ {per1})· 实际 {tokens} / {cost} · {intervals} 个采样区间",planStatsNote:"口径:「金额」为目录 API 价等值(订阅耗套餐额度,预算只计 API);估算只含 dsh 内调用,服务端「已用%」为全账号口径;每 1%/满窗按可信采样段差分(短段波动标「精度受限」);5h 滚动,周/月按本地日历。",billingClassLabel:"计费方式",billingClassPlan:"Plan 订阅",catalogDisplayLabel:"在费用设置直接显示",catalogDisplayHint:"只决定该模型价格卡是否在费用设置「价格表」区直接显示,不影响挂载状态与计费;不直接显示时已挂载模型在拓展价格表内展开厂商后可编辑。",priceTableDisplayHint:"各模型是否在「价格表」区直接显示,可在下方拓展价格表中逐模型用「在费用设置直接显示」开关切换;DeepSeek 模型默认直接显示,第三方模型挂载后默认收入拓展表。",catalogCustomModels:"手动新增模型",priceMatchLabel:"未知模型名自动匹配",priceMatchAuto:"自动(去后缀 / 前缀 / 家族相似)",priceMatchExact:"仅精确匹配",priceMatchNote:"自动匹配顺序:精确 → 手动指定 → 去日期/版本后缀 → 前缀 → 家族相似;未命中时 DeepSeek 回退默认价,其他 provider 不计价。",unmatchedTitle:"最近出现但未命中价格的模型",unmatchedHint:"按当前匹配模式未命中价格条目(含跨厂商兜底默认价);指定条目即写入手动匹配覆盖,选「默认价」回退 DeepSeek 默认价。本地推理(lmstudio / ollama / vLLM 等)默认零消耗,计费需在此指定条目。",overrideTargetDefault:"DeepSeek 默认价",overrideRemove:"移除",overrideTargetLocal:"本地模型(零消耗)",matchedTitle:"本月已命中价格的模型",matchedHint:"以下模型已自动命中价格条目。在行内选择目标即可改挂其它条目,或选择「本地模型(零消耗)」把该模型标记为本地来源——token 照常统计、费用按 0 计,历史金额即时归零。写入后该行转入上方手动指定区。",matchedKeepAuto:"保持自动命中",overrideNone:"暂无手动匹配覆盖。",mountedSuffix:"已挂载(参与计费)",flatInput:"输入",flatCached:"缓存",flatOutput:"输出",deepseekMountedHeader:"DeepSeek 价格表(已挂载)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow 硅基流动",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet 超算互联网 Token Plan",codingPlanVolcengine:"火山方舟 Volcano Ark Coding Plan",codingPlanQwen:"千问 Qwen Token Plan",codingPlanMimo:"小米 MiMo Token Plan",mimoWindowPlan:"套餐积分",mimoWindowCompensation:"补偿积分",codingPlanWindowBalance:"余额",qwenSource:"额度来源",qwenSourceLocal:"本地估算",qwenSourceCli:"官方 CLI",qwenSourceBailian:"百炼 CLI",qwenCliNote:"CLI 模式需在 DSH 主机安装 @qianwenai/qianwen-cli,并以同一系统账号运行 qianwen auth login。",qwenBailianNote:"百炼 CLI:在 DSH 主机安装 bailian-cli 并以同一系统账号运行 bl auth login --console。",qwenPlanCreditsLabel:"月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)",qwenPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",qwenRatesLabel:"Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)",qwenRatesModelPlaceholder:"模型名,如 qwen3.8-max-preview",qwenRatePlaceholder:"费率",qwenRate_input:"输入",qwenRate_cachedInput:"缓存读",qwenRate_output:"输出",qwenRateDraftNote:"待填齐三项正数后自动保存;全部清空恢复内置表。",qwenRatesAdd:"添加",qwenLocalNote:"本地账本估算,Credits 以控制台为准。仅统计 qwen、qwen-tokenplan、qianwen-tokenplan、qwen-token-plan、qianwen-token-plan 订阅渠道(含 llm- 前缀);显式 API 分类与 qianwen 按量渠道不计。表外模型需手动指定抵扣率。",scnetPlanCreditsLabel:"本地估算月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)",scnetPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",scnetLocalNote:"可接入外部控制台快照(以采集时间为准,最长保留 24 小时)。没有有效快照时,按官方 Credits 抵扣表由本地账本估算;本地估算不覆盖其他工具的调用和未收录模型,实际用量以控制台为准。",volcengineAccessKeyIdLabel:"火山引擎 AccessKey ID",volcengineSecretAccessKeyLabel:"火山引擎 SecretAccessKey",volcengineNote:"火山方舟需 AK/SK HMAC 签名(非 ARK_API_KEY):IAM 子用户授予 ArkReadOnlyAccess + BillingCenterReadOnlyAccess 后填 AccessKeyID/SecretAccessKey,或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY 自动发现;凭据仅发往 open.volcengineapi.com。",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}小时",countdownHourMinute:"{h}小时{m}分",countdownMinute:"{m}分钟",nextOffPeakIn:"{time}后进入平价",nextPeakIn:"{time}后进入高峰",peakSummary:"峰时段(UTC):{windows};生效时间:{time}。{status}",noPeakWindows:"未配置峰谷时段。{status}",unknown:"未知",cardToday:"今日费用",cardMonth:"本月费用",cardTotal:"累计费用",cardTotalSub:"自账本建立以来 · 调用 {calls} 次",cardsFootnote:"口径:金额为最近落盘快照(2 秒防抖,关闭即落盘),与官方实时账单的分钟级时差属预期;tokens 列为输入+输出+缓存+推理合计,推理 tokens 不计费(官方账单并入「输出」列),对账以金额为准。",timezoneHint:"时区提示:「今日/本月」按宿主机时区 {host} 取日界,与当前浏览器({browser})不同时,本地午夜后的调用会记到前一日(并非漏计;官方余额对账也会提示偏差)。可在宿主机以本地时区运行 dsh 对齐。",todaySessions:"今日会话",historyExpandHint:"点击日期行可展开当日会话明细",historySessionsLoading:"会话明细加载中…",historyNoSessions:"该日无会话明细(早期数据或会话日志已清理)",historySessionsError:"会话明细加载失败",sessionRankTitle:"按会话统计(全部历史)",sessionRankHint:"不按日期分组,全部历史会话;排序与条数可切换",sessionRankEmpty:"暂无会话数据",sessionRankLoading:"会话排行加载中…",sessionRankError:"会话排行加载失败",sessionRankLimit:"显示条数",showSessionIdLabel:"会话列表附显会话 ID",cardsTogglePlanTotal:"金额含 Plan 总额",cardsTogglePlanTotalHint:"开启后所有金额按含 Plan 订阅等值的总费用展示;关闭(默认)仅计真金白银 API 渠道",hideOfficialBalanceLabel:"隐藏官方账户余额(开启后侧边栏与设置页不再显示官方余额)",hideTodayCostLabel:"隐藏今日消耗金额(开启后侧边栏/预算明细/概览卡片不再显示今日费用)",sessionRankSort:"排序",sessionSortCostDesc:"费用 高→低",sessionSortCostAsc:"费用 低→高",sessionSortTimeDesc:"时间 新→旧",sessionSortTimeAsc:"时间 旧→新",sessionSortRecent:"实时顺序",history:"历史记录",usageTitle:"Token 用量统计",usageTotal:"累计 {tokens} tokens · 输入 {input} · 缓存 {cache} · 输出 {output} · {calls} 次调用",usageDay:"{date}:共 {tokens} tokens(输入 {input} · 缓存 {cache} · 输出 {output})· {calls} 次调用 · {cost}",usageEmpty:"暂无历史数据,开始对话后每日用量会汇总在这里",usageSectionLabel:"用量",usagePositionLabel:"Token 用量统计位置",usagePositionCost:"费用设置",usagePositionGeneral:"通用设置",usagePositionSection:"独立分节(用量)",displaySettings:"显示设置",tabOverview:"概览",tabQuotas:"额度",tabUsage:"用量",tabPricing:"价格",tabDisplay:"显示",historyDataTitle:"历史数据",positionLabel:"会话费用显示位置",positionDock:"输入区下方",positionHeader:"会话标题栏",off:"关闭",quotaStripGroup:"输入框上方额度横条",quotaStripEnable:"启用额度横条(输入框上方一条横排显示)",quotaStripShowBudget:"横条含预算已用%",quotaStripShowGo:"横条含 Go 额度",quotaStripShowPlans:"横条含 Coding Plan 额度",quotaStripNote:"横条悬停可见各窗口重置时刻与更新时间;无可用额度数据时自动隐藏。",quotaStripGuideTitle:"新增:输入框上方额度横条",quotaStripGuideBody:"可以在输入框上方用一条横条实时查看预算与多家订阅额度(OpenCode Go / Coding Plan)的用量百分比。要现在开启吗?可随时在「设置 → 显示设置」中更改。",quotaStripGuideOn:"开启横条",quotaStripGuideOff:"暂不开启",clickToRefresh:"点击立即刷新",balanceClickGuideTitle:"新增:余额图框点击刷新",balanceClickGuideBody:"点击侧边栏余额或 Coding Plan 图框即可刷新;刷新时图框闪烁,失败时保留原值并在悬停提示中说明原因。",balanceClickGuideOk:"知道了",sidebarLabel:"当日费用显示",sidebarOn:"侧边栏底部",currencyLabel:"货币单位",currencyCny:"人民币 CNY",currencyUsd:"美元 USD",currencyEur:"欧元 EUR",symbolLabel:"货币符号",rateLabel:"汇率(1 美元 = ? 目标币种)",decimalsLabel:"小数位数",balanceDisplayLabel:"余额显示位置",balanceSidebar:"主页面侧边栏",balanceSettings:"设置页",balanceBoth:"两者都显示",refreshIntervalLabel:"余额刷新间隔(分钟)",peakEnabledLabel:"启用 DeepSeek 峰谷时段价格",peakNoticeLabel:"峰时高价时段显著提示(侧边栏预算框/今日费用;设置页峰谷面板内预览)",badgeNote:"会话费用按每次调用的时间与价格计算,保留峰谷和历史档位。输入、输出、缓存读写分别统计;提供独立缓存写入价或长上下文档位时按对应规则计费。",priceTableTitle:"价格表(美元 / 1M tokens)",pricingCurrencyLabel:"官方价格币种",pricingCurrencyUsd:"美元(英文官方页)",pricingCurrencyCny:"人民币(中文官方页)",pricingCurrencyNote:"决定「从官方文档同步价格」抓取哪个语言的官方页。切换并同步后,历史账目会按新价目整体重算(日志覆盖不全的会话保持原口径),历史与官方账单同基准;重算在后台进行,完成后有提示。",priceTableNote:"按调用时间计价:Flash 新价自 9 月 10 日北京 12:00 生效,V4 Pro 自 9 月 14 日同刻转按 Flash 价;此前保留历史价。周一至周五 09–12、14–18 为两倍峰价,周末及中国公众假期全天谷价;缓存写入按命中价。",datedPriceNote:"这里显示当前适用价格。手工编辑会取消此条后续预定调价,已发生的历史价格仍保留。",defaultModelId:"default(未匹配模型时回退)",newModelPlaceholder:"新模型 ID(如 deepseek-v4-pro)",addModel:"添加模型",dataSync:"数据与同步",saving:"保存中…",autoSaveFailed:"自动保存失败:{message}",autoSavedAt:"已自动保存 {time}",autoSaveHint:"配置修改后自动保存",confirmFetch:"确认用官方文档价格覆盖价格表?",apply:"应用",cancel:"取消",syncFromDocs:"从官方文档同步价格",syncScopeNote:"同步范围:「从官方文档同步价格」仅更新 DeepSeek 官方模型价(含峰谷档);z-ai / Kimi / Qwen / Volcano 等第三方目录价随版本维护,滞后可在「拓展价格表」编辑,或用「模型名匹配」定价。",confirmReset:"确认清除全部历史?",importLegacy:"导入安装前历史",confirmImportLegacy:"确认导入?将回放全部会话日志,只补账本缺失的日期与会话,不影响已有记录。",legacyImportFailed:"导入安装前历史失败:{message}",legacyImportNote:"首次启动自动导入安装前历史;拷入旧日志后可在此重跑。金额按当前价格回推;已删除日志无法回放,跨安装时刻的会话不计安装前用量。",confirmClear:"确认清除",clearAllHistory:"清除全部历史",lastSync:"最近同步:{time}",neverSynced:"从未(使用内置价格)",source:";来源:{source}",sourceOfficial:"官方文档",sourceBundled:"内置默认",languageLabel:"界面语言",localeAuto:"跟随浏览器(自动)",localeZh:"简体中文",localeEn:"English",sectionLabel:"费用",rpcFailed:"{method} 调用失败",rpcSyncFailed:"同步调用失败",rpcBalanceFailed:"余额刷新调用失败"},en:{sessionCostTitle:"Cost of this session (billed exactly at each call time)",sessionDetailTokens:"Input {input} · Cache {cache} · Output {output}",sessionDetailCache:"Cache: read {read} · write {write} (writes billed at the hit price)",cost:"Cost {amount}",sessionLine:"This session {amount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",quotaUnlimited:"Unlimited",pricingCnyHint:"CNY totals use USD prices × {rate}. To compare official CNY bills, select CNY, then sync prices; syncing also updates historical costs.",balanceQueryFailed:"Balance query failed: {message}",unknownError:"Unknown error",balance:"Balance",queryFailed:"Query failed",balanceTitle:"DeepSeek open-platform account balance",reconcileLabel:"Cross-check official balance changes against the local ledger (warn when they diverge)",totalBalance:"Total {amount}",grantedToppedUp:"Granted {granted} · Topped-up {toppedUp}",updatedAt:"Updated {time}",budgetOf:"Budget ({period})",usedOf:"Used {used} / {amount}",todayShare:"Today {amount} · {pct} of budget",monthTotal:"This month {month} · All time {total}",budget:"Budget",todayCostTitle:"Today's cost (billed exactly at official prices)",callsTokens:"Calls {calls} · Input {input} · Cache {cache} · Output {output}",monthCost:"This month {amount}",totalCost:"All time {amount}",today:"Today",periodDay:"Today",periodMonth:"This month",periodAll:"All time",periodCustomRange:"Custom range",noHistory:"No history yet. Once you start chatting, costs are aggregated here per day.",colDate:"Date",colCalls:"Calls",colInTok:"In tok",colCacheTok:"Cache tok",colOutTok:"Out tok",colCost:"Cost",noSessionsToday:"No sessions recorded today.",colSession:"Session",enableBudget:"Enable budget",budgetAmountLabel:"Budget amount (in display currency)",budgetPeriodLabel:"Budget period",startDate:"Start date",endDate:"End date (empty = today)",rangeText:"Range: {range}",budgetDisabledNote:"Budget is disabled. Once enabled, this panel shows the budget limit, the amount used and the used percentage (converted to the display currency); the period can be today / this month / all time / a custom date range.",budgetStatus:"{period} budget {amount} · Used {used} · {pct}%",overLimit:" (over limit)",nearLimit:" (near limit)",legacyModel:"Legacy",defaultFallback:"Default fallback",remove:"Remove",tierBase:"Base",tierOffPeak:"Off-peak",tierPeak:"Peak",balanceRefreshFailed:"Balance refresh failed: {message}",balanceLine:"Total {total} · Granted {granted} · Topped-up {toppedUp} · Updated {time}",balanceQueryFailedHint:"Balance query failed: {message} (uses the API key configured in Settings → Models)",balanceNotQueried:"Balance not queried",accountBalance:"Account balance",refreshing:"Refreshing…",refreshBalance:"Refresh balance",customBalanceTitle:"Custom provider balance",customBalanceAdd:"Add entry",aliyunBalanceAdd:"Add Qianwen / Alibaba Cloud balance",aliyunBalanceNote:"Shows Alibaba Cloud China funds in the returned currency. Requires a RAM AccessKey with bss:DescribeBillingAccount, not a Qianwen API key. First two fields are required; Security Token is for STS only. Secrets stay in the credential store.",customBalanceConfigNote:"Extract accepts paths, numbers and add/subtract/divide. Divide NewApi quota by 500000 for USD.",customBalanceLabelZh:"Chinese name",customBalanceLabelEn:"English name",customBalanceUrl:"Request URL",customBalanceMethod:"HTTP method",customBalanceHeaders:"Headers (JSON)",customBalanceBody:"Request body (JSON)",customBalanceBodyNote:"Blank sends no body; JSON text is saved and sent as entered. Content-Type defaults to application/json; headers can override it.",customBalanceExtract:"Extract rules (JSON)",customBalanceDisplayLabel:"Custom balance display",customBalanceRefreshInterval:"Refresh interval (minutes)",customBalanceUnitLabel:"Source currency",customBalanceConvert:"Convert USD balance to display currency",customBalanceConvertNote:"Uses the display rate and precision. Keep the source currency; other currencies and credits stay unchanged.",balanceBarRemaining:"Balance {amount}",balanceBarToday:"Today {amount}",balanceBarSpent:"Spent {amount}",balanceShowProgressBar:"Balance progress bar (blue=balance, orange=today, gray=spent)",barDirectionsTitle:"Progress bar direction",barDirectionsHint:'Each group of bars can independently choose its fill direction: "Remaining" starts full and drains with usage; "Used" starts empty and fills up.',barDirection_balance:"Balance bars (official/custom)",barDirection_budget:"Budget bar",barDirection_go:"Go quota bar",barDirection_plan:"Plan / Codex quota bars",barDirectionRemaining:"Remaining (full → empty)",barDirectionUsed:"Used (empty → full)",balanceBudgetCapLabel:"Budget cap (optional)",balanceBudgetCapHint:"Leave empty to use API max_budget; if still missing, show full light-blue bar",customBalanceInvalidJson:"Invalid JSON",customBalanceHeadersVarNote:"Use {{VAR_NAME}} for a DSH credential or env variable without storing its value. <ROUTE>_API_KEY uses the uppercase Provider ID with punctuation replaced by underscores (openai→OPENAI_API_KEY, abc23-d→ABC23_D_API_KEY). Same name shares one key.",customBalanceAllowedHosts:"Allowed hosts (comma-separated)",customBalanceAllowedHostsHint:"When headers carry credentials only listed hosts are allowed; leave empty to allow with a warning. Protects keys when importing someone else's config.",customBalanceCredentialsTitle:"Credential input",customBalanceCredentialsHint:"Store the key for each {{VAR}} placeholder above (write-only: stored in the DSH credential store, never echoed back):",customBalanceNoPlaceholders:'No {{VAR}} placeholders in the headers yet — add e.g. "Authorization": "Bearer {{MY_API_KEY}}" and a credential input will appear here.',enable:"Enable",customBalanceLine:"Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}",customBalanceRemaining:"Remaining {amount}",refreshCustomBalance:"Refresh custom balance",goQuotaTitle:"OpenCode Go subscription quota",goQuotaRowLabel:"Go",goWindowRolling:"Rolling 5h",goWindowWeekly:"Weekly",goWindowMonthly:"Monthly",goResetAt:"Resets: {time}",resetReached:"Reset time reached",resetDays:"{d}d {h}h left",resetHours:"{h}h {m}m left",resetMinutes:"{m}m left",quotaUsed:"{pct}% used",quotaRemaining:"{pct}% remaining",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"Updated {time}",goQuotaDisplayLabel:"Go quota display position",goQuotaRefreshIntervalLabel:"Go quota refresh interval (minutes)",goQuotaRefreshMinutesUnit:"min",goQuotaKeyLabel:"OpenCode Go API key (optional; empty = auto-detect)",goMainLabel:"Go quota primary window",goDetailLabel:"Go box details",credentialConfiguredOf:"Configured (source: {source})",credentialNotConfigured:"Not configured",credentialSave:"Save",credentialClear:"Clear",credentialSaving:"Saving…",credentialInputHint:"The key is written to the DSH credential store only — it is never saved in the ledger and never echoed back.",secretMigrationPending:"These credentials are still stored in plaintext in the local ledger and could not be migrated automatically. Export the matching environment variables and restart:",budgetDetailLabel:"Budget box details",refreshGoQuota:"Refresh quota",goQuotaNotQueried:"Quota not queried",codingPlanAnthropic:"Anthropic (Claude Pro/Max)",codingPlanZai:"Z.ai / Zhipu GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"Quota origin (HTTPS)",minimaxOriginNote:"Empty: official sites. Otherwise the Key is sent only to this origin. Use a trusted address without a path.",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"Open DeepSeek top-up page (platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) weekly quota",codexQuotaEnabled:"Show Codex quota (requires signed-in dsh-openai-codex)",includeSubagentCost:"Include subagents in session cost",gatewayQuotaEmpty:"No quota data",codingPlanDisplayLabel:"Display position",codingPlanDisplayNote:`With "Main sidebar / Both" selected, this vendor's quota shows as a card in the sidebar (same box style as the Go quota / balance; the collapsed rail shows percentages).`,codingPlanKeyLabel:"API key (optional; empty = auto-detect)",codingPlanRefreshIntervalLabel:"Refresh interval (minutes)",refreshCodingPlan:"Refresh",codingPlanNotQueried:"Quota not queried",gatewayQuotaTitle:"CLIProxyAPI gateway quotas",gatewaySourceAdd:"Add source",gatewaySourceLabel:"Source label",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"Display",gatewaySourceAllowlist:"Allowed hosts",gatewaySourceCredential:"Management key (write-only)",gatewaySourceStatus:"Status",gatewaySourceUnsupported:"Unsupported providers",gatewaySourceUnknown:"Unknown",gatewaySourceNoAccounts:"No accounts",gatewaySourceFetchedAt:"fetched {time}",gatewaySwitchAccount:"Switch account (current: {account})",gatewayOnlyGemini:"Gemini quota only",refresh:"Refresh",quotaEnableFirst:"Enable this item first",quotaRefreshReady:"Enable and save a display position to refresh",quotaRemove:"Remove",quotaSectionNote:"Enabled items move to the top; click a name to expand its own settings. Up to 8 custom balances and 4 gateway sources.",codingPlanDisabledNote:"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.",goQuotaDisabledNote:"Enable to read OpenCode Go quota (rolling 5h, weekly, monthly) in the sidebar, Settings and bottom-right corner. If no subscription exists, the reason appears here.",cornerLabel:"Bottom-right (dock) display",cornerEnabledLabel:"Show OpenCode Go quota / budget at the bottom-right",cornerGoRolling:"Rolling-5h quota",cornerGoWeekly:"Weekly quota",cornerGoMonthly:"Monthly quota",cornerBudget:"Budget used %",goShortRolling:"5h",goShortWeekly:"Wk",goShortMonthly:"Mo",goShortDaily:"Daily",budgetShort:"Budget",ledgerReadFailed:"Ledger read failed: {message}",readingLedger:"Reading ledger…",ledgerUnavailable:"Ledger unavailable",syncFailed:"Sync failed: {message}",historyCleared:"History cleared.",clearFailed:"Clear failed: {message}",peakOff:"Peak/off-peak pricing is off; base prices are used",peakNotEffective:"Not yet effective (effective at {time}); base prices are currently used",peakActive:"Peak hour now; peak prices apply",peakNotice:"DeepSeek peak-hour pricing is active; current calls are billed at peak prices",offPeakActive:"Off-peak now; off-peak prices apply",weekendAllOffPeak:"Weekend — all off-peak (Sat & Sun billed at off-peak prices all day)",weekendChip:"Weekend — all off-peak",weekendShort:"Weekend",holidayAllOffPeak:"Chinese public holiday — off-peak all day",holidayChip:"Public holiday — all off-peak",holidayShort:"Holiday",peakHolidaysLabel:"Public holidays (Beijing dates, comma separated)",weekendRuleNote:"Since Aug 23, 2026 (Beijing time), weekends and Chinese public holidays are off-peak all day, including work-shift weekends.",peakShort:"Peak",offPeakShort:"Off-peak",peakStyleLabel:"Peak period strip style",peakStyleCompact:"Compact (one-line)",peakStyleClassic:"Classic (segments & chip)",peakAlertLabel:"Popup alert before peak/off-peak switch",peakAlertAheadLabel:"Lead time (minutes, 1-30)",peakAlertTargetLabel:"Alert type",peakAlertTargetPeak:"Entering peak",peakAlertTargetOffPeak:"Entering off-peak",peakAlertTargetBoth:"Both",peakAlertTitlePeak:"Entering peak hours soon",peakAlertTitleOffPeak:"Entering off-peak hours soon",peakAlertBody:"Billing switches to {phase} pricing in about {time}; mind your call costs in this window.",peakAlertPhasePeak:"peak",peakAlertPhaseOffPeak:"off-peak",peakAlertBtn:"Got it",peakAlertBadgePeak:"Peak alert",peakAlertBadgeOffPeak:"Off-peak alert",peakAlertPositionLabel:"Popup position",peakAlertPositionCorner:"Bottom-right",peakAlertPositionCenter:"Screen center",peakAlertWebNotifyLabel:"Also send a system notification",peakAlertWebNotifyHint:"When enabled, allow notification permission in the browser address bar so you get alerted even when the page is minimized or backgrounded.",peakAlertPreviewLabel:"Preview the popup",peakAlertPreviewPeak:"Preview entering peak",peakAlertPreviewOffPeak:"Preview entering off-peak",peakAlertPreviewTag:" (preview)",peakPanelTitle:"Peak/off-peak pricing & notice",peakNoticeHiddenHint:"Notice hidden: enable peak/off-peak pricing and the “prominent notice” toggle.",groupGeneral:"General",groupMoney:"Money & currency",groupSidebar:"Sidebar display",sidebarSimple:"Simplify the sidebar",sidebarSimpleNote:"Condense cards and details while keeping amounts, quotas and hover details. The panel uses at most 38% of the viewport height and scrolls as needed. Turn off to restore your layout.",sidebarSimpleTitle:"A lighter sidebar",sidebarSimpleBody:"Simple display leaves more room for conversations. Enable it now? You can change it in Settings → Cost → Display anytime.",sidebarSimpleOn:"Enable simple display",sidebarSimpleOff:"Keep current display",sidebarSimpleError:"Settings could not be saved. Retry or dismiss this guide and change them later in Settings.",closeGuide:"Dismiss guide",todayBudget:"Today / {period} budget",sidebarStyleLabel:"Sidebar progress style",sidebarStyleStandard:"Standard",sidebarStyleCompact:"Compact (2 columns)",restorePriceMatches:"Restore removed models ({count})",removePriceMatchHint:"Remove clears the override and hides the row until restored. Usage records are kept; automatic price matching applies.",groupCorner:"Corner chips",groupDetail:"Box details",catalogTitle:"Extended price catalog",catalogNote:"Read-only prices by vendor and model family. Mount an entry to bill with it. Unmounting a DeepSeek model restores the default price; it can be mounted again.",catalogOpen:"Expand extended price catalog",catalogCollapse:"Collapse extended price catalog",mountBtn:"Mount",unmountBtn:"Unmount",mountedTag:"Mounted",catalogUnpriced:"Unpriced",catalogDeepseekNote:"DeepSeek models support peak/off-peak tiers; once unmounted they bill at the default price and are no longer hit by auto-matching.",modelStatsTitle:"Per-model statistics (tokens & cost)",modelsTitle:"Sidebar model costs",modelsCount:"{n} models",modelsOther:"Other",models_enabled:"Show model cost card",models_defaultOpen:"Expand by default",models_remember:"Remember expansion",models_tokens:"Show tokens",models_shares:"Show cost shares",models_dock:"Top model in corner dock",models_period:"Default period",models_summary:"Collapsed summary",models_position:"Card position",models_topN:"Model rows (1–10)",models_refreshSeconds:"Refresh interval (10–60 seconds)",modelsTotal:"Period total and model count",modelsTop:"Top model and cost",modelsFirst:"Top",modelsAfter:"After balances",modelsLast:"Bottom",modelStatsToday:"Today",modelStatsHistory:"Last 90 days",modelStatsCostH:"Cost ranking",modelStatsTokensH:"Token usage",modelStatsHitH:"Cache hit rate",modelStatsHitUnreported:"unreported?",modelStatsHitUnreportedTip:"Long calls with zero hits may mean a relay stripped cache fields or broke prefix caching. Hit rate is unknown; all-miss cost is an upper bound. Direct API access may restore accurate hits.",modelStatsValueH:"Value · tokens per USD",modelStatsInput:"Input",modelStatsCache:"Cache",modelStatsOutput:"Output",modelStatsEmpty:"No usage data for this period.",modelStatsBlended:"blended {price}/M",modelStatsNote:"Hit rate = cache reads ÷ (reads + uncached input). “Unreported?” means missing cache fields, often behind relays; all-miss cost is an upper bound. Unit cost = cost ÷ tokens × 1M; value = tokens ÷ cost. Uses call-time USD prices.",billingClassLabel:"Billing class",billingClassPlan:"Plan subscription",modelStatsLegacy:"Unattributed (early data · billed as recorded)",sessionLineSplit:"This session {amount} (API) · Plan equiv. {planAmount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",costChipPlan:"Cost {amount} (+Plan)",sessionDetailPlan:"Plan subscription quota usage (equiv.) {amount}",planStatsTitle:"Token Plan usage stats (per-1% & full-window estimates)",planStatsEmpty:"No enabled coding-plan quota data yet; enable and successfully refresh a provider under the Quotas tab to see per-1% and full-window usage estimates here.",planStatsWindow:"Window",planStatsPercent:"Used %",planStatsLocal:"This period actual (local ledger)",planStatsPer1:"Per 1% quota ≈",planStatsFull:"Full window (100%) ≈",planStatsResets:"resets {time}",planStatsMethodSample:"sample delta",planStatsMethodLive:"current usage ratio",planStatsMethodNone:"not enough samples",planStatsMethodSampleAt:"{method} (as of {time})",planStatsConfidenceLow:"low reading precision",planStatsCurveTitle:"Plan usage curves (aggregated from sample intervals)",planStatsDaily:"Daily",planStatsWeekly:"Weekly",planStatsMonthly:"Monthly",planStatsCurveEmpty:"Not enough sample intervals yet (at least two successful refreshes with a percent change); the curves will take shape with continued use.",planStatsBarTip:"{date}: full-window est. ≈ {full} (per 1% ≈ {per1}) · actual {tokens} / {cost} · {intervals} sample interval(s)",planStatsNote:"Amounts use catalog-price equivalents; plans consume quota, budget counts API only. Estimates cover dsh calls; server “used %” is account-wide. Per-1% and full-window estimates use trusted sample deltas (short spans have limited precision). 5h rolling; week/month use local dates.",catalogDisplayLabel:"Show directly in Cost settings",catalogDisplayHint:"Controls direct display in the Cost price table; mounting and billing are unchanged. Hidden mounted models remain editable in this catalog’s vendor section.",priceTableDisplayHint:"Use “Show directly in Cost settings” per model below. DeepSeek models appear here by default; mounted third-party models stay in the extended catalog.",catalogCustomModels:"Custom models",priceMatchLabel:"Auto-match unknown model names",priceMatchAuto:"Auto (strip suffix / prefix / family similarity)",priceMatchExact:"Exact match only",priceMatchNote:"Match order: exact → manual override → strip date/version suffix → prefix → family similarity. Unmatched DeepSeek ids fall back to the default price; other providers stay unpriced.",unmatchedTitle:"Recently seen models without a price hit",unmatchedHint:"No price matched, including the DeepSeek fallback. Choose an entry for manual billing; “Default price” uses the DeepSeek default. Local models (lmstudio, ollama, vLLM) cost zero until assigned.",overrideTargetDefault:"DeepSeek default price",overrideRemove:"Remove",overrideTargetLocal:"Local model (zero cost)",matchedTitle:"Models matched this month",matchedHint:"These models matched automatically. Choose another entry or “Local model (zero cost)”. Local tokens still count; costs become zero, including history. Overrides move to the manual list above.",matchedKeepAuto:"Keep auto match",overrideNone:"No manual match overrides.",mountedSuffix:"Mounted (billed)",flatInput:"Input",flatCached:"Cached",flatOutput:"Output",deepseekMountedHeader:"DeepSeek price table (mounted)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet Token Plan",codingPlanVolcengine:"Volcano Ark Coding Plan",codingPlanQwen:"Qwen Token Plan (qianwenai.com)",codingPlanMimo:"Xiaomi MiMo Token Plan",mimoWindowPlan:"Plan credits",mimoWindowCompensation:"Compensation",codingPlanWindowBalance:"Balance",qwenSource:"Quota source",qwenSourceLocal:"Local estimate",qwenSourceCli:"Official CLI",qwenSourceBailian:"Bailian CLI",qwenCliNote:"Install @qianwenai/qianwen-cli on the DSH host and run qianwen auth login as the same OS user.",qwenBailianNote:"Bailian CLI: install bailian-cli on the DSH host and run bl auth login --console as the same OS user.",qwenPlanCreditsLabel:"Monthly credits quota (personal Lite 50K / Standard 500K; see your plan page)",qwenPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",qwenRatesLabel:"Credits rate overrides (optional; credits deducted per 1M tokens; empty = built-in table)",qwenRatesModelPlaceholder:"Model name, e.g. qwen3.8-max-preview",qwenRatePlaceholder:"rate",qwenRate_input:"Input",qwenRate_cachedInput:"Cached input",qwenRate_output:"Output",qwenRateDraftNote:"Enter all three positive rates to save automatically; clear all to restore the built-in table.",qwenRatesAdd:"Add",qwenLocalNote:"Local estimate; console is authoritative. Counts qwen, qwen-tokenplan, qianwen-tokenplan, qwen-token-plan and qianwen-token-plan (llm- prefix allowed). Excludes API routes and pay-as-you-go qianwen. Add rates for unlisted models.",scnetPlanCreditsLabel:"Monthly credits quota for local estimates (Basic 60,000 / Standard 240,000 / Pro 600,000)",scnetPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",scnetLocalNote:"Accepts console snapshots up to 24 hours old. Otherwise estimates credits from local records and official rates. Other tools and unlisted models are excluded; check the console for actual usage.",volcengineAccessKeyIdLabel:"Volcengine AccessKey ID",volcengineSecretAccessKeyLabel:"Volcengine SecretAccessKey",volcengineNote:"Volcano Ark needs AK/SK HMAC signature (not ARK_API_KEY): IAM sub-user with ArkReadOnlyAccess + BillingCenterReadOnlyAccess, then enter AccessKeyID/SecretAccessKey; or export VOLC_ACCESSKEY/VOLC_SECRETKEY (official SDK env); credentials only go to open.volcengineapi.com.",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}h",countdownHourMinute:"{h}h {m}m",countdownMinute:"{m}m",nextOffPeakIn:"Off-peak in {time}",nextPeakIn:"Peak in {time}",peakSummary:"Peak hours (UTC): {windows}; effective: {time}. {status}",noPeakWindows:"No peak windows configured. {status}",unknown:"unknown",cardToday:"Today",cardMonth:"This month",cardTotal:"All time",cardTotalSub:"Since the ledger was created · Calls {calls}",cardsFootnote:"Amounts use the latest ledger snapshot (2s debounce; flush on shutdown), so the bill may lag by minutes. Tokens include input, output, cache and reasoning. Reasoning is unbilled here and appears in official output; reconcile by amount.",timezoneHint:"Timezone notice: today/this-month key by the host's timezone {host}, which differs from this browser ({browser}) — calls after your local midnight land on the previous day (not lost). Run dsh in your local timezone to align.",todaySessions:"Today's sessions",historyExpandHint:"Click a date row to expand its session details",historySessionsLoading:"Loading session details…",historyNoSessions:"No session details for this day (early data or session logs cleaned)",historySessionsError:"Failed to load session details",sessionRankTitle:"By session (all history)",sessionRankHint:"All historical sessions, not grouped by date; sort and row count are switchable",sessionRankEmpty:"No session data yet",sessionRankLoading:"Loading session ranking…",sessionRankError:"Failed to load session ranking",sessionRankLimit:"Rows",showSessionIdLabel:"Show session IDs in session lists",cardsTogglePlanTotal:"Include plan totals",cardsTogglePlanTotalHint:"When on, every amount shows total equivalent cost including plan subscriptions; off (default) counts real-money API channels only",hideOfficialBalanceLabel:"Hide official account balance (balance UI removed from sidebar and settings)",hideTodayCostLabel:"Hide today's cost (today's amount removed from sidebar, budget details and overview card)",sessionRankSort:"Sort",sessionSortCostDesc:"Cost high→low",sessionSortCostAsc:"Cost low→high",sessionSortTimeDesc:"Time new→old",sessionSortTimeAsc:"Time old→new",sessionSortRecent:"Recent order",history:"History",usageTitle:"Token usage stats",usageTotal:"All-time {tokens} tokens · input {input} · cache {cache} · output {output} · {calls} calls",usageDay:"{date}: {tokens} tokens (input {input} · cache {cache} · output {output}) · {calls} calls · {cost}",usageEmpty:"No history yet — daily usage will accumulate here",usageSectionLabel:"Usage",usagePositionLabel:"Token usage stats position",usagePositionCost:"Cost settings",usagePositionGeneral:"General settings",usagePositionSection:"Own section (Usage)",displaySettings:"Display settings",tabOverview:"Overview",tabQuotas:"Quotas",tabUsage:"Usage",tabPricing:"Pricing",tabDisplay:"Display",historyDataTitle:"History data",positionLabel:"Session cost display position",positionDock:"Below the composer",positionHeader:"Session title bar",off:"Off",quotaStripGroup:"Quota strip above the input",quotaStripEnable:"Enable the quota strip (one row above the input box)",quotaStripShowBudget:"Strip includes budget used %",quotaStripShowGo:"Strip includes the Go quota",quotaStripShowPlans:"Strip includes coding plan quotas",quotaStripNote:"Hover a chip for reset times and the last refresh; the strip hides itself when there is no quota data.",quotaStripGuideTitle:"New: quota strip above the input",quotaStripGuideBody:"Show budget and subscription quotas (OpenCode Go / coding plans) as one compact strip above the input box. Enable it now? You can change this anytime in Settings → Display.",quotaStripGuideOn:"Enable the strip",quotaStripGuideOff:"Not now",clickToRefresh:"Click to refresh now",balanceClickGuideTitle:"New: click the balance box to refresh",balanceClickGuideBody:"Click a sidebar balance or plan box to refresh. It pulses while loading; on failure it keeps the old value and shows the reason on hover.",balanceClickGuideOk:"Got it",sidebarLabel:"Today cost display",sidebarOn:"Sidebar footer",currencyLabel:"Currency",currencyCny:"Chinese Yuan (CNY)",currencyUsd:"US Dollar (USD)",currencyEur:"Euro (EUR)",symbolLabel:"Currency symbol",rateLabel:"Exchange rate (1 USD = ? target currency)",decimalsLabel:"Decimal places",balanceDisplayLabel:"Balance display position",balanceSidebar:"Main sidebar",balanceSettings:"Settings page",balanceBoth:"Both",refreshIntervalLabel:"Balance refresh interval (minutes)",peakEnabledLabel:"Use DeepSeek peak-hour prices",peakNoticeLabel:"Prominent notice during peak hours (sidebar budget box, today's cost; previewed in the Settings peak panel)",badgeNote:"Session cost uses each call's time and price, including peak and historical rates. Input, output, cache reads and writes are counted separately; independent cache-write and long-context rates apply when configured.",priceTableTitle:"Price table (USD / 1M tokens)",pricingCurrencyLabel:"Official price currency",pricingCurrencyUsd:"USD (English official page)",pricingCurrencyCny:"CNY (Chinese official page)",pricingCurrencyNote:'Which language of the official pricing page "Sync" fetches. After re-syncing, history is re-costed on the new table (sessions without full log coverage keep their basis); the recompute runs in the background.',priceTableNote:"Prices follow call time: Flash rates since Sep 10 04:00 UTC; V4 Pro uses Flash rates since Sep 14 04:00 UTC. Earlier prices remain for history. Mon–Fri peaks 01–04 and 06–10 UTC cost twice off-peak; weekends and Chinese public holidays are off-peak. Cache writes use hit rates.",datedPriceNote:"Current rates are shown here. Editing cancels any future scheduled change for this entry; earlier historical rates are retained.",defaultModelId:"default (fallback for unmatched models)",newModelPlaceholder:"New model ID (e.g. deepseek-v4-pro)",addModel:"Add model",dataSync:"Data & sync",saving:"Saving…",autoSaveFailed:"Auto-save failed: {message}",autoSavedAt:"Auto-saved {time}",autoSaveHint:"Settings are auto-saved",confirmFetch:"Overwrite the price table with prices from the official docs?",apply:"Apply",cancel:"Cancel",syncFromDocs:"Sync prices from official docs",syncScopeNote:'Sync scope: "Sync prices from official docs" only updates DeepSeek official prices (incl. peak/off-peak). Third-party catalog prices (z-ai / Kimi / Qwen / Volcano) follow plugin releases; edit in the extended catalog or match by name.',confirmReset:"Clear all history?",importLegacy:"Import pre-install history",confirmImportLegacy:"Confirm import? Replays all session logs and only fills dates/sessions missing from the ledger; existing records are untouched.",legacyImportFailed:"Failed to import pre-install history: {message}",legacyImportNote:"Pre-install history imports at first launch; rerun here after copying old logs. Costs use current prices. Deleted logs cannot be replayed; earlier usage in a session spanning installation is excluded.",confirmClear:"Confirm clear",clearAllHistory:"Clear all history",lastSync:"Last sync: {time}",neverSynced:"Never (bundled prices)",source:"; Source: {source}",sourceOfficial:"Official docs",sourceBundled:"Bundled",languageLabel:"Language",localeAuto:"Follow browser (auto)",localeZh:"Simplified Chinese",localeEn:"English",sectionLabel:"Cost",rpcFailed:"{method} call failed",rpcSyncFailed:"Sync call failed",rpcBalanceFailed:"Balance refresh call failed"}};function qa(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function _(t){return t==="zh"||t==="en"?t:qa()}function K(t){const s=t==="zh"?Me.zh:Me.en;return(o,a)=>{let n=s[o]??Me.en[o]??o;if(a)for(const i of Object.keys(a))n=n.split("{"+i+"}").join(String(a[i]));return n}}const Ee={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustomRange"};function ce(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function fe(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&ce(s,"object"),t}function de(t,s){return(typeof t!="number"||!Number.isFinite(t))&&ce(s,"number"),t}function Ne(t,s){return typeof t!="string"&&ce(s,"string"),t}const Ge=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function Qt(t,s=!1){return t===null||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([o,a])=>s?o.length>0&&["plan","api"].includes(a):["auto","plan","api"].includes(a)))}function Ft(t,s){return typeof t!="boolean"&&ce(s,"boolean"),t}const Ke=(t,s,o)=>Object.fromEntries(s.map(a=>[a,o(t[a])]));function _t(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const a of Object.keys(t)){const n=t[a];if(n===null||typeof n!="object"||Array.isArray(n))continue;const i=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:0;o[a]={...Ke(n,["input","output","cacheRead","cacheWrite","reasoning","cost"],i),apiCost:n.apiCost===void 0?i(n.cost):i(n.apiCost)}}return o}function Wt(t,s){fe(t,s);const o={reasoning:t.reasoning===void 0?0:de(t.reasoning,s+".reasoning"),apiCost:t.apiCost===void 0?void 0:de(t.apiCost,s+".apiCost"),byModel:_t(t.byModel,s+".byModel"),byProviderModel:_t(t.byProviderModel,s+".byProviderModel")};for(const a of["input","output","cacheRead","cacheWrite","calls","cost"])o[a]=de(t[a],s+"."+a);return o}function rt(t,s){return{...Wt(t,s),id:Ne(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:""}}function Ye(t,s){const o={...Wt(t,s),date:Ne(t.date,s+".date"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||ce(s+".sessions","array"),o.sessions=t.sessions.map((a,n)=>rt(a,s+".sessions["+n+"]"))),o}function zt(t,s,o=["cacheWrite","reasoning"]){const a={};for(const n of["cacheHit","cacheMiss","output"])a[n]=de(t[n],s+"."+n);for(const n of o)t[n]!==void 0&&(a[n]=de(t[n],s+"."+n));return a}function ct(t,s){fe(t,s);const o=zt(t,s);for(const a of["offPeak","peak","legacyBase","longContext"])t[a]!==void 0&&(o[a]=zt(t[a],s+"."+a,["cacheWrite","reasoning","aboveInputTokens"]));t.legacy!==void 0&&(o.legacy=Ft(t.legacy,s+".legacy")),t.rateHistory!==void 0&&((!Array.isArray(t.rateHistory)||t.rateHistory.length>16)&&ce(s+".rateHistory","price history"),o.rateHistory=t.rateHistory.map((a,n)=>((!a||typeof a.before!="string"||!Number.isFinite(Date.parse(a.before)))&&ce(s+".rateHistory","dated price"),{...ct({...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 Ia(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:Ge(n.display,["sidebar","settings","off"],"both"),unit:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",convertToDisplayCurrency:n.convertToDisplayCurrency===!0,refreshMinutes:typeof n.refreshMinutes=="number"&&Number.isFinite(n.refreshMinutes)?n.refreshMinutes:15,request:n.request&&typeof n.request=="object"?n.request:{url:""},extract:n.extract&&typeof n.extract=="object"?n.extract:{},allowedHosts:Array.isArray(n?.allowedHosts)?n.allowedHosts.filter(i=>typeof i=="string"):[]};fe(t,s);const a={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const n of Object.keys(t.prices.models))a[n]=ct(t.prices.models[n],s+".prices.models."+n);return{locale:t.locale==="zh"||t.locale==="en"||t.locale==="auto"?t.locale:"auto",position:t.position==="header"||t.position==="off"?t.position:"dock",sidebar:t.sidebar!==!1,showSessionId:t.showSessionId===!0,hideOfficialBalance:t.hideOfficialBalance===!0,hideTodayCost:t.hideTodayCost===!0,showTotalWithPlan:t.showTotalWithPlan===!0,sidebarSimple:t.sidebarSimple===!0,sidebarSimplePromptSeen:t.sidebarSimplePromptSeen===!0,sidebarModels:Object.fromEntries(Object.entries(Bt).map(([n,i])=>[n,t.sidebarModels?.[n]??i])),codexQuotaEnabled:t.codexQuotaEnabled===!0,includeSubagentCost:t.includeSubagentCost===!0,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(n=>typeof n=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:de(t.decimals,s+".decimals"),exchangeRate:de(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((n,i)=>({start:de(n.start,s+".peakWindows["+i+"].start"),end:de(n.end,s+".peakWindows["+i+"].end")})):[],peakHolidays:Array.isArray(t.peakHolidays)?t.peakHolidays.filter(n=>typeof n=="string"):[],peakNotice:t.peakNotice!==!1,peakAlertEnabled:t.peakAlertEnabled!==!1,peakAlertAhead:Number.isFinite(t.peakAlertAhead)&&t.peakAlertAhead>=1&&t.peakAlertAhead<=30?t.peakAlertAhead:2,peakAlertTarget:t.peakAlertTarget==="peak"||t.peakAlertTarget==="offpeak"?t.peakAlertTarget:"both",peakAlertPosition:t.peakAlertPosition==="center"?"center":"corner",peakAlertWebNotify:t.peakAlertWebNotify===!0,peakStyle:t.peakStyle==="classic"?"classic":"compact",priceMatch:t.priceMatch==="exact"?"exact":"auto",priceOverrides:(()=>{const n={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[i,l]of Object.entries(t.priceOverrides))typeof i=="string"&&typeof l=="string"&&(n[i]=l);return n})(),priceTableDisplay:(()=>{const n={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[i,l]of Object.entries(t.priceTableDisplay))typeof i=="string"&&(n[i]=l===!0);return n})(),codingPlans:(()=>{const n={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const i of Object.keys(t.codingPlans)){const l=t.codingPlans[i];l===null||typeof l!="object"||Array.isArray(l)||(n[i]={enabled:l.enabled===!0,display:l.display==="sidebar"||l.display==="both"||l.display==="off"?l.display:"settings",refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?l.refreshMinutes:15,apiKey:typeof l.apiKey=="string"?l.apiKey:"",...i==="minimax"?{baseUrl:typeof l.baseUrl=="string"?l.baseUrl:""}:{},...i==="qwen"?{quotaSource:["cli","bailian"].includes(l.quotaSource)?l.quotaSource:"local"}:{},...typeof l.planCredits=="number"&&Number.isFinite(l.planCredits)&&l.planCredits>0?{planCredits:l.planCredits}:{},...typeof l.planStart=="string"?{planStart:l.planStart}:{},...l.rates!==null&&typeof l.rates=="object"&&!Array.isArray(l.rates)?{rates:l.rates}:{},...typeof l.accessKeyId=="string"?{accessKeyId:l.accessKeyId}:{},...typeof l.secretAccessKey=="string"?{secretAccessKey:l.secretAccessKey}:{}})}return n})(),prices:{models:a,default:ct(t.prices?.default??{cacheHit:0,cacheMiss:0,output:0},s+".prices.default"),providers:t.prices?.providers&&typeof t.prices.providers=="object"?t.prices.providers:{},currency:typeof t.prices?.currency=="string"&&t.prices.currency.length>0?t.prices.currency:void 0},historyDays:de(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:Ne(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:Ge(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:Ge(t.goQuota?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.goQuota?.refreshMinutes=="number"&&Number.isFinite(t.goQuota.refreshMinutes)?t.goQuota.refreshMinutes:15,apiKey:typeof t.goQuota?.apiKey=="string"?t.goQuota.apiKey:"",main:t.goQuota?.main==="weekly"||t.goQuota?.main==="monthly"?t.goQuota.main:"rolling",detail:t.goQuota?.detail!==!1},customBalance:o(t.customBalance),gatewayQuotas:(()=>{const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(n)?n.slice(0,4).filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).map(l=>({id:typeof l.id=="string"?l.id.slice(0,48):"",type:"cliproxyapi",label:typeof l.label=="string"?l.label.slice(0,80):"",baseURL:typeof l.baseURL=="string"?l.baseURL:"",enabled:l.enabled!==!1,display:Ge(l.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?Math.min(1440,Math.max(1,Math.floor(l.refreshMinutes))):15,includeProviders:Array.isArray(l.includeProviders)?[...new Set(l.includeProviders.filter(r=>typeof r=="string").map(r=>r.toLowerCase()).filter(r=>mt.includes(r)))]:mt,allowedHosts:Array.isArray(l.allowedHosts)?l.allowedHosts.filter(r=>typeof r=="string").slice(0,16):[],allowInsecureHttp:l.allowInsecureHttp===!0,antigravityOnlyGemini:l.antigravityOnlyGemini===!0,keyVar:typeof l.keyVar=="string"?l.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(i=>i!==null&&typeof i=="object").slice(0,8).map(o).filter(Boolean);const n=o(t.customBalance);return n?[n]:[]})(),corner:{enabled:t.corner?.enabled===!0,goRolling:t.corner?.goRolling!==!1,goWeekly:t.corner?.goWeekly!==!1,goMonthly:t.corner?.goMonthly!==!1,budget:t.corner?.budget!==!1},quotaStrip:{enabled:t.quotaStrip?.enabled===!0,budget:t.quotaStrip?.budget!==!1,go:t.quotaStrip?.go!==!1,plans:t.quotaStrip?.plans!==!1,promptSeen:t.quotaStrip?.promptSeen===!0},usage:{position:t.usage?.position==="general"||t.usage?.position==="section"?t.usage.position:"cost"},barDirections:(()=>{const n=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},i=(l,r)=>n[l]==="remaining"||n[l]==="used"?n[l]:r;return{balance:i("balance","remaining"),budget:i("budget","used"),go:i("go","used"),plan:i("plan","used")}})(),planBilling:{providers:Qt(t.planBilling?.providers),models:Qt(t.planBilling?.models,!0)}}}const qe=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Se=t=>qe(t)??0,Ha={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},Ua={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},Gt=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function dt(t,s){return fe(t,s),{status:t.status==="ok"||t.status==="error"?t.status:"off",message:typeof t.message=="string"?t.message:"",fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:0}}function ja(t,s){return{...dt(t,s),currency:typeof t.currency=="string"?t.currency:"",totalBalance:Se(t.totalBalance),grantedBalance:Se(t.grantedBalance),toppedUpBalance:Se(t.toppedUpBalance)}}function ut(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&ce(s,"object"),{percent:Se(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function Qa(t,s){return{...dt(t,s),rolling:ut(t.rolling,s+".rolling"),weekly:ut(t.weekly,s+".weekly"),monthly:ut(t.monthly,s+".monthly")}}function Kt(t,s){return{...dt(t,s),label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:Se(t.remaining),maxBudget:qe(t.maxBudget),spend:qe(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const Fa=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),_a=new Set(["off","loading","ok","partial","stale","error"]),mt=["antigravity","claude","codex","kimi","xai","workbuddy"],Yt={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function Wa(t,s){fe(t,s);const o=(l,r="")=>typeof l=="string"?l:r,a=l=>qe(l),n=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{id:o(l.id),label:o(l.label),...a(l.percent)===null?{}:{percent:a(l.percent)},resetsAt:o(l.resetsAt),periodHours:a(l.periodHours),scope:o(l.scope)}:null,i=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{unit:o(l.unit,"credits"),used:a(l.used),remaining:a(l.remaining),limit:a(l.limit),fetchedAt:o(l.fetchedAt),packages:Array.isArray(l.packages)?l.packages.filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)).map(r=>({id:o(r.id),label:o(r.label),used:a(r.used),remaining:a(r.remaining),limit:a(r.limit),startsAt:o(r.startsAt),resetsAt:o(r.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:_a.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:a(t.fetchedAt)??0,attemptedAt:a(t.attemptedAt)??0,serverVersion:o(t.serverVersion),keyConfigured:t.keyConfigured===!0,keySource:o(t.keySource,"none"),accounts:Array.isArray(t.accounts)?t.accounts.filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).slice(0,16).map(l=>({id:o(l.id),provider:o(l.provider,"unknown"),label:o(l.label,"unknown"),status:Fa.has(l.status)?l.status:"unknown",message:o(l.message),plan:o(l.plan),windows:Array.isArray(l.windows)?l.windows.map(n).filter(Boolean):[],credits:i(l.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(l=>typeof l=="string").slice(0,32):[]}}function za(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};if(t.providers!==null&&typeof t.providers=="object"&&!Array.isArray(t.providers))for(const[o,a]of Object.entries(t.providers)){if(a===null||typeof a!="object"||Array.isArray(a))continue;const n={},i={};if(a.windows!==null&&typeof a.windows=="object"&&!Array.isArray(a.windows))for(const[l,r]of Object.entries(a.windows))r===null||typeof r!="object"||Array.isArray(r)||(n[l]={...Ke(r,["percent","localTokens","localCost","sampleCount"],Se),...Ke(r,["sampleAt","per1Tokens","per1Cost","fullTokens","fullCost"],qe),resetsAt:typeof r.resetsAt=="string"?r.resetsAt:"",method:r.method==="sample"||r.method==="live"?r.method:"none",confidence:r.confidence==="high"||r.confidence==="low"?r.confidence:null});if(a.intervals!==null&&typeof a.intervals=="object"&&!Array.isArray(a.intervals))for(const[l,r]of Object.entries(a.intervals))Array.isArray(r)&&(i[l]=r.filter(d=>d!==null&&typeof d=="object"&&!Array.isArray(d)).map(d=>Ke(d,["t0","t1","tokens","cost","pct","per1Tokens","per1Cost"],Se)));s[o]={windows:n,intervals:i}}return{generatedAt:Se(t.generatedAt),providers:s}}function Vt(t,s){return fe(t,s),{today:Ye(t.today,s+".today"),month:Ye(t.month,s+".month"),total:Ye(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?Ha:ja(t.balance,s+".balance"),goQuota:t.goQuota==null?Ua:Qa(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?Gt():Kt(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,a)=>Kt(o,s+".customBalances["+a+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,a)=>Wa(o,s+".gatewayQuotas["+a+"]")):[],customVarStatus:t.customVarStatus!==null&&typeof t.customVarStatus=="object"&&!Array.isArray(t.customVarStatus)?Object.fromEntries(Object.entries(t.customVarStatus).filter(([,o])=>o!==null&&typeof o=="object").map(([o,a])=>[o,{configured:a.configured===!0,source:typeof a.source=="string"?a.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:za(t.planStats),history:Array.isArray(t.history)?t.history.map((o,a)=>Ye(o,s+".history["+a+"]")):[],config:Ia(t.config,s+".config"),reconcile:t.reconcile===null||t.reconcile===void 0?void 0:{ok:t.reconcile.ok===!0,message:typeof t.reconcile.message=="string"?t.reconcile.message:""},priceCatalog:t.priceCatalog!==null&&typeof t.priceCatalog=="object"&&!Array.isArray(t.priceCatalog)?t.priceCatalog:null,meta:{now:typeof t.meta?.now=="number"?t.meta.now:Date.now(),timezoneOffsetMinutes:typeof t.meta?.timezoneOffsetMinutes=="number"?t.meta.timezoneOffsetMinutes:0,timezone:typeof t.meta?.timezone=="string"?t.meta.timezone:"",dayKey:typeof t.meta?.dayKey=="string"?t.meta.dayKey:"",monthKey:typeof t.meta?.monthKey=="string"?t.meta.monthKey:""}}}function Ga(t,s){fe(t,s);const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=Vt(t.state,s+".state")),o}function se(t){return{parse:t}}const pt=se(Vt),Ka=se(t=>fe(t,"patch")),Ya=se(Ga),Jt=se(t=>Ne(t,"provider")),Va=se(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&ce("index","0-7 integer"),t}),Ja=se(t=>Ne(t,"date")),$a=se(t=>fe(t,"day")),Za=se(t=>(Number.isFinite(Number(t))||ce("limit","number"),Number(t))),$t=se(t=>Ne(t,"sort")),Xa=se(t=>fe(t,"topSessions")),Zt=se(t=>Ne(t,"target")),en=se(t=>Ne(t,"value")),Ce=(t,s)=>({mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:s,create:()=>s}),ie=(t,s,o,a=!1)=>({name:t,wire:t,source:"json",codec:Ce(s,o),...a?{acceptsUndefined:!0}:{}}),tn={package:"dsh-cost-meter",descriptors:[{method:"getState",result:Ce("CostState",pt)},{method:"updateConfig",parameters:[ie("patch","ConfigPatch",Ka)],result:Ce("CostState",pt)},{method:"fetchPrices"},{method:"refreshBalance"},{method:"refreshGoQuota"},{method:"refreshCustomBalance",parameters:[ie("index","CustomBalanceIndex",Va,!0)]},{method:"refreshCodingPlan",parameters:[ie("provider","CodingPlanProvider",Jt)]},{method:"refreshGatewayQuota",parameters:[ie("sourceId","GatewayQuotaSourceId",se(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&ce("sourceId","gateway source id"),t}),!0)]},{method:"resetHistory",result:Ce("CostState",pt)},{method:"importLegacyHistory"},{method:"getDaySessions",parameters:[ie("date","DayKey",Ja)],result:Ce("DayRecord",$a)},{method:"getSessionCost",parameters:[ie("sessionId","SessionId",Jt)],result:Ce("SessionCost",se(t=>({own:rt(t.own,"own"),subagents:rt(t.subagents,"subagents"),found:Ft(t.found,"found"),subagentCount:de(t.subagentCount,"subagentCount")})))},{method:"getTopSessions",parameters:[ie("limit","SessionLimit",Za),ie("sort","SessionSort",$t,!0),ie("dir","SessionSortDir",$t,!0)],result:Ce("TopSessions",Xa)},{method:"setCredential",parameters:[ie("target","CredentialTarget",Zt),ie("value","CredentialValue",en)]},{method:"clearCredential",parameters:[ie("target","CredentialTarget",Zt)]}].map(t=>({id:"dsh-cost-meter#costMeter/"+t.method,service:"costMeter",namespace:"costMeter",invocation:{kind:"direct"},parameters:[],result:Ce("FetchPricesResult",Ya),...t}))};function an(t,s){const o=s?.models??{};return typeof t=="string"&&t.length>0&&o[t]!==void 0?o[t]:s?.default??{cacheHit:0,cacheMiss:0,output:0}}function Ie(t){if(t===null||typeof t!="object")return;const s=l=>{const r=t[l];return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0},o=s("cacheMiss")??s("input")??0,n={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},i=s("reasoning");return i!==void 0&&(n.reasoning=i),s("cacheWrite")!==void 0&&(n.cacheWrite=s("cacheWrite")),n}function nn(t){const s=Ie(t);if(s===void 0)return null;for(const o of["offPeak","peak","legacyBase"]){const a=Ie(t[o]);a!==void 0&&(s[o]=a)}return Number.isFinite(t.longContext?.aboveInputTokens)&&t.longContext.aboveInputTokens>0&&(s.longContext={...Ie(t.longContext),aboveInputTokens:t.longContext.aboveInputTokens}),Array.isArray(t.rateHistory)&&(s.rateHistory=t.rateHistory.slice(0,16).map(o=>{const a={...Ie(o),before:o.before};for(const n of["offPeak","peak"]){const i=Ie(o[n]);i!==void 0&&(a[n]=i)}return a})),s}function Ve(t,s=Date.now()){if(!t||!Number.isFinite(s)||!Array.isArray(t.rateHistory))return t;let o=null,a=1/0;for(const l of t.rateHistory){const r=Date.parse(l.before);s<r&&r<a&&(o=l,a=r)}if(!o)return t;const{before:n,...i}=o;return{...t,...i}}const ft=Date.parse("2026-08-22T16:00:00Z");function Xt(t){if(!Number.isFinite(t)||t<ft)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,ft),end:(a+2)*864e5-8*36e5}}function ea(t,s){if(!Number.isFinite(t)||t<ft||!Array.isArray(s))return null;const o=Math.floor((t+8*36e5)/864e5);return s.includes(new Date(o*864e5).toISOString().slice(0,10))?{start:o*864e5-8*36e5,end:(o+1)*864e5-8*36e5}:null}const sn=(t,s)=>ea(t,s)??Xt(t);function Je(t,s,o,a){if(!Array.isArray(o)||o.length===0||sn(t,a)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(i=>{const l=Number(i.start),r=Number(i.end);return!Number.isFinite(l)||!Number.isFinite(r)?!1:l<r?n>=l&&n<r:n>=l||n<r})}const on=Date.parse("2026-08-16T16:00:00Z");function ta(t,s,o){const a=Ve(t,s)??{cacheHit:0,cacheMiss:0,output:0},n=l=>({cacheHit:l.cacheHit,cacheMiss:l.cacheMiss,output:l.output,reasoning:l.reasoning??0,...l.cacheWrite===void 0?{}:{cacheWrite:l.cacheWrite},...l.longContext===void 0?{}:{longContext:l.longContext}});if(Number.isFinite(s)&&s<on){const l=a.legacyBase;return n(l===void 0?a:l)}if(o?.enabled!==!0)return n(a);const i=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(Je(s,i,o.windows,o.holidays)){const l=a.peak;return n(l===void 0?a:l)}if(i!==void 0&&s>=i){const l=a.offPeak;return n(l===void 0?a:l)}return n(a)}function aa(t,s){const o=Math.max(0,Number(t.input)||0),a=Math.max(0,Number(t.output)||0),n=Math.max(0,Number(t.cacheRead)||0),i=Math.max(0,Number(t.cacheWrite)||0),l=Math.max(0,Number(t.reasoning)||0);return s.longContext&&o+n+i>s.longContext.aboveInputTokens&&(s=s.longContext),(o*s.cacheMiss+a*s.output+n*s.cacheHit+i*(s.cacheWrite??s.cacheHit)+l*(s.reasoning??0))/1e6}function na(t,s,o){const a=Number(t);if(!Number.isFinite(a)||a<0||a===0)return 0;if(s!=="CNY")return a;const n=Number(o);return!Number.isFinite(n)||n<=0?a:a/n}function te(t,s){const o=t?.barDirections,a=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return a;const n=o[s];return n==="remaining"||n==="used"?n:a}function ue(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),a=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:a,label:a}}const sa=(t,s)=>t.toFixed(s).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1");function oe(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",a=Number(s?.decimals),n=Math.max(0,Math.min(10,Number.isFinite(a)?Math.floor(a):2));let i=n;return t>0&&t<Math.pow(10,-n)&&(i=n+2),o+sa(t,i)}function Y(t,s){const o=Number(s?.exchangeRate),a=t*(Number.isFinite(o)&&o>0?o:1);return oe(a,s)}function U(t){const s=Math.max(0,Number(t)||0),o=a=>a>=100?String(Math.round(a)):String(Math.round(a*10)/10);return s<1e3?String(Math.round(s)):s>=999500?o(s/1e6)+"M":s<1e6?o(s/1e3)+"K":o(s/1e6)+"M"}function re(t){return String(t??"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/([^)]*)/g," ").replace(/[^a-z0-9]+/g,"")}function Te(t,s){if(typeof t!="string"||t.length===0)return null;const o=Array.isArray(s)?s.filter(k=>typeof k=="string"&&k.length>0):[];if(o.length===0)return null;const a=k=>String(k).toLowerCase().replace(/[-@]\d{4}-?\d{2}-?\d{2}$/,"").replace(/[-@]v\d+(\.\d+)*$/,""),n=o.find(k=>k===t);if(n!==void 0)return n;const i=re(t);if(i.length===0)return null;const l=o.find(k=>re(k)===i);if(l!==void 0)return l;let r=null,d=0;for(const k of o){const f=re(k);if(!(f.length<4||f===i)&&i.includes(f)&&f.length>d){const v=i.indexOf(f);if(/^\d{1,2}$/.test(i.slice(v+f.length)))continue;r=k,d=f.length}}if(r!==null)return r;const u=a(t),c=o.find(k=>a(k)===u);if(c!==void 0)return c;let g=null;for(const k of o){const f=a(k);if(f.length===0||f===u)continue;const v=u.slice(f.length);if(u.startsWith(f)&&/^[-_./:]/.test(v)){if(/^\d{1,2}$/.test(v.replace(/^[-_./:]+/,"")))continue;(g===null||a(g).length<f.length)&&(g=k)}}if(g!==null)return g;const m=k=>a(k).split(/[-_./:]+/).filter(Boolean),p=m(t);if(p.length<2)return null;let b=null,x=0;for(const k of o){const f=m(k);let v=0;for(;v<p.length&&v<f.length&&p[v]===f[v];)v+=1;v<p.length&&v<f.length&&/^\d+$/.test(p[v])&&/^\d+$/.test(f[v])||v>=2&&v===f.length&&v<p.length&&p.slice(v).every(S=>/^\d{1,2}$/.test(S))||v>=2&&v<p.length&&v<f.length&&(/^\d{1,2}$/.test(p[v])&&/^[a-z]/.test(f[v])||/^\d{1,2}$/.test(f[v])&&/^[a-z]/.test(p[v]))||v>=2&&(v>x||v===x&&b!==null&&k.length<b.length)&&(b=k,x=v)}return b}const ln=new Set(["lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),rn=["lmstudio:","lmstudio/","ollama:","ollama/","jan:","jan/","gpt4all:","gpt4all/","koboldcpp:","koboldcpp/","llamacpp:","llamacpp/","llama-cpp:","llama-cpp/","localai:","localai/","vllm:","vllm/","sglang:","sglang/","tabbyapi:","tabbyapi/","lmdeploy:","oobabooga/","text-generation-webui/","llama-server:","gguf:","local:"];function cn(t,s){if(typeof t=="string"&&ln.has(t))return!0;const o=typeof s=="string"?s.toLowerCase():"";return rn.some(a=>o.startsWith(a))}function bt(t,s,o){const a=o?.prices??{},n=o?.priceMatch==="exact"?"exact":"auto",i=o?.priceOverrides&&typeof o.priceOverrides=="object"?o.priceOverrides:{};let l=String(t??"").trim().toLowerCase();l.startsWith("llm-")&&(l=l.slice(4)),l===""&&(l="deepseek");let r=l,d=s;const u=i[l+":"+s];if(u==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof u=="string"&&u.length>0){const m=u.indexOf(":");if(m>0&&u.slice(m+1).length>0?(r=u.slice(0,m).trim().toLowerCase(),d=u.slice(m+1)):d=u,r==="deepseek"&&d==="__default__")return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}if(cn(r,d))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(r==="deepseek"||r.includes("deepseek")){const m=a.models??{},p=m[d]!==void 0?d:n==="auto"?Te(d,Object.keys(m)):null;if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0};if(n==="auto"){let b=null,x=-1,k="flat";for(const[f,v]of Object.entries(a.providers??{})){const S=v?.models??{},w=Te(d,Object.keys(S));if(w===null||S[w]?.unpriced===!0)continue;const y=(w===d||re(w)===re(d)?1e3:0)+re(w).length;y>x&&(b=S[w],x=y,k=S[w]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(b!==null)return{entry:b,priced:!0,billingMode:k,matched:!0}}return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}const c=a.providers?.[r]?.models??{},g=c[d]!==void 0?d:n==="auto"?Te(d,Object.keys(c)):null;if(g!==null)return{entry:c[g],priced:c[g]?.unpriced!==!0,billingMode:"flat",matched:!0};if(n==="auto"){const m=a.models??{},p=Te(d,Object.keys(m));if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0};let b=null,x=-1,k="flat";for(const[f,v]of Object.entries(a.providers??{})){if(f===r)continue;const S=v?.models??{},w=Te(d,Object.keys(S));if(w===null||S[w]?.unpriced===!0)continue;const y=(w===d||re(w)===re(d)?1e3:0)+re(w).length;y>x&&(b=S[w],x=y,k=S[w]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(b!==null)return{entry:b,priced:!0,billingMode:k,matched:!0}}if(l!=="deepseek"&&!l.includes("deepseek")&&typeof u=="string"&&u.length>0&&!u.includes(":")){const m=a.models??{},p=m[u]!==void 0?u:n==="auto"?Te(u,Object.keys(m)):null;if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function dn(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,a=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&a===0}function $e(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:la(t,s).total}function gt(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:gt(t)}const un={go:["go","zen","opencode","opencode-go"],qwen:["qwen","qwen-tokenplan","qianwen-tokenplan","qwen-token-plan","qianwen-token-plan"],scnet:["scnet","scnet-tokenplan","scnet-token-plan"],mimo:["mimo","xiaomimimo","mimo-token-plan","xiaomi-token-plan","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","xiaomi-token-plan-ams"]},oa=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","mimo","go"];function mn(t){const s=String(t??"").trim().toLowerCase().replace(/^llm-/,"");if(s.length===0)return null;for(const[o,a]of Object.entries(un))if(a.includes(s))return o;return oa.includes(s)?s:null}function pn(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const a of oa)a!=="go"&&o[a]?.enabled===!0&&s.add(a);return t?.goQuota?.enabled===!0&&s.add("go"),s}function fn(t,s,o){const a=String(t??"").trim().toLowerCase();if(a.length>0&&a!=="deepseek"&&!a.includes("deepseek"))return!1;const n=re(s);if(n.length===0)return!1;const i=o?.prices,l=i?.models??{};for(const r of Object.keys(l))if(re(r)===n)return!1;for(const r of Object.values(i?.providers??{}))for(const d of Object.keys(r?.models??{}))if(re(d)===n)return!0;return!1}function He(t,s,o){let a=mn(t);if(a===null&&fn(t,s,o)&&(a="go"),a===null)return"api";const n=o?.planBilling?.models;if(n!==null&&typeof n=="object"){const l=n[t+":"+s];if(l==="plan"||l==="api")return l;const r=n[a+":"+s];if(r==="plan"||r==="api")return r}const i=o?.planBilling?.providers?.[a];return i==="plan"||i==="api"?i:pn(o).has(a)?"plan":"api"}function la(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows,holidays:s.peakHolidays},a=Date.now(),n=t.byProviderModel??t.byModel??{};let i=0,l=0;for(const g of Object.keys(n)){const m=g.indexOf(":"),p=m>0?g.slice(0,m):"deepseek",b=m>0?g.slice(m+1):g,x=bt(p,b,s);if(x.priced){const k=aa(n[g],ta(nn(x.entry),a,{...o,enabled:x.billingMode==="deepseek-peak"&&o.enabled})),f=na(k,x.billingMode==="deepseek-peak"&&s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);i+=f,He(p,b,s)==="api"&&(l+=f)}}const r={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const g of Object.keys(n))r.input+=n[g].input??0,r.output+=n[g].output??0,r.cacheRead+=n[g].cacheRead??0,r.cacheWrite+=n[g].cacheWrite??0,r.reasoning+=n[g].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=aa(d,ta(an("default",s.prices),a,o)),c=na(u,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return i+=c,l+=c,{total:i,api:l}}function ia(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const a of Object.keys(o)){const n=a.indexOf(":"),i=n>0?a.slice(0,n):"deepseek",l=n>0?a.slice(n+1):a;if(He(i,l,s)==="plan")return!0}return!1}function ht(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function ra(t,s){if(t?.apiCost!==void 0)return gt(t);if(!ia(t,s))return $e(t,s);let o=0;for(const[a,n]of Object.entries(t.byProviderModel??{})){if(!Number.isFinite(n.cost))return la(t,s).api;const i=a.indexOf(":");He(a.slice(0,i),a.slice(i+1),s)==="plan"&&(o+=n.cost)}return Math.max(0,$e(t,s)-o)}function yt(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),a=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(a>0?":"+String(a).padStart(2,"0"):"")}function bn(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const a=-new Date().getTimezoneOffset();if(a===o)return null;const n=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:n?n+" ("+yt(o)+")":yt(o),browserLabel:yt(a)}}function gn(t){let s=t;const o=new Set;return{getSnapshot:()=>s,subscribe:a=>(o.add(a),()=>{o.delete(a)}),set:a=>{if(a!==s){s=a;for(const n of[...o])n()}}}}const{createElement:e,Fragment:q,useState:L,useEffect:X,useRef:ke}=Le;function Be({target:t,configured:s,source:o,t:a,api:n,placeholder:i,disabled:l}){const[r,d]=L(""),[u,c]=L(!1),[g,m]=L(null),p=l===!0||u,b=async()=>{const k=r.trim();if(!(k.length===0||p)){c(!0),m(null);try{const f=await n.setCredential(t,k);d(""),m({kind:"ok",text:f?.message??a("credentialSave")})}catch(f){m({kind:"err",text:String(f?.message??f)})}finally{c(!1)}}},x=async()=>{if(!p){c(!0),m(null);try{const k=await n.clearCredential(t);d(""),m({kind:"ok",text:k?.message??a("credentialClear")})}catch(k){m({kind:"err",text:String(k?.message??k)})}finally{c(!1)}}};return e("div",{className:"cm-field"},e("input",{className:"cm-input",type:"password",value:r,placeholder:typeof i=="string"?i:"",disabled:p,autoComplete:"off",onChange:k=>d(k.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:b,disabled:p||r.trim().length===0},a(u?"credentialSaving":"credentialSave")),s===!0?e("button",{className:"cm-btn small",onClick:x,disabled:p},a("credentialClear")):null),e("span",{className:"cm-hint"},s===!0?a("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):a("credentialNotConfigured")),e("span",{className:"cm-hint"},a("credentialInputHint")),Et(g))}function hn({pending:t,t:s}){return!Array.isArray(t)||t.length===0?null:e("div",{className:"cm-msg err"},e("div",null,s("secretMigrationPending")),e("div",null,t.join("、")))}function Ze({size:t=16,className:s}){return e("svg",{width:t,height:t,className:s,viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e("path",{d:"M4 4H12A2 2 0 0 1 14 6V11.5A2 2 0 0 1 12 13.5H4A2 2 0 0 1 2 11.5V6A2 2 0 0 1 4 4ZM4 5.3H12A0.7 0.7 0 0 1 12.7 6V11.5A0.7 0.7 0 0 1 12 12.2H4A0.7 0.7 0 0 1 3.3 11.5V6A0.7 0.7 0 0 1 4 5.3Z",fill:"currentColor",fillRule:"evenodd"}),e("path",{d:"M3.3 5.3H12.7V7.1H3.3Z",fill:"currentColor"}),e("path",{d:"M8 2.8A1.3 1.3 0 1 0 8 5.4A1.3 1.3 0 1 0 8 2.8Z",fill:"currentColor"}))}function ca(t,s){const o=ke(!1),a=ke(""),n=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(i=>String(i??0)).join("|"):"";X(()=>{if(!o.current){o.current=!0,a.current=n;return}if(n===""||n===a.current)return;a.current=n;const i=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(i)},[n])}function yn(t,s,o,a){const n=d=>["input","output","cacheRead","cacheWrite"].reduce((u,c)=>u+(d?.[c]??0),0),i=s?.found&&n(s.own)>=n(t)?s.own:t;if(!o||!s?.subagentCount)return i;const l=s.subagents,r={...i};for(const d of["input","output","cacheRead","cacheWrite","reasoning","cost"])r[d]=(i?.[d]??0)+(l?.[d]??0);r.apiCost=ra(i,a)+gt(l);for(const d of["byModel","byProviderModel"]){r[d]={...i?.[d]};for(const[u,c]of Object.entries(l?.[d]??{})){const g={...r[d][u]};for(const m of["input","output","cacheRead","cacheWrite","reasoning","cost"])g[m]=(g[m]??0)+(c[m]??0);delete g.apiCost,r[d][u]=g}}return r}function da(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?.(r=>r)?.state,a=o?.config,[n,i]=L(null);ca(t,s),X(()=>{if(!t.sessionId||!t.api?.getSessionCost)return;let r=!0,d=!1;const u=async()=>{if(!d){d=!0;try{const g=await t.api.getSessionCost(t.sessionId);r&&i({id:t.sessionId,include:a?.includeSubagentCost===!0,value:g})}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 l=n&&n.id===t.sessionId&&n.include===(a?.includeSubagentCost===!0)?n.value:null;return{usage:yn(s,l,a?.includeSubagentCost===!0,a),config:a}}function ua(t,s){let o=0,a=$e(t,s);if(s.showTotalWithPlan!==!0&&(t.apiCost!==void 0||ia(t,s))){const n={total:$e(t,s),api:ra(t,s)};o=Math.max(0,n.total-n.api),o>0&&(a=n.api)}return{cost:a,planPart:o}}function kn(t){const{usage:s,config:o}=da(t);if(!s||!o||ht(s)+(s?.output??0)===0)return null;const a=K(_(o.locale)),{cost:n,planPart:i}=ua(s,o),l=[a("sessionCostTitle"),a("sessionDetailTokens",{input:U(s?.input??0),cache:U((s?.cacheRead??0)+(s?.cacheWrite??0)),output:U(s?.output??0)}),a("sessionDetailCache",{read:U(s?.cacheRead??0),write:U(s?.cacheWrite??0)}),a("cost",{amount:Y(n,o)}),...i>0?[a("sessionDetailPlan",{amount:Y(i,o)})]:[]].join("; ");return e($,{label:l,side:"top",delayMs:500},e("div",{className:"cm-chip"},i>0?a("costChipPlan",{amount:Y(n,o)}):a("cost",{amount:Y(n,o)})))}function wn(t){const{usage:s,config:o}=da(t);if(!s||!o)return null;const a=s.input??0,n=(s.cacheRead??0)+(s.cacheWrite??0),i=s.output??0;if(a+n+i===0)return null;const l=K(_(o.locale)),{cost:r,planPart:d}=ua(s,o),u=ht(s)>0?((s.cacheRead??0)/ht(s)*100).toFixed(1)+"%":"—";return e("div",{className:"cm-root"},l(d>0?"sessionLineSplit":"sessionLine",{amount:Y(r,o),planAmount:Y(d,o),hitRate:u,input:U(a),cache:U(n),output:U(i)}))}const xn={USD:"$",CNY:"¥",EUR:"€"};function we(t,s,o){const a=typeof o=="string"?o.toUpperCase():"",n=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return oe(t,{symbol:xn[a]??n,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function ma(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const a=Number(s?.maxBudget);return Number.isFinite(a)&&a>0?a:null}function vn(t){const s=t.today,o=s?.byProviderModel;if(o===null||typeof o!="object"||Object.keys(o).length===0)return Number(s?.cost)||0;let a=0;for(const[n,i]of Object.entries(o)){const l=n.indexOf(":");let r=l>=0?n.slice(0,l):n;r.startsWith("llm-")&&(r=r.slice(4)),!(r!=="deepseek"&&r!=="deepseek-official")&&(a+=Number(i?.cost)||0)}return a}function pa(t,s,o,a,n=null){const i=o==="official"?vn(t):Number(t.today?.cost)||0;if(o==="custom"){const r=Ue(s,a,n);if(r==="USD")return i;if(r==="CREDITS")return 0;const d=Number(s?.exchangeRate);return i*(Number.isFinite(d)&&d>0?d:1)}const l=Number(s?.exchangeRate);return i*(Number.isFinite(l)&&l>0?l:1)}function fa({remaining:t,spend:s,todayUsed:o,cap:a}){if(a===null||a<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const n=Math.max(0,Number(t)||0),i=Math.max(0,Number(s)||0),l=Math.max(0,Math.min(i,Number(o)||0)),r=Math.max(0,i-l),d=Math.max(0,Math.min(100,n/a*100)),u=Math.max(0,Math.min(100-d,l/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:l}}function kt(t,s,o=null,a=null){const n=o??t.customBalance,i=ma(Ue(s,n,a)==="CREDITS"?null:s,n),l=Number(n?.remaining)||0,r=Number(n?.spend)||0,d=pa(t,s,"custom",n,a);return{cap:i,...fa({remaining:l,spend:r,todayUsed:d,cap:i})}}function Nn(t,s){const o=t.balance,a=ma(s,null),n=Number(o?.totalBalance)||0,i=pa(t,s,"official",null),l=a!==null?Math.max(0,a-n):0;return{cap:a,...fa({remaining:n,spend:l,todayUsed:i,cap:a})}}function wt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:a,todayPct:n,spentPct:i}=s,l=[];a>0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:a+"%"}})),n>0&&l.push(e("div",{className:"cm-bbox-seg-today",style:{width:n+"%"}})),i>0&&l.push(e("div",{className:"cm-bbox-seg-spent",style:{width:i+"%"}})),l.length===0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const r=o==="used"?[...l].reverse():l;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...r)}function ba(t,s,o,a,n){const i=[t("balanceBarRemaining",{amount:a})];return o.today>0&&i.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&i.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),n!==null&&n>0&&i.push(t("balanceBudgetCapLabel")+": "+s(n)),i.join(" · ")}function Ae(t){const[s,o]=L(!1),[a,n]=L(null);return{busy:s,err:a,run:()=>{s||typeof t!="function"||(o(!0),n(null),Promise.resolve().then(t).catch(l=>{n(l?.message??String(l))}).finally(()=>{o(!1)}))}}}const me=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function be(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const Sn="https://platform.deepseek.com/usage";function ga(t){return e("a",{className:"cm-bal-link",href:Sn,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},e("svg",{width:14,height:14,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},e("path",{d:"M8 4H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4M11 3h6v6M9 11l8-8"})))}function Cn(t){const{state:s,wide:o,api:a}=t,n=s.balance,i=K(_(s.config?.locale)),l=Ae(a?()=>a.refreshBalance():null);if(!n||n.status==="off")return null;if(n.status==="error")return e($,{label:[i("balanceQueryFailed",{message:n.message||i("unknownError")}),...be(i,l)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,i("balance")," ",e("span",{className:"cm-num"},i("queryFailed"))):"⚠"));const r=[i("balanceTitle"),i("totalBalance",{amount:we(n.totalBalance,s.config,n.currency)}),i("grantedToppedUp",{granted:we(n.grantedBalance,s.config,n.currency),toppedUp:we(n.toppedUpBalance,s.config,n.currency)}),i("updatedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...be(i,l)].join("; ");return e($,{label:r,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,e("span",{className:"cm-balance-name"},i("balance"),ga(i)),e("span",{className:"cm-num cm-bal-amt"},we(n.totalBalance,s.config,n.currency)),s.reconcile?.ok===!1?" ⚠":""):e(Ze,{size:16})))}function An(t){const{state:s,wide:o,api:a}=t,n=s.config,i=s.balance,l=K(_(n?.locale)),r=Ae(a?()=>a.refreshBalance():null);if(!i||i.status!=="ok")return null;const d=Nn(s,n),u=we(i.totalBalance,n,i.currency),c=p=>we(p,n,i.currency),g=[l("balanceTitle"),ba(l,c,d,u,d.cap),l("grantedToppedUp",{granted:we(i.grantedBalance,n,i.currency),toppedUp:we(i.toppedUpBalance,n,i.currency)}),l("updatedAt",{time:i.fetchedAt>0?new Date(i.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...be(l,r)].join("; "),m=e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-balance-name"},e("span",{className:"cm-bbox-label"},l("balance")),ga(l)),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},u)),e(wt,{segments:d,direction:te(n,"balance")}));return e($,{label:g,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(r.busy?" busy":""),...me(r.busy,r.run)},o?m:e("div",{className:"cm-bbox-rail cm-num"},Math.round(d.remainingPct)+"%")))}function xt(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 Ue(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 je(t,s,o,a){const n=Ue(s,o,a),i=Number(t);if(!Number.isFinite(i))return"—";const l=s?.currency==="USD"?1:Number(s?.exchangeRate);if((a??s?.customBalance)?.convertToDisplayCurrency===!0&&n==="USD"&&Number.isFinite(l)&&l>0){const c=i*l;return Number.isFinite(c)?oe(c,s):"—"}const r=n==="CREDITS",d=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4)));return(r?"":n==="CNY"?"¥":n==="EUR"?"€":"$")+sa(i,d)+(r?" Credits":"")}function vt(t,s,o,a,n=null){const i=je(t.remaining,s,t,n),l=m=>je(m,s,t,n);if(a&&s.balance?.showProgressBar===!0){const m=kt(a,s,t,n);return[ba(o,l,m,i,m.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const r=t.spend!==null?l(t.spend):"—",d=t.maxBudget!==null?l(t.maxBudget):"—",u=Ue(s,t,n)==="CREDITS"?NaN:Number(s?.balance?.budgetCap),c=Number.isFinite(u)&&u>0?o("balanceBudgetCapLabel")+": "+l(u):"",g=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:i,spend:r,maxBudget:d,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:i});return c?g+" · "+c:g}function Pn(t,s,o,a,n){const i=xt(n??s.customBalance??{},_(s?.locale)),l=je(a.remaining,s,a,n),r=kt(t,s,a,n);return{level:"ok",rail:Math.round(r.remainingPct)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},i),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},l)),e(wt,{segments:r,direction:te(s,"balance")}))}}function Nt(t,s){const o=s?.customBalances??[],a=Array.isArray(t?.customBalances)?t.customBalances:[],n=[];return o.forEach((i,l)=>{if(i?.enabled!==!0||i.display!=="sidebar"&&i.display!=="both")return;const r=a.find(d=>d.index===l)??(a.length===1&&o.length===1?a[0]:null);n.push({index:l,entry:i,snapshot:r})}),n.length===0&&a.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&n.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),n}function Mn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(_(n?.locale)),l=Nt(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:d,snapshot:u})=>e(Tn,{key:"cb-"+r,state:s,wide:o,api:a,t:i,index:r,entry:d,snapshot:u})))}function Tn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,d=s.config;if(r==null||r.status!=="ok")return null;const u=Ae(a?()=>a.refreshCustomBalance(i):null),c=Pn(s,d,n,r,l),g=[vt(r,d,n,s,l),...be(n,u)].join(" · ");return e($,{label:g,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(u.busy?" busy":""),...me(u.busy,u.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function Bn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(_(n?.locale)),l=Nt(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:d,snapshot:u})=>e(Dn,{key:"cbr-"+r,state:s,wide:o,api:a,t:i,index:r,entry:d,snapshot:u})))}function Dn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,d=s.config,u=r??Gt(i);if(u.status==="off")return null;const c=Ae(a?()=>a.refreshCustomBalance(i):null),g=xt(l??d.customBalance??{},_(d?.locale));if(u.status==="error")return e($,{label:[u.message||n("unknownError"),...be(n,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:g},g),e("span",{className:"cm-num cm-bal-amt"},n("queryFailed"))):"⚠"));const m=je(u.remaining,d,u,l),p=[vt(u,d,n,s,l),...be(n,c)].join(" · ");return e($,{label:p,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:g},g),e("span",{className:"cm-num cm-bal-amt"},m)):e(Ze,{size:16})))}function On(t){const o=(t.useCost?t.useCost(b=>b):void 0)?.state;if(!o)return null;const a=o.config,n=K(_(a?.locale)),i=a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},l=o.goQuota,r=a?.goQuota?.enabled!==!1&&l?.status==="ok",d=b=>b!==null&&typeof b?.percent=="number"?Math.round(Math.max(0,Math.min(100,b.percent))):null,u=[];if(a.sidebarModels?.dock){const b=Aa(o,a.sidebarModels.period,n);b.length&&u.push({key:"model-top",text:e(q,null,e("span",{className:"cm-bal-label"},b[0].label),e("span",{className:"cm-bal-amt"},Y(b[0].cost,a))),tip:b[0].label+" "+Y(b[0].cost,a),level:"ok"})}const c=(b,x,k,f)=>{if(!i.enabled||!b||!r)return;const v=d(x);if(v===null)return;const S=typeof x.resetsAt=="string"&&x.resetsAt.length>0?n("goResetAt",{time:new Date(x.resetsAt).toLocaleString()}):"";u.push({key:k,text:n(k)+" "+v+"%",tip:n(f)+": "+v+"%"+(S?" · "+S:""),level:v>=100?"over":v>=80?"warn":"ok"})},g=a?.goQuota?.main==="weekly"||a?.goQuota?.main==="monthly"?a.goQuota.main:"rolling",m=[g,...["rolling","weekly","monthly"].filter(b=>b!==g)],p=b=>b==="rolling"?["goRolling",l?.rolling,"goShortRolling","cornerGoRolling"]:b==="weekly"?["goWeekly",l?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",l?.monthly,"goShortMonthly","cornerGoMonthly"];for(const b of m){const[x,k,f,v]=p(b);c(i[x]===!0,k,f,v)}if(i.enabled&&i.budget===!0){const b=a.budget??{enabled:!1,amount:100,period:"month"};if(b.enabled===!0){const x=Number(a.exchangeRate),f=(o.budgetUsed??(b.period==="day"?z(o.today,a):b.period==="all"?z(o.total,a):z(o.month,a)))*(Number.isFinite(x)&&x>0?x:1),v=Math.max(0,Number(b.amount)||0),S=v>0?Math.min(999,f/v*100):null;if(S!==null){const w=S>=100?"over":S>=80?"warn":"ok";u.push({key:"budget",text:n("budgetShort")+" "+S.toFixed(1)+"%",tip:n("budgetOf",{period:n(Ee[b.period]??"periodMonth")})+" · "+n("usedOf",{used:oe(f,a),amount:oe(v,a)}),level:w})}}}return u.length===0?null:e("div",{className:"cm-corner"},u.map(b=>e($,{key:b.key,label:b.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(b.key==="model-top"?" cm-model-top":"")+(b.level==="ok"?"":" "+b.level)},b.text))))}function Xe(t,s,o){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const a=(m,p)=>{const b=new Date(t);return b.setUTCDate(b.getUTCDate()+m),b.setUTCHours(p,0,0,0),b.getTime()},n=new Set,i=Math.max(12,Math.min(380,(Array.isArray(o)?o.length:0)+7));for(let m=-i;m<=i;m+=1){n.add(a(m,16));for(const p of s){const b=Number(p?.start),x=Number(p?.end);!Number.isFinite(b)||!Number.isFinite(x)||(n.add(a(m,b)),n.add(a(x<=b?m+1:m,x)))}}const l=[...n].sort((m,p)=>m-p).flatMap(m=>{const p=Je(m-1,void 0,s,o),b=Je(m,void 0,s,o);return p===b?[]:[{at:m,intoPeak:b}]});let r=null,d=null;for(const m of l)m.at<=t&&(r===null||m.at>r.at)&&(r=m),m.at>t&&(d===null||m.at<d.at)&&(d=m);const u=ea(t,o),c=u??Xt(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:Je(t,void 0,s,o),weekend:!1,prevAtMs:r.at,nextAtMs:d.at,nextIntoPeak:d.intoPeak}}function et(t,s){if(!t||t.peakNotice===!1||t.peakEnabled!==!0)return null;const o=Date.parse(t.peakEffectiveAt||"");if(Number.isFinite(o)&&s<o)return null;const a=Array.isArray(t.peakWindows)?t.peakWindows:[];return Xe(s,a,t.peakHolidays)}function tt(t){return t.holiday===!0?{short:"holidayShort",chip:"holidayChip",notice:"holidayAllOffPeak"}:t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function ge(t,s,o){const a=Math.max(0,t.nextAtMs-s),n=Math.max(1,Math.ceil(a/6e4)),i=Math.floor(n/60),l=n%60;return i>0?l>0?o("countdownHourMinute",{h:i,m:l}):o("countdownHoursOnly",{h:i}):o("countdownMinute",{m:n})}const St="cm-peak-alert-preview";let ha=0;function Rn(t){const s=t.useCost?t.useCost(x=>x):void 0,o=s?.state?.config,[a,n]=L(Date.now()),[i,l]=L(null),[r,d]=L(null);if(X(()=>{const x=window.setInterval(()=>n(Date.now()),1e4);return()=>window.clearInterval(x)},[]),X(()=>{const x=k=>{const f=k.detail?.kind==="offpeak"?"offpeak":"peak";d(f);const v=s?.state?.config;if(v?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const S=K(_(v.locale));try{new Notification(S(f==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+S("peakAlertPreviewTag"),{body:S("peakAlertBody",{time:S("countdownMinute",{m:2}),phase:S(f==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(St,x),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(St,x),window.__cmPeakAlertLive=!1}},[]),X(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const x=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(x===null)return;const k=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",f=x.nextIntoPeak===!0;if(k!=="both"&&k!==(f?"peak":"offpeak"))return;const v=Number(o.peakAlertAhead),S=(Number.isFinite(v)&&v>=1?v:2)*6e4;if(a<x.nextAtMs-S||a>=x.nextAtMs||ha===x.nextAtMs)return;const w=K(_(o.locale));ha=x.nextAtMs;try{new Notification(w(f?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:w("peakAlertBody",{time:ge(x,a,w),phase:w(f?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[a]),!o||o.peakEnabled!==!0)return null;let u=null;if(o.peakAlertEnabled===!0){const x=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(x)&&a<x)){const k=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(k!==null){const f=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",v=Number(o.peakAlertAhead),S=(Number.isFinite(v)&&v>=1?v:2)*6e4;(f==="both"||f===(k.nextIntoPeak?"peak":"offpeak"))&&a>=k.nextAtMs-S&&a<k.nextAtMs&&i!==k.nextAtMs&&(u=k)}}}let c=null,g=!1,m=null;if(u!==null)c=u,g=u.nextIntoPeak===!0,m=()=>l(u.nextAtMs);else if(r!==null)c={nextAtMs:a+2*6e4,nextIntoPeak:r==="peak"},g=r==="peak",m=()=>d(null);else return null;const p=K(_(o.locale)),b=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+b+" "+(g?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},p(g?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},p(g?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},p("peakAlertBody",{time:ge(c,a,p),phase:p(g?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:m},p("peakAlertBtn"))))}function Ln(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:ge(i,a,o)}):o("nextOffPeakIn",{time:ge(i,a,o)});return e($,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"}),e("div",{className:"cm-peak-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(l.chip)+" · "+r)))}function En(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:ge(i,a,o)}):o("nextOffPeakIn",{time:ge(i,a,o)});return e($,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}}),e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"})),e("span",{className:"cm-peak-classic-chip"},o(l.chip)+" · "+r)))}function at(t,s,o){return e(s?.peakStyle==="classic"?En:Ln,{config:s,t:o})}function qn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:ge(i,a,o)}):o("nextOffPeakIn",{time:ge(i,a,o)}),d=[o(l.notice),r];return e($,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(i.weekend||i.holiday?"weekend":i.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:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(l.short))))}function In(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:ge(i,a,o)}):o("nextOffPeakIn",{time:ge(i,a,o)}),d=[o(l.notice),r];return e($,{label:d,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(i.weekend||i.holiday?"weekend":i.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:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(l.short))))}function Hn(t,s,o){return e(s?.peakStyle==="classic"?In:qn,{config:s,t:o})}function ya(t,s,o){const a=t.today,n=s.budget??{enabled:!1,amount:100,period:"month"},i=Number(s.exchangeRate),r=(t.budgetUsed??(n.period==="day"?z(t.today,s):n.period==="all"?z(t.total,s):z(t.month,s)))*(Number.isFinite(i)&&i>0?i:1),d=Math.max(0,Number(n.amount)||0),u=d>0?Math.min(999,r/d*100):null,c=ue(u===null?null:Math.min(100,u),te(s,"budget")),g=z(a,s)*(Number.isFinite(i)&&i>0?i:1),m=d>0?Math.min(999,g/d*100):null,p=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(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("budget")),e("span",{className:"cm-bbox-pct cm-num"},c.label===null?"—":c.label.toFixed(1)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:c.width+"%"}})),p?e(q,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},o("todayShare",{amount:Y(z(a,s),s),pct:m===null?"—":m.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:oe(r,s),amount:oe(d,s)}))):null,at(t,s,o))}}function ka(t,s,o){const a=t.goQuota,n=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",i=a[n],l=i!==null&&typeof i?.percent=="number"?Math.max(0,Math.min(100,Number(i.percent)||0)):0,r=p=>p!==null&&typeof p?.percent=="number"?Math.round(Math.max(0,Math.min(100,p.percent)))+"%":"—",d=p=>o(p==="rolling"?"goShortRolling":p==="weekly"?"goShortWeekly":"goShortMonthly"),u=["rolling","weekly","monthly"].filter(p=>p!==n),c=i!==null&&typeof i?.resetsAt=="string"&&i.resetsAt.length>0?o("goResetAt",{time:new Date(i.resetsAt).toLocaleString()}):"",g=s?.goQuota?.detail!==!1,m=ue(l,te(s,"go"));return{level:l>=100?"over":l>=80?"warn":"ok",rail:m.label===null?"—":Math.round(m.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+d(n)),e("span",{className:"cm-bbox-pct cm-num"},m.label===null?"—":Math.round(m.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:m.width+"%"}})),g?e(q,null,e("div",{className:"cm-bbox-line cm-num"},u.map(p=>d(p)+" "+r(a[p])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function Un(t){const{state:s,wide:o}=t,a=s.goQuota,n=K(_(s.config?.locale));if(!a||a.status!=="ok")return null;const i=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(a[i]===null||typeof a[i]?.percent!="number")return null;const l=ka(s,s.config,n),r=[n("goQuotaTitle"),n("goWindowRolling")+": "+(a.rolling===null?"—":Math.round(a.rolling.percent)+"%"),n("goWindowWeekly")+": "+(a.weekly===null?"—":Math.round(a.weekly.percent)+"%"),n("goWindowMonthly")+": "+(a.monthly===null?"—":Math.round(a.monthly.percent)+"%"+(a.monthly!==null&&typeof a.monthly.resetsAt=="string"&&a.monthly.resetsAt.length>0?" · "+n("goResetAt",{time:new Date(a.monthly.resetsAt).toLocaleString()}):"")),n("goQuotaFetchedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e($,{label:r,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(l.level==="ok"?"":" "+l.level)+(o?"":" rail")},o?l.body:e("div",{className:"cm-bbox-rail cm-num"},l.rail)))}function jn(t){return t===null||typeof t!="object"||t.unlimited||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function Qe(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function wa(t,s,o=Date.now()){if(typeof t!="string"||!t)return"";const a=Date.parse(t);if(!Number.isFinite(a))return"";const n=a-o;if(n<=0)return s("resetReached");const i=Math.ceil(n/6e4),l=Math.floor(i/1440),r=Math.floor(i%1440/60),d=i%60;return l>0?s("resetDays",{d:l,h:r}):r>0?s("resetHours",{h:r,m:d}):s("resetMinutes",{m:d})}function Fe(t,s,o=Date.now()){const a=wa(t?.resetsAt,s,o);return a?s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})+" ("+a+")":""}function nt(t,s,o){return t===null?"—":o(s==="remaining"?"quotaRemaining":"quotaUsed",{pct:t})}function st(t){const[,s]=L(0),o=()=>s(Date.now());return X(()=>{if(!t)return;const a=setInterval(o,6e4);return()=>clearInterval(a)},[t]),{onMouseEnter:o,onFocus:o}}function _e(t,s,o,a){const n=jn(s),i=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",l=ue(n,o),r=s?.unlimited?"∞":l.label===null?"—":l.label+"%";return{level:i,pct:n,text:r,label:l.label,row:e("div",{className:"cm-mm-row"+(i==="ok"?"":" "+i)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:l.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r))}}function xa(t){const{five:s,seven:o,fetchedAt:a,t:n,wide:i,refresh:l,direction:r="used"}=t,d=st(s?.resetsAt),u=wa(s?.resetsAt,n),c=_e(n("codingPlanRemain5h"),s,r,n),g=_e(n("codingPlanRemain7d"),o,r,n),m=c.level==="over"||g.level==="over"?"over":c.level==="warn"||g.level==="warn"?"warn":"ok",p=(f,v,S)=>{const w=v?.unlimited?n("quotaUnlimited"):nt(S.label,r,n),A=Fe(v,n);return f+" "+w+(A?" · "+A:"")},b=[n("codingPlanMinimaxTitle"),p(n("codingPlanRemain5h"),s,c),p(n("codingPlanRemain7d"),o,g),a>0?n("goQuotaFetchedAt",{time:new Date(a).toLocaleTimeString()}):null,...l?be(n,l):[]].filter(Boolean).join(`
|
|
3
|
-
`),x=e(q,null,e("div",{className:"cm-mm-title"},n("codingPlanMinimaxTitle")),c.row,
|
|
4
|
-
`),
|
|
5
|
-
`),f
|
|
6
|
-
`),B=w.map((O,G)=>O.text!=null?e("div",{key:G,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},O.name),e("span",{className:"cm-mm-text cm-num"},O.text)):e(q,{key:G},O.view.row)),P=O=>{if(!O.key||O.key==="Enter"||O.key===" "){O.stopPropagation(),O.preventDefault?.();const G=a.accounts[(x+1)%a.accounts.length];Vn(o.id,G.id),u({source:o.id,id:G.id})}},E=m?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:f||x+1}),onClick:P,onKeyDown:P,role:"button",tabIndex:0},`${x+1}/${a.accounts.length} ⇄`):null,h=m?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),E):e("div",{className:"cm-mm-title"},o.label||o.id),H=m&&f?e("div",{className:"cm-gw-sub"},f):null,ee=e(q,null,h,H,...B),he=w.filter(O=>O.view).map(O=>O.view.label).filter(O=>O!==null),xe=he.length>0?he.slice(0,2).map(O=>O+"%").join(" "):w[0].text??"—",D=e("div",{className:"cm-bbox-rail cm-num"},xe);return e($,{label:e("span",{style:{whiteSpace:"pre-line"}},T),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(A==="ok"?"":" "+A)+(i===!1?" rail":"")+(c.busy?" busy":""),...me(c.busy,c.run)},i===!1?e(q,null,D,E):ee))}function $n(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],i=[];for(const l of s.gatewayQuotas?.sources??[]){if(l.enabled===!1||l.display!=="sidebar"&&l.display!=="both")continue;const r=n.find(d=>d.id===l.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||i.push(e(Jn,{source:l,snapshot:r,state:t,wide:o,api:a}))}return i}const Zn={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function Xn(t){const s=t.useCost?t.useCost(b=>b):void 0;At(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=L(null),[n,i]=L({}),l=s?.state,r=t.api;if(!l)return null;const d=l.config,u=d.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(u.enabled!==!0)return null;const c=K(_(d?.locale)),g=[];if(u.budget!==!1){const b=d.budget??{enabled:!1,amount:100,period:"month"};if(b.enabled===!0){const x=Number(d.exchangeRate),f=(l.budgetUsed??(b.period==="day"?z(l.today,d):b.period==="all"?z(l.total,d):z(l.month,d)))*(Number.isFinite(x)&&x>0?x:1),v=Math.max(0,Number(b.amount)||0);if(v>0){const S=Math.min(999,f/v*100),w=S>=100?"over":S>=80?"warn":"ok";g.push({key:"budget",label:c("budgetShort"),level:w,tip:c("budgetOf",{period:c(Ee[b.period]??"periodMonth")})+" · "+c("usedOf",{used:oe(f,d),amount:oe(v,d)})+" · "+S.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(ue(Math.min(100,S),te(d,"budget")).width)}]})}}}if(u.go!==!1){const b=l.goQuota;if(d?.goQuota?.enabled!==!1&&b?.status==="ok"){const x=d.goQuota.main==="weekly"||d.goQuota.main==="monthly"?d.goQuota.main:"rolling",k=x==="rolling"?b.rolling:x==="weekly"?b.weekly:b.monthly;if(k!==null&&typeof k=="object"&&typeof k.percent=="number"){const f=Math.max(0,Math.min(100,Math.round(Number(k.percent)||0))),v=f>=100?"over":f>=80?"warn":"ok",S=typeof k.resetsAt=="string"&&k.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(k.resetsAt).toLocaleString()}):"";g.push({key:"go",label:"Go "+c(x==="rolling"?"goShortRolling":x==="weekly"?"goShortWeekly":"goShortMonthly"),level:v,tip:"Go: "+f+"%"+S,segs:[{name:"main",pct:Math.round(ue(f,te(d,"go")).width)}]})}}}if(u.plans!==!1)for(const b of Oe){const x=l.codingPlans?.[b.id];if(d.codingPlans?.[b.id]?.enabled!==!0||!x||x.status!=="ok")continue;const k=x.windows!==null&&typeof x.windows=="object"?x.windows:{},f=Object.entries(k);if(f.length===0)continue;const v=Zn[b.id]??b.id,S=[],w=[];let A=0,y=0;for(const[M,T]of f){const B=Pt(M,c),P=typeof T?.resetsAt=="string"&&T.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(T.resetsAt).toLocaleString()}):"",E=T!==null&&typeof T=="object"&&typeof T.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(T.percent)||0))):null;if(w.push(B+" "+(E===null?typeof T?.text=="string"?T.text:"—":E+"%")+P),E===null){S.push({name:M,pct:null,text:typeof T?.text=="string"?T.text:"—"});continue}y>=2||(y+=1,S.push({name:M,pct:Math.round(ue(E,te(d,"plan")).width)}),A=Math.max(A,E>=100?2:E>=80?1:0))}x.fetchedAt>0&&w.push(c("goQuotaFetchedAt",{time:new Date(x.fetchedAt).toLocaleTimeString()})),S.length!==0&&g.push({key:b.id,label:v,level:["ok","warn","over"][A],tip:w.join("; "),segs:S})}const m=d.codexQuotaEnabled===!0&&J.status==="ok"?J.windows.weekly??null:null;if(m!==null&&typeof m.percent=="number"){const b=Math.max(0,Math.min(100,Math.round(Number(m.percent)||0))),x=typeof m.resetsAt=="string"&&m.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(m.resetsAt).toLocaleString()}):"";g.push({key:"codex",label:"Codex",level:b>=100?"over":b>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+b+"%"+x,segs:[{name:"weekly",pct:Math.round(ue(b,te(d,"plan")).width)}]})}if(g.length===0)return null;const p=b=>{o!==null||!r||(a(b),i(x=>({...x,[b]:null})),Promise.resolve().then(()=>b==="budget"?r.reload():b==="go"?r.refreshGoQuota():b==="codex"?Ct(!0,d.codexQuotaEnabled===!0):r.refreshCodingPlan(b)).catch(x=>{i(k=>({...k,[b]:x?.message??String(x)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},g.map(b=>{const x=o===b.key,k=n[b.key],f=[e("span",{className:"cm-qlabel",key:"l"},b.label)];x?f.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):b.segs.forEach((S,w)=>{w>0&&f.push(e("span",{className:"cm-qsep",key:"sep"+w,"aria-hidden":"true"})),S.pct===null?f.push(e("span",{className:"cm-qtext",key:S.name},S.text)):f.push(e("span",{className:"cm-qseg",key:S.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:S.pct+"%"}})),e("span",null,S.pct+"%")))});const v=[b.tip];return!x&&r&&v.push(c("clickToRefresh")),x&&v.push(c("refreshing")),k&&v.push("⚠ "+c("balanceRefreshFailed",{message:k})),e($,{key:b.key,label:v.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(b.level==="ok"?"":" "+b.level),...r?me(x,()=>p(b.key)):{}},f))}))}const Na="dsh-cost-meter:simple-guide-dismissed";function Mt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Na)==="1"}catch{return!1}}function es(t){const s=t.useCost?t.useCost(p=>p):void 0,o=ke(!1),[a,n]=L(!1),[i,l]=L(!1),[r,d]=L(!1),u=s?.state?.config;if(!u||r||Mt(u))return null;const c=K(_(u.locale)),g=()=>{d(!0);try{window.localStorage.setItem(Na,"1")}catch{}},m=async p=>{if(!o.current){o.current=!0,n(!0),l(!1);try{if((await t.api.updateConfig({sidebarSimple:p,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==p)throw new Error;g()}catch{l(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:p=>{p.key==="Escape"&&(p.stopPropagation(),g())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:g},"×")),e("p",null,c("sidebarSimpleBody")),i?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>m(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>m(!0)},c("sidebarSimpleOn"))))}function ts(t){const s=t.useCost?t.useCost(r=>r):void 0,o=ke(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Mt(n)||n.quotaStrip?.promptSeen===!0)return null;const i=K(_(n?.locale)),l=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":i("quotaStripGuideTitle")},e("h4",null,i("quotaStripGuideTitle")),e("p",null,i("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>l(!1)},i("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>l(!0)},i("quotaStripGuideOn"))))}const Sa="dsh-cost-meter:balance-click-hint-seen",as=()=>{try{return window.localStorage.getItem(Sa)==="1"}catch{return!1}},ns=()=>{try{window.localStorage.setItem(Sa,"1")}catch{}};function ss(t){const s=t.useCost?t.useCost(p=>p):void 0,o=ke(!1),[a,n]=L(!1),[i]=L(as),l=s?.state;if(!l)return null;const r=l.config,d=r.balance?.display==="sidebar"||r.balance?.display==="both",u=(r?.customBalances??[]).some(p=>p?.enabled===!0&&(p.display==="sidebar"||p.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Oe.some(p=>{const b=r.codingPlans?.[p.id];return b?.enabled===!0&&(b.display==="sidebar"||b.display==="both")});if(a||i||r.balance?.clickHintSeen===!0||!d&&!u&&!c||!Mt(r)||r.quotaStrip?.promptSeen!==!0)return null;const g=K(_(r?.locale)),m=()=>{o.current!==!0&&(n(!0),o.current=!0,ns(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":g("balanceClickGuideTitle")},e("h4",null,g("balanceClickGuideTitle")),e("p",null,g("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:m},g("balanceClickGuideOk"))))}function Tt(t){const{state:s,wide:o}=t,a=s.today,n=s.config,i=K(_(n?.locale)),l=n.budget??{enabled:!1,amount:100,period:"month"},r=Number(n.exchangeRate),u=(s.budgetUsed??(l.period==="day"?z(s.today,n):l.period==="all"?z(s.total,n):z(s.month,n)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),g=c>0?Math.min(999,u/c*100):null,m=g===null?"ok":g>=100?"over":g>=80?"warn":"ok";if(l.enabled===!0){const b=z(a,n),x=b*(Number.isFinite(r)&&r>0?r:1),k=c>0?Math.min(999,x/c*100):null,f=[i("budgetOf",{period:i(Ee[l.period]??"periodMonth")}),i("usedOf",{used:oe(u,n),amount:oe(c,n)})+" · "+(g===null?"—":g.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[i("todayShare",{amount:Y(b,n),pct:k===null?"—":k.toFixed(1)+"%"})],i("monthTotal",{month:Y(z(s.month,n),n),total:Y(z(s.total,n),n)})].join("; ");if(t.summary===!0)return e($,{label:f,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(m==="ok"?"":" "+m),tabIndex:0},e("span",null,i("todayBudget",{period:i(Ee[l.period]??"periodMonth")})),e("span",{className:"cm-num"},Y(b,n)+" / "+oe(c,n))));const v=ya(s,n,i);return e($,{label:f,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(m==="ok"?"":" "+m)+(o?"":" rail")},o?v.body:e("div",{className:"cm-bbox-rail cm-num"},v.rail)))}const p=[i("todayCostTitle"),i("callsTokens",{calls:a.calls,input:U(a.input),cache:U(a.cacheRead+a.cacheWrite),output:U(a.output)}),i("monthCost",{amount:Y(z(s.month,n),n)}),i("totalCost",{amount:Y(z(s.total,n),n)})].join("; ");return e($,{label:p,side:"right",delayMs:300},e(q,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(q,null,i("today")," ",e("span",{className:"cm-num"},Y(z(a,n),n))):e(Ze,{size:16})),o?at(s,n,i):null))}function os(t){const s=t.useCost?t.useCost(E=>E):void 0;At(s?.state?.config?.codexQuotaEnabled===!0);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}ca(t,o);const a=s?.state,n=!!t.wide,i=ke(null);if(X(()=>{const E=i.current,h=E?.parentElement;if(!E||!h)return;const H=()=>{n?h.firstElementChild!==E&&h.insertBefore(E,h.firstElementChild):h.lastElementChild!==E&&h.appendChild(E)};H();const ee=new MutationObserver(()=>{E.isConnected&&H()});return ee.observe(h,{childList:!0}),n?(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap=""):(h.style.flexDirection="column",h.style.flexWrap="nowrap",h.style.alignItems="center",h.style.gap="6px"),()=>{ee.disconnect(),n||(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap="")}},[n,a]),!a)return null;const l=a.config,r=K(_(l?.locale)),d=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,c=Nt(a,l).length>0,g=d&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",m=c&&l.balance?.showProgressBar===!0,p=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",b=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[p]!==null,x=Oe.map(E=>E.id).filter(E=>{const h=l.codingPlans?.[E];if(h?.enabled!==!0||h.display!=="sidebar"&&h.display!=="both")return!1;const H=a.codingPlans?.[E];if(H?.status!=="ok")return!1;const ee=H.windows!==null&&typeof H.windows=="object"?H.windows:{};return Object.keys(ee).length>0}),k=x.length>0,f=$n(a,l,n,t.api),v=l.codexQuotaEnabled===!0&&J.status==="ok"&&J.windows.weekly!==null,S=(l.budget??{}).enabled===!0,w=l.sidebar!==!1&&l.hideTodayCost!==!0,A=l.sidebarModels?.enabled===!0;if(!A&&!d&&!c&&!b&&!k&&!v&&!S&&!w&&f.length===0)return null;const y=l.sidebarSimple===!0,M=!y&&n&&l.sidebarStyle==="compact",T=y&&n&&w&&S,B=[];T?B.push(e(Tt,{state:a,wide:n,summary:!0})):y&&n&&w&&B.push(e("div",{className:"cm-simple-summary"},e("span",null,r("today")),e("span",{className:"cm-num"},Y(z(a.today,l),l)))),g?B.push(e(An,{state:a,wide:n,api:t.api})):d&&B.push(e(Cn,{state:a,wide:n,api:t.api})),m?B.push(e(Mn,{state:a,wide:n,api:t.api})):c&&B.push(e(Bn,{state:a,wide:n,api:t.api}));const P=B.length;if(k&&B.push(...x.map(E=>E==="minimax"?e(Qn,{state:a,wide:n,api:t.api}):e(Yn,{id:E,state:a,wide:n,api:t.api}))),B.push(...f),v&&B.push(e(Kn,{state:a,wide:n,api:t.api})),b&&S&&n&&!y){const E=ka(a,l,r),h=ya(a,l,r),H=E.level==="over"||h.level==="over"?"over":E.level==="warn"||h.level==="warn"?"warn":"ok";B.push(e("div",{className:"cm-bbox cm-bbox-pair"+(H==="ok"?"":" "+H)},e("div",{className:"cm-bbox-section"+(E.level==="ok"?"":" "+E.level)},E.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(h.level==="ok"?"":" "+h.level)},h.body)))}else b&&B.push(e(Un,{state:a,wide:n})),S&&!T&&B.push(e(Tt,{state:a,wide:n}));return!S&&w&&!(y&&n)&&B.push(e(Tt,{state:a,wide:n})),y&&n&&w&&B.push(at(a,l,r)),n||B.push(Hn(a,l,r)),A&&B.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?P:B.length,0,e(ls,{key:"models",state:a,wide:n})),e("div",{ref:i,...y?{tabIndex:0,role:"region","aria-label":r("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(M?" compact":"")+(y?" simple":"")},...B)}const Bt={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Ca="dsh-cost-meter:models-open";function Aa(t,s,o){return Ta(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:Lt(a.key),cost:z(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function ls({state:t,wide:s}){const o={...Bt,...t.config.sidebarModels},a=K(_(t.config.locale)),n=()=>{try{const f=o.remember?window.localStorage.getItem(Ca):null;if(f!==null)return f==="1"}catch{}return o.defaultOpen},[i,l]=L(n),[r,d]=L(o.period);X(()=>d(o.period),[o.period]),X(()=>l(n()),[o.defaultOpen,o.remember]);const u=Aa(t,r,a),c=u.reduce((f,v)=>f+v.cost,0),g=f=>Y(f,t.config),m=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+g(c)+" · "+a("modelsCount",{n:u.length}),p=o.summary==="top"&&u.length?u[0].label+" "+g(u[0].cost):m,b=o.summary==="top"&&u.length?e(q,null,e("span",{className:"cm-bal-label"},u[0].label),e("span",{className:"cm-bal-amt"},g(u[0].cost))):e("span",{className:"cm-bal-label"},p),x=()=>{l(!i);try{o.remember&&window.localStorage.setItem(Ca,i?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:p+" · "+m},s?b:e(Ze,{size:16}));const k=u.slice(0,o.topN);return u.length>o.topN&&k.push(u.slice(o.topN).reduce((f,v)=>{for(const S of["cost","input","output","cacheRead","cacheWrite"])f[S]+=v[S];return f},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(i),title:m,onClick:x},e("span",{className:"cm-caret"+(i?" open":"")}),b),i?e(q,null,e("div",{className:"cm-buttons"},["today","history"].map(f=>e("button",{key:f,type:"button",className:"cm-mstats-tab"+(r===f?" active":""),"aria-pressed":r===f,onClick:()=>d(f)},a(f==="today"?"modelStatsToday":"modelStatsHistory")))),k.length?k.map(f=>e("div",{key:f.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:f.label},f.label),e("span",{className:"cm-num cm-bal-amt"},g(f.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?f.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?f.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+U(f.input)+" · "+a("modelStatsCache")+" "+U(f.cacheRead+f.cacheWrite)+" · "+a("modelStatsOutput")+" "+U(f.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function is({draft:t,setDraft:s,t:o}){const a={...Bt,...t?.sidebarModels},n=(l,r)=>{t&&s({...t,sidebarModels:{...a,[l]:r}})},i=(l,r)=>e("div",{className:"cm-field",key:l},e("label",null,o("models_"+l)),e("select",{className:"cm-input",value:a[l],onChange:d=>n(l,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(l=>e("label",{key:l,className:"cm-check"},e("input",{type:"checkbox",checked:a[l],onChange:r=>n(l,r.target.checked)}),o("models_"+l))),i("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),i("summary",[["total","modelsTotal"],["top","modelsTop"]]),i("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(l=>e("div",{key:l,className:"cm-field"},e("label",null,o("models_"+l)),ae({value:a[l]},r=>n(l,Math.max(l==="topN"?1:10,Math.min(l==="topN"?10:60,Math.floor(r))))))))}function Dt(t){return e("div",{className:"cm-card"},e("p",{className:"cm-card-title"},t.title),e("div",{className:"cm-card-value cm-num"},t.value),e("p",{className:"cm-card-sub"},t.sub))}const De=(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 rs(t){const{state:s,api:o}=t,a=K(_(s.config?.locale)),[n,i]=L(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},De(n,()=>i(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(cs,{state:s,api:o})):null)}function cs(t){const{state:s,api:o}=t,a=K(_(s.config?.locale)),[n,i]=L(null),[l,r]=L({}),[d,u]=L(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const g=p=>{if(n===p){i(null);return}i(p),!(l[p]!==void 0||d.has(p))&&(u(b=>{const x=new Set(b);return x.add(p),x}),o.getDaySessions(p).then(b=>r(x=>({...x,[p]:Array.isArray(b?.sessions)?b.sessions:[]}))).catch(()=>r(b=>({...b,[p]:"error"}))).finally(()=>u(b=>{const x=new Set(b);return x.delete(p),x})))},m=p=>p.map(b=>e("tr",{key:b.id},Ot(b,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(b.calls)),e("td",{className:"num"},U(b.input)),e("td",{className:"num"},U(b.cacheRead+b.cacheWrite)),e("td",{className:"num"},U(b.output)),e("td",{className:"num"},Y(z(b,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(p=>{const b=e("tr",{key:p.date,className:"cm-row-click",onClick:()=>g(p.date)},e("td",null,(n===p.date?"▾ ":"▸ ")+p.date),e("td",{className:"num"},String(p.calls)),e("td",{className:"num"},U(p.input)),e("td",{className:"num"},U(p.cacheRead+p.cacheWrite)),e("td",{className:"num"},U(p.output)),e("td",{className:"num"},Y(z(p,s.config),s.config)));if(n!==p.date)return[b];const x=l[p.date],k=d.has(p.date)&&x===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):x==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(x)||x.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,m(x)));return[b,e("tr",{key:p.date+"-sessions"},e("td",{colSpan:6},k))]}))))}function ds(t){const{state:s,api:o}=t,a=K(_(s.config?.locale)),[n,i]=L(!1),[l,r]=L(100),[d,u]=L("cost-desc"),[c,g]=L(null),[m,p]=L(!1),[b,x]=L(!1),k=Le.useRef(0),f=(A,y)=>{const[M,T]=y==="recent"?["recent","desc"]:y.split("-"),B=++k.current;p(!0),x(!1),o.getTopSessions(A,M,T).then(P=>{B===k.current&&g(Array.isArray(P?.sessions)?P.sessions:[])}).catch(()=>{B===k.current&&x(!0)}).finally(()=>{B===k.current&&p(!1)})},v=()=>{i(A=>{const y=!A;return y&&c===null&&!m&&f(l,d),y})},S=A=>{r(A),(n||c!==null)&&f(A,d)},w=A=>{u(A),(n||c!==null)&&f(l,A)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},De(n,v,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:d,onChange:A=>w(A.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(l),onChange:A=>S(Number(A.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),m?e("p",{className:"cm-empty"},a("sessionRankLoading")):b?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(A=>e("tr",{key:A.date+":"+A.id},e("td",null,A.date),Ot(A,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(A.calls)),e("td",{className:"num"},U(A.input)),e("td",{className:"num"},U((A.cacheRead??0)+(A.cacheWrite??0))),e("td",{className:"num"},U(A.output)),e("td",{className:"num"},Y(z(A,s.config),s.config)))))))):null)}function us(t){const{state:s}=t,o=K(_(s.config?.locale)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(i=>e("tr",{key:i.id},Ot(i,n,o),e("td",{className:"num"},String(i.calls)),e("td",{className:"num"},U(i.input)),e("td",{className:"num"},U(i.cacheRead+i.cacheWrite)),e("td",{className:"num"},U(i.output)),e("td",{className:"num"},Y(z(i,s.config),s.config)))))))}function Ot(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",i=a.length>0?a:n,l=a.length>0?a+" · "+t.id:t.id;return e("td",{title:l},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},i),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const ms={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function ps(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=o?.budget??i.budget,r=Number(i.exchangeRate),u=(s.budgetUsed??(l.period==="day"?z(s.today,i):l.period==="all"?z(s.total,i):z(s.month,i)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),g=l.enabled&&c>0?Math.min(999,u/c*100):null,m=g===null?"ok":g>=100?"over":g>=80?"warn":"ok",p=(k,f)=>{o!==null&&a({...o,budget:{...o.budget??i.budget,[k]:f}})},b=l.period==="custom"?l.customStart+" → "+(l.customEnd??n("periodDay")):null,x=l.enabled&&g!==null?n("budgetStatus",{period:n(Ee[l.period]??"periodMonth"),amount:oe(c,i),used:oe(u,i),pct:g.toFixed(1)})+(m==="over"?n("overLimit"):m==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:l.enabled===!0,onChange:k=>p("enabled",k.target.checked)}),e("span",null,n("enableBudget")))),l.enabled?e(q,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(m==="ok"?"":m),style:{width:(g===null?0:Math.min(100,g))+"%"}})),e("div",{className:"cm-budget-line"+(m==="over"?" over":"")+" cm-num"},x),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ae({value:l.amount},k=>p("amount",k))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:l.period,onChange:k=>p("period",k.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),l.period==="custom"?e(q,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:l.customStart??"",onChange:k=>p("customStart",k.target.value===""?null:k.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:l.customEnd??"",onChange:k=>p("customEnd",k.target.value===""?null:k.target.value)}))):null),b!==null?e("p",{className:"cm-hint"},n("rangeText",{range:b})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function fs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=(c,g)=>{o!==null&&a({...o,[c]:g})},r=o===null?i:{...i,...o},d=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),g=Date.now();if(Number.isFinite(c)&&g<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const m=r.peakWindows??[],p=Xe(g,m,r.peakHolidays);return p===null?n("offPeakActive"):p.holiday===!0?n("holidayAllOffPeak"):p.weekend===!0?n("weekendAllOffPeak"):p.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.locale)==="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=>l("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>l("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>l("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>l("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const g=Number(c.target.value);Number.isInteger(g)&&g>=1&&g<=30&&l("peakAlertAhead",g)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>l("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>l("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{l("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?at(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},u),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>l("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ae(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const i=Number(n);Number.isFinite(i)&&i>=0&&s(i)}})}function Rt(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:i,t:l}=t,r=Ve(o),d=m=>{const p={...Ve(m)};if(Array.isArray(m.rateHistory)){const b=m.rateHistory.filter(x=>Date.parse(x.before)<=Date.now());b.length>0?p.rateHistory=b:delete p.rateHistory}return p},u=(m,p,b)=>{if(b===null){if(a){const M=d(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),T={...M[m]??{}};delete T[p];const B={...M};Object.keys(T).length>0?B[m]=T:delete B[m],i({...n,prices:{...n.prices,default:B}});return}const S={...n.prices.models},w=d(S[s]??{cacheHit:0,cacheMiss:0,output:0}),A={...w[m]??{}};delete A[p];const y={...w};Object.keys(A).length>0?y[m]=A:delete y[m],S[s]=y,i({...n,prices:{...n.prices,models:S}});return}const x=Math.max(0,b);if(a){let w={...d(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(m==="base")w[p]=x;else{const A={...w[m]??{},[p]:x};w={...w,[m]:A}}i({...n,prices:{...n.prices,default:w}});return}const k={...n.prices.models},f=d(k[s]??{cacheHit:0,cacheMiss:0,output:0});let v={...f};if(m==="base")v[p]=x;else{const S={...f[m]??{},[p]:x};v={...f,[m]:S}}k[s]=v,i({...n,prices:{...n.prices,models:k}})},c=()=>{const m={...n.prices.models};delete m[s],i({...n,prices:{...n.prices,models:m}})},g=(m,p)=>{const b=p==="base"?r:r[p]??null,x=p==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:p},e("span",null,m),ae({value:b?.cacheHit??null,emptyMode:x},k=>u(p,"cacheHit",k)),ae({value:b?.cacheMiss??null,emptyMode:x},k=>u(p,"cacheMiss",k)),ae({value:b?.output??null,emptyMode:x},k=>u(p,"output",k)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(q,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},l("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},l("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},l("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatCached")),e("span",null,l("flatInput")),e("span",null,l("flatOutput"))),g(l("tierBase"),"base"),g(l("tierOffPeak"),"offPeak"),g(l("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},l("datedPriceNote")):null)}const Pa={deepseek:"DeepSeek",openai:"OpenAI",anthropic:"Anthropic",google:"Google Gemini",moonshot:"Moonshot (Kimi)","z-ai":"Z.ai / 智谱",xai:"xAI",alibaba:"阿里云百炼",minimax:"MiniMax",tencent:"腾讯混元",xiaomi:"小米",upstage:"Upstage",nvidia:"NVIDIA",mistral:"Mistral",meta:"Meta",meituan:"美团 LongCat","opencode-go":"OpenCode Go"};function bs(t,s,o="USD"){if(t=Ve(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");const a=i=>(o==="CNY"?"¥":"$")+String(i),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function gs(t){const{state:s,draft:o,setDraft:a,t:n}=t,[i,l]=L(!1),[r,d]=L({}),u=s.priceCatalog;if(u===null||typeof u!="object")return null;const c=o?.prices??s.config.prices,g=o?.priceTableDisplay??s.config.priceTableDisplay??{},m=(y,M)=>{const T=g[y+":"+M];return typeof T=="boolean"?T:y==="deepseek"},p=(y,M,T)=>{o!==null&&a({...o,priceTableDisplay:{...g,[y+":"+M]:T}})},b=(y,M)=>y==="deepseek"?c.models?.[M]!==void 0:c.providers?.[y]?.models?.[M]!==void 0,x=(y,M,T)=>{if(o===null)return;const B=JSON.parse(JSON.stringify(T));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[M]:B}}});return}const P={...o.prices.providers??{}},E=P[y]??{};P[y]={...E,models:{...E.models??{},[M]:B}},a({...o,prices:{...o.prices,providers:P}})},k=(y,M)=>{if(o===null)return;if(y==="deepseek"){const P={...o.prices.models};delete P[M],a({...o,prices:{...o.prices,models:P}});return}const T={...o.prices.providers??{}},B=T[y];if(B!==void 0&&B.models!==void 0){const P={...B.models};delete P[M],T[y]={...B,models:P},a({...o,prices:{...o.prices,providers:T}})}},f=Object.keys(u).sort((y,M)=>y==="deepseek"?-1:M==="deepseek"?1:y.localeCompare(M)),v=y=>Object.values(u[y]).reduce((M,T)=>M+Object.keys(T).length,0),S=new Set(Object.values(u.deepseek??{}).flatMap(y=>Object.keys(y))),w=Object.keys(c.models??{}).filter(y=>!S.has(y)).sort(),A=(y,M,T)=>{const B=b(y,M),P=m(y,M),E=B?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:P,onChange:h=>p(y,M,h.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(B&&!P&&o!==null){const h=y==="deepseek"?e(Rt,{key:M,modelId:M,entry:c.models[M],isDefault:!1,draft:o,setDraft:a,t:n}):e(Da,{key:M,provider:y,modelId:M,entry:c.providers?.[y]?.models?.[M],draft:o,setDraft:a,t:n});return e("div",{key:M,className:"cm-catalog-mounted"},E,h)}return e("div",{key:M,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},M),e("span",{className:"cm-catalog-price"},bs(T,n,y==="deepseek"?c.currency:"USD")),B?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,E,e("button",{className:"cm-btn small",disabled:!B&&T?.unpriced===!0,onClick:()=>B?k(y,M):x(y,M,T)},n(B?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>l(y=>!y)},n(i?"catalogCollapse":"catalogOpen"))),i?e(q,null,e("p",{className:"cm-note"},n("catalogNote")),f.map(y=>{const M=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>d(T=>({...T,[y]:!M}))},e("span",null,(M?"▾ ":"▸ ")+(Pa[y]??y)+" · "+v(y))),M?e(q,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(u[y]).sort().map(T=>e("div",{key:T},e("div",{className:"cm-catalog-family"},T),Object.keys(u[y][T]).sort().map(B=>A(y,B,u[y][T][B])))),y==="deepseek"&&w.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),w.map(T=>A("deepseek",T,null))):null):null)})):null)}const Ma=t=>t==="zen"?"go":t,Lt=t=>{const s=t.indexOf(":");return s<=0?t:Ma(t.slice(0,s).toLowerCase())+t.slice(s)};function Ta(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],i=u=>Number.isFinite(Number(u))&&Number(u)>0?Number(u):0,l=(u,c,g)=>{if(!g||typeof g!="object")return;const m=u[c]??(u[c]=Object.fromEntries([...n,"apiCost"].map(b=>[b,0])));for(const b of n)m[b]+=i(g[b]);const p=c.indexOf(":");m.apiCost+=i(g.apiCost??(He(p>0?c.slice(0,p):"deepseek",p>0?c.slice(p+1):c,s)==="plan"?0:g.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(([g,m])=>[g.includes(":")?g:"deepseek:"+g,m]));const c={};for(const g of Array.isArray(u.sessions)?u.sessions:[])if(!(!g||typeof g!="object"))if(g.byProviderModel&&Object.keys(g.byProviderModel).length)for(const[m,p]of Object.entries(g.byProviderModel))l(c,m,p);else l(c,(g.provider||"deepseek")+":"+(g.model||"unknown"),g);return Object.keys(c).length?c:n.some(g=>i(u[g])>0)?{"deepseek:legacy":u}:{}};return(u=>{const c={},g=m=>{for(const[p,b]of Object.entries(m??{}))l(c,p,b)};if(u==="today")g(r(t.today));else{const m=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const p of t.history??[]){const b=Date.parse(p.date+"T00:00:00Z");b<=m&&b>=m-76896e5&&g(r(p))}}return Object.entries(c).map(([m,p])=>{const b=m.indexOf(":"),x=(b>0?m.slice(0,b):"deepseek").toLowerCase(),k=b>0?m.slice(b+1):m,f=p.input+p.output+p.cacheRead+p.cacheWrite+p.reasoning,v=p.cacheRead+p.input;return{label:m==="deepseek:legacy"?o("modelStatsLegacy"):x==="deepseek"||x===""?k:Ma(x)+":"+k,key:m,...p,tokens:f,cls:He(x,k,s),hitRate:v>0?p.cacheRead/v:null,cacheUnreported:dn(p),blended:f>0&&p.cost>0?p.cost/f*1e6:null,perUsd:p.cost>0?f/p.cost:null}}).filter(m=>m.tokens>0||m.cost>0)})(a).sort((u,c)=>c.cost-u.cost||c.tokens-u.tokens)}function hs(t){const{state:s,config:o,t:a,initialTab:n}=t,[i,l]=L(n==="history"?"history":"today"),[r,d]=L(!1),u=Ta(s,o,a,i),c=f=>(Math.max(0,Math.min(1,f))*100).toFixed(1)+"%",g=u.reduce((f,v)=>Math.max(f,v.cost),0),m=u.reduce((f,v)=>Math.max(f,v.tokens),0),p=u.reduce((f,v)=>Math.max(f,v.perUsd??0),0),b=(f,v)=>e("button",{className:"cm-mstats-tab"+(i===f?" active":""),onClick:()=>l(f)},v),x=f=>f.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,k=(f,v,S,w,A)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:f},f,A??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+S,style:{width:c(v)}})),e("span",{className:"cm-mstats-val"},w));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},De(r,()=>d(!r),a("modelStatsTitle"))),r?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},b("today",a("modelStatsToday")),b("history",a("modelStatsHistory"))),u.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(q,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),u.map(f=>e(q,{key:"c:"+f.label},k(f.label,g>0?f.cost/g:0,"cost",Y(f.cost,o),e(q,null,x(f),f.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...u].sort((f,v)=>v.tokens-f.tokens).map(f=>e("div",{className:"cm-mstats-row",key:"t:"+f.label},e("span",{className:"cm-mstats-name",title:f.label},f.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:c(m>0?f.input/m:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:c(m>0?(f.cacheRead+f.cacheWrite)/m:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:c(m>0?(f.output+f.reasoning)/m:0)}})),e("span",{className:"cm-mstats-val"},U(f.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...u].sort((f,v)=>(v.hitRate??-1)-(f.hitRate??-1)).map(f=>e(q,{key:"h:"+f.label},k(f.label,f.hitRate??0,"hit",f.cacheUnreported?a("modelStatsHitUnreported"):f.hitRate===null?"—":(f.hitRate*100).toFixed(1)+"%",f.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...u].sort((f,v)=>(v.perUsd??-1)-(f.perUsd??-1)).map(f=>e(q,{key:"v:"+f.label},k(f.label,p>0?(f.perUsd??0)/p:0,"value",f.perUsd===null?"—":U(f.perUsd)+" tok/$"+(f.blended!==null?" · "+a("modelStatsBlended",{price:"$"+f.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function ys(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 ks(t,s){if(t==="go")return"OpenCode Go";const o=Oe.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const Ba=["fiveHour","weekly","monthly","daily"];function ws(t,s){const o=new Map,a=n=>{const i=new Date(n),l=r=>String(r).padStart(2,"0");if(s==="monthly")return i.getFullYear()+"-"+l(i.getMonth()+1);if(s==="weekly"){const r=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(i.getDay()+6)%7);return r.getFullYear()+"-"+l(r.getMonth()+1)+"-"+l(r.getDate())}return i.getFullYear()+"-"+l(i.getMonth()+1)+"-"+l(i.getDate())};for(const n of Object.values(t??{}))for(const i of n??[]){if(i===null||typeof i!="object"||!(i.tokens>0)&&!(i.cost>0))continue;const l=a(Number(i.t1)||Number(i.t0)),r=o.get(l)??{key:l,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(i.tokens)||0,r.cost+=Number(i.cost)||0,r.pct+=Number(i.pct)||0,r.intervals+=1,o.set(l,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,i)=>n.key<i.key?-1:n.key>i.key?1:0)}function xs(t){const{state:s,config:o,t:a}=t,[n,i]=L(!1),[l,r]=L("daily"),d=_(o?.locale),u=s?.planStats,c=u!=null&&typeof u.providers=="object"?u.providers:{},g=Object.keys(c).sort(),m=y=>Y(Number(y)||0,o??s?.config),p=y=>y.method==="none"||y.per1Tokens===null?"—":U(y.per1Tokens)+" tok · "+m(y.per1Cost),b=y=>y.method==="none"||y.fullTokens===null?"—":U(y.fullTokens)+" tok · "+m(y.fullCost),x=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),k=y=>{let M=x(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(M=a("planStatsMethodSampleAt",{method:M,time:new Date(Number(y.sampleAt)).toLocaleString(d==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(M+=" · "+a("planStatsConfidenceLow")),M},f=([y,M,T])=>e("tr",{key:M+":"+y},e("td",null,ys(y,d)),e("td",{className:"num"},Math.round(T.percent*10)/10+"%"),e("td",{className:"num"},U(T.localTokens)+" tok · "+m(T.localCost)),e("td",{className:"num"},p(T)),e("td",{className:"num"},b(T)),e("td",{className:"num cm-plan-reset"},T.resetsAt.length>0?a("planStatsResets",{time:new Date(T.resetsAt).toLocaleString(d==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},k(T))),v=n?g.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,M])=>({winKey:y,list:M})):[],S=ws(Object.fromEntries(v.map(y=>[y.winKey,y.list])),l),w=S.reduce((y,M)=>Math.max(y,M.fullTokens??0),0),A=(y,M)=>e("button",{key:y,className:"cm-mstats-tab"+(l===y?" active":""),onClick:()=>r(y)},M);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},De(n,()=>i(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},g.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(q,null,g.map(y=>{const M=c[y]?.windows??{},T=[...Ba.filter(B=>M[B]!==void 0).map(B=>[B,y,M[B]]),...Object.keys(M).filter(B=>!Ba.includes(B)).map(B=>[B,y,M[B]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},ks(y,a),e("span",{className:"cm-plan-updated"},(()=>{const B=Number(c[y]?.generatedAt)||Number(u?.generatedAt)||0;return B>0?new Date(B).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,T.map(f))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},A("daily",a("planStatsDaily")),A("weekly",a("planStatsWeekly")),A("monthly",a("planStatsMonthly"))),S.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(q,null,[...S].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(w>0?(y.fullTokens??0)/w*100:0).toFixed(1)+"%"}})),e($,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":U(y.fullTokens),per1:y.per1Tokens===null?"—":U(y.per1Tokens),tokens:U(y.tokens),cost:m(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":U(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Da(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:i,t:l}=t,r=c=>{const g={...n.prices.providers??{}},m=g[s]??{};g[s]={...m,models:c},i({...n,prices:{...n.prices,providers:g}})},d=(c,g)=>{if(n===null)return;const m={...(n.prices.providers??{})[s]?.models??{}};m[o]={...m[o]??{},[c]:Math.max(0,g)},r(m)},u=()=>{if(n===null)return;const c={...(n.prices.providers??{})[s]?.models??{}};delete c[o],r(c)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(q,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},l("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:u},l("unmountBtn")))),a?.unpriced===!0?null:e(q,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatInput")),e("span",null,l("flatCached")),e("span",null,l("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ae({value:a?.input??null,emptyMode:"ignore"},c=>d("input",c)),ae({value:a?.cachedInput??null,emptyMode:"ignore"},c=>d("cachedInput",c)),ae({value:a?.output??null,emptyMode:"ignore"},c=>d("output",c)))))}const We=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Et=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function vs(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),[d,u]=L(null),c=s.balance,g=s.config,m=s.reconcile,p=(n?.balance??g.balance??{}).reconcile!==!1,b=v=>{n===null||typeof i!="function"||i({...n,balance:{...n.balance??g.balance??{},reconcile:v.target.checked}})},x=async()=>{if(!l){r(!0),u(null);try{const v=await o.refreshBalance();u({kind:v.ok?"ok":"err",text:v.message})}catch(v){u({kind:"err",text:a("balanceRefreshFailed",{message:v?.message??String(v)})})}finally{r(!1)}}},k=v=>we(v,g,c?.currency),f=c.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:k(c.totalBalance),granted:k(c.grantedBalance),toppedUp:k(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:c.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:x,disabled:l},a(l?"refreshing":"refreshBalance"))),f,m!==void 0&&m.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+m.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:p,onChange:b}),a("reconcileLabel")),Et(d))}function ot(t){const{name:s,enabled:o,saved:a,busy:n,open:i,statusNode:l,configNode:r,errorMsg:d,onToggle:u,onRefresh:c,onRemove:g,onToggleOpen:m,t:p}=t,b=r!=null;return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":p("enable")+": "+s,checked:o===!0,onChange:x=>u(x.target.checked)})),e("div",{className:"cm-quota-name"},b?De(i===!0,m,s):e("h3",{className:"cm-h"},s)),g?e("button",{className:"cm-btn small",onClick:g},p("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:c,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?p("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?p("quotaRefreshReady"):p("refresh")},p(n===!0?"refreshing":"refresh"))),l,b&&i===!0?e("div",{className:"cm-collapse-body"},r):null,d!=null?e("div",{className:"cm-msg "+d.kind},d.text):null)}function lt(t,s){const[o,a]=L(!1),[n,i]=L(null),l=ke(!1);return[o,n,async()=>{if(!l.current){l.current=!0,a(!0),i(null);try{const d=await s();i({kind:d.ok?"ok":"err",text:d.message})}catch(d){i({kind:"err",text:t("syncFailed",{message:d?.message??String(d)})})}finally{l.current=!1,a(!1)}}}]}const Ns=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},Oa=(t,s,o,a,n,i=s)=>{if(typeof o?.percent!="number")return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const l=Math.max(0,Math.min(100,Number(o.percent)||0)),r=ue(l,a),d=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),d?e("span",{className:"cm-go-reset"},d):null)};function Ss(t){const{state:s,api:o,t:a,entry:n,index:i,canRemove:l,onPatch:r,onRemove:d}=t,u=n.adapter==="aliyun",[c,g]=L(!1),m=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[p,b]=L(m),[x,k]=L(()=>(n.allowedHosts??[]).join(", ")),[f,v]=L({}),S=ke(!1),w=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(R=>R.index===i)??null,M=n.enabled===!0,T=()=>{g(R=>!R)};X(()=>{c&&!S.current&&(b(m()),k((n.allowedHosts??[]).join(", ")),v({})),S.current=c},[c]);const B=(R,V)=>r({[R]:V}),P=(R,V)=>r({request:{...n.request??{},[R]:V}}),E=u?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(R=>typeof R=="string"?[...R.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(V=>V[1]):[]))],h=(R,V)=>{b(N=>({...N,[R]:V}));try{const N=R==="body",I=N&&!V.trim()?void 0:JSON.parse(V);if(!N&&(I===null||typeof I!="object"||Array.isArray(I)))throw new Error("invalid");if(R==="headers"&&Object.values(I).some(Q=>typeof Q!="string"))throw new Error("invalid");v(Q=>({...Q,[R]:""})),R==="extract"?B(R,I):P(R,N?I===void 0?void 0:V:I)}catch{v(N=>({...N,[R]:a("customBalanceInvalidJson")}))}},H=(R,V,N,I)=>!u&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(V)),I&&e("span",{className:"cm-hint"},a(I)),e("textarea",{className:"cm-input",rows:N,value:p[R],onChange:Q=>h(R,Q.target.value)}),f[R]?e("span",{className:"cm-hint err"},f[R]):null),ee=R=>{k(R);const V=R.split(/[\s,;]+/).map(N=>N.trim()).filter(N=>N.length>0);B("allowedHosts",V)},[he,xe,D]=lt(a,()=>(w.customBalances??[])[i]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(i)),O=y!==null&&y.status==="ok"?e(q,null,w.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(wt,{segments:kt(s,w,y,n),direction:te(w,"balance")}),e("div",{className:"cm-bal-line"},vt(y,w,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:je(y.remaining,w,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),G=e(q,null,e("p",{className:"cm-note"},a(u?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:Ue(w,y,n)!=="USD",onChange:R=>B("convertToDisplayCurrency",R.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([R,V])=>e("div",{key:R,className:"cm-field"},e("label",null,a(V)),e("input",{className:"cm-input",value:n[R]??"",onChange:N=>B(R,N.target.value)}))),!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:R=>B("unit",R.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:R=>B("display",R.target.value)},...We(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ae({value:n.refreshMinutes??15},R=>B("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(R)))))),!u&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:R=>P("method",R.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!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:R=>P("url",R.target.value)})),H("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&H("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),E.length>0?e(q,null,!u&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),E.map(R=>e(Be,{key:"cb-var-"+R,target:"customVar:"+R,configured:(s.customVarStatus?.[R]?.configured??!1)===!0,source:s.customVarStatus?.[R]?.source??"",t:a,api:o,placeholder:"{{"+R+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!u&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:x,placeholder:"api.example.com, relay.example.org",onChange:R=>ee(R.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),H("extract","customBalanceExtract",8)));return e(ot,{name:`#${i+1} · `+(xt(n,_(w?.locale))||a("customBalanceTitle")),enabled:M,saved:JSON.stringify(n)===JSON.stringify(w.customBalances?.[i])?w.customBalances[i]:null,busy:he,open:c,statusNode:O,configNode:G,errorMsg:xe,onToggle:R=>B("enabled",R),onRefresh:D,onRemove:l?d:null,onToggleOpen:T,t:a})}function Ra({config:t,draft:s,setDraft:o,t:a,api:n}){const i=s?.goQuota??t.goQuota,l=(r,d)=>{s&&o({...s,goQuota:{...i,[r]:d}})};return e(q,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:i[r],onChange:u=>l(r,u.target.value)},r==="display"?We(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")),ae({value:i.refreshMinutes},r=>l("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(Be,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function Cs(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),d=s.goQuota,u=s.config,c=n?.goQuota?.enabled??u.goQuota?.enabled??!0,g=(w,A)=>{n!==null&&i({...n,goQuota:{...n.goQuota??u.goQuota,[w]:A}})},[m,p,b]=lt(a,()=>o.refreshGoQuota()),x=u.goQuota?.main==="weekly"||u.goQuota?.main==="monthly"?u.goQuota.main:"rolling",k=[x,...["rolling","weekly","monthly"].filter(w=>w!==x)],f=w=>w==="rolling"?"goWindowRolling":w==="weekly"?"goWindowWeekly":"goWindowMonthly",v=w=>w==="rolling"?d.rolling:w==="weekly"?d.weekly:d.monthly,S=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):d.status==="ok"?e("div",{className:"cm-go-list"},k.map(w=>Oa(a,a(f(w)),v(w),te(u,"go"),w===x)),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(ot,{name:a("goQuotaTitle"),enabled:c,saved:u.goQuota,busy:m,open:l,statusNode:S,errorMsg:p,configNode:e(Ra,{config:u,draft:n,setDraft:i,t:a,api:o}),onToggleOpen:()=>r(w=>!w),onToggle:w=>g("enabled",w),onRefresh:b,t:a})}const As=(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 Ps(t){const{state:s,api:o,t:a,draft:n,setDraft:i,index:l}=t,r=s.config,u=(n??r).gatewayQuotas?.sources??[],c=u[l]??{},m=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(P=>P.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},p=As(c,s.customVarStatus),[b,x]=L(!1),[k,f,v]=lt(a,()=>o.refreshGatewayQuota(c.id)),S=P=>{n!==null&&i({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:P}})},w=P=>S(u.map((E,h)=>h===l?{...E,...P}:E)),A=(P,E,h)=>e("div",{className:"cm-field"},e("label",null,P),e("input",{className:"cm-input",value:E??"",onChange:h})),y=(P,E)=>{const h=_e(P?.label||P?.id||a("gatewaySourceUnknown"),P,te(r,"plan"),a);return e(q,{key:P?.id||E},h.row,P?.resetsAt?e("div",{className:"cm-note"},Fe(P,a)):null)},M=(P,E)=>e("div",{key:P.id||E,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},P.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(P.used??"—")+" / "+(P.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(P.remaining??"—")+" remaining")),T=P=>P==null?null:e(q,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},P.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(P.used??"—")+" / "+(P.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(P.remaining??"—")+" remaining")),(P.packages??[]).map(M)),B=(P,E)=>e("div",{key:P.id||E,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Yt[P.provider]??P.provider??a("gatewaySourceUnknown"))+" · "+(P.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},P.status)),P.plan?e("div",{className:"cm-note"},P.plan):null,P.windows.length>0?e("div",{className:"cm-go-list"},P.windows.map(y)):null,T(P.credits),P.message?e("div",{className:"cm-note"},P.message):null);return e(ot,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(P=>P.id===c.id),busy:k,open:b,errorMsg:f,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(m.status??a("gatewaySourceUnknown"))+(m.serverVersion?" · "+m.serverVersion:"")+(m.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(m.fetchedAt).toLocaleTimeString()}):"")+(m.message?" · "+m.message:"")),configNode:e(q,null,e("div",{className:"cm-grid"},A(a("gatewaySourceLabel"),c.label,P=>w({label:P.target.value})),A(a("gatewaySourceBaseURL"),c.baseURL,P=>w({baseURL:P.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:P=>w({display:P.target.value})},...We(a))),A(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),P=>w({allowedHosts:P.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:P=>w({antigravityOnlyGemini:P.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),p?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(Be,{target:"customVar:"+p,configured:s.customVarStatus?.[p]?.configured===!0,source:s.customVarStatus?.[p]?.source??"",t:a,api:o,placeholder:p})):null,m.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+m.unsupportedProviders.join(", ")):null,m.accounts.length>0?m.accounts.map(B):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:P=>w({enabled:P}),onRefresh:v,onRemove:()=>S(u.filter((P,E)=>E!==l)),onToggleOpen:()=>x(P=>!P),t:a})}const Oe=[{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 Ms(t){const{state:s,api:o,t:a,draft:n,setDraft:i,planId:l,labelKey:r}=t,d=s.config,u=s.codingPlans??{},c=n?.codingPlans?.[l]??d.codingPlans?.[l]??{},g=u[l]??{status:"off",message:"",fetchedAt:0,windows:{}},m=c.enabled===!0,[p,b]=L(!1),[x,k,f]=lt(a,()=>o.refreshCodingPlan(l)),v=(D,O)=>{if(n===null)return;const G=n.codingPlans??d.codingPlans??{};i({...n,codingPlans:{...G,[l]:{...G[l]??{},[D]:O}}})},[S,w]=L(""),[A,y]=L({}),M=D=>D?.rates!==null&&typeof D?.rates=="object"&&!Array.isArray(D.rates)?D.rates:{},T=["input","cachedInput","output"],B=D=>A[D]??M(c)[D]??{},P=D=>T.every(O=>Number.isFinite(Number(D[O]))&&Number(D[O])>0),E=(D,O,G)=>{if(n===null)return;const R={...B(D),[O]:String(G)};y(Q=>({...Q,[D]:R}));const V=T.every(Q=>String(R[Q]??"").trim()==="");if(!V&&!P(R))return;const N=n.codingPlans??d.codingPlans??{},I={...(N.qwen??{}).rates??{}};V?delete I[D]:I[D]=Object.fromEntries(T.map(Q=>[Q,Number(R[Q])])),i({...n,codingPlans:{...N,qwen:{...N.qwen??{},rates:I}}})},h=D=>{n!==null&&y(O=>({...O,[D]:O[D]??M(c)[D]??{}}))},H=D=>{if(n===null)return;y(R=>{const V={...R};return delete V[D],V});const O=n.codingPlans??d.codingPlans??{},G={...(O.qwen??{}).rates??{}};delete G[D],i({...n,codingPlans:{...O,qwen:{...O.qwen??{},rates:G}}})},ee=g.windows!==null&&typeof g.windows=="object"?g.windows:{},he=m===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):g.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(ee).length>0?l==="minimax"&&(Qe(ee).five!=null||Qe(ee).seven!=null)?e(xa,{five:Qe(ee).five,seven:Qe(ee).seven,fetchedAt:g.fetchedAt,t:a,wide:!0,direction:te(d,"plan")}):Object.entries(ee).map(([D,O])=>Oa(a,D.replace(/_/g," "),O,te(d,"plan"),!1,D)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:g.fetchedAt>0?new Date(g.fetchedAt).toLocaleTimeString():"—"}))):g.status==="error"?e("div",{className:"cm-bal-line err"},g.message||a("unknownError")):g.status==="off"&&g.message?e("p",{className:"cm-note"},g.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),xe=e(q,null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:D=>v("baseUrl",D.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:D=>v("quotaSource",D.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:l==="minimax"?"both":"settings",onChange:D=>v("display",D.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),l!=="scnet"&&(l!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ae({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},D=>{v("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D))))})):null,l==="scnet"||l==="qwen"&&(c.quotaSource??"local")==="local"?e(q,null,e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:l==="qwen"?5e5:24e4,onChange:D=>{const O=Number(D.target.value);Number.isFinite(O)&&O>0&&v("planCredits",Math.floor(O))}})),e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:D=>v("planStart",D.target.value)})),l==="qwen"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(M(c)),...Object.keys(A)])].sort().map(D=>e("div",{key:D,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},D),T.map(O=>e("input",{key:O,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:B(D)[O]??"",placeholder:a("qwenRate_"+O),"aria-label":D+" · "+a("qwenRate_"+O),onChange:G=>{const R=G.target.value;E(D,O,R)}})),e("button",{className:"cm-btn small",onClick:()=>H(D)},a("overrideRemove")),D in A&&!P(B(D))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:S,onChange:D=>w(D.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const D=S.trim();D.length!==0&&(h(D),w(""))},disabled:S.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(Be,{target:"codingPlans.volcengine.ak",configured:g.keyConfigured===!0,source:g.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(Be,{target:"codingPlans.volcengine.sk",configured:g.keyConfigured===!0,source:g.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(q,null,e("div",{className:"cm-field"},e("label",null,l==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(Be,{target:"codingPlans."+l,configured:g.keyConfigured===!0,source:g.keySource,t:a,api:o,placeholder:l==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(ot,{name:a(r),enabled:m,saved:d.codingPlans?.[l],busy:x,open:p,errorMsg:k,statusNode:he,configNode:xe,onToggle:D=>v("enabled",D),onRefresh:f,onToggleOpen:()=>b(D=>!D),t:a})}function Ts(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,l=s.config,r=n??l,d=r.codingPlans??{},u=r.gatewayQuotas?.sources??[],c=n?.customBalances??l.customBalances??[],g=S=>{n!==null&&i({...n,customBalances:S,...S.length===0?{customBalance:{...l.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},m=ke({next:0,keys:[]}).current;for(;m.keys.length<c.length;)m.keys.push(m.next++);m.keys.length=c.length;const p=S=>{m.keys.splice(S,1),g(c.filter((w,A)=>A!==S))},b=(S,w)=>g(c.map((A,y)=>y===S?{...A,...w}:A)),x=(S="custom")=>{c.length>=8||g([...c,{...S==="aliyun"?{adapter:S}:{},enabled:!1,label:S==="aliyun"?"千问 / 阿里云":"",labelEn:S==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:S==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:S==="aliyun"?"https://business.aliyuncs.com/":"",method:S==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},k=()=>{u.length>=4||n===null||i({...n,gatewayQuotas:{...n.gatewayQuotas??l.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:mt,allowedHosts:[],allowInsecureHttp:!1}]}})},f=[...u.map((S,w)=>({kind:"gateway",key:"gw-"+(S.id??w),index:w,enabled:S.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Oe.map(S=>({kind:"plan",key:"plan-"+S.id,planId:S.id,labelKey:S.labelKey,enabled:d[S.id]?.enabled===!0})),...c.map((S,w)=>({kind:"custom",key:"cb-"+m.keys[w],index:w,enabled:S.enabled===!0}))],v=S=>S.kind==="plan"?e(Ms,{key:S.key,planId:S.planId,labelKey:S.labelKey,state:s,api:o,t:a,draft:n,setDraft:i}):S.kind==="go"?e(Cs,{key:S.key,state:s,api:o,t:a,draft:n,setDraft:i}):S.kind==="gateway"?e(Ps,{key:S.key,index:S.index,state:s,api:o,t:a,draft:n,setDraft:i}):e(Ss,{key:S.key,state:s,api:o,t:a,entry:c[S.index],index:S.index,canRemove:!0,onPatch:w=>b(S.index,w),onRemove:()=>p(S.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ns(f).map(v)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:k,disabled:u.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>x(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>x("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const Bs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],La=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function qt(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=_(a?.locale),i=t.t??K(n),l=Array.isArray(o.history)?o.history:[];if(l.length===0)return e("div",null,e("h3",{className:"cm-h"},i("usageTitle")),e("p",{className:"cm-empty"},i("usageEmpty")));const r=o.meta?.dayKey??"",d=new Map(l.map(w=>[w.date,w])),u=w=>{const A=y=>String(y).padStart(2,"0");return w.getFullYear()+"-"+A(w.getMonth()+1)+"-"+A(w.getDate())},c=new Date;c.setHours(0,0,0,0);const g=new Date(c);g.setDate(g.getDate()+(6-(c.getDay()+6)%7));const m=26,p=[],b=[];let x=-1;for(let w=m-1;w>=0;w-=1){for(let y=0;y<7;y+=1){const M=new Date(g);M.setDate(M.getDate()-(w*7+(6-y)));const T=d.get(u(M));p.push(T!==void 0?{day:T,tokens:La(T)}:{day:{date:u(M)},tokens:0})}const A=new Date(g);A.setDate(A.getDate()-(w*7+6)),b.push(A.getMonth()!==x?n==="en"?Bs[A.getMonth()]:String(A.getMonth()+1)+"月":""),x=A.getMonth()}const k=Math.max(...p.map(w=>w.tokens),1),f=w=>{const A=w/k;return A<.25?1:A<.5?2:A<.75?3:4},v=w=>{const{day:A,tokens:y}=w,M="cm-ug-cell"+(y>0?" l"+f(y):"")+(A.date===r?" today":""),T=i("usageDay",{date:A.date,tokens:U(y),input:U(A.input??0),cache:U((A.cacheRead??0)+(A.cacheWrite??0)),output:U(A.output??0),calls:A.calls??0,cost:Y(z(A,a),a)});return e($,{key:A.date,label:T,side:"top",delayMs:200},e("div",{className:M}))},S=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},i("usageTitle")),e("div",{className:"cm-ug-total"},i("usageTotal",{tokens:U(La(S)),input:U(S.input??0),cache:U((S.cacheRead??0)+(S.cacheWrite??0)),output:U(S.output??0),calls:S.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+m+",1fr)"}},p.map(v)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+m+",1fr)"}},b.map((w,A)=>e("span",{key:"m"+String(A),className:"cm-ug-monthc"},w))))}function Ds(t){const s=t.useCost?t.useCost(N=>N):void 0,o=t.api,a=s?.state??null,[n,i]=L(null),[l,r]=L(null),[d,u]=L(!1),[c,g]=L(!1),[m,p]=L(!1),[b,x]=L(""),[k,f]=L(!1),[v,S]=L(!1),[w,A]=L("overview"),[y,M]=L({status:"idle",at:0,error:null}),T=Le.useRef(null),B=Le.useRef(null),P=Le.useRef(null);X(()=>{if(a!==null){const N=JSON.stringify(a.config);i(I=>{const Q=I!==null&&JSON.stringify(I)!==T.current;return Q||(B.current=a.config,P.current=a.config),Q?I:JSON.parse(N)}),T.current=N}},[a]),X(()=>{n!==null&&P.current===null&&B.current!==null&&(P.current=B.current)},[n]),X(()=>{if(n===null||o===void 0)return;const N=JSON.stringify(n);if(N===T.current)return;M(Q=>Q.status==="saving"?Q:{...Q,status:"saving"});const I=setTimeout(()=>{const Q={},le=P.current??B.current;if(le!==null&&typeof le=="object")for(const C of Object.keys(n))JSON.stringify(n[C])!==JSON.stringify(le[C])&&(Q[C]=n[C]);if(Object.keys(Q).length===0){T.current=N,M({status:"saved",at:Date.now(),error:null});return}o.updateConfig(Q).then(()=>{T.current=N,le!==null&&typeof le=="object"&&(P.current={...le,...Q}),M({status:"saved",at:Date.now(),error:null})},C=>{M({status:"error",at:0,error:C?.message??String(C)})})},600);return()=>{clearTimeout(I)}},[n,o]),X(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:h("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const E=_((n??a?.config)?.locale),h=K(E);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?h("readingLedger"):h("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},h("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},h("refresh")));const H=a.config,ee=async()=>{if(!k){f(!0),r(null);try{const N=await o.fetchPrices();if(r({kind:N.ok?"ok":"err",text:N.message}),N.ok&&N.state&&typeof N.state.config=="object"){const I=JSON.stringify(N.state.config);i(JSON.parse(I)),T.current=I}}catch(N){r({kind:"err",text:h("syncFailed",{message:N?.message??String(N)})})}finally{f(!1),u(!1)}}},he=async()=>{if(!k){f(!0);try{await o.resetHistory(),r({kind:"ok",text:h("historyCleared")})}catch(N){r({kind:"err",text:h("clearFailed",{message:N?.message??String(N)})})}finally{f(!1),g(!1)}}},xe=async()=>{if(!k){f(!0),r(null);try{const N=await o.importLegacyHistory();r({kind:"ok",text:N.message})}catch(N){r({kind:"err",text:h("legacyImportFailed",{message:N?.message??String(N)})})}finally{f(!1),p(!1)}}},D=(N,I)=>{n!==null&&i({...n,[N]:I})},O=()=>{if(n===null)return;const N=b.trim().toLowerCase();if(N.length===0||!/^[a-z0-9_.-]+$/.test(N)||n?.prices.models[N]!==void 0)return;const I={...n.prices.models,[N]:{cacheHit:0,cacheMiss:0,output:0}};i({...n,prices:{...n.prices,models:I}}),x("")},G=n===null?[]:Object.keys(n.prices.models).filter(N=>{const Q=(n?.priceTableDisplay??H.priceTableDisplay??{})["deepseek:"+N];return typeof Q=="boolean"?Q:!0}).map(N=>e(Rt,{key:N,modelId:N,entry:n.prices.models[N]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:i,t:h})),R=[["overview",h("tabOverview")],["quotas",h("tabQuotas")],["usage",h("tabUsage")],["pricing",h("tabPricing")],["display",h("tabDisplay")]],V=y.status==="saving"?e("span",{className:"cm-hint"},h("saving")):y.status==="error"?e("span",{className:"cm-msg err"},h("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?h("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):h("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},R.map(([N,I])=>e("button",{key:N,type:"button",role:"tab","aria-selected":String(w===N),className:"cm-tab"+(w===N?" active":""),onClick:()=>A(N)},I))),V),Et(l),w==="overview"?e(q,{key:"overview"},e("div",{className:"cm-cards"},H.hideTodayCost===!0?null:e(Dt,{title:h("cardToday"),value:Y(z(a.today,H),H),sub:h("callsTokens",{calls:a.today.calls,input:U(a.today.input),cache:U(a.today.cacheRead+a.today.cacheWrite),output:U(a.today.output)})}),e(Dt,{title:h("cardMonth"),value:Y(z(a.month,H),H),sub:h("callsTokens",{calls:a.month.calls,input:U(a.month.input),cache:U(a.month.cacheRead+a.month.cacheWrite),output:U(a.month.output)})}),e(Dt,{title:h("cardTotal"),value:Y(z(a.total,H),H),sub:h("cardTotalSub",{calls:a.total.calls})})),e("p",{className:"cm-note",key:"cards-footnote"},h("cardsFootnote")),(()=>{const N=bn(a);return N!==null?e("p",{className:"cm-note",key:"tz-hint"},h("timezoneHint",{host:N.hostLabel,browser:N.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:h("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??H).showTotalWithPlan===!0,onChange:N=>{const I=n??H;I!=null&&i({...I,showTotalWithPlan:N.target.checked})}}),e("span",null,h("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},h("todaySessions")),e(us,{state:a,t:h})),e(ps,{state:a,draft:n,setDraft:i,t:h}),(H.balance?.display==="settings"||H.balance?.display==="both")&&H.hideOfficialBalance!==!0?e(vs,{state:a,api:o,t:h,draft:n,setDraft:i}):null):null,w==="quotas"?e(Ts,{key:"quotas",state:a,api:o,t:h,draft:n,setDraft:i}):null,w==="usage"?e(q,{key:"usage"},!ze||(H.usage?.position??"cost")==="cost"?e(qt,{state:a,t:h,locale:E}):null,e(hs,{state:a,config:n??H,t:h}),e(xs,{state:a,config:n??H,t:h}),e(rs,{state:a,api:o}),e(ds,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},h("historyDataTitle")),e("div",{className:"cm-buttons"},m?e(q,null,e("span",{className:"cm-hint"},h("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:xe,disabled:k},h("apply")),e("button",{className:"cm-btn",onClick:()=>p(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>p(!0),disabled:k},h("importLegacy")),c?e(q,null,e("span",{className:"cm-hint"},h("confirmReset")),e("button",{className:"cm-btn danger",onClick:he,disabled:k},h("confirmClear")),e("button",{className:"cm-btn",onClick:()=>g(!1)},h("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>g(!0),disabled:k},h("clearAllHistory"))),e("p",{className:"cm-note"},h("legacyImportNote")))):null,w==="display"?e(q,{key:"display"},e(is,{draft:n,setDraft:i,t:h}),a?.secretMigration?.pending?.length>0?e(hn,{pending:a.secretMigration.pending,t:h}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,h("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:N=>D("locale",N.target.value)},e("option",{value:"auto"},h("localeAuto")),e("option",{value:"zh"},h("localeZh")),e("option",{value:"en"},h("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},h("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},h("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled"].map(N=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[N]===!0,onChange:I=>D(N,I.target.checked)}),e("span",null,h(N)))),ze?e("div",{className:"cm-field"},e("label",null,h("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:N=>{n!==null&&i({...n,usage:{...n.usage??{position:"cost"},position:N.target.value}})}},e("option",{value:"cost"},h("usagePositionCost")),e("option",{value:"general"},h("usagePositionGeneral")),e("option",{value:"section"},h("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,h("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:N=>D("position",N.target.value)},e("option",{value:"dock"},h("positionDock")),e("option",{value:"header"},h("positionHeader")),e("option",{value:"off"},h("off")))),e("div",{className:"cm-field"},e("label",null,h("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:N=>D("sidebar",N.target.value==="on")},e("option",{value:"on"},h("sidebarOn")),e("option",{value:"off"},h("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:N=>D("showSessionId",N.target.checked)}),e("span",null,h("showSessionIdLabel"))),e("div",{className:"cm-grid-group"},h("groupMoney")),e("div",{className:"cm-field"},e("label",null,h("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:N=>{const I=ms[N.target.value];I!==void 0&&n!==null&&i({...n,currency:N.target.value,...I})}},e("option",{value:"CNY"},h("currencyCny")),e("option",{value:"USD"},h("currencyUsd")),e("option",{value:"EUR"},h("currencyEur")))),e("div",{className:"cm-field"},e("label",null,h("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:N=>D("symbol",N.target.value)})),e("div",{className:"cm-field"},e("label",null,h("rateLabel")),ae({value:n?.exchangeRate??1,emptyMode:"ignore"},N=>D("exchangeRate",N))),e("div",{className:"cm-field"},e("label",null,h("decimalsLabel")),ae({value:n?.decimals??2},N=>D("decimals",Math.min(10,Math.floor(N))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:N=>D("hideOfficialBalance",N.target.checked)}),e("span",null,h("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:N=>D("hideTodayCost",N.target.checked)}),e("span",null,h("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},h("groupSidebar")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:N=>{n&&i({...n,sidebarSimple:N.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,h("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,h("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:N=>D("sidebarStyle",N.target.value)},e("option",{value:"standard"},h("sidebarStyleStandard")),e("option",{value:"compact"},h("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,h("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:N.target.value}})}},...We(h))),e("div",{className:"cm-field"},e("label",null,h("refreshIntervalLabel")),ae({value:n?.balance?.refreshMinutes??5},N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(N)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:N.target.checked}})}}),e("span",null,h("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,h("balanceBudgetCapLabel")),ae({value:n?.balance?.budgetCap??""},N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:N>0?N:null}})}),e("span",{className:"cm-hint"},h("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,h("barDirectionsTitle")),["balance","budget","go","plan"].map(N=>e("div",{className:"cm-dir-row",key:N},e("span",{className:"cm-dir-label"},h("barDirection_"+N)),e("select",{className:"cm-input",value:n?.barDirections?.[N]??(N==="balance"?"remaining":"used"),onChange:I=>{if(n===null)return;const Q={balance:"remaining",budget:"used",go:"used",plan:"used"};i({...n,barDirections:{...n.barDirections??Q,[N]:I.target.value}})}},e("option",{value:"remaining"},h("barDirectionRemaining")),e("option",{value:"used"},h("barDirectionUsed"))))),e("span",{className:"cm-hint"},h("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,h("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??H.customBalance?.display??"both",onChange:N=>{n!==null&&i({...n,customBalance:{...n.customBalance??H.customBalance??{},display:N.target.value}})}},...We(h))),e("div",{className:"cm-field"},e("label",null,h("customBalanceRefreshInterval")),ae({value:n?.customBalance?.refreshMinutes??H.customBalance?.refreshMinutes??15},N=>{n!==null&&i({...n,customBalance:{...n.customBalance??H.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(N)))}})})),e(Ra,{config:H,draft:n,setDraft:i,t:h,api:o}),e("div",{className:"cm-grid-group"},h("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:N=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:N.target.checked,promptSeen:!0}})}}),e("span",null,h("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([N,I])=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[N]!==!1,onChange:Q=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip,[N]:Q.target.checked}})}}),e("span",null,h(I)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("quotaStripNote"))),e("div",{className:"cm-grid-group"},h("groupCorner")),e("div",{className:"cm-field"},e("label",null,h("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:N=>{n!==null&&i({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:N.target.checked}})}}),e("span",null,h("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([N,I])=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[N]!==!1,onChange:Q=>{n!==null&&i({...n,corner:{...n.corner,[N]:Q.target.checked}})}}),e("span",null,h(I)))):null),e("div",{className:"cm-grid-group"},h("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:N=>{n!==null&&i({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:N.target.checked}})}}),e("span",null,h("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:N=>{n!==null&&i({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:N.target.checked}})}}),e("span",null,h("budgetDetailLabel"))))),e("p",{className:"cm-note"},h("badgeNote")))):null,w==="pricing"?e(q,{key:"pricing"},e(fs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,De(v,()=>S(!v),h("priceTableTitle")),v?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},h("priceTableNote")),e("p",{className:"cm-hint"},h("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},h("deepseekMountedHeader")),G,e(Rt,{key:"__default__",modelId:h("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:i,t:h}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:h("newModelPlaceholder"),value:b,onChange:N=>x(N.target.value)}),e("button",{className:"cm-btn small",onClick:O,disabled:b.trim().length===0},h("addModel"))),(()=>{const N=n?.priceTableDisplay??H.priceTableDisplay??{},I=n?.prices?.providers??{},Q=C=>Object.keys(I[C]?.models??{}).filter(F=>N[C+":"+F]===!0),le=Object.keys(I).filter(C=>Q(C).length>0).sort((C,F)=>C.localeCompare(F));return le.length===0?null:le.map(C=>e("div",{key:C},e("div",{className:"cm-catalog-vendor"},(Pa[C]??C)+" · "+h("mountedSuffix")),Q(C).sort().map(F=>e(Da,{key:C+":"+F,provider:C,modelId:F,entry:I[C].models[F],draft:n,setDraft:i,t:h}))))})()):null),(()=>{const N=n?.priceOverrides??H.priceOverrides??{},I=n?.priceMatchDismissed??H.priceMatchDismissed??[],Q=n?.prices??H.prices,le=a.today.byProviderModel??{},C={prices:Q,priceMatch:n?.priceMatch??H.priceMatch},F=Object.keys(le).filter(j=>{if(I.includes(j)||N[j]!==void 0)return!1;const W=j.indexOf(":"),ye=(W>0?j.slice(0,W):"deepseek").toLowerCase(),It=W>0?j.slice(W+1):j;return bt(ye,It,C).matched!==!0}),Z=[...new Set([...F,...Object.keys(N)])].filter(j=>!I.includes(j)),ne=a.month?.byProviderModel??{},Re=Object.keys(ne).filter(j=>{if(I.includes(j)||N[j]!==void 0)return!1;const W=j.indexOf(":"),ye=(W>0?j.slice(0,W):"deepseek").toLowerCase(),It=W>0?j.slice(W+1):j;return bt(ye,It,C).matched===!0}).sort(),ve=[{value:"__local__",label:h("overrideTargetLocal")},{value:"deepseek:__default__",label:h("overrideTargetDefault")},...Object.keys(Q.models??{}).map(j=>({value:"deepseek:"+j,label:"DeepSeek · "+j})),...Object.entries(Q.providers??{}).flatMap(([j,W])=>Object.keys(W?.models??{}).map(ye=>({value:j+":"+ye,label:j+" · "+ye})))],pe=(j,W)=>{if(n===null)return;const ye={...n.priceOverrides??{}};W===""?delete ye[j]:ye[j]=W,i({...n,priceOverrides:ye})},Pe=j=>{if(n===null)return;const W={...n.priceOverrides??{}};delete W[j],i({...n,priceOverrides:W,priceMatchDismissed:[...new Set([...I,j])]})};return e("div",null,e("h3",{className:"cm-h"},h("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:j=>D("priceMatch",j.target.value)},e("option",{value:"auto"},h("priceMatchAuto")),e("option",{value:"exact"},h("priceMatchExact")))),e("p",{className:"cm-note"},h("priceMatchNote")),Z.length>0?e(q,null,e("h3",{className:"cm-h"},h("unmatchedTitle")),e("p",{className:"cm-hint"},h("unmatchedHint")),Z.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,Lt(j)),e("select",{className:"cm-input",value:N[j]??"",onChange:W=>pe(j,W.target.value)},e("option",{value:""},"—"),ve.map(W=>e("option",{key:W.value,value:W.value},W.label))),e("button",{className:"cm-btn small",title:h("removePriceMatchHint"),onClick:()=>Pe(j)},h("overrideRemove"))))):e("p",{className:"cm-hint"},h("overrideNone")),I.length>0?e("button",{className:"cm-btn small",onClick:()=>D("priceMatchDismissed",[])},h("restorePriceMatches",{count:I.length})):null,Re.length>0?e(q,null,e("h3",{className:"cm-h"},h("matchedTitle")),e("p",{className:"cm-hint"},h("matchedHint")),Re.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,Lt(j)),e("select",{className:"cm-input",value:"",onChange:W=>{W.target.value!==""&&pe(j,W.target.value)}},e("option",{value:""},h("matchedKeepAuto")),ve.map(W=>e("option",{key:W.value,value:W.value},W.label)))))):null)})(),e(gs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,e("h3",{className:"cm-h"},h("dataSync")),(n??H).currency==="CNY"&&(n??H).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},h("pricingCnyHint",{rate:(n??H).exchangeRate}),(n??H).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:k,onClick:()=>D("pricingCurrency","CNY")},h("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,h("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:N=>D("pricingCurrency",N.target.value)},e("option",{value:"USD"},h("pricingCurrencyUsd")),e("option",{value:"CNY"},h("pricingCurrencyCny"))),e("p",{className:"cm-note"},h("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},d?e(q,null,e("span",{className:"cm-hint"},h("confirmFetch")),e("button",{className:"cm-btn",onClick:ee,disabled:k},h("apply")),e("button",{className:"cm-btn",onClick:()=>u(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>u(!0),disabled:k},h("syncFromDocs"))),e("p",{className:"cm-note"},h("lastSync",{time:H.fetchedAt!==null?new Date(H.fetchedAt).toLocaleString():h("neverSynced")})+h("source",{source:H.priceSource==="official"?h("sourceOfficial"):h("sourceBundled")})),e("p",{className:"cm-note"},h("syncScopeNote")))):null)}const Os=["remote"];async function Rs(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(tn);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=gn({status:"loading",error:null,state:null}),i=()=>K(_(n.getSnapshot().state?.config?.locale)),l=async(C,F)=>{const Z=await a[C](...F??[]);if(Z===null||typeof Z!="object"||Z.ok!==!0)throw new Error(Z?.error?.message??i()("rpcFailed",{method:C}));return Z.value};let r=Date.now(),d=!1,u=!0,c=1;const g=async()=>{if(!u||d)return;d=!0,r=Date.now();const C=n.getSnapshot();C.state===null&&n.set({...C,status:"loading"});try{const F=await l("getState");if(!u)return;c=1,n.set({status:"ready",error:null,state:F})}catch(F){if(!u)return;C.state===null&&(r=Date.now()),c=Math.min(c*2,60),n.set({status:"error",error:F?.message??String(F),state:C.state})}finally{d=!1}};t.effect(()=>t.on("connection/reset",()=>{g()}),"cost-meter: reconnect reload");const m=setInterval(()=>{const C=n.getSnapshot().state,F=C?.config.sidebarModels,Z=C?F?.enabled||F?.dock?F.refreshSeconds:60:c;!document.hidden&&Date.now()-r>=(Z||60)*1e3&&g()},1e3);t.effect(()=>()=>{u=!1,clearInterval(m)},"cost-meter: poll timer");const p=()=>{document.visibilityState==="visible"&&g()};document.addEventListener("visibilitychange",p),t.effect(()=>()=>{document.removeEventListener("visibilitychange",p)},"cost-meter: visibility reload");const b=async(C,F="rpcSyncFailed",Z=!1)=>{const ne=await C;if(ne===null||typeof ne!="object"||ne.ok!==!0)throw new Error(ne?.error?.message??(Z?ne?.value?.message:void 0)??i()(F));return ne.value.state!==void 0&&n.set({status:"ready",error:null,state:ne.value.state}),ne.value},x={reload:g,updateConfig:async C=>{const F=await l("updateConfig",[C]);return n.set({status:"ready",error:null,state:F}),F},fetchPrices:async()=>b(a.fetchPrices()),resetHistory:async()=>{const C=await l("resetHistory");return n.set({status:"ready",error:null,state:C}),C},importLegacyHistory:async()=>{const C=await a.importLegacyHistory();if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??i()("legacyImportFailed",{message:"RPC failed"}));return C.value.state!==void 0&&n.set({status:"ready",error:null,state:C.value.state}),C.value},getDaySessions:async C=>l("getDaySessions",[C]),getSessionCost:async C=>l("getSessionCost",[C]),getTopSessions:async(C,F,Z)=>l("getTopSessions",[C,F,Z]),refreshBalance:async()=>b(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>b(a.refreshGoQuota()),refreshGatewayQuota:async(C=null)=>b(C==null?a.refreshGatewayQuota():a.refreshGatewayQuota(C)),refreshCustomBalance:async(C=null)=>b(C==null?a.refreshCustomBalance():a.refreshCustomBalance(C)),refreshCodingPlan:async C=>b(a.refreshCodingPlan(C)),setCredential:async(C,F)=>b(a.setCredential(C,F),"rpcSyncFailed",!0),clearCredential:async C=>b(a.clearCredential(C),"rpcSyncFailed",!0)};g();const k=t.get("slots");if(k===void 0)return;const f=()=>({hooks:{cost:n},api:x}),v=()=>({gen:0,dispose:null}),S=(C,F,Z,ne,Re=!0)=>{C.dispose!==null&&(C.dispose(),C.dispose=null),C.gen+=1;const ve=C.gen;Re&&k.inject(F,()=>{if(C.gen!==ve)return;const pe=typeof Z=="function"?Z():k.register(Z,ne);if(C.gen!==ve){pe();return}return C.dispose=pe,()=>{C.dispose===pe&&(C.dispose=null),pe()}})},w=v(),A=C=>{const F=C==="header"?"conversation.session.header.actions":"conversation.composer.dock";S(w,F,C==="header"?{name:F,id:"cost-meter",order:-5,inject:f}:{name:F,id:"cost-meter",order:5,inject:f},C==="header"?kn:wn,C!=="off")},y=v(),M=C=>{S(y,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:f},os,C)},T=v(),B=C=>{S(T,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:f},On,C)};k.inject("conversation.input.dock",()=>k.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:f},Xn)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:f},es)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:f},ts)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:f},ss));const P=v(),E=C=>{S(P,"sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:f},Rn),null,C)};window.cmPeakAlertPreview=C=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(St,{detail:{kind:C==="offpeak"?"offpeak":"peak"}}))};const h=v(),H=C=>{S(h,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:C==="en"?Me.en.sectionLabel:Me.zh.sectionLabel,inject:f},Ds,!0)},ee=v(),he=C=>{S(ee,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:f},qt,C)},xe=v(),D=(C,F)=>{S(xe,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:F==="en"?Me.en.usageSectionLabel:Me.zh.usageSectionLabel,inject:f},qt,C)};let O=null,G=null,R=null,V=null,N=null,I=null;const Q=()=>{const C=n.getSnapshot().state,F=C?.config?.position??"dock",Z=C?.config?.sidebar!==!1&&C?.config?.hideTodayCost!==!0,ne=C?.config?.balance?.display??"both",Re=(ne==="sidebar"||ne==="both")&&C?.config?.hideOfficialBalance!==!0,ve=Z||Re||C?.config?.codexQuotaEnabled===!0||C?.config?.sidebarModels?.enabled===!0,pe=C?.config?.corner?.enabled===!0||C?.config?.sidebarModels?.dock===!0,Pe=_(C?.config?.locale),j=C?.config?.usage?.position??"cost";F!==O&&(A(F),O=F),ve!==G&&(M(ve),G=ve),pe!==R&&(B(pe),R=pe);const W=C?.config?.peakEnabled===!0;W!==I&&(E(W),I=W),Pe!==V&&(H(Pe),V=Pe),j!==N?(ze&&(he(j==="general"),D(j==="section",Pe)),N=j):ze&&j==="section"&&Pe!==V&&D(!0,Pe)};Q();const le=n.subscribe(Q);return()=>{le()}}return it.apply=Rs,it.inject=Os,Ut.exports}});
|
|
2
|
+
window.__ModuleLoader__.load({id:"dsh-cost-meter",factory:It=>{var Ut={exports:{}},rt=Ut.exports;Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"});const Ee=It("react"),{Tooltip:$}=It("@deepseek-ai/dsh-client-ui-primitives"),Ge=!1,Ea='.cm-root{display:block;text-align:center;max-width:var(--dsh-chat-content-width,720px);width:100%;margin:0 auto;box-sizing:border-box;padding:4px calc(var(--dsh-composer-side-clearance,0px) + 16px) 0;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-chip{display:inline-flex;align-items:center;gap:4px;max-width:180px;padding:0 8px;height:22px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-foot{display:flex;align-items:center;gap:6px;height:32px;padding:0 8px;border-radius:8px;font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden}.cm-foot:hover,.cm-foot-rail:hover,.cm-corner-chip:hover,.cm-qchip:hover,.cm-tab:hover,.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}.cm-foot-rail{width:100%;justify-content:center;padding:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-num{font-variant-numeric:tabular-nums}.cm-go-rail{font-size:11px;font-weight:700;color:var(--dsw-alias-label-primary)}.cm-go-list{display:flex;flex-direction:column;gap:10px}.cm-go-row{display:flex;align-items:center;gap:8px;font-size:12px}.cm-go-label{flex:none;width:88px;color:var(--dsw-alias-label-secondary)}.cm-go-bar{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-interactive-bg-hover);overflow:hidden}.cm-go-fill{height:100%;border-radius:3px;background:var(--dsw-alias-brand-primary)}.cm-go-num{flex:none;min-width:44px;text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.cm-go-reset{flex:none;max-width:230px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-go-time{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-go-row.main .cm-go-label{font-weight:600;color:var(--dsw-alias-label-primary)}.cm-corner{display:flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:2px auto 0;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-corner-chip{display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:20px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums}.cm-qstrip{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;width:100%;max-width:var(--dsh-chat-content-width,720px);margin:0 auto;box-sizing:border-box;padding:0 calc(var(--dsh-composer-side-clearance,0px) + 16px)}.cm-qchip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11px;line-height:22px;color:var(--dsw-alias-label-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:default}.cm-qchip .cm-qlabel{color:var(--dsw-alias-label-primary);font-weight:600}.cm-qchip .cm-qbar{display:block;width:44px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l1);overflow:hidden;flex:none}.cm-qchip .cm-qfill{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-state-ok-primary,#3ba272)}.cm-qchip .cm-qseg{display:inline-flex;align-items:center;gap:4px}.cm-qchip .cm-qsep{width:1px;height:12px;background:var(--dsw-alias-border-l1);flex:none}.cm-qchip .cm-qtext{color:var(--dsw-alias-label-secondary)}.cm-qchip.warn .cm-qfill{background:var(--dsw-alias-state-warn-primary)}.cm-qchip.over .cm-qfill{background:var(--dsw-alias-state-error-primary)}.cm-qchip.action{cursor:pointer;user-select:none;outline:none}.cm-qchip.action:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-qchip.action:active{transform:translateY(.5px)}.cm-plan-provider{display:flex;flex-direction:column;gap:8px}.cm-plan-provider+.cm-plan-provider{margin-top:14px}.cm-plan-provider-name{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600}.cm-plan-updated{font-size:11px;font-weight:400;color:var(--dsw-alias-label-tertiary)}.cm-plan-tag{flex:none;margin-left:6px;padding:0 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);font-size:10px;line-height:16px;color:var(--dsw-alias-state-warn-primary)}.cm-plan-reset,.cm-plan-method{font-size:11px;color:var(--dsw-alias-label-tertiary)}.cm-qguide{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:9999;max-width:440px;width:calc(100% - 32px);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 28px #0000002e;padding:14px 16px;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:8px}.cm-qguide h4{margin:0;font-size:13px;font-weight:600}.cm-qguide p{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}.cm-qguide .cm-buttons{display:flex;gap:8px;justify-content:flex-end}.cm-section{display:flex;flex-direction:column;gap:20px;padding:4px 2px 24px;font-size:13px;color:var(--dsw-alias-label-primary)}.cm-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.cm-cards-toggle{display:flex;align-items:center;gap:6px;margin:-6px 2px 0 auto;width:fit-content;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;user-select:none}.cm-cards-toggle:hover{color:var(--dsw-alias-label-primary)}.cm-cards-toggle input{margin:0;cursor:pointer}.cm-card,.cm-budget{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px 16px;background:var(--dsw-alias-bg-layer-1)}.cm-card-title{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0 0 8px}.cm-card-value{font-size:20px;line-height:28px;font-weight:600}.cm-card-sub{font-size:12px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-h{font-size:13px;font-weight:600;margin:0}.cm-collapse-h{display:flex;align-items:center;gap:8px;background:none;border:none;padding:0;margin:0;cursor:pointer;color:inherit;font:inherit;text-align:left}.cm-collapse-h:hover .cm-h{color:var(--dsw-alias-interactive-text-hover,var(--dsw-alias-label-primary))}.cm-caret{flex:none;width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid var(--dsw-alias-label-secondary);transform:rotate(-90deg);transition:transform .15s ease}.cm-caret.open{transform:rotate(0)}.cm-collapse-body{display:flex;flex-direction:column;gap:12px;margin-top:12px}.cm-toolbar{display:flex;justify-content:flex-end;align-items:center;gap:10px}.cm-toolbar .cm-field{flex-direction:row;align-items:center;gap:8px}.cm-toolbar .cm-field label{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-toolbar .cm-input{min-width:150px;padding:4px 10px}.cm-tabs-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;border-bottom:1px solid var(--dsh-alias-border-l1);padding-bottom:10px}.cm-tabs{display:flex;align-items:center;gap:4px;flex-wrap:wrap}.cm-tab{font:inherit;font-size:13px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:8px;padding:6px 14px;cursor:pointer;white-space:nowrap}.cm-tab.active{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary-inverted);font-weight:600}.cm-tabs-row .cm-msg{padding:2px 10px}.cm-note{font-size:12px;color:var(--dsw-alias-label-tertiary);margin:0}.cm-table{width:100%;border-collapse:collapse;font-size:12px}.cm-table th,.cm-table td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}.cm-table th{color:var(--dsw-alias-label-tertiary);font-weight:500}.cm-table td.num,.cm-table th.num{text-align:right;font-variant-numeric:tabular-nums}.cm-table tr:last-child td{border-bottom:none}.cm-table tr.cm-row-click{cursor:pointer}.cm-table tr.cm-row-click:hover td{background:var(--dsw-alias-bg-hover,rgba(127,127,127,.08))}.cm-sess-title{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-sess-id{font-size:11px;font-family:ui-monospace,Consolas,monospace;color:var(--dsw-alias-label-tertiary)}.cm-empty{font-size:12px;color:var(--dsw-alias-label-tertiary);padding:8px 0}.cm-scroll{max-height:320px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px}.cm-grid{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:12px}.cm-field{display:flex;flex-direction:column;gap:6px}.cm-field label{font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-input{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;outline:none}.cm-input:focus{border-color:var(--dsw-alias-state-business-primary)}.cm-input.narrow{max-width:120px}.cm-range-row{display:flex;align-items:center;gap:10px}.cm-range{flex:1;min-width:0;accent-color:var(--dsw-alias-state-business-primary)}.cm-range-value{flex:none;min-width:44px;font-size:12px;color:var(--dsw-alias-label-tertiary);text-align:right}.cm-check{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary);cursor:pointer}.cm-price-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:10px;background:var(--dsw-alias-bg-layer-1)}.cm-price-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-price-name{font-weight:600;font-size:13px}.cm-price-legacy{font-size:11px;color:var(--dsw-alias-label-tertiary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px}.cm-price-row{display:grid;grid-template-columns:52px 1fr 1fr 1fr;gap:8px;align-items:center}.cm-price-row span{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-price-row input{width:100%}.cm-buttons{display:flex;flex-wrap:wrap;gap:10px;align-items:center}.cm-btn{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-elevated-fill);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 14px;cursor:pointer}.cm-btn.primary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-label-primary-inverted)}.cm-btn.primary:hover{opacity:.88;background:var(--dsw-alias-state-business-primary)}.cm-btn.danger,.cm-msg.err,.cm-bal-line.err,.cm-bal-err{color:var(--dsw-alias-state-error-primary)}.cm-btn.small{padding:3px 10px;font-size:12px}.cm-msg{font-size:12px;line-height:18px;padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1)}.cm-msg.ok{color:var(--dsw-alias-state-success-primary)}.cm-hint{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-budget{display:flex;flex-direction:column;gap:10px}.cm-peak-alert{position:fixed;z-index:9999;width:340px;max-width:calc(100vw - 32px);padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:0 14px 36px #00000038;display:flex;flex-direction:column;gap:8px;font-size:12px;animation:cm-peak-alert-in .22s cubic-bezier(.2,.8,.2,1)}.cm-peak-alert.cm-peak-alert-corner{right:20px;bottom:20px}.cm-peak-alert.cm-peak-alert-center{top:50%;left:50%;transform:translate(-50%,-50%);animation-name:cm-peak-alert-in-center}.cm-peak-alert-peak{border-top:3px solid var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak{border-top:3px solid var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:600;letter-spacing:.4px;text-transform:uppercase}.cm-peak-alert-badge:before{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 4px color-mix(in srgb,currentColor 16%,transparent)}.cm-peak-alert-peak .cm-peak-alert-badge{color:var(--dsw-alias-state-warn-primary)}.cm-peak-alert-offpeak .cm-peak-alert-badge{color:var(--dsw-alias-state-info-primary,#3b82f6)}.cm-peak-alert-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-peak-alert-body{color:var(--dsw-alias-label-secondary);line-height:1.55}.cm-peak-alert-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}.cm-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}@keyframes cm-peak-alert-in{0%{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes cm-peak-alert-in-center{0%{opacity:0;transform:translate(-50%,calc(-50% + 10px))}to{opacity:1;transform:translate(-50%,-50%)}}.cm-budget-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-quota-name{flex:1;min-width:0}.cm-budget-bar{height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-budget-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary);transition:width .3s ease}.cm-ug{display:flex;flex-direction:column;gap:12px}.cm-ug-total{font-size:13px;color:var(--dsw-alias-label-primary)}.cm-ug-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,auto);gap:3px;width:100%}.cm-ug-cell{width:100%;aspect-ratio:1/1;border-radius:3px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);border:1px solid var(--dsw-alias-border-l1)}.cm-ug-cell.l1,.cm-ug-cell.l2,.cm-ug-cell.l3,.cm-ug-cell.l4{border-color:transparent}.cm-ug-cell.l1{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 25%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l2{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 50%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l3{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 75%,var(--dsw-alias-bg-layer-3))}.cm-ug-cell.l4{background:var(--dsw-alias-state-business-primary)}.cm-ug-cell.today{outline:1px solid var(--dsw-alias-label-secondary);outline-offset:1px}.cm-ug-months{display:grid;grid-auto-flow:column;gap:3px;width:100%;font-size:10px;color:var(--dsw-alias-label-tertiary);margin-top:4px}.cm-ug-monthc{white-space:nowrap}.cm-budget-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-budget-line.over{color:var(--dsw-alias-state-error-primary)}.cm-peak-strip{display:flex;align-items:center;gap:6px;margin-top:4px;min-width:0}.cm-peak-track{position:relative;display:flex;flex:1;height:6px;min-width:0;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-segment{height:100%;flex:1}.cm-peak-high{background:#ff9800}.cm-peak-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-marker{position:absolute;top:0;left:50%;width:2px;height:100%;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2}.cm-peak-chip{font-size:11px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-classic{position:relative;display:flex;flex-direction:column;gap:5px;margin-top:6px;min-width:0}.cm-peak-classic .cm-peak-track{flex:none;height:8px}.cm-peak-classic-marker{position:absolute;top:0;left:50%;width:4px;height:12px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%);transition:left .4s ease;z-index:2;border-radius:2px}.cm-peak-classic-marker:after{content:"";position:absolute;top:-7px;left:50%;transform:translate(-50%);border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #ff9800}.cm-peak-classic.off .cm-peak-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic.off .cm-peak-classic-marker:after{border-top-color:var(--dsw-alias-state-business-primary)}.cm-peak-classic-chip{align-self:flex-start;font-size:11px;font-weight:600;line-height:1.4;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 8px;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-strip.peak .cm-peak-chip,.cm-peak-classic.peak .cm-peak-classic-chip,.cm-peak-rail.peak .cm-peak-rail-label,.cm-peak-rail-classic.peak .cm-peak-rail-classic-label{color:#ff9800}.cm-peak-strip.off .cm-peak-chip,.cm-peak-classic.off .cm-peak-classic-chip,.cm-peak-rail.off .cm-peak-rail-label,.cm-peak-rail-classic.off .cm-peak-rail-classic-label{color:var(--dsw-alias-state-business-primary)}.cm-peak-strip.weekend .cm-peak-chip,.cm-peak-classic.weekend .cm-peak-classic-chip,.cm-peak-rail.weekend .cm-peak-rail-label,.cm-peak-rail-classic.weekend .cm-peak-rail-classic-label{color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker{border-color:#34a853}.cm-peak-classic.weekend .cm-peak-classic-marker:after{border-top-color:#34a853}.cm-peak-rail{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-track{position:relative;display:flex;flex-direction:column;width:6px;height:56px;border-radius:999px;overflow:hidden;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-segment{width:100%;flex:1}.cm-peak-rail-high{background:#ff9800}.cm-peak-rail-low{background:var(--dsw-alias-state-business-primary)}.cm-peak-rail-marker{position:absolute;left:0;top:50%;width:100%;height:2px;background:var(--dsw-alias-bg-base);box-shadow:0 0 0 1px var(--dsw-alias-label-tertiary);transform:translateY(-50%);transition:top .4s ease;z-index:2}.cm-peak-rail-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-peak-rail-classic{display:flex;flex-direction:column;align-items:center;gap:3px;width:40px;box-sizing:border-box}.cm-peak-rail-classic-track{position:relative;display:flex;flex-direction:column;width:14px;height:56px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3)}.cm-peak-rail-classic-segment{position:relative;width:100%;flex:1;overflow:hidden}.cm-peak-rail-classic-segment.peak{background:#ff9800;border-radius:999px 999px 0 0}.cm-peak-rail-classic-segment.off{background:var(--dsw-alias-state-business-primary);border-radius:0 0 999px 999px}.cm-peak-rail-classic-marker{position:absolute;left:50%;top:50%;width:12px;height:4px;background:var(--dsw-alias-bg-base);border:1.5px solid #ff9800;box-shadow:0 0 0 1px var(--dsw-alias-bg-base),0 0 0 2px var(--dsw-alias-label-tertiary);transform:translate(-50%,-50%);transition:top .4s ease;z-index:2;border-radius:2px}.cm-peak-rail-classic.off .cm-peak-rail-classic-marker{border-color:var(--dsw-alias-state-business-primary)}.cm-peak-rail-classic-label{font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.cm-peak-rail-classic.weekend .cm-peak-rail-classic-marker{border-color:#34a853}.cm-grid-group{grid-column:1 / -1;margin-top:8px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:4px}.cm-grid-group:first-child{margin-top:0}.cm-peak-preview{margin-top:8px}.cm-toggle-btn{background:none;border:none;padding:0;font-size:12px;font-weight:600;color:var(--dsw-alias-state-business-primary);cursor:pointer}.cm-toggle-btn:hover{text-decoration:underline}.cm-collapsed-note{margin-top:4px}.cm-catalog-vendor{margin-top:10px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-tertiary);border-bottom:1px solid var(--dsw-alias-border-l1);padding-bottom:2px;display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-vendor-toggle{cursor:pointer;user-select:none}.cm-vendor-toggle:hover{color:var(--dsw-alias-label-secondary)}.cm-vendor-display{display:inline-flex;align-items:center;gap:4px;font-weight:400;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}.cm-catalog-family{margin:6px 0 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}.cm-catalog-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px}.cm-catalog-mounted{display:flex;flex-direction:column;gap:4px;padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1)}.cm-catalog-id{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-catalog-price{color:var(--dsw-alias-label-secondary);white-space:nowrap;font-size:11px}.cm-catalog-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);white-space:nowrap}.cm-mstats-tabs{display:flex;gap:8px;margin-bottom:8px}.cm-mstats-tab{background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:2px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}.cm-mstats-tab.active{background:var(--dsw-alias-state-business-primary);border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-bg-base);font-weight:600}.cm-mstats-h{margin:10px 0 4px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}.cm-mstats-row{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:8px;align-items:center;font-size:11px;line-height:1.7}.cm-mstats-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-barbg{position:relative;height:10px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden;display:flex}.cm-mstats-bar{height:100%;min-width:0;border-radius:999px}.cm-mstats-bar.cost{background:#ff9800}.cm-mstats-bar.hit{background:#34a853}.cm-mstats-bar.value{background:#a142f4}.cm-mstats-seg{height:100%;min-width:0}.cm-mstats-seg.in{background:var(--dsw-alias-state-business-primary)}.cm-mstats-seg.cache{background:#ff9800}.cm-mstats-seg.out{background:#34a853}.cm-mstats-val{white-space:nowrap;color:var(--dsw-alias-label-secondary)}.cm-mstats-legend{display:flex;gap:12px;font-size:10px;color:var(--dsw-alias-label-tertiary);margin:2px 0 4px}.cm-mstats-dot{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.cm-mstats-note{margin-top:10px;font-size:10px;line-height:1.6;color:var(--dsw-alias-label-tertiary)}.cm-match-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:12px;flex-wrap:wrap}.cm-match-row .cm-input{flex:1;min-width:160px}.cm-budget-controls{display:grid;grid-template-columns:repeat(2,minmax(180px,1fr));gap:12px}.cm-bbox{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:6px;min-width:148px;box-sizing:border-box}.cm-bbox.rail{padding:6px;min-width:0;width:40px;align-items:center;justify-content:center;border-radius:10px}.cm-bbox.warn{border-color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over{border-color:var(--dsw-alias-state-error-primary)}.cm-bbox-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.cm-bbox-label,.cm-bbox-pct{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct{color:var(--dsw-alias-state-error-primary)}.cm-bbox-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);overflow:hidden}.cm-bbox-bar.segments{display:flex;height:8px}.cm-bbox-bar.segments .cm-bbox-fill{flex:none;border-radius:0;height:100%}.cm-bbox-bar.segments .cm-bbox-fill:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments .cm-bbox-seg-today{flex:none;height:100%;background:#ff9800}.cm-bbox-bar.segments .cm-bbox-seg-spent{flex:none;height:100%;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-fill:first-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:first-child{border-radius:999px 0 0 999px}.cm-bbox-bar.segments.rev .cm-bbox-fill,.cm-bbox-bar.segments.rev .cm-bbox-fill:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-today:last-child,.cm-bbox-bar.segments.rev .cm-bbox-seg-spent:last-child{border-radius:0 999px 999px 0}.cm-bbox-bar.segments.rev .cm-bbox-seg-spent{border-radius:0}.cm-dir-row{display:flex;align-items:center;gap:8px;margin-top:6px}.cm-dir-label{flex:1 1 40%;font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-dir-row .cm-input{flex:1 1 60%;width:auto}.cm-bbox-fill{height:100%;border-radius:999px;background:var(--dsw-alias-state-business-primary)}.cm-balance-name{display:inline-flex;align-items:center;gap:4px;min-width:0}.cm-model-costs{font-size:12px}.cm-model-costs .cm-bal-label{white-space:nowrap}.cm-model-top{gap:4px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.cm-model-costs .cm-collapse-h{min-width:0;width:100%;white-space:nowrap}.cm-model-costs .cm-bbox-bar{margin-top:3px}.cm-bal-label{min-width:0;overflow:hidden;text-overflow:ellipsis}.cm-bal-amt{margin-left:auto;text-align:right;flex-shrink:0}.cm-bbox-pct.cm-bal-amt{color:var(--dsw-alias-state-business-primary)}.cm-bal-link{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:2px;border-radius:4px;font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary);text-decoration:none;outline:none}.cm-bal-link:hover{color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-interactive-bg-hover)}.cm-bal-link:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-brand-primary)}.cm-bbox.warn .cm-bbox-fill,.cm-bbox .cm-bbox-section.warn .cm-bbox-fill,.cm-bbox .cm-mm-row.warn .cm-bbox-fill,.cm-budget-fill.warn{background:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-fill,.cm-bbox-section.over .cm-bbox-fill,.cm-mm-row.over .cm-bbox-fill,.cm-budget-fill.over{background:var(--dsw-alias-state-error-primary)}.cm-bbox-line{font-size:12px;color:var(--dsw-alias-label-tertiary)}.cm-bbox-rail{font-size:11px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-bbox.warn .cm-bbox-pct,.cm-bbox.warn .cm-bbox-rail,.cm-bbox .cm-bbox-section.warn .cm-bbox-pct,.cm-bbox .cm-mm-row.warn .cm-bbox-pct,.cm-mm-row.warn .cm-bbox-label,.cm-corner-chip.warn,.cm-qchip.warn,.cm-simple-summary.warn{color:var(--dsw-alias-state-warn-primary)}.cm-bbox.over .cm-bbox-pct,.cm-bbox.over .cm-bbox-rail,.cm-bbox-section.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-pct,.cm-mm-row.over .cm-bbox-label,.cm-corner-chip.over,.cm-qchip.over,.cm-simple-summary.over{color:var(--dsw-alias-state-error-primary)}.cm-bbox-pair{display:flex;flex-direction:column;gap:0;padding:2px 10px}.cm-bbox-pair .cm-bbox-section{display:flex;flex-direction:column;gap:4px;padding:4px 0}.cm-bbox-pair .cm-bbox-bar{height:4px}.cm-bbox-divider{height:1px;background:var(--dsw-alias-border-l1);margin:0}.cm-bbox.clickable,.cm-foot.clickable{cursor:pointer}.cm-bbox.clickable:hover{border-color:var(--dsw-alias-state-business-primary)}.cm-bbox.clickable:focus-visible,.cm-foot.clickable:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}@keyframes cm-click-refresh-pulse{0%,to{opacity:.55}50%{opacity:1}}.cm-bbox.clickable.busy,.cm-foot.clickable.busy{animation:cm-click-refresh-pulse 1.1s ease-in-out infinite}.cm-mm{padding:8px 10px;gap:4px}.cm-mm-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}.cm-mm-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);grid-column:1/-1}.cm-gw-switcher{cursor:pointer;user-select:none;font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary)}.cm-gw-switcher:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.cm-gw-sub{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-mm-row{display:flex;align-items:center;gap:8px;padding:2px 0}.cm-mm-row .cm-bbox-label{flex:none;width:auto;min-width:22px;max-width:115px;font-weight:400;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;word-break:keep-all}.cm-mm-row .cm-bbox-bar{flex:1;min-width:40px;height:6px}.cm-mm-row .cm-bbox-pct{flex:none;min-width:2.4em;text-align:right;font-variant-numeric:tabular-nums}.cm-mm-row.wide .cm-bbox-label{width:auto;max-width:64px;flex:0 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-mm-row.wide .cm-mm-text{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-bal-line{font-size:13px;color:var(--dsw-alias-label-secondary)}.cm-bal-line.warn{color:var(--dsw-alias-state-warning-primary,#b45309)}.cm-footer-stack{display:flex;flex-direction:column;gap:6px;width:100%;align-items:stretch;box-sizing:border-box}.cm-footer-stack.rail{align-items:center}.cm-footer-stack .cm-bbox{width:100%;min-width:0}.cm-footer-stack .cm-foot{width:100%;box-sizing:border-box}.cm-footer-stack.compact .cm-bbox{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:2px;align-items:center}.cm-footer-stack.compact .cm-bbox>*{grid-column:1/-1}.cm-footer-stack.compact .cm-bbox>.cm-mm-row{grid-column:auto}.cm-footer-stack.compact .cm-mm-row{min-width:0;gap:4px;flex-wrap:nowrap}.cm-footer-stack.compact .cm-mm-row .cm-bbox-label{flex:0 1 auto;min-width:0;max-width:45%;width:auto}.cm-footer-stack.compact .cm-mm-row .cm-bbox-bar{min-width:0;flex:1 1 0}.cm-footer-stack.simple{gap:0;max-height:38vh;max-height:min(38dvh,320px);overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.cm-footer-stack.simple>*{flex-shrink:0}.cm-footer-stack.simple:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}.cm-footer-stack.simple .cm-bbox{border:0;border-radius:0;padding:4px 8px;gap:2px;background:transparent;box-shadow:inset 0 -1px var(--dsw-alias-border-l1)}.cm-footer-stack.simple .cm-mm-title{font-size:11px;line-height:16px;margin:0}.cm-footer-stack.simple .cm-mm-row{gap:6px;min-height:16px;line-height:16px;margin:0;padding:0}.cm-footer-stack.simple .cm-mm-text{font-size:11px}.cm-footer-stack.simple>.cm-peak-strip,.cm-footer-stack.simple>.cm-peak-classic{margin:0;padding:4px 8px}.cm-simple-summary>span{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-footer-stack.simple .cm-bbox-pct{font-size:12px;line-height:18px}.cm-footer-stack.simple .cm-bbox-bar{height:4px}.cm-footer-stack.simple .cm-bbox-line{display:none}.cm-footer-stack.simple .cm-foot{height:26px;padding:0 8px}.cm-footer-stack.simple .cm-peak-classic{margin-top:2px;gap:2px}.cm-footer-stack.simple .cm-peak-classic-chip{padding:0 4px;border:0;background:transparent}.cm-simple-summary{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);display:flex;justify-content:space-between;align-items:center;gap:8px;padding:5px 8px;font-size:12px;font-weight:600;border-bottom:1px solid var(--dsw-alias-border-l1)}.cm-footer-stack.simple.rail{border:0;background:transparent}.cm-footer-stack.simple.rail .cm-bbox{padding:4px 2px}.cm-footer-stack.simple .cm-peak-rail-track,.cm-footer-stack.simple .cm-peak-rail-classic-track{height:28px}@media(max-width:640px){.cm-cards,.cm-grid,.cm-budget-controls{grid-template-columns:1fr}}',jt="dsh-cost-meter/client.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(jt)+"]")===null){const t=document.createElement("style");t.dataset.plugin="dsh-cost-meter",t.dataset.pluginCss=jt,t.textContent=Ea,document.head.appendChild(t)}const Te={zh:{sessionCostTitle:"本会话费用(按每次调用实际时刻精确计费)",sessionDetailTokens:"输入 {input} · 缓存 {cache} · 输出 {output}",sessionDetailCache:"缓存:读 {read} · 写 {write}(写入按命中价计费)",cost:"费用 {amount}",sessionLine:"本会话 {amount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",quotaUnlimited:"无限制",pricingCnyHint:"当前人民币金额来自美元价格 × 汇率 {rate}。对照官方人民币账单,请选择 CNY,再同步价格;同步会更新历史费用。",balanceQueryFailed:"余额查询失败:{message}",unknownError:"未知错误",balance:"余额",queryFailed:"查询失败",balanceTitle:"DeepSeek 开放平台账户余额",reconcileLabel:"官方余额变动与本地账本交叉对账(偏差超阈时提示)",totalBalance:"总余额 {amount}",grantedToppedUp:"赠送 {granted} · 充值 {toppedUp}",updatedAt:"更新时间 {time}",budgetOf:"预算({period})",usedOf:"已用 {used} / {amount}",todayShare:"今日 {amount} · 占预算 {pct}",monthTotal:"本月 {month} · 累计 {total}",budget:"预算",todayCostTitle:"今日费用(按官方价格精确计费)",callsTokens:"调用 {calls} 次 · 输入 {input} · 缓存 {cache} · 输出 {output}",monthCost:"本月 {amount}",totalCost:"累计 {amount}",today:"今日",periodDay:"今日",periodMonth:"本月",periodAll:"累计",periodCustomRange:"自定义区间",noHistory:"暂无历史记录。开始对话后,费用将按天汇总在这里。",colDate:"日期",colCalls:"调用",colInTok:"输入 tok",colCacheTok:"缓存 tok",colOutTok:"输出 tok",colCost:"费用",noSessionsToday:"今日暂无会话记录。",colSession:"会话",enableBudget:"启用预算",budgetAmountLabel:"预算额度(按显示币种)",budgetPeriodLabel:"预算周期",startDate:"开始日期",endDate:"结束日期(留空 = 今日)",rangeText:"统计区间:{range}",budgetDisabledNote:"启用预算后显示额度、已用金额及比例(按显示币种换算);可选今日、本月、累计或自定义周期。",budgetStatus:"{period}预算 {amount} · 已用 {used} · {pct}%",overLimit:"(已超出)",nearLimit:"(接近上限)",legacyModel:"旧模型",defaultFallback:"默认回退",remove:"移除",tierBase:"基础",tierOffPeak:"谷时",tierPeak:"峰时",balanceRefreshFailed:"余额刷新失败:{message}",balanceLine:"总余额 {total} · 赠送 {granted} · 充值 {toppedUp} · 更新于 {time}",balanceQueryFailedHint:"余额查询失败:{message}(使用 设置→模型 中配置的 API Key)",balanceNotQueried:"未查询余额",accountBalance:"官方账户余额",refreshing:"刷新中…",refreshBalance:"刷新余额",customBalanceTitle:"自定义 Provider 余额",customBalanceAdd:"添加配置",aliyunBalanceAdd:"添加千问 / 阿里云余额",aliyunBalanceNote:"查询阿里云中国站资金账户可用金,按接口币种显示。使用有 bss:DescribeBillingAccount 权限的 RAM AccessKey,不用千问 API Key。前两项必填;STS 临时凭据才需 Security Token。密钥只存凭据库。",customBalanceConfigNote:"extract 支持点路径、数值和 add/subtract/divide 运算;NewApi quota 除以 500000 得到美元。",customBalanceLabelZh:"中文名称",customBalanceLabelEn:"英文名称",customBalanceUrl:"请求 URL",customBalanceMethod:"请求方法",customBalanceHeaders:"请求头 (JSON)",customBalanceBody:"请求体 (JSON)",customBalanceBodyNote:"留空不发送;JSON 原文保存并发送。默认 Content-Type 为 application/json,可在请求头覆盖。",customBalanceExtract:"解析规则 (JSON)",customBalanceDisplayLabel:"自定义余额显示位置",customBalanceRefreshInterval:"刷新间隔 (分钟)",customBalanceUnitLabel:"余额原币种",customBalanceConvert:"按显示币种折算(USD 余额)",customBalanceConvertNote:"使用显示汇率与精度;余额币种保持端点原币种。其他币种及积分不折算。",balanceBarRemaining:"余额 {amount}",balanceBarToday:"当日已用 {amount}",balanceBarSpent:"已用 {amount}",balanceShowProgressBar:"余额进度条 (蓝=余额,橙=当日,灰=已用)",barDirectionsTitle:"进度条方向",barDirectionsHint:"各组进度条可独立选择填充方向:「剩余方向」满条起步、随消耗递减;「已用方向」空条起步、随消耗填满。",barDirection_balance:"余额条(官方/自定义)",barDirection_budget:"预算条",barDirection_go:"Go 额度条",barDirection_plan:"Plan / Codex 额度条",barDirectionRemaining:"剩余方向(满 → 空)",barDirectionUsed:"已用方向(空 → 满)",balanceBudgetCapLabel:"额度上限 (可选)",balanceBudgetCapHint:"留空则优先使用 API 返回的 max_budget;仍无则显示整条浅蓝",customBalanceInvalidJson:"JSON 格式无效",customBalanceHeadersVarNote:"{{VAR_NAME}} 从 DSH 凭据库或环境变量读取,不落盘。<ROUTE>_API_KEY 的 ROUTE 是 Provider ID 大写、符号换下划线:openai→OPENAI_API_KEY、abc23-d→ABC23_D_API_KEY。同名共用密钥。",customBalanceAllowedHosts:"凭据白名单 (逗号分隔)",customBalanceAllowedHostsHint:"请求头带密钥时仅放行列表内主机,留空则放行并警告,防导入他人配置外带密钥。",customBalanceCredentialsTitle:"凭据输入",customBalanceCredentialsHint:"为上方 {{VAR}} 占位符存入密钥(write-only,只写凭据库,不回显):",customBalanceNoPlaceholders:'请求头还没有 {{VAR}} 占位符:填入如 "Authorization": "Bearer {{MY_API_KEY}}" 后这里会出现凭据输入框。',enable:"启用",customBalanceLine:"剩余 {remaining} · 已用 {spend} / 额度 {maxBudget} · 更新于 {time}",customBalanceRemaining:"剩余 {amount}",refreshCustomBalance:"刷新自定义余额",goQuotaTitle:"OpenCode Go 订阅额度",goQuotaRowLabel:"Go",goWindowRolling:"滚动 5 小时",goWindowWeekly:"本周",goWindowMonthly:"本月",goResetAt:"重置:{time}",resetReached:"已到重置时间",resetDays:"剩余 {d}天{h}小时",resetHours:"剩余 {h}小时{m}分",resetMinutes:"剩余 {m}分钟",quotaUsed:"已用 {pct}%",quotaRemaining:"剩余 {pct}%",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"更新于 {time}",goQuotaDisplayLabel:"Go 额度显示位置",goQuotaRefreshIntervalLabel:"Go 额度刷新间隔(分钟)",goQuotaRefreshMinutesUnit:"分钟",goQuotaKeyLabel:"OpenCode Go API Key(可选,留空自动发现)",goMainLabel:"Go 额度主档位",goDetailLabel:"Go 图框详细信息",credentialConfiguredOf:"已配置(来源:{source})",credentialNotConfigured:"未配置",credentialSave:"保存",credentialClear:"清除",credentialSaving:"保存中…",credentialInputHint:"密钥只写入 DSH 凭据库,不保存在账本里,也不会回显。",secretMigrationPending:"以下密钥仍在本地账本,未迁入凭据库。请导出对应环境变量后重启:",budgetDetailLabel:"预算图框详细信息",refreshGoQuota:"刷新额度",goQuotaNotQueried:"未查询额度",codingPlanAnthropic:"Anthropic(Claude Pro/Max)",codingPlanZai:"Z.ai / 智谱 GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"查询域名(HTTPS)",minimaxOriginNote:"留空自动选择官方站点。填写后 Key 仅发往该域名;使用可信地址,不含路径。",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"打开 DeepSeek 充值页(platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) 周额度",codexQuotaEnabled:"显示 Codex 额度(需安装并登录 dsh-openai-codex)",includeSubagentCost:"本会话费用包含子代理",gatewayQuotaEmpty:"暂无额度数据",codingPlanDisplayLabel:"显示位置",codingPlanDisplayNote:"选「主页面侧边栏 / 两者」后显示额度卡片;窄栏显示百分比。",codingPlanKeyLabel:"API Key(可选,留空自动发现)",codingPlanRefreshIntervalLabel:"刷新间隔(分钟)",refreshCodingPlan:"刷新",codingPlanNotQueried:"未查询额度",gatewayQuotaTitle:"CLIProxyAPI 网关额度",gatewaySourceAdd:"添加来源",gatewaySourceLabel:"来源名称",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"显示位置",gatewaySourceAllowlist:"允许的 Host",gatewaySourceCredential:"Management Key(只写)",gatewaySourceStatus:"状态",gatewaySourceUnsupported:"不支持的 Provider",gatewaySourceUnknown:"未知",gatewaySourceNoAccounts:"未发现账号",gatewaySourceFetchedAt:"抓取于 {time}",gatewaySwitchAccount:"切换账号 (当前: {account})",gatewayOnlyGemini:"只显示 Gemini 额度",refresh:"刷新",quotaEnableFirst:"先勾选启用这一项",quotaRefreshReady:"启用并保存显示位置后可刷新",quotaRemove:"删除",quotaSectionNote:"勾选启用后会排到最上面;点名称可展开该项自己的配置。自定义余额最多 8 条,网关来源最多 4 条。",codingPlanDisabledNote:"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。",goQuotaDisabledNote:"开启后读取 OpenCode Go 的滚动 5 小时、周、月额度,显示在侧栏、设置页及右下角;无订阅时提示原因。",cornerLabel:"右下角显示(dock)",cornerEnabledLabel:"在右下角显示 OpenCode Go 额度 / 预算",cornerGoRolling:"滚动 5 小时额度",cornerGoWeekly:"本周额度",cornerGoMonthly:"本月额度",cornerBudget:"预算已用%",goShortRolling:"5h",goShortWeekly:"周",goShortMonthly:"月",goShortDaily:"日",budgetShort:"预算",ledgerReadFailed:"账本读取失败:{message}",readingLedger:"正在读取账本…",ledgerUnavailable:"账本不可用",syncFailed:"同步失败:{message}",historyCleared:"历史记录已清除。",clearFailed:"清除失败:{message}",peakOff:"峰谷计价已关闭,按基础价格计费",peakNotEffective:"尚未生效(生效时间:{time}),当前按基础价格计费",peakActive:"当前处于峰时段,按峰时价计费",peakNotice:"当前为 DeepSeek 峰时高价时段,按峰时价计费",offPeakActive:"当前处于谷时段,按谷时价计费",weekendAllOffPeak:"周末时段——全谷价(周六及周日全天按谷时价计费)",weekendChip:"周末时段——全谷价",weekendShort:"周末全谷",holidayAllOffPeak:"法定假日——全天谷价",holidayChip:"法定假日——全谷价",holidayShort:"假日",peakHolidaysLabel:"法定假日(北京日期,逗号分隔)",weekendRuleNote:"自 2026-08-23 北京时间 00:00 起,周末和中国公众假期全天谷价;调休上班的周末仍按谷价。",peakShort:"峰时",offPeakShort:"平价",peakStyleLabel:"峰谷时段条样式",peakStyleCompact:"简洁(单行紧凑)",peakStyleClassic:"经典(分段与胶囊芯片)",peakAlertLabel:"峰/谷切换前弹窗提醒",peakAlertAheadLabel:"提前提醒(分钟,1-30)",peakAlertTargetLabel:"提醒类型",peakAlertTargetPeak:"进入峰时",peakAlertTargetOffPeak:"进入谷时",peakAlertTargetBoth:"峰和谷",peakAlertTitlePeak:"即将进入峰时",peakAlertTitleOffPeak:"即将进入谷时",peakAlertBody:"约 {time} 后计费档位切换为{phase}价,请注意本时段调用成本。",peakAlertPhasePeak:"峰时",peakAlertPhaseOffPeak:"谷时",peakAlertBtn:"知道了",peakAlertBadgePeak:"峰价提醒",peakAlertBadgeOffPeak:"谷价提醒",peakAlertPositionLabel:"弹窗位置",peakAlertPositionCorner:"右下角",peakAlertPositionCenter:"屏幕中心",peakAlertWebNotifyLabel:"同步发送系统通知",peakAlertWebNotifyHint:"开关后请在浏览器地址栏允许通知权限,才能在页面最小化/切走时收到提醒。",peakAlertPreviewLabel:"预览弹窗",peakAlertPreviewPeak:"预览 进入峰",peakAlertPreviewOffPeak:"预览 进入谷",peakAlertPreviewTag:"(预览)",peakPanelTitle:"峰谷计价与提示",peakNoticeHiddenHint:"提示已隐藏:需启用峰谷计价并开启「峰时高价时段显著提示」。",groupGeneral:"常规",groupMoney:"金额与币种",groupSidebar:"侧边栏显示",sidebarSimple:"简化侧栏显示",sidebarSimpleNote:"精简卡片,保留金额、额度和悬停详情;高度最多占屏幕 38%,超出可滚动。关闭后恢复。",sidebarSimpleTitle:"试试更轻巧的侧栏",sidebarSimpleBody:"简化显示可以为会话列表留出更多空间。要现在开启吗?之后可在「设置 → 费用 → 显示」中切换。",sidebarSimpleOn:"开启简化显示",sidebarSimpleOff:"保留当前显示",sidebarSimpleError:"设置未能保存。可重试,或关闭提示后在设置中调整。",closeGuide:"关闭提示",todayBudget:"今日 / {period}预算",sidebarStyleLabel:"侧边栏进度条样式",sidebarStyleStandard:"标准",sidebarStyleCompact:"紧凑(两列)",restorePriceMatches:"恢复已移除的模型 ({count})",removePriceMatchHint:"移除会清除手动映射并隐藏此行,可恢复;不会删除用量记录,后续按自动匹配规则计价。",groupCorner:"右下角角标",groupDetail:"图框详细信息",catalogTitle:"拓展价格表",catalogNote:"按厂商、模型家族分类的只读参考价。挂载后复制到可编辑价格表并计费;DeepSeek 取消挂载后用默认价,可重新挂载。",catalogOpen:"展开拓展价格表",catalogCollapse:"收起拓展价格表",mountBtn:"挂载",unmountBtn:"取消挂载",mountedTag:"已挂载",catalogUnpriced:"未核价",catalogDeepseekNote:"DeepSeek 模型支持峰谷两档;取消挂载后按默认价计费且不再被自动匹配命中。",modelStatsTitle:"按模型统计(token 与费用)",modelsTitle:"侧栏模型花费",modelsCount:"{n} 模型",modelsOther:"其它",models_enabled:"显示模型花费卡片",models_defaultOpen:"默认展开",models_remember:"记住展开状态",models_tokens:"显示 Token",models_shares:"显示费用占比条",models_dock:"右下角显示 Top-1 模型",models_period:"默认周期",models_summary:"收起摘要",models_position:"卡片位置",models_topN:"模型行数(1–10)",models_refreshSeconds:"刷新间隔(10–60 秒)",modelsTotal:"周期总额与模型数",modelsTop:"Top-1 模型与金额",modelsFirst:"顶部",modelsAfter:"余额之后",modelsLast:"底部",modelStatsToday:"今日",modelStatsHistory:"近 90 天",modelStatsCostH:"费用排行",modelStatsTokensH:"Token 消耗",modelStatsHitH:"缓存命中率",modelStatsHitUnreported:"未上报?",modelStatsHitUnreportedTip:"长调用始终无缓存命中,代理可能移除缓存字段或破坏缓存。命中率未知;全未命中价是金额上界,可直连官方 API 核对。",modelStatsValueH:"性价比 · 每美元 token 数",modelStatsInput:"输入",modelStatsCache:"缓存",modelStatsOutput:"输出",modelStatsEmpty:"该时段暂无用量数据。",modelStatsBlended:"综合单价 {price}/M",modelStatsNote:"命中率=缓存读÷(缓存读+普通输入);「未上报?」表示可能缺缓存字段(常见于代理),金额按全未命中计(上界);单价=费用÷总 token×1M(USD/M);性价比=总 token÷费用。按调用时美元价计。",modelStatsLegacy:"未分模型(早期数据 · 按当时记录计费)",sessionLineSplit:"本会话 {amount}(API)· Plan 等值 {planAmount} · 命中 {hitRate} · 输入 {input} · 缓存 {cache} · 输出 {output}",costChipPlan:"费用 {amount}(+Plan)",sessionDetailPlan:"Plan 订阅额度消耗(等值){amount}",planStatsTitle:"Token Plan 用量统计(每 1% 与满窗估算)",planStatsEmpty:"暂无已启用的 Coding Plan 额度数据;在「额度」标签启用并成功刷新后,这里会显示各窗口的每 1% 额度与满窗用量估算。",planStatsWindow:"窗口",planStatsPercent:"已用 %",planStatsLocal:"本周期实际(本地账本)",planStatsPer1:"每 1% 额度 ≈",planStatsFull:"满窗 100% ≈",planStatsResets:"重置 {time}",planStatsMethodSample:"采样差分",planStatsMethodLive:"当前用量折算",planStatsMethodNone:"样本不足",planStatsMethodSampleAt:"{method}(基准 {time})",planStatsConfidenceLow:"读数精度受限",planStatsCurveTitle:"Plan 用量曲线(按采样区间聚合)",planStatsDaily:"每日",planStatsWeekly:"每周",planStatsMonthly:"每月",planStatsCurveEmpty:"采样区间尚不足(至少两次成功刷新且百分比有变化),曲线会在持续使用后逐步成形。",planStatsBarTip:"{date}:满窗估计 ≈ {full}(每 1% ≈ {per1})· 实际 {tokens} / {cost} · {intervals} 个采样区间",planStatsNote:"金额为目录 API 价等值(订阅耗额度,预算只计 API);估算仅含 dsh 调用,服务端已用%按全账号计;每 1%/满窗由可信样本差分估算(短段精度受限);5h 滚动,周/月按本地日历。",billingClassLabel:"计费方式",billingClassPlan:"Plan 订阅",catalogDisplayLabel:"在费用设置直接显示",catalogDisplayHint:"仅控制是否在费用价格表直接显示;不影响挂载和计费。隐藏的已挂载模型仍可在拓展表编辑。",priceTableDisplayHint:"在下方拓展表逐模型切换直接显示。DeepSeek 默认直接显示;第三方模型挂载后默认留在拓展表。",catalogCustomModels:"手动新增模型",priceMatchLabel:"未知模型名自动匹配",priceMatchAuto:"自动(去后缀 / 前缀 / 家族相似)",priceMatchExact:"仅精确匹配",priceMatchNote:"匹配顺序:精确→手动指定→去版本后缀→前缀→家族;未匹配的 DeepSeek 用默认价,其他 provider 不计价。",unmatchedTitle:"最近出现但未命中价格的模型",unmatchedHint:"当前模式未匹配价格(含跨厂商兜底价)。指定条目会保存手动覆盖;「默认价」使用 DeepSeek 默认价。本地推理(lmstudio/ollama/vLLM)默认零费用,需在此指定价格。",overrideTargetDefault:"DeepSeek 默认价",overrideRemove:"移除",overrideTargetLocal:"本地模型(零消耗)",matchedTitle:"本月已命中价格的模型",matchedHint:"以下模型自动匹配价格。可改选其它条目或「本地模型(零消耗)」:token 仍统计,历史费用即时归零。保存后移入上方手动指定区。",matchedKeepAuto:"保持自动命中",overrideNone:"暂无手动匹配覆盖。",mountedSuffix:"已挂载(参与计费)",flatInput:"输入",flatCached:"缓存",flatOutput:"输出",deepseekMountedHeader:"DeepSeek 价格表(已挂载)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow 硅基流动",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet 超算互联网 Token Plan",codingPlanVolcengine:"火山方舟 Volcano Ark Coding Plan",codingPlanQwen:"千问 Qwen Token Plan",codingPlanMimo:"小米 MiMo Token Plan",mimoWindowPlan:"套餐积分",mimoWindowCompensation:"补偿积分",codingPlanWindowBalance:"余额",qwenSource:"额度来源",qwenSourceLocal:"本地估算",qwenSourceCli:"官方 CLI",qwenSourceBailian:"百炼 CLI",qwenCliNote:"CLI 模式需在 DSH 主机安装 @qianwenai/qianwen-cli,并以同一系统账号运行 qianwen auth login。",qwenBailianNote:"百炼 CLI:在 DSH 主机安装 bailian-cli 并以同一系统账号运行 bl auth login --console。",qwenPlanCreditsLabel:"月度 Credits 额度(个人版 Lite 5 万 / 标准版 50 万,以订阅页为准)",qwenPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",qwenRatesLabel:"Credits 抵扣率覆盖(可选;每百万 token 抵扣的 Credits,留空用内置表)",qwenRatesModelPlaceholder:"模型名,如 qwen3.8-max-preview",qwenRatePlaceholder:"费率",qwenRate_input:"输入",qwenRate_cachedInput:"缓存读",qwenRate_output:"输出",qwenRateDraftNote:"待填齐三项正数后自动保存;全部清空恢复内置表。",qwenRatesAdd:"添加",qwenLocalNote:"本地估算,Credits 以控制台为准。只计 qwen、qwen-tokenplan、qianwen-tokenplan、qwen-token-plan、qianwen-token-plan 订阅渠道(含 llm- 前缀);排除 API 与 qianwen 按量渠道。表外模型需设抵扣率。",scnetPlanCreditsLabel:"本地估算月度 Credits 额度(基础 60,000 / 标准 240,000 / 高级 600,000)",scnetPlanStartLabel:"订阅起始日(可选,格式 YYYY-MM-DD;留空按自然月)",scnetLocalNote:"可接入最长 24 小时的控制台快照;否则按官方 Credits 表从本地账本估算。其他工具和表外模型未计入;以控制台为准。",volcengineAccessKeyIdLabel:"火山引擎 AccessKey ID",volcengineSecretAccessKeyLabel:"火山引擎 SecretAccessKey",volcengineNote:"火山方舟使用 AK/SK HMAC 签名(非 ARK_API_KEY)。IAM 需 ArkReadOnlyAccess + BillingCenterReadOnlyAccess;填 AccessKeyID/SecretAccessKey 或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。仅发送至 open.volcengineapi.com。",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}小时",countdownHourMinute:"{h}小时{m}分",countdownMinute:"{m}分钟",nextOffPeakIn:"{time}后进入平价",nextPeakIn:"{time}后进入高峰",peakSummary:"峰时段(UTC):{windows};生效时间:{time}。{status}",noPeakWindows:"未配置峰谷时段。{status}",unknown:"未知",cardToday:"今日费用",cardMonth:"本月费用",cardTotal:"累计费用",cardTotalSub:"自账本建立以来 · 调用 {calls} 次",externalUsage:"外部用量",combinedUsage:"DSH + 外部合计",externalStale:"外部快照超过 24 小时未更新",externalHistory:"近期每日记录",cardsFootnote:"金额取最近落盘快照(2 秒防抖,关闭时落盘),可能比官方账单晚几分钟。tokens 含输入、输出、缓存、推理;推理不另计费(官方并入输出)。以金额对账。",timezoneHint:"今日/本月按宿主时区 {host} 取日界,不同于浏览器({browser});本地午夜后调用可能计入前一天,对账也可能偏差。让 dsh 使用本地时区即可对齐。",todaySessions:"今日会话",historyExpandHint:"点击日期行可展开当日会话明细",historySessionsLoading:"会话明细加载中…",historyNoSessions:"该日无会话明细(早期数据或会话日志已清理)",historySessionsError:"会话明细加载失败",sessionRankTitle:"按会话统计(全部历史)",sessionRankHint:"不按日期分组,全部历史会话;排序与条数可切换",sessionRankEmpty:"暂无会话数据",sessionRankLoading:"会话排行加载中…",sessionRankError:"会话排行加载失败",sessionRankLimit:"显示条数",showSessionIdLabel:"会话列表附显会话 ID",cardsTogglePlanTotal:"金额含 Plan 总额",cardsTogglePlanTotalHint:"开启后所有金额按含 Plan 订阅等值的总费用展示;关闭(默认)仅计真金白银 API 渠道",hideOfficialBalanceLabel:"隐藏官方账户余额(开启后侧边栏与设置页不再显示官方余额)",hideTodayCostLabel:"隐藏今日消耗金额(开启后侧边栏/预算明细/概览卡片不再显示今日费用)",sessionRankSort:"排序",sessionSortCostDesc:"费用 高→低",sessionSortCostAsc:"费用 低→高",sessionSortTimeDesc:"时间 新→旧",sessionSortTimeAsc:"时间 旧→新",sessionSortRecent:"实时顺序",history:"历史记录",usageTitle:"Token 用量统计",usageTotal:"累计 {tokens} tokens · 输入 {input} · 缓存 {cache} · 输出 {output} · {calls} 次调用",usageDay:"{date}:共 {tokens} tokens(输入 {input} · 缓存 {cache} · 输出 {output})· {calls} 次调用 · {cost}",usageEmpty:"暂无历史数据,开始对话后每日用量会汇总在这里",usageSectionLabel:"用量",usagePositionLabel:"Token 用量统计位置",usagePositionCost:"费用设置",usagePositionGeneral:"通用设置",usagePositionSection:"独立分节(用量)",displaySettings:"显示设置",tabOverview:"概览",tabQuotas:"额度",tabUsage:"用量",tabPricing:"价格",tabDisplay:"显示",historyDataTitle:"历史数据",positionLabel:"会话费用显示位置",positionDock:"输入区下方",positionHeader:"会话标题栏",off:"关闭",quotaStripGroup:"输入框上方额度横条",quotaStripEnable:"启用额度横条(输入框上方一条横排显示)",quotaStripShowBudget:"横条含预算已用%",quotaStripShowGo:"横条含 Go 额度",quotaStripShowPlans:"横条含 Coding Plan 额度",quotaStripNote:"横条悬停可见各窗口重置时刻与更新时间;无可用额度数据时自动隐藏。",quotaStripGuideTitle:"新增:输入框上方额度横条",quotaStripGuideBody:"在输入框上方显示预算及 OpenCode Go/Coding Plan 额度百分比。现在开启吗?可在「设置 → 显示设置」修改。",quotaStripGuideOn:"开启横条",quotaStripGuideOff:"暂不开启",clickToRefresh:"点击立即刷新",balanceClickGuideTitle:"新增:余额图框点击刷新",balanceClickGuideBody:"点击侧边栏余额或 Coding Plan 图框即可刷新;刷新时图框闪烁,失败时保留原值并在悬停提示中说明原因。",balanceClickGuideOk:"知道了",sidebarLabel:"当日费用显示",sidebarOn:"侧边栏底部",currencyLabel:"货币单位",currencyCny:"人民币 CNY",currencyUsd:"美元 USD",currencyEur:"欧元 EUR",symbolLabel:"货币符号",rateLabel:"汇率(1 美元 = ? 目标币种)",decimalsLabel:"小数位数",balanceDisplayLabel:"余额显示位置",balanceSidebar:"主页面侧边栏",balanceSettings:"设置页",balanceBoth:"两者都显示",refreshIntervalLabel:"余额刷新间隔(分钟)",peakEnabledLabel:"启用 DeepSeek 峰谷时段价格",peakNoticeLabel:"峰时高价时段显著提示(侧边栏预算框/今日费用;设置页峰谷面板内预览)",badgeNote:"会话按调用时价格计费(含峰谷与历史档位)。输入、输出、缓存读写分开统计;独立缓存写入价与长上下文档位按配置生效。",priceTableTitle:"价格表(美元 / 1M tokens)",pricingCurrencyLabel:"官方价格币种",pricingCurrencyUsd:"美元(英文官方页)",pricingCurrencyCny:"人民币(中文官方页)",pricingCurrencyNote:"决定同步价格所用的官方页语言。切换并同步后后台重算历史;日志不全的会话保留原价。完成后提示。",priceTableNote:"按调用时间计价:Flash 自 9 月 10 日北京 12:00 用新价,V4 Pro 自 9 月 14 日同刻用 Flash 价;此前用历史价。工作日 09–12、14–18 峰价翻倍;周末及中国公众假期全天谷价。缓存写入按命中价。",datedPriceNote:"这里显示当前适用价格。手工编辑会取消此条后续预定调价,已发生的历史价格仍保留。",defaultModelId:"default(未匹配模型时回退)",newModelPlaceholder:"新模型 ID(如 deepseek-v4-pro)",addModel:"添加模型",dataSync:"数据与同步",saving:"保存中…",autoSaveFailed:"自动保存失败:{message}",autoSavedAt:"已自动保存 {time}",autoSaveHint:"配置修改后自动保存",confirmFetch:"确认用官方文档价格覆盖价格表?",apply:"应用",cancel:"取消",syncFromDocs:"从官方文档同步价格",syncScopeNote:"官方同步只更新 DeepSeek 价格(含峰谷);z-ai/Kimi/Qwen/Volcano 等第三方价格随版本更新,也可在拓展价格表或模型名匹配中调整。",confirmReset:"确认清除全部历史?",importLegacy:"导入安装前历史",confirmImportLegacy:"确认导入?将回放全部会话日志,只补账本缺失的日期与会话,不影响已有记录。",legacyImportFailed:"导入安装前历史失败:{message}",legacyImportNote:"首次启动自动导入旧记录;拷入日志后可重跑。按当前价格回推;已删除日志无法回放,跨安装时刻的会话不计此前用量。",confirmClear:"确认清除",clearAllHistory:"清除全部历史",lastSync:"最近同步:{time}",neverSynced:"从未(使用内置价格)",source:";来源:{source}",sourceOfficial:"官方文档",sourceBundled:"内置默认",languageLabel:"界面语言",localeAuto:"跟随浏览器(自动)",localeZh:"简体中文",localeEn:"English",sectionLabel:"费用",rpcFailed:"{method} 调用失败",rpcSyncFailed:"同步调用失败",rpcBalanceFailed:"余额刷新调用失败"},en:{sessionCostTitle:"Cost of this session (billed exactly at each call time)",sessionDetailTokens:"Input {input} · Cache {cache} · Output {output}",sessionDetailCache:"Cache: read {read} · write {write} (writes billed at the hit price)",cost:"Cost {amount}",sessionLine:"This session {amount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",quotaUnlimited:"Unlimited",pricingCnyHint:"CNY totals use USD prices × {rate}. To compare official CNY bills, select CNY, then sync prices; syncing also updates historical costs.",balanceQueryFailed:"Balance query failed: {message}",unknownError:"Unknown error",balance:"Balance",queryFailed:"Query failed",balanceTitle:"DeepSeek open-platform account balance",reconcileLabel:"Cross-check official balance changes against the local ledger (warn when they diverge)",totalBalance:"Total {amount}",grantedToppedUp:"Granted {granted} · Topped-up {toppedUp}",updatedAt:"Updated {time}",budgetOf:"Budget ({period})",usedOf:"Used {used} / {amount}",todayShare:"Today {amount} · {pct} of budget",monthTotal:"This month {month} · All time {total}",budget:"Budget",todayCostTitle:"Today's cost (billed exactly at official prices)",callsTokens:"Calls {calls} · Input {input} · Cache {cache} · Output {output}",monthCost:"This month {amount}",totalCost:"All time {amount}",today:"Today",periodDay:"Today",periodMonth:"This month",periodAll:"All time",periodCustomRange:"Custom range",noHistory:"No history yet. Once you start chatting, costs are aggregated here per day.",colDate:"Date",colCalls:"Calls",colInTok:"In tok",colCacheTok:"Cache tok",colOutTok:"Out tok",colCost:"Cost",noSessionsToday:"No sessions recorded today.",colSession:"Session",enableBudget:"Enable budget",budgetAmountLabel:"Budget amount (in display currency)",budgetPeriodLabel:"Budget period",startDate:"Start date",endDate:"End date (empty = today)",rangeText:"Range: {range}",budgetDisabledNote:"Enable a budget to see its limit, used amount and percentage in the display currency. Choose today, month, all time or a custom range.",budgetStatus:"{period} budget {amount} · Used {used} · {pct}%",overLimit:" (over limit)",nearLimit:" (near limit)",legacyModel:"Legacy",defaultFallback:"Default fallback",remove:"Remove",tierBase:"Base",tierOffPeak:"Off-peak",tierPeak:"Peak",balanceRefreshFailed:"Balance refresh failed: {message}",balanceLine:"Total {total} · Granted {granted} · Topped-up {toppedUp} · Updated {time}",balanceQueryFailedHint:"Balance query failed: {message} (uses the API key configured in Settings → Models)",balanceNotQueried:"Balance not queried",accountBalance:"Account balance",refreshing:"Refreshing…",refreshBalance:"Refresh balance",customBalanceTitle:"Custom provider balance",customBalanceAdd:"Add entry",aliyunBalanceAdd:"Add Qianwen / Alibaba Cloud balance",aliyunBalanceNote:"Shows Alibaba Cloud China funds in the returned currency. Use a RAM AccessKey with bss:DescribeBillingAccount, not a Qianwen key. First two fields are required; Security Token is STS-only. Secrets stay in the credential store.",customBalanceConfigNote:"Extract accepts paths, numbers and add/subtract/divide. Divide NewApi quota by 500000 for USD.",customBalanceLabelZh:"Chinese name",customBalanceLabelEn:"English name",customBalanceUrl:"Request URL",customBalanceMethod:"HTTP method",customBalanceHeaders:"Headers (JSON)",customBalanceBody:"Request body (JSON)",customBalanceBodyNote:"Blank sends no body; JSON text is saved and sent as entered. Content-Type defaults to application/json; headers can override it.",customBalanceExtract:"Extract rules (JSON)",customBalanceDisplayLabel:"Custom balance display",customBalanceRefreshInterval:"Refresh interval (minutes)",customBalanceUnitLabel:"Source currency",customBalanceConvert:"Convert USD balance to display currency",customBalanceConvertNote:"Uses the display rate and precision. Keep the source currency; other currencies and credits stay unchanged.",balanceBarRemaining:"Balance {amount}",balanceBarToday:"Today {amount}",balanceBarSpent:"Spent {amount}",balanceShowProgressBar:"Balance progress bar (blue=balance, orange=today, gray=spent)",barDirectionsTitle:"Progress bar direction",barDirectionsHint:'Each group of bars can independently choose its fill direction: "Remaining" starts full and drains with usage; "Used" starts empty and fills up.',barDirection_balance:"Balance bars (official/custom)",barDirection_budget:"Budget bar",barDirection_go:"Go quota bar",barDirection_plan:"Plan / Codex quota bars",barDirectionRemaining:"Remaining (full → empty)",barDirectionUsed:"Used (empty → full)",balanceBudgetCapLabel:"Budget cap (optional)",balanceBudgetCapHint:"Leave empty to use API max_budget; if still missing, show full light-blue bar",customBalanceInvalidJson:"Invalid JSON",customBalanceHeadersVarNote:"{{VAR_NAME}} reads a DSH credential or env variable without storing it. <ROUTE>_API_KEY uses uppercase Provider ID with symbols replaced by underscores: openai→OPENAI_API_KEY, abc23-d→ABC23_D_API_KEY. Same name shares a key.",customBalanceAllowedHosts:"Allowed hosts (comma-separated)",customBalanceAllowedHostsHint:"When headers carry credentials only listed hosts are allowed; leave empty to allow with a warning. Protects keys when importing someone else's config.",customBalanceCredentialsTitle:"Credential input",customBalanceCredentialsHint:"Store the key for each {{VAR}} placeholder above (write-only: stored in the DSH credential store, never echoed back):",customBalanceNoPlaceholders:'No {{VAR}} placeholders in the headers yet — add e.g. "Authorization": "Bearer {{MY_API_KEY}}" and a credential input will appear here.',enable:"Enable",customBalanceLine:"Remaining {remaining} · Spent {spend} / Budget {maxBudget} · Updated {time}",customBalanceRemaining:"Remaining {amount}",refreshCustomBalance:"Refresh custom balance",goQuotaTitle:"OpenCode Go subscription quota",goQuotaRowLabel:"Go",goWindowRolling:"Rolling 5h",goWindowWeekly:"Weekly",goWindowMonthly:"Monthly",goResetAt:"Resets: {time}",resetReached:"Reset time reached",resetDays:"{d}d {h}h left",resetHours:"{h}h {m}m left",resetMinutes:"{m}m left",quotaUsed:"{pct}% used",quotaRemaining:"{pct}% remaining",goQuotaPercent:"{percent}%",goQuotaFetchedAt:"Updated {time}",goQuotaDisplayLabel:"Go quota display position",goQuotaRefreshIntervalLabel:"Go quota refresh interval (minutes)",goQuotaRefreshMinutesUnit:"min",goQuotaKeyLabel:"OpenCode Go API key (optional; empty = auto-detect)",goMainLabel:"Go quota primary window",goDetailLabel:"Go box details",credentialConfiguredOf:"Configured (source: {source})",credentialNotConfigured:"Not configured",credentialSave:"Save",credentialClear:"Clear",credentialSaving:"Saving…",credentialInputHint:"The key is written to the DSH credential store only — it is never saved in the ledger and never echoed back.",secretMigrationPending:"These credentials remain in the local ledger. Export the matching environment variables and restart:",budgetDetailLabel:"Budget box details",refreshGoQuota:"Refresh quota",goQuotaNotQueried:"Quota not queried",codingPlanAnthropic:"Anthropic (Claude Pro/Max)",codingPlanZai:"Z.ai / Zhipu GLM Coding Plan",codingPlanMinimax:"MiniMax Token Plan",codingPlanMinimaxTitle:"MiniMax Plan",minimaxOrigin:"Quota origin (HTTPS)",minimaxOriginNote:"Empty: official sites. Otherwise the Key is sent only to this origin. Use a trusted address without a path.",codingPlanRemain5h:"5h",codingPlanRemain7d:"7d",balanceRechargeLink:"Open DeepSeek top-up page (platform.deepseek.com/usage)",codexQuotaTitle:"ChatGPT (Codex) weekly quota",codexQuotaEnabled:"Show Codex quota (requires signed-in dsh-openai-codex)",includeSubagentCost:"Include subagents in session cost",gatewayQuotaEmpty:"No quota data",codingPlanDisplayLabel:"Display position",codingPlanDisplayNote:"“Main sidebar / Both” shows a quota card; the narrow rail shows percentages.",codingPlanKeyLabel:"API key (optional; empty = auto-detect)",codingPlanRefreshIntervalLabel:"Refresh interval (minutes)",refreshCodingPlan:"Refresh",codingPlanNotQueried:"Quota not queried",gatewayQuotaTitle:"CLIProxyAPI gateway quotas",gatewaySourceAdd:"Add source",gatewaySourceLabel:"Source label",gatewaySourceBaseURL:"Base URL",gatewaySourceDisplay:"Display",gatewaySourceAllowlist:"Allowed hosts",gatewaySourceCredential:"Management key (write-only)",gatewaySourceStatus:"Status",gatewaySourceUnsupported:"Unsupported providers",gatewaySourceUnknown:"Unknown",gatewaySourceNoAccounts:"No accounts",gatewaySourceFetchedAt:"fetched {time}",gatewaySwitchAccount:"Switch account (current: {account})",gatewayOnlyGemini:"Gemini quota only",refresh:"Refresh",quotaEnableFirst:"Enable this item first",quotaRefreshReady:"Enable and save a display position to refresh",quotaRemove:"Remove",quotaSectionNote:"Enabled items move to the top; click a name to expand its own settings. Up to 8 custom balances and 4 gateway sources.",codingPlanDisabledNote:"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.",goQuotaDisabledNote:"Enable OpenCode Go rolling 5h, weekly and monthly quotas in the sidebar, Settings and bottom-right corner. Missing subscriptions show a reason.",cornerLabel:"Bottom-right (dock) display",cornerEnabledLabel:"Show OpenCode Go quota / budget at the bottom-right",cornerGoRolling:"Rolling-5h quota",cornerGoWeekly:"Weekly quota",cornerGoMonthly:"Monthly quota",cornerBudget:"Budget used %",goShortRolling:"5h",goShortWeekly:"Wk",goShortMonthly:"Mo",goShortDaily:"Daily",budgetShort:"Budget",ledgerReadFailed:"Ledger read failed: {message}",readingLedger:"Reading ledger…",ledgerUnavailable:"Ledger unavailable",syncFailed:"Sync failed: {message}",historyCleared:"History cleared.",clearFailed:"Clear failed: {message}",peakOff:"Peak/off-peak pricing is off; base prices are used",peakNotEffective:"Not yet effective (effective at {time}); base prices are currently used",peakActive:"Peak hour now; peak prices apply",peakNotice:"DeepSeek peak-hour pricing is active; current calls are billed at peak prices",offPeakActive:"Off-peak now; off-peak prices apply",weekendAllOffPeak:"Weekend — all off-peak (Sat & Sun billed at off-peak prices all day)",weekendChip:"Weekend — all off-peak",weekendShort:"Weekend",holidayAllOffPeak:"Chinese public holiday — off-peak all day",holidayChip:"Public holiday — all off-peak",holidayShort:"Holiday",peakHolidaysLabel:"Public holidays (Beijing dates, comma separated)",weekendRuleNote:"Since Aug 23, 2026 (Beijing time), weekends and Chinese public holidays are off-peak all day, including work-shift weekends.",peakShort:"Peak",offPeakShort:"Off-peak",peakStyleLabel:"Peak period strip style",peakStyleCompact:"Compact (one-line)",peakStyleClassic:"Classic (segments & chip)",peakAlertLabel:"Popup alert before peak/off-peak switch",peakAlertAheadLabel:"Lead time (minutes, 1-30)",peakAlertTargetLabel:"Alert type",peakAlertTargetPeak:"Entering peak",peakAlertTargetOffPeak:"Entering off-peak",peakAlertTargetBoth:"Both",peakAlertTitlePeak:"Entering peak hours soon",peakAlertTitleOffPeak:"Entering off-peak hours soon",peakAlertBody:"Billing switches to {phase} pricing in about {time}; mind your call costs in this window.",peakAlertPhasePeak:"peak",peakAlertPhaseOffPeak:"off-peak",peakAlertBtn:"Got it",peakAlertBadgePeak:"Peak alert",peakAlertBadgeOffPeak:"Off-peak alert",peakAlertPositionLabel:"Popup position",peakAlertPositionCorner:"Bottom-right",peakAlertPositionCenter:"Screen center",peakAlertWebNotifyLabel:"Also send a system notification",peakAlertWebNotifyHint:"When enabled, allow notification permission in the browser address bar so you get alerted even when the page is minimized or backgrounded.",peakAlertPreviewLabel:"Preview the popup",peakAlertPreviewPeak:"Preview entering peak",peakAlertPreviewOffPeak:"Preview entering off-peak",peakAlertPreviewTag:" (preview)",peakPanelTitle:"Peak/off-peak pricing & notice",peakNoticeHiddenHint:"Notice hidden: enable peak/off-peak pricing and the “prominent notice” toggle.",groupGeneral:"General",groupMoney:"Money & currency",groupSidebar:"Sidebar display",sidebarSimple:"Simplify the sidebar",sidebarSimpleNote:"Condense cards but keep amounts, quotas and hover details. Height is capped at 38% of the viewport with scrolling. Turn off to restore.",sidebarSimpleTitle:"A lighter sidebar",sidebarSimpleBody:"Simple display leaves more room for conversations. Enable it now? You can change it in Settings → Cost → Display anytime.",sidebarSimpleOn:"Enable simple display",sidebarSimpleOff:"Keep current display",sidebarSimpleError:"Settings could not be saved. Retry or dismiss this guide and change them later in Settings.",closeGuide:"Dismiss guide",todayBudget:"Today / {period} budget",sidebarStyleLabel:"Sidebar progress style",sidebarStyleStandard:"Standard",sidebarStyleCompact:"Compact (2 columns)",restorePriceMatches:"Restore removed models ({count})",removePriceMatchHint:"Remove clears the override and hides the row until restored. Usage records are kept; automatic price matching applies.",groupCorner:"Corner chips",groupDetail:"Box details",catalogTitle:"Extended price catalog",catalogNote:"Read-only prices by vendor and model family. Mount to bill; unmount DeepSeek to restore its default price. You can remount later.",catalogOpen:"Expand extended price catalog",catalogCollapse:"Collapse extended price catalog",mountBtn:"Mount",unmountBtn:"Unmount",mountedTag:"Mounted",catalogUnpriced:"Unpriced",catalogDeepseekNote:"DeepSeek models support peak/off-peak tiers; once unmounted they bill at the default price and are no longer hit by auto-matching.",modelStatsTitle:"Per-model statistics (tokens & cost)",modelsTitle:"Sidebar model costs",modelsCount:"{n} models",modelsOther:"Other",models_enabled:"Show model cost card",models_defaultOpen:"Expand by default",models_remember:"Remember expansion",models_tokens:"Show tokens",models_shares:"Show cost shares",models_dock:"Top model in corner dock",models_period:"Default period",models_summary:"Collapsed summary",models_position:"Card position",models_topN:"Model rows (1–10)",models_refreshSeconds:"Refresh interval (10–60 seconds)",modelsTotal:"Period total and model count",modelsTop:"Top model and cost",modelsFirst:"Top",modelsAfter:"After balances",modelsLast:"Bottom",modelStatsToday:"Today",modelStatsHistory:"Last 90 days",modelStatsCostH:"Cost ranking",modelStatsTokensH:"Token usage",modelStatsHitH:"Cache hit rate",modelStatsHitUnreported:"unreported?",modelStatsHitUnreportedTip:"Zero hits on long calls may mean a relay removed cache fields or broke caching. Hit rate is unknown; all-miss cost is an upper bound. Check via direct API.",modelStatsValueH:"Value · tokens per USD",modelStatsInput:"Input",modelStatsCache:"Cache",modelStatsOutput:"Output",modelStatsEmpty:"No usage data for this period.",modelStatsBlended:"blended {price}/M",modelStatsNote:"Hit rate = cache reads ÷ (reads + uncached input). “Unreported?” suggests missing cache fields, often behind relays; all-miss cost is an upper bound. Unit cost = cost ÷ tokens × 1M; value = tokens ÷ cost. Call-time USD prices apply.",billingClassLabel:"Billing class",billingClassPlan:"Plan subscription",modelStatsLegacy:"Unattributed (early data · billed as recorded)",sessionLineSplit:"This session {amount} (API) · Plan equiv. {planAmount} · Hit {hitRate} · Input {input} · Cache {cache} · Output {output}",costChipPlan:"Cost {amount} (+Plan)",sessionDetailPlan:"Plan subscription quota usage (equiv.) {amount}",planStatsTitle:"Token Plan usage stats (per-1% & full-window estimates)",planStatsEmpty:"No enabled coding-plan quota data yet; enable and successfully refresh a provider under the Quotas tab to see per-1% and full-window usage estimates here.",planStatsWindow:"Window",planStatsPercent:"Used %",planStatsLocal:"This period actual (local ledger)",planStatsPer1:"Per 1% quota ≈",planStatsFull:"Full window (100%) ≈",planStatsResets:"resets {time}",planStatsMethodSample:"sample delta",planStatsMethodLive:"current usage ratio",planStatsMethodNone:"not enough samples",planStatsMethodSampleAt:"{method} (as of {time})",planStatsConfidenceLow:"low reading precision",planStatsCurveTitle:"Plan usage curves (aggregated from sample intervals)",planStatsDaily:"Daily",planStatsWeekly:"Weekly",planStatsMonthly:"Monthly",planStatsCurveEmpty:"Not enough sample intervals yet (at least two successful refreshes with a percent change); the curves will take shape with continued use.",planStatsBarTip:"{date}: full-window est. ≈ {full} (per 1% ≈ {per1}) · actual {tokens} / {cost} · {intervals} sample interval(s)",planStatsNote:"Amounts are catalog-price equivalents; plans use quota, budget counts API only. Estimates cover dsh calls; server used % covers the account. Per-1% and full-window estimates use sample deltas (short spans have limited precision). 5h rolls; week/month use local dates.",catalogDisplayLabel:"Show directly in Cost settings",catalogDisplayHint:"Controls direct display in Cost settings; mounting and billing stay unchanged. Hidden models remain editable in this catalog.",priceTableDisplayHint:"Toggle direct display per model below. DeepSeek appears by default; mounted third-party models stay in the extended catalog.",catalogCustomModels:"Custom models",priceMatchLabel:"Auto-match unknown model names",priceMatchAuto:"Auto (strip suffix / prefix / family similarity)",priceMatchExact:"Exact match only",priceMatchNote:"Match order: exact → manual → strip version → prefix → family. Unmatched DeepSeek uses default price; other providers stay unpriced.",unmatchedTitle:"Recently seen models without a price hit",unmatchedHint:"No price matched, including fallback. Choose an entry to bill manually; “Default price” uses DeepSeek defaults. Local models (lmstudio/ollama/vLLM) cost zero until assigned.",overrideTargetDefault:"DeepSeek default price",overrideRemove:"Remove",overrideTargetLocal:"Local model (zero cost)",matchedTitle:"Models matched this month",matchedHint:"These models matched automatically. Choose another entry or “Local model (zero cost)”. Tokens still count; historical costs become zero. Overrides move to the manual list.",matchedKeepAuto:"Keep auto match",overrideNone:"No manual match overrides.",mountedSuffix:"Mounted (billed)",flatInput:"Input",flatCached:"Cached",flatOutput:"Output",deepseekMountedHeader:"DeepSeek price table (mounted)",codingPlanKimi:"Kimi / Moonshot",codingPlanOpenrouter:"OpenRouter",codingPlanSiliconflow:"SiliconFlow",codingPlanCommandcode:"CommandCode",codingPlanScnet:"SCNet Token Plan",codingPlanVolcengine:"Volcano Ark Coding Plan",codingPlanQwen:"Qwen Token Plan (qianwenai.com)",codingPlanMimo:"Xiaomi MiMo Token Plan",mimoWindowPlan:"Plan credits",mimoWindowCompensation:"Compensation",codingPlanWindowBalance:"Balance",qwenSource:"Quota source",qwenSourceLocal:"Local estimate",qwenSourceCli:"Official CLI",qwenSourceBailian:"Bailian CLI",qwenCliNote:"Install @qianwenai/qianwen-cli on the DSH host and run qianwen auth login as the same OS user.",qwenBailianNote:"Bailian CLI: install bailian-cli on the DSH host and run bl auth login --console as the same OS user.",qwenPlanCreditsLabel:"Monthly credits quota (personal Lite 50K / Standard 500K; see your plan page)",qwenPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",qwenRatesLabel:"Credits rate overrides (optional; credits deducted per 1M tokens; empty = built-in table)",qwenRatesModelPlaceholder:"Model name, e.g. qwen3.8-max-preview",qwenRatePlaceholder:"rate",qwenRate_input:"Input",qwenRate_cachedInput:"Cached input",qwenRate_output:"Output",qwenRateDraftNote:"Enter all three positive rates to save automatically; clear all to restore the built-in table.",qwenRatesAdd:"Add",qwenLocalNote:"Local estimate; console is authoritative. Counts qwen, qwen-tokenplan, qianwen-tokenplan, qwen-token-plan and qianwen-token-plan (also llm- prefix). Excludes API and pay-as-you-go qianwen. Add rates for other models.",scnetPlanCreditsLabel:"Monthly credits quota for local estimates (Basic 60,000 / Standard 240,000 / Pro 600,000)",scnetPlanStartLabel:"Plan start date (optional, YYYY-MM-DD; empty = calendar month)",scnetLocalNote:"Accepts console snapshots up to 24h old; otherwise estimates from local records and official rates. Other tools and unlisted models are excluded. Check the console.",volcengineAccessKeyIdLabel:"Volcengine AccessKey ID",volcengineSecretAccessKeyLabel:"Volcengine SecretAccessKey",volcengineNote:"Volcano Ark uses AK/SK HMAC (not ARK_API_KEY). IAM needs ArkReadOnlyAccess + BillingCenterReadOnlyAccess. Enter AccessKeyID/SecretAccessKey or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Credentials only go to open.volcengineapi.com.",volcengineAccessKeyPlaceholder:"AK...",volcengineSecretPlaceholder:"SK...",countdownHoursOnly:"{h}h",countdownHourMinute:"{h}h {m}m",countdownMinute:"{m}m",nextOffPeakIn:"Off-peak in {time}",nextPeakIn:"Peak in {time}",peakSummary:"Peak hours (UTC): {windows}; effective: {time}. {status}",noPeakWindows:"No peak windows configured. {status}",unknown:"unknown",cardToday:"Today",cardMonth:"This month",cardTotal:"All time",cardTotalSub:"Since the ledger was created · Calls {calls}",externalUsage:"External usage",combinedUsage:"DSH + external total",externalStale:"External snapshot has not been updated for 24 hours",externalHistory:"Recent daily records",cardsFootnote:"Amounts use the latest snapshot (2s debounce, flush on exit) and may lag the official bill by minutes. Tokens include input, output, cache and reasoning. Reasoning is not billed separately; reconcile by amount.",timezoneHint:"Today/month use host timezone {host}, unlike this browser ({browser}). Calls after local midnight may land on the previous day and affect reconciliation. Run dsh in your local timezone to align.",todaySessions:"Today's sessions",historyExpandHint:"Click a date row to expand its session details",historySessionsLoading:"Loading session details…",historyNoSessions:"No session details for this day (early data or session logs cleaned)",historySessionsError:"Failed to load session details",sessionRankTitle:"By session (all history)",sessionRankHint:"All historical sessions, not grouped by date; sort and row count are switchable",sessionRankEmpty:"No session data yet",sessionRankLoading:"Loading session ranking…",sessionRankError:"Failed to load session ranking",sessionRankLimit:"Rows",showSessionIdLabel:"Show session IDs in session lists",cardsTogglePlanTotal:"Include plan totals",cardsTogglePlanTotalHint:"When on, every amount shows total equivalent cost including plan subscriptions; off (default) counts real-money API channels only",hideOfficialBalanceLabel:"Hide official account balance (balance UI removed from sidebar and settings)",hideTodayCostLabel:"Hide today's cost (today's amount removed from sidebar, budget details and overview card)",sessionRankSort:"Sort",sessionSortCostDesc:"Cost high→low",sessionSortCostAsc:"Cost low→high",sessionSortTimeDesc:"Time new→old",sessionSortTimeAsc:"Time old→new",sessionSortRecent:"Recent order",history:"History",usageTitle:"Token usage stats",usageTotal:"All-time {tokens} tokens · input {input} · cache {cache} · output {output} · {calls} calls",usageDay:"{date}: {tokens} tokens (input {input} · cache {cache} · output {output}) · {calls} calls · {cost}",usageEmpty:"No history yet — daily usage will accumulate here",usageSectionLabel:"Usage",usagePositionLabel:"Token usage stats position",usagePositionCost:"Cost settings",usagePositionGeneral:"General settings",usagePositionSection:"Own section (Usage)",displaySettings:"Display settings",tabOverview:"Overview",tabQuotas:"Quotas",tabUsage:"Usage",tabPricing:"Pricing",tabDisplay:"Display",historyDataTitle:"History data",positionLabel:"Session cost display position",positionDock:"Below the composer",positionHeader:"Session title bar",off:"Off",quotaStripGroup:"Quota strip above the input",quotaStripEnable:"Enable the quota strip (one row above the input box)",quotaStripShowBudget:"Strip includes budget used %",quotaStripShowGo:"Strip includes the Go quota",quotaStripShowPlans:"Strip includes coding plan quotas",quotaStripNote:"Hover a chip for reset times and the last refresh; the strip hides itself when there is no quota data.",quotaStripGuideTitle:"New: quota strip above the input",quotaStripGuideBody:"Show budget and OpenCode Go/coding-plan percentages above the input box. Enable now? Change it anytime in Settings → Display.",quotaStripGuideOn:"Enable the strip",quotaStripGuideOff:"Not now",clickToRefresh:"Click to refresh now",balanceClickGuideTitle:"New: click the balance box to refresh",balanceClickGuideBody:"Click a sidebar balance or plan box to refresh. It pulses while loading; on failure it keeps the old value and shows the reason on hover.",balanceClickGuideOk:"Got it",sidebarLabel:"Today cost display",sidebarOn:"Sidebar footer",currencyLabel:"Currency",currencyCny:"Chinese Yuan (CNY)",currencyUsd:"US Dollar (USD)",currencyEur:"Euro (EUR)",symbolLabel:"Currency symbol",rateLabel:"Exchange rate (1 USD = ? target currency)",decimalsLabel:"Decimal places",balanceDisplayLabel:"Balance display position",balanceSidebar:"Main sidebar",balanceSettings:"Settings page",balanceBoth:"Both",refreshIntervalLabel:"Balance refresh interval (minutes)",peakEnabledLabel:"Use DeepSeek peak-hour prices",peakNoticeLabel:"Prominent notice during peak hours (sidebar budget box, today's cost; previewed in the Settings peak panel)",badgeNote:"Session cost uses call-time prices, including peak and historical rates. Input, output, cache reads and writes are separate; configured cache-write and long-context rates apply.",priceTableTitle:"Price table (USD / 1M tokens)",pricingCurrencyLabel:"Official price currency",pricingCurrencyUsd:"USD (English official page)",pricingCurrencyCny:"CNY (Chinese official page)",pricingCurrencyNote:"Selects the official pricing-page language. Sync then recalculates history in the background; sessions without full logs keep their earlier basis.",priceTableNote:"Call-time prices: Flash changes Sep 10 04:00 UTC; V4 Pro uses Flash prices from Sep 14 04:00 UTC. Earlier calls retain history. Mon–Fri peaks 01–04 and 06–10 UTC cost 2×; weekends and Chinese public holidays are off-peak. Cache writes use hit rates.",datedPriceNote:"Current rates are shown here. Editing cancels any future scheduled change for this entry; earlier historical rates are retained.",defaultModelId:"default (fallback for unmatched models)",newModelPlaceholder:"New model ID (e.g. deepseek-v4-pro)",addModel:"Add model",dataSync:"Data & sync",saving:"Saving…",autoSaveFailed:"Auto-save failed: {message}",autoSavedAt:"Auto-saved {time}",autoSaveHint:"Settings are auto-saved",confirmFetch:"Overwrite the price table with prices from the official docs?",apply:"Apply",cancel:"Cancel",syncFromDocs:"Sync prices from official docs",syncScopeNote:"Official sync updates DeepSeek prices (including peak rates). Third-party prices (z-ai/Kimi/Qwen/Volcano) follow releases; edit in the extended catalog or model matching.",confirmReset:"Clear all history?",importLegacy:"Import pre-install history",confirmImportLegacy:"Confirm import? Replays all session logs and only fills dates/sessions missing from the ledger; existing records are untouched.",legacyImportFailed:"Failed to import pre-install history: {message}",legacyImportNote:"Pre-install history imports at first launch; rerun after copying old logs. Costs use current prices. Deleted logs cannot replay; sessions spanning installation exclude earlier usage.",confirmClear:"Confirm clear",clearAllHistory:"Clear all history",lastSync:"Last sync: {time}",neverSynced:"Never (bundled prices)",source:"; Source: {source}",sourceOfficial:"Official docs",sourceBundled:"Bundled",languageLabel:"Language",localeAuto:"Follow browser (auto)",localeZh:"Simplified Chinese",localeEn:"English",sectionLabel:"Cost",rpcFailed:"{method} call failed",rpcSyncFailed:"Sync call failed",rpcBalanceFailed:"Balance refresh call failed"}};function qa(){return(typeof navigator<"u"&&typeof navigator.language=="string"?navigator.language:"").toLowerCase().startsWith("zh")?"zh":"en"}function W(t){return t==="zh"||t==="en"?t:qa()}function K(t){const s=t==="zh"?Te.zh:Te.en;return(o,a)=>{let n=s[o]??Te.en[o]??o;if(a)for(const i of Object.keys(a))n=n.split("{"+i+"}").join(String(a[i]));return n}}const qe={day:"periodDay",month:"periodMonth",all:"periodAll",custom:"periodCustomRange"};function ce(t,s){throw new Error("dsh-cost-meter: 服务端数据非法 ("+t+": "+s+")")}function fe(t,s){return(t===null||typeof t!="object"||Array.isArray(t))&&ce(s,"object"),t}function de(t,s){return(typeof t!="number"||!Number.isFinite(t))&&ce(s,"number"),t}function Se(t,s){return typeof t!="string"&&ce(s,"string"),t}const Ke=(t,s,o)=>typeof t=="string"&&s.includes(t)?t:o;function Qt(t,s=!1){return t===null||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([o,a])=>s?o.length>0&&["plan","api"].includes(a):["auto","plan","api"].includes(a)))}function Ft(t,s){return typeof t!="boolean"&&ce(s,"boolean"),t}const Ye=(t,s,o)=>Object.fromEntries(s.map(a=>[a,o(t[a])]));function _t(t,s){const o={};if(t!==null&&typeof t=="object"&&!Array.isArray(t))for(const a of Object.keys(t)){const n=t[a];if(n===null||typeof n!="object"||Array.isArray(n))continue;const i=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:0;o[a]={...Ye(n,["input","output","cacheRead","cacheWrite","reasoning","cost"],i),apiCost:n.apiCost===void 0?i(n.cost):i(n.apiCost)}}return o}function Wt(t,s){fe(t,s);const o={reasoning:t.reasoning===void 0?0:de(t.reasoning,s+".reasoning"),apiCost:t.apiCost===void 0?void 0:de(t.apiCost,s+".apiCost"),byModel:_t(t.byModel,s+".byModel"),byProviderModel:_t(t.byProviderModel,s+".byProviderModel")};for(const a of["input","output","cacheRead","cacheWrite","calls","cost"])o[a]=de(t[a],s+"."+a);return o}function ct(t,s){return{...Wt(t,s),id:Se(t.id,s+".id"),provider:typeof t.provider=="string"?t.provider:"",model:typeof t.model=="string"?t.model:""}}function be(t,s){const o={...Wt(t,s),date:Se(t.date,s+".date"),sessions:[]};return t.sessions!==void 0&&(Array.isArray(t.sessions)||ce(s+".sessions","array"),o.sessions=t.sessions.map((a,n)=>ct(a,s+".sessions["+n+"]"))),o}function zt(t,s,o=["cacheWrite","reasoning"]){const a={};for(const n of["cacheHit","cacheMiss","output"])a[n]=de(t[n],s+"."+n);for(const n of o)t[n]!==void 0&&(a[n]=de(t[n],s+"."+n));return a}function dt(t,s){fe(t,s);const o=zt(t,s);for(const a of["offPeak","peak","legacyBase","longContext"])t[a]!==void 0&&(o[a]=zt(t[a],s+"."+a,["cacheWrite","reasoning","aboveInputTokens"]));t.legacy!==void 0&&(o.legacy=Ft(t.legacy,s+".legacy")),t.rateHistory!==void 0&&((!Array.isArray(t.rateHistory)||t.rateHistory.length>16)&&ce(s+".rateHistory","price history"),o.rateHistory=t.rateHistory.map((a,n)=>((!a||typeof a.before!="string"||!Number.isFinite(Date.parse(a.before)))&&ce(s+".rateHistory","dated price"),{...dt({...a,rateHistory:void 0},s+".rateHistory."+n),before:a.before})));for(const a of["billingMode","sourceUrl","checkedAt","notes"])typeof t[a]=="string"&&(o[a]=t[a]);return o}function Ha(t,s){const o=n=>n==null?void 0:{...n.adapter==="aliyun"?{adapter:"aliyun"}:{},enabled:n.enabled===!0,label:typeof n.label=="string"?n.label:"",labelEn:typeof n.labelEn=="string"?n.labelEn:"",display:Ke(n.display,["sidebar","settings","off"],"both"),unit:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",convertToDisplayCurrency:n.convertToDisplayCurrency===!0,refreshMinutes:typeof n.refreshMinutes=="number"&&Number.isFinite(n.refreshMinutes)?n.refreshMinutes:15,request:n.request&&typeof n.request=="object"?n.request:{url:""},extract:n.extract&&typeof n.extract=="object"?n.extract:{},allowedHosts:Array.isArray(n?.allowedHosts)?n.allowedHosts.filter(i=>typeof i=="string"):[]};fe(t,s);const a={};if(t.prices!==null&&typeof t.prices=="object"&&t.prices.models!==null&&typeof t.prices.models=="object")for(const n of Object.keys(t.prices.models))a[n]=dt(t.prices.models[n],s+".prices.models."+n);return{locale:t.locale==="zh"||t.locale==="en"||t.locale==="auto"?t.locale:"auto",position:t.position==="header"||t.position==="off"?t.position:"dock",sidebar:t.sidebar!==!1,showSessionId:t.showSessionId===!0,hideOfficialBalance:t.hideOfficialBalance===!0,hideTodayCost:t.hideTodayCost===!0,showTotalWithPlan:t.showTotalWithPlan===!0,sidebarSimple:t.sidebarSimple===!0,sidebarSimplePromptSeen:t.sidebarSimplePromptSeen===!0,sidebarModels:Object.fromEntries(Object.entries(Dt).map(([n,i])=>[n,t.sidebarModels?.[n]??i])),codexQuotaEnabled:t.codexQuotaEnabled===!0,includeSubagentCost:t.includeSubagentCost===!0,sidebarStyle:t.sidebarStyle==="compact"?"compact":"standard",priceMatchDismissed:Array.isArray(t.priceMatchDismissed)?t.priceMatchDismissed.filter(n=>typeof n=="string"):[],pricingCurrency:t.pricingCurrency==="CNY"?"CNY":"USD",currency:typeof t.currency=="string"?t.currency:"CNY",symbol:typeof t.symbol=="string"?t.symbol:"¥",decimals:de(t.decimals,s+".decimals"),exchangeRate:de(t.exchangeRate,s+".exchangeRate"),peakEnabled:t.peakEnabled===!0,peakEffectiveAt:typeof t.peakEffectiveAt=="string"?t.peakEffectiveAt:"",peakWindows:Array.isArray(t.peakWindows)?t.peakWindows.map((n,i)=>({start:de(n.start,s+".peakWindows["+i+"].start"),end:de(n.end,s+".peakWindows["+i+"].end")})):[],peakHolidays:Array.isArray(t.peakHolidays)?t.peakHolidays.filter(n=>typeof n=="string"):[],peakNotice:t.peakNotice!==!1,peakAlertEnabled:t.peakAlertEnabled!==!1,peakAlertAhead:Number.isFinite(t.peakAlertAhead)&&t.peakAlertAhead>=1&&t.peakAlertAhead<=30?t.peakAlertAhead:2,peakAlertTarget:t.peakAlertTarget==="peak"||t.peakAlertTarget==="offpeak"?t.peakAlertTarget:"both",peakAlertPosition:t.peakAlertPosition==="center"?"center":"corner",peakAlertWebNotify:t.peakAlertWebNotify===!0,peakStyle:t.peakStyle==="classic"?"classic":"compact",priceMatch:t.priceMatch==="exact"?"exact":"auto",priceOverrides:(()=>{const n={};if(t.priceOverrides!==null&&typeof t.priceOverrides=="object"&&!Array.isArray(t.priceOverrides))for(const[i,l]of Object.entries(t.priceOverrides))typeof i=="string"&&typeof l=="string"&&(n[i]=l);return n})(),priceTableDisplay:(()=>{const n={};if(t.priceTableDisplay!==null&&typeof t.priceTableDisplay=="object"&&!Array.isArray(t.priceTableDisplay))for(const[i,l]of Object.entries(t.priceTableDisplay))typeof i=="string"&&(n[i]=l===!0);return n})(),codingPlans:(()=>{const n={};if(t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans))for(const i of Object.keys(t.codingPlans)){const l=t.codingPlans[i];l===null||typeof l!="object"||Array.isArray(l)||(n[i]={enabled:l.enabled===!0,display:l.display==="sidebar"||l.display==="both"||l.display==="off"?l.display:"settings",refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?l.refreshMinutes:15,apiKey:typeof l.apiKey=="string"?l.apiKey:"",...i==="minimax"?{baseUrl:typeof l.baseUrl=="string"?l.baseUrl:""}:{},...i==="qwen"?{quotaSource:["cli","bailian"].includes(l.quotaSource)?l.quotaSource:"local"}:{},...typeof l.planCredits=="number"&&Number.isFinite(l.planCredits)&&l.planCredits>0?{planCredits:l.planCredits}:{},...typeof l.planStart=="string"?{planStart:l.planStart}:{},...l.rates!==null&&typeof l.rates=="object"&&!Array.isArray(l.rates)?{rates:l.rates}:{},...typeof l.accessKeyId=="string"?{accessKeyId:l.accessKeyId}:{},...typeof l.secretAccessKey=="string"?{secretAccessKey:l.secretAccessKey}:{}})}return n})(),prices:{models:a,default:dt(t.prices?.default??{cacheHit:0,cacheMiss:0,output:0},s+".prices.default"),providers:t.prices?.providers&&typeof t.prices.providers=="object"?t.prices.providers:{},currency:typeof t.prices?.currency=="string"&&t.prices.currency.length>0?t.prices.currency:void 0},historyDays:de(t.historyDays,s+".historyDays"),fetchedAt:t.fetchedAt===null||t.fetchedAt===void 0?null:Se(t.fetchedAt,s+".fetchedAt"),priceSource:typeof t.priceSource=="string"?t.priceSource:"bundled",budget:{enabled:t.budget?.enabled===!0,amount:typeof t.budget?.amount=="number"&&Number.isFinite(t.budget.amount)?t.budget.amount:100,period:t.budget?.period==="day"||t.budget?.period==="all"||t.budget?.period==="custom"?t.budget.period:"month",customStart:typeof t.budget?.customStart=="string"?t.budget.customStart:null,customEnd:typeof t.budget?.customEnd=="string"?t.budget.customEnd:null,detail:t.budget?.detail!==!1},balance:{display:Ke(t.balance?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.balance?.refreshMinutes=="number"&&Number.isFinite(t.balance.refreshMinutes)?t.balance.refreshMinutes:5,showProgressBar:t.balance?.showProgressBar===!0,budgetCap:typeof t.balance?.budgetCap=="number"&&Number.isFinite(t.balance.budgetCap)&&t.balance.budgetCap>0?t.balance.budgetCap:null,clickHintSeen:t.balance?.clickHintSeen===!0},goQuota:{enabled:t.goQuota?.enabled!==!1,display:Ke(t.goQuota?.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof t.goQuota?.refreshMinutes=="number"&&Number.isFinite(t.goQuota.refreshMinutes)?t.goQuota.refreshMinutes:15,apiKey:typeof t.goQuota?.apiKey=="string"?t.goQuota.apiKey:"",main:t.goQuota?.main==="weekly"||t.goQuota?.main==="monthly"?t.goQuota.main:"rolling",detail:t.goQuota?.detail!==!1},customBalance:o(t.customBalance),gatewayQuotas:(()=>{const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:t.gatewayQuotas?.sources;return{sources:Array.isArray(n)?n.slice(0,4).filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).map(l=>({id:typeof l.id=="string"?l.id.slice(0,48):"",type:"cliproxyapi",label:typeof l.label=="string"?l.label.slice(0,80):"",baseURL:typeof l.baseURL=="string"?l.baseURL:"",enabled:l.enabled!==!1,display:Ke(l.display,["sidebar","settings","off"],"both"),refreshMinutes:typeof l.refreshMinutes=="number"&&Number.isFinite(l.refreshMinutes)?Math.min(1440,Math.max(1,Math.floor(l.refreshMinutes))):15,includeProviders:Array.isArray(l.includeProviders)?[...new Set(l.includeProviders.filter(r=>typeof r=="string").map(r=>r.toLowerCase()).filter(r=>pt.includes(r)))]:pt,allowedHosts:Array.isArray(l.allowedHosts)?l.allowedHosts.filter(r=>typeof r=="string").slice(0,16):[],allowInsecureHttp:l.allowInsecureHttp===!0,antigravityOnlyGemini:l.antigravityOnlyGemini===!0,keyVar:typeof l.keyVar=="string"?l.keyVar:""})):[]}})(),customBalances:(()=>{if(Array.isArray(t.customBalances))return t.customBalances.filter(i=>i!==null&&typeof i=="object").slice(0,8).map(o).filter(Boolean);const n=o(t.customBalance);return n?[n]:[]})(),corner:{enabled:t.corner?.enabled===!0,goRolling:t.corner?.goRolling!==!1,goWeekly:t.corner?.goWeekly!==!1,goMonthly:t.corner?.goMonthly!==!1,budget:t.corner?.budget!==!1},quotaStrip:{enabled:t.quotaStrip?.enabled===!0,budget:t.quotaStrip?.budget!==!1,go:t.quotaStrip?.go!==!1,plans:t.quotaStrip?.plans!==!1,promptSeen:t.quotaStrip?.promptSeen===!0},usage:{position:t.usage?.position==="general"||t.usage?.position==="section"?t.usage.position:"cost"},barDirections:(()=>{const n=t.barDirections!==null&&typeof t.barDirections=="object"&&!Array.isArray(t.barDirections)?t.barDirections:{},i=(l,r)=>n[l]==="remaining"||n[l]==="used"?n[l]:r;return{balance:i("balance","remaining"),budget:i("budget","used"),go:i("go","used"),plan:i("plan","used")}})(),planBilling:{providers:Qt(t.planBilling?.providers),models:Qt(t.planBilling?.models,!0)}}}const He=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Ce=t=>He(t)??0,Ia={status:"off",message:"",fetchedAt:0,currency:"",totalBalance:0,grantedBalance:0,toppedUpBalance:0},Ua={status:"off",message:"",fetchedAt:0,rolling:null,weekly:null,monthly:null},Gt=(t=null)=>({status:"off",message:"",fetchedAt:0,label:"",unit:"USD",remaining:0,maxBudget:null,spend:null,index:t});function ut(t,s){return fe(t,s),{status:t.status==="ok"||t.status==="error"?t.status:"off",message:typeof t.message=="string"?t.message:"",fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:0}}function ja(t,s){return{...ut(t,s),currency:typeof t.currency=="string"?t.currency:"",totalBalance:Ce(t.totalBalance),grantedBalance:Ce(t.grantedBalance),toppedUpBalance:Ce(t.toppedUpBalance)}}function mt(t,s){return t==null?null:((typeof t!="object"||Array.isArray(t))&&ce(s,"object"),{percent:Ce(t.percent),resetsAt:typeof t.resetsAt=="string"?t.resetsAt:""})}function Qa(t,s){return{...ut(t,s),rolling:mt(t.rolling,s+".rolling"),weekly:mt(t.weekly,s+".weekly"),monthly:mt(t.monthly,s+".monthly")}}function Kt(t,s){return{...ut(t,s),label:typeof t.label=="string"?t.label:"",unit:typeof t.unit=="string"?t.unit:"USD",remaining:Ce(t.remaining),maxBudget:He(t.maxBudget),spend:He(t.spend),index:typeof t.index=="number"&&Number.isFinite(t.index)&&t.index>=0?Math.floor(t.index):null}}const Fa=new Set(["ok","partial","unknown","error","stale","unsupported","capability_missing"]),_a=new Set(["off","loading","ok","partial","stale","error"]),pt=["antigravity","claude","codex","kimi","xai","workbuddy"],Yt={antigravity:"Antigravity",claude:"Claude",codex:"Codex",kimi:"Kimi",xai:"xAI",workbuddy:"WorkBuddy"};function Wa(t,s){fe(t,s);const o=(l,r="")=>typeof l=="string"?l:r,a=l=>He(l),n=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{id:o(l.id),label:o(l.label),...a(l.percent)===null?{}:{percent:a(l.percent)},resetsAt:o(l.resetsAt),periodHours:a(l.periodHours),scope:o(l.scope)}:null,i=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?{unit:o(l.unit,"credits"),used:a(l.used),remaining:a(l.remaining),limit:a(l.limit),fetchedAt:o(l.fetchedAt),packages:Array.isArray(l.packages)?l.packages.filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)).map(r=>({id:o(r.id),label:o(r.label),used:a(r.used),remaining:a(r.remaining),limit:a(r.limit),startsAt:o(r.startsAt),resetsAt:o(r.resetsAt)})):[]}:void 0;return{id:o(t.id),type:"cliproxyapi",label:o(t.label),status:_a.has(t.status)?t.status:"error",message:o(t.message),fetchedAt:a(t.fetchedAt)??0,attemptedAt:a(t.attemptedAt)??0,serverVersion:o(t.serverVersion),keyConfigured:t.keyConfigured===!0,keySource:o(t.keySource,"none"),accounts:Array.isArray(t.accounts)?t.accounts.filter(l=>l!==null&&typeof l=="object"&&!Array.isArray(l)).slice(0,16).map(l=>({id:o(l.id),provider:o(l.provider,"unknown"),label:o(l.label,"unknown"),status:Fa.has(l.status)?l.status:"unknown",message:o(l.message),plan:o(l.plan),windows:Array.isArray(l.windows)?l.windows.map(n).filter(Boolean):[],credits:i(l.credits)})):[],unsupportedProviders:Array.isArray(t.unsupportedProviders)?t.unsupportedProviders.filter(l=>typeof l=="string").slice(0,32):[]}}function za(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};if(t.providers!==null&&typeof t.providers=="object"&&!Array.isArray(t.providers))for(const[o,a]of Object.entries(t.providers)){if(a===null||typeof a!="object"||Array.isArray(a))continue;const n={},i={};if(a.windows!==null&&typeof a.windows=="object"&&!Array.isArray(a.windows))for(const[l,r]of Object.entries(a.windows))r===null||typeof r!="object"||Array.isArray(r)||(n[l]={...Ye(r,["percent","localTokens","localCost","sampleCount"],Ce),...Ye(r,["sampleAt","per1Tokens","per1Cost","fullTokens","fullCost"],He),resetsAt:typeof r.resetsAt=="string"?r.resetsAt:"",method:r.method==="sample"||r.method==="live"?r.method:"none",confidence:r.confidence==="high"||r.confidence==="low"?r.confidence:null});if(a.intervals!==null&&typeof a.intervals=="object"&&!Array.isArray(a.intervals))for(const[l,r]of Object.entries(a.intervals))Array.isArray(r)&&(i[l]=r.filter(u=>u!==null&&typeof u=="object"&&!Array.isArray(u)).map(u=>Ye(u,["t0","t1","tokens","cost","pct","per1Tokens","per1Cost"],Ce)));s[o]={windows:n,intervals:i}}return{generatedAt:Ce(t.generatedAt),providers:s}}function Vt(t,s){return fe(t,s),{today:be(t.today,s+".today"),month:be(t.month,s+".month"),total:be(t.total,s+".total"),budgetUsed:typeof t.budgetUsed=="number"&&Number.isFinite(t.budgetUsed)?t.budgetUsed:void 0,balance:t.balance==null?Ia:ja(t.balance,s+".balance"),goQuota:t.goQuota==null?Ua:Qa(t.goQuota,s+".goQuota"),customBalance:t.customBalance==null?Gt():Kt(t.customBalance,s+".customBalance"),customBalances:Array.isArray(t.customBalances)?t.customBalances.filter(o=>o!==null&&typeof o=="object").map((o,a)=>Kt(o,s+".customBalances["+a+"]")):[],gatewayQuotas:Array.isArray(t.gatewayQuotas)?t.gatewayQuotas.filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)).map((o,a)=>Wa(o,s+".gatewayQuotas["+a+"]")):[],customVarStatus:t.customVarStatus!==null&&typeof t.customVarStatus=="object"&&!Array.isArray(t.customVarStatus)?Object.fromEntries(Object.entries(t.customVarStatus).filter(([,o])=>o!==null&&typeof o=="object").map(([o,a])=>[o,{configured:a.configured===!0,source:typeof a.source=="string"?a.source:""}])):{},codingPlans:t.codingPlans!==null&&typeof t.codingPlans=="object"&&!Array.isArray(t.codingPlans)?t.codingPlans:{},planStats:za(t.planStats),history:Array.isArray(t.history)?t.history.map((o,a)=>be(o,s+".history["+a+"]")):[],externalUsage:t.externalUsage&&Array.isArray(t.externalUsage.sources)?{fetchedAt:Number(t.externalUsage.fetchedAt)||0,stale:t.externalUsage.stale===!0,sources:t.externalUsage.sources.map(o=>({source:String(o.source),today:be(o.today,s+".external.today"),month:be(o.month,s+".external.month"),total:be(o.total,s+".external.total"),history:(o.history??[]).map(a=>be(a,s+".external.history"))})),combined:Object.fromEntries(["today","month","total","history"].map(o=>[o,o==="history"?(t.externalUsage.combined.history??[]).map(a=>be(a,s+".external.history")):be(t.externalUsage.combined[o],s+".external."+o)]))}:null,config:Ha(t.config,s+".config"),reconcile:t.reconcile===null||t.reconcile===void 0?void 0:{ok:t.reconcile.ok===!0,message:typeof t.reconcile.message=="string"?t.reconcile.message:""},priceCatalog:t.priceCatalog!==null&&typeof t.priceCatalog=="object"&&!Array.isArray(t.priceCatalog)?t.priceCatalog:null,meta:{now:typeof t.meta?.now=="number"?t.meta.now:Date.now(),timezoneOffsetMinutes:typeof t.meta?.timezoneOffsetMinutes=="number"?t.meta.timezoneOffsetMinutes:0,timezone:typeof t.meta?.timezone=="string"?t.meta.timezone:"",dayKey:typeof t.meta?.dayKey=="string"?t.meta.dayKey:"",monthKey:typeof t.meta?.monthKey=="string"?t.meta.monthKey:""}}}function Ga(t,s){fe(t,s);const o={ok:t.ok===!0,message:typeof t.message=="string"?t.message:""};return t.state!==void 0&&t.state!==null&&(o.state=Vt(t.state,s+".state")),o}function se(t){return{parse:t}}const ft=se(Vt),Ka=se(t=>fe(t,"patch")),Ya=se(Ga),Jt=se(t=>Se(t,"provider")),Va=se(t=>{if(t!=null)return(typeof t!="number"||!Number.isInteger(t)||t<0||t>7)&&ce("index","0-7 integer"),t}),Ja=se(t=>Se(t,"date")),$a=se(t=>fe(t,"day")),Za=se(t=>(Number.isFinite(Number(t))||ce("limit","number"),Number(t))),$t=se(t=>Se(t,"sort")),Xa=se(t=>fe(t,"topSessions")),Zt=se(t=>Se(t,"target")),en=se(t=>Se(t,"value")),Ae=(t,s)=>({mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:s,create:()=>s}),ie=(t,s,o,a=!1)=>({name:t,wire:t,source:"json",codec:Ae(s,o),...a?{acceptsUndefined:!0}:{}}),tn={package:"dsh-cost-meter",descriptors:[{method:"getState",result:Ae("CostState",ft)},{method:"updateConfig",parameters:[ie("patch","ConfigPatch",Ka)],result:Ae("CostState",ft)},{method:"fetchPrices"},{method:"refreshBalance"},{method:"refreshGoQuota"},{method:"refreshCustomBalance",parameters:[ie("index","CustomBalanceIndex",Va,!0)]},{method:"refreshCodingPlan",parameters:[ie("provider","CodingPlanProvider",Jt)]},{method:"refreshGatewayQuota",parameters:[ie("sourceId","GatewayQuotaSourceId",se(t=>{if(t!=null)return(typeof t!="string"||t.length>48||!/^[a-z0-9][a-z0-9_-]*$/.test(t))&&ce("sourceId","gateway source id"),t}),!0)]},{method:"resetHistory",result:Ae("CostState",ft)},{method:"importLegacyHistory"},{method:"getDaySessions",parameters:[ie("date","DayKey",Ja)],result:Ae("DayRecord",$a)},{method:"getSessionCost",parameters:[ie("sessionId","SessionId",Jt)],result:Ae("SessionCost",se(t=>({own:ct(t.own,"own"),subagents:ct(t.subagents,"subagents"),found:Ft(t.found,"found"),subagentCount:de(t.subagentCount,"subagentCount")})))},{method:"getTopSessions",parameters:[ie("limit","SessionLimit",Za),ie("sort","SessionSort",$t,!0),ie("dir","SessionSortDir",$t,!0)],result:Ae("TopSessions",Xa)},{method:"setCredential",parameters:[ie("target","CredentialTarget",Zt),ie("value","CredentialValue",en)]},{method:"clearCredential",parameters:[ie("target","CredentialTarget",Zt)]}].map(t=>({id:"dsh-cost-meter#costMeter/"+t.method,service:"costMeter",namespace:"costMeter",invocation:{kind:"direct"},parameters:[],result:Ae("FetchPricesResult",Ya),...t}))};function an(t,s){const o=s?.models??{};return typeof t=="string"&&t.length>0&&o[t]!==void 0?o[t]:s?.default??{cacheHit:0,cacheMiss:0,output:0}}function Ie(t){if(t===null||typeof t!="object")return;const s=l=>{const r=t[l];return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0},o=s("cacheMiss")??s("input")??0,n={cacheHit:s("cacheHit")??s("cachedInput")??s("cacheRead")??o,cacheMiss:o,output:s("output")??0},i=s("reasoning");return i!==void 0&&(n.reasoning=i),s("cacheWrite")!==void 0&&(n.cacheWrite=s("cacheWrite")),n}function nn(t){const s=Ie(t);if(s===void 0)return null;for(const o of["offPeak","peak","legacyBase"]){const a=Ie(t[o]);a!==void 0&&(s[o]=a)}return Number.isFinite(t.longContext?.aboveInputTokens)&&t.longContext.aboveInputTokens>0&&(s.longContext={...Ie(t.longContext),aboveInputTokens:t.longContext.aboveInputTokens}),Array.isArray(t.rateHistory)&&(s.rateHistory=t.rateHistory.slice(0,16).map(o=>{const a={...Ie(o),before:o.before};for(const n of["offPeak","peak"]){const i=Ie(o[n]);i!==void 0&&(a[n]=i)}return a})),s}function Ve(t,s=Date.now()){if(!t||!Number.isFinite(s)||!Array.isArray(t.rateHistory))return t;let o=null,a=1/0;for(const l of t.rateHistory){const r=Date.parse(l.before);s<r&&r<a&&(o=l,a=r)}if(!o)return t;const{before:n,...i}=o;return{...t,...i}}const bt=Date.parse("2026-08-22T16:00:00Z");function Xt(t){if(!Number.isFinite(t)||t<bt)return null;const s=Math.floor((t+8*36e5)/864e5),o=(s+4)%7;if(o!==6&&o!==0)return null;const a=o===6?s:s-1;return{start:Math.max(a*864e5-8*36e5,bt),end:(a+2)*864e5-8*36e5}}function ea(t,s){if(!Number.isFinite(t)||t<bt||!Array.isArray(s))return null;const o=Math.floor((t+8*36e5)/864e5);return s.includes(new Date(o*864e5).toISOString().slice(0,10))?{start:o*864e5-8*36e5,end:(o+1)*864e5-8*36e5}:null}const sn=(t,s)=>ea(t,s)??Xt(t);function Je(t,s,o,a){if(!Array.isArray(o)||o.length===0||sn(t,a)!==null||Number.isFinite(s)&&t<s)return!1;const n=new Date(t).getUTCHours();return o.some(i=>{const l=Number(i.start),r=Number(i.end);return!Number.isFinite(l)||!Number.isFinite(r)?!1:l<r?n>=l&&n<r:n>=l||n<r})}const on=Date.parse("2026-08-16T16:00:00Z");function ta(t,s,o){const a=Ve(t,s)??{cacheHit:0,cacheMiss:0,output:0},n=l=>({cacheHit:l.cacheHit,cacheMiss:l.cacheMiss,output:l.output,reasoning:l.reasoning??0,...l.cacheWrite===void 0?{}:{cacheWrite:l.cacheWrite},...l.longContext===void 0?{}:{longContext:l.longContext}});if(Number.isFinite(s)&&s<on){const l=a.legacyBase;return n(l===void 0?a:l)}if(o?.enabled!==!0)return n(a);const i=typeof o.effectiveAtMs=="number"&&Number.isFinite(o.effectiveAtMs)?o.effectiveAtMs:void 0;if(Je(s,i,o.windows,o.holidays)){const l=a.peak;return n(l===void 0?a:l)}if(i!==void 0&&s>=i){const l=a.offPeak;return n(l===void 0?a:l)}return n(a)}function aa(t,s){const o=Math.max(0,Number(t.input)||0),a=Math.max(0,Number(t.output)||0),n=Math.max(0,Number(t.cacheRead)||0),i=Math.max(0,Number(t.cacheWrite)||0),l=Math.max(0,Number(t.reasoning)||0);return s.longContext&&o+n+i>s.longContext.aboveInputTokens&&(s=s.longContext),(o*s.cacheMiss+a*s.output+n*s.cacheHit+i*(s.cacheWrite??s.cacheHit)+l*(s.reasoning??0))/1e6}function na(t,s,o){const a=Number(t);if(!Number.isFinite(a)||a<0||a===0)return 0;if(s!=="CNY")return a;const n=Number(o);return!Number.isFinite(n)||n<=0?a:a/n}function te(t,s){const o=t?.barDirections,a=s==="balance"?"remaining":"used";if(o===null||typeof o!="object"||Array.isArray(o))return a;const n=o[s];return n==="remaining"||n==="used"?n:a}function ue(t,s){if(t==null||!Number.isFinite(Number(t)))return{width:0,label:null};const o=Math.max(0,Math.min(100,Number(t))),a=s==="remaining"?Math.round((100-o)*10)/10:Math.round(o*10)/10;return{width:a,label:a}}const sa=(t,s)=>t.toFixed(s).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1");function oe(t,s){const o=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$",a=Number(s?.decimals),n=Math.max(0,Math.min(10,Number.isFinite(a)?Math.floor(a):2));let i=n;return t>0&&t<Math.pow(10,-n)&&(i=n+2),o+sa(t,i)}function Y(t,s){const o=Number(s?.exchangeRate),a=t*(Number.isFinite(o)&&o>0?o:1);return oe(a,s)}function I(t){const s=Math.max(0,Number(t)||0),o=a=>a>=100?String(Math.round(a)):String(Math.round(a*10)/10);return s<1e3?String(Math.round(s)):s>=999500?o(s/1e6)+"M":s<1e6?o(s/1e3)+"K":o(s/1e6)+"M"}function re(t){return String(t??"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/([^)]*)/g," ").replace(/[^a-z0-9]+/g,"")}function Be(t,s){if(typeof t!="string"||t.length===0)return null;const o=Array.isArray(s)?s.filter(k=>typeof k=="string"&&k.length>0):[];if(o.length===0)return null;const a=k=>String(k).toLowerCase().replace(/[-@]\d{4}-?\d{2}-?\d{2}$/,"").replace(/[-@]v\d+(\.\d+)*$/,""),n=o.find(k=>k===t);if(n!==void 0)return n;const i=re(t);if(i.length===0)return null;const l=o.find(k=>re(k)===i);if(l!==void 0)return l;let r=null,u=0;for(const k of o){const b=re(k);if(!(b.length<4||b===i)&&i.includes(b)&&b.length>u){const v=i.indexOf(b);if(/^\d{1,2}$/.test(i.slice(v+b.length)))continue;r=k,u=b.length}}if(r!==null)return r;const d=a(t),c=o.find(k=>a(k)===d);if(c!==void 0)return c;let f=null;for(const k of o){const b=a(k);if(b.length===0||b===d)continue;const v=d.slice(b.length);if(d.startsWith(b)&&/^[-_./:]/.test(v)){if(/^\d{1,2}$/.test(v.replace(/^[-_./:]+/,"")))continue;(f===null||a(f).length<b.length)&&(f=k)}}if(f!==null)return f;const m=k=>a(k).split(/[-_./:]+/).filter(Boolean),p=m(t);if(p.length<2)return null;let g=null,x=0;for(const k of o){const b=m(k);let v=0;for(;v<p.length&&v<b.length&&p[v]===b[v];)v+=1;v<p.length&&v<b.length&&/^\d+$/.test(p[v])&&/^\d+$/.test(b[v])||v>=2&&v===b.length&&v<p.length&&p.slice(v).every(S=>/^\d{1,2}$/.test(S))||v>=2&&v<p.length&&v<b.length&&(/^\d{1,2}$/.test(p[v])&&/^[a-z]/.test(b[v])||/^\d{1,2}$/.test(b[v])&&/^[a-z]/.test(p[v]))||v>=2&&(v>x||v===x&&g!==null&&k.length<g.length)&&(g=k,x=v)}return g}const ln=new Set(["lmstudio","ollama","jan","gpt4all","koboldcpp","llamacpp","llama-cpp","localai","vllm","sglang","tabbyapi","lmdeploy","oobabooga","text-generation-webui","llama-server"]),rn=["lmstudio:","lmstudio/","ollama:","ollama/","jan:","jan/","gpt4all:","gpt4all/","koboldcpp:","koboldcpp/","llamacpp:","llamacpp/","llama-cpp:","llama-cpp/","localai:","localai/","vllm:","vllm/","sglang:","sglang/","tabbyapi:","tabbyapi/","lmdeploy:","oobabooga/","text-generation-webui/","llama-server:","gguf:","local:"];function cn(t,s){if(typeof t=="string"&&ln.has(t))return!0;const o=typeof s=="string"?s.toLowerCase():"";return rn.some(a=>o.startsWith(a))}function gt(t,s,o){const a=o?.prices??{},n=o?.priceMatch==="exact"?"exact":"auto",i=o?.priceOverrides&&typeof o.priceOverrides=="object"?o.priceOverrides:{};let l=String(t??"").trim().toLowerCase();l.startsWith("llm-")&&(l=l.slice(4)),l===""&&(l="deepseek");let r=l,u=s;const d=i[l+":"+s];if(d==="__local__")return{entry:null,priced:!1,billingMode:"flat",matched:!0};if(typeof d=="string"&&d.length>0){const m=d.indexOf(":");if(m>0&&d.slice(m+1).length>0?(r=d.slice(0,m).trim().toLowerCase(),u=d.slice(m+1)):u=d,r==="deepseek"&&u==="__default__")return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}if(cn(r,u))return{entry:null,priced:!1,billingMode:"flat",matched:!1};if(r==="deepseek"||r.includes("deepseek")){const m=a.models??{},p=m[u]!==void 0?u:n==="auto"?Be(u,Object.keys(m)):null;if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0};if(n==="auto"){let g=null,x=-1,k="flat";for(const[b,v]of Object.entries(a.providers??{})){const S=v?.models??{},w=Be(u,Object.keys(S));if(w===null||S[w]?.unpriced===!0)continue;const y=(w===u||re(w)===re(u)?1e3:0)+re(w).length;y>x&&(g=S[w],x=y,k=S[w]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(g!==null)return{entry:g,priced:!0,billingMode:k,matched:!0}}return{entry:a.default??{cacheHit:0,cacheMiss:0,output:0},priced:!0,billingMode:"deepseek-peak",matched:!1}}const c=a.providers?.[r]?.models??{},f=c[u]!==void 0?u:n==="auto"?Be(u,Object.keys(c)):null;if(f!==null)return{entry:c[f],priced:c[f]?.unpriced!==!0,billingMode:"flat",matched:!0};if(n==="auto"){const m=a.models??{},p=Be(u,Object.keys(m));if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0};let g=null,x=-1,k="flat";for(const[b,v]of Object.entries(a.providers??{})){if(b===r)continue;const S=v?.models??{},w=Be(u,Object.keys(S));if(w===null||S[w]?.unpriced===!0)continue;const y=(w===u||re(w)===re(u)?1e3:0)+re(w).length;y>x&&(g=S[w],x=y,k=S[w]?.billingMode==="deepseek-peak"?"deepseek-peak":"flat")}if(g!==null)return{entry:g,priced:!0,billingMode:k,matched:!0}}if(l!=="deepseek"&&!l.includes("deepseek")&&typeof d=="string"&&d.length>0&&!d.includes(":")){const m=a.models??{},p=m[d]!==void 0?d:n==="auto"?Be(d,Object.keys(m)):null;if(p!==null)return{entry:m[p],priced:!0,billingMode:"deepseek-peak",matched:!0}}return{entry:null,priced:!1,billingMode:"flat",matched:!1}}function dn(t){const s=Number(t?.calls)||0,o=Number(t?.input)||0,a=Number(t?.cacheRead)||0;return s>=3&&o>=1e5&&a===0}function $e(t,s){return!t||!s?0:typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:la(t,s).total}function ht(t){if(t===null||typeof t!="object")return 0;const s=Number(t.cost)||0,o=t.apiCost===void 0||t.apiCost===null?s:Number(t.apiCost);return Number.isFinite(o)&&o>=0?Math.min(o,s):s}function _(t,s){return s!==null&&typeof s=="object"&&s.showTotalWithPlan===!0?Number(t?.cost)||0:ht(t)}const un={go:["go","zen","opencode","opencode-go"],qwen:["qwen","qwen-tokenplan","qianwen-tokenplan","qwen-token-plan","qianwen-token-plan"],scnet:["scnet","scnet-tokenplan","scnet-token-plan"],mimo:["mimo","xiaomimimo","mimo-token-plan","xiaomi-token-plan","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","xiaomi-token-plan-ams"]},oa=["anthropic","zai","minimax","kimi","openrouter","siliconflow","commandcode","scnet","volcengine","qwen","mimo","go"];function mn(t){const s=String(t??"").trim().toLowerCase().replace(/^llm-/,"");if(s.length===0)return null;for(const[o,a]of Object.entries(un))if(a.includes(s))return o;return oa.includes(s)?s:null}function pn(t){const s=new Set,o=t?.codingPlans;if(o!==null&&typeof o=="object")for(const a of oa)a!=="go"&&o[a]?.enabled===!0&&s.add(a);return t?.goQuota?.enabled===!0&&s.add("go"),s}function fn(t,s,o){const a=String(t??"").trim().toLowerCase();if(a.length>0&&a!=="deepseek"&&!a.includes("deepseek"))return!1;const n=re(s);if(n.length===0)return!1;const i=o?.prices,l=i?.models??{};for(const r of Object.keys(l))if(re(r)===n)return!1;for(const r of Object.values(i?.providers??{}))for(const u of Object.keys(r?.models??{}))if(re(u)===n)return!0;return!1}function Ue(t,s,o){let a=mn(t);if(a===null&&fn(t,s,o)&&(a="go"),a===null)return"api";const n=o?.planBilling?.models;if(n!==null&&typeof n=="object"){const l=n[t+":"+s];if(l==="plan"||l==="api")return l;const r=n[a+":"+s];if(r==="plan"||r==="api")return r}const i=o?.planBilling?.providers?.[a];return i==="plan"||i==="api"?i:pn(o).has(a)?"plan":"api"}function la(t,s){if(!t||!s)return{total:0,api:0};const o={enabled:s.peakEnabled===!0,effectiveAtMs:Date.parse(s.peakEffectiveAt||""),windows:s.peakWindows,holidays:s.peakHolidays},a=Date.now(),n=t.byProviderModel??t.byModel??{};let i=0,l=0;for(const f of Object.keys(n)){const m=f.indexOf(":"),p=m>0?f.slice(0,m):"deepseek",g=m>0?f.slice(m+1):f,x=gt(p,g,s);if(x.priced){const k=aa(n[f],ta(nn(x.entry),a,{...o,enabled:x.billingMode==="deepseek-peak"&&o.enabled})),b=na(k,x.billingMode==="deepseek-peak"&&s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);i+=b,Ue(p,g,s)==="api"&&(l+=b)}}const r={input:0,output:0,cacheRead:0,cacheWrite:0,reasoning:0};for(const f of Object.keys(n))r.input+=n[f].input??0,r.output+=n[f].output??0,r.cacheRead+=n[f].cacheRead??0,r.cacheWrite+=n[f].cacheWrite??0,r.reasoning+=n[f].reasoning??0;const u={input:Math.max(0,(t.input??0)-r.input),output:Math.max(0,(t.output??0)-r.output),cacheRead:Math.max(0,(t.cacheRead??0)-r.cacheRead),cacheWrite:Math.max(0,(t.cacheWrite??0)-r.cacheWrite),reasoning:Math.max(0,(t.reasoning??0)-r.reasoning)},d=aa(u,ta(an("default",s.prices),a,o)),c=na(d,s.prices?.currency==="CNY"?"CNY":"USD",s.exchangeRate);return i+=c,l+=c,{total:i,api:l}}function ia(t,s){if(!t||!s)return!1;const o=t.byProviderModel??{};for(const a of Object.keys(o)){const n=a.indexOf(":"),i=n>0?a.slice(0,n):"deepseek",l=n>0?a.slice(n+1):a;if(Ue(i,l,s)==="plan")return!0}return!1}function yt(t){return(t?.input??0)+(t?.cacheRead??0)+(t?.cacheWrite??0)}function ra(t,s){if(t?.apiCost!==void 0)return ht(t);if(!ia(t,s))return $e(t,s);let o=0;for(const[a,n]of Object.entries(t.byProviderModel??{})){if(!Number.isFinite(n.cost))return la(t,s).api;const i=a.indexOf(":");Ue(a.slice(0,i),a.slice(i+1),s)==="plan"&&(o+=n.cost)}return Math.max(0,$e(t,s)-o)}function kt(t){const s=Math.abs(Math.round(Number(t)||0)),o=Math.floor(s/60),a=s%60;return"UTC"+(Number(t)<0?"-":"+")+o+(a>0?":"+String(a).padStart(2,"0"):"")}function bn(t){const s=t?.meta,o=Number(s?.timezoneOffsetMinutes);if(!Number.isFinite(o))return null;const a=-new Date().getTimezoneOffset();if(a===o)return null;const n=typeof s?.timezone=="string"&&s.timezone.length>0?s.timezone:"";return{hostLabel:n?n+" ("+kt(o)+")":kt(o),browserLabel:kt(a)}}function gn(t){let s=t;const o=new Set;return{getSnapshot:()=>s,subscribe:a=>(o.add(a),()=>{o.delete(a)}),set:a=>{if(a!==s){s=a;for(const n of[...o])n()}}}}const{createElement:e,Fragment:q,useState:L,useEffect:X,useRef:we}=Ee;function De({target:t,configured:s,source:o,t:a,api:n,placeholder:i,disabled:l}){const[r,u]=L(""),[d,c]=L(!1),[f,m]=L(null),p=l===!0||d,g=async()=>{const k=r.trim();if(!(k.length===0||p)){c(!0),m(null);try{const b=await n.setCredential(t,k);u(""),m({kind:"ok",text:b?.message??a("credentialSave")})}catch(b){m({kind:"err",text:String(b?.message??b)})}finally{c(!1)}}},x=async()=>{if(!p){c(!0),m(null);try{const k=await n.clearCredential(t);u(""),m({kind:"ok",text:k?.message??a("credentialClear")})}catch(k){m({kind:"err",text:String(k?.message??k)})}finally{c(!1)}}};return e("div",{className:"cm-field"},e("input",{className:"cm-input",type:"password",value:r,placeholder:typeof i=="string"?i:"",disabled:p,autoComplete:"off",onChange:k=>u(k.target.value)}),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:g,disabled:p||r.trim().length===0},a(d?"credentialSaving":"credentialSave")),s===!0?e("button",{className:"cm-btn small",onClick:x,disabled:p},a("credentialClear")):null),e("span",{className:"cm-hint"},s===!0?a("credentialConfiguredOf",{source:typeof o=="string"&&o.length>0?o:"unknown"}):a("credentialNotConfigured")),e("span",{className:"cm-hint"},a("credentialInputHint")),Et(f))}function hn({pending:t,t:s}){return!Array.isArray(t)||t.length===0?null:e("div",{className:"cm-msg err"},e("div",null,s("secretMigrationPending")),e("div",null,t.join("、")))}function Ze({size:t=16,className:s}){return e("svg",{width:t,height:t,className:s,viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e("path",{d:"M4 4H12A2 2 0 0 1 14 6V11.5A2 2 0 0 1 12 13.5H4A2 2 0 0 1 2 11.5V6A2 2 0 0 1 4 4ZM4 5.3H12A0.7 0.7 0 0 1 12.7 6V11.5A0.7 0.7 0 0 1 12 12.2H4A0.7 0.7 0 0 1 3.3 11.5V6A0.7 0.7 0 0 1 4 5.3Z",fill:"currentColor",fillRule:"evenodd"}),e("path",{d:"M3.3 5.3H12.7V7.1H3.3Z",fill:"currentColor"}),e("path",{d:"M8 2.8A1.3 1.3 0 1 0 8 5.4A1.3 1.3 0 1 0 8 2.8Z",fill:"currentColor"}))}function ca(t,s){const o=we(!1),a=we(""),n=s!==null&&typeof s=="object"?[s.input,s.cacheRead,s.cacheWrite,s.output,s.reasoning,s.cost].map(i=>String(i??0)).join("|"):"";X(()=>{if(!o.current){o.current=!0,a.current=n;return}if(n===""||n===a.current)return;a.current=n;const i=setTimeout(()=>{t.api?.reload?.()},800);return()=>clearTimeout(i)},[n])}function yn(t,s,o,a){const n=u=>["input","output","cacheRead","cacheWrite"].reduce((d,c)=>d+(u?.[c]??0),0),i=s?.found&&n(s.own)>=n(t)?s.own:t;if(!o||!s?.subagentCount)return i;const l=s.subagents,r={...i};for(const u of["input","output","cacheRead","cacheWrite","reasoning","cost"])r[u]=(i?.[u]??0)+(l?.[u]??0);r.apiCost=ra(i,a)+ht(l);for(const u of["byModel","byProviderModel"]){r[u]={...i?.[u]};for(const[d,c]of Object.entries(l?.[u]??{})){const f={...r[u][d]};for(const m of["input","output","cacheRead","cacheWrite","reasoning","cost"])f[m]=(f[m]??0)+(c[m]??0);delete f.apiCost,r[u][d]=f}}return r}function da(t){const s=t.useProjection?t.useProjection("costUsage"):void 0,o=t.useCost?.(r=>r)?.state,a=o?.config,[n,i]=L(null);ca(t,s),X(()=>{if(!t.sessionId||!t.api?.getSessionCost)return;let r=!0,u=!1;const d=async()=>{if(!u){u=!0;try{const f=await t.api.getSessionCost(t.sessionId);r&&i({id:t.sessionId,include:a?.includeSubagentCost===!0,value:f})}catch{}finally{u=!1}}};d();const c=a?.includeSubagentCost===!0?setInterval(d,1e4):null;return()=>{r=!1,c!==null&&clearInterval(c)}},[t.sessionId,o?.meta?.now,s,a?.includeSubagentCost]);const l=n&&n.id===t.sessionId&&n.include===(a?.includeSubagentCost===!0)?n.value:null;return{usage:yn(s,l,a?.includeSubagentCost===!0,a),config:a}}function ua(t,s){let o=0,a=$e(t,s);if(s.showTotalWithPlan!==!0&&(t.apiCost!==void 0||ia(t,s))){const n={total:$e(t,s),api:ra(t,s)};o=Math.max(0,n.total-n.api),o>0&&(a=n.api)}return{cost:a,planPart:o}}function kn(t){const{usage:s,config:o}=da(t);if(!s||!o||yt(s)+(s?.output??0)===0)return null;const a=K(W(o.locale)),{cost:n,planPart:i}=ua(s,o),l=[a("sessionCostTitle"),a("sessionDetailTokens",{input:I(s?.input??0),cache:I((s?.cacheRead??0)+(s?.cacheWrite??0)),output:I(s?.output??0)}),a("sessionDetailCache",{read:I(s?.cacheRead??0),write:I(s?.cacheWrite??0)}),a("cost",{amount:Y(n,o)}),...i>0?[a("sessionDetailPlan",{amount:Y(i,o)})]:[]].join("; ");return e($,{label:l,side:"top",delayMs:500},e("div",{className:"cm-chip"},i>0?a("costChipPlan",{amount:Y(n,o)}):a("cost",{amount:Y(n,o)})))}function wn(t){const{usage:s,config:o}=da(t);if(!s||!o)return null;const a=s.input??0,n=(s.cacheRead??0)+(s.cacheWrite??0),i=s.output??0;if(a+n+i===0)return null;const l=K(W(o.locale)),{cost:r,planPart:u}=ua(s,o),d=yt(s)>0?((s.cacheRead??0)/yt(s)*100).toFixed(1)+"%":"—";return e("div",{className:"cm-root"},l(u>0?"sessionLineSplit":"sessionLine",{amount:Y(r,o),planAmount:Y(u,o),hitRate:d,input:I(a),cache:I(n),output:I(i)}))}const xn={USD:"$",CNY:"¥",EUR:"€"};function xe(t,s,o){const a=typeof o=="string"?o.toUpperCase():"",n=typeof s?.symbol=="string"&&s.symbol.length>0?s.symbol:"$";return oe(t,{symbol:xn[a]??n,decimals:Math.max(2,Math.min(10,Math.floor(Number(s?.decimals)||2)))})}function ma(t,s){const o=Number(t?.balance?.budgetCap);if(Number.isFinite(o)&&o>0)return o;const a=Number(s?.maxBudget);return Number.isFinite(a)&&a>0?a:null}function vn(t){const s=t.today,o=s?.byProviderModel;if(o===null||typeof o!="object"||Object.keys(o).length===0)return Number(s?.cost)||0;let a=0;for(const[n,i]of Object.entries(o)){const l=n.indexOf(":");let r=l>=0?n.slice(0,l):n;r.startsWith("llm-")&&(r=r.slice(4)),!(r!=="deepseek"&&r!=="deepseek-official")&&(a+=Number(i?.cost)||0)}return a}function pa(t,s,o,a,n=null){const i=o==="official"?vn(t):Number(t.today?.cost)||0;if(o==="custom"){const r=je(s,a,n);if(r==="USD")return i;if(r==="CREDITS")return 0;const u=Number(s?.exchangeRate);return i*(Number.isFinite(u)&&u>0?u:1)}const l=Number(s?.exchangeRate);return i*(Number.isFinite(l)&&l>0?l:1)}function fa({remaining:t,spend:s,todayUsed:o,cap:a}){if(a===null||a<=0)return{remainingPct:100,todayPct:0,spentPct:0,hasCap:!1,pastSpend:0,today:0};const n=Math.max(0,Number(t)||0),i=Math.max(0,Number(s)||0),l=Math.max(0,Math.min(i,Number(o)||0)),r=Math.max(0,i-l),u=Math.max(0,Math.min(100,n/a*100)),d=Math.max(0,Math.min(100-u,l/a*100)),c=Math.max(0,Math.min(100-u-d,r/a*100));return{remainingPct:u,todayPct:d,spentPct:c,hasCap:!0,pastSpend:r,today:l}}function wt(t,s,o=null,a=null){const n=o??t.customBalance,i=ma(je(s,n,a)==="CREDITS"?null:s,n),l=Number(n?.remaining)||0,r=Number(n?.spend)||0,u=pa(t,s,"custom",n,a);return{cap:i,...fa({remaining:l,spend:r,todayUsed:u,cap:i})}}function Nn(t,s){const o=t.balance,a=ma(s,null),n=Number(o?.totalBalance)||0,i=pa(t,s,"official",null),l=a!==null?Math.max(0,a-n):0;return{cap:a,...fa({remaining:n,spend:l,todayUsed:i,cap:a})}}function xt(t){const{segments:s,direction:o="remaining"}=t,{remainingPct:a,todayPct:n,spentPct:i}=s,l=[];a>0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:a+"%"}})),n>0&&l.push(e("div",{className:"cm-bbox-seg-today",style:{width:n+"%"}})),i>0&&l.push(e("div",{className:"cm-bbox-seg-spent",style:{width:i+"%"}})),l.length===0&&l.push(e("div",{className:"cm-bbox-fill",style:{width:"100%"}}));const r=o==="used"?[...l].reverse():l;return e("div",{className:"cm-bbox-bar segments"+(o==="used"?" rev":"")},...r)}function ba(t,s,o,a,n){const i=[t("balanceBarRemaining",{amount:a})];return o.today>0&&i.push(t("balanceBarToday",{amount:s(o.today)})),o.pastSpend>0&&i.push(t("balanceBarSpent",{amount:s(o.pastSpend)})),n!==null&&n>0&&i.push(t("balanceBudgetCapLabel")+": "+s(n)),i.join(" · ")}function Pe(t){const[s,o]=L(!1),[a,n]=L(null);return{busy:s,err:a,run:()=>{s||typeof t!="function"||(o(!0),n(null),Promise.resolve().then(t).catch(l=>{n(l?.message??String(l))}).finally(()=>{o(!1)}))}}}const me=(t,s)=>({role:"button",tabIndex:0,"aria-busy":t?"true":"false",onClick:s,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),s())}});function ge(t,s){const o=[t("clickToRefresh")];return s.busy&&o.push(t("refreshing")),s.err&&o.push("⚠ "+t("balanceRefreshFailed",{message:s.err})),o}const Sn="https://platform.deepseek.com/usage";function ga(t){return e("a",{className:"cm-bal-link",href:Sn,target:"_blank",rel:"noreferrer noopener",title:t("balanceRechargeLink"),"aria-label":t("balanceRechargeLink"),onClick:s=>s.stopPropagation(),onKeyDown:s=>s.stopPropagation()},e("svg",{width:14,height:14,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},e("path",{d:"M8 4H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4M11 3h6v6M9 11l8-8"})))}function Cn(t){const{state:s,wide:o,api:a}=t,n=s.balance,i=K(W(s.config?.locale)),l=Pe(a?()=>a.refreshBalance():null);if(!n||n.status==="off")return null;if(n.status==="error")return e($,{label:[i("balanceQueryFailed",{message:n.message||i("unknownError")}),...ge(i,l)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,i("balance")," ",e("span",{className:"cm-num"},i("queryFailed"))):"⚠"));const r=[i("balanceTitle"),i("totalBalance",{amount:xe(n.totalBalance,s.config,n.currency)}),i("grantedToppedUp",{granted:xe(n.grantedBalance,s.config,n.currency),toppedUp:xe(n.toppedUpBalance,s.config,n.currency)}),i("updatedAt",{time:n.fetchedAt>0?new Date(n.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ge(i,l)].join("; ");return e($,{label:r,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(l.busy?" busy":""),...me(l.busy,l.run)},o?e(q,null,e("span",{className:"cm-balance-name"},i("balance"),ga(i)),e("span",{className:"cm-num cm-bal-amt"},xe(n.totalBalance,s.config,n.currency)),s.reconcile?.ok===!1?" ⚠":""):e(Ze,{size:16})))}function An(t){const{state:s,wide:o,api:a}=t,n=s.config,i=s.balance,l=K(W(n?.locale)),r=Pe(a?()=>a.refreshBalance():null);if(!i||i.status!=="ok")return null;const u=Nn(s,n),d=xe(i.totalBalance,n,i.currency),c=p=>xe(p,n,i.currency),f=[l("balanceTitle"),ba(l,c,u,d,u.cap),l("grantedToppedUp",{granted:xe(i.grantedBalance,n,i.currency),toppedUp:xe(i.toppedUpBalance,n,i.currency)}),l("updatedAt",{time:i.fetchedAt>0?new Date(i.fetchedAt).toLocaleTimeString():"—"}),...s.reconcile?.ok===!1?["⚠ "+s.reconcile.message]:[],...ge(l,r)].join("; "),m=e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-balance-name"},e("span",{className:"cm-bbox-label"},l("balance")),ga(l)),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},d)),e(xt,{segments:u,direction:te(n,"balance")}));return e($,{label:f,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(o?"":" rail")+(r.busy?" busy":""),...me(r.busy,r.run)},o?m:e("div",{className:"cm-bbox-rail cm-num"},Math.round(u.remainingPct)+"%")))}function vt(t,s){const o=typeof t?.label=="string"?t.label:"",a=typeof t?.labelEn=="string"?t.labelEn:"";return s==="en"?a||o||"Custom balance":o||a||"自定义余额"}function je(t,s,o){if((o??t?.customBalance)?.adapter==="aliyun"&&["CNY","USD","EUR"].includes(s?.unit))return s.unit;const a=o?.unit??t?.customBalance?.unit;return["CNY","EUR","USD","CREDITS"].includes(a)?a:["CNY","EUR","CREDITS"].includes(s?.unit)?s.unit:"USD"}function Qe(t,s,o,a){const n=je(s,o,a),i=Number(t);if(!Number.isFinite(i))return"—";const l=s?.currency==="USD"?1:Number(s?.exchangeRate);if((a??s?.customBalance)?.convertToDisplayCurrency===!0&&n==="USD"&&Number.isFinite(l)&&l>0){const c=i*l;return Number.isFinite(c)?oe(c,s):"—"}const r=n==="CREDITS",u=Math.max(2,Math.min(6,Math.floor(Number(s?.decimals)||4)));return(r?"":n==="CNY"?"¥":n==="EUR"?"€":"$")+sa(i,u)+(r?" Credits":"")}function Nt(t,s,o,a,n=null){const i=Qe(t.remaining,s,t,n),l=m=>Qe(m,s,t,n);if(a&&s.balance?.showProgressBar===!0){const m=wt(a,s,t,n);return[ba(o,l,m,i,m.cap),o("updatedAt",{time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"})].join(" · ")}const r=t.spend!==null?l(t.spend):"—",u=t.maxBudget!==null?l(t.maxBudget):"—",d=je(s,t,n)==="CREDITS"?NaN:Number(s?.balance?.budgetCap),c=Number.isFinite(d)&&d>0?o("balanceBudgetCapLabel")+": "+l(d):"",f=t.maxBudget!==null&&t.spend!==null?o("customBalanceLine",{remaining:i,spend:r,maxBudget:u,time:t.fetchedAt>0?new Date(t.fetchedAt).toLocaleTimeString():"—"}):o("customBalanceRemaining",{amount:i});return c?f+" · "+c:f}function Pn(t,s,o,a,n){const i=vt(n??s.customBalance??{},W(s?.locale)),l=Qe(a.remaining,s,a,n),r=wt(t,s,a,n);return{level:"ok",rail:Math.round(r.remainingPct)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},i),e("span",{className:"cm-bbox-pct cm-num cm-bal-amt"},l)),e(xt,{segments:r,direction:te(s,"balance")}))}}function St(t,s){const o=s?.customBalances??[],a=Array.isArray(t?.customBalances)?t.customBalances:[],n=[];return o.forEach((i,l)=>{if(i?.enabled!==!0||i.display!=="sidebar"&&i.display!=="both")return;const r=a.find(u=>u.index===l)??(a.length===1&&o.length===1?a[0]:null);n.push({index:l,entry:i,snapshot:r})}),n.length===0&&a.length===0&&s?.customBalance?.enabled===!0&&(s.customBalance.display==="sidebar"||s.customBalance.display==="both")&&t?.customBalance?.status&&t.customBalance.status!=="off"&&n.push({index:null,entry:s.customBalance,snapshot:t.customBalance}),n}function Mn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(W(n?.locale)),l=St(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:u,snapshot:d})=>e(Tn,{key:"cb-"+r,state:s,wide:o,api:a,t:i,index:r,entry:u,snapshot:d})))}function Tn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,u=s.config;if(r==null||r.status!=="ok")return null;const d=Pe(a?()=>a.refreshCustomBalance(i):null),c=Pn(s,u,n,r,l),f=[Nt(r,u,n,s,l),...ge(n,d)].join(" · ");return e($,{label:f,side:"right",delayMs:300},e("div",{className:"cm-bbox clickable"+(c.level==="ok"?"":" "+c.level)+(o?"":" rail")+(d.busy?" busy":""),...me(d.busy,d.run)},o?c.body:e("div",{className:"cm-bbox-rail cm-num"},c.rail)))}function Bn(t){const{state:s,wide:o,api:a}=t,n=s.config,i=K(W(n?.locale)),l=St(s,n);return l.length===0?null:e(q,null,l.map(({index:r,entry:u,snapshot:d})=>e(Dn,{key:"cbr-"+r,state:s,wide:o,api:a,t:i,index:r,entry:u,snapshot:d})))}function Dn(t){const{state:s,wide:o,api:a,t:n,index:i,entry:l,snapshot:r}=t,u=s.config,d=r??Gt(i);if(d.status==="off")return null;const c=Pe(a?()=>a.refreshCustomBalance(i):null),f=vt(l??u.customBalance??{},W(u?.locale));if(d.status==="error")return e($,{label:[d.message||n("unknownError"),...ge(n,c)].join("; "),side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+" cm-bal-err"+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:f},f),e("span",{className:"cm-num cm-bal-amt"},n("queryFailed"))):"⚠"));const m=Qe(d.remaining,u,d,l),p=[Nt(d,u,n,s,l),...ge(n,c)].join(" · ");return e($,{label:p,side:"right",delayMs:300},e("div",{className:"cm-foot clickable"+(o?"":" cm-foot-rail")+(c.busy?" busy":""),...me(c.busy,c.run)},o?e(q,null,e("span",{className:"cm-bal-label",title:f},f),e("span",{className:"cm-num cm-bal-amt"},m)):e(Ze,{size:16})))}function On(t){const o=(t.useCost?t.useCost(g=>g):void 0)?.state;if(!o)return null;const a=o.config,n=K(W(a?.locale)),i=a.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},l=o.goQuota,r=a?.goQuota?.enabled!==!1&&l?.status==="ok",u=g=>g!==null&&typeof g?.percent=="number"?Math.round(Math.max(0,Math.min(100,g.percent))):null,d=[];if(a.sidebarModels?.dock){const g=Aa(o,a.sidebarModels.period,n);g.length&&d.push({key:"model-top",text:e(q,null,e("span",{className:"cm-bal-label"},g[0].label),e("span",{className:"cm-bal-amt"},Y(g[0].cost,a))),tip:g[0].label+" "+Y(g[0].cost,a),level:"ok"})}const c=(g,x,k,b)=>{if(!i.enabled||!g||!r)return;const v=u(x);if(v===null)return;const S=typeof x.resetsAt=="string"&&x.resetsAt.length>0?n("goResetAt",{time:new Date(x.resetsAt).toLocaleString()}):"";d.push({key:k,text:n(k)+" "+v+"%",tip:n(b)+": "+v+"%"+(S?" · "+S:""),level:v>=100?"over":v>=80?"warn":"ok"})},f=a?.goQuota?.main==="weekly"||a?.goQuota?.main==="monthly"?a.goQuota.main:"rolling",m=[f,...["rolling","weekly","monthly"].filter(g=>g!==f)],p=g=>g==="rolling"?["goRolling",l?.rolling,"goShortRolling","cornerGoRolling"]:g==="weekly"?["goWeekly",l?.weekly,"goShortWeekly","cornerGoWeekly"]:["goMonthly",l?.monthly,"goShortMonthly","cornerGoMonthly"];for(const g of m){const[x,k,b,v]=p(g);c(i[x]===!0,k,b,v)}if(i.enabled&&i.budget===!0){const g=a.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const x=Number(a.exchangeRate),b=(o.budgetUsed??(g.period==="day"?_(o.today,a):g.period==="all"?_(o.total,a):_(o.month,a)))*(Number.isFinite(x)&&x>0?x:1),v=Math.max(0,Number(g.amount)||0),S=v>0?Math.min(999,b/v*100):null;if(S!==null){const w=S>=100?"over":S>=80?"warn":"ok";d.push({key:"budget",text:n("budgetShort")+" "+S.toFixed(1)+"%",tip:n("budgetOf",{period:n(qe[g.period]??"periodMonth")})+" · "+n("usedOf",{used:oe(b,a),amount:oe(v,a)}),level:w})}}}return d.length===0?null:e("div",{className:"cm-corner"},d.map(g=>e($,{key:g.key,label:g.tip,side:"top",delayMs:500},e("span",{className:"cm-corner-chip"+(g.key==="model-top"?" cm-model-top":"")+(g.level==="ok"?"":" "+g.level)},g.text))))}function Xe(t,s,o){if(!Array.isArray(s)||s.length===0||!Number.isFinite(t))return null;const a=(m,p)=>{const g=new Date(t);return g.setUTCDate(g.getUTCDate()+m),g.setUTCHours(p,0,0,0),g.getTime()},n=new Set,i=Math.max(12,Math.min(380,(Array.isArray(o)?o.length:0)+7));for(let m=-i;m<=i;m+=1){n.add(a(m,16));for(const p of s){const g=Number(p?.start),x=Number(p?.end);!Number.isFinite(g)||!Number.isFinite(x)||(n.add(a(m,g)),n.add(a(x<=g?m+1:m,x)))}}const l=[...n].sort((m,p)=>m-p).flatMap(m=>{const p=Je(m-1,void 0,s,o),g=Je(m,void 0,s,o);return p===g?[]:[{at:m,intoPeak:g}]});let r=null,u=null;for(const m of l)m.at<=t&&(r===null||m.at>r.at)&&(r=m),m.at>t&&(u===null||m.at<u.at)&&(u=m);const d=ea(t,o),c=d??Xt(t);return c!==null?u===null?null:{inPeak:!1,weekend:d===null,...d?{holiday:!0}:{},prevAtMs:c.start,nextAtMs:u.at,nextIntoPeak:u.intoPeak}:r===null||u===null?null:{inPeak:Je(t,void 0,s,o),weekend:!1,prevAtMs:r.at,nextAtMs:u.at,nextIntoPeak:u.intoPeak}}function et(t,s){if(!t||t.peakNotice===!1||t.peakEnabled!==!0)return null;const o=Date.parse(t.peakEffectiveAt||"");if(Number.isFinite(o)&&s<o)return null;const a=Array.isArray(t.peakWindows)?t.peakWindows:[];return Xe(s,a,t.peakHolidays)}function tt(t){return t.holiday===!0?{short:"holidayShort",chip:"holidayChip",notice:"holidayAllOffPeak"}:t.weekend===!0?{short:"weekendShort",chip:"weekendChip",notice:"weekendAllOffPeak"}:t.inPeak?{short:"peakShort",chip:"peakShort",notice:"peakNotice"}:{short:"offPeakShort",chip:"offPeakShort",notice:"offPeakActive"}}function he(t,s,o){const a=Math.max(0,t.nextAtMs-s),n=Math.max(1,Math.ceil(a/6e4)),i=Math.floor(n/60),l=n%60;return i>0?l>0?o("countdownHourMinute",{h:i,m:l}):o("countdownHoursOnly",{h:i}):o("countdownMinute",{m:n})}const Ct="cm-peak-alert-preview";let ha=0;function Rn(t){const s=t.useCost?t.useCost(x=>x):void 0,o=s?.state?.config,[a,n]=L(Date.now()),[i,l]=L(null),[r,u]=L(null);if(X(()=>{const x=window.setInterval(()=>n(Date.now()),1e4);return()=>window.clearInterval(x)},[]),X(()=>{const x=k=>{const b=k.detail?.kind==="offpeak"?"offpeak":"peak";u(b);const v=s?.state?.config;if(v?.peakAlertWebNotify===!0&&window.Notification&&Notification.permission==="granted"){const S=K(W(v.locale));try{new Notification(S(b==="peak"?"peakAlertTitlePeak":"peakAlertTitleOffPeak")+S("peakAlertPreviewTag"),{body:S("peakAlertBody",{time:S("countdownMinute",{m:2}),phase:S(b==="peak"?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}}};return window.addEventListener(Ct,x),window.__cmPeakAlertLive=!0,()=>{window.removeEventListener(Ct,x),window.__cmPeakAlertLive=!1}},[]),X(()=>{if(!o||o.peakAlertEnabled!==!0||o.peakEnabled!==!0||o.peakAlertWebNotify!==!0||!window.Notification||Notification.permission!=="granted")return;const x=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(x===null)return;const k=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",b=x.nextIntoPeak===!0;if(k!=="both"&&k!==(b?"peak":"offpeak"))return;const v=Number(o.peakAlertAhead),S=(Number.isFinite(v)&&v>=1?v:2)*6e4;if(a<x.nextAtMs-S||a>=x.nextAtMs||ha===x.nextAtMs)return;const w=K(W(o.locale));ha=x.nextAtMs;try{new Notification(w(b?"peakAlertTitlePeak":"peakAlertTitleOffPeak"),{body:w("peakAlertBody",{time:he(x,a,w),phase:w(b?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})})}catch{}},[a]),!o||o.peakEnabled!==!0)return null;let d=null;if(o.peakAlertEnabled===!0){const x=Date.parse(o.peakEffectiveAt||"");if(!(Number.isFinite(x)&&a<x)){const k=Xe(a,Array.isArray(o.peakWindows)?o.peakWindows:[],o.peakHolidays);if(k!==null){const b=o.peakAlertTarget==="peak"||o.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",v=Number(o.peakAlertAhead),S=(Number.isFinite(v)&&v>=1?v:2)*6e4;(b==="both"||b===(k.nextIntoPeak?"peak":"offpeak"))&&a>=k.nextAtMs-S&&a<k.nextAtMs&&i!==k.nextAtMs&&(d=k)}}}let c=null,f=!1,m=null;if(d!==null)c=d,f=d.nextIntoPeak===!0,m=()=>l(d.nextAtMs);else if(r!==null)c={nextAtMs:a+2*6e4,nextIntoPeak:r==="peak"},f=r==="peak",m=()=>u(null);else return null;const p=K(W(o.locale)),g=o.peakAlertPosition==="center"?"cm-peak-alert-center":"cm-peak-alert-corner";return e("div",{className:"cm-peak-alert "+g+" "+(f?"cm-peak-alert-peak":"cm-peak-alert-offpeak"),role:"alert"},e("div",{className:"cm-peak-alert-badge"},p(f?"peakAlertBadgePeak":"peakAlertBadgeOffPeak")),e("div",{className:"cm-peak-alert-title"},p(f?"peakAlertTitlePeak":"peakAlertTitleOffPeak")),e("div",{className:"cm-peak-alert-body"},p("peakAlertBody",{time:he(c,a,p),phase:p(f?"peakAlertPhasePeak":"peakAlertPhaseOffPeak")})),e("div",{className:"cm-peak-alert-actions"},e("button",{className:"cm-btn",onClick:m},p("peakAlertBtn"))))}function Ln(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)});return e($,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-strip "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"}),e("div",{className:"cm-peak-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-chip"},o(l.chip)+" · "+r)))}function En(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const u=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(u)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)});return e($,{label:o(l.notice),side:"right",delayMs:300},e("div",{className:"cm-peak-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off")},e("div",{className:"cm-peak-classic-marker",style:{left:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}}),e("div",{className:"cm-peak-track"},e("div",{className:"cm-peak-segment cm-peak-high"}),e("div",{className:"cm-peak-segment cm-peak-low"})),e("span",{className:"cm-peak-classic-chip"},o(l.chip)+" · "+r)))}function at(t,s,o){return e(s?.peakStyle==="classic"?En:Ln,{config:s,t:o})}function qn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)}),u=[o(l.notice),r];return e($,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-track"},e("div",{className:"cm-peak-rail-segment cm-peak-rail-high"}),e("div",{className:"cm-peak-rail-segment cm-peak-rail-low"}),e("div",{className:"cm-peak-rail-marker",style:{top:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-label"},o(l.short))))}function Hn(t){const{config:s,t:o}=t,[a,n]=L(Date.now());X(()=>{const d=window.setInterval(()=>n(Date.now()),3e4);return()=>window.clearInterval(d)},[]);const i=et(s,a);if(i===null)return null;const l=tt(i),r=i.nextIntoPeak?o("nextPeakIn",{time:he(i,a,o)}):o("nextOffPeakIn",{time:he(i,a,o)}),u=[o(l.notice),r];return e($,{label:u,side:"right",delayMs:300},e("div",{className:"cm-peak-rail-classic "+(i.weekend||i.holiday?"weekend":i.inPeak?"peak":"off"),"aria-label":u.join("; ")},e("div",{className:"cm-peak-rail-classic-track"},e("div",{className:"cm-peak-rail-classic-segment peak"}),e("div",{className:"cm-peak-rail-classic-segment off"}),e("div",{className:"cm-peak-rail-classic-marker",style:{top:i.weekend||i.holiday?"50%":i.inPeak?"25%":"75%"}})),e("span",{className:"cm-peak-rail-classic-label"},o(l.short))))}function In(t,s,o){return e(s?.peakStyle==="classic"?Hn:qn,{config:s,t:o})}function ya(t,s,o){const a=t.today,n=s.budget??{enabled:!1,amount:100,period:"month"},i=Number(s.exchangeRate),r=(t.budgetUsed??(n.period==="day"?_(t.today,s):n.period==="all"?_(t.total,s):_(t.month,s)))*(Number.isFinite(i)&&i>0?i:1),u=Math.max(0,Number(n.amount)||0),d=u>0?Math.min(999,r/u*100):null,c=ue(d===null?null:Math.min(100,d),te(s,"budget")),f=_(a,s)*(Number.isFinite(i)&&i>0?i:1),m=u>0?Math.min(999,f/u*100):null,p=n.detail!==!1;return{level:d===null?"ok":d>=100?"over":d>=80?"warn":"ok",rail:c.label===null?"—":Math.round(c.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("budget")),e("span",{className:"cm-bbox-pct cm-num"},c.label===null?"—":c.label.toFixed(1)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:c.width+"%"}})),p?e(q,null,s.hideTodayCost===!0?null:e("div",{className:"cm-bbox-line cm-num"},o("todayShare",{amount:Y(_(a,s),s),pct:m===null?"—":m.toFixed(1)+"%"})),e("div",{className:"cm-bbox-line cm-num"},o("usedOf",{used:oe(r,s),amount:oe(u,s)}))):null,at(t,s,o))}}function ka(t,s,o){const a=t.goQuota,n=s?.goQuota?.main==="weekly"||s?.goQuota?.main==="monthly"?s.goQuota.main:"rolling",i=a[n],l=i!==null&&typeof i?.percent=="number"?Math.max(0,Math.min(100,Number(i.percent)||0)):0,r=p=>p!==null&&typeof p?.percent=="number"?Math.round(Math.max(0,Math.min(100,p.percent)))+"%":"—",u=p=>o(p==="rolling"?"goShortRolling":p==="weekly"?"goShortWeekly":"goShortMonthly"),d=["rolling","weekly","monthly"].filter(p=>p!==n),c=i!==null&&typeof i?.resetsAt=="string"&&i.resetsAt.length>0?o("goResetAt",{time:new Date(i.resetsAt).toLocaleString()}):"",f=s?.goQuota?.detail!==!1,m=ue(l,te(s,"go"));return{level:l>=100?"over":l>=80?"warn":"ok",rail:m.label===null?"—":Math.round(m.label)+"%",body:e(q,null,e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bbox-label"},o("goQuotaRowLabel")+" "+u(n)),e("span",{className:"cm-bbox-pct cm-num"},m.label===null?"—":Math.round(m.label)+"%")),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:m.width+"%"}})),f?e(q,null,e("div",{className:"cm-bbox-line cm-num"},d.map(p=>u(p)+" "+r(a[p])).join(" · ")),c?e("div",{className:"cm-bbox-line"},c):null):null)}}function Un(t){const{state:s,wide:o}=t,a=s.goQuota,n=K(W(s.config?.locale));if(!a||a.status!=="ok")return null;const i=s.config?.goQuota?.main==="weekly"||s.config?.goQuota?.main==="monthly"?s.config.goQuota.main:"rolling";if(a[i]===null||typeof a[i]?.percent!="number")return null;const l=ka(s,s.config,n),r=[n("goQuotaTitle"),n("goWindowRolling")+": "+(a.rolling===null?"—":Math.round(a.rolling.percent)+"%"),n("goWindowWeekly")+": "+(a.weekly===null?"—":Math.round(a.weekly.percent)+"%"),n("goWindowMonthly")+": "+(a.monthly===null?"—":Math.round(a.monthly.percent)+"%"+(a.monthly!==null&&typeof a.monthly.resetsAt=="string"&&a.monthly.resetsAt.length>0?" · "+n("goResetAt",{time:new Date(a.monthly.resetsAt).toLocaleString()}):"")),n("goQuotaFetchedAt",{time:a.fetchedAt>0?new Date(a.fetchedAt).toLocaleTimeString():"—"})].join("; ");return e($,{label:r,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(l.level==="ok"?"":" "+l.level)+(o?"":" rail")},o?l.body:e("div",{className:"cm-bbox-rail cm-num"},l.rail)))}function jn(t){return t===null||typeof t!="object"||t.unlimited||typeof t.percent!="number"?null:Math.max(0,Math.min(100,Math.round(Number(t.percent)||0)))}function Fe(t){const s=t!==null&&typeof t=="object"?t:{};return{five:s["5h"]??null,seven:s["7d"]??s.week??s.weekly??null}}function wa(t,s,o=Date.now()){if(typeof t!="string"||!t)return"";const a=Date.parse(t);if(!Number.isFinite(a))return"";const n=a-o;if(n<=0)return s("resetReached");const i=Math.ceil(n/6e4),l=Math.floor(i/1440),r=Math.floor(i%1440/60),u=i%60;return l>0?s("resetDays",{d:l,h:r}):r>0?s("resetHours",{h:r,m:u}):s("resetMinutes",{m:u})}function _e(t,s,o=Date.now()){const a=wa(t?.resetsAt,s,o);return a?s("goResetAt",{time:new Date(t.resetsAt).toLocaleString()})+" ("+a+")":""}function nt(t,s,o){return t===null?"—":o(s==="remaining"?"quotaRemaining":"quotaUsed",{pct:t})}function st(t){const[,s]=L(0),o=()=>s(Date.now());return X(()=>{if(!t)return;const a=setInterval(o,6e4);return()=>clearInterval(a)},[t]),{onMouseEnter:o,onFocus:o}}function We(t,s,o,a){const n=jn(s),i=n===null?"ok":n>=100?"over":n>=80?"warn":"ok",l=ue(n,o),r=s?.unlimited?"∞":l.label===null?"—":l.label+"%";return{level:i,pct:n,text:r,label:l.label,row:e("div",{className:"cm-mm-row"+(i==="ok"?"":" "+i)},e("span",{className:"cm-bbox-label"},t),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:l.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},r))}}function xa(t){const{five:s,seven:o,fetchedAt:a,t:n,wide:i,refresh:l,direction:r="used"}=t,u=st(s?.resetsAt),d=wa(s?.resetsAt,n),c=We(n("codingPlanRemain5h"),s,r,n),f=We(n("codingPlanRemain7d"),o,r,n),m=c.level==="over"||f.level==="over"?"over":c.level==="warn"||f.level==="warn"?"warn":"ok",p=(b,v,S)=>{const w=v?.unlimited?n("quotaUnlimited"):nt(S.label,r,n),A=_e(v,n);return b+" "+w+(A?" · "+A:"")},g=[n("codingPlanMinimaxTitle"),p(n("codingPlanRemain5h"),s,c),p(n("codingPlanRemain7d"),o,f),a>0?n("goQuotaFetchedAt",{time:new Date(a).toLocaleTimeString()}):null,...l?ge(n,l):[]].filter(Boolean).join(`
|
|
3
|
+
`),x=e(q,null,e("div",{className:"cm-mm-title"},n("codingPlanMinimaxTitle")),c.row,f.row,d?e("div",{className:"cm-mm-reset"},"5h · "+d):null),k=e(q,null,e("div",{className:"cm-bbox-rail cm-num"},c.text),e("div",{className:"cm-bbox-rail cm-num"},f.text));return e($,{label:e("span",{style:{whiteSpace:"pre-line"}},g),side:"right",delayMs:300},e("div",{...u,className:"cm-bbox cm-mm"+(m==="ok"?"":" "+m)+(i===!1?" rail":"")+(l?" clickable"+(l.busy?" busy":""):""),...l?me(l.busy,l.run):{}},i===!1?k:x))}function Qn(t){const{state:s,wide:o,api:a}=t,n=s.codingPlans?.minimax,i=K(W(s.config?.locale)),l=Pe(a?()=>a.refreshCodingPlan("minimax"):null);if(!n||n.status!=="ok")return null;const{five:r,seven:u}=Fe(n.windows);return r==null&&u==null?null:e(xa,{five:r,seven:u,fetchedAt:n.fetchedAt,t:i,wide:o,refresh:l,direction:te(s.config,"plan")})}const Fn="/plugins/dsh-openai-codex/auth/status",_n=168*3600;function Wn(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)===_n);if(!a||typeof a.remainingPercent!="number"||!Number.isFinite(Number(a.remainingPercent)))return null;const n=Math.max(0,Math.min(100,Math.round((100-Number(a.remainingPercent))*10)/10)),i=Number(a.resetAt),l=Number.isFinite(i)&&i>0?new Date(i*1e3).toISOString():"";return{weekly:{percent:n,resetsAt:l}}}const J={status:"idle",windows:{},fetchedAt:0,inFlight:null,listeners:[]},zn=t=>(J.listeners.push(t),()=>{J.listeners=J.listeners.filter(s=>s!==t)}),Gn=()=>{for(const t of J.listeners)try{t()}catch{}};async function At(t=!1,s=!1){if(!s)return;if(J.inFlight!==null)return J.inFlight;if(!t&&J.fetchedAt>0&&Date.now()-J.fetchedAt<5*6e4)return;const o=(async()=>{try{const a=await fetch(Fn,{credentials:"same-origin",headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});let n={};if(a.ok){const i=Wn(await a.json().catch(()=>null));i!==null&&(n=i)}J.status=Object.keys(n).length>0?"ok":"unavailable",J.windows=n}catch{J.status="unavailable"}finally{J.fetchedAt=Date.now(),J.inFlight=null,Gn()}})();return J.inFlight=o,o}function Pt(t){const[s,o]=L(()=>({status:J.status,windows:J.windows,fetchedAt:J.fetchedAt}));return X(()=>{if(!t)return;let a=!0;const n=()=>{a&&o({status:J.status,windows:J.windows,fetchedAt:J.fetchedAt})},i=zn(n);return n(),At(!1,!0),()=>{a=!1,i()}},[t]),s}function Kn(t){const s=st(),{state:o,wide:a}=t,n=K(W(o.config?.locale)),i=Pt(o.config?.codexQuotaEnabled===!0),l=Pe(()=>At(!0,o.config?.codexQuotaEnabled===!0));if(o.config?.codexQuotaEnabled!==!0||i.status!=="ok")return null;const r=i.windows.weekly??null;if(r===null)return null;const u=te(o.config,"plan"),d=We(n("goShortWeekly"),r,u,n),c=[n("codexQuotaTitle"),nt(d.label,u,n),_e(r,n),i.fetchedAt>0?n("goQuotaFetchedAt",{time:new Date(i.fetchedAt).toLocaleTimeString()}):null,...ge(n,l)].filter(Boolean).join(`
|
|
4
|
+
`),f=e(q,null,e("div",{className:"cm-mm-title"},n("codexQuotaTitle")),d.row),m=e("div",{className:"cm-bbox-rail cm-num"},d.label===null?"—":d.label+"%");return e($,{label:e("span",{style:{whiteSpace:"pre-line"}},c),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(d.level==="ok"?"":" "+d.level)+(a===!1?" rail":"")+(l.busy?" busy":""),...me(l.busy,l.run)},a===!1?m:f))}function Mt(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 Yn(t){const s=st(),{id:o,state:a,wide:n,api:i}=t,l=a.codingPlans?.[o],r=K(W(a.config?.locale)),u=Pe(i?()=>i.refreshCodingPlan(o):null),d=Re.find(w=>w.id===o);if(!d||!l||l.status!=="ok")return null;const c=l.windows!==null&&typeof l.windows=="object"?l.windows:{},f=Object.entries(c);if(f.length===0)return null;const m=w=>w!==null&&typeof w=="object"&&typeof w.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(w.percent)||0))):null,p=te(a.config,"plan"),g=f.map(([w,A])=>{const y=m(A);if(y===null)return e("div",{key:w,className:"cm-mm-row wide"},e("span",{className:"cm-mm-text"},typeof A?.text=="string"?A.text:"—"));const M=y>=100?"over":y>=80?"warn":"ok",T=ue(y,p);return e("div",{key:w,className:"cm-mm-row wide"+(M==="ok"?"":" "+M)},e("span",{className:"cm-bbox-label"},Mt(w,r)),e("div",{className:"cm-bbox-bar"},e("div",{className:"cm-bbox-fill",style:{width:T.width+"%"}})),e("span",{className:"cm-bbox-pct cm-num"},T.label===null?"—":T.label+"%"))}),x=f.map(([w,A])=>{const y=m(A),M=_e(A,r),T=y===null?typeof A?.text=="string"?A.text:"—":nt(ue(y,p).label,p,r);return Mt(w,r)+" "+T+(M?" · "+M:"")});l.fetchedAt>0&&x.push(r("goQuotaFetchedAt",{time:new Date(l.fetchedAt).toLocaleTimeString()})),x.push(...ge(r,u));const k=[r(d.labelKey),...x].join(`
|
|
5
|
+
`),b=f.map(([,w])=>m(w)).filter(w=>w!==null),v=b.some(w=>w>=100)?"over":b.some(w=>w>=80)?"warn":"ok",S=b.length>0?b.slice(0,2).map(w=>ue(w,p).label+"%").join(" "):typeof f[0][1]?.text=="string"?f[0][1].text:"—";return e($,{label:e("span",{style:{whiteSpace:"pre-line"}},k),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(v==="ok"?"":" "+v)+(n===!1?" rail":"")+(u.busy?" busy":""),...me(u.busy,u.run)},n===!1?e("div",{className:"cm-bbox-rail cm-num"},S):e(q,null,e("div",{className:"cm-mm-title"},r(d.labelKey)),...g)))}const va=t=>{try{return window.localStorage?.getItem?.("cm.gw."+t)??""}catch{return""}},Vn=(t,s)=>{try{window.localStorage?.setItem?.("cm.gw."+t,s)}catch{}};function Jn(t){const s=st(),{source:o,snapshot:a,state:n,wide:i,api:l}=t,r=K(W(n.config?.locale)),[u,d]=L(()=>({source:o.id,id:va(o.id)})),c=Pe(l?()=>l.refreshGatewayQuota(o.id):null),f=te(n.config,"plan"),m=a.accounts.length>1,p=u.source===o.id?u.id:va(o.id),g=a.accounts.findIndex(O=>O.id===p),x=g>=0?g:Math.max(0,a.accounts.findIndex(O=>O.windows.length>0||O.credits!=null)),k=a.accounts[x]??a.accounts[0],b=k?.label||k?.id||"",v=O=>m?(Yt[O.provider]??O.provider)+" · ":"",S=m&&k?[k]:a.accounts,w=[];for(const O of S){if(w.length>=4)break;for(const G of O.windows){if(w.length>=4)break;const R=v(O)+(G.label||G.id||r("gatewaySourceUnknown"));w.push({win:G,name:R,view:We(R,G,f,r)})}O.windows.length===0&&O.credits!=null&&w.push({win:null,name:v(O)+(O.credits.unit||"credits"),text:(O.credits.used??"—")+" / "+(O.credits.limit??"—")})}w.length===0&&w.push({name:r("gatewayQuotaEmpty"),text:"—"});const A=w.some(O=>O.view?.level==="over")?"over":w.some(O=>O.view?.level==="warn")?"warn":"ok",y=w.map(O=>{if(O.text!=null)return O.name+" "+O.text;const G=_e(O.win,r);return O.name+" "+nt(O.view.label,f,r)+(G?" · "+G:"")});a.fetchedAt>0&&y.push(r("goQuotaFetchedAt",{time:new Date(a.fetchedAt).toLocaleTimeString()})),y.push(...ge(r,c));const T=[m&&b?`${o.label||o.id} (${x+1}/${a.accounts.length} · ${b})`:o.label||o.id,...y].join(`
|
|
6
|
+
`),B=w.map((O,G)=>O.text!=null?e("div",{key:G,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},O.name),e("span",{className:"cm-mm-text cm-num"},O.text)):e(q,{key:G},O.view.row)),P=O=>{if(!O.key||O.key==="Enter"||O.key===" "){O.stopPropagation(),O.preventDefault?.();const G=a.accounts[(x+1)%a.accounts.length];Vn(o.id,G.id),d({source:o.id,id:G.id})}},E=m?e("span",{className:"cm-gw-switcher","aria-label":r("gatewaySwitchAccount",{account:b||x+1}),onClick:P,onKeyDown:P,role:"button",tabIndex:0},`${x+1}/${a.accounts.length} ⇄`):null,h=m?e("div",{className:"cm-bbox-head"},e("div",{className:"cm-mm-title"},o.label||o.id),E):e("div",{className:"cm-mm-title"},o.label||o.id),U=m&&b?e("div",{className:"cm-gw-sub"},b):null,ee=e(q,null,h,U,...B),ye=w.filter(O=>O.view).map(O=>O.view.label).filter(O=>O!==null),ve=ye.length>0?ye.slice(0,2).map(O=>O+"%").join(" "):w[0].text??"—",D=e("div",{className:"cm-bbox-rail cm-num"},ve);return e($,{label:e("span",{style:{whiteSpace:"pre-line"}},T),side:"right",delayMs:300},e("div",{...s,className:"cm-bbox cm-mm clickable"+(A==="ok"?"":" "+A)+(i===!1?" rail":"")+(c.busy?" busy":""),...me(c.busy,c.run)},i===!1?e(q,null,D,E):ee))}function $n(t,s,o,a){const n=Array.isArray(t.gatewayQuotas)?t.gatewayQuotas:[],i=[];for(const l of s.gatewayQuotas?.sources??[]){if(l.enabled===!1||l.display!=="sidebar"&&l.display!=="both")continue;const r=n.find(u=>u.id===l.id);!r||r.status!=="ok"&&r.status!=="partial"&&r.status!=="stale"||r.accounts.length===0||i.push(e(Jn,{source:l,snapshot:r,state:t,wide:o,api:a}))}return i}const Zn={anthropic:"Claude",zai:"Z.ai",minimax:"MM",kimi:"Kimi",openrouter:"OR",siliconflow:"SF",commandcode:"CC",scnet:"SCNet",volcengine:"Ark",qwen:"Qwen",mimo:"MiMo"};function Xn(t){const s=t.useCost?t.useCost(g=>g):void 0;Pt(s?.state?.config?.codexQuotaEnabled===!0);const[o,a]=L(null),[n,i]=L({}),l=s?.state,r=t.api;if(!l)return null;const u=l.config,d=u.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};if(d.enabled!==!0)return null;const c=K(W(u?.locale)),f=[];if(d.budget!==!1){const g=u.budget??{enabled:!1,amount:100,period:"month"};if(g.enabled===!0){const x=Number(u.exchangeRate),b=(l.budgetUsed??(g.period==="day"?_(l.today,u):g.period==="all"?_(l.total,u):_(l.month,u)))*(Number.isFinite(x)&&x>0?x:1),v=Math.max(0,Number(g.amount)||0);if(v>0){const S=Math.min(999,b/v*100),w=S>=100?"over":S>=80?"warn":"ok";f.push({key:"budget",label:c("budgetShort"),level:w,tip:c("budgetOf",{period:c(qe[g.period]??"periodMonth")})+" · "+c("usedOf",{used:oe(b,u),amount:oe(v,u)})+" · "+S.toFixed(1)+"%",segs:[{name:"main",pct:Math.round(ue(Math.min(100,S),te(u,"budget")).width)}]})}}}if(d.go!==!1){const g=l.goQuota;if(u?.goQuota?.enabled!==!1&&g?.status==="ok"){const x=u.goQuota.main==="weekly"||u.goQuota.main==="monthly"?u.goQuota.main:"rolling",k=x==="rolling"?g.rolling:x==="weekly"?g.weekly:g.monthly;if(k!==null&&typeof k=="object"&&typeof k.percent=="number"){const b=Math.max(0,Math.min(100,Math.round(Number(k.percent)||0))),v=b>=100?"over":b>=80?"warn":"ok",S=typeof k.resetsAt=="string"&&k.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(k.resetsAt).toLocaleString()}):"";f.push({key:"go",label:"Go "+c(x==="rolling"?"goShortRolling":x==="weekly"?"goShortWeekly":"goShortMonthly"),level:v,tip:"Go: "+b+"%"+S,segs:[{name:"main",pct:Math.round(ue(b,te(u,"go")).width)}]})}}}if(d.plans!==!1)for(const g of Re){const x=l.codingPlans?.[g.id];if(u.codingPlans?.[g.id]?.enabled!==!0||!x||x.status!=="ok")continue;const k=x.windows!==null&&typeof x.windows=="object"?x.windows:{},b=Object.entries(k);if(b.length===0)continue;const v=Zn[g.id]??g.id,S=[],w=[];let A=0,y=0;for(const[M,T]of b){const B=Mt(M,c),P=typeof T?.resetsAt=="string"&&T.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(T.resetsAt).toLocaleString()}):"",E=T!==null&&typeof T=="object"&&typeof T.percent=="number"?Math.max(0,Math.min(100,Math.round(Number(T.percent)||0))):null;if(w.push(B+" "+(E===null?typeof T?.text=="string"?T.text:"—":E+"%")+P),E===null){S.push({name:M,pct:null,text:typeof T?.text=="string"?T.text:"—"});continue}y>=2||(y+=1,S.push({name:M,pct:Math.round(ue(E,te(u,"plan")).width)}),A=Math.max(A,E>=100?2:E>=80?1:0))}x.fetchedAt>0&&w.push(c("goQuotaFetchedAt",{time:new Date(x.fetchedAt).toLocaleTimeString()})),S.length!==0&&f.push({key:g.id,label:v,level:["ok","warn","over"][A],tip:w.join("; "),segs:S})}const m=u.codexQuotaEnabled===!0&&J.status==="ok"?J.windows.weekly??null:null;if(m!==null&&typeof m.percent=="number"){const g=Math.max(0,Math.min(100,Math.round(Number(m.percent)||0))),x=typeof m.resetsAt=="string"&&m.resetsAt.length>0?" · "+c("goResetAt",{time:new Date(m.resetsAt).toLocaleString()}):"";f.push({key:"codex",label:"Codex",level:g>=100?"over":g>=80?"warn":"ok",tip:c("codexQuotaTitle")+": "+g+"%"+x,segs:[{name:"weekly",pct:Math.round(ue(g,te(u,"plan")).width)}]})}if(f.length===0)return null;const p=g=>{o!==null||!r||(a(g),i(x=>({...x,[g]:null})),Promise.resolve().then(()=>g==="budget"?r.reload():g==="go"?r.refreshGoQuota():g==="codex"?At(!0,u.codexQuotaEnabled===!0):r.refreshCodingPlan(g)).catch(x=>{i(k=>({...k,[g]:x?.message??String(x)}))}).finally(()=>a(null)))};return e("div",{className:"cm-qstrip"},f.map(g=>{const x=o===g.key,k=n[g.key],b=[e("span",{className:"cm-qlabel",key:"l"},g.label)];x?b.push(e("span",{className:"cm-qtext",key:"busy"},c("refreshing"))):g.segs.forEach((S,w)=>{w>0&&b.push(e("span",{className:"cm-qsep",key:"sep"+w,"aria-hidden":"true"})),S.pct===null?b.push(e("span",{className:"cm-qtext",key:S.name},S.text)):b.push(e("span",{className:"cm-qseg",key:S.name},e("span",{className:"cm-qbar"},e("span",{className:"cm-qfill",style:{width:S.pct+"%"}})),e("span",null,S.pct+"%")))});const v=[g.tip];return!x&&r&&v.push(c("clickToRefresh")),x&&v.push(c("refreshing")),k&&v.push("⚠ "+c("balanceRefreshFailed",{message:k})),e($,{key:g.key,label:v.join("; "),side:"bottom",delayMs:400},e("span",{className:"cm-qchip"+(r?" action":"")+(g.level==="ok"?"":" "+g.level),...r?me(x,()=>p(g.key)):{}},b))}))}const Na="dsh-cost-meter:simple-guide-dismissed";function Tt(t){if(t?.sidebarSimplePromptSeen===!0)return!0;try{return window.localStorage.getItem(Na)==="1"}catch{return!1}}function es(t){const s=t.useCost?t.useCost(p=>p):void 0,o=we(!1),[a,n]=L(!1),[i,l]=L(!1),[r,u]=L(!1),d=s?.state?.config;if(!d||r||Tt(d))return null;const c=K(W(d.locale)),f=()=>{u(!0);try{window.localStorage.setItem(Na,"1")}catch{}},m=async p=>{if(!o.current){o.current=!0,n(!0),l(!1);try{if((await t.api.updateConfig({sidebarSimple:p,sidebarSimplePromptSeen:!0}))?.config?.sidebarSimple!==p)throw new Error;f()}catch{l(!0)}finally{o.current=!1,n(!1)}}};return e("div",{className:"cm-qguide",role:"dialog","aria-label":c("sidebarSimpleTitle"),"aria-busy":a,onKeyDown:p=>{p.key==="Escape"&&(p.stopPropagation(),f())}},e("div",{className:"cm-bbox-head"},e("h4",null,c("sidebarSimpleTitle")),e("button",{type:"button",className:"cm-btn small","aria-label":c("closeGuide"),onClick:f},"×")),e("p",null,c("sidebarSimpleBody")),i?e("p",{role:"alert"},c("sidebarSimpleError")):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",disabled:a,onClick:()=>m(!1)},c("sidebarSimpleOff")),e("button",{type:"button",className:"cm-btn small primary",disabled:a,onClick:()=>m(!0)},c("sidebarSimpleOn"))))}function ts(t){const s=t.useCost?t.useCost(r=>r):void 0,o=we(!1),a=s?.state;if(!a)return null;const n=a.config;if(!Tt(n)||n.quotaStrip?.promptSeen===!0)return null;const i=K(W(n?.locale)),l=r=>{if(o.current===!0)return;o.current=!0;const u=n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0};t.api.updateConfig({quotaStrip:{...u,enabled:r,promptSeen:!0}}).catch(()=>{o.current=!1})};return e("div",{className:"cm-qguide",role:"dialog","aria-label":i("quotaStripGuideTitle")},e("h4",null,i("quotaStripGuideTitle")),e("p",null,i("quotaStripGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small",onClick:()=>l(!1)},i("quotaStripGuideOff")),e("button",{type:"button",className:"cm-btn small primary",onClick:()=>l(!0)},i("quotaStripGuideOn"))))}const Sa="dsh-cost-meter:balance-click-hint-seen",as=()=>{try{return window.localStorage.getItem(Sa)==="1"}catch{return!1}},ns=()=>{try{window.localStorage.setItem(Sa,"1")}catch{}};function ss(t){const s=t.useCost?t.useCost(p=>p):void 0,o=we(!1),[a,n]=L(!1),[i]=L(as),l=s?.state;if(!l)return null;const r=l.config,u=r.balance?.display==="sidebar"||r.balance?.display==="both",d=(r?.customBalances??[]).some(p=>p?.enabled===!0&&(p.display==="sidebar"||p.display==="both"))||r.customBalance?.enabled===!0&&(r.customBalance?.display==="sidebar"||r.customBalance?.display==="both"),c=Re.some(p=>{const g=r.codingPlans?.[p.id];return g?.enabled===!0&&(g.display==="sidebar"||g.display==="both")});if(a||i||r.balance?.clickHintSeen===!0||!u&&!d&&!c||!Tt(r)||r.quotaStrip?.promptSeen!==!0)return null;const f=K(W(r?.locale)),m=()=>{o.current!==!0&&(n(!0),o.current=!0,ns(),t.api.updateConfig({balance:{...r.balance??{},clickHintSeen:!0}}).catch(()=>{o.current=!1,n(!1)}))};return e("div",{className:"cm-qguide",role:"dialog","aria-label":f("balanceClickGuideTitle")},e("h4",null,f("balanceClickGuideTitle")),e("p",null,f("balanceClickGuideBody")),e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn small primary",onClick:m},f("balanceClickGuideOk"))))}function Bt(t){const{state:s,wide:o}=t,a=s.today,n=s.config,i=K(W(n?.locale)),l=n.budget??{enabled:!1,amount:100,period:"month"},r=Number(n.exchangeRate),d=(s.budgetUsed??(l.period==="day"?_(s.today,n):l.period==="all"?_(s.total,n):_(s.month,n)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),f=c>0?Math.min(999,d/c*100):null,m=f===null?"ok":f>=100?"over":f>=80?"warn":"ok";if(l.enabled===!0){const g=_(a,n),x=g*(Number.isFinite(r)&&r>0?r:1),k=c>0?Math.min(999,x/c*100):null,b=[i("budgetOf",{period:i(qe[l.period]??"periodMonth")}),i("usedOf",{used:oe(d,n),amount:oe(c,n)})+" · "+(f===null?"—":f.toFixed(1)+"%"),...n.hideTodayCost===!0?[]:[i("todayShare",{amount:Y(g,n),pct:k===null?"—":k.toFixed(1)+"%"})],i("monthTotal",{month:Y(_(s.month,n),n),total:Y(_(s.total,n),n)})].join("; ");if(t.summary===!0)return e($,{label:b,side:"right",delayMs:300},e("div",{className:"cm-simple-summary"+(m==="ok"?"":" "+m),tabIndex:0},e("span",null,i("todayBudget",{period:i(qe[l.period]??"periodMonth")})),e("span",{className:"cm-num"},Y(g,n)+" / "+oe(c,n))));const v=ya(s,n,i);return e($,{label:b,side:"right",delayMs:300},e("div",{className:"cm-bbox"+(m==="ok"?"":" "+m)+(o?"":" rail")},o?v.body:e("div",{className:"cm-bbox-rail cm-num"},v.rail)))}const p=[i("todayCostTitle"),i("callsTokens",{calls:a.calls,input:I(a.input),cache:I(a.cacheRead+a.cacheWrite),output:I(a.output)}),i("monthCost",{amount:Y(_(s.month,n),n)}),i("totalCost",{amount:Y(_(s.total,n),n)})].join("; ");return e($,{label:p,side:"right",delayMs:300},e(q,null,e("div",{className:"cm-foot"+(o?"":" cm-foot-rail")},o?e(q,null,i("today")," ",e("span",{className:"cm-num"},Y(_(a,n),n))):e(Ze,{size:16})),o?at(s,n,i):null))}function os(t){const s=t.useCost?t.useCost(E=>E):void 0;Pt(s?.state?.config?.codexQuotaEnabled===!0);let o;if(t.useProjection)try{o=t.useProjection("costUsage")}catch{o=void 0}ca(t,o);const a=s?.state,n=!!t.wide,i=we(null);if(X(()=>{const E=i.current,h=E?.parentElement;if(!E||!h)return;const U=()=>{n?h.firstElementChild!==E&&h.insertBefore(E,h.firstElementChild):h.lastElementChild!==E&&h.appendChild(E)};U();const ee=new MutationObserver(()=>{E.isConnected&&U()});return ee.observe(h,{childList:!0}),n?(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap=""):(h.style.flexDirection="column",h.style.flexWrap="nowrap",h.style.alignItems="center",h.style.gap="6px"),()=>{ee.disconnect(),n||(h.style.flexDirection="",h.style.flexWrap="",h.style.alignItems="",h.style.gap="")}},[n,a]),!a)return null;const l=a.config,r=K(W(l?.locale)),u=(l.balance?.display==="sidebar"||l.balance?.display==="both")&&l.hideOfficialBalance!==!0,c=St(a,l).length>0,f=u&&l.balance?.showProgressBar===!0&&a.balance?.status==="ok",m=c&&l.balance?.showProgressBar===!0,p=l.goQuota?.main==="weekly"||l.goQuota?.main==="monthly"?l.goQuota.main:"rolling",g=l.goQuota?.enabled!==!1&&(l.goQuota?.display==="sidebar"||l.goQuota?.display==="both")&&a.goQuota?.status==="ok"&&a.goQuota?.[p]!==null,x=Re.map(E=>E.id).filter(E=>{const h=l.codingPlans?.[E];if(h?.enabled!==!0||h.display!=="sidebar"&&h.display!=="both")return!1;const U=a.codingPlans?.[E];if(U?.status!=="ok")return!1;const ee=U.windows!==null&&typeof U.windows=="object"?U.windows:{};return Object.keys(ee).length>0}),k=x.length>0,b=$n(a,l,n,t.api),v=l.codexQuotaEnabled===!0&&J.status==="ok"&&J.windows.weekly!==null,S=(l.budget??{}).enabled===!0,w=l.sidebar!==!1&&l.hideTodayCost!==!0,A=l.sidebarModels?.enabled===!0;if(!A&&!u&&!c&&!g&&!k&&!v&&!S&&!w&&b.length===0)return null;const y=l.sidebarSimple===!0,M=!y&&n&&l.sidebarStyle==="compact",T=y&&n&&w&&S,B=[];T?B.push(e(Bt,{state:a,wide:n,summary:!0})):y&&n&&w&&B.push(e("div",{className:"cm-simple-summary"},e("span",null,r("today")),e("span",{className:"cm-num"},Y(_(a.today,l),l)))),f?B.push(e(An,{state:a,wide:n,api:t.api})):u&&B.push(e(Cn,{state:a,wide:n,api:t.api})),m?B.push(e(Mn,{state:a,wide:n,api:t.api})):c&&B.push(e(Bn,{state:a,wide:n,api:t.api}));const P=B.length;if(k&&B.push(...x.map(E=>E==="minimax"?e(Qn,{state:a,wide:n,api:t.api}):e(Yn,{id:E,state:a,wide:n,api:t.api}))),B.push(...b),v&&B.push(e(Kn,{state:a,wide:n,api:t.api})),g&&S&&n&&!y){const E=ka(a,l,r),h=ya(a,l,r),U=E.level==="over"||h.level==="over"?"over":E.level==="warn"||h.level==="warn"?"warn":"ok";B.push(e("div",{className:"cm-bbox cm-bbox-pair"+(U==="ok"?"":" "+U)},e("div",{className:"cm-bbox-section"+(E.level==="ok"?"":" "+E.level)},E.body),e("div",{className:"cm-bbox-divider"}),e("div",{className:"cm-bbox-section"+(h.level==="ok"?"":" "+h.level)},h.body)))}else g&&B.push(e(Un,{state:a,wide:n})),S&&!T&&B.push(e(Bt,{state:a,wide:n}));return!S&&w&&!(y&&n)&&B.push(e(Bt,{state:a,wide:n})),y&&n&&w&&B.push(at(a,l,r)),n||B.push(In(a,l,r)),A&&B.splice(l.sidebarModels.position==="first"?0:l.sidebarModels.position==="afterBalance"?P:B.length,0,e(ls,{key:"models",state:a,wide:n})),e("div",{ref:i,...y?{tabIndex:0,role:"region","aria-label":r("sidebarSimple")}:{},className:"cm-footer-stack"+(n?"":" rail")+(M?" compact":"")+(y?" simple":"")},...B)}const Dt={enabled:!1,period:"today",topN:5,summary:"total",position:"last",defaultOpen:!1,remember:!0,tokens:!1,shares:!0,refreshSeconds:60,dock:!1},Ca="dsh-cost-meter:models-open";function Aa(t,s,o){return Ta(t,t.config,o,s).map(a=>({...a,label:a.key==="deepseek:legacy"?a.label:Lt(a.key),cost:_(a,t.config)})).sort((a,n)=>n.cost-a.cost||n.tokens-a.tokens||a.key.localeCompare(n.key))}function ls({state:t,wide:s}){const o={...Dt,...t.config.sidebarModels},a=K(W(t.config.locale)),n=()=>{try{const b=o.remember?window.localStorage.getItem(Ca):null;if(b!==null)return b==="1"}catch{}return o.defaultOpen},[i,l]=L(n),[r,u]=L(o.period);X(()=>u(o.period),[o.period]),X(()=>l(n()),[o.defaultOpen,o.remember]);const d=Aa(t,r,a),c=d.reduce((b,v)=>b+v.cost,0),f=b=>Y(b,t.config),m=a(r==="history"?"modelStatsHistory":"modelStatsToday")+" "+f(c)+" · "+a("modelsCount",{n:d.length}),p=o.summary==="top"&&d.length?d[0].label+" "+f(d[0].cost):m,g=o.summary==="top"&&d.length?e(q,null,e("span",{className:"cm-bal-label"},d[0].label),e("span",{className:"cm-bal-amt"},f(d[0].cost))):e("span",{className:"cm-bal-label"},p),x=()=>{l(!i);try{o.remember&&window.localStorage.setItem(Ca,i?"0":"1")}catch{}};if(!s||t.config.sidebarSimple)return e("div",{className:"cm-foot cm-num"+(s?"":" cm-foot-rail"),title:p+" · "+m},s?g:e(Ze,{size:16}));const k=d.slice(0,o.topN);return d.length>o.topN&&k.push(d.slice(o.topN).reduce((b,v)=>{for(const S of["cost","input","output","cacheRead","cacheWrite"])b[S]+=v[S];return b},{key:"other",label:a("modelsOther"),cost:0,input:0,output:0,cacheRead:0,cacheWrite:0})),e("div",{className:"cm-bbox cm-model-costs"},e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(i),title:m,onClick:x},e("span",{className:"cm-caret"+(i?" open":"")}),g),i?e(q,null,e("div",{className:"cm-buttons"},["today","history"].map(b=>e("button",{key:b,type:"button",className:"cm-mstats-tab"+(r===b?" active":""),"aria-pressed":r===b,onClick:()=>u(b)},a(b==="today"?"modelStatsToday":"modelStatsHistory")))),k.length?k.map(b=>e("div",{key:b.key},e("div",{className:"cm-bbox-head"},e("span",{className:"cm-bal-label",title:b.label},b.label),e("span",{className:"cm-num cm-bal-amt"},f(b.cost))),o.shares?e("div",{className:"cm-bbox-bar",title:(c>0?b.cost/c*100:0).toFixed(1)+"%"},e("div",{className:"cm-bbox-fill",style:{width:(c>0?b.cost/c*100:0)+"%"}})):null,o.tokens?e("div",{className:"cm-mstats-note"},a("modelStatsInput")+" "+I(b.input)+" · "+a("modelStatsCache")+" "+I(b.cacheRead+b.cacheWrite)+" · "+a("modelStatsOutput")+" "+I(b.output)):null)):e("span",{className:"cm-note"},a("modelStatsEmpty"))):null)}function is({draft:t,setDraft:s,t:o}){const a={...Dt,...t?.sidebarModels},n=(l,r)=>{t&&s({...t,sidebarModels:{...a,[l]:r}})},i=(l,r)=>e("div",{className:"cm-field",key:l},e("label",null,o("models_"+l)),e("select",{className:"cm-input",value:a[l],onChange:u=>n(l,u.target.value)},r.map(([u,d])=>e("option",{key:u,value:u},o(d)))));return e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},o("modelsTitle")),["enabled","defaultOpen","remember","tokens","shares","dock"].map(l=>e("label",{key:l,className:"cm-check"},e("input",{type:"checkbox",checked:a[l],onChange:r=>n(l,r.target.checked)}),o("models_"+l))),i("period",[["today","modelStatsToday"],["history","modelStatsHistory"]]),i("summary",[["total","modelsTotal"],["top","modelsTop"]]),i("position",[["first","modelsFirst"],["afterBalance","modelsAfter"],["last","modelsLast"]]),["topN","refreshSeconds"].map(l=>e("div",{key:l,className:"cm-field"},e("label",null,o("models_"+l)),ae({value:a[l]},r=>n(l,Math.max(l==="topN"?1:10,Math.min(l==="topN"?10:60,Math.floor(r))))))))}function ot(t){return e("div",{className:"cm-card"},e("p",{className:"cm-card-title"},t.title),e("div",{className:"cm-card-value cm-num"},t.value),e("p",{className:"cm-card-sub"},t.sub))}function rs({state:t,t:s}){const o=t.externalUsage;if(!o)return null;const a=t.config,n=d=>Y(_(d,a),a),i=d=>s("callsTokens",{calls:d.calls,input:I(d.input),cache:I(d.cacheRead+d.cacheWrite),output:I(d.output)}),l=(d,c)=>({calls:d.calls+c.calls,input:d.input+c.input,output:d.output+c.output,cacheRead:d.cacheRead+c.cacheRead,cacheWrite:d.cacheWrite+c.cacheWrite,cost:_(d,a)+c.cost,apiCost:_(d,a)+c.cost}),r=(d,c)=>e("tr",{key:d},e("td",null,d),e("td",{className:"num"},String(c.calls)),e("td",{className:"num"},I(c.input)),e("td",{className:"num"},I(c.cacheRead+c.cacheWrite)),e("td",{className:"num"},I(c.output)),e("td",{className:"num"},n(c))),u=d=>e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,s("colDate")),...["colCalls","colInTok","colCacheTok","colOutTok","colCost"].map(c=>e("th",{className:"num"},s(c))))),e("tbody",null,d)));return e("section",{className:"cm-budget"},e("h3",{className:"cm-h"},s("externalUsage")),o.stale?e("p",{className:"cm-note"},s("externalStale")):null,e("div",{className:"cm-cards"},["today","month","total"].map((d,c)=>{const f=l(t[d],o.combined[d]);return e(ot,{key:d,title:s("combinedUsage")+" · "+s(["cardToday","cardMonth","cardTotal"][c]),value:n(f),sub:i(f)})})),...o.sources.map(d=>e("details",{key:d.source},e("summary",null,d.source+" · "+s("cardToday")+" "+n(d.today)+" · "+s("cardMonth")+" "+n(d.month)+" · "+i(d.today)),u(["today","month","total"].map((c,f)=>r(s(["cardToday","cardMonth","cardTotal"][f]),d[c]))),e("p",{className:"cm-note"},s("externalHistory")),u(d.history.map(c=>r(c.date,c))))))}const Oe=(t,s,o)=>e("button",{type:"button",className:"cm-collapse-h","aria-expanded":String(t),onClick:s},e("span",{className:"cm-caret"+(t?" open":"")}),e("h3",{className:"cm-h"},o));function cs(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,i]=L(!1);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,()=>i(!n),a("history"))),n?e("div",{className:"cm-collapse-body"},e(ds,{state:s,api:o})):null)}function ds(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,i]=L(null),[l,r]=L({}),[u,d]=L(()=>new Set),c=s.history??[];if(c.length===0)return e("p",{className:"cm-empty"},a("noHistory"));const f=p=>{if(n===p){i(null);return}i(p),!(l[p]!==void 0||u.has(p))&&(d(g=>{const x=new Set(g);return x.add(p),x}),o.getDaySessions(p).then(g=>r(x=>({...x,[p]:Array.isArray(g?.sessions)?g.sessions:[]}))).catch(()=>r(g=>({...g,[p]:"error"}))).finally(()=>d(g=>{const x=new Set(g);return x.delete(p),x})))},m=p=>p.map(g=>e("tr",{key:g.id},Ot(g,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(g.calls)),e("td",{className:"num"},I(g.input)),e("td",{className:"num"},I(g.cacheRead+g.cacheWrite)),e("td",{className:"num"},I(g.output)),e("td",{className:"num"},Y(_(g,s.config),s.config))));return e("div",{className:"cm-scroll"},e("p",{className:"cm-hint",style:{padding:"6px 10px 0"}},a("historyExpandHint")),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.flatMap(p=>{const g=e("tr",{key:p.date,className:"cm-row-click",onClick:()=>f(p.date)},e("td",null,(n===p.date?"▾ ":"▸ ")+p.date),e("td",{className:"num"},String(p.calls)),e("td",{className:"num"},I(p.input)),e("td",{className:"num"},I(p.cacheRead+p.cacheWrite)),e("td",{className:"num"},I(p.output)),e("td",{className:"num"},Y(_(p,s.config),s.config)));if(n!==p.date)return[g];const x=l[p.date],k=u.has(p.date)&&x===void 0?e("p",{className:"cm-empty"},a("historySessionsLoading")):x==="error"?e("p",{className:"cm-empty"},a("historySessionsError")):!Array.isArray(x)||x.length===0?e("p",{className:"cm-empty"},a("historyNoSessions")):e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,m(x)));return[g,e("tr",{key:p.date+"-sessions"},e("td",{colSpan:6},k))]}))))}function us(t){const{state:s,api:o}=t,a=K(W(s.config?.locale)),[n,i]=L(!1),[l,r]=L(100),[u,d]=L("cost-desc"),[c,f]=L(null),[m,p]=L(!1),[g,x]=L(!1),k=Ee.useRef(0),b=(A,y)=>{const[M,T]=y==="recent"?["recent","desc"]:y.split("-"),B=++k.current;p(!0),x(!1),o.getTopSessions(A,M,T).then(P=>{B===k.current&&f(Array.isArray(P?.sessions)?P.sessions:[])}).catch(()=>{B===k.current&&x(!0)}).finally(()=>{B===k.current&&p(!1)})},v=()=>{i(A=>{const y=!A;return y&&c===null&&!m&&b(l,u),y})},S=A=>{r(A),(n||c!==null)&&b(A,u)},w=A=>{d(A),(n||c!==null)&&b(l,A)};return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,v,a("sessionRankTitle"))),n?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-hint"},a("sessionRankHint")),e("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",margin:"6px 0"}},e("div",{className:"cm-field"},e("label",null,a("sessionRankSort")),e("select",{className:"cm-input",value:u,onChange:A=>w(A.target.value)},e("option",{value:"cost-desc"},a("sessionSortCostDesc")),e("option",{value:"cost-asc"},a("sessionSortCostAsc")),e("option",{value:"time-desc"},a("sessionSortTimeDesc")),e("option",{value:"time-asc"},a("sessionSortTimeAsc")),e("option",{value:"recent"},a("sessionSortRecent")))),e("div",{className:"cm-field"},e("label",null,a("sessionRankLimit")),e("select",{className:"cm-input",value:String(l),onChange:A=>S(Number(A.target.value))},e("option",{value:"50"},"50"),e("option",{value:"100"},"100"),e("option",{value:"200"},"200")))),m?e("p",{className:"cm-empty"},a("sessionRankLoading")):g?e("p",{className:"cm-empty"},a("sessionRankError")):c===null||c.length===0?e("p",{className:"cm-empty"},a("sessionRankEmpty")):e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("colDate")),e("th",null,a("colSession")),e("th",{className:"num"},a("colCalls")),e("th",{className:"num"},a("colInTok")),e("th",{className:"num"},a("colCacheTok")),e("th",{className:"num"},a("colOutTok")),e("th",{className:"num"},a("colCost")))),e("tbody",null,c.map(A=>e("tr",{key:A.date+":"+A.id},e("td",null,A.date),Ot(A,s.config?.showSessionId===!0,a),e("td",{className:"num"},String(A.calls)),e("td",{className:"num"},I(A.input)),e("td",{className:"num"},I((A.cacheRead??0)+(A.cacheWrite??0))),e("td",{className:"num"},I(A.output)),e("td",{className:"num"},Y(_(A,s.config),s.config)))))))):null)}function ms(t){const{state:s}=t,o=K(W(s.config?.locale)),a=s.today.sessions??[];if(a.length===0)return e("p",{className:"cm-empty"},o("noSessionsToday"));const n=s.config?.showSessionId===!0;return e("div",{className:"cm-scroll"},e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,o("colSession")),e("th",{className:"num"},o("colCalls")),e("th",{className:"num"},o("colInTok")),e("th",{className:"num"},o("colCacheTok")),e("th",{className:"num"},o("colOutTok")),e("th",{className:"num"},o("colCost")))),e("tbody",null,a.map(i=>e("tr",{key:i.id},Ot(i,n,o),e("td",{className:"num"},String(i.calls)),e("td",{className:"num"},I(i.input)),e("td",{className:"num"},I(i.cacheRead+i.cacheWrite)),e("td",{className:"num"},I(i.output)),e("td",{className:"num"},Y(_(i,s.config),s.config)))))))}function Ot(t,s,o){const a=typeof t.title=="string"?t.title.trim():"",n=String(t.id).slice(0,14)+"…",i=a.length>0?a:n,l=a.length>0?a+" · "+t.id:t.id;return e("td",{title:l},e("div",{className:"cm-sess-title"+(a.length===0?" cm-sess-id":"")},i),s&&a.length>0?e("div",{className:"cm-sess-id"},n):null)}const ps={CNY:{symbol:"¥",decimals:4,exchangeRate:7.2},USD:{symbol:"$",decimals:6,exchangeRate:1},EUR:{symbol:"€",decimals:6,exchangeRate:.92}};function fs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=o?.budget??i.budget,r=Number(i.exchangeRate),d=(s.budgetUsed??(l.period==="day"?_(s.today,i):l.period==="all"?_(s.total,i):_(s.month,i)))*(Number.isFinite(r)&&r>0?r:1),c=Math.max(0,Number(l.amount)||0),f=l.enabled&&c>0?Math.min(999,d/c*100):null,m=f===null?"ok":f>=100?"over":f>=80?"warn":"ok",p=(k,b)=>{o!==null&&a({...o,budget:{...o.budget??i.budget,[k]:b}})},g=l.period==="custom"?l.customStart+" → "+(l.customEnd??n("periodDay")):null,x=l.enabled&&f!==null?n("budgetStatus",{period:n(qe[l.period]??"periodMonth"),amount:oe(c,i),used:oe(d,i),pct:f.toFixed(1)})+(m==="over"?n("overLimit"):m==="warn"?n("nearLimit"):""):null;return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("budget")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:l.enabled===!0,onChange:k=>p("enabled",k.target.checked)}),e("span",null,n("enableBudget")))),l.enabled?e(q,null,e("div",{className:"cm-budget-bar"},e("div",{className:"cm-budget-fill "+(m==="ok"?"":m),style:{width:(f===null?0:Math.min(100,f))+"%"}})),e("div",{className:"cm-budget-line"+(m==="over"?" over":"")+" cm-num"},x),e("div",{className:"cm-budget-controls"},e("div",{className:"cm-field"},e("label",null,n("budgetAmountLabel")),ae({value:l.amount},k=>p("amount",k))),e("div",{className:"cm-field"},e("label",null,n("budgetPeriodLabel")),e("select",{className:"cm-input",value:l.period,onChange:k=>p("period",k.target.value)},e("option",{value:"day"},n("periodDay")),e("option",{value:"month"},n("periodMonth")),e("option",{value:"all"},n("periodAll")),e("option",{value:"custom"},n("periodCustomRange")))),l.period==="custom"?e(q,null,e("div",{className:"cm-field"},e("label",null,n("startDate")),e("input",{className:"cm-input",type:"date",value:l.customStart??"",onChange:k=>p("customStart",k.target.value===""?null:k.target.value)})),e("div",{className:"cm-field"},e("label",null,n("endDate")),e("input",{className:"cm-input",type:"date",value:l.customEnd??"",onChange:k=>p("customEnd",k.target.value===""?null:k.target.value)}))):null),g!==null?e("p",{className:"cm-hint"},n("rangeText",{range:g})):null):e("p",{className:"cm-note"},n("budgetDisabledNote")))}function bs(t){const{state:s,draft:o,setDraft:a,t:n}=t,i=s.config,l=(c,f)=>{o!==null&&a({...o,[c]:f})},r=o===null?i:{...i,...o},u=(()=>{if(r.peakEnabled!==!0)return n("peakOff");const c=Date.parse(r.peakEffectiveAt||""),f=Date.now();if(Number.isFinite(c)&&f<c)return n("peakNotEffective",{time:new Date(c).toLocaleString()});const m=r.peakWindows??[],p=Xe(f,m,r.peakHolidays);return p===null?n("offPeakActive"):p.holiday===!0?n("holidayAllOffPeak"):p.weekend===!0?n("weekendAllOffPeak"):p.inPeak?n("peakActive"):n("offPeakActive")})(),d=(r.peakWindows?.length??0)>0?n("peakSummary",{windows:r.peakWindows.map(c=>c.start+":00-"+c.end+":00").join(W(r.locale)==="zh"?"、":", "),time:r.peakEffectiveAt||n("unknown"),status:u}):n("noPeakWindows",{status:u});return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("peakPanelTitle")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakEnabled!==!1,onChange:c=>l("peakEnabled",c.target.checked)}),e("span",null,n("peakEnabledLabel")))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakNotice!==!1,onChange:c=>l("peakNotice",c.target.checked)}),e("span",null,n("peakNoticeLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakStyleLabel")),e("select",{className:"cm-input",value:o?.peakStyle==="classic"?"classic":"compact",onChange:c=>l("peakStyle",c.target.value)},e("option",{value:"compact"},n("peakStyleCompact")),e("option",{value:"classic"},n("peakStyleClassic"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertEnabled!==!1,onChange:c=>l("peakAlertEnabled",c.target.checked)}),e("span",null,n("peakAlertLabel")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertAheadLabel")),e("input",{className:"cm-input narrow",type:"number",min:"1",max:"30",step:"1",value:String(typeof o?.peakAlertAhead=="number"&&Number.isFinite(o.peakAlertAhead)&&o.peakAlertAhead>=1&&o.peakAlertAhead<=30?o.peakAlertAhead:2),onChange:c=>{const f=Number(c.target.value);Number.isInteger(f)&&f>=1&&f<=30&&l("peakAlertAhead",f)}})),e("div",{className:"cm-field"},e("label",null,n("peakAlertTargetLabel")),e("select",{className:"cm-input",value:o?.peakAlertTarget==="peak"||o?.peakAlertTarget==="offpeak"?o.peakAlertTarget:"both",onChange:c=>l("peakAlertTarget",c.target.value)},e("option",{value:"both"},n("peakAlertTargetBoth")),e("option",{value:"peak"},n("peakAlertTargetPeak")),e("option",{value:"offpeak"},n("peakAlertTargetOffPeak"))))),e("div",{className:"cm-grid"},e("div",{className:"cm-field"},e("label",null,n("peakAlertPositionLabel")),e("select",{className:"cm-input",value:o?.peakAlertPosition==="center"?"center":"corner",onChange:c=>l("peakAlertPosition",c.target.value)},e("option",{value:"corner"},n("peakAlertPositionCorner")),e("option",{value:"center"},n("peakAlertPositionCenter")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:o?.peakAlertWebNotify===!0,onChange:c=>{l("peakAlertWebNotify",c.target.checked),c.target.checked&&window.Notification&&Notification.permission==="default"&&Promise.resolve(Notification.requestPermission()).catch(()=>{})}}),e("span",null,n("peakAlertWebNotifyLabel"))),e("p",{className:"cm-hint"},n("peakAlertWebNotifyHint")))),e("div",{className:"cm-field"},e("label",null,n("peakAlertPreviewLabel")),e("div",{className:"cm-row"},e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("peak")},n("peakAlertPreviewPeak")),e("button",{className:"cm-btn",onClick:()=>window.cmPeakAlertPreview?.("offpeak")},n("peakAlertPreviewOffPeak")))),e("div",{className:"cm-peak-preview"},o?.peakEnabled!==!1&&o?.peakNotice!==!1?at(s,r,n):e("p",{className:"cm-hint"},n("peakNoticeHiddenHint"))),e("p",{className:"cm-hint"},d),e("div",{className:"cm-field"},e("label",null,n("peakHolidaysLabel")),e("input",{className:"cm-input",defaultValue:(r.peakHolidays??[]).join(", "),onBlur:c=>l("peakHolidays",c.target.value.split(/[,,\s]+/).filter(Boolean))})),e("p",{className:"cm-hint"},n("weekendRuleNote")))}function ae(t,s){const o=t.value;return e("input",{className:"cm-input narrow",type:"number",step:"any",min:"0",value:typeof o=="number"?String(o):"",onChange:a=>{const n=a.target.value;if(n===""){if(t.emptyMode==="clear"){s(null);return}if(t.emptyMode==="ignore")return;s(0);return}const i=Number(n);Number.isFinite(i)&&i>=0&&s(i)}})}function Rt(t){const{modelId:s,entry:o,isDefault:a,draft:n,setDraft:i,t:l}=t,r=Ve(o),u=m=>{const p={...Ve(m)};if(Array.isArray(m.rateHistory)){const g=m.rateHistory.filter(x=>Date.parse(x.before)<=Date.now());g.length>0?p.rateHistory=g:delete p.rateHistory}return p},d=(m,p,g)=>{if(g===null){if(a){const M=u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0}),T={...M[m]??{}};delete T[p];const B={...M};Object.keys(T).length>0?B[m]=T:delete B[m],i({...n,prices:{...n.prices,default:B}});return}const S={...n.prices.models},w=u(S[s]??{cacheHit:0,cacheMiss:0,output:0}),A={...w[m]??{}};delete A[p];const y={...w};Object.keys(A).length>0?y[m]=A:delete y[m],S[s]=y,i({...n,prices:{...n.prices,models:S}});return}const x=Math.max(0,g);if(a){let w={...u(n.prices.default??{cacheHit:0,cacheMiss:0,output:0})};if(m==="base")w[p]=x;else{const A={...w[m]??{},[p]:x};w={...w,[m]:A}}i({...n,prices:{...n.prices,default:w}});return}const k={...n.prices.models},b=u(k[s]??{cacheHit:0,cacheMiss:0,output:0});let v={...b};if(m==="base")v[p]=x;else{const S={...b[m]??{},[p]:x};v={...b,[m]:S}}k[s]=v,i({...n,prices:{...n.prices,models:k}})},c=()=>{const m={...n.prices.models};delete m[s],i({...n,prices:{...n.prices,models:m}})},f=(m,p)=>{const g=p==="base"?r:r[p]??null,x=p==="base"?"ignore":"clear";return e("div",{className:"cm-price-row",key:p},e("span",null,m),ae({value:g?.cacheHit??null,emptyMode:x},k=>d(p,"cacheHit",k)),ae({value:g?.cacheMiss??null,emptyMode:x},k=>d(p,"cacheMiss",k)),ae({value:g?.output??null,emptyMode:x},k=>d(p,"output",k)))};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},s),e(q,null,r?.legacy===!0?e("span",{className:"cm-price-legacy"},l("legacyModel")):null,a?e("span",{className:"cm-price-legacy"},l("defaultFallback")):null,a?null:e("button",{className:"cm-btn small danger",onClick:c},l("remove")))),e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatCached")),e("span",null,l("flatInput")),e("span",null,l("flatOutput"))),f(l("tierBase"),"base"),f(l("tierOffPeak"),"offPeak"),f(l("tierPeak"),"peak"),Array.isArray(o?.rateHistory)&&o.rateHistory.length>0?e("p",{className:"cm-note"},l("datedPriceNote")):null)}const Pa={deepseek:"DeepSeek",openai:"OpenAI",anthropic:"Anthropic",google:"Google Gemini",moonshot:"Moonshot (Kimi)","z-ai":"Z.ai / 智谱",xai:"xAI",alibaba:"阿里云百炼",minimax:"MiniMax",tencent:"腾讯混元",xiaomi:"小米",upstage:"Upstage",nvidia:"NVIDIA",mistral:"Mistral",meta:"Meta",meituan:"美团 LongCat","opencode-go":"OpenCode Go"};function gs(t,s,o="USD"){if(t=Ve(t),t===null||typeof t!="object")return"";if(t.unpriced===!0)return s("catalogUnpriced");const a=i=>(o==="CNY"?"¥":"$")+String(i),n=t.peak!==null&&typeof t.peak=="object"?t.peak:null;return n!==null?a(t.cacheMiss)+"/"+a(n.cacheMiss)+" in · "+a(t.output)+"/"+a(n.output)+" out":a(t.cacheMiss??t.input??0)+" in · "+a(t.output??0)+" out"}function hs(t){const{state:s,draft:o,setDraft:a,t:n}=t,[i,l]=L(!1),[r,u]=L({}),d=s.priceCatalog;if(d===null||typeof d!="object")return null;const c=o?.prices??s.config.prices,f=o?.priceTableDisplay??s.config.priceTableDisplay??{},m=(y,M)=>{const T=f[y+":"+M];return typeof T=="boolean"?T:y==="deepseek"},p=(y,M,T)=>{o!==null&&a({...o,priceTableDisplay:{...f,[y+":"+M]:T}})},g=(y,M)=>y==="deepseek"?c.models?.[M]!==void 0:c.providers?.[y]?.models?.[M]!==void 0,x=(y,M,T)=>{if(o===null)return;const B=JSON.parse(JSON.stringify(T));if(y==="deepseek"){a({...o,prices:{...o.prices,models:{...o.prices.models,[M]:B}}});return}const P={...o.prices.providers??{}},E=P[y]??{};P[y]={...E,models:{...E.models??{},[M]:B}},a({...o,prices:{...o.prices,providers:P}})},k=(y,M)=>{if(o===null)return;if(y==="deepseek"){const P={...o.prices.models};delete P[M],a({...o,prices:{...o.prices,models:P}});return}const T={...o.prices.providers??{}},B=T[y];if(B!==void 0&&B.models!==void 0){const P={...B.models};delete P[M],T[y]={...B,models:P},a({...o,prices:{...o.prices,providers:T}})}},b=Object.keys(d).sort((y,M)=>y==="deepseek"?-1:M==="deepseek"?1:y.localeCompare(M)),v=y=>Object.values(d[y]).reduce((M,T)=>M+Object.keys(T).length,0),S=new Set(Object.values(d.deepseek??{}).flatMap(y=>Object.keys(y))),w=Object.keys(c.models??{}).filter(y=>!S.has(y)).sort(),A=(y,M,T)=>{const B=g(y,M),P=m(y,M),E=B?e("label",{className:"cm-check cm-vendor-display",title:n("catalogDisplayHint")},e("input",{type:"checkbox",checked:P,onChange:h=>p(y,M,h.target.checked)}),e("span",null,n("catalogDisplayLabel"))):null;if(B&&!P&&o!==null){const h=y==="deepseek"?e(Rt,{key:M,modelId:M,entry:c.models[M],isDefault:!1,draft:o,setDraft:a,t:n}):e(Da,{key:M,provider:y,modelId:M,entry:c.providers?.[y]?.models?.[M],draft:o,setDraft:a,t:n});return e("div",{key:M,className:"cm-catalog-mounted"},E,h)}return e("div",{key:M,className:"cm-catalog-row"},e("span",{className:"cm-catalog-id"},M),e("span",{className:"cm-catalog-price"},gs(T,n,y==="deepseek"?c.currency:"USD")),B?e("span",{className:"cm-catalog-tag"},n("mountedTag")):null,E,e("button",{className:"cm-btn small",disabled:!B&&T?.unpriced===!0,onClick:()=>B?k(y,M):x(y,M,T)},n(B?"unmountBtn":"mountBtn")))};return e("div",{className:"cm-budget",style:{marginTop:"8px"}},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},n("catalogTitle")),e("button",{className:"cm-toggle-btn",onClick:()=>l(y=>!y)},n(i?"catalogCollapse":"catalogOpen"))),i?e(q,null,e("p",{className:"cm-note"},n("catalogNote")),b.map(y=>{const M=r[y]===!0;return e("div",{key:y},e("div",{className:"cm-catalog-vendor cm-vendor-toggle",onClick:()=>u(T=>({...T,[y]:!M}))},e("span",null,(M?"▾ ":"▸ ")+(Pa[y]??y)+" · "+v(y))),M?e(q,null,y==="deepseek"?e("p",{className:"cm-hint"},n("catalogDeepseekNote")):null,Object.keys(d[y]).sort().map(T=>e("div",{key:T},e("div",{className:"cm-catalog-family"},T),Object.keys(d[y][T]).sort().map(B=>A(y,B,d[y][T][B])))),y==="deepseek"&&w.length>0?e("div",null,e("div",{className:"cm-catalog-family"},n("catalogCustomModels")),w.map(T=>A("deepseek",T,null))):null):null)})):null)}const Ma=t=>t==="zen"?"go":t,Lt=t=>{const s=t.indexOf(":");return s<=0?t:Ma(t.slice(0,s).toLowerCase())+t.slice(s)};function Ta(t,s,o,a){const n=["input","output","cacheRead","cacheWrite","reasoning","cost","calls"],i=d=>Number.isFinite(Number(d))&&Number(d)>0?Number(d):0,l=(d,c,f)=>{if(!f||typeof f!="object")return;const m=d[c]??(d[c]=Object.fromEntries([...n,"apiCost"].map(g=>[g,0])));for(const g of n)m[g]+=i(f[g]);const p=c.indexOf(":");m.apiCost+=i(f.apiCost??(Ue(p>0?c.slice(0,p):"deepseek",p>0?c.slice(p+1):c,s)==="plan"?0:f.cost))},r=d=>{if(!d||typeof d!="object")return{};if(d.byProviderModel&&Object.keys(d.byProviderModel).length)return d.byProviderModel;if(d.byModel&&Object.keys(d.byModel).length)return Object.fromEntries(Object.entries(d.byModel).map(([f,m])=>[f.includes(":")?f:"deepseek:"+f,m]));const c={};for(const f of Array.isArray(d.sessions)?d.sessions:[])if(!(!f||typeof f!="object"))if(f.byProviderModel&&Object.keys(f.byProviderModel).length)for(const[m,p]of Object.entries(f.byProviderModel))l(c,m,p);else l(c,(f.provider||"deepseek")+":"+(f.model||"unknown"),f);return Object.keys(c).length?c:n.some(f=>i(d[f])>0)?{"deepseek:legacy":d}:{}};return(d=>{const c={},f=m=>{for(const[p,g]of Object.entries(m??{}))l(c,p,g)};if(d==="today")f(r(t.today));else{const m=Date.parse((t.meta?.dayKey||new Date().toISOString().slice(0,10))+"T00:00:00Z");for(const p of t.history??[]){const g=Date.parse(p.date+"T00:00:00Z");g<=m&&g>=m-76896e5&&f(r(p))}}return Object.entries(c).map(([m,p])=>{const g=m.indexOf(":"),x=(g>0?m.slice(0,g):"deepseek").toLowerCase(),k=g>0?m.slice(g+1):m,b=p.input+p.output+p.cacheRead+p.cacheWrite+p.reasoning,v=p.cacheRead+p.input;return{label:m==="deepseek:legacy"?o("modelStatsLegacy"):x==="deepseek"||x===""?k:Ma(x)+":"+k,key:m,...p,tokens:b,cls:Ue(x,k,s),hitRate:v>0?p.cacheRead/v:null,cacheUnreported:dn(p),blended:b>0&&p.cost>0?p.cost/b*1e6:null,perUsd:p.cost>0?b/p.cost:null}}).filter(m=>m.tokens>0||m.cost>0)})(a).sort((d,c)=>c.cost-d.cost||c.tokens-d.tokens)}function ys(t){const{state:s,config:o,t:a,initialTab:n}=t,[i,l]=L(n==="history"?"history":"today"),[r,u]=L(!1),d=Ta(s,o,a,i),c=b=>(Math.max(0,Math.min(1,b))*100).toFixed(1)+"%",f=d.reduce((b,v)=>Math.max(b,v.cost),0),m=d.reduce((b,v)=>Math.max(b,v.tokens),0),p=d.reduce((b,v)=>Math.max(b,v.perUsd??0),0),g=(b,v)=>e("button",{className:"cm-mstats-tab"+(i===b?" active":""),onClick:()=>l(b)},v),x=b=>b.cls==="plan"?e("span",{className:"cm-plan-tag",title:a("billingClassLabel")},a("billingClassPlan")):null,k=(b,v,S,w,A)=>e("div",{className:"cm-mstats-row"},e("span",{className:"cm-mstats-name",title:b},b,A??null),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar "+S,style:{width:c(v)}})),e("span",{className:"cm-mstats-val"},w));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(r,()=>u(!r),a("modelStatsTitle"))),r?e("div",{className:"cm-collapse-body"},e("div",{className:"cm-mstats-tabs"},g("today",a("modelStatsToday")),g("history",a("modelStatsHistory"))),d.length===0?e("p",{className:"cm-note"},a("modelStatsEmpty")):e(q,null,e("div",{className:"cm-mstats-h"},a("modelStatsCostH")),d.map(b=>e(q,{key:"c:"+b.label},k(b.label,f>0?b.cost/f:0,"cost",Y(b.cost,o),e(q,null,x(b),b.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null)))),e("div",{className:"cm-mstats-h"},a("modelStatsTokensH")),e("div",{className:"cm-mstats-legend"},e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"var(--dsw-alias-state-business-primary)"}}),a("modelStatsInput")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#ff9800"}}),a("modelStatsCache")),e("span",null,e("span",{className:"cm-mstats-dot",style:{background:"#34a853"}}),a("modelStatsOutput"))),[...d].sort((b,v)=>v.tokens-b.tokens).map(b=>e("div",{className:"cm-mstats-row",key:"t:"+b.label},e("span",{className:"cm-mstats-name",title:b.label},b.label),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-seg in",style:{width:c(m>0?b.input/m:0)}}),e("div",{className:"cm-mstats-seg cache",style:{width:c(m>0?(b.cacheRead+b.cacheWrite)/m:0)}}),e("div",{className:"cm-mstats-seg out",style:{width:c(m>0?(b.output+b.reasoning)/m:0)}})),e("span",{className:"cm-mstats-val"},I(b.tokens)))),e("div",{className:"cm-mstats-h"},a("modelStatsHitH")),[...d].sort((b,v)=>(v.hitRate??-1)-(b.hitRate??-1)).map(b=>e(q,{key:"h:"+b.label},k(b.label,b.hitRate??0,"hit",b.cacheUnreported?a("modelStatsHitUnreported"):b.hitRate===null?"—":(b.hitRate*100).toFixed(1)+"%",b.cacheUnreported?e("span",{className:"cm-plan-tag",title:a("modelStatsHitUnreportedTip")},"⚠"):null))),e("div",{className:"cm-mstats-h"},a("modelStatsValueH")),[...d].sort((b,v)=>(v.perUsd??-1)-(b.perUsd??-1)).map(b=>e(q,{key:"v:"+b.label},k(b.label,p>0?(b.perUsd??0)/p:0,"value",b.perUsd===null?"—":I(b.perUsd)+" tok/$"+(b.blended!==null?" · "+a("modelStatsBlended",{price:"$"+b.blended.toFixed(2)}):"")))),e("p",{className:"cm-mstats-note"},a("modelStatsNote")))):null)}function ks(t,s){return t==="fiveHour"?s==="en"?"5-hour":"5 小时":t==="weekly"?s==="en"?"This week":"本周":t==="monthly"?s==="en"?"This month":"本月":t==="daily"?s==="en"?"Today":"当日":t}function ws(t,s){if(t==="go")return"OpenCode Go";const o=Re.find(a=>a.id===t);return o!==void 0?s(o.labelKey):t}const Ba=["fiveHour","weekly","monthly","daily"];function xs(t,s){const o=new Map,a=n=>{const i=new Date(n),l=r=>String(r).padStart(2,"0");if(s==="monthly")return i.getFullYear()+"-"+l(i.getMonth()+1);if(s==="weekly"){const r=new Date(i.getFullYear(),i.getMonth(),i.getDate()-(i.getDay()+6)%7);return r.getFullYear()+"-"+l(r.getMonth()+1)+"-"+l(r.getDate())}return i.getFullYear()+"-"+l(i.getMonth()+1)+"-"+l(i.getDate())};for(const n of Object.values(t??{}))for(const i of n??[]){if(i===null||typeof i!="object"||!(i.tokens>0)&&!(i.cost>0))continue;const l=a(Number(i.t1)||Number(i.t0)),r=o.get(l)??{key:l,tokens:0,cost:0,pct:0,intervals:0};r.tokens+=Number(i.tokens)||0,r.cost+=Number(i.cost)||0,r.pct+=Number(i.pct)||0,r.intervals+=1,o.set(l,r)}return[...o.values()].map(n=>({...n,per1Tokens:n.pct>0?n.tokens/n.pct:null,fullTokens:n.pct>0?n.tokens/n.pct*100:null})).sort((n,i)=>n.key<i.key?-1:n.key>i.key?1:0)}function vs(t){const{state:s,config:o,t:a}=t,[n,i]=L(!1),[l,r]=L("daily"),u=W(o?.locale),d=s?.planStats,c=d!=null&&typeof d.providers=="object"?d.providers:{},f=Object.keys(c).sort(),m=y=>Y(Number(y)||0,o??s?.config),p=y=>y.method==="none"||y.per1Tokens===null?"—":I(y.per1Tokens)+" tok · "+m(y.per1Cost),g=y=>y.method==="none"||y.fullTokens===null?"—":I(y.fullTokens)+" tok · "+m(y.fullCost),x=y=>y.method==="sample"?a("planStatsMethodSample"):y.method==="live"?a("planStatsMethodLive"):a("planStatsMethodNone"),k=y=>{let M=x(y);return y.method==="sample"&&Number(y.sampleAt)>0&&(M=a("planStatsMethodSampleAt",{method:M,time:new Date(Number(y.sampleAt)).toLocaleString(u==="en"?"en-US":"zh-CN")})),(y.method==="sample"||y.method==="live")&&y.confidence==="low"&&(M+=" · "+a("planStatsConfidenceLow")),M},b=([y,M,T])=>e("tr",{key:M+":"+y},e("td",null,ks(y,u)),e("td",{className:"num"},Math.round(T.percent*10)/10+"%"),e("td",{className:"num"},I(T.localTokens)+" tok · "+m(T.localCost)),e("td",{className:"num"},p(T)),e("td",{className:"num"},g(T)),e("td",{className:"num cm-plan-reset"},T.resetsAt.length>0?a("planStatsResets",{time:new Date(T.resetsAt).toLocaleString(u==="en"?"en-US":"zh-CN")}):"—"),e("td",{className:"cm-plan-method"},k(T))),v=n?f.flatMap(y=>Object.entries(c[y]?.intervals??{})).map(([y,M])=>({winKey:y,list:M})):[],S=xs(Object.fromEntries(v.map(y=>[y.winKey,y.list])),l),w=S.reduce((y,M)=>Math.max(y,M.fullTokens??0),0),A=(y,M)=>e("button",{key:y,className:"cm-mstats-tab"+(l===y?" active":""),onClick:()=>r(y)},M);return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},Oe(n,()=>i(!n),a("planStatsTitle"))),n?e("div",{className:"cm-collapse-body"},f.length===0?e("p",{className:"cm-empty"},a("planStatsEmpty")):e(q,null,f.map(y=>{const M=c[y]?.windows??{},T=[...Ba.filter(B=>M[B]!==void 0).map(B=>[B,y,M[B]]),...Object.keys(M).filter(B=>!Ba.includes(B)).map(B=>[B,y,M[B]])];return e("div",{key:y,className:"cm-plan-provider"},e("div",{className:"cm-plan-provider-name"},ws(y,a),e("span",{className:"cm-plan-updated"},(()=>{const B=Number(c[y]?.generatedAt)||Number(d?.generatedAt)||0;return B>0?new Date(B).toLocaleTimeString(u==="en"?"en-US":"zh-CN"):""})())),e("table",{className:"cm-table"},e("thead",null,e("tr",null,e("th",null,a("planStatsWindow")),e("th",{className:"num"},a("planStatsPercent")),e("th",null,a("planStatsLocal")),e("th",null,a("planStatsPer1")),e("th",null,a("planStatsFull")),e("th",null,""),e("th",null,""))),e("tbody",null,T.map(b))))}),e("div",{className:"cm-mstats-h",style:{marginTop:"10px"}},a("planStatsCurveTitle")),e("div",{className:"cm-mstats-tabs"},A("daily",a("planStatsDaily")),A("weekly",a("planStatsWeekly")),A("monthly",a("planStatsMonthly"))),S.length===0?e("p",{className:"cm-note"},a("planStatsCurveEmpty")):e(q,null,[...S].reverse().map(y=>e("div",{className:"cm-mstats-row",key:y.key},e("span",{className:"cm-mstats-name"},y.key),e("div",{className:"cm-mstats-barbg"},e("div",{className:"cm-mstats-bar value",style:{width:(w>0?(y.fullTokens??0)/w*100:0).toFixed(1)+"%"}})),e($,{label:a("planStatsBarTip",{date:y.key,full:y.fullTokens===null?"—":I(y.fullTokens),per1:y.per1Tokens===null?"—":I(y.per1Tokens),tokens:I(y.tokens),cost:m(y.cost),intervals:y.intervals}),side:"top",delayMs:200},e("span",{className:"cm-mstats-val"},y.fullTokens===null?"—":I(y.fullTokens)))))),e("p",{className:"cm-note"},a("planStatsNote")))):null)}function Da(t){const{provider:s,modelId:o,entry:a,draft:n,setDraft:i,t:l}=t,r=c=>{const f={...n.prices.providers??{}},m=f[s]??{};f[s]={...m,models:c},i({...n,prices:{...n.prices,providers:f}})},u=(c,f)=>{if(n===null)return;const m={...(n.prices.providers??{})[s]?.models??{}};m[o]={...m[o]??{},[c]:Math.max(0,f)},r(m)},d=()=>{if(n===null)return;const c={...(n.prices.providers??{})[s]?.models??{}};delete c[o],r(c)};return e("div",{className:"cm-price-card"},e("div",{className:"cm-price-head"},e("span",{className:"cm-price-name"},o),e(q,null,a?.unpriced===!0?e("span",{className:"cm-price-legacy"},l("catalogUnpriced")):null,e("button",{className:"cm-btn small danger",onClick:d},l("unmountBtn")))),a?.unpriced===!0?null:e(q,null,e("div",{className:"cm-price-row"},e("span",null,""),e("span",null,l("flatInput")),e("span",null,l("flatCached")),e("span",null,l("flatOutput"))),e("div",{className:"cm-price-row"},e("span",null,"USD"),ae({value:a?.input??null,emptyMode:"ignore"},c=>u("input",c)),ae({value:a?.cachedInput??null,emptyMode:"ignore"},c=>u("cachedInput",c)),ae({value:a?.output??null,emptyMode:"ignore"},c=>u("output",c)))))}const ze=t=>[e("option",{key:"sidebar",value:"sidebar"},t("balanceSidebar")),e("option",{key:"settings",value:"settings"},t("balanceSettings")),e("option",{key:"both",value:"both"},t("balanceBoth")),e("option",{key:"off",value:"off"},t("off"))],Et=t=>t!=null?e("div",{className:"cm-msg "+t.kind},t.text):null;function Ns(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),[u,d]=L(null),c=s.balance,f=s.config,m=s.reconcile,p=(n?.balance??f.balance??{}).reconcile!==!1,g=v=>{n===null||typeof i!="function"||i({...n,balance:{...n.balance??f.balance??{},reconcile:v.target.checked}})},x=async()=>{if(!l){r(!0),d(null);try{const v=await o.refreshBalance();d({kind:v.ok?"ok":"err",text:v.message})}catch(v){d({kind:"err",text:a("balanceRefreshFailed",{message:v?.message??String(v)})})}finally{r(!1)}}},k=v=>xe(v,f,c?.currency),b=c.status==="ok"?e("div",{className:"cm-bal-line"},e("span",null,a("balanceLine",{total:k(c.totalBalance),granted:k(c.grantedBalance),toppedUp:k(c.toppedUpBalance),time:c.fetchedAt>0?new Date(c.fetchedAt).toLocaleTimeString():"—"}))):c.status==="error"?e("div",{className:"cm-bal-line err"},a("balanceQueryFailedHint",{message:c.message||a("unknownError")})):e("div",{className:"cm-bal-line"},a("balanceNotQueried"));return e("div",{className:"cm-budget"},e("div",{className:"cm-budget-head"},e("h3",{className:"cm-h"},a("accountBalance")),e("button",{className:"cm-btn small",onClick:x,disabled:l},a(l?"refreshing":"refreshBalance"))),b,m!==void 0&&m.ok===!1?e("div",{className:"cm-bal-line warn"},"⚠ "+m.message):null,e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:p,onChange:g}),a("reconcileLabel")),Et(u))}function lt(t){const{name:s,enabled:o,saved:a,busy:n,open:i,statusNode:l,configNode:r,errorMsg:u,onToggle:d,onRefresh:c,onRemove:f,onToggleOpen:m,t:p}=t,g=r!=null;return e("div",{className:"cm-budget cm-quota-card"},e("div",{className:"cm-budget-head"},e("label",{className:"cm-check"},e("input",{type:"checkbox","aria-label":p("enable")+": "+s,checked:o===!0,onChange:x=>d(x.target.checked)})),e("div",{className:"cm-quota-name"},g?Oe(i===!0,m,s):e("h3",{className:"cm-h"},s)),f?e("button",{className:"cm-btn small",onClick:f},p("quotaRemove")):null,e("button",{className:"cm-btn small",onClick:c,disabled:n===!0||o!==!0||a?.enabled!==!0||a.display==="off",title:o!==!0?p("quotaEnableFirst"):a?.enabled!==!0||a.display==="off"?p("quotaRefreshReady"):p("refresh")},p(n===!0?"refreshing":"refresh"))),l,g&&i===!0?e("div",{className:"cm-collapse-body"},r):null,u!=null?e("div",{className:"cm-msg "+u.kind},u.text):null)}function it(t,s){const[o,a]=L(!1),[n,i]=L(null),l=we(!1);return[o,n,async()=>{if(!l.current){l.current=!0,a(!0),i(null);try{const u=await s();i({kind:u.ok?"ok":"err",text:u.message})}catch(u){i({kind:"err",text:t("syncFailed",{message:u?.message??String(u)})})}finally{l.current=!1,a(!1)}}}]}const Ss=t=>{const s=t.filter(a=>a.enabled===!0),o=t.filter(a=>a.enabled!==!0);return[...s,...o]},Oa=(t,s,o,a,n,i=s)=>{if(typeof o?.percent!="number")return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("span",{className:"cm-go-num"},typeof o?.text=="string"?o.text:"—"));const l=Math.max(0,Math.min(100,Number(o.percent)||0)),r=ue(l,a),u=typeof o.resetsAt=="string"&&o.resetsAt.length>0?t("goResetAt",{time:new Date(o.resetsAt).toLocaleString()}):"";return e("div",{key:i,className:"cm-go-row"+(n?" main":"")},e("span",{className:"cm-go-label"},s),e("div",{className:"cm-go-bar"},e("div",{className:"cm-go-fill",style:{width:r.width+"%"}})),e("span",{className:"cm-go-num"},r.label===null?"—":t("goQuotaPercent",{percent:String(Math.round(r.label))})),u?e("span",{className:"cm-go-reset"},u):null)};function Cs(t){const{state:s,api:o,t:a,entry:n,index:i,canRemove:l,onPatch:r,onRemove:u}=t,d=n.adapter==="aliyun",[c,f]=L(!1),m=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[p,g]=L(m),[x,k]=L(()=>(n.allowedHosts??[]).join(", ")),[b,v]=L({}),S=we(!1),w=s.config,y=(Array.isArray(s.customBalances)?s.customBalances:[]).find(R=>R.index===i)??null,M=n.enabled===!0,T=()=>{f(R=>!R)};X(()=>{c&&!S.current&&(g(m()),k((n.allowedHosts??[]).join(", ")),v({})),S.current=c},[c]);const B=(R,V)=>r({[R]:V}),P=(R,V)=>r({request:{...n.request??{},[R]:V}}),E=d?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(R=>typeof R=="string"?[...R.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(V=>V[1]):[]))],h=(R,V)=>{g(N=>({...N,[R]:V}));try{const N=R==="body",H=N&&!V.trim()?void 0:JSON.parse(V);if(!N&&(H===null||typeof H!="object"||Array.isArray(H)))throw new Error("invalid");if(R==="headers"&&Object.values(H).some(Q=>typeof Q!="string"))throw new Error("invalid");v(Q=>({...Q,[R]:""})),R==="extract"?B(R,H):P(R,N?H===void 0?void 0:V:H)}catch{v(N=>({...N,[R]:a("customBalanceInvalidJson")}))}},U=(R,V,N,H)=>!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(V)),H&&e("span",{className:"cm-hint"},a(H)),e("textarea",{className:"cm-input",rows:N,value:p[R],onChange:Q=>h(R,Q.target.value)}),b[R]?e("span",{className:"cm-hint err"},b[R]):null),ee=R=>{k(R);const V=R.split(/[\s,;]+/).map(N=>N.trim()).filter(N=>N.length>0);B("allowedHosts",V)},[ye,ve,D]=it(a,()=>(w.customBalances??[])[i]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):o.refreshCustomBalance(i)),O=y!==null&&y.status==="ok"?e(q,null,w.balance?.showProgressBar===!0?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(xt,{segments:wt(s,w,y,n),direction:te(w,"balance")}),e("div",{className:"cm-bal-line"},Nt(y,w,a,s,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:Qe(y.remaining,w,y,n)}))):y!==null&&y.status==="error"?e("div",{className:"cm-bal-line err"},y.message||a("unknownError")):e("div",{className:"cm-bal-line"},y?.message||a("balanceNotQueried")),G=e(q,null,e("p",{className:"cm-note"},a(d?"aliyunBalanceNote":"customBalanceConfigNote")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:je(w,y,n)!=="USD",onChange:R=>B("convertToDisplayCurrency",R.target.checked)}),a("customBalanceConvert")),e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([R,V])=>e("div",{key:R,className:"cm-field"},e("label",null,a(V)),e("input",{className:"cm-input",value:n[R]??"",onChange:N=>B(R,N.target.value)}))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:R=>B("unit",R.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:R=>B("display",R.target.value)},...ze(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),ae({value:n.refreshMinutes??15},R=>B("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(R)))))),!d&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:R=>P("method",R.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"https://example.com/key/info",onChange:R=>P("url",R.target.value)})),U("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&U("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceCredentialsTitle")),E.length>0?e(q,null,!d&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),E.map(R=>e(De,{key:"cb-var-"+R,target:"customVar:"+R,configured:(s.customVarStatus?.[R]?.configured??!1)===!0,source:s.customVarStatus?.[R]?.source??"",t:a,api:o,placeholder:"{{"+R+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!d&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:x,placeholder:"api.example.com, relay.example.org",onChange:R=>ee(R.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),U("extract","customBalanceExtract",8)));return e(lt,{name:`#${i+1} · `+(vt(n,W(w?.locale))||a("customBalanceTitle")),enabled:M,saved:JSON.stringify(n)===JSON.stringify(w.customBalances?.[i])?w.customBalances[i]:null,busy:ye,open:c,statusNode:O,configNode:G,errorMsg:ve,onToggle:R=>B("enabled",R),onRefresh:D,onRemove:l?u:null,onToggleOpen:T,t:a})}function Ra({config:t,draft:s,setDraft:o,t:a,api:n}){const i=s?.goQuota??t.goQuota,l=(r,u)=>{s&&o({...s,goQuota:{...i,[r]:u}})};return e(q,null,[["display","goQuotaDisplayLabel"],["main","goMainLabel"]].map(([r,u])=>e("div",{key:r,className:"cm-field"},e("label",null,a(u)),e("select",{className:"cm-input",value:i[r],onChange:d=>l(r,d.target.value)},r==="display"?ze(a):["rolling","weekly","monthly"].map((d,c)=>e("option",{key:d,value:d},a(["goWindowRolling","goWindowWeekly","goWindowMonthly"][c])))))),e("div",{className:"cm-field"},e("label",null,a("goQuotaRefreshIntervalLabel")),ae({value:i.refreshMinutes},r=>l("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(r)))))),e("label",null,a("goQuotaKeyLabel")),e(De,{target:"goQuota",configured:t.goQuota?.keyConfigured===!0,source:t.goQuota?.keySource,t:a,api:n,placeholder:"sk-…"}))}function As(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,[l,r]=L(!1),u=s.goQuota,d=s.config,c=n?.goQuota?.enabled??d.goQuota?.enabled??!0,f=(w,A)=>{n!==null&&i({...n,goQuota:{...n.goQuota??d.goQuota,[w]:A}})},[m,p,g]=it(a,()=>o.refreshGoQuota()),x=d.goQuota?.main==="weekly"||d.goQuota?.main==="monthly"?d.goQuota.main:"rolling",k=[x,...["rolling","weekly","monthly"].filter(w=>w!==x)],b=w=>w==="rolling"?"goWindowRolling":w==="weekly"?"goWindowWeekly":"goWindowMonthly",v=w=>w==="rolling"?u.rolling:w==="weekly"?u.weekly:u.monthly,S=c===!1?e("p",{className:"cm-note"},a("goQuotaDisabledNote")):u.status==="ok"?e("div",{className:"cm-go-list"},k.map(w=>Oa(a,a(b(w)),v(w),te(d,"go"),w===x)),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:u.fetchedAt>0?new Date(u.fetchedAt).toLocaleTimeString():"—"}))):u.status==="error"?e("div",{className:"cm-bal-line err"},u.message||a("unknownError")):u.status==="off"&&u.message?e("p",{className:"cm-note"},u.message):e("div",{className:"cm-bal-line"},a("goQuotaNotQueried"));return e(lt,{name:a("goQuotaTitle"),enabled:c,saved:d.goQuota,busy:m,open:l,statusNode:S,errorMsg:p,configNode:e(Ra,{config:d,draft:n,setDraft:i,t:a,api:o}),onToggleOpen:()=>r(w=>!w),onToggle:w=>f("enabled",w),onRefresh:g,t:a})}const Ps=(t,s)=>{if(typeof t?.keyVar=="string"&&t.keyVar.length>0)return t.keyVar;const a="CLIPROXYAPI_MANAGEMENT_KEY_"+(String(t?.id??"").toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"GATEWAY");return Object.keys(s??{}).find(n=>n===a||n.startsWith(a+"_"))??a};function Ms(t){const{state:s,api:o,t:a,draft:n,setDraft:i,index:l}=t,r=s.config,d=(n??r).gatewayQuotas?.sources??[],c=d[l]??{},m=(Array.isArray(s.gatewayQuotas)?s.gatewayQuotas:[]).find(P=>P.id===c.id)??{id:c.id,status:"off",accounts:[],unsupportedProviders:[]},p=Ps(c,s.customVarStatus),[g,x]=L(!1),[k,b,v]=it(a,()=>o.refreshGatewayQuota(c.id)),S=P=>{n!==null&&i({...n,gatewayQuotas:{...n.gatewayQuotas??r.gatewayQuotas??{},sources:P}})},w=P=>S(d.map((E,h)=>h===l?{...E,...P}:E)),A=(P,E,h)=>e("div",{className:"cm-field"},e("label",null,P),e("input",{className:"cm-input",value:E??"",onChange:h})),y=(P,E)=>{const h=We(P?.label||P?.id||a("gatewaySourceUnknown"),P,te(r,"plan"),a);return e(q,{key:P?.id||E},h.row,P?.resetsAt?e("div",{className:"cm-note"},_e(P,a)):null)},M=(P,E)=>e("div",{key:P.id||E,className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},P.label||"package"),e("span",{className:"cm-bbox-pct cm-num"},(P.used??"—")+" / "+(P.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(P.remaining??"—")+" remaining")),T=P=>P==null?null:e(q,null,e("div",{className:"cm-mm-row wide"},e("span",{className:"cm-bbox-label"},P.unit||"credits"),e("span",{className:"cm-bbox-pct cm-num"},(P.used??"—")+" / "+(P.limit??"—")),e("span",{className:"cm-bbox-pct cm-num"},(P.remaining??"—")+" remaining")),(P.packages??[]).map(M)),B=(P,E)=>e("div",{key:P.id||E,className:"cm-budget",style:{marginTop:"8px",padding:"10px 12px"}},e("div",{className:"cm-budget-head"},e("strong",null,(Yt[P.provider]??P.provider??a("gatewaySourceUnknown"))+" · "+(P.label||a("gatewaySourceUnknown"))),e("span",{className:"cm-hint"},P.status)),P.plan?e("div",{className:"cm-note"},P.plan):null,P.windows.length>0?e("div",{className:"cm-go-list"},P.windows.map(y)):null,T(P.credits),P.message?e("div",{className:"cm-note"},P.message):null);return e(lt,{name:c.label||c.id||a("gatewayQuotaTitle"),enabled:c.enabled===!0,saved:r.gatewayQuotas?.sources?.find(P=>P.id===c.id),busy:k,open:g,errorMsg:b,statusNode:e("div",{className:"cm-note"},a("gatewaySourceStatus")+": "+(m.status??a("gatewaySourceUnknown"))+(m.serverVersion?" · "+m.serverVersion:"")+(m.fetchedAt>0?" · "+a("gatewaySourceFetchedAt",{time:new Date(m.fetchedAt).toLocaleTimeString()}):"")+(m.message?" · "+m.message:"")),configNode:e(q,null,e("div",{className:"cm-grid"},A(a("gatewaySourceLabel"),c.label,P=>w({label:P.target.value})),A(a("gatewaySourceBaseURL"),c.baseURL,P=>w({baseURL:P.target.value})),e("div",{className:"cm-field"},e("label",null,a("gatewaySourceDisplay")),e("select",{className:"cm-input",value:c.display??"both",onChange:P=>w({display:P.target.value})},...ze(a))),A(a("gatewaySourceAllowlist"),(c.allowedHosts??[]).join(", "),P=>w({allowedHosts:P.target.value.split(/[\s,;]+/).filter(Boolean)})),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:c.antigravityOnlyGemini===!0,onChange:P=>w({antigravityOnlyGemini:P.target.checked})}),e("span",null,a("gatewayOnlyGemini")))),p?e("div",{className:"cm-field"},e("label",null,a("gatewaySourceCredential")),e(De,{target:"customVar:"+p,configured:s.customVarStatus?.[p]?.configured===!0,source:s.customVarStatus?.[p]?.source??"",t:a,api:o,placeholder:p})):null,m.unsupportedProviders.length>0?e("div",{className:"cm-note"},a("gatewaySourceUnsupported")+": "+m.unsupportedProviders.join(", ")):null,m.accounts.length>0?m.accounts.map(B):e("div",{className:"cm-bal-line"},a("gatewaySourceNoAccounts"))),onToggle:P=>w({enabled:P}),onRefresh:v,onRemove:()=>S(d.filter((P,E)=>E!==l)),onToggleOpen:()=>x(P=>!P),t:a})}const Re=[{id:"anthropic",labelKey:"codingPlanAnthropic"},{id:"zai",labelKey:"codingPlanZai"},{id:"minimax",labelKey:"codingPlanMinimax"},{id:"kimi",labelKey:"codingPlanKimi"},{id:"openrouter",labelKey:"codingPlanOpenrouter"},{id:"siliconflow",labelKey:"codingPlanSiliconflow"},{id:"commandcode",labelKey:"codingPlanCommandcode"},{id:"scnet",labelKey:"codingPlanScnet"},{id:"volcengine",labelKey:"codingPlanVolcengine"},{id:"qwen",labelKey:"codingPlanQwen"},{id:"mimo",labelKey:"codingPlanMimo"}];function Ts(t){const{state:s,api:o,t:a,draft:n,setDraft:i,planId:l,labelKey:r}=t,u=s.config,d=s.codingPlans??{},c=n?.codingPlans?.[l]??u.codingPlans?.[l]??{},f=d[l]??{status:"off",message:"",fetchedAt:0,windows:{}},m=c.enabled===!0,[p,g]=L(!1),[x,k,b]=it(a,()=>o.refreshCodingPlan(l)),v=(D,O)=>{if(n===null)return;const G=n.codingPlans??u.codingPlans??{};i({...n,codingPlans:{...G,[l]:{...G[l]??{},[D]:O}}})},[S,w]=L(""),[A,y]=L({}),M=D=>D?.rates!==null&&typeof D?.rates=="object"&&!Array.isArray(D.rates)?D.rates:{},T=["input","cachedInput","output"],B=D=>A[D]??M(c)[D]??{},P=D=>T.every(O=>Number.isFinite(Number(D[O]))&&Number(D[O])>0),E=(D,O,G)=>{if(n===null)return;const R={...B(D),[O]:String(G)};y(Q=>({...Q,[D]:R}));const V=T.every(Q=>String(R[Q]??"").trim()==="");if(!V&&!P(R))return;const N=n.codingPlans??u.codingPlans??{},H={...(N.qwen??{}).rates??{}};V?delete H[D]:H[D]=Object.fromEntries(T.map(Q=>[Q,Number(R[Q])])),i({...n,codingPlans:{...N,qwen:{...N.qwen??{},rates:H}}})},h=D=>{n!==null&&y(O=>({...O,[D]:O[D]??M(c)[D]??{}}))},U=D=>{if(n===null)return;y(R=>{const V={...R};return delete V[D],V});const O=n.codingPlans??u.codingPlans??{},G={...(O.qwen??{}).rates??{}};delete G[D],i({...n,codingPlans:{...O,qwen:{...O.qwen??{},rates:G}}})},ee=f.windows!==null&&typeof f.windows=="object"?f.windows:{},ye=m===!1?e("p",{className:"cm-note"},a("codingPlanDisabledNote")):f.status==="ok"?e("div",{className:"cm-go-list"},Object.keys(ee).length>0?l==="minimax"&&(Fe(ee).five!=null||Fe(ee).seven!=null)?e(xa,{five:Fe(ee).five,seven:Fe(ee).seven,fetchedAt:f.fetchedAt,t:a,wide:!0,direction:te(u,"plan")}):Object.entries(ee).map(([D,O])=>Oa(a,D.replace(/_/g," "),O,te(u,"plan"),!1,D)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:f.fetchedAt>0?new Date(f.fetchedAt).toLocaleTimeString():"—"}))):f.status==="error"?e("div",{className:"cm-bal-line err"},f.message||a("unknownError")):f.status==="off"&&f.message?e("p",{className:"cm-note"},f.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),ve=e(q,null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:c.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:D=>v("baseUrl",D.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:c.quotaSource??"local",onChange:D=>v("quotaSource",D.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(c.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input",value:typeof c.display=="string"?c.display:l==="minimax"?"both":"settings",onChange:D=>v("display",D.target.value)},e("option",{value:"sidebar"},a("balanceSidebar")),e("option",{value:"settings"},a("balanceSettings")),e("option",{value:"both"},a("balanceBoth")),e("option",{value:"off"},a("off"))),e("span",{className:"cm-hint"},a("codingPlanDisplayNote"))),l!=="scnet"&&(l!=="qwen"||(c.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),ae({value:typeof c.refreshMinutes=="number"&&Number.isFinite(c.refreshMinutes)&&c.refreshMinutes>0?c.refreshMinutes:15},D=>{v("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(D))))})):null,l==="scnet"||l==="qwen"&&(c.quotaSource??"local")==="local"?e(q,null,e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof c.planCredits=="number"&&Number.isFinite(c.planCredits)&&c.planCredits>0?c.planCredits:l==="qwen"?5e5:24e4,onChange:D=>{const O=Number(D.target.value);Number.isFinite(O)&&O>0&&v("planCredits",Math.floor(O))}})),e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof c.planStart=="string"?c.planStart:"",onChange:D=>v("planStart",D.target.value)})),l==="qwen"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(M(c)),...Object.keys(A)])].sort().map(D=>e("div",{key:D,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},D),T.map(O=>e("input",{key:O,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:B(D)[O]??"",placeholder:a("qwenRate_"+O),"aria-label":D+" · "+a("qwenRate_"+O),onChange:G=>{const R=G.target.value;E(D,O,R)}})),e("button",{className:"cm-btn small",onClick:()=>U(D)},a("overrideRemove")),D in A&&!P(B(D))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:S,onChange:D=>w(D.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const D=S.trim();D.length!==0&&(h(D),w(""))},disabled:S.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(q,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(De,{target:"codingPlans.volcengine.ak",configured:f.keyConfigured===!0,source:f.keySource,t:a,api:o,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(De,{target:"codingPlans.volcengine.sk",configured:f.keyConfigured===!0,source:f.keySource,t:a,api:o,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},a("volcengineNote"))):e(q,null,e("div",{className:"cm-field"},e("label",null,l==="mimo"?"Cookie (platform.xiaomimimo.com)":a("codingPlanKeyLabel"))),e(De,{target:"codingPlans."+l,configured:f.keyConfigured===!0,source:f.keySource,t:a,api:o,placeholder:l==="mimo"?"api-platform_serviceToken=…; userId=…":"sk-…"})));return e(lt,{name:a(r),enabled:m,saved:u.codingPlans?.[l],busy:x,open:p,errorMsg:k,statusNode:ye,configNode:ve,onToggle:D=>v("enabled",D),onRefresh:b,onToggleOpen:()=>g(D=>!D),t:a})}function Bs(t){const{state:s,api:o,t:a,draft:n,setDraft:i}=t,l=s.config,r=n??l,u=r.codingPlans??{},d=r.gatewayQuotas?.sources??[],c=n?.customBalances??l.customBalances??[],f=S=>{n!==null&&i({...n,customBalances:S,...S.length===0?{customBalance:{...l.customBalance??{},enabled:!1,request:{url:"",headers:{}}}}:{}})},m=we({next:0,keys:[]}).current;for(;m.keys.length<c.length;)m.keys.push(m.next++);m.keys.length=c.length;const p=S=>{m.keys.splice(S,1),f(c.filter((w,A)=>A!==S))},g=(S,w)=>f(c.map((A,y)=>y===S?{...A,...w}:A)),x=(S="custom")=>{c.length>=8||f([...c,{...S==="aliyun"?{adapter:S}:{},enabled:!1,label:S==="aliyun"?"千问 / 阿里云":"",labelEn:S==="aliyun"?"Qianwen / Alibaba Cloud":"",display:"both",unit:S==="aliyun"?"CNY":"USD",refreshMinutes:15,request:{url:S==="aliyun"?"https://business.aliyuncs.com/":"",method:S==="aliyun"?"POST":"GET",headers:{}},extract:{},allowedHosts:[]}])},k=()=>{d.length>=4||n===null||i({...n,gatewayQuotas:{...n.gatewayQuotas??l.gatewayQuotas??{},sources:[...d,{id:"gateway-"+Date.now().toString(36),type:"cliproxyapi",label:"CLIProxyAPI",baseURL:"http://127.0.0.1:8317",enabled:!1,display:"both",refreshMinutes:15,includeProviders:pt,allowedHosts:[],allowInsecureHttp:!1}]}})},b=[...d.map((S,w)=>({kind:"gateway",key:"gw-"+(S.id??w),index:w,enabled:S.enabled===!0})),{kind:"go",key:"go",enabled:r.goQuota?.enabled!==!1},...Re.map(S=>({kind:"plan",key:"plan-"+S.id,planId:S.id,labelKey:S.labelKey,enabled:u[S.id]?.enabled===!0})),...c.map((S,w)=>({kind:"custom",key:"cb-"+m.keys[w],index:w,enabled:S.enabled===!0}))],v=S=>S.kind==="plan"?e(Ts,{key:S.key,planId:S.planId,labelKey:S.labelKey,state:s,api:o,t:a,draft:n,setDraft:i}):S.kind==="go"?e(As,{key:S.key,state:s,api:o,t:a,draft:n,setDraft:i}):S.kind==="gateway"?e(Ms,{key:S.key,index:S.index,state:s,api:o,t:a,draft:n,setDraft:i}):e(Cs,{key:S.key,state:s,api:o,t:a,entry:c[S.index],index:S.index,canRemove:!0,onPatch:w=>g(S.index,w),onRemove:()=>p(S.index)});return e("div",null,e("p",{className:"cm-note"},a("quotaSectionNote")),e("div",{className:"cm-quota-list"},Ss(b).map(v)),e("div",{className:"cm-buttons"},e("button",{className:"cm-btn small",onClick:k,disabled:d.length>=4},a("gatewaySourceAdd")),e("button",{className:"cm-btn small",onClick:()=>x(),disabled:c.length>=8},a("customBalanceAdd")),e("button",{className:"cm-btn small",onClick:()=>x("aliyun"),disabled:c.length>=8},a("aliyunBalanceAdd"))))}const Ds=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],La=t=>(t.input??0)+(t.output??0)+(t.cacheRead??0)+(t.cacheWrite??0);function qt(t){const s=t.useCost?t.useCost(w=>w):void 0,o=t.state??s?.state;if(!o)return null;const a=o.config,n=W(a?.locale),i=t.t??K(n),l=Array.isArray(o.history)?o.history:[];if(l.length===0)return e("div",null,e("h3",{className:"cm-h"},i("usageTitle")),e("p",{className:"cm-empty"},i("usageEmpty")));const r=o.meta?.dayKey??"",u=new Map(l.map(w=>[w.date,w])),d=w=>{const A=y=>String(y).padStart(2,"0");return w.getFullYear()+"-"+A(w.getMonth()+1)+"-"+A(w.getDate())},c=new Date;c.setHours(0,0,0,0);const f=new Date(c);f.setDate(f.getDate()+(6-(c.getDay()+6)%7));const m=26,p=[],g=[];let x=-1;for(let w=m-1;w>=0;w-=1){for(let y=0;y<7;y+=1){const M=new Date(f);M.setDate(M.getDate()-(w*7+(6-y)));const T=u.get(d(M));p.push(T!==void 0?{day:T,tokens:La(T)}:{day:{date:d(M)},tokens:0})}const A=new Date(f);A.setDate(A.getDate()-(w*7+6)),g.push(A.getMonth()!==x?n==="en"?Ds[A.getMonth()]:String(A.getMonth()+1)+"月":""),x=A.getMonth()}const k=Math.max(...p.map(w=>w.tokens),1),b=w=>{const A=w/k;return A<.25?1:A<.5?2:A<.75?3:4},v=w=>{const{day:A,tokens:y}=w,M="cm-ug-cell"+(y>0?" l"+b(y):"")+(A.date===r?" today":""),T=i("usageDay",{date:A.date,tokens:I(y),input:I(A.input??0),cache:I((A.cacheRead??0)+(A.cacheWrite??0)),output:I(A.output??0),calls:A.calls??0,cost:Y(_(A,a),a)});return e($,{key:A.date,label:T,side:"top",delayMs:200},e("div",{className:M}))},S=o.total;return e("div",{className:"cm-ug"},e("h3",{className:"cm-h"},i("usageTitle")),e("div",{className:"cm-ug-total"},i("usageTotal",{tokens:I(La(S)),input:I(S.input??0),cache:I((S.cacheRead??0)+(S.cacheWrite??0)),output:I(S.output??0),calls:S.calls??0})),e("div",{className:"cm-ug-grid",style:{gridTemplateColumns:"repeat("+m+",1fr)"}},p.map(v)),e("div",{className:"cm-ug-months",style:{gridTemplateColumns:"repeat("+m+",1fr)"}},g.map((w,A)=>e("span",{key:"m"+String(A),className:"cm-ug-monthc"},w))))}function Os(t){const s=t.useCost?t.useCost(N=>N):void 0,o=t.api,a=s?.state??null,[n,i]=L(null),[l,r]=L(null),[u,d]=L(!1),[c,f]=L(!1),[m,p]=L(!1),[g,x]=L(""),[k,b]=L(!1),[v,S]=L(!1),[w,A]=L("overview"),[y,M]=L({status:"idle",at:0,error:null}),T=Ee.useRef(null),B=Ee.useRef(null),P=Ee.useRef(null);X(()=>{if(a!==null){const N=JSON.stringify(a.config);i(H=>{const Q=H!==null&&JSON.stringify(H)!==T.current;return Q||(B.current=a.config,P.current=a.config),Q?H:JSON.parse(N)}),T.current=N}},[a]),X(()=>{n!==null&&P.current===null&&B.current!==null&&(P.current=B.current)},[n]),X(()=>{if(n===null||o===void 0)return;const N=JSON.stringify(n);if(N===T.current)return;M(Q=>Q.status==="saving"?Q:{...Q,status:"saving"});const H=setTimeout(()=>{const Q={},le=P.current??B.current;if(le!==null&&typeof le=="object")for(const C of Object.keys(n))JSON.stringify(n[C])!==JSON.stringify(le[C])&&(Q[C]=n[C]);if(Object.keys(Q).length===0){T.current=N,M({status:"saved",at:Date.now(),error:null});return}o.updateConfig(Q).then(()=>{T.current=N,le!==null&&typeof le=="object"&&(P.current={...le,...Q}),M({status:"saved",at:Date.now(),error:null})},C=>{M({status:"error",at:0,error:C?.message??String(C)})})},600);return()=>{clearTimeout(H)}},[n,o]),X(()=>{a!==null&&s?.status==="error"&&s.error&&r({kind:"err",text:h("ledgerReadFailed",{message:s.error})})},[s?.status,s?.error]);const E=W((n??a?.config)?.locale),h=K(E);if(s===void 0||a===null)return e("div",{className:"cm-section"},e("p",{className:"cm-empty"},s?.status==="loading"?h("readingLedger"):h("ledgerUnavailable")),s?.error&&e("p",{className:"cm-err",role:"alert"},h("ledgerReadFailed",{message:s.error})),e("button",{className:"cm-btn",disabled:s?.status==="loading"||!o?.reload,onClick:o?.reload},h("refresh")));const U=a.config,ee=async()=>{if(!k){b(!0),r(null);try{const N=await o.fetchPrices();if(r({kind:N.ok?"ok":"err",text:N.message}),N.ok&&N.state&&typeof N.state.config=="object"){const H=JSON.stringify(N.state.config);i(JSON.parse(H)),T.current=H}}catch(N){r({kind:"err",text:h("syncFailed",{message:N?.message??String(N)})})}finally{b(!1),d(!1)}}},ye=async()=>{if(!k){b(!0);try{await o.resetHistory(),r({kind:"ok",text:h("historyCleared")})}catch(N){r({kind:"err",text:h("clearFailed",{message:N?.message??String(N)})})}finally{b(!1),f(!1)}}},ve=async()=>{if(!k){b(!0),r(null);try{const N=await o.importLegacyHistory();r({kind:"ok",text:N.message})}catch(N){r({kind:"err",text:h("legacyImportFailed",{message:N?.message??String(N)})})}finally{b(!1),p(!1)}}},D=(N,H)=>{n!==null&&i({...n,[N]:H})},O=()=>{if(n===null)return;const N=g.trim().toLowerCase();if(N.length===0||!/^[a-z0-9_.-]+$/.test(N)||n?.prices.models[N]!==void 0)return;const H={...n.prices.models,[N]:{cacheHit:0,cacheMiss:0,output:0}};i({...n,prices:{...n.prices,models:H}}),x("")},G=n===null?[]:Object.keys(n.prices.models).filter(N=>{const Q=(n?.priceTableDisplay??U.priceTableDisplay??{})["deepseek:"+N];return typeof Q=="boolean"?Q:!0}).map(N=>e(Rt,{key:N,modelId:N,entry:n.prices.models[N]??{cacheHit:0,cacheMiss:0,output:0},isDefault:!1,draft:n,setDraft:i,t:h})),R=[["overview",h("tabOverview")],["quotas",h("tabQuotas")],["usage",h("tabUsage")],["pricing",h("tabPricing")],["display",h("tabDisplay")]],V=y.status==="saving"?e("span",{className:"cm-hint"},h("saving")):y.status==="error"?e("span",{className:"cm-msg err"},h("autoSaveFailed",{message:y.error??""})):e("span",{className:"cm-hint"},y.status==="saved"?h("autoSavedAt",{time:new Date(y.at).toLocaleTimeString()}):h("autoSaveHint"));return e("div",{className:"cm-section"},e("div",{className:"cm-tabs-row"},e("div",{className:"cm-tabs",role:"tablist"},R.map(([N,H])=>e("button",{key:N,type:"button",role:"tab","aria-selected":String(w===N),className:"cm-tab"+(w===N?" active":""),onClick:()=>A(N)},H))),V),Et(l),w==="overview"?e(q,{key:"overview"},e("div",{className:"cm-cards"},U.hideTodayCost===!0?null:e(ot,{title:h("cardToday"),value:Y(_(a.today,U),U),sub:h("callsTokens",{calls:a.today.calls,input:I(a.today.input),cache:I(a.today.cacheRead+a.today.cacheWrite),output:I(a.today.output)})}),e(ot,{title:h("cardMonth"),value:Y(_(a.month,U),U),sub:h("callsTokens",{calls:a.month.calls,input:I(a.month.input),cache:I(a.month.cacheRead+a.month.cacheWrite),output:I(a.month.output)})}),e(ot,{title:h("cardTotal"),value:Y(_(a.total,U),U),sub:h("cardTotalSub",{calls:a.total.calls})})),e(rs,{state:a,t:h}),e("p",{className:"cm-note",key:"cards-footnote"},h("cardsFootnote")),(()=>{const N=bn(a);return N!==null?e("p",{className:"cm-note",key:"tz-hint"},h("timezoneHint",{host:N.hostLabel,browser:N.browserLabel})):null})(),e("label",{className:"cm-cards-toggle",title:h("cardsTogglePlanTotalHint")},e("input",{type:"checkbox",checked:(n??U).showTotalWithPlan===!0,onChange:N=>{const H=n??U;H!=null&&i({...H,showTotalWithPlan:N.target.checked})}}),e("span",null,h("cardsTogglePlanTotal"))),e("div",null,e("h3",{className:"cm-h"},h("todaySessions")),e(ms,{state:a,t:h})),e(fs,{state:a,draft:n,setDraft:i,t:h}),(U.balance?.display==="settings"||U.balance?.display==="both")&&U.hideOfficialBalance!==!0?e(Ns,{state:a,api:o,t:h,draft:n,setDraft:i}):null):null,w==="quotas"?e(Bs,{key:"quotas",state:a,api:o,t:h,draft:n,setDraft:i}):null,w==="usage"?e(q,{key:"usage"},!Ge||(U.usage?.position??"cost")==="cost"?e(qt,{state:a,t:h,locale:E}):null,e(ys,{state:a,config:n??U,t:h}),e(vs,{state:a,config:n??U,t:h}),e(cs,{state:a,api:o}),e(us,{state:a,api:o}),e("div",null,e("h3",{className:"cm-h"},h("historyDataTitle")),e("div",{className:"cm-buttons"},m?e(q,null,e("span",{className:"cm-hint"},h("confirmImportLegacy")),e("button",{className:"cm-btn",onClick:ve,disabled:k},h("apply")),e("button",{className:"cm-btn",onClick:()=>p(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>p(!0),disabled:k},h("importLegacy")),c?e(q,null,e("span",{className:"cm-hint"},h("confirmReset")),e("button",{className:"cm-btn danger",onClick:ye,disabled:k},h("confirmClear")),e("button",{className:"cm-btn",onClick:()=>f(!1)},h("cancel"))):e("button",{className:"cm-btn danger",onClick:()=>f(!0),disabled:k},h("clearAllHistory"))),e("p",{className:"cm-note"},h("legacyImportNote")))):null,w==="display"?e(q,{key:"display"},e(is,{draft:n,setDraft:i,t:h}),a?.secretMigration?.pending?.length>0?e(hn,{pending:a.secretMigration.pending,t:h}):null,e("div",{className:"cm-toolbar"},e("div",{className:"cm-field"},e("label",null,h("languageLabel")),e("select",{className:"cm-input",value:n?.locale??"auto",onChange:N=>D("locale",N.target.value)},e("option",{value:"auto"},h("localeAuto")),e("option",{value:"zh"},h("localeZh")),e("option",{value:"en"},h("localeEn"))))),e("div",null,e("h3",{className:"cm-h"},h("displaySettings")),e("div",{className:"cm-grid"},e("div",{className:"cm-grid-group"},h("groupGeneral")),...["includeSubagentCost","codexQuotaEnabled"].map(N=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n?.[N]===!0,onChange:H=>D(N,H.target.checked)}),e("span",null,h(N)))),Ge?e("div",{className:"cm-field"},e("label",null,h("usagePositionLabel")),e("select",{className:"cm-input",value:n?.usage?.position??"cost",onChange:N=>{n!==null&&i({...n,usage:{...n.usage??{position:"cost"},position:N.target.value}})}},e("option",{value:"cost"},h("usagePositionCost")),e("option",{value:"general"},h("usagePositionGeneral")),e("option",{value:"section"},h("usagePositionSection")))):null,e("div",{className:"cm-field"},e("label",null,h("positionLabel")),e("select",{className:"cm-input",value:n?.position??"dock",onChange:N=>D("position",N.target.value)},e("option",{value:"dock"},h("positionDock")),e("option",{value:"header"},h("positionHeader")),e("option",{value:"off"},h("off")))),e("div",{className:"cm-field"},e("label",null,h("sidebarLabel")),e("select",{className:"cm-input",value:n?.sidebar===!1?"off":"on",onChange:N=>D("sidebar",N.target.value==="on")},e("option",{value:"on"},h("sidebarOn")),e("option",{value:"off"},h("off")))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.showSessionId===!0,onChange:N=>D("showSessionId",N.target.checked)}),e("span",null,h("showSessionIdLabel"))),e("div",{className:"cm-grid-group"},h("groupMoney")),e("div",{className:"cm-field"},e("label",null,h("currencyLabel")),e("select",{className:"cm-input",value:n?.currency??"CNY",onChange:N=>{const H=ps[N.target.value];H!==void 0&&n!==null&&i({...n,currency:N.target.value,...H})}},e("option",{value:"CNY"},h("currencyCny")),e("option",{value:"USD"},h("currencyUsd")),e("option",{value:"EUR"},h("currencyEur")))),e("div",{className:"cm-field"},e("label",null,h("symbolLabel")),e("input",{className:"cm-input narrow",type:"text",value:n?.symbol??"",onChange:N=>D("symbol",N.target.value)})),e("div",{className:"cm-field"},e("label",null,h("rateLabel")),ae({value:n?.exchangeRate??1,emptyMode:"ignore"},N=>D("exchangeRate",N))),e("div",{className:"cm-field"},e("label",null,h("decimalsLabel")),ae({value:n?.decimals??2},N=>D("decimals",Math.min(10,Math.floor(N))))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideOfficialBalance===!0,onChange:N=>D("hideOfficialBalance",N.target.checked)}),e("span",null,h("hideOfficialBalanceLabel"))),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.hideTodayCost===!0,onChange:N=>D("hideTodayCost",N.target.checked)}),e("span",null,h("hideTodayCostLabel"))),e("div",{className:"cm-grid-group"},h("groupSidebar")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.sidebarSimple===!0,onChange:N=>{n&&i({...n,sidebarSimple:N.target.checked,sidebarSimplePromptSeen:!0})}}),e("span",null,h("sidebarSimple"))),e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("sidebarSimpleNote"))),e("div",{className:"cm-field"},e("label",null,h("sidebarStyleLabel")),e("select",{className:"cm-input",value:n?.sidebarStyle??"standard",disabled:n?.sidebarSimple===!0,onChange:N=>D("sidebarStyle",N.target.value)},e("option",{value:"standard"},h("sidebarStyleStandard")),e("option",{value:"compact"},h("sidebarStyleCompact")))),e("div",{className:"cm-field"},e("label",null,h("balanceDisplayLabel")),e("select",{className:"cm-input",value:n?.balance?.display??"both",onChange:N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5},display:N.target.value}})}},...ze(h))),e("div",{className:"cm-field"},e("label",null,h("refreshIntervalLabel")),ae({value:n?.balance?.refreshMinutes??5},N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(N)))}})})),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.balance?.showProgressBar===!0,onChange:N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},showProgressBar:N.target.checked}})}}),e("span",null,h("balanceShowProgressBar")))),e("div",{className:"cm-field"},e("label",null,h("balanceBudgetCapLabel")),ae({value:n?.balance?.budgetCap??""},N=>{n!==null&&i({...n,balance:{...n.balance??{display:"both",refreshMinutes:5,showProgressBar:!1,budgetCap:null},budgetCap:N>0?N:null}})}),e("span",{className:"cm-hint"},h("balanceBudgetCapHint"))),e("div",{className:"cm-field"},e("label",null,h("barDirectionsTitle")),["balance","budget","go","plan"].map(N=>e("div",{className:"cm-dir-row",key:N},e("span",{className:"cm-dir-label"},h("barDirection_"+N)),e("select",{className:"cm-input",value:n?.barDirections?.[N]??(N==="balance"?"remaining":"used"),onChange:H=>{if(n===null)return;const Q={balance:"remaining",budget:"used",go:"used",plan:"used"};i({...n,barDirections:{...n.barDirections??Q,[N]:H.target.value}})}},e("option",{value:"remaining"},h("barDirectionRemaining")),e("option",{value:"used"},h("barDirectionUsed"))))),e("span",{className:"cm-hint"},h("barDirectionsHint"))),e("div",{className:"cm-field"},e("label",null,h("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n?.customBalance?.display??U.customBalance?.display??"both",onChange:N=>{n!==null&&i({...n,customBalance:{...n.customBalance??U.customBalance??{},display:N.target.value}})}},...ze(h))),e("div",{className:"cm-field"},e("label",null,h("customBalanceRefreshInterval")),ae({value:n?.customBalance?.refreshMinutes??U.customBalance?.refreshMinutes??15},N=>{n!==null&&i({...n,customBalance:{...n.customBalance??U.customBalance??{},refreshMinutes:Math.min(1440,Math.max(1,Math.floor(N)))}})})),e(Ra,{config:U,draft:n,setDraft:i,t:h,api:o}),e("div",{className:"cm-grid-group"},h("quotaStripGroup")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.quotaStrip?.enabled===!0,onChange:N=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip??{enabled:!1,budget:!0,go:!0,plans:!0},enabled:N.target.checked,promptSeen:!0}})}}),e("span",null,h("quotaStripEnable")))),n?.quotaStrip?.enabled===!0?[["budget","quotaStripShowBudget"],["go","quotaStripShowGo"],["plans","quotaStripShowPlans"]].map(([N,H])=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n.quotaStrip[N]!==!1,onChange:Q=>{n!==null&&i({...n,quotaStrip:{...n.quotaStrip,[N]:Q.target.checked}})}}),e("span",null,h(H)))):null,e("div",{className:"cm-field"},e("span",{className:"cm-hint"},h("quotaStripNote"))),e("div",{className:"cm-grid-group"},h("groupCorner")),e("div",{className:"cm-field"},e("label",null,h("cornerLabel")),e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.corner?.enabled===!0,onChange:N=>{n!==null&&i({...n,corner:{...n.corner??{enabled:!1,goRolling:!0,goWeekly:!0,goMonthly:!0,budget:!0},enabled:N.target.checked}})}}),e("span",null,h("cornerEnabledLabel"))),n?.corner?.enabled===!0?[["goRolling","cornerGoRolling"],["goWeekly","cornerGoWeekly"],["goMonthly","cornerGoMonthly"],["budget","cornerBudget"]].map(([N,H])=>e("label",{key:N,className:"cm-check"},e("input",{type:"checkbox",checked:n.corner[N]!==!1,onChange:Q=>{n!==null&&i({...n,corner:{...n.corner,[N]:Q.target.checked}})}}),e("span",null,h(H)))):null),e("div",{className:"cm-grid-group"},h("groupDetail")),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.goQuota?.detail!==!1,onChange:N=>{n!==null&&i({...n,goQuota:{...n.goQuota??{display:"both",refreshMinutes:15,apiKey:"",main:"rolling",detail:!0},detail:N.target.checked}})}}),e("span",null,h("goDetailLabel")))),e("div",{className:"cm-field"},e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n?.budget?.detail!==!1,onChange:N=>{n!==null&&i({...n,budget:{...n.budget??{enabled:!1,amount:100,period:"month",customStart:null,customEnd:null,detail:!0},detail:N.target.checked}})}}),e("span",null,h("budgetDetailLabel"))))),e("p",{className:"cm-note"},h("badgeNote")))):null,w==="pricing"?e(q,{key:"pricing"},e(bs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,Oe(v,()=>S(!v),h("priceTableTitle")),v?e("div",{className:"cm-collapse-body"},e("p",{className:"cm-note"},h("priceTableNote")),e("p",{className:"cm-hint"},h("priceTableDisplayHint")),e("div",{className:"cm-catalog-vendor"},h("deepseekMountedHeader")),G,e(Rt,{key:"__default__",modelId:h("defaultModelId"),entry:n?.prices.default??{cacheHit:0,cacheMiss:0,output:0},isDefault:!0,draft:n,setDraft:i,t:h}),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:h("newModelPlaceholder"),value:g,onChange:N=>x(N.target.value)}),e("button",{className:"cm-btn small",onClick:O,disabled:g.trim().length===0},h("addModel"))),(()=>{const N=n?.priceTableDisplay??U.priceTableDisplay??{},H=n?.prices?.providers??{},Q=C=>Object.keys(H[C]?.models??{}).filter(F=>N[C+":"+F]===!0),le=Object.keys(H).filter(C=>Q(C).length>0).sort((C,F)=>C.localeCompare(F));return le.length===0?null:le.map(C=>e("div",{key:C},e("div",{className:"cm-catalog-vendor"},(Pa[C]??C)+" · "+h("mountedSuffix")),Q(C).sort().map(F=>e(Da,{key:C+":"+F,provider:C,modelId:F,entry:H[C].models[F],draft:n,setDraft:i,t:h}))))})()):null),(()=>{const N=n?.priceOverrides??U.priceOverrides??{},H=n?.priceMatchDismissed??U.priceMatchDismissed??[],Q=n?.prices??U.prices,le=a.today.byProviderModel??{},C={prices:Q,priceMatch:n?.priceMatch??U.priceMatch},F=Object.keys(le).filter(j=>{if(H.includes(j)||N[j]!==void 0)return!1;const z=j.indexOf(":"),ke=(z>0?j.slice(0,z):"deepseek").toLowerCase(),Ht=z>0?j.slice(z+1):j;return gt(ke,Ht,C).matched!==!0}),Z=[...new Set([...F,...Object.keys(N)])].filter(j=>!H.includes(j)),ne=a.month?.byProviderModel??{},Le=Object.keys(ne).filter(j=>{if(H.includes(j)||N[j]!==void 0)return!1;const z=j.indexOf(":"),ke=(z>0?j.slice(0,z):"deepseek").toLowerCase(),Ht=z>0?j.slice(z+1):j;return gt(ke,Ht,C).matched===!0}).sort(),Ne=[{value:"__local__",label:h("overrideTargetLocal")},{value:"deepseek:__default__",label:h("overrideTargetDefault")},...Object.keys(Q.models??{}).map(j=>({value:"deepseek:"+j,label:"DeepSeek · "+j})),...Object.entries(Q.providers??{}).flatMap(([j,z])=>Object.keys(z?.models??{}).map(ke=>({value:j+":"+ke,label:j+" · "+ke})))],pe=(j,z)=>{if(n===null)return;const ke={...n.priceOverrides??{}};z===""?delete ke[j]:ke[j]=z,i({...n,priceOverrides:ke})},Me=j=>{if(n===null)return;const z={...n.priceOverrides??{}};delete z[j],i({...n,priceOverrides:z,priceMatchDismissed:[...new Set([...H,j])]})};return e("div",null,e("h3",{className:"cm-h"},h("priceMatchLabel")),e("div",{className:"cm-field"},e("select",{className:"cm-input",value:n?.priceMatch==="exact"?"exact":"auto",onChange:j=>D("priceMatch",j.target.value)},e("option",{value:"auto"},h("priceMatchAuto")),e("option",{value:"exact"},h("priceMatchExact")))),e("p",{className:"cm-note"},h("priceMatchNote")),Z.length>0?e(q,null,e("h3",{className:"cm-h"},h("unmatchedTitle")),e("p",{className:"cm-hint"},h("unmatchedHint")),Z.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,Lt(j)),e("select",{className:"cm-input",value:N[j]??"",onChange:z=>pe(j,z.target.value)},e("option",{value:""},"—"),Ne.map(z=>e("option",{key:z.value,value:z.value},z.label))),e("button",{className:"cm-btn small",title:h("removePriceMatchHint"),onClick:()=>Me(j)},h("overrideRemove"))))):e("p",{className:"cm-hint"},h("overrideNone")),H.length>0?e("button",{className:"cm-btn small",onClick:()=>D("priceMatchDismissed",[])},h("restorePriceMatches",{count:H.length})):null,Le.length>0?e(q,null,e("h3",{className:"cm-h"},h("matchedTitle")),e("p",{className:"cm-hint"},h("matchedHint")),Le.map(j=>e("div",{key:j,className:"cm-match-row"},e("span",null,Lt(j)),e("select",{className:"cm-input",value:"",onChange:z=>{z.target.value!==""&&pe(j,z.target.value)}},e("option",{value:""},h("matchedKeepAuto")),Ne.map(z=>e("option",{key:z.value,value:z.value},z.label)))))):null)})(),e(hs,{state:a,draft:n,setDraft:i,t:h}),e("div",null,e("h3",{className:"cm-h"},h("dataSync")),(n??U).currency==="CNY"&&(n??U).prices?.currency!=="CNY"?e("div",{className:"cm-note",role:"status"},h("pricingCnyHint",{rate:(n??U).exchangeRate}),(n??U).pricingCurrency!=="CNY"?e("button",{className:"cm-btn small",disabled:k,onClick:()=>D("pricingCurrency","CNY")},h("pricingCurrencyCny")):null):null,e("div",{className:"cm-field"},e("label",null,h("pricingCurrencyLabel")),e("select",{className:"cm-input",value:n?.pricingCurrency==="CNY"?"CNY":"USD",onChange:N=>D("pricingCurrency",N.target.value)},e("option",{value:"USD"},h("pricingCurrencyUsd")),e("option",{value:"CNY"},h("pricingCurrencyCny"))),e("p",{className:"cm-note"},h("pricingCurrencyNote"))),e("div",{className:"cm-buttons"},u?e(q,null,e("span",{className:"cm-hint"},h("confirmFetch")),e("button",{className:"cm-btn",onClick:ee,disabled:k},h("apply")),e("button",{className:"cm-btn",onClick:()=>d(!1)},h("cancel"))):e("button",{className:"cm-btn",onClick:()=>d(!0),disabled:k},h("syncFromDocs"))),e("p",{className:"cm-note"},h("lastSync",{time:U.fetchedAt!==null?new Date(U.fetchedAt).toLocaleString():h("neverSynced")})+h("source",{source:U.priceSource==="official"?h("sourceOfficial"):h("sourceBundled")})),e("p",{className:"cm-note"},h("syncScopeNote")))):null)}const Rs=["remote"];async function Ls(t){const s=t.remote;if(s===void 0||typeof s.$mount!="function")return;const o=await s.$mount(tn);t.effect(()=>()=>{o()},"cost-meter: remote contribution");const a=t.get("remote.costMeter");if(a===void 0)return;const n=gn({status:"loading",error:null,state:null}),i=()=>K(W(n.getSnapshot().state?.config?.locale)),l=async(C,F)=>{const Z=await a[C](...F??[]);if(Z===null||typeof Z!="object"||Z.ok!==!0)throw new Error(Z?.error?.message??i()("rpcFailed",{method:C}));return Z.value};let r=Date.now(),u=!1,d=!0,c=1;const f=async()=>{if(!d||u)return;u=!0,r=Date.now();const C=n.getSnapshot();C.state===null&&n.set({...C,status:"loading"});try{const F=await l("getState");if(!d)return;c=1,n.set({status:"ready",error:null,state:F})}catch(F){if(!d)return;C.state===null&&(r=Date.now()),c=Math.min(c*2,60),n.set({status:"error",error:F?.message??String(F),state:C.state})}finally{u=!1}};t.effect(()=>t.on("connection/reset",()=>{f()}),"cost-meter: reconnect reload");const m=setInterval(()=>{const C=n.getSnapshot().state,F=C?.config.sidebarModels,Z=C?F?.enabled||F?.dock?F.refreshSeconds:60:c;!document.hidden&&Date.now()-r>=(Z||60)*1e3&&f()},1e3);t.effect(()=>()=>{d=!1,clearInterval(m)},"cost-meter: poll timer");const p=()=>{document.visibilityState==="visible"&&f()};document.addEventListener("visibilitychange",p),t.effect(()=>()=>{document.removeEventListener("visibilitychange",p)},"cost-meter: visibility reload");const g=async(C,F="rpcSyncFailed",Z=!1)=>{const ne=await C;if(ne===null||typeof ne!="object"||ne.ok!==!0)throw new Error(ne?.error?.message??(Z?ne?.value?.message:void 0)??i()(F));return ne.value.state!==void 0&&n.set({status:"ready",error:null,state:ne.value.state}),ne.value},x={reload:f,updateConfig:async C=>{const F=await l("updateConfig",[C]);return n.set({status:"ready",error:null,state:F}),F},fetchPrices:async()=>g(a.fetchPrices()),resetHistory:async()=>{const C=await l("resetHistory");return n.set({status:"ready",error:null,state:C}),C},importLegacyHistory:async()=>{const C=await a.importLegacyHistory();if(C===null||typeof C!="object"||C.ok!==!0)throw new Error(C?.error?.message??C?.value?.message??i()("legacyImportFailed",{message:"RPC failed"}));return C.value.state!==void 0&&n.set({status:"ready",error:null,state:C.value.state}),C.value},getDaySessions:async C=>l("getDaySessions",[C]),getSessionCost:async C=>l("getSessionCost",[C]),getTopSessions:async(C,F,Z)=>l("getTopSessions",[C,F,Z]),refreshBalance:async()=>g(a.refreshBalance(),"rpcBalanceFailed"),refreshGoQuota:async()=>g(a.refreshGoQuota()),refreshGatewayQuota:async(C=null)=>g(C==null?a.refreshGatewayQuota():a.refreshGatewayQuota(C)),refreshCustomBalance:async(C=null)=>g(C==null?a.refreshCustomBalance():a.refreshCustomBalance(C)),refreshCodingPlan:async C=>g(a.refreshCodingPlan(C)),setCredential:async(C,F)=>g(a.setCredential(C,F),"rpcSyncFailed",!0),clearCredential:async C=>g(a.clearCredential(C),"rpcSyncFailed",!0)};f();const k=t.get("slots");if(k===void 0)return;const b=()=>({hooks:{cost:n},api:x}),v=()=>({gen:0,dispose:null}),S=(C,F,Z,ne,Le=!0)=>{C.dispose!==null&&(C.dispose(),C.dispose=null),C.gen+=1;const Ne=C.gen;Le&&k.inject(F,()=>{if(C.gen!==Ne)return;const pe=typeof Z=="function"?Z():k.register(Z,ne);if(C.gen!==Ne){pe();return}return C.dispose=pe,()=>{C.dispose===pe&&(C.dispose=null),pe()}})},w=v(),A=C=>{const F=C==="header"?"conversation.session.header.actions":"conversation.composer.dock";S(w,F,C==="header"?{name:F,id:"cost-meter",order:-5,inject:b}:{name:F,id:"cost-meter",order:5,inject:b},C==="header"?kn:wn,C!=="off")},y=v(),M=C=>{S(y,"sidebar.footer.action",{name:"sidebar.footer.action",id:"cost-meter",order:0,inject:b},os,C)},T=v(),B=C=>{S(T,"conversation.composer.dock",{name:"conversation.composer.dock",id:"cost-meter-corner",order:9,inject:b},On,C)};k.inject("conversation.input.dock",()=>k.register({name:"conversation.input.dock",id:"cost-meter-qstrip",order:5,inject:b},Xn)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-simple-guide",order:1,inject:b},es)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-qstrip-guide",order:1,inject:b},ts)),k.inject("sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-balance-click-guide",order:2,inject:b},ss));const P=v(),E=C=>{S(P,"sidebar.footer.action",()=>k.register({name:"sidebar.footer.action",id:"cost-meter-peak-alert",order:0,inject:b},Rn),null,C)};window.cmPeakAlertPreview=C=>{if(window.__cmPeakAlertLive!==!0){console.warn("[dsh-cost-meter] 弹窗组件未挂载:需启用峰谷计价并重启 dsh web 后再预览。");return}window.dispatchEvent(new CustomEvent(Ct,{detail:{kind:C==="offpeak"?"offpeak":"peak"}}))};const h=v(),U=C=>{S(h,"settings.section",{name:"settings.section",id:"cost-meter",order:30,label:C==="en"?Te.en.sectionLabel:Te.zh.sectionLabel,inject:b},Os,!0)},ee=v(),ye=C=>{S(ee,"settings.general.item",{name:"settings.general.item",id:"cost-meter-usage",order:30,inject:b},qt,C)},ve=v(),D=(C,F)=>{S(ve,"settings.section",{name:"settings.section",id:"cost-meter-usage",order:31,label:F==="en"?Te.en.usageSectionLabel:Te.zh.usageSectionLabel,inject:b},qt,C)};let O=null,G=null,R=null,V=null,N=null,H=null;const Q=()=>{const C=n.getSnapshot().state,F=C?.config?.position??"dock",Z=C?.config?.sidebar!==!1&&C?.config?.hideTodayCost!==!0,ne=C?.config?.balance?.display??"both",Le=(ne==="sidebar"||ne==="both")&&C?.config?.hideOfficialBalance!==!0,Ne=Z||Le||C?.config?.codexQuotaEnabled===!0||C?.config?.sidebarModels?.enabled===!0,pe=C?.config?.corner?.enabled===!0||C?.config?.sidebarModels?.dock===!0,Me=W(C?.config?.locale),j=C?.config?.usage?.position??"cost";F!==O&&(A(F),O=F),Ne!==G&&(M(Ne),G=Ne),pe!==R&&(B(pe),R=pe);const z=C?.config?.peakEnabled===!0;z!==H&&(E(z),H=z),Me!==V&&(U(Me),V=Me),j!==N?(Ge&&(ye(j==="general"),D(j==="section",Me)),N=j):Ge&&j==="section"&&Me!==V&&D(!0,Me)};Q();const le=n.subscribe(Q);return()=>{le()}}return rt.apply=Ls,rt.inject=Rs,Ut.exports}});
|