dsh-cost-meter 1.8.19 → 1.8.21

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.
@@ -1,4 +1,4 @@
1
- window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:Je=>{const he=Je("react"),{createElement:e,useState:A,useEffect:oe,useRef:ce,Fragment:se}=he,yt=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],W=(t,n)=>n==="total"?t.cost:n==="plan"?Math.max(0,t.cost-t.apiCost):t.apiCost,pe=t=>t.input+t.cacheRead+t.cacheWrite+t.output,H=(t,n)=>n>0?(100*t/n).toFixed(1)+"%":"—",Qe=(t,n)=>new Date(Date.parse(t)+n*864e5).toISOString().slice(0,10),Pe=t=>n=>{if(typeof n!==t||t==="number"&&!Number.isFinite(n))throw new Error("Invalid statistics "+t);return n},P=Pe("number"),x=Pe("string"),$=Pe("boolean"),re=t=>t===null?null:P(t),V=t=>n=>{if(!Array.isArray(n))throw new Error("Invalid statistics array");return n.map(t)},D=t=>n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid statistics object");return Object.fromEntries(Object.entries(t).map(([r,o])=>[r,o(n[r])]))},te=Object.fromEntries(yt.map(t=>[t,P])),Ve=D(te),He=D({provider:x,model:x,bucket:x,tokens:P,rate:P,cost:P,priced:$,plan:$}),ze=t=>x(t??""),_e=D({sessionId:ze,kind:x,turn:re,step:re,provider:x,model:x,atMs:P,cost:P,apiCost:P,plan:$,priced:$,longContext:$,rows:V(He)}),Re=D({from:x,to:x,retainedFrom:x,retainedTo:x,totals:Ve,days:V(D({...te,date:x})),models:V(D({...te,key:x,provider:x,model:x,priced:$})),sessions:V(D({...te,id:x,title:x})),providers:V(x),modelOptions:V(x),sessionCount:P,offset:P,unassignedCost:P,unmodeledCost:P}),Me=D({found:$,cost:P,apiCost:P,rows:V(He),calls:V(_e),totalCalls:P,offset:P,recorded:Ve,agents:t=>V(D({...te,id:x,title:x}))(t??[]),callShares:t=>V(D({index:P,cost:P,apiCost:P,tokens:P,calls:P,other:$,unpriced:$}))(t??[]),kinds:V(D({...te,kind:x,unpriced:$})),turns:V(D({...te,sessionId:ze,turn:re,unpriced:$})),totalTurns:P,turnOffset:P,stepShares:D(Object.fromEntries(["cost","calls"].map(t=>[t,V(D({...te,sessionId:ze,turn:re,step:re,other:$,unpriced:$}))])))}),Oe=D({found:$,turn:P,input:x,inputTruncated:$,totalTools:P,offset:P,tools:V(D({seq:P,step:re,name:x,callId:x,atMs:P,arguments:x,result:x,truncated:$,status:x}))}),ve=["system","tools","user","inject","skill","assistant","tool","other"],xe=t=>{if(P(t)<0)throw new Error("Invalid context costs amount");return t},Xe=D(Object.fromEntries(["input","cacheRead","cacheWrite","output","reasoning"].map(t=>[t,xe]))),kt=t=>t===null?null:Xe(t),Ee=D({status:x,sessionId:x,generatedAt:P,revision:P,provider:x,model:x,basis:x,priced:$,source:x,linked:$,contextTokens:xe,components:V(D({key:t=>{if(!ve.includes(t))throw new Error("Invalid context costs category");return t},tokens:xe})),rates:kt,longContext:t=>t===null?null:{...Xe(t),aboveInputTokens:xe(t.aboveInputTokens)},lastCall:t=>t===null?null:_e(t)}),Ye=t=>{const n=x(t?.sessionId);if(!n||n.length>512)throw new Error("Invalid context costs session");return{sessionId:n}},Ge=D({version:x,compatible:$,reason:x}),Ze=t=>{const n=D({sessionId:x,turn:P,offset:P})({...t,offset:t.offset??0});if(!n.sessionId||n.sessionId.length>512||![n.turn,n.offset].every(r=>Number.isSafeInteger(r)&&r>=0)||n.offset>1e7)throw new Error("Invalid turn inspection query");return n},et=t=>{const n=D({from:x,to:x,provider:x,model:x,sessionId:x,basis:x,offset:P})(t);if(n.turnOffset=P(t.turnOffset??0),!["api","plan","total"].includes(n.basis)||![n.offset,n.turnOffset].every(r=>Number.isSafeInteger(r)&&r>=0&&r<=1e7))throw new Error("Invalid statistics query");return n},Ae=(t,n)=>{const r={parse:n};return{mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:r,create:()=>r}},tt={package:"dsh-cost-meter/statistics",descriptors:[["getBillingStatistics","BillingStatistics",Re],["getSessionBilling","SessionBilling",Me],["getTurnInspection","TurnInspection",Oe,Ze],["getContextCosts","ContextCosts",Ee,Ye]].map(([t,n,r,o])=>({id:"dsh-cost-meter#costMeter/"+t,service:"costMeter",namespace:"costMeter",method:t,invocation:{kind:"direct"},parameters:[{name:"query",wire:"query",source:"json",codec:Ae(o?n+"Query":"StatisticsQuery",o??et)}],result:Ae(n,r)})).concat({id:"dsh-cost-meter#costMeter/getContextIntegration",service:"costMeter",namespace:"costMeter",method:"getContextIntegration",invocation:{kind:"direct"},parameters:[],result:Ae("ContextIntegration",Ge)})},at=`
1
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:Ht=>{const wt=Ht("react"),{createElement:t,useState:j,useEffect:nt,useRef:dt,Fragment:tt}=wt,ze=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],D=(e,n)=>n==="total"?e.cost:n==="plan"?Math.max(0,e.cost-e.apiCost):e.apiCost,gt=e=>e.input+e.cacheRead+e.cacheWrite+e.output,_=(e,n)=>n>0?(100*e/n).toFixed(1)+"%":"—",Xt=(e,n)=>new Date(Date.parse(e)+n*864e5).toISOString().slice(0,10),At=e=>n=>{if(typeof n!==e||e==="number"&&!Number.isFinite(n))throw new Error("Invalid statistics "+e);return n},C=At("number"),y=At("string"),K=At("boolean"),et=e=>e===null?null:C(e),J=e=>n=>{if(!Array.isArray(n))throw new Error("Invalid statistics array");return n.map(e)},U=e=>n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid statistics object");return Object.fromEntries(Object.entries(e).map(([l,o])=>[l,o(n[l])]))},ct=Object.fromEntries(ze.map(e=>[e,C])),Yt=U(ct),Lt=U({provider:y,model:y,bucket:y,tokens:C,rate:C,cost:C,priced:K,plan:K}),qt=e=>y(e??""),Gt=U({sessionId:qt,logSeq:e=>et(e??null),kind:y,turn:et,step:et,provider:y,model:y,atMs:C,cost:C,apiCost:C,plan:K,priced:K,longContext:K,rows:J(Lt)}),Bt=U({from:y,to:y,retainedFrom:y,retainedTo:y,totals:Yt,days:J(U({...ct,date:y})),models:J(U({...ct,key:y,provider:y,model:y,priced:K})),sessions:J(U({...ct,id:y,title:y})),providers:J(y),modelOptions:J(y),sessionCount:C,offset:C,unassignedCost:C,unmodeledCost:C}),Dt=U({found:K,cost:C,apiCost:C,rows:J(Lt),calls:J(Gt),totalCalls:C,offset:C,recorded:Yt,agents:e=>J(U({...ct,id:y,title:y}))(e??[]),callShares:e=>J(U({index:C,cost:C,apiCost:C,tokens:C,calls:C,other:K,unpriced:K}))(e??[]),kinds:J(U({...ct,kind:y,unpriced:K})),turns:J(U({...ct,sessionId:qt,turn:et,unpriced:K})),totalTurns:C,turnOffset:C,stepShares:U(Object.fromEntries(["cost","calls"].map(e=>[e,J(U({...ct,sessionId:qt,turn:et,step:et,other:K,unpriced:K}))])))}),St=U({found:K,turn:C,input:y,inputTruncated:K,totalTools:C,offset:C,tools:J(U({seq:C,step:et,name:y,callId:y,atMs:C,arguments:y,result:y,truncated:K,status:y}))}),Zt=e=>({...U({found:K,kind:y,input:y,injected:y,skills:y,precedingTools:y,output:y,reasoning:y,truncated:K,totalTools:C,offset:C})(e),tools:St({...e,turn:0,inputTruncated:!1}).tools.map((n,l)=>({...n,durationMs:et(e.tools[l].durationMs??null)}))}),It=["system","tools","user","inject","skill","assistant","tool","other"],Tt=e=>{if(C(e)<0)throw new Error("Invalid context costs amount");return e},te=U(Object.fromEntries(["input","cacheRead","cacheWrite","output","reasoning"].map(e=>[e,Tt]))),Pe=e=>e===null?null:te(e),Ut=U({status:y,sessionId:y,generatedAt:C,revision:C,provider:y,model:y,basis:y,priced:K,source:y,linked:K,contextTokens:Tt,components:J(U({key:e=>{if(!It.includes(e))throw new Error("Invalid context costs category");return e},tokens:Tt})),rates:Pe,longContext:e=>e===null?null:{...te(e),aboveInputTokens:Tt(e.aboveInputTokens)},lastCall:e=>e===null?null:Gt(e)}),zt=e=>{const n=y(e?.sessionId);if(!n||n.length>512)throw new Error("Invalid context costs session");return{sessionId:n}},ee=U({version:y,compatible:K,reason:y}),ae=U({cost:C,apiCost:C,totalSteps:C,offset:C,shares:J(U({key:y,sessionId:y,turn:et,step:et,kind:y,tools:J(y),cost:C,apiCost:C,unpriced:K,other:K,count:C})),groups:J(U({key:y,kind:y,tools:J(y),steps:C,cost:C,apiCost:C,unpriced:K})),steps:J(U({key:y,sessionId:y,turn:et,step:et,kind:y,tools:J(y),atMs:C,calls:C,cost:C,apiCost:C,unpriced:K,rows:J(Lt)}))}),se=e=>{const n={...zt(e),basis:y(e.basis??"total"),offset:C(e.offset??0)};if(!["api","plan","total"].includes(n.basis)||!Number.isSafeInteger(n.offset)||n.offset<0||n.offset>1e7)throw new Error("Invalid step billing query");return n},ne=e=>{const n=U({sessionId:y,turn:C,offset:C})({...e,offset:e.offset??0});if(!n.sessionId||n.sessionId.length>512||![n.turn,n.offset].every(l=>Number.isSafeInteger(l)&&l>=0)||n.offset>1e7)throw new Error("Invalid turn inspection query");return n},ce=e=>{const n=U({from:y,to:y,provider:y,model:y,sessionId:y,basis:y,offset:C})(e);if(n.turnOffset=C(e.turnOffset??0),!["api","plan","total"].includes(n.basis)||![n.offset,n.turnOffset].every(l=>Number.isSafeInteger(l)&&l>=0&&l<=1e7))throw new Error("Invalid statistics query");return n},oe=e=>{const n={...zt(e),seq:C(e.seq),atMs:C(e.atMs),offset:C(e.offset??0)};if(![n.seq,n.offset].every(l=>Number.isSafeInteger(l)&&l>=0)||n.offset>1e7||n.atMs<=0)throw new Error("Invalid call inspection query");return n},Wt=(e,n)=>{const l={parse:n};return{mode:"strict",typeSymbol:"dsh-cost-meter#"+e,schema:l,create:()=>l}},le={package:"dsh-cost-meter/statistics",descriptors:[["getSessionTrajectory","Trajectory",ae,se],["getBillingStatistics","BillingStatistics",Bt],["getSessionBilling","SessionBilling",Dt],["getTurnInspection","TurnInspection",St,ne],["getCallInspection","CallInspection",Zt,oe],["getContextCosts","ContextCosts",Ut,zt]].map(([e,n,l,o])=>({id:"dsh-cost-meter#costMeter/"+e,service:"costMeter",namespace:"costMeter",method:e,invocation:{kind:"direct"},parameters:[{name:"query",wire:"query",source:"json",codec:Wt(o?n+"Query":"StatisticsQuery",o??ce)}],result:Wt(n,l)})).concat({id:"dsh-cost-meter#costMeter/getContextIntegration",service:"costMeter",namespace:"costMeter",method:"getContextIntegration",invocation:{kind:"direct"},parameters:[],result:Wt("ContextIntegration",ee)})},re=`
2
2
  .cm-stat{--cm-accent:var(--dsw-alias-state-business-primary,#4d6bfe);--cm-plan:var(--dsw-alias-label-tertiary,#8b9099);--cm-muted:var(--dsw-alias-label-tertiary,#858a94);--cm-border:var(--dsw-alias-border-l3,#e9eaed);--cm-surface:var(--dsw-alias-bg-layer-1,#f7f8fa);color:var(--dsw-alias-label-primary,#25262b);font-family:var(--ds-font-family-sans,inherit);font-size:13px;line-height:1.55;container-type:inline-size}
3
3
  .cm-stat *{box-sizing:border-box}.cm-stat h2,.cm-stat h3,.cm-stat p{margin:0}.cm-stat h2{font-size:18px;font-weight:600;letter-spacing:0}.cm-stat h3{font-size:14px;font-weight:500}
4
4
  .cm-stat-head{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0 0 18px}.cm-stat-sub{font-size:12px;color:var(--cm-muted)}
@@ -17,10 +17,10 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
17
17
  .cm-stat-page{display:flex;gap:12px;align-items:center;justify-content:flex-end;margin-top:14px}.cm-stat-note{padding:10px 12px;background:var(--dsw-alias-bg-layer-2,#f5f7fa);border-radius:8px;margin:12px 0!important;font-size:12px;color:var(--cm-muted)}.cm-stat-error{color:var(--dsw-alias-state-error-primary,#c75040);white-space:pre-wrap}.cm-stat-empty{padding:30px;text-align:center;color:var(--cm-muted)}.cm-stat-call{padding:11px 0;border-bottom:1px solid var(--dsw-alias-border-l1,#dce3ec)}.cm-stat-call summary{cursor:pointer;overflow-wrap:anywhere}.cm-stat-call p{overflow-wrap:anywhere;margin-top:6px}
18
18
  .cm-stat summary{cursor:pointer}.cm-stat-help{font-size:12px;color:var(--cm-muted);margin:10px 0}.cm-stat-help>p{margin-top:8px}.cm-stat-shares{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px;margin:20px 0}.cm-stat-share-list{list-style:none;margin:12px 0 0;padding:0;display:grid;gap:11px}.cm-stat-share-head{display:flex;justify-content:space-between;gap:12px;font-size:12px}.cm-stat-share-head>span:first-child{min-width:0;overflow-wrap:anywhere}.cm-stat-share-value{white-space:nowrap;font-variant-numeric:tabular-nums}.cm-stat-share-track{height:6px;background:var(--cm-surface);border-radius:99px;overflow:hidden;margin-top:5px}.cm-stat-share-fill{display:block;height:100%;background:var(--cm-accent);border-radius:99px;opacity:.68}.cm-stat-share-list li:nth-child(even) .cm-stat-share-fill{opacity:.42}.cm-stat-share-list li[data-other=true] .cm-stat-share-fill{background:var(--cm-plan)}
19
19
  .cm-stat-breakdown{padding-block:18px;border-block:1px solid var(--cm-border);margin-block:18px}.cm-stat-turns{margin-top:24px}.cm-stat-turn{border-top:1px solid var(--cm-border)}.cm-stat-turn-toggle{display:flex;align-items:center;gap:10px;justify-content:space-between;width:100%;text-align:left;padding:12px 4px;background:transparent;border:0}.cm-stat-turn-toggle:hover{background:var(--dsw-alias-interactive-bg-hover,#f5f6f8)}.cm-stat-turn-toggle>span:first-child{font-weight:500}.cm-stat-turn-toggle>span:last-child{color:var(--cm-muted);font-size:12px;text-align:right;font-variant-numeric:tabular-nums}.cm-stat-inspection{background:var(--cm-surface);padding:16px;border-radius:10px;margin:0 0 12px}.cm-stat-inspection h4{font-size:12px;font-weight:500;margin:0 0 8px}.cm-stat-pre{font:12px/1.6 var(--ds-font-family-code,monospace);white-space:pre-wrap;overflow-wrap:anywhere;max-height:280px;overflow:auto;margin:8px 0 16px;padding:12px;border:1px solid var(--cm-border);background:var(--dsw-alias-bg-base,#fff);border-radius:8px}.cm-stat-tool{border-top:1px solid var(--cm-border);padding:10px 0}.cm-stat-tool summary{display:flex;flex-wrap:wrap;gap:8px;align-items:center;font-size:12px}.cm-stat-tool summary::before{content:'›';color:var(--cm-muted)}.cm-stat-tool[open] summary::before{content:'⌄'}.cm-stat-tool .cm-stat-sub{margin-left:auto}.cm-stat-truncated{color:var(--cm-muted);font-size:12px}.cm-stat-step-list{columns:2;column-gap:28px}.cm-stat-step-list li{break-inside:avoid;margin-bottom:12px}.cm-stat-step-list.cm-stat-share-list{display:block}
20
- .cm-stat-dialog{border-color:var(--dsw-alias-border-l3,#e9eaed);box-shadow:var(--dsw-elevation-prominent,0 20px 90px #0002)}.cm-stat-dialog-head>.cm-btn{border:0;border-radius:8px;background:transparent;font-size:22px;line-height:28px;width:32px;height:32px;padding:0}.cm-stat-dialog-head>.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#f0f1f4)}.cm-stat-dialog-head>.cm-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:2px}.cm-session-options{margin-top:18px;border-top:1px solid var(--cm-border);padding-top:12px}.cm-session-options>summary{color:var(--cm-muted);font-size:12px}.cm-session-options .cm-context-setting{border:0;padding:0}.cm-stat-session>.cm-stat-panel{border:0;padding:0;margin:0}.cm-stat-session .cm-stat-metrics{margin-top:0}.cm-stat-session .cm-plan{margin:20px 0}
20
+ .cm-stat-dialog{border-color:var(--dsw-alias-border-l3,#e9eaed);box-shadow:var(--dsw-elevation-prominent,0 20px 90px #0002)}.cm-stat-dialog-head>.cm-btn{border:0;border-radius:8px;background:transparent;font-size:22px;line-height:28px;width:32px;height:32px;padding:0}.cm-stat-dialog-head>.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#f0f1f4)}.cm-stat-dialog-head>.cm-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:2px}.cm-session-options{margin-top:8px;border-top:1px solid var(--cm-border);padding-top:8px}.cm-session-options>summary{color:var(--cm-muted);font-size:12px}.cm-session-options .cm-context-setting{border:0;padding:0}.cm-stat-session>.cm-stat-panel{border:0;padding:0;margin:0}.cm-stat-session .cm-stat-metrics{margin-top:0}.cm-stat-session .cm-plan{margin:20px 0}
21
21
  @container(max-width:700px){.cm-stat-shares{grid-template-columns:1fr;gap:20px}.cm-stat-step-list{columns:1}.cm-stat-turn-toggle{align-items:flex-start}.cm-stat-turn-toggle>span:last-child{max-width:60%}.cm-stat-metric{padding:10px!important}.cm-stat-metric:nth-child(2){border:0}.cm-stat-page{gap:8px}}
22
22
  @container(max-width:700px){.cm-stat-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.cm-stat-grid{grid-template-columns:1fr}.cm-stat-panel{padding:12px}.cm-stat-head{align-items:start}.cm-stat-controls label{flex:1}.cm-stat input,.cm-stat select{max-width:100%;width:100%}.cm-stat-value{font-size:23px}}
23
- `;function st(t,n){return t.key===n?{...t,error:"",failed:!1,loading:!0}:{value:null,error:"",failed:!1,loading:!0,key:n}}function de(t,n){return{value:n,error:"",failed:!1,loading:!1,key:t}}function nt(t,n,r){return{value:t.key===n?t.value:null,error:String(r?.message??r),failed:!0,loading:!1,key:n}}function ye(t){return!t.value&&(t.loading||t.failed===!0)}function ke(t,n){const r=[t.meta.dayKey,t.total?.calls,t.total?.cost,t.total?.apiCost,t.today?.calls,t.today?.cost,t.today?.apiCost].join(":"),o=JSON.stringify([t.config.prices,t.config.priceOverrides,t.config.priceMatch,t.config.planBilling,t.config.codingPlans,t.config.goQuota?.enabled,t.config.peakEnabled,t.config.peakEffectiveAt,t.config.peakWindows,t.config.peakHolidays,t.config.fetchedAt,t.config.priceSource,t.config.currency,t.config.exchangeRate,t.config.decimals,t.config.showTotalWithPlan,t.config.includeSubagentCost]);return n+":"+r+":"+o}const je=new WeakMap;function me(t,n,r){let o=je.get(t);o||je.set(t,o=new Map);const i=n+":"+JSON.stringify(r);let s=o.get(i);return s||(s={},o.set(i,s),o.size>32&&o.delete(o.keys().next().value)),s}const ue=(t,n)=>t.revision===n?t.value:null;function Ne(t,n,r,o,i=!1){const s=me(t,n,r);if(s.pending&&s.pendingRevision===o)return s.pending;if(!i&&ue(s,o)&&Date.now()-s.at<1e3)return Promise.resolve(s.value);const m=(async()=>t[n](r))().then(p=>(s.pending===m&&Object.assign(s,{value:p,revision:o,at:Date.now()}),p)).finally(()=>{s.pending===m&&(s.pending=null)});return s.pending=m,s.pendingRevision=o,m}function Le(t,n,r,o){const i=JSON.stringify(r),[s,m]=A(()=>({...de(i,ue(me(t,n,r),o)),loading:!0}));return oe(()=>{let p=!0;return m(c=>c.key===i?st(c,i):{...de(i,ue(me(t,n,r),o)),loading:!0}),Ne(t,n,JSON.parse(i),o).then(c=>{p&&m(de(i,c))},c=>{p&&m(g=>nt(g,i,c))}),()=>{p=!1}},[t,n,i,o]),s.key===i?s:{...de(i,ue(me(t,n,r),o)),loading:!0}}const X=(t,n,r={})=>e("button",{type:"button",className:"cm-stat-btn",onClick:n,...r},t),ge=t=>e("p",{className:"cm-stat-error",role:"alert"},t);function ot(t){const n=!!t.longContext&&t.contextTokens>t.longContext.aboveInputTokens,r=n?t.longContext:t.rates,o=t.components.map(i=>({...i,cost:r?i.tokens*r.input/1e6:0}));return{long:n,rates:r,parts:o,cost:o.reduce((i,s)=>i+s.cost,0)}}const we=`
23
+ `;function ie(e,n){return e.key===n?{...e,error:"",failed:!1,loading:!0}:{value:null,error:"",failed:!1,loading:!0,key:n}}function ft(e,n){return{value:n,error:"",failed:!1,loading:!1,key:e}}function pe(e,n,l){return{value:e.key===n?e.value:null,error:String(l?.message??l),failed:!0,loading:!1,key:n}}function Pt(e){return!e.value&&(e.loading||e.failed===!0)}function Rt(e,n){const l=[e.meta.dayKey,e.total?.calls,e.total?.cost,e.total?.apiCost,e.today?.calls,e.today?.cost,e.today?.apiCost].join(":"),o=JSON.stringify([e.config.prices,e.config.priceOverrides,e.config.priceMatch,e.config.planBilling,e.config.codingPlans,e.config.goQuota?.enabled,e.config.peakEnabled,e.config.peakEffectiveAt,e.config.peakWindows,e.config.peakHolidays,e.config.fetchedAt,e.config.priceSource,e.config.currency,e.config.exchangeRate,e.config.decimals,e.config.showTotalWithPlan,e.config.includeSubagentCost]);return n+":"+l+":"+o}const Ft=new WeakMap;function bt(e,n,l){let o=Ft.get(e);o||Ft.set(e,o=new Map);const c=n+":"+JSON.stringify(l);let a=o.get(c);return a||(a={},o.set(c,a),o.size>32&&o.delete(o.keys().next().value)),a}const ht=(e,n)=>e.revision===n?e.value:null;function Mt(e,n,l,o,c=!1){const a=bt(e,n,l);if(a.pending&&a.pendingRevision===o)return a.pending;if(!c&&ht(a,o)&&Date.now()-a.at<1e3)return Promise.resolve(a.value);const p=(async()=>e[n](l))().then(u=>(a.pending===p&&Object.assign(a,{value:u,revision:o,at:Date.now()}),u)).finally(()=>{a.pending===p&&(a.pending=null)});return a.pending=p,a.pendingRevision=o,p}function vt(e,n,l,o){const c=JSON.stringify(l),[a,p]=j(()=>({...ft(c,ht(bt(e,n,l),o)),loading:!0}));return nt(()=>{let u=!0;return p(r=>r.key===c?ie(r,c):{...ft(c,ht(bt(e,n,l),o)),loading:!0}),Mt(e,n,JSON.parse(c),o).then(r=>{u&&p(ft(c,r))},r=>{u&&p(b=>pe(b,c,r))}),()=>{u=!1}},[e,n,c,o]),a.key===c?a:{...ft(c,ht(bt(e,n,l),o)),loading:!0}}const Y=(e,n,l={})=>t("button",{type:"button",className:"cm-stat-btn",onClick:n,...l},e),ot=e=>t("p",{className:"cm-stat-error",role:"alert"},e);function me(e){const n=!!e.longContext&&e.contextTokens>e.longContext.aboveInputTokens,l=n?e.longContext:e.rates,o=e.components.map(c=>({...c,cost:l?c.tokens*l.input/1e6:0}));return{long:n,rates:l,parts:o,cost:o.reduce((c,a)=>c+a.cost,0)}}const jt=`
24
24
  .cm-plan{font:13px/1.55 var(--ds-font-family-sans,system-ui);color:var(--dsw-alias-label-primary);min-width:0;container-type:inline-size;--cmp-border:var(--dsw-alias-border-l3,#e5e7eb);--cmp-muted:var(--dsw-alias-label-secondary,#737780);--cmp-bg:var(--dsw-alias-bg-layer-2,#f6f7f9);--cmp-accent:var(--dsw-alias-state-business-primary,#4d6bfe)}
25
25
  .cm-plan *{box-sizing:border-box}.cm-plan h3,.cm-plan p{margin:0}.cm-plan h3{font-size:14px;font-weight:500}.cm-plan-head{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}.cm-plan-sub{font-size:11px;color:var(--cmp-muted);overflow-wrap:anywhere}.cm-plan button,.cm-plan input{font:inherit;color:inherit}.cm-plan button{border:.5px solid var(--cmp-border);border-radius:var(--dsw-radius-sm,8px);padding:4px 9px;background:transparent;cursor:pointer}.cm-plan button:hover{background:var(--cmp-bg)}.cm-plan button:disabled{opacity:.5;cursor:default}.cm-plan input:focus-visible,.cm-plan button:focus-visible{outline:2px solid var(--cmp-accent);outline-offset:2px}
26
26
  .cm-plan-summary{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;margin:14px 0;padding:14px 0;border-block:1px solid var(--cmp-border)}.cm-plan-amount{font-size:clamp(16px,4cqw,24px);font-variant-numeric:tabular-nums;font-weight:500;overflow-wrap:anywhere}.cm-plan-stack{display:flex;height:10px;overflow:hidden;border-radius:4px;background:var(--cmp-bg);margin-bottom:12px}.cm-plan-stack span{min-width:0}
@@ -30,19 +30,30 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
30
30
  @container(max-width:540px){.cm-cost-chart{grid-template-columns:128px minmax(0,1fr);gap:10px 12px}.cm-cost-donut{width:128px;height:128px}.cm-cost-center{inset:32px 18px}.cm-cost-center b{font-size:21px}.cm-cost-legend{grid-template-columns:1fr;gap:1px}.cm-plan .cm-cost-key{padding:4px;font-size:11px}}
31
31
  @container(max-width:320px){.cm-cost-chart{grid-template-columns:1fr}.cm-cost-donut{margin:auto}.cm-cost-legend{grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 8px}}
32
32
  @container(max-width:420px){.cm-plan-summary{gap:8px;grid-template-columns:1fr 1fr}.cm-plan-part-head{align-items:start;flex-wrap:wrap}}
33
- @media(prefers-reduced-motion:reduce){.cm-cost-arc{transition:none}}`,G=["#627bff","#f6b64b","#30c89c","#ad78f5","#fb8c6f","#42b4f5","#24bdc9","#a0aec5"].map((t,n)=>"var(--cm-chart-"+n+","+t+")"),ct={input:0,cacheRead:6,cacheWrite:1,output:5,reasoning:3},Nt=`
33
+ @media(prefers-reduced-motion:reduce){.cm-cost-arc{transition:none}}`,G=["#627bff","#f6b64b","#30c89c","#ad78f5","#fb8c6f","#42b4f5","#24bdc9","#a0aec5"].map((e,n)=>"var(--cm-chart-"+n+","+e+")"),Ot={input:0,cacheRead:6,cacheWrite:1,output:5,reasoning:3},Re=`
34
34
  .cm-context-compact>.cm-plan-head{margin-bottom:10px}.cm-context-compact .cm-context-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.cm-context-compact .cm-context-current,.cm-context-compact .cm-plan-last{min-width:0;container-type:inline-size}.cm-context-compact .cm-plan-last{border:0;border-left:1px solid var(--cmp-border);padding:0 0 0 18px;margin:0}.cm-context-compact .cm-plan-summary{margin:10px 0;padding:8px 0;gap:8px}.cm-context-compact .cm-plan-amount{font-size:18px}.cm-context-compact .cm-cost-chart{margin-top:10px;gap:6px 10px}.cm-context-compact .cm-cost-legend{grid-template-columns:1fr}.cm-context-compact .cm-plan-sub{font-size:10px}.cm-context-compact .cm-plan-total{margin-top:6px!important}.cm-context-compact .cm-plan-note{grid-column:1/-1}
35
35
  @container(max-width:740px){.cm-context-compact .cm-context-columns{grid-template-columns:1fr}.cm-context-compact .cm-plan-last{border:0;border-top:1px solid var(--cmp-border);padding:12px 0 0}}
36
36
 
37
- .cm-session-tabs{display:flex;gap:4px;border-bottom:1px solid var(--cm-border);padding-bottom:8px;margin-bottom:10px}.cm-session-tabs .cm-stat-btn{border-color:transparent;padding:5px 12px;color:var(--cm-muted)}.cm-session-tabs .cm-stat-btn[aria-pressed=true]{background:var(--cm-surface);color:var(--cm-accent);box-shadow:none}.cm-stat-session .cm-stat-metrics{margin:4px 0 14px;padding:10px 0}.cm-stat-session .cm-stat-value{font-size:22px;margin:2px 0}.cm-stat-session .cm-stat-panel-head{margin-bottom:4px}.cm-stat-session .cm-spend{margin:10px 0}.cm-stat-session .cm-stat-chart{height:90px}.cm-stat-secondary{font-size:12px;color:var(--cm-muted)}.cm-stat-secondary>summary{padding:8px 0}.cm-stat-session .cm-spend-card{padding:14px}.cm-stat-session .cm-spend-card .cm-cost-chart{margin-top:8px;gap:6px 12px}.cm-stat-session .cm-spend-card .cm-cost-key{padding:3px 4px}.cm-stat-session .cm-cache-compare{padding-top:10px;margin-top:10px}.cm-stat-session .cm-cache-compare h3{margin-bottom:6px}.cm-stat-session .cm-cache-compare>div{margin-top:6px}.cm-stat-session .cm-cost-inspect{font-size:10px}.cm-stat-session .cm-cost-key-amount{margin-top:1px}
37
+ .cm-stat-session{position:relative}.cm-stat-session>.cm-stat-panel-head{position:absolute;right:0;top:0;z-index:1}.cm-stat-session>.cm-stat-panel-head>p{display:none}.cm-session-tabs{padding-right:65px;display:flex;gap:4px;border-bottom:1px solid var(--cm-border);padding-bottom:8px;margin-bottom:10px}.cm-session-tabs .cm-stat-btn{border-color:transparent;padding:5px 12px;color:var(--cm-muted)}.cm-session-tabs .cm-stat-btn[aria-pressed=true]{background:var(--cm-surface);color:var(--cm-accent);box-shadow:none}.cm-stat-session .cm-stat-metrics{margin:4px 0 14px;padding:10px 0}.cm-stat-session .cm-stat-value{font-size:22px;margin:2px 0}.cm-stat-session .cm-stat-panel-head{margin-bottom:4px}.cm-stat-session .cm-spend{margin:10px 0}.cm-stat-session .cm-stat-chart{height:90px}.cm-stat-secondary{font-size:12px;color:var(--cm-muted)}.cm-stat-secondary>summary{padding:8px 0}.cm-stat-session .cm-spend-card{padding:14px}.cm-stat-session .cm-spend-card .cm-cost-chart{margin-top:8px;gap:6px 12px}.cm-stat-session .cm-spend-card .cm-cost-key{padding:3px 4px}.cm-stat-session .cm-cache-compare{padding-top:10px;margin-top:10px}.cm-stat-session .cm-cache-compare h3{margin-bottom:6px}.cm-stat-session .cm-cache-compare>div{margin-top:6px}.cm-stat-session .cm-cost-inspect{font-size:10px}.cm-stat-session .cm-cost-key-amount{margin-top:1px}
38
38
 
39
39
  .cm-spend{margin:20px 0}.cm-spend-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.cm-spend-card{border:1px solid var(--cmp-border);border-radius:12px;padding:18px;container-type:inline-size;min-width:0}.cm-spend-card .cm-cost-legend{grid-template-columns:1fr}.cm-spend-card .cm-cost-chart{margin-bottom:0}.cm-spend-card h3{font-weight:500}.cm-cache-compare{border-top:1px solid var(--cmp-border);padding-top:16px;margin-top:20px}.cm-cache-compare h3{font-size:12px;margin-bottom:12px}.cm-cache-compare>div{margin-top:10px}.cm-spend>.cm-plan-sub{margin-top:10px}.cm-cost-key-amount{display:block;font-size:10px;font-weight:400;margin-top:3px;color:var(--cmp-muted);font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.cm-cost-key-label{overflow-wrap:anywhere}.cm-call-share{display:inline-block;border-radius:5px;padding:1px 7px;margin-left:8px;background:var(--cm-surface);color:var(--cm-accent);font-size:11px;font-variant-numeric:tabular-nums}.cm-plan .cm-cost-key[data-active=true]{background:var(--dsw-alias-interactive-bg-hover,#f2f5fc)}
40
40
  @container(max-width:740px){.cm-spend-grid{grid-template-columns:1fr}}
41
- `;function fe({rows:t,total:n,label:r,text:o,onSelect:i,amounts:s=!1}){const[m,p]=A(""),[c,g]=A(""),f=t.find(u=>u.key===(m||c)),y=u=>u.unpriced&&u.value===0?"—":n>0?H(u.value,n):"—",h=u=>u.meta??u.tokens.toLocaleString()+" tokens",v=u=>({"data-active":f?.key===u.key,onMouseEnter:()=>p(u.key),onMouseLeave:()=>p(""),onFocus:S=>{S.currentTarget.matches(":focus-visible")&&g(u.key)},onBlur:()=>g(""),onPointerDown:()=>g(""),onClick:()=>i?.(u),onKeyDown:S=>{S.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(S.key)&&(S.preventDefault(),i?.(u))}});let w=0;const N=t.filter(u=>u.value>0&&n>0).map(u=>{const S=Math.min(100,u.value/n*100),j=w;w+=S;const T=Math.min(.8,S*.15);return e("circle",{...v(u),key:u.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":u.label+" · "+y(u)+" · "+u.amount+" · "+h(u),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:u.color,strokeWidth:18,strokeDasharray:S-T+" "+(100-S+T),strokeDashoffset:-j-T/2,transform:"rotate(-90 78 78)"})});return e("div",{className:"cm-cost-chart","aria-label":r,"data-inspecting":!!f,onMouseLeave:()=>p("")},e("div",{className:"cm-cost-donut"},e("svg",{viewBox:"0 0 156 156","aria-label":r},e("circle",{cx:78,cy:78,r:61,fill:"none",stroke:"var(--cmp-bg)",strokeWidth:16}),...N),e("div",{className:"cm-cost-center","aria-hidden":!0},e("b",null,f?y(f):n>0?"100%":"—"),e("small",null,f?.label??r))),e("div",{className:"cm-cost-legend"},...t.map(u=>e("button",{...v(u),type:"button",key:u.key,className:"cm-cost-key","aria-label":u.label+" "+y(u)},e("i",{className:"cm-plan-dot",style:{background:u.color}}),e("span",{className:"cm-cost-key-label"},u.label,s?e("small",{className:"cm-cost-key-amount"},u.amount):null),e("span",{className:"cm-cost-key-share"},y(u))))),e("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},f?e(se,null,e("strong",null,f.label),e("span",null,h(f)),e("strong",null,f.amount)):i?o("悬停查看占比,点击单次调用查看明细","Hover for shares; select an individual call for details"):o("悬停图表或图例,查看费用与 Token","Hover or focus the chart or legend for costs and tokens")))}function Ce({api:t,sessionId:n,revision:r="",text:o=(p,c)=>c,money:i=p=>"$"+p.toLocaleString("en-US",{maximumFractionDigits:6}),integrated:s=!1,compact:m=!1}){const p=ce(null),c=ce(()=>{}),g=ce(r);g.current=r;const[f,y]=A(()=>({value:ue(me(t,"getContextCosts",{sessionId:n}),r),error:"",busy:!0}));oe(()=>{let d=!0,K=!1,C=typeof IntersectionObserver!="function";const M=async(q=!1)=>{if(!(!d||K||!C||document.hidden)){K=!0,y(E=>({...E,busy:!0}));try{const E=await Ne(t,"getContextCosts",{sessionId:n},g.current,q===!0);if(E.sessionId!==n)throw new Error("Context costs session mismatch");d&&y({value:E,error:"",busy:!1})}catch{d&&y(E=>({...E,busy:!1,error:o("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{K=!1}}};c.current=M;const Z=typeof IntersectionObserver=="function"?new IntersectionObserver(q=>{C=q.some(E=>E.isIntersecting),C&&M()}):null;p.current&&Z?.observe(p.current),M();const z=setInterval(M,1e4);return document.addEventListener("visibilitychange",M),()=>{d=!1,clearInterval(z),Z?.disconnect(),document.removeEventListener("visibilitychange",M)}},[t,n]),oe(()=>{const d=setTimeout(()=>c.current(),250);return()=>clearTimeout(d)},[r]);const h=f.value?.sessionId===n?f.value:null,v=e("div",{className:"cm-plan-head"},e("h3",null,o("上下文费用构成","Context cost breakdown")),e("div",null,s&&t.disableIntegration?e("button",{type:"button",onClick:t.disableIntegration},o("关闭联动","Turn off integration")):null,e("button",{type:"button",onClick:()=>c.current(!0),disabled:f.busy},o("刷新","Refresh")))),w=d=>e("section",{className:"cm-plan"+(m?" cm-context-compact":""),ref:p,"aria-label":o("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},e("style",null,we),v,s?e("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,f.error?e("p",{role:"alert",className:"cm-plan-error"},f.error):null,d);if(!h||h.status!=="ready")return w(e("p",{className:"cm-plan-note"},h?h.status==="route-unavailable"?o("完成一次请求后,可显示该模型的上下文费用。","Complete a request to see context costs at that model’s rates."):h.status==="session-unavailable"?o("打开此会话后可读取当前上下文。","Open this conversation to read its current context."):o("当前宿主未提供上下文测量;已发生费用仍可在费用明细中查看。","Context measurement is unavailable on this host. Recorded costs remain available in billing details."):f.error?o("点击刷新重试。","Select Refresh to retry."):o("正在读取当前上下文…","Reading current context…")));const N=ot(h),u=h.priced&&!!N.rates,S=[o("系统提示","System prompt"),o("工具定义","Tool schemas"),o("用户输入","User messages"),o("注入内容","Injected context"),o("技能","Skills"),o("历史回复","Prior replies"),o("工具结果","Tool results"),o("其他","Other")],j=d=>Math.round(d).toLocaleString(),T=d=>u?"≈ "+i(d):o("未定价","Unpriced"),k=h.lastCall,L={input:o("非缓存输入","Uncached input"),cacheRead:o("缓存读取","Cache reads"),cacheWrite:o("缓存写入","Cache writes"),output:o("输出(含推理 Token)","Output (including reasoning tokens)"),reasoning:o("单独推理费用","Separate reasoning fees")};return w(e("div",{className:"cm-context-columns"},e("div",{className:"cm-context-current"},e("p",{className:"cm-plan-sub"},h.provider+" / "+h.model),e("div",{className:"cm-plan-summary"},e("div",null,e("div",{className:"cm-plan-sub"},o("当前上下文","Current context")),e("div",{className:"cm-plan-amount"},"≈ "+j(h.contextTokens)+" tokens")),e("div",null,e("div",{className:"cm-plan-sub"},o("输入费用参考","Input cost reference")),e("div",{className:"cm-plan-amount"},T(N.cost)))),e("p",{className:"cm-plan-sub",style:{marginBottom:12}},o("按非缓存输入单价估算,未计缓存折扣;不代表已发生费用。","Estimated at uncached input rates, before cache discounts; not a charge already incurred.")),e(fe,{rows:N.parts.filter(d=>d.tokens>0).map(d=>({key:d.key,label:S[ve.indexOf(d.key)],tokens:Math.round(d.tokens),value:u?d.cost:d.tokens,amount:T(d.cost),color:G[ve.indexOf(d.key)]})),total:u?N.cost:h.contextTokens,label:u?o("参考费用占比","Reference cost share"):o("Token 占比","Token share"),text:o}),e("details",{className:"cm-cost-table"},e("summary",null,o("展开各部分明细","Show component details")),e("ul",{className:"cm-plan-parts"},...N.parts.filter(d=>d.tokens>0).map(d=>{const K=ve.indexOf(d.key);return e("li",{key:d.key},e("div",{className:"cm-plan-part-head"},e("span",null,e("i",{className:"cm-plan-dot",style:{background:G[K]}}),S[K]),e("span",null,T(d.cost))),e("div",{className:"cm-plan-part-meta"},e("span",null,"≈ "+j(d.tokens)+" tokens"),e("span",null,u?H(d.cost,N.cost):"—")))})))),k?e("section",{className:"cm-plan-last"},e("h3",null,o("最近一次调用 · 用量计费","Latest call · usage-based costs")),e("p",{className:"cm-plan-sub"},k.provider+" / "+k.model+" · "+new Date(k.atMs).toLocaleString()),e(fe,{rows:k.rows.filter(d=>d.tokens>0&&(d.bucket!=="reasoning"||d.rate>0)).map(d=>({key:d.bucket,label:L[d.bucket]??d.bucket,tokens:d.tokens,value:d.cost,amount:k.priced?i(d.cost):o("未定价","Unpriced"),color:G[ct[d.bucket]??7]})),total:k.priced?k.cost:0,label:o("费用占比","Cost share"),text:o}),e("details",{className:"cm-cost-table"},e("summary",null,o("展开调用明细","Show call details")),e("ul",{className:"cm-plan-parts",style:{marginTop:12}},...k.rows.filter(d=>d.bucket!=="reasoning"||d.rate>0).map(d=>e("li",{key:d.bucket},e("div",{className:"cm-plan-part-head"},e("span",null,L[d.bucket]??d.bucket),e("span",null,k.priced?i(d.cost):o("未定价","Unpriced"))),e("div",{className:"cm-plan-part-meta"},e("span",null,j(d.tokens)+" tokens"),e("span",null,k.priced?H(d.cost,k.cost):"—")))))),e("p",{className:"cm-plan-total"},o("合计 ","Total ")+(k.priced?i(k.cost):o("未定价","Unpriced"))+(k.plan?o(" · Plan 的 API 等值"," · Plan API equivalent"):"")),e("p",{className:"cm-plan-sub"},o("基于提供商返回用量与调用时段的配置费率;与上方上下文参考费用不相加。","Uses reported usage and configured rates for the call time; do not add it to the context reference above."))):e("p",{className:"cm-plan-note"},o("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),u?null:e("p",{className:"cm-plan-note"},o("此模型没有可用单价;未知金额不按零计算。请在费用设置中配置价格。","This model has no available rates; unknown costs are not zero. Configure prices in Cost settings.")),h.basis==="plan"?e("p",{className:"cm-plan-note"},o("当前为 Plan:参考金额是 API 等值,不代表额外扣款。","This is a Plan route: reference amounts are API equivalents, not extra charges.")):null))}const qe=[["conversation.view","id","context"],["sidebar.right.pane.tab","key","dsh-context"],["conversation.input.overlay","id","context-modal"]];function rt(t,n,r,o,i){const s=t.get("slots");if(!["entries","subscribe","register","entriesOfSlot"].every(f=>typeof s?.[f]=="function"))return()=>{};const m=[],p=new Map;let c=!0;function g(f){return function(h){i&&he.useSyncExternalStore(i.subscribe,r);const v=ce(null),[w,N]=A(null),u=h.useProjection?.("contextBreakdown"),S=h.useProjection?.("tokenUsage"),j=JSON.stringify([u,S]);oe(()=>{if(!v.current||typeof MutationObserver!="function")return;const k=document.createElement("div");k.className="cm-plan-host",k.dataset.cmContextCosts="";const L=()=>{const K=v.current?.querySelector("[data-lc-current]");if(!K){k.remove(),N(null);return}k.parentElement!==K&&(K.appendChild(k),N(k))},d=new MutationObserver(L);return d.observe(v.current,{childList:!0,subtree:!0}),L(),()=>{d.disconnect(),k.remove()}},[h.sessionId]);const T=(k,L)=>r()==="en"?L:k;return e("div",{ref:v,style:{display:"contents"},"data-cm-context-bridge":h.sessionId},e(f,h),w&&h.sessionId?o(e(Ce,{key:h.sessionId,api:n,sessionId:h.sessionId,integrated:!0,text:T,revision:j}),w):null)}}for(const[f,y,h]of qe){let v=!1;const w=()=>{if(!(!c||v)){v=!0;try{const N=s.entries(f).filter(L=>L.locale==="dsh-context"&&L.options[y]===h&&L.registrant!=="dsh-cost-meter-context-bridge"),u=N.length===1?N[0]:null,S=p.get(f);if(S?.original===u&&s.entries(f).some(L=>L.component===S.component)||(S?.dispose(),p.delete(f),!u||u.children||u.store||typeof u.component!="function")||s.entriesOfSlot(f).find(L=>L.options[y]===h)!==u)return;const T=g(u.component),k=s.register({name:f,...u.options,inject:u.inject,locale:u.locale,priority:(u.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},T);p.set(f,{original:u,component:T,dispose:k})}finally{v=!1}}};m.push(s.subscribe(f,w)),w()}return()=>{c=!1;for(const f of m)f();for(const f of p.values())f.dispose();p.clear()}}const Be="dsh-cost-meter:context-intro-seen",it=()=>{try{return localStorage.getItem(Be)==="1"}catch{return!1}},wt=()=>{try{localStorage.setItem(Be,"1")}catch{}};function lt(t,n,r,o,i){const s=t.get("slots"),m=new Set,p=[];let c=!0,g=null,f=[],y=!1,h=0,v=it(),w=null,N=0,u=Promise.resolve(),S={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const j=["entries","entriesOfSlot","register","subscribe"].every(z=>typeof s?.[z]=="function"),T=z=>{S={...S,...z};for(const q of m)q()},k=()=>{if(!c)return;const z=r.getSnapshot().state?.config,q=j&&S.peer.compatible&&f.length>0,E=q&&!S.saving&&(w??z?.contextCostsEnabled)===!0;if(!E&&g){const F=g;g=null,F()}E&&!g&&(g=rt(t,{...n,disableIntegration:()=>{K(!1)}},o,i,r));const Q=S.prompt&&(S.manual||q);T({available:q,enabled:E,prompt:Q||!!(z&&q&&!z.contextCostsPromptSeen&&!z.contextCostsEnabled&&!v)})},L=async(z=!1)=>{if(!c||!j)return;const q=qe.flatMap(([Q,F,_])=>s.entries(Q).filter(R=>R.locale==="dsh-context"&&R.options[F]===_&&R.registrant!=="dsh-cost-meter-context-bridge"&&!R.children&&!R.store));if(!z&&y&&q.length===f.length&&q.every((Q,F)=>Q===f[F]))return;f=q,y=!0;const E=++h;if(T({peer:{version:"",compatible:!1,reason:q.length?"unavailable":"missing"}}),k(),!!q.length)try{const Q=await n.getContextIntegration();c&&E===h&&(T({peer:Q}),k())}catch{c&&E===h&&k()}};function d(){v=!0,wt()}async function K(z,q=!1){if(!c||z&&!S.available&&!q)return;const E=++N;d(),w=z,T({prompt:!1,manual:!1,saving:!0,error:""}),k();const Q=u.catch(()=>{}).then(()=>n.saveIntegration(z));u=Q;try{await Q,c&&E===N&&(w=null,T({saving:!1}),k())}catch{c&&E===N&&(w=!1,T({saving:!1,error:"save"}),k())}}if(p.push(r.subscribe(k)),j)for(const[z]of qe)p.push(s.subscribe(z,()=>{L()}));const C=()=>{document.hidden||L(!0)};document.addEventListener("visibilitychange",C);const M=z=>{z.key===Be&&z.newValue==="1"&&!v&&(v=!0,T({prompt:!1}),k())};return window.addEventListener("storage",M),L(),k(),{getSnapshot:()=>S,subscribe:z=>(m.add(z),()=>m.delete(z)),choose:K,dismiss:()=>K(S.manual?r.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:d,preview:()=>T({prompt:!0,manual:!0}),refresh:()=>{L(!0)},dispose:()=>{c=!1,++h;for(const z of p)z();g?.(),m.clear(),document.removeEventListener("visibilitychange",C),window.removeEventListener("storage",M)}}}const pt=`
41
+ `;function lt({rows:e,total:n,label:l,text:o,onSelect:c,amounts:a=!1}){const[p,u]=j(""),[r,b]=j(""),x=e.find(g=>g.key===(p||r)),m=g=>g.unpriced&&g.value===0?"—":n>0?_(g.value,n):"—",I=g=>g.meta??g.tokens.toLocaleString()+" tokens",d=g=>({"data-active":x?.key===g.key,onMouseEnter:()=>u(g.key),onMouseLeave:()=>u(""),onFocus:P=>{P.currentTarget.matches(":focus-visible")&&b(g.key)},onBlur:()=>b(""),onPointerDown:()=>b(""),onClick:()=>c?.(g),onKeyDown:P=>{P.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(P.key)&&(P.preventDefault(),c?.(g))}});let z=0;const w=e.filter(g=>g.value>0&&n>0).map(g=>{const P=Math.min(100,g.value/n*100),Q=z;z+=P;const O=Math.min(.8,P*.15);return t("circle",{...d(g),key:g.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":g.label+" · "+m(g)+" · "+g.amount+" · "+I(g),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:g.color,strokeWidth:18,strokeDasharray:P-O+" "+(100-P+O),strokeDashoffset:-Q-O/2,transform:"rotate(-90 78 78)"})});return t("div",{className:"cm-cost-chart","aria-label":l,"data-inspecting":!!x,onMouseLeave:()=>u("")},t("div",{className:"cm-cost-donut"},t("svg",{viewBox:"0 0 156 156","aria-label":l},t("circle",{cx:78,cy:78,r:61,fill:"none",stroke:"var(--cmp-bg)",strokeWidth:16}),...w),t("div",{className:"cm-cost-center","aria-hidden":!0},t("b",null,x?m(x):n>0?"100%":"—"),t("small",null,x?.label??l))),t("div",{className:"cm-cost-legend"},...e.map(g=>t("button",{...d(g),type:"button",key:g.key,className:"cm-cost-key","aria-label":g.label+" "+m(g)},t("i",{className:"cm-plan-dot",style:{background:g.color}}),t("span",{className:"cm-cost-key-label"},g.label,a?t("small",{className:"cm-cost-key-amount"},g.amount):null),t("span",{className:"cm-cost-key-share"},m(g))))),t("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},x?t(tt,null,t("strong",null,x.label),t("span",null,I(x)),t("strong",null,x.amount)):null))}function Et({api:e,sessionId:n,revision:l="",text:o=(r,b)=>b,money:c=r=>"$"+r.toLocaleString("en-US",{maximumFractionDigits:6}),integrated:a=!1,compact:p=!1,expanded:u=!1}){const r=dt(null),b=dt(()=>{}),x=dt(l);x.current=l;const[m,I]=j(()=>({value:ht(bt(e,"getContextCosts",{sessionId:n}),l),error:"",busy:!0}));nt(()=>{let v=!0,F=!1,H=typeof IntersectionObserver!="function";const R=async(A=!1)=>{if(!(!v||F||!H||document.hidden)){F=!0,I(W=>({...W,busy:!0}));try{const W=await Mt(e,"getContextCosts",{sessionId:n},x.current,A===!0);if(W.sessionId!==n)throw new Error("Context costs session mismatch");v&&I({value:W,error:"",busy:!1})}catch{v&&I(W=>({...W,busy:!1,error:o("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{F=!1}}};b.current=R;const S=typeof IntersectionObserver=="function"?new IntersectionObserver(A=>{H=A.some(W=>W.isIntersecting),H&&R()}):null;r.current&&S?.observe(r.current),R();const E=setInterval(R,1e4);return document.addEventListener("visibilitychange",R),()=>{v=!1,clearInterval(E),S?.disconnect(),document.removeEventListener("visibilitychange",R)}},[e,n]),nt(()=>{const v=setTimeout(()=>b.current(),250);return()=>clearTimeout(v)},[l]);const d=m.value?.sessionId===n?m.value:null,z=t("div",{className:"cm-plan-head"},t("h3",null,o("上下文费用构成","Context cost breakdown")),t("div",null,a&&e.disableIntegration?t("button",{type:"button",onClick:e.disableIntegration},o("关闭联动","Turn off integration")):null,t("button",{type:"button",onClick:()=>b.current(!0),disabled:m.busy},o("刷新","Refresh")))),w=v=>t("section",{className:"cm-plan"+(p?" cm-context-compact":""),ref:r,"aria-label":o("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},t("style",null,jt),z,a?t("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,m.error?t("p",{role:"alert",className:"cm-plan-error"},m.error):null,v);if(!d||d.status!=="ready")return w(t("p",{className:"cm-plan-note"},d?d.status==="route-unavailable"?o("完成一次请求后,可显示该模型的上下文费用。","Complete a request to see context costs at that model’s rates."):d.status==="session-unavailable"?o("打开此会话后可读取当前上下文。","Open this conversation to read its current context."):o("当前宿主未提供上下文测量;已发生费用仍可在费用明细中查看。","Context measurement is unavailable on this host. Recorded costs remain available in billing details."):m.error?o("点击刷新重试。","Select Refresh to retry."):o("正在读取当前上下文…","Reading current context…")));const g=me(d),P=d.priced&&!!g.rates,Q=[o("系统提示","System prompt"),o("工具定义","Tool schemas"),o("用户输入","User messages"),o("注入内容","Injected context"),o("技能","Skills"),o("历史回复","Prior replies"),o("工具结果","Tool results"),o("其他","Other")],O=v=>Math.round(v).toLocaleString(),k=v=>P?"≈ "+c(v):o("未定价","Unpriced"),T=d.lastCall,V={input:o("非缓存输入","Uncached input"),cacheRead:o("缓存读取","Cache reads"),cacheWrite:o("缓存写入","Cache writes"),output:o("输出(含推理 Token)","Output (including reasoning tokens)"),reasoning:o("单独推理费用","Separate reasoning fees")};return w(t("div",{className:"cm-context-columns"},t("div",{className:"cm-context-current"},t("p",{className:"cm-plan-sub"},d.provider+" / "+d.model),t("div",{className:"cm-plan-summary"},t("div",null,t("div",{className:"cm-plan-sub"},o("当前上下文","Current context")),t("div",{className:"cm-plan-amount"},"≈ "+O(d.contextTokens)+" tokens")),t("div",null,t("div",{className:"cm-plan-sub"},d.basis==="plan"?o("Plan 输入等值","Plan input equivalent"):o("非缓存输入估算","Uncached input estimate")),t("div",{className:"cm-plan-amount"},k(g.cost)))),t(lt,{rows:g.parts.filter(v=>v.tokens>0).map(v=>({key:v.key,label:Q[It.indexOf(v.key)],tokens:Math.round(v.tokens),value:P?v.cost:v.tokens,amount:k(v.cost),color:G[It.indexOf(v.key)]})),total:P?g.cost:d.contextTokens,label:P?o("参考费用占比","Reference cost share"):o("Token 占比","Token share"),text:o}),t("details",{className:"cm-cost-table",open:u},t("summary",null,o("各部分计费","Component costs")),t("ul",{className:"cm-plan-parts"},...g.parts.filter(v=>v.tokens>0).map(v=>{const F=It.indexOf(v.key);return t("li",{key:v.key},t("div",{className:"cm-plan-part-head"},t("span",null,t("i",{className:"cm-plan-dot",style:{background:G[F]}}),Q[F]),t("span",null,k(v.cost))),t("div",{className:"cm-plan-part-meta"},t("span",null,"≈ "+O(v.tokens)+" tokens"),t("span",null,P?_(v.cost,g.cost):"—")))})))),T?t("section",{className:"cm-plan-last"},t("h3",null,o("最近一次调用 · 用量计费","Latest call · usage-based costs")),t("p",{className:"cm-plan-sub"},T.provider+" / "+T.model+" · "+new Date(T.atMs).toLocaleString()),t(lt,{rows:T.rows.filter(v=>v.tokens>0&&(v.bucket!=="reasoning"||v.rate>0)).map(v=>({key:v.bucket,label:V[v.bucket]??v.bucket,tokens:v.tokens,value:v.cost,amount:T.priced?c(v.cost):o("未定价","Unpriced"),color:G[Ot[v.bucket]??7]})),total:T.priced?T.cost:0,label:o("费用占比","Cost share"),text:o}),t("details",{className:"cm-cost-table",open:u},t("summary",null,o("调用计费明细","Call billing details")),t("ul",{className:"cm-plan-parts",style:{marginTop:12}},...T.rows.filter(v=>v.bucket!=="reasoning"||v.rate>0).map(v=>t("li",{key:v.bucket},t("div",{className:"cm-plan-part-head"},t("span",null,V[v.bucket]??v.bucket),t("span",null,T.priced?c(v.cost):o("未定价","Unpriced"))),t("div",{className:"cm-plan-part-meta"},t("span",null,O(v.tokens)+" tokens"),t("span",null,T.priced?_(v.cost,T.cost):"—")))))),t("p",{className:"cm-plan-total"},o("合计 ","Total ")+(T.priced?c(T.cost):o("未定价","Unpriced"))+(T.plan?o(" · Plan 的 API 等值"," · Plan API equivalent"):""))):t("p",{className:"cm-plan-note"},o("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),P?null:t("p",{className:"cm-plan-note"},o("未配置模型单价","Model rates not configured"))))}const Kt=[["conversation.view","id","context"],["sidebar.right.pane.tab","key","dsh-context"],["conversation.input.overlay","id","context-modal"]];function de(e,n,l,o,c){const a=e.get("slots");if(!["entries","subscribe","register","entriesOfSlot"].every(x=>typeof a?.[x]=="function"))return()=>{};const p=[],u=new Map;let r=!0;function b(x){return function(I){c&&wt.useSyncExternalStore(c.subscribe,l);const d=dt(null),[z,w]=j(null),g=I.useProjection?.("contextBreakdown"),P=I.useProjection?.("tokenUsage"),Q=JSON.stringify([g,P]);nt(()=>{if(!d.current||typeof MutationObserver!="function")return;const k=document.createElement("div");k.className="cm-plan-host",k.dataset.cmContextCosts="";const T=()=>{const v=d.current?.querySelector("[data-lc-current]");if(!v){k.remove(),w(null);return}k.parentElement!==v&&(v.appendChild(k),w(k))},V=new MutationObserver(T);return V.observe(d.current,{childList:!0,subtree:!0}),T(),()=>{V.disconnect(),k.remove()}},[I.sessionId]);const O=(k,T)=>l()==="en"?T:k;return t("div",{ref:d,style:{display:"contents"},"data-cm-context-bridge":I.sessionId},t(x,I),z&&I.sessionId?o(t(Et,{key:I.sessionId,api:n,sessionId:I.sessionId,integrated:!0,text:O,revision:Q}),z):null)}}for(const[x,m,I]of Kt){let d=!1;const z=()=>{if(!(!r||d)){d=!0;try{const w=a.entries(x).filter(T=>T.locale==="dsh-context"&&T.options[m]===I&&T.registrant!=="dsh-cost-meter-context-bridge"),g=w.length===1?w[0]:null,P=u.get(x);if(P?.original===g&&a.entries(x).some(T=>T.component===P.component)||(P?.dispose(),u.delete(x),!g||g.children||g.store||typeof g.component!="function")||a.entriesOfSlot(x).find(T=>T.options[m]===I)!==g)return;const O=b(g.component),k=a.register({name:x,...g.options,inject:g.inject,locale:g.locale,priority:(g.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},O);u.set(x,{original:g,component:O,dispose:k})}finally{d=!1}}};p.push(a.subscribe(x,z)),z()}return()=>{r=!1;for(const x of p)x();for(const x of u.values())x.dispose();u.clear()}}const $t="dsh-cost-meter:context-intro-seen",ue=()=>{try{return localStorage.getItem($t)==="1"}catch{return!1}},Me=()=>{try{localStorage.setItem($t,"1")}catch{}};function ge(e,n,l,o,c){const a=e.get("slots"),p=new Set,u=[];let r=!0,b=null,x=[],m=!1,I=0,d=ue(),z=null,w=0,g=Promise.resolve(),P={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const Q=["entries","entriesOfSlot","register","subscribe"].every(S=>typeof a?.[S]=="function"),O=S=>{P={...P,...S};for(const E of p)E()},k=()=>{if(!r)return;const S=l.getSnapshot().state?.config,E=Q&&P.peer.compatible&&x.length>0,A=E&&!P.saving&&(z??S?.contextCostsEnabled)===!0;if(!A&&b){const i=b;b=null,i()}A&&!b&&(b=de(e,{...n,disableIntegration:()=>{v(!1)}},o,c,l));const W=P.prompt&&(P.manual||E);O({available:E,enabled:A,prompt:W||!!(S&&E&&!S.contextCostsPromptSeen&&!S.contextCostsEnabled&&!d)})},T=async(S=!1)=>{if(!r||!Q)return;const E=Kt.flatMap(([W,i,M])=>a.entries(W).filter(h=>h.locale==="dsh-context"&&h.options[i]===M&&h.registrant!=="dsh-cost-meter-context-bridge"&&!h.children&&!h.store&&typeof h.component=="function"));if(!S&&m&&E.length===x.length&&E.every((W,i)=>W===x[i]))return;x=E,m=!0;const A=++I;O({peer:{version:"",compatible:!1,reason:E.length?"unavailable":"missing"}}),k();try{const W=await n.getContextIntegration();r&&A===I&&(O({peer:W}),k())}catch{r&&A===I&&k()}};function V(){d=!0,Me()}async function v(S,E=!1){if(!r||S&&!P.available&&!E)return;const A=++w;V(),z=S,O({prompt:!1,manual:!1,saving:!0,error:""}),k();const W=g.catch(()=>{}).then(()=>n.saveIntegration(S));g=W;try{await W,r&&A===w&&(z=null,O({saving:!1}),k())}catch{r&&A===w&&(z=!1,O({saving:!1,error:"save"}),k())}}if(u.push(l.subscribe(k)),Q)for(const[S]of Kt)u.push(a.subscribe(S,()=>{T()}));const F=()=>{document.hidden||T(!0)};document.addEventListener("visibilitychange",F);const H=S=>{S.key===$t&&S.newValue==="1"&&!d&&(d=!0,O({prompt:!1}),k())};return window.addEventListener("storage",H),T(),k(),{getSnapshot:()=>P,subscribe:S=>(p.add(S),()=>p.delete(S)),choose:v,dismiss:()=>v(P.manual?l.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:V,preview:()=>O({prompt:!0,manual:!0}),refresh:()=>{T(!0)},dispose:()=>{r=!1,++I;for(const S of u)S();b?.(),p.clear(),document.removeEventListener("visibilitychange",F),window.removeEventListener("storage",H)}}}const fe=`
42
42
  .cm-context-intro{--cmp-top:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,var(--dsh-windows-titlebar-height,0px)));inset:var(--cmp-top) 0 0;pointer-events:auto;overflow:hidden;box-sizing:border-box;color:var(--dsw-alias-label-primary,#25262b);background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,#fff));font:13px/1.6 var(--ds-font-family-sans,system-ui);border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:var(--dsw-radius-xl,16px);padding:0;width:min(760px,calc(100vw - 32px));max-height:calc(100dvh - var(--cmp-top) - 32px);margin:auto;box-shadow:var(--dsw-elevation-prominent,0 24px 80px #0003)}[data-fullscreen] .cm-context-intro{--cmp-top:0px}
43
43
  .cm-context-intro[open]{display:flex;flex-direction:column}.cm-context-intro::backdrop{inset:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,var(--dsh-windows-titlebar-height,0px))) 0 0;background:#0005}[data-fullscreen] .cm-context-intro::backdrop{inset:0}.cm-context-intro *{box-sizing:border-box}.cm-context-intro h2,.cm-context-intro p{margin:0}.cm-context-intro h2{font-size:18px;font-weight:600}.cm-context-intro button{font:inherit;cursor:pointer;border:1px solid var(--dsw-alias-border-l3,#e9eaed);background:transparent;border-radius:8px;padding:7px 14px;color:inherit}.cm-context-intro button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:2px}.cm-context-intro button:disabled{opacity:.5;cursor:default}
44
44
  .cm-context-intro-head,.cm-context-intro-foot{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:18px 24px;flex:none;z-index:1}.cm-context-intro-head{top:0;border-bottom:1px solid var(--dsw-alias-border-l3,#e9eaed)}.cm-context-intro-foot{bottom:0;border-top:1px solid var(--dsw-alias-border-l3,#e9eaed);flex-wrap:wrap}.cm-context-intro-body{padding:20px 24px;overflow:auto;min-height:0;overscroll-behavior:contain}.cm-context-intro button.cm-context-close{border:0;padding:0;width:30px;height:30px;flex-shrink:0;font-size:22px;line-height:30px}.cm-context-intro .cm-context-primary{background:var(--dsw-alias-state-business-primary,#4d6bfe);color:#fff;border-color:transparent}.cm-context-muted{font-size:12px;color:var(--dsw-alias-label-secondary,#737780)}.cm-context-intro-actions{display:flex;gap:8px;margin-left:auto}
45
45
  .cm-context-previews{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin:18px 0}.cm-context-preview{border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:12px;padding:14px;min-width:0;background:var(--dsw-alias-bg-layer-1,#f7f8fa)}.cm-context-preview h3{font-size:12px;font-weight:500;margin:0 0 12px}.cm-context-preview-card{background:var(--dsw-alias-bg-base,#fff);border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:10px;padding:14px}.cm-context-preview-number{font-size:22px;font-variant-numeric:tabular-nums;margin:6px 0}.cm-context-preview-number span{font-size:11px;font-weight:400}.cm-context-preview-bar{height:8px;display:flex;overflow:hidden;border-radius:4px;margin:10px 0}.cm-context-preview-bar i{display:block}.cm-context-preview-legend{display:flex;flex-wrap:wrap;gap:4px 10px;font-size:10px;color:var(--dsw-alias-label-secondary,#737780)}.cm-context-preview-extra{border-top:1px solid var(--dsw-alias-border-l3,#e9eaed);margin-top:14px;padding-top:12px}.cm-context-preview-metrics{display:flex;gap:12px;margin:8px 0}.cm-context-preview-metrics span{display:block;font-size:10px;color:var(--dsw-alias-label-secondary,#737780)}.cm-context-preview-metrics b{font-size:15px;font-weight:500}.cm-context-preview-row{display:flex;justify-content:space-between;font-size:11px;margin-top:8px}
46
46
  .cm-context-setting{border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:12px;padding:14px 16px;margin-bottom:18px}.cm-context-setting label{display:flex;align-items:center;gap:9px;cursor:pointer}.cm-context-setting input{accent-color:var(--dsw-alias-state-business-primary,#4d6bfe);width:15px;height:15px}.cm-context-setting p{margin-top:7px}.cm-context-setting .cm-plan-actions{margin-top:8px}
47
47
  @media(max-width:580px){.cm-context-previews{grid-template-columns:1fr}.cm-context-intro-body{padding:16px}.cm-context-intro-head,.cm-context-intro-foot{padding:14px 16px}.cm-context-intro-foot>p{width:100%}.cm-context-intro-actions{width:100%}.cm-context-intro-actions button{flex:1}}
48
- `;function De({after:t,text:n}){const r=[n("系统","System"),n("工具定义","Tools"),n("用户","User"),n("历史回复","Replies"),n("工具结果","Results")],o=[0,1,2,5,6].map(i=>G[i]);return e("section",{className:"cm-context-preview","aria-label":t?n("启用后预览","Enabled preview"):n("启用前预览","Before preview")},e("h3",null,t?n("启用后 · 上下文 + 费用","After · context + costs"):n("启用前 · 上下文","Before · context")),e("div",{className:"cm-context-preview-card"},e("p",null,n("当前上下文","Current context")),e("div",{className:"cm-context-preview-number"},"12,000",e("span",null," / 128,000 tokens")),e("div",{className:"cm-context-preview-bar","aria-hidden":!0,style:{background:"var(--dsw-alias-border-l3,#e5e7eb)"}},...[10,15,10,15,50].map((i,s)=>e("i",{key:s,style:{width:i*12e3/128e3+"%",background:o[s]}}))),e("div",{className:"cm-context-preview-legend"},...r.map((i,s)=>e("span",{key:i},e("i",{className:"cm-plan-dot",style:{background:o[s]}}),i))),t?e("div",{className:"cm-plan cm-context-preview-extra"},e("p",null,n("上下文费用构成","Context cost breakdown")),e("div",{className:"cm-context-preview-metrics"},e("div",null,e("span",null,n("输入费用参考","Input cost reference")),e("b",null,"≈ $0.012"))),e("p",{className:"cm-context-muted"},n("按非缓存单价估算","Estimated at uncached rates")),e(fe,{text:n,total:12e3,label:n("费用占比","Cost share"),rows:[1200,1800,1200,1800,6e3].map((i,s)=>({key:String(s),label:r[s],value:i,tokens:i,amount:"≈ $"+i/1e6,color:o[s]}))}),e("div",{className:"cm-context-preview-extra"},e("p",null,n("最近一次调用","Latest call")),e("div",{className:"cm-context-preview-row"},e("span",null,n("输入 $0.012 · 输出 $0.004","Input $0.012 · output $0.004"))),e("p",{className:"cm-context-muted"},n("用量计费合计 $0.016","Usage-based total $0.016")))):null))}function dt({manager:t,getLocale:n}){const r=he.useSyncExternalStore(t.subscribe,t.getSnapshot),o=ce(null),i=(s,m)=>n()==="en"?m:s;return oe(()=>{const s=o.current;if(!r.prompt||!s)return;let m=!0,p=!1,c=null;const g=()=>{if(!(!m||p||document.hidden)){if(!r.manual&&it()){t.dismiss();return}if(!(!r.manual&&[...document.querySelectorAll('dialog[open],[role="dialog"],[aria-modal="true"],.lc-modal-backdrop')].some(y=>y!==s&&y.getClientRects().length)))try{c=document.activeElement,s.showModal(),p=!0,t.opened()}catch{}}};g();const f=setInterval(g,1e3);return()=>{m=!1,clearInterval(f),s.open&&s.close(),p&&c?.isConnected&&c.focus?.({preventScroll:!0})}},[r.prompt,r.manual,t]),r.prompt?e("dialog",{ref:o,className:"cm-context-intro","aria-labelledby":"cm-context-intro-title","aria-describedby":"cm-context-intro-description",onKeyDown:s=>{if(s.key!=="Tab")return;const m=[...s.currentTarget.querySelectorAll("button:not(:disabled)")].filter(g=>g.getClientRects().length),p=m[0],c=m.at(-1);(s.shiftKey&&document.activeElement===p||!s.shiftKey&&document.activeElement===c)&&(s.preventDefault(),(s.shiftKey?c:p)?.focus())},onCancel:s=>{s.preventDefault(),t.dismiss()},onClose:()=>{t.getSnapshot().prompt&&t.dismiss()},onClick:s=>{if(s.target===s.currentTarget){const m=s.currentTarget.getBoundingClientRect();(s.clientX<m.left||s.clientX>m.right||s.clientY<m.top||s.clientY>m.bottom)&&t.dismiss()}}},e("style",null,we+pt),e("header",{className:"cm-context-intro-head"},e("div",null,e("h2",{id:"cm-context-intro-title"},i("让上下文占用与费用一起可见","See context usage and costs together")),e("p",{className:"cm-context-muted"},"dsh-context × dsh-cost-meter")),e("button",{type:"button",className:"cm-context-close","aria-label":i("关闭预览","Close preview"),autoFocus:!0,onClick:()=>{t.dismiss()}},"×")),e("div",{className:"cm-context-intro-body"},e("p",{id:"cm-context-intro-description"},r.available?i("已检测到兼容版本 ","Compatible version detected: ")+"dsh-context "+r.peer.version+i("。启用后,在它的当前上下文面板内增加上下文费用区。",". Add context costs inside its current-context panel."):i("界面预览。检测到已验证的兼容版本后,可以开启联动。","Interface preview. Enable integration when a verified compatible version is detected.")),e("div",{className:"cm-context-previews"},e(De,{text:i,after:!1}),e(De,{text:i,after:!0})),e("p",{className:"cm-context-muted"},i("示例数据:输入 $1 / M tokens,输出 $4 / M tokens。实际界面显示当前上下文的各部分 Token、费用占比,以及最近一次调用的输入、缓存和输出费用。","Example data: $1 / M input tokens and $4 / M output tokens. The live panel shows context tokens and cost shares, plus input, cache and output costs for the latest call.")),e("p",{style:{marginTop:12}},i("只读取已有数据,不发送模型请求,不产生额外 API 费用。只显示数据,不修改或压缩上下文。","Reads existing data without model requests or extra API charges. The display does not modify or compact your context."))),e("footer",{className:"cm-context-intro-foot"},e("p",{className:"cm-context-muted"},i("关闭后不再自动提示;可在费用统计中随时开关。","No repeated prompt after closing. Change this anytime in Cost statistics.")),e("div",{className:"cm-context-intro-actions"},e("button",{type:"button",onClick:()=>{t.dismiss()}},r.manual?i("关闭预览","Close preview"):i("暂不启用","Not now")),e("button",{type:"button",className:"cm-context-primary",disabled:!r.available||r.saving,onClick:()=>{t.choose(!0)}},i("启用联动","Enable integration"))))):null}function Ue({manager:t,getLocale:n}){const r=he.useSyncExternalStore(t.subscribe,t.getSnapshot),o=(i,s)=>n()==="en"?s:i;return e("details",{className:"cm-plan cm-context-setting","aria-label":o("dsh-context 联动设置","dsh-context integration settings")},e("style",null,we+pt),e("summary",null,"dsh-context "+o("联动","integration")+" · "+(r.enabled?o("已启用","On"):o("未启用","Off"))),e("div",null,e("p",{className:"cm-plan-sub",style:{marginBottom:8}},o("联动为可选项;本插件的上下文费用功能可独立使用。","Integration is optional; context costs also work independently in this plugin.")),e("label",null,e("input",{type:"checkbox",role:"switch",checked:r.enabled,disabled:r.saving||!r.available,onChange:i=>{t.choose(i.target.checked)}}),o("在 dsh-context 面板中显示上下文费用","Show context costs in dsh-context")),e("p",{className:"cm-plan-sub"},r.available?"dsh-context "+r.peer.version+o(" · 可随时关闭,独立上下文费用仍可使用。"," · Turn off anytime; standalone context costs remain available."):o("需要启用已验证的 dsh-context 0.62.0 或 0.66.0,并由宿主提供版本信息。","Requires enabled dsh-context 0.62.0 or 0.66.0 and host version information.")),r.error?e("p",{className:"cm-plan-error",role:"alert"},o("设置保存失败,联动保持关闭。可在此重试。","Could not save the setting; integration remains off. Retry here.")):null,e("div",{className:"cm-plan-actions"},e("button",{type:"button",onClick:t.preview},o("查看启用前后预览","Preview before and after")),e("button",{type:"button",onClick:t.refresh},o("重新检测","Check again")))))}function Se({offset:t,count:n,size:r,onChange:o,text:i}){return e("div",{className:"cm-stat-page"},e("span",{className:"cm-stat-sub"},n?`${t+1}–${Math.min(t+r,n)} / ${n}`:"0"),X(i("上一页","Previous"),()=>o(Math.max(0,t-r)),{disabled:!t}),X(i("下一页","Next"),()=>o(t+r),{disabled:t+r>=n}))}function mt({rows:t,money:n,text:r,onSelect:o,label:i}){const s=Math.max(0,...t.map(p=>p.value)),m=t.reduce((p,c)=>p+c.value,0);return e("div",null,e("div",{className:"cm-stat-panel-head"},e("h3",null,i),e("span",{className:"cm-stat-sub"},r("最高 ","Peak ")+n(s)+" · "+r("合计 ","Total ")+n(m))),e("div",{className:"cm-stat-chart",role:"group","aria-label":i},t.map((p,c)=>e("button",{key:c,type:"button",className:"cm-stat-bar",title:p.label+" · "+n(p.value),"aria-label":p.label+" · "+n(p.value),onClick:()=>o(p)},e("span",{style:{height:s?Math.max(1,p.value/s*100)+"%":"0%",opacity:p.value?void 0:.2}})))),e("div",{className:"cm-stat-axis"},e("span",null,t[0]?.label),e("span",null,t.at(-1)?.label)))}function ut(t,n){const r=Math.max(1,Math.ceil(t.length/60)),o=[];for(let i=0;i<t.length;i+=r){const s=t.slice(i,i+r),m=s[0].date,p=s.at(-1).date;o.push({from:m,to:p,label:m===p?m:m+" – "+p,value:s.reduce((c,g)=>c+W(g,n),0)})}return o}function gt({title:t,rows:n,total:r,format:o,text:i,columns:s=!1}){return e("section",{"aria-label":t},e("h3",null,t),r<=0?e("p",{className:"cm-stat-sub"},i("暂无可计算的占比","No measurable share yet")):e("ol",{className:"cm-stat-share-list"+(s?" cm-stat-step-list":"")},n.map((m,p)=>e("li",{key:p,"data-other":m.other||void 0},e("div",{className:"cm-stat-share-head"},e("span",null,m.label),e("span",{className:"cm-stat-share-value"},o(m.value)+(m.unpriced?" + ?":"")+" · "+H(m.value,r))),e("div",{className:"cm-stat-share-track","aria-hidden":!0},e("span",{className:"cm-stat-share-fill",style:{width:Math.min(100,100*m.value/r)+"%"}}))))))}function ft({api:t,sessionId:n,turn:r,revision:o,text:i}){const[s,m]=A(0),[p,c]=A(0),g=Le(t,"getTurnInspection",{sessionId:n,turn:r,offset:s},o+":"+p),f=()=>X(i("重试","Retry"),()=>c(w=>w+1)),y=e("div",{className:"cm-stat-inspection"},ge(g.error),f()),h=g.failed?y:null;if(ye(g))return g.loading?e("p",{className:"cm-stat-empty",role:"status"},i("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…")):y;const v=g.value;return v.found?e("div",{className:"cm-stat-inspection"},h,e("h4",null,i("本轮用户输入","User input for this turn")),v.input?e("pre",{className:"cm-stat-pre"},v.input):e("p",{className:"cm-stat-sub"},i("日志未记录本轮用户输入。","No user input is recorded for this turn.")),v.inputTruncated?e("p",{className:"cm-stat-truncated"},i("输入过长,此处显示前 16,000 个字符。","Showing the first 16,000 characters of this input.")):null,e("h4",null,i("工具调用","Tool calls")+" · "+v.totalTools),v.totalTools?null:e("p",{className:"cm-stat-sub"},i("这一轮没有工具调用记录。","No tool calls are recorded in this turn.")),v.tools.map(w=>e("details",{key:w.seq,className:"cm-stat-tool"},e("summary",null,e("span",null,(w.step==null?"":i("步骤 ","Step ")+w.step+" · ")+w.name),e("span",{className:"cm-stat-sub"},{complete:i("已完成","Completed"),error:i("调用失败","Failed"),pending:i("未记录结果","No recorded result")}[w.status])),e("h4",{style:{marginTop:12}},i("调用参数","Arguments")),e("pre",{className:"cm-stat-pre"},w.arguments),e("h4",null,i("返回结果","Result")),e("pre",{className:"cm-stat-pre"},w.result||i("没有可显示的文本结果","No text result is available")),w.truncated?e("p",{className:"cm-stat-truncated"},i("长内容显示前 16,000 个字符;完整内容保留在会话轨迹中。","Long content is limited to 16,000 characters here; the full content remains in the conversation trajectory.")):null)),e(Se,{offset:s,count:v.totalTools,size:20,onChange:m,text:i}),e("p",{className:"cm-stat-sub"},i("这里显示整轮原始记录,不受上方模型或计费筛选影响。附件仅显示类型。","Shows the whole turn, independent of model and cost filters above. Attachments are represented by type."))):e(se,null,h,e("p",{className:"cm-stat-note"},i("这一轮的原始日志不可用。","Original records for this turn are unavailable.")))}function We({api:t,query:n,revision:r,money:o,formatTokens:i,text:s,overview:m=!1,children:p}){const[c,g]=A(0),[f,y]=A(-1),[h,v]=A(0),[w,N]=A("summary"),[u,S]=A(null),[j,T]=A("cost"),[k,L]=A(0),d=Le(t,"getSessionBilling",{...n,offset:c,turnOffset:h},r+":"+k),K=ce(!1);oe(()=>{K.current&&!d.loading&&f>=0&&(document.getElementById("cm-stat-call-"+f)?.scrollIntoView({block:"nearest"}),K.current=!1)},[d.loading,d.value,c,f,w]);const C=d.value,M=n.basis,Z={input:s("非缓存输入","Uncached input"),output:s("输出","Output"),cacheRead:s("缓存读取","Cache read"),cacheWrite:s("缓存写入","Cache write"),reasoning:s("推理","Reasoning")},z={model:s("模型调用","Model call"),compaction:s("上下文压缩","Compaction"),search:s("原生搜索","Native search")},q=a=>a==null?s("未标明轮次","Turn not recorded"):s("轮次 ","Turn ")+a;if(ye(d))return d.loading?e("p",{className:"cm-stat-empty",role:"status"},s("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):ge(d.error);const E=d.failed?e("div",null,ge(d.error),X(s("重试","Retry"),()=>L(a=>a+1))):null;if(!C.found)return e(se,null,E,e("p",{className:"cm-stat-note"},s("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),p);const Q=a=>!a||a===n.sessionId?s("主会话","Main conversation"):s("子代理 ","Subagent ")+((C.agents??[]).find(b=>b.id===a)?.title||a).slice(0,80),F=a=>JSON.stringify([a.sessionId||n.sessionId,a.turn]),_=a=>((C.agents?.length??0)>1?Q(a.sessionId)+" · ":"")+q(a.turn),R=a=>M==="total"||(M==="plan"?a.plan:!a.plan),U=Object.keys(Z).map(a=>{const b=C.rows.filter(I=>I.bucket===a&&R(I));return{bucket:a,tokens:b.reduce((I,O)=>I+O.tokens,0),cost:b.reduce((I,O)=>I+O.cost,0),unpriced:b.some(I=>!I.priced)}}),Y=W(C,M),ie=W(C.recorded,M),Ke=Math.abs(Y-ie)>Math.max(1e-8,Math.abs(ie)*1e-8)||C.totalCalls!==C.recorded.calls,le=U.some(a=>a.unpriced),Ie=le?s("已知费用占比","Known cost share"):s("费用占比","Cost share"),Te=a=>{N("calls"),K.current=!0,g(Math.floor(a/50)*50),y(a%50)},B=a=>({key:a.bucket,label:Z[a.bucket],tokens:a.tokens,value:a.cost,unpriced:a.unpriced,amount:a.unpriced&&!a.cost?s("未定价","Unpriced"):o(a.cost)+(a.unpriced?" + ?":""),color:G[ct[a.bucket]??7]}),ae=new Map;for(const a of C.rows.filter(R)){const b=JSON.stringify([a.provider,a.model]),I=ae.get(b)??{key:b,label:a.model,provider:a.provider,tokens:0,value:0,unpriced:!1};I.value+=a.cost,I.tokens+=a.bucket==="reasoning"?0:a.tokens,I.unpriced||=!a.priced,ae.set(b,I)}const l=[...ae.values()].sort((a,b)=>b.value-a.value).map((a,b)=>({...a,label:a.provider+" / "+a.label,amount:a.unpriced&&!a.value?s("未定价","Unpriced"):o(a.value)+(a.unpriced?" + ?":""),color:G[b%7]}));if(l.length>7){const a=l.splice(7),b=a.reduce((O,be)=>O+be.value,0),I=a.some(O=>O.unpriced);l.push({key:"other-models",label:s("其余 ","Other ")+a.length+s(" 个模型"," models"),value:b,tokens:a.reduce((O,be)=>O+be.tokens,0),unpriced:I,amount:I&&!b?s("未定价","Unpriced"):o(b)+(I?" + ?":""),color:G[7]})}const J=U.find(a=>a.bucket==="cacheRead"),ne=U.filter(a=>["input","cacheRead","cacheWrite"].includes(a.bucket)),$e=J.tokens>0?e("div",{className:"cm-cache-compare"},e("h3",null,s("缓存读取的占比","Cache read share")),...[[s("输入 Token","Input tokens"),J.tokens,ne.reduce((a,b)=>a+b.tokens,0)],[s("输入费用","Input cost"),J.cost,ne.some(a=>a.unpriced)?0:ne.reduce((a,b)=>a+b.cost,0)]].map(([a,b,I])=>e("div",{key:a},e("div",{className:"cm-stat-share-head"},e("span",null,a),e("span",null,H(b,I))),e("div",{className:"cm-stat-share-track","aria-hidden":!0},e("span",{style:{display:"block",height:"100%",width:(I>0?b/I*100:0)+"%",borderRadius:9,background:G[6]}}))))):null,ee=(a,b,I={},O=null)=>e("section",{className:"cm-spend-card","aria-label":a},e("h3",null,a),e(fe,{rows:b,total:Y,label:Ie,text:s,amounts:!0,...I}),O),Fe=(a,b)=>e("p",{key:b,className:"cm-stat-sub"},Z[a.bucket]+": "+a.tokens.toLocaleString()+" × "+(a.priced?o(a.rate):"?")+" / 1,000,000 = "+(a.priced?o(a.cost):"?")),xt=(a,b,I)=>e("div",{className:"cm-stat-scroll",style:{marginTop:20}},e("h3",null,a),e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[a,s("调用次数","Calls"),s("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",s("Plan 等值","Plan equivalent")].map(O=>e("th",{key:O},O)))),e("tbody",null,b.map((O,be)=>e("tr",{key:be},e("td",null,I(O)),e("td",null,O.calls),e("td",null,[O.input,O.cacheRead+O.cacheWrite,O.output].map(i).join(" / ")),e("td",null,o(O.apiCost)+(O.unpriced?" + ?":"")),e("td",null,o(Math.max(0,O.cost-O.apiCost))+(O.unpriced?" + ?":"")))))));return e("section",{className:"cm-stat-panel"},e("style",null,we+Nt),m?e("nav",{className:"cm-session-tabs","aria-label":s("费用视图","Cost views")},...[["summary",s("费用概览","Overview")],["context",s("上下文","Context")],["calls",s("调用明细","Call details")]].map(([a,b])=>X(b,()=>{N(a),y(-1)},{key:a,"aria-pressed":w===a}))):null,m?e("div",{className:"cm-stat-metrics"},...[[M==="total"?s("API + Plan 等值","API + Plan equivalent"):M==="plan"?s("Plan 等值","Plan equivalent"):s("API 费用","API cost"),o(Y)+(U.some(a=>a.unpriced)?" + ?":""),s("按本对话调用日志估算","Estimated from this conversation’s call logs")],[s("调用次数","Calls"),C.totalCalls.toLocaleString(),(C.agents?.length??0)>1?s("包含子代理","Includes subagents"):s("本会话","This conversation")],[s("Token 用量","Token usage"),i(U.reduce((a,b)=>a+(b.bucket==="reasoning"?0:b.tokens),0)),s("输入、缓存与输出","Input, cache and output")],[s("缓存命中率","Cache hit rate"),H(U.find(a=>a.bucket==="cacheRead")?.tokens??0,U.filter(a=>["input","cacheRead","cacheWrite"].includes(a.bucket)).reduce((a,b)=>a+b.tokens,0)),s("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([a,b,I])=>e("div",{className:"cm-stat-metric",key:a},e("div",{className:"cm-stat-sub"},a),e("div",{className:"cm-stat-value"},b),e("div",{className:"cm-stat-sub"},I)))):null,!m||w==="context"?p:null,m?null:e("div",{className:"cm-stat-panel-head"},e("h3",null,m?s("已发生费用 · 调用明细","Recorded costs · call details"):s("单对话费用明细","Conversation cost details")),e("span",{className:"cm-stat-sub"},(C.agents?.length??0)>1?s("包含子代理及其后代","Includes subagents and their descendants"):s("本会话自身的调用","Own conversation calls"))),E,!m&&Ke?e("p",{className:"cm-stat-note"},s("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+o(ie)+" / "+C.recorded.calls+s(" 次;明细 "," calls; details ")+o(Y)+" / "+C.totalCalls+s(" 次。"," calls.")):null,(!m||w==="calls")&&(C.agents?.length??0)>1?xt(s("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),C.agents,a=>Q(a.id)):null,!m||w==="summary"?e("div",{className:"cm-plan cm-spend"},le?e("p",{className:"cm-plan-sub"},s("占比仅包含已知金额;未定价的用量显示 ?。","Shares cover known amounts only; unpriced usage is marked ?.")):null,e("div",{className:"cm-spend-grid"},ee(s("费用构成","Cost composition"),U.filter(a=>a.tokens>0&&(a.bucket!=="reasoning"||a.cost>0||a.unpriced)).map(B),{},$e),(C.callShares?.length??0)>0?ee(s("每次调用费用占比","Cost share per call"),C.callShares.map((a,b)=>({...a,key:String(a.index),label:a.other?s("其余 ","Other ")+a.calls+s(" 次调用"," calls"):s("调用 #","Call #")+(a.index+1),meta:a.other?a.calls+s(" 次调用"," calls"):a.tokens.toLocaleString()+" tokens",value:W(a,M),amount:a.unpriced&&!W(a,M)?s("未定价","Unpriced"):o(W(a,M))+(a.unpriced?" + ?":""),color:G[a.other?7:b%7]})),{onSelect:a=>{a.other||Te(a.index)}}):null,l.length>1?ee(s("模型费用分布","Cost by model"),l):null,C.kinds.length>1?ee(s("各环节费用占比","Cost by activity"),C.kinds.map((a,b)=>({key:a.kind,label:z[a.kind]??a.kind,value:W(a,M),tokens:pe(a),meta:a.calls+s(" 次调用"," calls")+" · "+i(pe(a))+" tok",unpriced:a.unpriced,amount:o(W(a,M))+(a.unpriced?" + ?":""),color:G[b]}))):null),(C.callShares?.length??0)>0?e("p",{className:"cm-plan-sub"},s("全部调用为分母 · 前 7 次单列,其余合并 · 点击查看明细","Shares of all calls · Top 7 + remainder · Select for details")):null):null,!m||w==="calls"?e(se,null,e("details",{className:"cm-stat-secondary",open:!m},e("summary",null,s("轮次、步骤与单价","Turns, steps and rates")),e("section",{className:"cm-stat-breakdown"},e("div",{className:"cm-stat-panel-head"},e("h3",null,s("各步骤占比","Share by step")),e("div",{className:"cm-stat-periods"},...[["cost",s("费用","Cost")],["calls",s("调用次数","Calls")]].map(([a,b])=>X(b,()=>T(a),{key:a,"aria-pressed":j===a})))),e(gt,{title:j==="cost"?s("费用占比 · 全部调用","Cost share · all calls"):s("调用次数占比 · 全部调用","Call count share · all calls"),rows:(C.stepShares?.[j]??[]).map(a=>({label:a.other?s("其余步骤合计","All other steps"):_(a)+(a.step==null?"":s(" · 步骤 "," · step ")+a.step),value:j==="cost"?W(a,M):a.calls,unpriced:j==="cost"&&a.unpriced,other:a.other})),total:j==="cost"?Y:C.totalCalls,format:j==="cost"?o:a=>a.toLocaleString(),text:s,columns:!0}),e("p",{className:"cm-stat-sub",style:{marginTop:12}},s("分母包含所选范围的全部调用,跨页合计。显示前 12 项,其余合并;无步骤编号的调用单列。工具本身不额外算作模型调用。","Shares use all calls in the selected range, across pages. Top 12 entries are shown; the rest are combined. Missing step IDs remain explicit. Tools are not counted as extra model calls."))),e("details",{className:"cm-stat-help"},e("summary",null,s("单价与 Token 明细","Rates and token details")),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[s("费用构成","Cost component"),"Tokens",s("费用","Cost"),s("费用占比","Cost share")].map(a=>e("th",{key:a},a)))),e("tbody",null,U.map(a=>e("tr",{key:a.bucket},e("td",null,Z[a.bucket]),e("td",null,a.tokens.toLocaleString()),e("td",null,o(a.cost)+(a.unpriced?" + ?":"")),e("td",null,H(a.cost,Y))))))),e("p",{className:"cm-stat-sub",style:{marginTop:10}},s("推理 Token 可能包含在输出中;单价为 0 时不另收推理费。未定价用量显示 ?。","Reasoning tokens may overlap output; a zero reasoning rate adds no separate charge. Unpriced usage is marked ?.")),xt(s("按调用类型统计","Cost by call type"),C.kinds,a=>z[a.kind]??a.kind)),e("section",{className:"cm-stat-turns"},e("div",{className:"cm-stat-panel-head"},e("h3",null,s("按轮次统计","Cost by turn")),e("span",{className:"cm-stat-sub"},s("展开查看输入和工具调用","Expand to inspect input and tool calls"))),C.turns.map(a=>e("div",{key:F(a),className:"cm-stat-turn"},e("button",{type:"button",className:"cm-stat-turn-toggle",disabled:a.turn==null,"aria-expanded":a.turn!=null&&u===F(a),onClick:()=>S(b=>b===F(a)?null:F(a))},e("span",null,(a.turn==null?"":u===F(a)?"⌄ ":"› ")+_(a)),e("span",null,a.calls+s(" 次调用"," calls")+" · "+i(pe(a))+" tok · "+o(W(a,M))+(a.unpriced?" + ?":"")+" · "+H(W(a,M),Y))),a.turn!=null&&u===F(a)?e(ft,{key:F(a),api:t,sessionId:a.sessionId||n.sessionId,turn:a.turn,revision:r,text:s}):null))),e("p",{className:"cm-stat-sub"},s("轮次沿用日志编号;未记录轮次的调用单列。每轮包含其全部调用,跨调用分页也不会拆分。","Turn numbers come from the log; calls without one are listed separately. Each turn includes all its calls, across call pages.")),e(Se,{offset:h,count:C.totalTurns,size:25,onChange:a=>{v(a),S(null)},text:s})),e("div",{style:{marginTop:24}},e(mt,{rows:C.calls.map((a,b)=>({label:"#"+(c+b+1),index:b,value:W(a,M)})),money:o,text:s,label:s("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:a=>{y(a.index),document.getElementById("cm-stat-call-"+a.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),C.calls.map((a,b)=>e("details",{key:c+b,id:"cm-stat-call-"+b,className:"cm-stat-call",open:f===b,onToggle:I=>{I.currentTarget.open?y(b):y(O=>O===b?-1:O)}},e("summary",null,"#"+(c+b+1)+" · "+_(a)+(a.step==null?"":s(" / 步骤 "," / step ")+a.step)+" · "+(z[a.kind]??a.kind)+" · "+a.provider+" / "+a.model+" · "+(a.plan?"Plan ":"API ")+(a.priced?o(a.cost):"?")+(a.longContext?s(" · 长上下文价"," · long-context rate"):""),e("span",{className:"cm-call-share"},(a.priced?H(W(a,M),Y):"—")+" · "+Ie)),f===b?e("div",{className:"cm-plan"},e(fe,{rows:a.rows.filter(R).filter(I=>I.tokens>0&&(I.bucket!=="reasoning"||I.cost>0||!I.priced)).map(I=>B({...I,unpriced:!I.priced})),total:W(a,M),label:s("本次费用构成","This call’s costs"),text:s,amounts:!0})):null,e("p",{className:"cm-stat-sub"},new Date(a.atMs).toLocaleString()),a.rows.map(Fe))),e(Se,{offset:c,count:C.totalCalls,size:50,onChange:a=>{g(a),y(-1)},text:s})):null)}function bt({state:t,api:n,sessionId:r,formatMoneyUsd:o,formatTokens:i,resolveLocale:s,contextIntegration:m}){const p=(N,u)=>(s?s(t.config):t.config.locale)==="en"?u:N,[c,g]=A(0),[f,y]=A(t.config.showTotalWithPlan?"total":"api"),h=ke(t,c),v=N=>o(N,{...t.config,decimals:Math.max(N!==0&&Math.abs(N)<.01?8:4,t.config.decimals??2)}),w={sessionId:r,from:"",to:"",provider:"",model:"",basis:f,offset:0};return e("div",{className:"cm-stat cm-stat-session","data-session-id":r},e("style",null,at),e("div",{className:"cm-stat-panel-head"},e("p",{className:"cm-stat-sub"},p("当前对话 · 全部调用","This conversation · all calls")),X(p("刷新","Refresh"),()=>g(N=>N+1))),e(We,{key:r+":"+f,api:n,query:w,revision:h,money:v,formatTokens:i,text:p,overview:!0},e(Ce,{key:r,api:n,sessionId:r,revision:h,money:v,text:p,compact:!0})),e("details",{className:"cm-session-options"},e("summary",null,p("显示与联动设置","Display and integration settings")),e("div",{className:"cm-stat-controls"},e("label",null,p("计费口径","Cost basis"),e("select",{value:f,onChange:N=>y(N.target.value)},...[["api",p("API 费用","API cost")],["plan",p("Plan 等值","Plan equivalent")],["total",p("API + Plan 等值","API + Plan equivalent")]].map(([N,u])=>e("option",{key:N,value:N},u))))),m?e(Ue,m):null))}function ht({state:t,api:n,sessionId:r="",formatMoneyUsd:o,formatTokens:i,resolveLocale:s,contextIntegration:m}){const p=s?s(t.config)==="en":t.config.locale==="en"||t.config.locale!=="zh"&&(t.config.activeLocale||t.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",c=(l,J)=>p?J:l,[g,f]=A(r?"all":"week"),[y,h]=A(null),[v,w]=A({id:r,title:r}),[N,u]=A(""),[S,j]=A(""),[T,k]=A(t.config.showTotalWithPlan?"total":"api"),[L,d]=A(0),[K,C]=A(0),[M,Z]=A(!1),z=t.meta.dayKey||new Date().toISOString().slice(0,10),q=g==="all"?"":g==="custom"?y?.from||z:Qe(z,g==="week"?-6:g==="month"?-29:0),E=g==="custom"&&y?.to||z,Q={from:q,to:E,provider:N,model:S,basis:T,sessionId:v.id,offset:L},F=ke(t,K),_=Le(n,"getBillingStatistics",Q,F),R=_.value,U=l=>o(l,{...t.config,decimals:Math.max(l!==0&&Math.abs(l)<.01?8:4,t.config.decimals??2)}),Y=l=>{f(l),d(0)},ie=l=>{w(l),d(0),u(""),j("")},Ke=T==="total"?c("API + Plan 等值","API + Plan equivalent"):T==="plan"?c("Plan 等值","Plan equivalent"):c("API 费用","API cost"),le=(l,J,ne,$e)=>e("label",null,l,e("select",{value:J,onChange:ee=>{ne(ee.target.value),d(0)}},$e.map(([ee,Fe])=>e("option",{key:ee,value:ee},Fe)))),Ie={input:c("未缓存输入","Uncached input"),cacheRead:c("缓存读取","Cache read"),cacheWrite:c("缓存写入","Cache write"),output:c("输出","Output")},Te=(l,J)=>e("section",{className:"cm-stat-panel"},e("div",{className:"cm-stat-panel-head"},e("h3",null,l)),J),B=R?.totals,ae=(l,J,ne)=>e("div",{className:"cm-stat-metric",key:l},e("div",{className:"cm-stat-sub"},l),e("div",{className:"cm-stat-value"},J),e("div",{className:"cm-stat-sub"},ne));return e("div",{className:"cm-stat"},e("style",null,at),m?e(Ue,m):null,e("header",{className:"cm-stat-head"},e("div",null,e("h2",null,c("计费统计","Cost statistics")),e("p",{className:"cm-stat-sub"},v.id?c("单对话 · ","Conversation · ")+(v.title===v.id&&R?.sessions[0]?.title||v.title):c("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),X(c("刷新","Refresh"),()=>C(l=>l+1))),v.id?X(c("← 全部对话","← All conversations"),()=>ie({id:"",title:""})):null,e("div",{className:"cm-stat-controls"},e("div",{className:"cm-stat-periods"},...[["today",c("今天","Today")],["week",c("近 7 天","Last 7 days")],["month",c("近 30 天","Last 30 days")],["all",c("全部记录","All retained")],["custom",c("自定义","Custom")]].map(([l,J])=>X(J,()=>Y(l),{key:l,"aria-pressed":g===l})))),g==="custom"?e("div",{className:"cm-stat-controls"},...["from","to"].map(l=>e("label",{key:l},l==="from"?c("开始日期","From"):c("结束日期","To"),e("input",{type:"date",value:l==="from"?q:E,onChange:J=>{h({from:q,to:E,[l]:J.target.value}),d(0)}})))):null,e("div",{className:"cm-stat-controls"},le(c("计费口径","Cost basis"),T,k,[["api",c("API 费用","API cost")],["plan",c("Plan 等值","Plan equivalent")],["total",c("API + Plan 等值","API + Plan equivalent")]]),le(c("提供商","Provider"),N,l=>{u(l),j("")},[["",c("全部提供商","All providers")],...[...new Set([N,...R?.providers??[]])].filter(Boolean).map(l=>[l,l])]),le(c("模型","Model"),S,j,[["",c("全部模型","All models")],...[...new Set([S,...R?.modelOptions??[]])].filter(Boolean).map(l=>[l,l])])),e("details",{className:"cm-stat-help"},e("summary",null,c("计费说明","About billing")),e("p",null,c("按宿主时区归日:","Days use the host timezone: ")+(t.meta.timezone||"UTC")+" · "+c("API 金额是按已记录用量和配置单价计算的估算;Plan 为订阅用量的 API 等值,不是订阅账单。外部导入用量在原概览中单列。","API amounts estimate recorded usage at configured rates; Plan is API-equivalent usage, not the subscription invoice. External usage remains separate in Overview."))),ye(_)?_.loading?e("p",{className:"cm-stat-empty",role:"status"},c("加载统计…","Loading statistics…")):ge(_.error):R?e(se,null,_.failed?ge(_.error):null,e("p",{className:"cm-stat-sub",style:{marginTop:8}},R.from+" – "+R.to+(R.retainedFrom?" · "+c("账本保留范围 ","Retained ledger ")+R.retainedFrom+" – "+R.retainedTo:"")),e("div",{className:"cm-stat-metrics"},ae(c("API 费用","API cost"),U(B.apiCost),c("已入账估算","Recorded estimate")),ae(c("Plan 等值费用","Plan equivalent"),U(Math.max(0,B.cost-B.apiCost)),c("不代表实际扣款","Not an actual debit")),ae(c("调用次数","Calls"),B.calls.toLocaleString(),R.sessionCount+c(" 个对话 · 平均 "," conversations · average ")+U(B.calls?W(B,T)/B.calls:0)),ae(c("缓存命中率","Cache hit rate"),H(B.cacheRead,B.input+B.cacheRead+B.cacheWrite),i(pe(B))+" Tokens")),v.id?e("section",{className:"cm-stat-panel"},e(Ce,{key:v.id,api:n,sessionId:v.id,revision:F,money:U,text:c})):null,v.id?e(We,{key:JSON.stringify([v.id,q,E,N,S,T]),api:n,query:{...Q,from:R.from,to:R.to,offset:0},revision:F,money:U,formatTokens:i,text:c}):null,R.models.some(l=>!l.priced)?e("p",{className:"cm-stat-note"},c("部分模型当前未配置价格,金额可能不完整;未定价不等于免费。","Some models have no configured price. Amounts may be incomplete; unpriced usage is not free.")):null,!B.calls&&!B.cost?e("p",{className:"cm-stat-empty"},c("所选范围没有已记录的用量。","No recorded usage in this range.")):null,e("section",{className:"cm-stat-panel"},e(mt,{rows:ut(R.days,T),money:U,text:c,label:c("费用趋势 · ","Cost over time · ")+Ke,onSelect:l=>{h({from:l.from,to:l.to}),Y("custom")}}),e("p",{className:"cm-stat-sub",style:{marginTop:12}},c("点击柱形查看该日期范围。长区间按相邻日期合并,保留全部金额。","Select a bar to inspect its date range. Long ranges group adjacent days without dropping costs."))),e("div",{className:"cm-stat-grid"},Te(c("模型费用排行","Cost by model"),e(se,null,e("ol",{className:"cm-stat-rank"},(M?R.models:R.models.slice(0,8)).map(l=>e("li",{key:l.key},e("button",{type:"button",onClick:()=>{u(l.provider),j(l.model),d(0)},title:l.key},e("div",{className:"cm-stat-rankline"},e("span",null,l.model),e("span",{className:"cm-stat-number"},U(W(l,T))+(l.priced?"":" + ?"))),e("div",{className:"cm-stat-sub"},l.provider+" · "+l.calls+c(" 次 · "," calls · ")+H(W(l,T),W(B,T))),e("div",{className:"cm-stat-track"},e("span",{style:{width:H(W(l,T),W(B,T))}}))))),R.models.length>8?X(M?c("收起","Show less"):c("显示全部模型","Show all models"),()=>Z(l=>!l)):null,R.unmodeledCost>1e-8?e("p",{className:"cm-stat-note"},c("历史未分配到模型的费用:","Historical cost without a model: ")+U(R.unmodeledCost)):null)),Te(c("Token 构成","Token composition"),e(se,null,e("ol",{className:"cm-stat-rank"},Object.entries(Ie).map(([l,J])=>e("li",{key:l},e("div",{className:"cm-stat-rankline"},e("span",null,J),e("span",{className:"cm-stat-number"},i(B[l]))),e("div",{className:"cm-stat-track"},e("span",{style:{width:H(B[l],pe(B)),background:l.startsWith("cache")?"var(--cm-plan)":void 0}}))))),e("p",{className:"cm-stat-note"},c("这里展示 Token 数量占比,不是费用占比。缓存写入计入输入分母,不算缓存命中。","These are token shares, not cost shares. Cache writes count as input, not cache hits.")),e("p",{className:"cm-stat-sub"},c("单独上报的推理 Token:","Reported reasoning tokens: ")+i(B.reasoning))))),v.id?null:e("section",{className:"cm-stat-panel"},e("div",{className:"cm-stat-panel-head"},e("h3",null,c("对话费用排行","Cost by conversation")),e("span",{className:"cm-stat-sub"},t.config.includeSubagentCost?c("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):c("点击对话查看明细","Select a conversation for details"))),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[c("对话","Conversation"),c("调用","Calls"),"API",c("Plan 等值","Plan equivalent"),c("缓存命中","Cache hits")].map(l=>e("th",{key:l},l)))),e("tbody",null,R.sessions.map(l=>e("tr",{key:l.id},e("td",null,e("button",{type:"button",title:l.id,onClick:()=>ie({id:l.id,title:l.title})},l.title)),e("td",null,l.calls.toLocaleString()),e("td",null,U(l.apiCost)),e("td",null,U(Math.max(0,l.cost-l.apiCost))),e("td",null,H(l.cacheRead,l.input+l.cacheRead+l.cacheWrite))))))),R.unassignedCost>1e-8?e("p",{className:"cm-stat-note"},c("未关联对话的费用:","Cost not linked to a conversation: ")+U(R.unassignedCost)):null,e(Se,{offset:L,count:R.sessionCount,size:25,onChange:d,text:c})))):null)}function vt(t,{state:n,sessionId:r=""}={}){if(!n||document.hidden)return;const o=ke(n,0),i=n.meta.dayKey||new Date().toISOString().slice(0,10),s={sessionId:r,from:r?"":Qe(i,-6),to:r?"":i,provider:"",model:"",basis:n.config.showTotalWithPlan?"total":"api",offset:0};return Promise.all(r?[Ne(t,"getSessionBilling",{...s,turnOffset:0},o+":0")]:[Ne(t,"getBillingStatistics",{from:s.from,to:s.to,provider:"",model:"",basis:s.basis,sessionId:"",offset:0},o)])}async function Ct(t,n,r){const o=typeof n=="function"?n:()=>n&&r?r(n.getSnapshot().state?.config??{activeLocale:n.getSnapshot().locale}):"en",i=await t.get("remote").$mount(tt);t.effect(()=>()=>i(),"cost-meter: statistics contribution");const s=t.get("remote.costMeter"),m=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getContextCosts"].map(g=>[g,async f=>{const y=await s[g]((g==="getContextCosts"?Ye:g==="getTurnInspection"?Ze:et)(f));if(!y?.ok)throw new Error(y?.error?.message||"Statistics request failed");return{getBillingStatistics:Re,getSessionBilling:Me,getTurnInspection:Oe,getContextCosts:Ee}[g](y.value)}]));let p;if(n?.subscribe&&typeof t.get("slots")?.entries=="function"){m.getContextIntegration=async()=>{const y=await s.getContextIntegration();if(!y?.ok)throw new Error("Integration check failed");return Ge(y.value)},m.saveIntegration=async y=>{const h=await s.updateConfig({contextCostsEnabled:y,contextCostsPromptSeen:!0});if(!h?.ok||!h.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:h.value})},p=lt(t,m,n,o,Je("react-dom").createPortal),t.effect(()=>p.dispose,"cost-meter: optional dsh-context integration");const g=t.get("slots"),f=()=>g.register({name:"shell.overlay",id:"cost-meter-context-intro",order:50},()=>e(dt,{manager:p,getLocale:o}));typeof g.inject=="function"&&t.effect(()=>g.inject("shell.overlay",f),"cost-meter: context preview prompt")}const c=g=>e(g.sessionId?bt:ht,{...g,api:m,contextIntegration:p?{manager:p,getLocale:o}:null});return c.prefetch=g=>vt(m,g),t.effect(()=>()=>je.delete(m),"cost-meter: statistics cache cleanup"),c}return{mount:Ct,prefetchStatistics:vt,Statistics:ht,SessionStatistics:bt,SessionDetail:We,TurnInspection:ft,ShareChart:gt,ContextCosts:Ce,ContextPrompt:dt,ContextPreview:De,ContextIntegrationSettings:Ue,createContextIntegration:lt,contextCostBreakdown:ot,installContextCosts:rt,CONTRIBUTION:tt,parseContextCosts:Ee,parseStatistics:Re,parseDetail:Me,parseInspection:Oe,dailyChartRows:ut,requestStart:st,requestValue:de,requestFailure:nt,showsPlaceholder:ye,refreshKeyOf:ke}}});
48
+ `;function Jt({after:e,text:n}){const l=[n("系统","System"),n("工具定义","Tools"),n("用户","User"),n("历史回复","Replies"),n("工具结果","Results")],o=[0,1,2,5,6].map(c=>G[c]);return t("section",{className:"cm-context-preview","aria-label":e?n("启用后预览","Enabled preview"):n("启用前预览","Before preview")},t("h3",null,e?n("启用后 · 上下文 + 费用","After · context + costs"):n("启用前 · 上下文","Before · context")),t("div",{className:"cm-context-preview-card"},t("p",null,n("当前上下文","Current context")),t("div",{className:"cm-context-preview-number"},"12,000",t("span",null," / 128,000 tokens")),t("div",{className:"cm-context-preview-bar","aria-hidden":!0,style:{background:"var(--dsw-alias-border-l3,#e5e7eb)"}},...[10,15,10,15,50].map((c,a)=>t("i",{key:a,style:{width:c*12e3/128e3+"%",background:o[a]}}))),t("div",{className:"cm-context-preview-legend"},...l.map((c,a)=>t("span",{key:c},t("i",{className:"cm-plan-dot",style:{background:o[a]}}),c))),e?t("div",{className:"cm-plan cm-context-preview-extra"},t("p",null,n("上下文费用构成","Context cost breakdown")),t("div",{className:"cm-context-preview-metrics"},t("div",null,t("span",null,n("输入费用参考","Input cost reference")),t("b",null,"≈ $0.012"))),t("p",{className:"cm-context-muted"},n("按非缓存单价估算","Estimated at uncached rates")),t(lt,{text:n,total:12e3,label:n("费用占比","Cost share"),rows:[1200,1800,1200,1800,6e3].map((c,a)=>({key:String(a),label:l[a],value:c,tokens:c,amount:"≈ $"+c/1e6,color:o[a]}))}),t("div",{className:"cm-context-preview-extra"},t("p",null,n("最近一次调用","Latest call")),t("div",{className:"cm-context-preview-row"},t("span",null,n("输入 $0.012 · 输出 $0.004","Input $0.012 · output $0.004"))),t("p",{className:"cm-context-muted"},n("用量计费合计 $0.016","Usage-based total $0.016")))):null))}function be({manager:e,getLocale:n}){const l=wt.useSyncExternalStore(e.subscribe,e.getSnapshot),o=dt(null),c=(a,p)=>n()==="en"?p:a;return nt(()=>{const a=o.current;if(!l.prompt||!a)return;let p=!0,u=!1,r=null;const b=()=>{if(!(!p||u||document.hidden)){if(!l.manual&&ue()){e.dismiss();return}if(!(!l.manual&&[...document.querySelectorAll('dialog[open],[role="dialog"],[aria-modal="true"],.lc-modal-backdrop')].some(m=>m!==a&&m.getClientRects().length)))try{r=document.activeElement,a.showModal(),u=!0,e.opened()}catch{}}};b();const x=setInterval(b,1e3);return()=>{p=!1,clearInterval(x),a.open&&a.close(),u&&r?.isConnected&&r.focus?.({preventScroll:!0})}},[l.prompt,l.manual,e]),l.prompt?t("dialog",{ref:o,className:"cm-context-intro","aria-labelledby":"cm-context-intro-title","aria-describedby":"cm-context-intro-description",onKeyDown:a=>{if(a.key!=="Tab")return;const p=[...a.currentTarget.querySelectorAll("button:not(:disabled)")].filter(b=>b.getClientRects().length),u=p[0],r=p.at(-1);(a.shiftKey&&document.activeElement===u||!a.shiftKey&&document.activeElement===r)&&(a.preventDefault(),(a.shiftKey?r:u)?.focus())},onCancel:a=>{a.preventDefault(),e.dismiss()},onClose:()=>{e.getSnapshot().prompt&&e.dismiss()},onClick:a=>{if(a.target===a.currentTarget){const p=a.currentTarget.getBoundingClientRect();(a.clientX<p.left||a.clientX>p.right||a.clientY<p.top||a.clientY>p.bottom)&&e.dismiss()}}},t("style",null,jt+fe),t("header",{className:"cm-context-intro-head"},t("div",null,t("h2",{id:"cm-context-intro-title"},c("让上下文占用与费用一起可见","See context usage and costs together")),t("p",{className:"cm-context-muted"},"dsh-context × dsh-cost-meter")),t("button",{type:"button",className:"cm-context-close","aria-label":c("关闭预览","Close preview"),autoFocus:!0,onClick:()=>{e.dismiss()}},"×")),t("div",{className:"cm-context-intro-body"},t("p",{id:"cm-context-intro-description"},l.available?c("已检测到兼容版本 ","Compatible version detected: ")+"dsh-context "+l.peer.version+c("。启用后,在它的当前上下文面板内增加上下文费用区。",". Add context costs inside its current-context panel."):c("界面预览。检测到已验证的兼容版本后,可以开启联动。","Interface preview. Enable integration when a verified compatible version is detected.")),t("div",{className:"cm-context-previews"},t(Jt,{text:c,after:!1}),t(Jt,{text:c,after:!0}))),t("footer",{className:"cm-context-intro-foot"},t("div",{className:"cm-context-intro-actions"},t("button",{type:"button",onClick:()=>{e.dismiss()}},l.manual?c("关闭预览","Close preview"):c("暂不启用","Not now")),t("button",{type:"button",className:"cm-context-primary",disabled:!l.available||l.saving,onClick:()=>{e.choose(!0)}},c("启用联动","Enable integration"))))):null}function Qt({manager:e,getLocale:n}){const l=wt.useSyncExternalStore(e.subscribe,e.getSnapshot),o=(c,a)=>n()==="en"?a:c;return t("details",{className:"cm-plan cm-context-setting","aria-label":o("dsh-context 联动设置","dsh-context integration settings")},t("style",null,jt+fe),t("summary",null,"dsh-context "+o("联动","integration")+" · "+(l.enabled?o("已启用","On"):o("未启用","Off"))),t("div",null,t("label",null,t("input",{type:"checkbox",role:"switch",checked:l.enabled,disabled:l.saving||!l.available,onChange:c=>{e.choose(c.target.checked)}}),o("在 dsh-context 面板中显示上下文费用","Show context costs in dsh-context")),t("p",{className:"cm-plan-sub"},l.available?"dsh-context "+l.peer.version:l.peer.reason==="missing"?o("请安装并启用 dsh-context,然后重新检测。","Install and enable dsh-context, then check again."):l.peer.reason==="unavailable"?o("无法读取 dsh-context 状态,请重新检测。","Could not read dsh-context status. Check again."):o("当前 dsh-context 未提供所需界面接口,请更新插件或宿主后重新检测。","Required dsh-context view interfaces are unavailable. Update the plugin or host, then check again.")),l.error?t("p",{className:"cm-plan-error",role:"alert"},o("设置保存失败,联动保持关闭。可在此重试。","Could not save the setting; integration remains off. Retry here.")):null,t("div",{className:"cm-plan-actions"},t("button",{type:"button",onClick:e.preview},o("查看启用前后预览","Preview before and after")),t("button",{type:"button",onClick:e.refresh},o("重新检测","Check again")))))}function xt({offset:e,count:n,size:l,onChange:o,text:c}){return t("div",{className:"cm-stat-page"},t("span",{className:"cm-stat-sub"},n?`${e+1}–${Math.min(e+l,n)} / ${n}`:"0"),Y(c("上一页","Previous"),()=>o(Math.max(0,e-l)),{disabled:!e}),Y(c("下一页","Next"),()=>o(e+l),{disabled:e+l>=n}))}function he({rows:e,money:n,text:l,onSelect:o,label:c}){const a=Math.max(0,...e.map(u=>u.value)),p=e.reduce((u,r)=>u+r.value,0);return t("div",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c),t("span",{className:"cm-stat-sub"},l("最高 ","Peak ")+n(a)+" · "+l("合计 ","Total ")+n(p))),t("div",{className:"cm-stat-chart",role:"group","aria-label":c},e.map((u,r)=>t("button",{key:r,type:"button",className:"cm-stat-bar",title:u.label+" · "+n(u.value),"aria-label":u.label+" · "+n(u.value),onClick:()=>o(u)},t("span",{style:{height:a?Math.max(1,u.value/a*100)+"%":"0%",opacity:u.value?void 0:.2}})))),t("div",{className:"cm-stat-axis"},t("span",null,e[0]?.label),t("span",null,e.at(-1)?.label)))}function ve(e,n){const l=Math.max(1,Math.ceil(e.length/60)),o=[];for(let c=0;c<e.length;c+=l){const a=e.slice(c,c+l),p=a[0].date,u=a.at(-1).date;o.push({from:p,to:u,label:p===u?p:p+" – "+u,value:a.reduce((r,b)=>r+D(b,n),0)})}return o}function xe({title:e,rows:n,total:l,format:o,text:c,columns:a=!1}){return t("section",{"aria-label":e},t("h3",null,e),l<=0?t("p",{className:"cm-stat-sub"},c("暂无可计算的占比","No measurable share yet")):t("ol",{className:"cm-stat-share-list"+(a?" cm-stat-step-list":"")},n.map((p,u)=>t("li",{key:u,"data-other":p.other||void 0},t("div",{className:"cm-stat-share-head"},t("span",null,p.label),t("span",{className:"cm-stat-share-value"},o(p.value)+(p.unpriced?" + ?":"")+" · "+_(p.value,l))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{className:"cm-stat-share-fill",style:{width:Math.min(100,100*p.value/l)+"%"}}))))))}function ye({api:e,sessionId:n,turn:l,revision:o,text:c}){const[a,p]=j(0),[u,r]=j(0),b=vt(e,"getTurnInspection",{sessionId:n,turn:l,offset:a},o+":"+u),x=()=>Y(c("重试","Retry"),()=>r(z=>z+1)),m=t("div",{className:"cm-stat-inspection"},ot(b.error),x()),I=b.failed?m:null;if(Pt(b))return b.loading?t("p",{className:"cm-stat-empty",role:"status"},c("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…")):m;const d=b.value;return d.found?t("div",{className:"cm-stat-inspection"},I,t("h4",null,c("本轮用户输入","User input for this turn")),d.input?t("pre",{className:"cm-stat-pre"},d.input):t("p",{className:"cm-stat-sub"},c("日志未记录本轮用户输入。","No user input is recorded for this turn.")),d.inputTruncated?t("p",{className:"cm-stat-truncated"},c("显示前 16,000 字符","First 16,000 characters")):null,t("h4",null,c("工具调用","Tool calls")+" · "+d.totalTools),d.totalTools?null:t("p",{className:"cm-stat-sub"},c("这一轮没有工具调用记录。","No tool calls are recorded in this turn.")),d.tools.map(z=>t("details",{key:z.seq,className:"cm-stat-tool"},t("summary",null,t("span",null,(z.step==null?"":c("步骤 ","Step ")+z.step+" · ")+z.name),t("span",{className:"cm-stat-sub"},{complete:c("已完成","Completed"),error:c("调用失败","Failed"),pending:c("未记录结果","No recorded result")}[z.status])),t("h4",{style:{marginTop:12}},c("调用参数","Arguments")),t("pre",{className:"cm-stat-pre"},z.arguments),t("h4",null,c("返回结果","Result")),t("pre",{className:"cm-stat-pre"},z.result||c("没有可显示的文本结果","No text result is available")),z.truncated?t("p",{className:"cm-stat-truncated"},c("内容已截取","Content truncated")):null)),t(xt,{offset:a,count:d.totalTools,size:20,onChange:p,text:c})):t(tt,null,I,t("p",{className:"cm-stat-note"},c("这一轮的原始日志不可用。","Original records for this turn are unavailable.")))}function je({api:e,sessionId:n,seq:l,atMs:o,revision:c,text:a,view:p,onViewChange:u}){const[r,b]=j(0),[x,m]=j(0),I=vt(e,"getCallInspection",{sessionId:n,seq:l,atMs:o,offset:r},c+":"+x),d=I.value,z=(w,g,P=!1)=>g?t("details",{className:"cm-stat-tool",open:P},t("summary",null,w,t("span",{className:"cm-stat-sub"},g.length.toLocaleString()+a(" 字符"," chars"))),t("pre",{className:"cm-stat-pre"},g)):null;return t("section",{className:"cm-stat-inspection cm-call-content","aria-label":a("调用内容","Call content")},t("nav",{className:"cm-session-tabs","aria-label":a("调用内容视图","Call content views")},...[["input",a("输入记录","Inputs")],["output",a("模型回复","Response")],["tools",a("工具调用","Tools")+(d?.totalTools?" · "+d.totalTools:"")]].map(([w,g])=>Y(g,()=>u(w),{key:w,"aria-pressed":p===w}))),I.failed?t(tt,null,ot(I.error),Y(a("重试","Retry"),()=>m(w=>w+1))):null,d?d.found?t(tt,null,p==="output"?t(tt,null,z(d.kind==="compaction"?a("压缩摘要","Compaction summary"):a("本次回复","Response"),d.output,!0),z(a("思考内容","Reasoning"),d.reasoning,!d.output),!d.output&&!d.reasoning?t("p",{className:"cm-stat-sub"},d.totalTools?a("本次回复为工具调用","This response contains tool calls"):a("未记录回复内容","No recorded response")):null):null,p==="input"?t(tt,null,z(a("本轮用户输入","Turn input"),d.input,!0),z(a("技能内容","Skills"),d.skills),z(a("注入内容","Injected context"),d.injected),z(a("上一步工具返回","Previous step’s tool results"),d.precedingTools),!d.input&&!d.skills&&!d.injected&&!d.precedingTools?t("p",{className:"cm-stat-sub"},a("未记录输入内容","No recorded input")):null):null,p==="tools"?t(tt,null,d.totalTools?null:t("p",{className:"cm-stat-sub"},a("本次没有工具调用","No tools in this call")),...d.tools.map((w,g)=>t("details",{key:w.callId,className:"cm-stat-tool",open:g===0},t("summary",null,w.name,t("span",{className:"cm-stat-sub"},(w.durationMs!=null?(w.durationMs/1e3).toLocaleString(void 0,{maximumFractionDigits:2})+" s · ":"")+{complete:a("已完成","Completed"),error:a("失败","Failed"),pending:a("未记录结果","No result")}[w.status])),t("div",{className:"cm-call-tool-parts"},t("div",null,t("h4",null,a("参数","Arguments")),t("pre",{className:"cm-stat-pre"},w.arguments)),t("div",null,t("h4",null,a("返回结果","Result")),t("pre",{className:"cm-stat-pre"},w.result||"—"))),w.truncated?t("span",{className:"cm-stat-truncated"},a("内容已截取","Content truncated")):null)),d.totalTools>20?t(xt,{offset:r,count:d.totalTools,size:20,onChange:b,text:a}):null):null,d.truncated?t("span",{className:"cm-stat-truncated"},a("长文本显示前 16,000 字符","Long text limited to 16,000 characters")):null):t("p",{className:"cm-stat-sub"},a("原始内容不可用","Original content unavailable")):I.loading?t("p",{role:"status"},a("读取调用内容…","Loading call content…")):null)}function Oe({call:e,sessionId:n,api:l,revision:o,money:c,text:a,names:p}){const[u,r]=j("output"),b=e.rows.filter(m=>m.tokens>0),x=b.filter(m=>m.bucket!=="reasoning"||m.cost>0||!m.priced).map(m=>({key:m.bucket,label:p[m.bucket],tokens:m.tokens,value:m.cost,unpriced:!m.priced,amount:m.priced?c(m.cost):a("未定价","Unpriced"),color:G[Ot[m.bucket]??7]}));return t("div",{className:"cm-call-detail-grid"},t("style",null,`
49
+ .cm-call-detail-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.35fr);gap:18px;margin-top:12px;align-items:start}
50
+ .cm-call-bill{min-width:0;container-type:inline-size}.cm-call-bill .cm-stat-value{font-size:22px}.cm-call-bill .cm-cost-chart{margin:10px 0 0}.cm-call-bill .cm-stat-table{font-size:11px}.cm-call-bill .cm-stat-table td,.cm-call-bill .cm-stat-table th{padding:8px 6px}.cm-call-bill .cm-stat-table td{font-variant-numeric:tabular-nums;white-space:nowrap}
51
+ .cm-call-content{min-width:0;padding:12px;margin:0}.cm-call-content .cm-session-tabs{margin-bottom:10px}.cm-call-content .cm-stat-pre{max-height:220px;font-size:12px;margin-bottom:8px}.cm-call-content .cm-stat-tool{padding:8px 0}.cm-call-content .cm-stat-tool>summary{color:var(--dsw-alias-label-primary)}.cm-call-tool-parts{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);gap:10px;margin-top:10px}.cm-call-tool-parts>div{min-width:0}
52
+ @container(max-width:850px){.cm-call-detail-grid{grid-template-columns:1fr}.cm-call-tool-parts{grid-template-columns:1fr}}
53
+ `),t("section",{className:"cm-plan cm-call-bill","aria-label":a("本次计费明细","Call billing breakdown")},t("div",{className:"cm-stat-panel-head"},t("h3",null,e.plan?a("Plan 等值费用","Plan equivalent"):a("API 费用","API cost")),t("strong",{className:"cm-stat-value"},e.priced?c(e.cost):"?")),t("p",{className:"cm-stat-sub"},new Date(e.atMs).toLocaleString()),t(lt,{rows:x,total:e.cost,label:a("本次费用构成","This call’s costs"),text:a,amounts:!0,onSelect:m=>r(["output","reasoning"].includes(m.key)?"output":"input")}),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[a("计费项目","Component"),"Tokens",a("单价 / 百万","Rate / 1M"),a("金额","Cost"),a("占比","Share")].map(m=>t("th",{key:m},m)))),t("tbody",null,...b.map(m=>{const I=m.bucket==="reasoning"&&m.priced&&m.rate===0;return t("tr",{key:m.bucket},t("td",null,p[m.bucket]),t("td",null,m.tokens.toLocaleString()),t("td",null,m.priced?c(m.rate):"?"),t("td",null,I?a("未单独计费","No separate charge"):m.priced?c(m.cost):"?"),t("td",null,m.priced&&!I?_(m.cost,e.cost):"—"))}))))),e.logSeq!=null?t(je,{api:l,sessionId:e.sessionId||n,seq:e.logSeq,atMs:e.atMs,revision:o,text:a,view:u,onViewChange:r}):t("p",{className:"cm-stat-sub"},a("未保存调用内容","Call content not stored")))}function ke({api:e,sessionId:n,revision:l,money:o,text:c,basis:a,composition:p,detailed:u=!1}){const[r,b]=j(0),[x,m]=j([]),[I,d]=j(""),[z,w]=j([]),[g,P]=j(!1),[Q,O]=j(0),k=vt(e,"getSessionTrajectory",{sessionId:n,offset:r,basis:a},l+":"+Q);nt(()=>{b(0),m([]),d(""),w([])},[n,l,a]),nt(()=>{k.value?.offset===r&&m(i=>r===0?k.value.steps:[...new Map([...i,...k.value.steps].map(M=>[M.key,M])).values()])},[k.value,r]);const T=k.value,V={input:c("输入","Input"),cacheRead:c("缓存读取","Cache read"),cacheWrite:c("缓存写入","Cache write"),output:c("输出","Output"),reasoning:c("推理","Reasoning")},v=i=>({model:c("模型调用","Model calls"),compaction:c("上下文压缩","Compaction"),search:c("原生搜索","Native search")})[i]??i,F=i=>i.rows.filter(M=>a==="total"||(a==="plan"?M.plan:!M.plan)),H=(i,M)=>{const h=F(i).filter(B=>M.includes(B.bucket));return o(h.reduce((B,it)=>B+it.cost,0))+(h.some(B=>!B.priced)?" + ?":"")};if(!T)return t("p",{className:"cm-stat-sub"},k.error||c("读取步骤费用…","Reading step costs…"),k.error?Y(c("重试","Retry"),()=>O(i=>i+1)):null);const R=D(T,a),S=T.shares.map((i,M)=>({key:i.key,label:i.other?c("其余 ","Other ")+i.count+c(" 步"," steps"):(i.sessionId!==n?c("子代理 · ","Subagent · "):"")+(i.turn==null?v(i.kind):c("轮次 ","Turn ")+i.turn+(i.step==null?"":c(" · 步骤 "," · step ")+i.step)),value:D(i,a),amount:o(D(i,a))+(i.unpriced?" + ?":""),meta:i.tools.join(" + ")||v(i.kind),unpriced:i.unpriced,color:G[i.other?7:M%7]})),E=x.length?x:T.steps,A=i=>u?!z.includes(i.key):I===i.key,W=i=>u?w(M=>M.includes(i.key)?M.filter(h=>h!==i.key):[...M,i.key]):d(I===i.key?"":i.key);return u?t("section",{className:"cm-step-cards cm-plan","aria-label":c("逐步费用明细","Cost details by step")},t("style",null,`
54
+ .cm-step-cards .cm-trajectory-pie{border:1px solid var(--cm-border);border-radius:12px;padding:14px;margin-bottom:12px}.cm-step-cards .cm-trajectory-pie .cm-cost-chart{grid-template-columns:180px minmax(0,1fr);gap:8px 20px;align-items:center}.cm-step-cards .cm-trajectory-pie .cm-cost-donut{width:180px;height:180px}.cm-step-cards .cm-trajectory-pie .cm-cost-center{inset:47px 30px}.cm-step-cards .cm-trajectory-pie .cm-cost-legend{grid-template-columns:repeat(2,minmax(0,1fr))}.cm-individual-steps>summary{padding:8px 0;font-size:13px}.cm-step-card-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.cm-step-fee-card{border:1px solid var(--cm-border);border-radius:12px;padding:12px;min-width:0;container-type:inline-size}.cm-step-fee-head{display:flex;justify-content:space-between;gap:8px;align-items:start}.cm-step-fee-head .cm-step-name{border:0;background:transparent;padding:0;text-align:left;font-size:12px;font-weight:500;min-width:0}.cm-step-fee-head small{display:block;margin-top:3px;overflow-wrap:anywhere;color:var(--cm-muted);font-size:10px;font-weight:400}.cm-step-fee-head strong{font-size:15px;font-weight:500;font-variant-numeric:tabular-nums}.cm-step-cards .cm-cost-chart{grid-template-columns:104px minmax(0,1fr);gap:5px 12px;margin:8px 0}.cm-step-cards .cm-cost-donut{width:104px;height:104px}.cm-step-cards .cm-cost-center{inset:25px 12px}.cm-step-cards .cm-cost-center b{font-size:19px}.cm-step-cards .cm-cost-legend{grid-template-columns:1fr;gap:2px}.cm-step-cards .cm-cost-key{padding:3px 4px;font-size:11px}.cm-step-cards .cm-cost-inspect{min-height:16px}.cm-step-cards .cm-stat-table td,.cm-step-cards .cm-stat-table th{font-size:10px;padding:6px 4px}.cm-step-cards .cm-step-rates{border-top:1px solid var(--cm-border)}.cm-step-cards .cm-step-rates td:not(:first-child){white-space:nowrap}.cm-step-cards .cm-step-more{text-align:center;margin-top:10px}
55
+ @container(max-width:720px){.cm-step-card-grid{grid-template-columns:1fr}.cm-step-cards .cm-trajectory-pie .cm-cost-chart{grid-template-columns:120px minmax(0,1fr);gap:6px}.cm-step-cards .cm-trajectory-pie .cm-cost-donut{width:120px;height:120px}.cm-step-cards .cm-trajectory-pie .cm-cost-center{inset:30px 18px}.cm-step-cards .cm-trajectory-pie .cm-cost-legend{grid-template-columns:1fr}}
56
+ `),k.error?t("p",{className:"cm-stat-error"},k.error):null,t("section",{className:"cm-trajectory-pie","aria-label":c("轨迹步骤费用占比","Trajectory step cost shares")},t("div",{className:"cm-stat-panel-head"},t("h3",null,c("轨迹步骤费用占比","Trajectory step cost shares")),t("span",{className:"cm-stat-sub"},T.totalSteps+c(" 步 · "," steps · ")+o(R))),t(lt,{rows:S,total:R,label:c("总费用占比","Total cost share"),text:c,amounts:!0})),t("details",{className:"cm-individual-steps",open:g,onToggle:i=>{i.target===i.currentTarget&&P(i.currentTarget.open)}},t("summary",null,c("逐步费用明细","Individual step details")+" · "+T.totalSteps),g?t("div",{className:"cm-step-card-grid"},...E.map(i=>{const M=new Map;for(const h of F(i)){if(h.bucket==="reasoning"&&h.priced&&h.cost===0)continue;const B=M.get(h.bucket)??{key:h.bucket,label:V[h.bucket]??h.bucket,value:0,tokens:0,unpriced:!1,color:G[Ot[h.bucket]??7]};B.value+=h.cost,B.tokens+=h.tokens,B.unpriced||=!h.priced,M.set(h.bucket,B)}return t("article",{className:"cm-step-fee-card",key:i.key},t("div",{className:"cm-step-fee-head"},t("button",{type:"button",className:"cm-step-name","aria-expanded":A(i),onClick:()=>W(i)},(A(i)?"⌄ ":"› ")+(i.sessionId!==n?c("子代理 · ","Subagent · "):"")+(i.turn==null?v(i.kind):c("轮次 ","Turn ")+i.turn+(i.step==null?"":c(" · 步骤 "," · step ")+i.step)),t("small",null,i.tools.length?i.tools.join(" + "):v(i.kind))),t("div",{style:{textAlign:"right"}},t("strong",null,o(D(i,a))+(i.unpriced?" + ?":"")),t("small",null,_(D(i,a),R)+c(" 会话费用"," of session cost")))),t(lt,{rows:[...M.values()].map(h=>({...h,amount:o(h.value)+(h.unpriced?" + ?":"")})),total:D(i,a),label:c("本步费用","Step cost"),text:c,amounts:!0}),A(i)?t("div",{className:"cm-step-rates cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("计费项目","Billing item"),"Tokens",c("单价 / 百万","Rate / million"),c("金额","Cost")].map(h=>t("th",{key:h},h)))),t("tbody",null,...F(i).map((h,B)=>t("tr",{key:B},t("td",{title:h.provider+" / "+h.model},V[h.bucket]??h.bucket),t("td",null,h.tokens.toLocaleString()),t("td",null,h.priced?o(h.rate):"—"),t("td",null,h.priced?o(h.cost):c("未定价","Unpriced"))))))):null)})):null),g&&E.length<T.totalSteps?t("div",{className:"cm-step-more"},Y(k.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:k.loading})):null):t("section",{className:"cm-step-costs cm-plan","aria-label":c("步骤计费","Step billing")},t("style",null,`
57
+ .cm-stat-session .cm-step-costs{margin:6px 0}.cm-step-costs .cm-step-name{border:0!important;padding:0!important;background:transparent!important;flex-direction:row!important;align-items:center;gap:8px!important}.cm-step-costs .cm-step-name small{max-width:150px!important}.cm-step-cost-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;align-items:start}.cm-step-cost-grid>section{min-width:0}.cm-step-cost-grid>section:last-child{grid-column:1/-1}.cm-step-costs .cm-spend-card{padding:12px!important}.cm-step-costs .cm-cost-chart{grid-template-columns:98px minmax(0,1fr);gap:4px 8px;margin-top:8px}.cm-step-costs .cm-cost-donut{width:98px;height:98px}.cm-step-costs .cm-cost-center{inset:24px 12px}.cm-step-costs .cm-cost-center b{font-size:18px}.cm-step-costs .cm-cost-key{padding:4px 2px!important;font-size:11px!important}.cm-step-costs .cm-cost-legend{grid-template-columns:1fr}.cm-step-costs .cm-cost-inspect{min-height:16px}.cm-step-costs .cm-stat-table td,.cm-step-costs .cm-stat-table th{padding:6px;font-size:11px}.cm-step-costs td:not(:first-child){white-space:nowrap}.cm-step-costs .cm-step-name{display:flex;flex-direction:column;gap:2px;min-width:100px;font-size:12px}.cm-step-costs .cm-step-name small{color:var(--cm-muted);font-size:10px;max-width:190px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-step-costs .cm-step-rates{padding:10px;background:var(--cm-surface)}.cm-step-costs .cm-step-more{margin-top:8px;text-align:center}.cm-step-costs .cm-stat-panel-head{margin-bottom:6px}
58
+ @container(max-width:760px){.cm-step-cost-grid{grid-template-columns:1fr}.cm-step-costs .cm-cost-chart{grid-template-columns:98px minmax(0,1fr)}.cm-step-costs .cm-cost-legend{grid-template-columns:repeat(2,minmax(0,1fr))}}
59
+ `),k.error?t("p",{className:"cm-stat-error"},k.error):null,t("div",{className:"cm-step-cost-grid"},p,u?null:t("section",{className:"cm-spend-card","aria-label":c("步骤费用构成","Step cost composition")},t("h3",null,c("步骤费用构成","Step cost composition")),t(lt,{rows:S,total:R,label:c("费用占比","Cost share"),text:c,amounts:!1})),t("section",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c("计费轨迹","Billing trajectory")+" · "+T.totalSteps+c(" 步"," steps"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("步骤 / 工具","Step / tools"),c("输入","Input"),c("输出","Output"),c("缓存","Cache"),c("费用","Cost"),c("占比","Share")].map(i=>t("th",{key:i},i)))),t("tbody",null,...E.map(i=>t(tt,{key:i.key},t("tr",null,t("td",null,t("button",{type:"button",className:"cm-step-name","aria-expanded":A(i),onClick:()=>W(i)},t("span",null,(A(i)?"⌄ ":"› ")+(i.sessionId!==n?c("子代理 · ","Subagent · "):"")+(i.turn==null?v(i.kind):c("轮次 ","Turn ")+i.turn+(i.step==null?"":c(" · 步骤 "," · step ")+i.step))),t("small",{title:i.tools.join(" + ")},i.tools.length?i.tools.join(" + "):v(i.kind)))),t("td",null,H(i,["input"])),t("td",null,H(i,["output","reasoning"])),t("td",null,H(i,["cacheRead","cacheWrite"])),t("td",null,o(D(i,a))+(i.unpriced?" + ?":"")),t("td",null,_(D(i,a),R))),A(i)?t("tr",null,t("td",{colSpan:6,className:"cm-step-rates"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("模型 / 项目","Model / item"),"Tokens",c("单价 / 百万","Rate / million"),c("金额","Cost")].map(M=>t("th",{key:M},M)))),t("tbody",null,...F(i).map((M,h)=>t("tr",{key:h},t("td",null,M.model+" · "+(V[M.bucket]??M.bucket)),t("td",null,M.tokens.toLocaleString()),t("td",null,M.priced?o(M.rate):"—"),t("td",null,M.priced?o(M.cost):c("未定价","Unpriced")))))))):null))))),E.length<T.totalSteps?t("div",{className:"cm-step-more"},Y(k.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:k.loading})):null)))}function Vt({api:e,query:n,revision:l,money:o,formatTokens:c,text:a,overview:p=!1,children:u}){const[r,b]=j(0),[x,m]=j(-1),[I,d]=j(0),[z,w]=j("summary"),[g,P]=j(!1),[Q,O]=j(null),[k,T]=j("cost"),[V,v]=j(0),F=vt(e,"getSessionBilling",{...n,offset:r,turnOffset:I},l+":"+V),H=dt(!1);nt(()=>{H.current&&!F.loading&&x>=0&&(document.getElementById("cm-stat-call-"+x)?.scrollIntoView({block:"nearest"}),H.current=!1)},[F.loading,F.value,r,x,z]);const R=F.value,S=n.basis,E={input:a("非缓存输入","Uncached input"),output:a("输出","Output"),cacheRead:a("缓存读取","Cache read"),cacheWrite:a("缓存写入","Cache write"),reasoning:a("推理","Reasoning")},A={model:a("模型调用","Model call"),compaction:a("上下文压缩","Compaction"),search:a("原生搜索","Native search")},W=s=>s==null?a("未标明轮次","Turn not recorded"):a("轮次 ","Turn ")+s;if(Pt(F))return F.loading?t("p",{className:"cm-stat-empty",role:"status"},a("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):ot(F.error);const i=F.failed?t("div",null,ot(F.error),Y(a("重试","Retry"),()=>v(s=>s+1))):null;if(!R.found)return t(tt,null,i,t("p",{className:"cm-stat-note"},a("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),u);const M=s=>!s||s===n.sessionId?a("主会话","Main conversation"):a("子代理 ","Subagent ")+((R.agents??[]).find(N=>N.id===s)?.title||s).slice(0,80),h=s=>JSON.stringify([s.sessionId||n.sessionId,s.turn]),B=s=>((R.agents?.length??0)>1?M(s.sessionId)+" · ":"")+W(s.turn),it=s=>S==="total"||(S==="plan"?s.plan:!s.plan),Z=Object.keys(E).map(s=>{const N=R.rows.filter(L=>L.bucket===s&&it(L));return{bucket:s,tokens:N.reduce((L,q)=>L+q.tokens,0),cost:N.reduce((L,q)=>L+q.cost,0),unpriced:N.some(L=>!L.priced)}}),st=D(R,S),pt=D(R.recorded,S),_t=Math.abs(st-pt)>Math.max(1e-8,Math.abs(pt)*1e-8)||R.totalCalls!==R.recorded.calls,yt=Z.some(s=>s.unpriced),$=yt?a("已知费用占比","Known cost share"):a("费用占比","Cost share"),ut=s=>{w("summary"),H.current=!0,b(Math.floor(s/50)*50),m(s%50)},f=s=>({key:s.bucket,label:E[s.bucket],tokens:s.tokens,value:s.cost,unpriced:s.unpriced,amount:s.unpriced&&!s.cost?a("未定价","Unpriced"):o(s.cost)+(s.unpriced?" + ?":""),color:G[Ot[s.bucket]??7]}),X=new Map;for(const s of R.rows.filter(it)){const N=JSON.stringify([s.provider,s.model]),L=X.get(N)??{key:N,label:s.model,provider:s.provider,tokens:0,value:0,unpriced:!1};L.value+=s.cost,L.tokens+=s.bucket==="reasoning"?0:s.tokens,L.unpriced||=!s.priced,X.set(N,L)}const at=[...X.values()].sort((s,N)=>N.value-s.value).map((s,N)=>({...s,label:s.provider+" / "+s.label,amount:s.unpriced&&!s.value?a("未定价","Unpriced"):o(s.value)+(s.unpriced?" + ?":""),color:G[N%7]}));if(at.length>7){const s=at.splice(7),N=s.reduce((q,Ct)=>q+Ct.value,0),L=s.some(q=>q.unpriced);at.push({key:"other-models",label:a("其余 ","Other ")+s.length+a(" 个模型"," models"),value:N,tokens:s.reduce((q,Ct)=>q+Ct.tokens,0),unpriced:L,amount:L&&!N?a("未定价","Unpriced"):o(N)+(L?" + ?":""),color:G[7]})}const kt=Z.find(s=>s.bucket==="cacheRead"),Nt=Z.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)),mt=kt.tokens>0?t("div",{className:"cm-cache-compare"},t("h3",null,a("缓存读取的占比","Cache read share")),...[[a("输入 Token","Input tokens"),kt.tokens,Nt.reduce((s,N)=>s+N.tokens,0)],[a("输入费用","Input cost"),kt.cost,Nt.some(s=>s.unpriced)?0:Nt.reduce((s,N)=>s+N.cost,0)]].map(([s,N,L])=>t("div",{key:s},t("div",{className:"cm-stat-share-head"},t("span",null,s),t("span",null,_(N,L))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{style:{display:"block",height:"100%",width:(L>0?N/L*100:0)+"%",borderRadius:9,background:G[6]}}))))):null,rt=(s,N,L={},q=null)=>t("section",{className:"cm-spend-card","aria-label":s},t("h3",null,s),t(lt,{rows:N,total:st,label:$,text:a,amounts:!0,...L}),q),Ie=(R.callShares?.length??0)>0?rt(a("每次调用费用占比","Cost share per call"),R.callShares.map((s,N)=>({...s,key:String(s.index),label:s.other?a("其余 ","Other ")+s.calls+a(" 次调用"," calls"):a("调用 #","Call #")+(s.index+1),meta:s.other?s.calls+a(" 次调用"," calls"):s.tokens.toLocaleString()+" tokens",value:D(s,S),amount:s.unpriced&&!D(s,S)?a("未定价","Unpriced"):o(D(s,S))+(s.unpriced?" + ?":""),color:G[s.other?7:N%7]})),{onSelect:s=>{s.other||ut(s.index)}}):null,Te=(s,N,L)=>t("div",{className:"cm-stat-scroll",style:{marginTop:20}},t("h3",null,s),t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[s,a("调用次数","Calls"),a("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",a("Plan 等值","Plan equivalent")].map(q=>t("th",{key:q},q)))),t("tbody",null,N.map((q,Ct)=>t("tr",{key:Ct},t("td",null,L(q)),t("td",null,q.calls),t("td",null,[q.input,q.cacheRead+q.cacheWrite,q.output].map(c).join(" / ")),t("td",null,o(q.apiCost)+(q.unpriced?" + ?":"")),t("td",null,o(Math.max(0,q.cost-q.apiCost))+(q.unpriced?" + ?":"")))))));return t("section",{className:"cm-stat-panel"},t("style",null,jt+Re),p?t("nav",{className:"cm-session-tabs","aria-label":a("费用视图","Cost views")},...[["summary",a("费用概览","Overview")],["context",a("费用明细","Cost details")]].map(([s,N])=>Y(N,()=>{w(s),m(-1),P(!1)},{key:s,"aria-pressed":z===s}))):null,p?t("div",{className:"cm-stat-metrics"},...[[S==="total"?a("API + Plan 等值","API + Plan equivalent"):S==="plan"?a("Plan 等值","Plan equivalent"):a("API 费用","API cost"),o(st)+(Z.some(s=>s.unpriced)?" + ?":""),a("按本对话调用日志估算","Estimated from this conversation’s call logs")],[a("调用次数","Calls"),R.totalCalls.toLocaleString(),(R.agents?.length??0)>1?a("包含子代理","Includes subagents"):a("本会话","This conversation")],[a("Token 用量","Token usage"),c(Z.reduce((s,N)=>s+(N.bucket==="reasoning"?0:N.tokens),0)),a("输入、缓存与输出","Input, cache and output")],[a("缓存命中率","Cache hit rate"),_(Z.find(s=>s.bucket==="cacheRead")?.tokens??0,Z.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)).reduce((s,N)=>s+N.tokens,0)),a("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([s,N,L])=>t("div",{className:"cm-stat-metric",key:s},t("div",{className:"cm-stat-sub"},s),t("div",{className:"cm-stat-value"},N),t("div",{className:"cm-stat-sub"},L)))):null,p&&z==="context"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:S,detailed:!0}):null,p?z==="context"?t("details",{className:"cm-stat-secondary"},t("summary",{style:{padding:"8px 0"}},a("上下文费用参考","Context cost reference")),u):null:u,p?null:t("div",{className:"cm-stat-panel-head"},t("h3",null,p?a("已发生费用 · 调用明细","Recorded costs · call details"):a("单对话费用明细","Conversation cost details")),t("span",{className:"cm-stat-sub"},(R.agents?.length??0)>1?a("包含子代理及其后代","Includes subagents and their descendants"):a("本会话自身的调用","Own conversation calls"))),i,!p&&_t?t("p",{className:"cm-stat-note"},a("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+o(pt)+" / "+R.recorded.calls+a(" 次;明细 "," calls; details ")+o(st)+" / "+R.totalCalls+a(" 次。"," calls.")):null,(!p||z==="calls")&&(R.agents?.length??0)>1?Te(a("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),R.agents,s=>M(s.id)):null,p?null:t("div",{className:"cm-plan cm-spend"},yt?t("p",{className:"cm-plan-sub"},a("存在未定价调用","Some calls are unpriced")):null,t("div",{className:"cm-spend-grid"},rt(a("费用构成","Cost composition"),Z.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f),{},mt),Ie,at.length>1?rt(a("模型费用分布","Cost by model"),at):null,R.kinds.length>1?rt(a("各环节费用占比","Cost by activity"),R.kinds.map((s,N)=>({key:s.kind,label:A[s.kind]??s.kind,value:D(s,S),tokens:gt(s),meta:s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok",unpriced:s.unpriced,amount:o(D(s,S))+(s.unpriced?" + ?":""),color:G[N]}))):null)),p&&z==="summary"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:S,composition:rt(a("费用构成","Cost composition"),Z.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f))}):null,!p||z==="summary"?t("details",{className:"cm-call-section",open:!p||g||x>=0,onToggle:s=>{s.target===s.currentTarget&&(P(s.currentTarget.open),s.currentTarget.open||m(-1))}},t("summary",{style:{padding:"10px 0",fontSize:13}},a("逐次调用明细","Individual calls")+" · "+R.totalCalls),p?t("div",{className:"cm-plan cm-spend-grid"},Ie,at.length>1?rt(a("模型费用分布","Cost by model"),at):mt):null,p?null:t("details",{className:"cm-stat-secondary",open:!p},t("summary",null,a("轮次、步骤与单价","Turns, steps and rates")),t("section",{className:"cm-stat-breakdown"},t("div",{className:"cm-stat-panel-head"},t("h3",null,a("各步骤占比","Share by step")),t("div",{className:"cm-stat-periods"},...[["cost",a("费用","Cost")],["calls",a("调用次数","Calls")]].map(([s,N])=>Y(N,()=>T(s),{key:s,"aria-pressed":k===s})))),t(xe,{title:k==="cost"?a("费用占比 · 全部调用","Cost share · all calls"):a("调用次数占比 · 全部调用","Call count share · all calls"),rows:(R.stepShares?.[k]??[]).map(s=>({label:s.other?a("其余步骤合计","All other steps"):B(s)+(s.step==null?"":a(" · 步骤 "," · step ")+s.step),value:k==="cost"?D(s,S):s.calls,unpriced:k==="cost"&&s.unpriced,other:s.other})),total:k==="cost"?st:R.totalCalls,format:k==="cost"?o:s=>s.toLocaleString(),text:a,columns:!0})),t("details",{className:"cm-stat-help"},t("summary",null,a("单价与 Token 明细","Rates and token details")),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[a("费用构成","Cost component"),"Tokens",a("费用","Cost"),a("费用占比","Cost share")].map(s=>t("th",{key:s},s)))),t("tbody",null,Z.map(s=>t("tr",{key:s.bucket},t("td",null,E[s.bucket]),t("td",null,s.tokens.toLocaleString()),t("td",null,o(s.cost)+(s.unpriced?" + ?":"")),t("td",null,_(s.cost,st))))))),Te(a("按调用类型统计","Cost by call type"),R.kinds,s=>A[s.kind]??s.kind)),t("section",{className:"cm-stat-turns"},t("div",{className:"cm-stat-panel-head"},t("h3",null,a("按轮次统计","Cost by turn")),t("span",{className:"cm-stat-sub"},a("展开查看输入和工具调用","Expand to inspect input and tool calls"))),R.turns.map(s=>t("div",{key:h(s),className:"cm-stat-turn"},t("button",{type:"button",className:"cm-stat-turn-toggle",disabled:s.turn==null,"aria-expanded":s.turn!=null&&Q===h(s),onClick:()=>O(N=>N===h(s)?null:h(s))},t("span",null,(s.turn==null?"":Q===h(s)?"⌄ ":"› ")+B(s)),t("span",null,s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok · "+o(D(s,S))+(s.unpriced?" + ?":"")+" · "+_(D(s,S),st))),s.turn!=null&&Q===h(s)?t(ye,{key:h(s),api:e,sessionId:s.sessionId||n.sessionId,turn:s.turn,revision:l,text:a}):null))),t(xt,{offset:I,count:R.totalTurns,size:25,onChange:s=>{d(s),O(null)},text:a})),t("div",{style:{marginTop:24}},t(he,{rows:R.calls.map((s,N)=>({label:"#"+(r+N+1),index:N,value:D(s,S)})),money:o,text:a,label:a("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:s=>{m(s.index),document.getElementById("cm-stat-call-"+s.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),R.calls.map((s,N)=>t("details",{key:r+N,id:"cm-stat-call-"+N,className:"cm-stat-call",open:x===N,onToggle:L=>{L.currentTarget.open?m(N):m(q=>q===N?-1:q)}},t("summary",null,"#"+(r+N+1)+" · "+B(s)+(s.step==null?"":a(" / 步骤 "," / step ")+s.step)+" · "+(A[s.kind]??s.kind)+" · "+s.provider+" / "+s.model+" · "+(s.plan?"Plan ":"API ")+(s.priced?o(s.cost):"?")+(s.longContext?a(" · 长上下文价"," · long-context rate"):""),t("span",{className:"cm-call-share"},(s.priced?_(D(s,S),st):"—")+" · "+$)),x===N?t(Oe,{key:(s.sessionId||n.sessionId)+":"+(s.logSeq??N),call:s,sessionId:n.sessionId,api:e,revision:l,money:o,text:a,names:E}):null)),t(xt,{offset:r,count:R.totalCalls,size:50,onChange:s=>{b(s),m(-1)},text:a})):null)}function Ne(e,n,l){const o=()=>["api","plan","total"].includes(e.statisticsBasis)?e.statisticsBasis:e.showTotalWithPlan?"total":"api",[c,a]=j(o),[p,u]=j(!1),[r,b]=j("");return nt(()=>{p||a(o())},[e.statisticsBasis,e.showTotalWithPlan,p]),{basis:c,choose:async m=>{if(!(p||!["api","plan","total"].includes(m))){a(m),u(!0),b("");try{await n.saveStatisticsBasis(m)}catch{b(l("计费口径保存失败,请重试。","Could not save the cost basis. Try again."))}finally{u(!1)}}},saving:p,error:r}}function Ce({state:e,api:n,sessionId:l,formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:p}){const u=(w,g)=>(a?a(e.config):e.config.locale)==="en"?g:w,[r,b]=j(0),x=Ne(e.config,n,u),{basis:m}=x,I=Rt(e,r),d=w=>o(w,{...e.config,decimals:Math.max(w!==0&&Math.abs(w)<.01?8:4,e.config.decimals??2)}),z={sessionId:l,from:"",to:"",provider:"",model:"",basis:m,offset:0};return t("div",{className:"cm-stat cm-stat-session","data-session-id":l},t("style",null,re),t("div",{className:"cm-stat-panel-head"},t("p",{className:"cm-stat-sub"},u("当前对话 · 全部调用","This conversation · all calls")),Y(u("刷新","Refresh"),()=>b(w=>w+1))),t(Vt,{key:l+":"+m,api:n,query:z,revision:I,money:d,formatTokens:c,text:u,overview:!0},t(Et,{key:l,api:n,sessionId:l,revision:I,money:d,text:u,compact:!0,expanded:!0})),t("details",{className:"cm-session-options"},t("summary",null,u("显示与联动设置","Display and integration settings")),t("div",{className:"cm-stat-controls"},t("label",null,u("计费口径","Cost basis"),t("select",{value:m,disabled:x.saving,onChange:w=>x.choose(w.target.value)},...[["api",u("API 费用","API cost")],["plan",u("Plan 等值","Plan equivalent")],["total",u("API + Plan 等值","API + Plan equivalent")]].map(([w,g])=>t("option",{key:w,value:w},g))))),x.error?ot(x.error):null,p?t(Qt,p):null))}function we({state:e,api:n,sessionId:l="",formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:p}){const u=a?a(e.config)==="en":e.config.locale==="en"||e.config.locale!=="zh"&&(e.config.activeLocale||e.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",r=(f,X)=>u?X:f,[b,x]=j(l?"all":"week"),[m,I]=j(null),[d,z]=j({id:l,title:l}),[w,g]=j(""),[P,Q]=j(""),O=Ne(e.config,n,r),{basis:k}=O,[T,V]=j(0),[v,F]=j(0),[H,R]=j(!1),S=e.meta.dayKey||new Date().toISOString().slice(0,10),E=b==="all"?"":b==="custom"?m?.from||S:Xt(S,b==="week"?-6:b==="month"?-29:0),A=b==="custom"&&m?.to||S,W={from:E,to:A,provider:w,model:P,basis:k,sessionId:d.id,offset:T},i=Rt(e,v),M=vt(n,"getBillingStatistics",W,i),h=M.value,B=f=>o(f,{...e.config,decimals:Math.max(f!==0&&Math.abs(f)<.01?8:4,e.config.decimals??2)}),it=f=>{x(f),V(0)},Z=f=>{z(f),V(0),g(""),Q("")},st=k==="total"?r("API + Plan 等值","API + Plan equivalent"):k==="plan"?r("Plan 等值","Plan equivalent"):r("API 费用","API cost"),pt=(f,X,at,kt,Nt=!1)=>t("label",null,f,t("select",{value:X,disabled:Nt,onChange:mt=>{at(mt.target.value),V(0)}},kt.map(([mt,rt])=>t("option",{key:mt,value:mt},rt)))),_t={input:r("未缓存输入","Uncached input"),cacheRead:r("缓存读取","Cache read"),cacheWrite:r("缓存写入","Cache write"),output:r("输出","Output")},yt=(f,X)=>t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,f)),X),$=h?.totals,ut=(f,X,at)=>t("div",{className:"cm-stat-metric",key:f},t("div",{className:"cm-stat-sub"},f),t("div",{className:"cm-stat-value"},X),t("div",{className:"cm-stat-sub"},at));return t("div",{className:"cm-stat"},t("style",null,re),p?t(Qt,p):null,t("header",{className:"cm-stat-head"},t("div",null,t("h2",null,r("计费统计","Cost statistics")),t("p",{className:"cm-stat-sub"},d.id?r("单对话 · ","Conversation · ")+(d.title===d.id&&h?.sessions[0]?.title||d.title):r("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),Y(r("刷新","Refresh"),()=>F(f=>f+1))),d.id?Y(r("← 全部对话","← All conversations"),()=>Z({id:"",title:""})):null,t("div",{className:"cm-stat-controls"},t("div",{className:"cm-stat-periods"},...[["today",r("今天","Today")],["week",r("近 7 天","Last 7 days")],["month",r("近 30 天","Last 30 days")],["all",r("全部记录","All retained")],["custom",r("自定义","Custom")]].map(([f,X])=>Y(X,()=>it(f),{key:f,"aria-pressed":b===f})))),b==="custom"?t("div",{className:"cm-stat-controls"},...["from","to"].map(f=>t("label",{key:f},f==="from"?r("开始日期","From"):r("结束日期","To"),t("input",{type:"date",value:f==="from"?E:A,onChange:X=>{I({from:E,to:A,[f]:X.target.value}),V(0)}})))):null,t("div",{className:"cm-stat-controls"},pt(r("计费口径","Cost basis"),k,O.choose,[["api",r("API 费用","API cost")],["plan",r("Plan 等值","Plan equivalent")],["total",r("API + Plan 等值","API + Plan equivalent")]],O.saving),pt(r("提供商","Provider"),w,f=>{g(f),Q("")},[["",r("全部提供商","All providers")],...[...new Set([w,...h?.providers??[]])].filter(Boolean).map(f=>[f,f])]),pt(r("模型","Model"),P,Q,[["",r("全部模型","All models")],...[...new Set([P,...h?.modelOptions??[]])].filter(Boolean).map(f=>[f,f])])),O.error?ot(O.error):null,Pt(M)?M.loading?t("p",{className:"cm-stat-empty",role:"status"},r("加载统计…","Loading statistics…")):ot(M.error):h?t(tt,null,M.failed?ot(M.error):null,t("p",{className:"cm-stat-sub",style:{marginTop:8}},h.from+" – "+h.to+(h.retainedFrom?" · "+r("账本保留范围 ","Retained ledger ")+h.retainedFrom+" – "+h.retainedTo:"")),t("div",{className:"cm-stat-metrics"},ut(r("API 费用","API cost"),B($.apiCost),r("已入账估算","Recorded estimate")),ut(r("Plan 等值费用","Plan equivalent"),B(Math.max(0,$.cost-$.apiCost)),""),ut(r("调用次数","Calls"),$.calls.toLocaleString(),h.sessionCount+r(" 个对话 · 平均 "," conversations · average ")+B($.calls?D($,k)/$.calls:0)),ut(r("缓存命中率","Cache hit rate"),_($.cacheRead,$.input+$.cacheRead+$.cacheWrite),c(gt($))+" Tokens")),d.id?t("section",{className:"cm-stat-panel"},t(Et,{key:d.id,api:n,sessionId:d.id,revision:i,money:B,text:r})):null,d.id?t(Vt,{key:JSON.stringify([d.id,E,A,w,P,k]),api:n,query:{...W,from:h.from,to:h.to,offset:0},revision:i,money:B,formatTokens:c,text:r}):null,h.models.some(f=>!f.priced)?t("p",{className:"cm-stat-note"},r("部分模型未配置价格","Some models have no rates")):null,!$.calls&&!$.cost?t("p",{className:"cm-stat-empty"},r("所选范围没有已记录的用量。","No recorded usage in this range.")):null,t("section",{className:"cm-stat-panel"},t(he,{rows:ve(h.days,k),money:B,text:r,label:r("费用趋势 · ","Cost over time · ")+st,onSelect:f=>{I({from:f.from,to:f.to}),it("custom")}})),t("div",{className:"cm-stat-grid"},yt(r("模型费用排行","Cost by model"),t(tt,null,t("ol",{className:"cm-stat-rank"},(H?h.models:h.models.slice(0,8)).map(f=>t("li",{key:f.key},t("button",{type:"button",onClick:()=>{g(f.provider),Q(f.model),V(0)},title:f.key},t("div",{className:"cm-stat-rankline"},t("span",null,f.model),t("span",{className:"cm-stat-number"},B(D(f,k))+(f.priced?"":" + ?"))),t("div",{className:"cm-stat-sub"},f.provider+" · "+f.calls+r(" 次 · "," calls · ")+_(D(f,k),D($,k))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_(D(f,k),D($,k))}}))))),h.models.length>8?Y(H?r("收起","Show less"):r("显示全部模型","Show all models"),()=>R(f=>!f)):null,h.unmodeledCost>1e-8?t("p",{className:"cm-stat-note"},r("历史未分配到模型的费用:","Historical cost without a model: ")+B(h.unmodeledCost)):null)),yt(r("Token 构成","Token composition"),t(tt,null,t("ol",{className:"cm-stat-rank"},Object.entries(_t).map(([f,X])=>t("li",{key:f},t("div",{className:"cm-stat-rankline"},t("span",null,X),t("span",{className:"cm-stat-number"},c($[f]))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_($[f],gt($)),background:f.startsWith("cache")?"var(--cm-plan)":void 0}}))))),t("p",{className:"cm-stat-sub"},r("单独上报的推理 Token:","Reported reasoning tokens: ")+c($.reasoning))))),d.id?null:t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,r("对话费用排行","Cost by conversation")),t("span",{className:"cm-stat-sub"},e.config.includeSubagentCost?r("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):r("点击对话查看明细","Select a conversation for details"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[r("对话","Conversation"),r("调用","Calls"),"API",r("Plan 等值","Plan equivalent"),r("缓存命中","Cache hits")].map(f=>t("th",{key:f},f)))),t("tbody",null,h.sessions.map(f=>t("tr",{key:f.id},t("td",null,t("button",{type:"button",title:f.id,onClick:()=>Z({id:f.id,title:f.title})},f.title)),t("td",null,f.calls.toLocaleString()),t("td",null,B(f.apiCost)),t("td",null,B(Math.max(0,f.cost-f.apiCost))),t("td",null,_(f.cacheRead,f.input+f.cacheRead+f.cacheWrite))))))),h.unassignedCost>1e-8?t("p",{className:"cm-stat-note"},r("未关联对话的费用:","Cost not linked to a conversation: ")+B(h.unassignedCost)):null,t(xt,{offset:T,count:h.sessionCount,size:25,onChange:V,text:r})))):null)}function Se(e,{state:n,sessionId:l=""}={}){if(!n||document.hidden)return;const o=Rt(n,0),c=n.meta.dayKey||new Date().toISOString().slice(0,10),a={sessionId:l,from:l?"":Xt(c,-6),to:l?"":c,provider:"",model:"",basis:n.config.showTotalWithPlan?"total":"api",offset:0};return Promise.all(l?[Mt(e,"getSessionBilling",{...a,turnOffset:0},o+":0")]:[Mt(e,"getBillingStatistics",{from:a.from,to:a.to,provider:"",model:"",basis:a.basis,sessionId:"",offset:0},o)])}async function Ee(e,n,l){const o=typeof n=="function"?n:()=>n&&l?l(n.getSnapshot().state?.config??{activeLocale:n.getSnapshot().locale}):"en",c=await e.get("remote").$mount(le);e.effect(()=>()=>c(),"cost-meter: statistics contribution");const a=e.get("remote.costMeter"),p=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getCallInspection","getContextCosts","getSessionTrajectory"].map(b=>[b,async x=>{const m=await a[b]((b==="getSessionTrajectory"?se:b==="getContextCosts"?zt:b==="getCallInspection"?oe:b==="getTurnInspection"?ne:ce)(x));if(!m?.ok)throw new Error(m?.error?.message||"Statistics request failed");return{getBillingStatistics:Bt,getSessionBilling:Dt,getTurnInspection:St,getCallInspection:Zt,getContextCosts:Ut,getSessionTrajectory:ae}[b](m.value)}]));p.saveStatisticsBasis=async b=>{const x=await a.updateConfig({statisticsBasis:b});if(!x?.ok||x.value?.config?.statisticsBasis!==b)throw new Error("Cost basis setting failed");n?.set?.({status:"ready",error:null,state:x.value})};let u;if(n?.subscribe&&typeof e.get("slots")?.entries=="function"){p.getContextIntegration=async()=>{const m=await a.getContextIntegration();if(!m?.ok)throw new Error("Integration check failed");return ee(m.value)},p.saveIntegration=async m=>{const I=await a.updateConfig({contextCostsEnabled:m,contextCostsPromptSeen:!0});if(!I?.ok||!I.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:I.value})},u=ge(e,p,n,o,Ht("react-dom").createPortal),e.effect(()=>u.dispose,"cost-meter: optional dsh-context integration");const b=e.get("slots"),x=()=>b.register({name:"shell.overlay",id:"cost-meter-context-intro",order:50},()=>t(be,{manager:u,getLocale:o}));typeof b.inject=="function"&&e.effect(()=>b.inject("shell.overlay",x),"cost-meter: context preview prompt")}const r=b=>t(b.sessionId?Ce:we,{...b,api:p,contextIntegration:u?{manager:u,getLocale:o}:null});return r.prefetch=b=>Se(p,b),e.effect(()=>()=>Ft.delete(p),"cost-meter: statistics cache cleanup"),r}return{mount:Ee,prefetchStatistics:Se,Statistics:we,SessionStatistics:Ce,SessionDetail:Vt,TurnInspection:ye,ShareChart:xe,ContextCosts:Et,ContextPrompt:be,ContextPreview:Jt,ContextIntegrationSettings:Qt,createContextIntegration:ge,contextCostBreakdown:me,installContextCosts:de,CONTRIBUTION:le,parseContextCosts:Ut,parseStatistics:Bt,parseDetail:Dt,parseInspection:St,dailyChartRows:ve,requestStart:ie,requestValue:ft,requestFailure:pe,showsPlaceholder:Pt,refreshKeyOf:Rt}}});
@@ -9,8 +9,8 @@ const count = value => typeof value === 'number' && Number.isFinite(value) && va
9
9
  const zeroParts = () => Object.fromEntries(CONTEXT_PARTS.map(key => [key, 0]))
10
10
  const sourceName = source => typeof source === 'string' ? source : source?.type ?? source?.kind ?? ''
11
11
 
12
- // Exact releases exercised with their published client, not an inferred range.
13
- export const CONTEXT_VERSIONS = ['0.62.0', '0.66.0']
12
+ // The client checks the active peer registrations and required slot APIs.
13
+ // Release numbers are informational: compatible interfaces may survive upgrades.
14
14
  export async function getContextIntegration(ctx) {
15
15
  try {
16
16
  const manager = ctx.get('pluginManager')
@@ -19,8 +19,7 @@ export async function getContextIntegration(ctx) {
19
19
  const peer = bundles.find(row => row.name === 'dsh-context' && row.enabled && !row.error)
20
20
  if (!peer) return { version: '', compatible: false, reason: 'missing' }
21
21
  const version = typeof peer.version === 'string' ? peer.version : ''
22
- const compatible = CONTEXT_VERSIONS.includes(version)
23
- return { version, compatible, reason: compatible ? 'ready' : 'unsupported' }
22
+ return { version, compatible: true, reason: 'ready' }
24
23
  } catch { return { version: '', compatible: false, reason: 'unavailable' } }
25
24
  }
26
25
 
package/lib/index.js CHANGED
@@ -42,6 +42,8 @@ import { getSessionCost as readSessionCost, sessionCostIds, readSessionHeaders,
42
42
  import { getTurnCost, getSessionBilling } from './turn-cost.js'
43
43
  import { getContextCosts, getContextIntegration } from './context-costs.js'
44
44
  import { getTurnInspection } from './turn-inspection.js'
45
+ import { getCallInspection } from './call-inspection.js'
46
+ import { getSessionTrajectory } from './trajectory.js'
45
47
  import { billingStatistics } from './billing-statistics.js'
46
48
 
47
49
  export const name = 'cost-meter'
@@ -2638,6 +2640,8 @@ function createService(ctx, ledger, openRouterPrices) {
2638
2640
  },
2639
2641
  async getSessionBilling(query) { ledger.refresh(); return getSessionBilling(ledger, ctx, query) },
2640
2642
  async getTurnInspection(query) { return getTurnInspection(ctx, query) },
2643
+ async getCallInspection(query) { return getCallInspection(ctx, query) },
2644
+ async getSessionTrajectory(query) { ledger.refresh(); return getSessionTrajectory(ledger, ctx, query) },
2641
2645
  async getContextCosts(query) { return getContextCosts(ledger, ctx, query) },
2642
2646
  async getContextIntegration() { return getContextIntegration(ctx) },
2643
2647
  async getTopSessions(limit, sort = 'cost', dir = 'desc') {
package/lib/store.js CHANGED
@@ -147,6 +147,7 @@ export function defaultConfig() {
147
147
  sessionCostCompact: false, // 输入区下方会话费用行只显示金额(悬停 title 与费用明细弹窗保留完整分项)
148
148
  contextCostsEnabled: false,
149
149
  contextCostsPromptSeen: false,
150
+ statisticsBasis: 'auto', // 未选择时沿用全局 API / 含 Plan 口径。
150
151
  sidebarTodayMetric: 'cost',
151
152
  showTotalWithPlan: false, // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计;默认按真金白银(apiCost)
152
153
  includeSubagentCost: false, // 本会话展示可合并连续子代理后代;不重复写入每日账本。
@@ -1158,6 +1159,7 @@ export function applyConfigPatch(current, rawPatch) {
1158
1159
  for (const key of ['contextCostsEnabled', 'contextCostsPromptSeen']) if (candidate[key] !== undefined && typeof candidate[key] !== 'boolean') errors.push(key + ' must be a boolean')
1159
1160
  if (candidate.sidebarTodayMetric !== undefined && !['cost', 'tokens'].includes(candidate.sidebarTodayMetric)) errors.push('sidebarTodayMetric must be cost or tokens')
1160
1161
  // 「含 Plan 总额」全局开关(v1.6.0):布尔,可缺省(默认关)。
1162
+ if (candidate.statisticsBasis !== undefined && !['auto', 'api', 'plan', 'total'].includes(candidate.statisticsBasis)) errors.push('statisticsBasis must be auto, api, plan or total')
1161
1163
  if (candidate.showTotalWithPlan !== undefined && typeof candidate.showTotalWithPlan !== 'boolean') errors.push(vmsg(locale, 'showTotalWithPlan'))
1162
1164
  for (const field of ['includeSubagentCost', 'codexQuotaEnabled', 'codexQuotaSidebar']) {
1163
1165
  if (candidate[field] !== undefined && typeof candidate[field] !== 'boolean') errors.push(vmsg(locale, field))
@@ -1504,6 +1506,7 @@ export function sanitizeConfig(raw) {
1504
1506
  out.contextCostsEnabled = out.contextCostsEnabled === true
1505
1507
  out.contextCostsPromptSeen = out.contextCostsPromptSeen === true
1506
1508
  out.sidebarTodayMetric = oneOf(out.sidebarTodayMetric, ['cost', 'tokens'], 'cost')
1509
+ out.statisticsBasis = ['api', 'plan', 'total'].includes(out.statisticsBasis) ? out.statisticsBasis : 'auto'
1507
1510
  out.showTotalWithPlan = out.showTotalWithPlan === true
1508
1511
  out.includeSubagentCost = out.includeSubagentCost === true
1509
1512
  out.codexQuotaEnabled = out.codexQuotaEnabled === true