dsh-cost-meter 1.8.21 → 1.8.23

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: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=`
1
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:Ht=>{const wt=Ht("react"),{createElement:t,useState:A,useEffect:ct,useRef:dt,Fragment:Z}=wt,ze=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],W=(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},N=At("number"),x=At("string"),K=At("boolean"),at=e=>e===null?null:N(e),Q=e=>n=>{if(!Array.isArray(n))throw new Error("Invalid statistics array");return n.map(e)},F=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])]))},ot=Object.fromEntries(ze.map(e=>[e,N])),Yt=F(ot),qt=F({provider:x,model:x,bucket:x,tokens:N,rate:N,cost:N,priced:K,plan:K}),Lt=e=>x(e??""),Gt=F({sessionId:Lt,logSeq:e=>at(e??null),kind:x,turn:at,step:at,provider:x,model:x,atMs:N,cost:N,apiCost:N,plan:K,priced:K,longContext:K,rows:Q(qt)}),Bt=F({from:x,to:x,retainedFrom:x,retainedTo:x,totals:Yt,days:Q(F({...ot,date:x})),models:Q(F({...ot,key:x,provider:x,model:x,priced:K})),sessions:Q(F({...ot,id:x,title:x})),providers:Q(x),modelOptions:Q(x),sessionCount:N,offset:N,unassignedCost:N,unmodeledCost:N}),Dt=F({found:K,cost:N,apiCost:N,rows:Q(qt),calls:Q(Gt),totalCalls:N,offset:N,recorded:Yt,agents:e=>Q(F({...ot,id:x,title:x}))(e??[]),callShares:e=>Q(F({index:N,cost:N,apiCost:N,tokens:N,calls:N,other:K,unpriced:K}))(e??[]),kinds:Q(F({...ot,kind:x,unpriced:K})),turns:Q(F({...ot,sessionId:Lt,turn:at,unpriced:K})),totalTurns:N,turnOffset:N,stepShares:F(Object.fromEntries(["cost","calls"].map(e=>[e,Q(F({...ot,sessionId:Lt,turn:at,step:at,other:K,unpriced:K}))])))}),St=F({found:K,turn:N,input:x,inputTruncated:K,totalTools:N,offset:N,tools:Q(F({seq:N,step:at,name:x,callId:x,atMs:N,arguments:x,result:x,truncated:K,status:x}))}),Zt=e=>({...F({found:K,kind:x,input:x,injected:x,skills:x,precedingTools:x,output:x,reasoning:x,truncated:K,totalTools:N,offset:N})(e),tools:St({...e,turn:0,inputTruncated:!1}).tools.map((n,l)=>({...n,durationMs:at(e.tools[l].durationMs??null)}))}),It=["system","tools","user","inject","skill","assistant","tool","other"],Tt=e=>{if(N(e)<0)throw new Error("Invalid context costs amount");return e},te=F(Object.fromEntries(["input","cacheRead","cacheWrite","output","reasoning"].map(e=>[e,Tt]))),Pe=e=>e===null?null:te(e),Ut=F({status:x,sessionId:x,generatedAt:N,revision:N,provider:x,model:x,basis:x,priced:K,source:x,linked:K,contextTokens:Tt,components:Q(F({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=x(e?.sessionId);if(!n||n.length>512)throw new Error("Invalid context costs session");return{sessionId:n}},ee=F({version:x,compatible:K,reason:x}),ae=F({cost:N,apiCost:N,totalSteps:N,offset:N,shares:Q(F({key:x,sessionId:x,turn:at,step:at,kind:x,tools:Q(x),cost:N,apiCost:N,unpriced:K,other:K,count:N})),groups:Q(F({key:x,kind:x,tools:Q(x),steps:N,cost:N,apiCost:N,unpriced:K})),steps:Q(F({key:x,sessionId:x,turn:at,step:at,kind:x,tools:Q(x),atMs:N,calls:N,cost:N,apiCost:N,unpriced:K,rows:Q(qt)}))}),se=e=>{const n={...zt(e),basis:x(e.basis??"total"),offset:N(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=F({sessionId:x,turn:N,offset:N})({...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=F({from:x,to:x,provider:x,model:x,sessionId:x,basis:x,offset:N})(e);if(n.turnOffset=N(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:N(e.seq),atMs:N(e.atMs),offset:N(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)}
@@ -20,7 +20,7 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
20
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 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=`
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 m=(async()=>e[n](l))().then(u=>(a.pending===m&&Object.assign(a,{value:u,revision:o,at:Date.now()}),u)).finally(()=>{a.pending===m&&(a.pending=null)});return a.pending=m,a.pendingRevision=o,m}function vt(e,n,l,o){const c=JSON.stringify(l),[a,m]=A(()=>({...ft(c,ht(bt(e,n,l),o)),loading:!0}));return ct(()=>{let u=!0;return m(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&&m(ft(c,r))},r=>{u&&m(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),lt=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,7 +30,7 @@ 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((e,n)=>"var(--cm-chart-"+n+","+e+")"),Ot={input:0,cacheRead:6,cacheWrite:1,output:5,reasoning:3},Re=`
33
+ @media(prefers-reduced-motion:reduce){.cm-cost-arc{transition:none}}`,tt=["#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
 
@@ -38,22 +38,22 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
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 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=`
41
+ `;function rt({rows:e,total:n,label:l,text:o,onSelect:c,amounts:a=!1}){const[m,u]=A(""),[r,b]=A(""),C=e.find(v=>v.key===(m||r)),i=v=>v.unpriced&&v.value===0?"—":n>0?_(v.value,n):"—",M=v=>v.meta??v.tokens.toLocaleString()+" tokens",d=v=>({"data-active":C?.key===v.key,onMouseEnter:()=>u(v.key),onMouseLeave:()=>u(""),onFocus:j=>{j.currentTarget.matches(":focus-visible")&&b(v.key)},onBlur:()=>b(""),onPointerDown:()=>b(""),onClick:()=>c?.(v),onKeyDown:j=>{j.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(j.key)&&(j.preventDefault(),c?.(v))}});let w=0;const y=e.filter(v=>v.value>0&&n>0).map(v=>{const j=Math.min(100,v.value/n*100),$=w;w+=j;const P=Math.min(.8,j*.15);return t("circle",{...d(v),key:v.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":v.label+" · "+i(v)+" · "+v.amount+" · "+M(v),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:v.color,strokeWidth:18,strokeDasharray:j-P+" "+(100-j+P),strokeDashoffset:-$-P/2,transform:"rotate(-90 78 78)"})});return t("div",{className:"cm-cost-chart","aria-label":l,"data-inspecting":!!C,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}),...y),t("div",{className:"cm-cost-center","aria-hidden":!0},t("b",null,C?i(C):n>0?"100%":"—"),t("small",null,C?.label??l))),t("div",{className:"cm-cost-legend"},...e.map(v=>t("button",{...d(v),type:"button",key:v.key,className:"cm-cost-key","aria-label":v.label+" "+i(v)},t("i",{className:"cm-plan-dot",style:{background:v.color}}),t("span",{className:"cm-cost-key-label"},v.label,a?t("small",{className:"cm-cost-key-amount"},v.amount):null),t("span",{className:"cm-cost-key-share"},i(v))))),t("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},C?t(Z,null,t("strong",null,C.label),t("span",null,M(C)),t("strong",null,C.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:m=!1,expanded:u=!1}){const r=dt(null),b=dt(()=>{}),C=dt(l);C.current=l;const[i,M]=A(()=>({value:ht(bt(e,"getContextCosts",{sessionId:n}),l),error:"",busy:!0}));ct(()=>{let g=!0,O=!1,V=typeof IntersectionObserver!="function";const I=async(R=!1)=>{if(!(!g||O||!V||document.hidden)){O=!0,M(L=>({...L,busy:!0}));try{const L=await Mt(e,"getContextCosts",{sessionId:n},C.current,R===!0);if(L.sessionId!==n)throw new Error("Context costs session mismatch");g&&M({value:L,error:"",busy:!1})}catch{g&&M(L=>({...L,busy:!1,error:o("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{O=!1}}};b.current=I;const q=typeof IntersectionObserver=="function"?new IntersectionObserver(R=>{V=R.some(L=>L.isIntersecting),V&&I()}):null;r.current&&q?.observe(r.current),I();const H=setInterval(I,1e4);return document.addEventListener("visibilitychange",I),()=>{g=!1,clearInterval(H),q?.disconnect(),document.removeEventListener("visibilitychange",I)}},[e,n]),ct(()=>{const g=setTimeout(()=>b.current(),250);return()=>clearTimeout(g)},[l]);const d=i.value?.sessionId===n?i.value:null,w=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:i.busy},o("刷新","Refresh")))),y=g=>t("section",{className:"cm-plan"+(m?" cm-context-compact":""),ref:r,"aria-label":o("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},t("style",null,jt),w,a?t("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,i.error?t("p",{role:"alert",className:"cm-plan-error"},i.error):null,g);if(!d||d.status!=="ready")return y(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."):i.error?o("点击刷新重试。","Select Refresh to retry."):o("正在读取当前上下文…","Reading current context…")));const v=me(d),j=d.priced&&!!v.rates,$=[o("系统提示","System prompt"),o("工具定义","Tool schemas"),o("用户输入","User messages"),o("注入内容","Injected context"),o("技能","Skills"),o("历史回复","Prior replies"),o("工具结果","Tool results"),o("其他","Other")],P=g=>Math.round(g).toLocaleString(),S=g=>j?"≈ "+c(g):o("未定价","Unpriced"),z=d.lastCall,E={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 y(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"},"≈ "+P(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"},S(v.cost)))),t(rt,{rows:v.parts.filter(g=>g.tokens>0).map(g=>({key:g.key,label:$[It.indexOf(g.key)],tokens:Math.round(g.tokens),value:j?g.cost:g.tokens,amount:S(g.cost),color:tt[It.indexOf(g.key)]})),total:j?v.cost:d.contextTokens,label:j?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"},...v.parts.filter(g=>g.tokens>0).map(g=>{const O=It.indexOf(g.key);return t("li",{key:g.key},t("div",{className:"cm-plan-part-head"},t("span",null,t("i",{className:"cm-plan-dot",style:{background:tt[O]}}),$[O]),t("span",null,S(g.cost))),t("div",{className:"cm-plan-part-meta"},t("span",null,"≈ "+P(g.tokens)+" tokens"),t("span",null,j?_(g.cost,v.cost):"—")))})))),z?t("section",{className:"cm-plan-last"},t("h3",null,o("最近一次调用 · 用量计费","Latest call · usage-based costs")),t("p",{className:"cm-plan-sub"},z.provider+" / "+z.model+" · "+new Date(z.atMs).toLocaleString()),t(rt,{rows:z.rows.filter(g=>g.tokens>0&&(g.bucket!=="reasoning"||g.rate>0)).map(g=>({key:g.bucket,label:E[g.bucket]??g.bucket,tokens:g.tokens,value:g.cost,amount:z.priced?c(g.cost):o("未定价","Unpriced"),color:tt[Ot[g.bucket]??7]})),total:z.priced?z.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}},...z.rows.filter(g=>g.bucket!=="reasoning"||g.rate>0).map(g=>t("li",{key:g.bucket},t("div",{className:"cm-plan-part-head"},t("span",null,E[g.bucket]??g.bucket),t("span",null,z.priced?c(g.cost):o("未定价","Unpriced"))),t("div",{className:"cm-plan-part-meta"},t("span",null,P(g.tokens)+" tokens"),t("span",null,z.priced?_(g.cost,z.cost):"—")))))),t("p",{className:"cm-plan-total"},o("合计 ","Total ")+(z.priced?c(z.cost):o("未定价","Unpriced"))+(z.plan?o(" · Plan 的 API 等值"," · Plan API equivalent"):""))):t("p",{className:"cm-plan-note"},o("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),j?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(i=>typeof a?.[i]=="function"))return()=>{};const m=[],u=new Map;let r=!0;function b(i){return function(d){c&&wt.useSyncExternalStore(c.subscribe,l);const w=dt(null),[y,v]=A(null),j=d.useProjection?.("contextBreakdown"),$=d.useProjection?.("tokenUsage"),P=JSON.stringify([j,$]);ct(()=>{const E=i?w.current:w.current?.closest("[data-conversation-session]");if(!E||!i&&E.dataset.conversationSession!==d.sessionId||typeof MutationObserver!="function")return;const g=document.createElement("div");g.className="cm-plan-host",g.dataset.cmContextCosts="";const O=()=>{const I=i?E.querySelector("[data-lc-current]"):[...E.querySelectorAll('[data-slot="conversation.view"] [data-lc-current]')].find(q=>q.closest("[data-conversation-session]")===E);if(!I){g.remove(),v(null);return}g.parentElement!==I&&(I.appendChild(g),v(g))},V=new MutationObserver(O);return V.observe(E,{childList:!0,subtree:!0}),O(),()=>{V.disconnect(),g.remove()}},[d.sessionId]);const S=(E,g)=>l()==="en"?g:E,z=y&&d.sessionId?o(t(Et,{key:d.sessionId,api:n,sessionId:d.sessionId,integrated:!0,text:S,revision:P}),y):null;return i?t("div",{ref:w,style:{display:"contents"},"data-cm-context-bridge":d.sessionId},t(i,d),z):t(Z,null,t("span",{ref:w,hidden:!0}),z)}}const C=()=>{r=!1;for(const i of m)i();for(const i of u.values())i.dispose();u.clear()};try{for(const[i,M,d]of Kt){const w=i==="conversation.view",y=w?"conversation.input.overlay":i;let v=!1;const j=()=>{if(!(!r||v)){v=!0;try{const $=a.entries(i).filter(O=>O.locale==="dsh-context"&&O.options[M]===d&&O.registrant!=="dsh-cost-meter-context-bridge"),P=$.length===1?$[0]:null,S=u.get(i),z=a.entriesOfSlot(i).find(O=>O.options[M]===d);if(S?.original===P&&a.entries(y).some(O=>O.component===S.component)&&(w?z===P:z?.component===S.component)||(S?.dispose(),u.delete(i),!P||P.children||P.store||typeof P.component!="function")||a.entriesOfSlot(i).find(O=>O.options[M]===d)!==P||w&&typeof a.spec=="function"&&!a.spec(y))return;const E=b(w?null:P.component),g=a.register(w?{name:y,id:"cost-meter-context-main",registrant:"dsh-cost-meter-context-bridge"}:{name:i,...P.options,inject:P.inject,locale:P.locale,priority:(P.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},E);u.set(i,{original:P,component:E,dispose:g})}finally{v=!1}}};m.push(a.subscribe(i,j)),w&&m.push(a.subscribe(y,j)),j()}}catch(i){throw C(),i}return C}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"),m=new Set,u=[];let r=!0,b=null,C=[],i=!1,M=0,d=ue(),w=null,y=0,v=Promise.resolve(),j=!1,$=!1,P={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const S=["entries","entriesOfSlot","register","subscribe"].every(R=>typeof a?.[R]=="function"),z=R=>{P={...P,...R};for(const L of m)L()},E=()=>{if(r){if(j){$=!0;return}j=!0;try{do{$=!1;const R=l.getSnapshot().state?.config,L=S&&P.peer.compatible&&C.length>0,p=L&&!P.saving&&(w??R?.contextCostsEnabled)===!0;if(!p&&b){const h=b;b=null,h()}if(p&&!b){const h=de(e,{...n,disableIntegration:()=>{V(!1)}},o,c,l);r?b=h:h()}const T=P.prompt&&(P.manual||L);r&&z({available:L,enabled:p,prompt:T||!!(R&&L&&!R.contextCostsPromptSeen&&!R.contextCostsEnabled&&!d)})}while(r&&$)}finally{j=!1}}},g=async(R=!1)=>{if(!r||!S)return;const L=Kt.flatMap(([T,h,B])=>a.entries(T).filter(G=>G.locale==="dsh-context"&&G.options[h]===B&&G.registrant!=="dsh-cost-meter-context-bridge"&&!G.children&&!G.store&&typeof G.component=="function"));if(!R&&i&&L.length===C.length&&L.every((T,h)=>T===C[h]))return;C=L,i=!0;const p=++M;z({peer:{version:"",compatible:!1,reason:L.length?"unavailable":"missing"}}),E();try{const T=await n.getContextIntegration();r&&p===M&&(z({peer:T}),E())}catch{r&&p===M&&E()}};function O(){d=!0,Me()}async function V(R,L=!1){if(!r||R&&!P.available&&!L)return;const p=++y;O(),w=R,z({prompt:!1,manual:!1,saving:!0,error:""}),E();const T=v.catch(()=>{}).then(()=>n.saveIntegration(R));v=T;try{await T,r&&p===y&&(w=null,z({saving:!1}),E())}catch{r&&p===y&&(w=!1,z({saving:!1,error:"save"}),E())}}if(u.push(l.subscribe(E)),S)for(const[R]of Kt)u.push(a.subscribe(R,()=>{g()}));const I=()=>{document.hidden||g(!0)};document.addEventListener("visibilitychange",I);const q=R=>{R.key===$t&&R.newValue==="1"&&!d&&(d=!0,z({prompt:!1}),E())};return window.addEventListener("storage",q),g(),E(),{getSnapshot:()=>P,subscribe:R=>(m.add(R),()=>m.delete(R)),choose:V,dismiss:()=>V(P.manual?l.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:O,preview:()=>z({prompt:!0,manual:!0}),refresh:()=>{g(!0)},dispose:()=>{r=!1,++M;for(const R of u)R();b?.(),m.clear(),document.removeEventListener("visibilitychange",I),window.removeEventListener("storage",q)}}}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 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,`
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=>tt[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(rt,{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,m)=>n()==="en"?m:a;return ct(()=>{const a=o.current;if(!l.prompt||!a)return;let m=!0,u=!1,r=null;const b=()=>{if(!(!m||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(i=>i!==a&&i.getClientRects().length)))try{r=document.activeElement,a.showModal(),u=!0,e.opened()}catch{}}};b();const C=setInterval(b,1e3);return()=>{m=!1,clearInterval(C),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 m=[...a.currentTarget.querySelectorAll("button:not(:disabled)")].filter(b=>b.getClientRects().length),u=m[0],r=m.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 m=a.currentTarget.getBoundingClientRect();(a.clientX<m.left||a.clientX>m.right||a.clientY<m.top||a.clientY>m.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)),m=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(m))),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),m=a[0].date,u=a.at(-1).date;o.push({from:m,to:u,label:m===u?m:m+" – "+u,value:a.reduce((r,b)=>r+W(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((m,u)=>t("li",{key:u,"data-other":m.other||void 0},t("div",{className:"cm-stat-share-head"},t("span",null,m.label),t("span",{className:"cm-stat-share-value"},o(m.value)+(m.unpriced?" + ?":"")+" · "+_(m.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*m.value/l)+"%"}}))))))}function ye({api:e,sessionId:n,turn:l,revision:o,text:c}){const[a,m]=A(0),[u,r]=A(0),b=vt(e,"getTurnInspection",{sessionId:n,turn:l,offset:a},o+":"+u),C=()=>Y(c("重试","Retry"),()=>r(w=>w+1)),i=t("div",{className:"cm-stat-inspection"},lt(b.error),C()),M=b.failed?i:null;if(Pt(b))return b.loading?t("p",{className:"cm-stat-empty",role:"status"},c("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…")):i;const d=b.value;return d.found?t("div",{className:"cm-stat-inspection"},M,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(w=>t("details",{key:w.seq,className:"cm-stat-tool"},t("summary",null,t("span",null,(w.step==null?"":c("步骤 ","Step ")+w.step+" · ")+w.name),t("span",{className:"cm-stat-sub"},{complete:c("已完成","Completed"),error:c("调用失败","Failed"),pending:c("未记录结果","No recorded result")}[w.status])),t("h4",{style:{marginTop:12}},c("调用参数","Arguments")),t("pre",{className:"cm-stat-pre"},w.arguments),t("h4",null,c("返回结果","Result")),t("pre",{className:"cm-stat-pre"},w.result||c("没有可显示的文本结果","No text result is available")),w.truncated?t("p",{className:"cm-stat-truncated"},c("内容已截取","Content truncated")):null)),t(xt,{offset:a,count:d.totalTools,size:20,onChange:m,text:c})):t(Z,null,M,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:m,onViewChange:u}){const[r,b]=A(0),[C,i]=A(0),M=vt(e,"getCallInspection",{sessionId:n,seq:l,atMs:o,offset:r},c+":"+C),d=M.value,w=(y,v,j=!1)=>v?t("details",{className:"cm-stat-tool",open:j},t("summary",null,y,t("span",{className:"cm-stat-sub"},v.length.toLocaleString()+a(" 字符"," chars"))),t("pre",{className:"cm-stat-pre"},v)):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(([y,v])=>Y(v,()=>u(y),{key:y,"aria-pressed":m===y}))),M.failed?t(Z,null,lt(M.error),Y(a("重试","Retry"),()=>i(y=>y+1))):null,d?d.found?t(Z,null,m==="output"?t(Z,null,w(d.kind==="compaction"?a("压缩摘要","Compaction summary"):a("本次回复","Response"),d.output,!0),w(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,m==="input"?t(Z,null,w(a("本轮用户输入","Turn input"),d.input,!0),w(a("技能内容","Skills"),d.skills),w(a("注入内容","Injected context"),d.injected),w(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,m==="tools"?t(Z,null,d.totalTools?null:t("p",{className:"cm-stat-sub"},a("本次没有工具调用","No tools in this call")),...d.tools.map((y,v)=>t("details",{key:y.callId,className:"cm-stat-tool",open:v===0},t("summary",null,y.name,t("span",{className:"cm-stat-sub"},(y.durationMs!=null?(y.durationMs/1e3).toLocaleString(void 0,{maximumFractionDigits:2})+" s · ":"")+{complete:a("已完成","Completed"),error:a("失败","Failed"),pending:a("未记录结果","No result")}[y.status])),t("div",{className:"cm-call-tool-parts"},t("div",null,t("h4",null,a("参数","Arguments")),t("pre",{className:"cm-stat-pre"},y.arguments)),t("div",null,t("h4",null,a("返回结果","Result")),t("pre",{className:"cm-stat-pre"},y.result||"—"))),y.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")):M.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:m}){const[u,r]=A("output"),b=e.rows.filter(i=>i.tokens>0),C=b.filter(i=>i.bucket!=="reasoning"||i.cost>0||!i.priced).map(i=>({key:i.bucket,label:m[i.bucket],tokens:i.tokens,value:i.cost,unpriced:!i.priced,amount:i.priced?c(i.cost):a("未定价","Unpriced"),color:tt[Ot[i.bucket]??7]}));return t("div",{className:"cm-call-detail-grid"},t("style",null,`
49
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
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
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
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,`
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(rt,{rows:C,total:e.cost,label:a("本次费用构成","This call’s costs"),text:a,amounts:!0,onSelect:i=>r(["output","reasoning"].includes(i.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(i=>t("th",{key:i},i)))),t("tbody",null,...b.map(i=>{const M=i.bucket==="reasoning"&&i.priced&&i.rate===0;return t("tr",{key:i.bucket},t("td",null,m[i.bucket]),t("td",null,i.tokens.toLocaleString()),t("td",null,i.priced?c(i.rate):"?"),t("td",null,M?a("未单独计费","No separate charge"):i.priced?c(i.cost):"?"),t("td",null,i.priced&&!M?_(i.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:m,detailed:u=!1}){const[r,b]=A(0),[C,i]=A([]),[M,d]=A(""),[w,y]=A([]),[v,j]=A(!1),[$,P]=A(0),S=vt(e,"getSessionTrajectory",{sessionId:n,offset:r,basis:a},l+":"+$);ct(()=>{b(0),i([]),d(""),y([])},[n,l,a]),ct(()=>{S.value?.offset===r&&i(p=>r===0?S.value.steps:[...new Map([...p,...S.value.steps].map(T=>[T.key,T])).values()])},[S.value,r]);const z=S.value,E={input:c("输入","Input"),cacheRead:c("缓存读取","Cache read"),cacheWrite:c("缓存写入","Cache write"),output:c("输出","Output"),reasoning:c("推理","Reasoning")},g=p=>({model:c("模型调用","Model calls"),compaction:c("上下文压缩","Compaction"),search:c("原生搜索","Native search")})[p]??p,O=p=>p.rows.filter(T=>a==="total"||(a==="plan"?T.plan:!T.plan)),V=(p,T)=>{const h=O(p).filter(B=>T.includes(B.bucket));return o(h.reduce((B,G)=>B+G.cost,0))+(h.some(B=>!B.priced)?" + ?":"")};if(!z)return t("p",{className:"cm-stat-sub"},S.error||c("读取步骤费用…","Reading step costs…"),S.error?Y(c("重试","Retry"),()=>P(p=>p+1)):null);const I=W(z,a),q=z.shares.map((p,T)=>({key:p.key,label:p.other?c("其余 ","Other ")+p.count+c(" 步"," steps"):(p.sessionId!==n?c("子代理 · ","Subagent · "):"")+(p.turn==null?g(p.kind):c("轮次 ","Turn ")+p.turn+(p.step==null?"":c(" · 步骤 "," · step ")+p.step)),value:W(p,a),amount:o(W(p,a))+(p.unpriced?" + ?":""),meta:p.tools.join(" + ")||g(p.kind),unpriced:p.unpriced,color:tt[p.other?7:T%7]})),H=C.length?C:z.steps,R=p=>u?!w.includes(p.key):M===p.key,L=p=>u?y(T=>T.includes(p.key)?T.filter(h=>h!==p.key):[...T,p.key]):d(M===p.key?"":p.key);return u?t("section",{className:"cm-step-cards cm-plan","aria-label":c("逐步费用明细","Cost details by step")},t("style",null,`
54
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
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,`
56
+ `),S.error?t("p",{className:"cm-stat-error"},S.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"},z.totalSteps+c(" 步 · "," steps · ")+o(I))),t(rt,{rows:q,total:I,label:c("总费用占比","Total cost share"),text:c,amounts:!0})),t("details",{className:"cm-individual-steps",open:v,onToggle:p=>{p.target===p.currentTarget&&j(p.currentTarget.open)}},t("summary",null,c("逐步费用明细","Individual step details")+" · "+z.totalSteps),v?t("div",{className:"cm-step-card-grid"},...H.map(p=>{const T=new Map;for(const h of O(p)){if(h.bucket==="reasoning"&&h.priced&&h.cost===0)continue;const B=T.get(h.bucket)??{key:h.bucket,label:E[h.bucket]??h.bucket,value:0,tokens:0,unpriced:!1,color:tt[Ot[h.bucket]??7]};B.value+=h.cost,B.tokens+=h.tokens,B.unpriced||=!h.priced,T.set(h.bucket,B)}return t("article",{className:"cm-step-fee-card",key:p.key},t("div",{className:"cm-step-fee-head"},t("button",{type:"button",className:"cm-step-name","aria-expanded":R(p),onClick:()=>L(p)},(R(p)?"⌄ ":"› ")+(p.sessionId!==n?c("子代理 · ","Subagent · "):"")+(p.turn==null?g(p.kind):c("轮次 ","Turn ")+p.turn+(p.step==null?"":c(" · 步骤 "," · step ")+p.step)),t("small",null,p.tools.length?p.tools.join(" + "):g(p.kind))),t("div",{style:{textAlign:"right"}},t("strong",null,o(W(p,a))+(p.unpriced?" + ?":"")),t("small",null,_(W(p,a),I)+c(" 会话费用"," of session cost")))),t(rt,{rows:[...T.values()].map(h=>({...h,amount:o(h.value)+(h.unpriced?" + ?":"")})),total:W(p,a),label:c("本步费用","Step cost"),text:c,amounts:!0}),R(p)?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,...O(p).map((h,B)=>t("tr",{key:B},t("td",{title:h.provider+" / "+h.model},E[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),v&&H.length<z.totalSteps?t("div",{className:"cm-step-more"},Y(S.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:S.loading})):null):t("section",{className:"cm-step-costs cm-plan","aria-label":c("步骤计费","Step billing")},t("style",null,`
57
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
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}}});
59
+ `),S.error?t("p",{className:"cm-stat-error"},S.error):null,t("div",{className:"cm-step-cost-grid"},m,u?null:t("section",{className:"cm-spend-card","aria-label":c("步骤费用构成","Step cost composition")},t("h3",null,c("步骤费用构成","Step cost composition")),t(rt,{rows:q,total:I,label:c("费用占比","Cost share"),text:c,amounts:!1})),t("section",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c("计费轨迹","Billing trajectory")+" · "+z.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(p=>t("th",{key:p},p)))),t("tbody",null,...H.map(p=>t(Z,{key:p.key},t("tr",null,t("td",null,t("button",{type:"button",className:"cm-step-name","aria-expanded":R(p),onClick:()=>L(p)},t("span",null,(R(p)?"⌄ ":"› ")+(p.sessionId!==n?c("子代理 · ","Subagent · "):"")+(p.turn==null?g(p.kind):c("轮次 ","Turn ")+p.turn+(p.step==null?"":c(" · 步骤 "," · step ")+p.step))),t("small",{title:p.tools.join(" + ")},p.tools.length?p.tools.join(" + "):g(p.kind)))),t("td",null,V(p,["input"])),t("td",null,V(p,["output","reasoning"])),t("td",null,V(p,["cacheRead","cacheWrite"])),t("td",null,o(W(p,a))+(p.unpriced?" + ?":"")),t("td",null,_(W(p,a),I))),R(p)?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(T=>t("th",{key:T},T)))),t("tbody",null,...O(p).map((T,h)=>t("tr",{key:h},t("td",null,T.model+" · "+(E[T.bucket]??T.bucket)),t("td",null,T.tokens.toLocaleString()),t("td",null,T.priced?o(T.rate):"—"),t("td",null,T.priced?o(T.cost):c("未定价","Unpriced")))))))):null))))),H.length<z.totalSteps?t("div",{className:"cm-step-more"},Y(S.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:S.loading})):null)))}function Vt({api:e,query:n,revision:l,money:o,formatTokens:c,text:a,overview:m=!1,children:u}){const[r,b]=A(0),[C,i]=A(-1),[M,d]=A(0),[w,y]=A("summary"),[v,j]=A(!1),[$,P]=A(null),[S,z]=A("cost"),[E,g]=A(0),O=vt(e,"getSessionBilling",{...n,offset:r,turnOffset:M},l+":"+E),V=dt(!1);ct(()=>{V.current&&!O.loading&&C>=0&&(document.getElementById("cm-stat-call-"+C)?.scrollIntoView({block:"nearest"}),V.current=!1)},[O.loading,O.value,r,C,w]);const I=O.value,q=n.basis,H={input:a("非缓存输入","Uncached input"),output:a("输出","Output"),cacheRead:a("缓存读取","Cache read"),cacheWrite:a("缓存写入","Cache write"),reasoning:a("推理","Reasoning")},R={model:a("模型调用","Model call"),compaction:a("上下文压缩","Compaction"),search:a("原生搜索","Native search")},L=s=>s==null?a("未标明轮次","Turn not recorded"):a("轮次 ","Turn ")+s;if(Pt(O))return O.loading?t("p",{className:"cm-stat-empty",role:"status"},a("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):lt(O.error);const p=O.failed?t("div",null,lt(O.error),Y(a("重试","Retry"),()=>g(s=>s+1))):null;if(!I.found)return t(Z,null,p,t("p",{className:"cm-stat-note"},a("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),u);const T=s=>!s||s===n.sessionId?a("主会话","Main conversation"):a("子代理 ","Subagent ")+((I.agents??[]).find(k=>k.id===s)?.title||s).slice(0,80),h=s=>JSON.stringify([s.sessionId||n.sessionId,s.turn]),B=s=>((I.agents?.length??0)>1?T(s.sessionId)+" · ":"")+L(s.turn),G=s=>q==="total"||(q==="plan"?s.plan:!s.plan),et=Object.keys(H).map(s=>{const k=I.rows.filter(D=>D.bucket===s&&G(D));return{bucket:s,tokens:k.reduce((D,U)=>D+U.tokens,0),cost:k.reduce((D,U)=>D+U.cost,0),unpriced:k.some(D=>!D.priced)}}),nt=W(I,q),pt=W(I.recorded,q),_t=Math.abs(nt-pt)>Math.max(1e-8,Math.abs(pt)*1e-8)||I.totalCalls!==I.recorded.calls,yt=et.some(s=>s.unpriced),J=yt?a("已知费用占比","Known cost share"):a("费用占比","Cost share"),ut=s=>{y("summary"),V.current=!0,b(Math.floor(s/50)*50),i(s%50)},f=s=>({key:s.bucket,label:H[s.bucket],tokens:s.tokens,value:s.cost,unpriced:s.unpriced,amount:s.unpriced&&!s.cost?a("未定价","Unpriced"):o(s.cost)+(s.unpriced?" + ?":""),color:tt[Ot[s.bucket]??7]}),X=new Map;for(const s of I.rows.filter(G)){const k=JSON.stringify([s.provider,s.model]),D=X.get(k)??{key:k,label:s.model,provider:s.provider,tokens:0,value:0,unpriced:!1};D.value+=s.cost,D.tokens+=s.bucket==="reasoning"?0:s.tokens,D.unpriced||=!s.priced,X.set(k,D)}const st=[...X.values()].sort((s,k)=>k.value-s.value).map((s,k)=>({...s,label:s.provider+" / "+s.label,amount:s.unpriced&&!s.value?a("未定价","Unpriced"):o(s.value)+(s.unpriced?" + ?":""),color:tt[k%7]}));if(st.length>7){const s=st.splice(7),k=s.reduce((U,Ct)=>U+Ct.value,0),D=s.some(U=>U.unpriced);st.push({key:"other-models",label:a("其余 ","Other ")+s.length+a(" 个模型"," models"),value:k,tokens:s.reduce((U,Ct)=>U+Ct.tokens,0),unpriced:D,amount:D&&!k?a("未定价","Unpriced"):o(k)+(D?" + ?":""),color:tt[7]})}const kt=et.find(s=>s.bucket==="cacheRead"),Nt=et.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,k)=>s+k.tokens,0)],[a("输入费用","Input cost"),kt.cost,Nt.some(s=>s.unpriced)?0:Nt.reduce((s,k)=>s+k.cost,0)]].map(([s,k,D])=>t("div",{key:s},t("div",{className:"cm-stat-share-head"},t("span",null,s),t("span",null,_(k,D))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{style:{display:"block",height:"100%",width:(D>0?k/D*100:0)+"%",borderRadius:9,background:tt[6]}}))))):null,it=(s,k,D={},U=null)=>t("section",{className:"cm-spend-card","aria-label":s},t("h3",null,s),t(rt,{rows:k,total:nt,label:J,text:a,amounts:!0,...D}),U),Ie=(I.callShares?.length??0)>0?it(a("每次调用费用占比","Cost share per call"),I.callShares.map((s,k)=>({...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:W(s,q),amount:s.unpriced&&!W(s,q)?a("未定价","Unpriced"):o(W(s,q))+(s.unpriced?" + ?":""),color:tt[s.other?7:k%7]})),{onSelect:s=>{s.other||ut(s.index)}}):null,Te=(s,k,D)=>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(U=>t("th",{key:U},U)))),t("tbody",null,k.map((U,Ct)=>t("tr",{key:Ct},t("td",null,D(U)),t("td",null,U.calls),t("td",null,[U.input,U.cacheRead+U.cacheWrite,U.output].map(c).join(" / ")),t("td",null,o(U.apiCost)+(U.unpriced?" + ?":"")),t("td",null,o(Math.max(0,U.cost-U.apiCost))+(U.unpriced?" + ?":"")))))));return t("section",{className:"cm-stat-panel"},t("style",null,jt+Re),m?t("nav",{className:"cm-session-tabs","aria-label":a("费用视图","Cost views")},...[["summary",a("费用概览","Overview")],["context",a("费用明细","Cost details")]].map(([s,k])=>Y(k,()=>{y(s),i(-1),j(!1)},{key:s,"aria-pressed":w===s}))):null,m?t("div",{className:"cm-stat-metrics"},...[[q==="total"?a("API + Plan 等值","API + Plan equivalent"):q==="plan"?a("Plan 等值","Plan equivalent"):a("API 费用","API cost"),o(nt)+(et.some(s=>s.unpriced)?" + ?":""),a("按本对话调用日志估算","Estimated from this conversation’s call logs")],[a("调用次数","Calls"),I.totalCalls.toLocaleString(),(I.agents?.length??0)>1?a("包含子代理","Includes subagents"):a("本会话","This conversation")],[a("Token 用量","Token usage"),c(et.reduce((s,k)=>s+(k.bucket==="reasoning"?0:k.tokens),0)),a("输入、缓存与输出","Input, cache and output")],[a("缓存命中率","Cache hit rate"),_(et.find(s=>s.bucket==="cacheRead")?.tokens??0,et.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)).reduce((s,k)=>s+k.tokens,0)),a("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([s,k,D])=>t("div",{className:"cm-stat-metric",key:s},t("div",{className:"cm-stat-sub"},s),t("div",{className:"cm-stat-value"},k),t("div",{className:"cm-stat-sub"},D)))):null,m&&w==="context"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:q,detailed:!0}):null,m?w==="context"?t("details",{className:"cm-stat-secondary"},t("summary",{style:{padding:"8px 0"}},a("上下文费用参考","Context cost reference")),u):null:u,m?null:t("div",{className:"cm-stat-panel-head"},t("h3",null,m?a("已发生费用 · 调用明细","Recorded costs · call details"):a("单对话费用明细","Conversation cost details")),t("span",{className:"cm-stat-sub"},(I.agents?.length??0)>1?a("包含子代理及其后代","Includes subagents and their descendants"):a("本会话自身的调用","Own conversation calls"))),p,!m&&_t?t("p",{className:"cm-stat-note"},a("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+o(pt)+" / "+I.recorded.calls+a(" 次;明细 "," calls; details ")+o(nt)+" / "+I.totalCalls+a(" 次。"," calls.")):null,(!m||w==="calls")&&(I.agents?.length??0)>1?Te(a("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),I.agents,s=>T(s.id)):null,m?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"},it(a("费用构成","Cost composition"),et.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f),{},mt),Ie,st.length>1?it(a("模型费用分布","Cost by model"),st):null,I.kinds.length>1?it(a("各环节费用占比","Cost by activity"),I.kinds.map((s,k)=>({key:s.kind,label:R[s.kind]??s.kind,value:W(s,q),tokens:gt(s),meta:s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok",unpriced:s.unpriced,amount:o(W(s,q))+(s.unpriced?" + ?":""),color:tt[k]}))):null)),m&&w==="summary"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:q,composition:it(a("费用构成","Cost composition"),et.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f))}):null,!m||w==="summary"?t("details",{className:"cm-call-section",open:!m||v||C>=0,onToggle:s=>{s.target===s.currentTarget&&(j(s.currentTarget.open),s.currentTarget.open||i(-1))}},t("summary",{style:{padding:"10px 0",fontSize:13}},a("逐次调用明细","Individual calls")+" · "+I.totalCalls),m?t("div",{className:"cm-plan cm-spend-grid"},Ie,st.length>1?it(a("模型费用分布","Cost by model"),st):mt):null,m?null:t("details",{className:"cm-stat-secondary",open:!m},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,k])=>Y(k,()=>z(s),{key:s,"aria-pressed":S===s})))),t(xe,{title:S==="cost"?a("费用占比 · 全部调用","Cost share · all calls"):a("调用次数占比 · 全部调用","Call count share · all calls"),rows:(I.stepShares?.[S]??[]).map(s=>({label:s.other?a("其余步骤合计","All other steps"):B(s)+(s.step==null?"":a(" · 步骤 "," · step ")+s.step),value:S==="cost"?W(s,q):s.calls,unpriced:S==="cost"&&s.unpriced,other:s.other})),total:S==="cost"?nt:I.totalCalls,format:S==="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,et.map(s=>t("tr",{key:s.bucket},t("td",null,H[s.bucket]),t("td",null,s.tokens.toLocaleString()),t("td",null,o(s.cost)+(s.unpriced?" + ?":"")),t("td",null,_(s.cost,nt))))))),Te(a("按调用类型统计","Cost by call type"),I.kinds,s=>R[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"))),I.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&&$===h(s),onClick:()=>P(k=>k===h(s)?null:h(s))},t("span",null,(s.turn==null?"":$===h(s)?"⌄ ":"› ")+B(s)),t("span",null,s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok · "+o(W(s,q))+(s.unpriced?" + ?":"")+" · "+_(W(s,q),nt))),s.turn!=null&&$===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:M,count:I.totalTurns,size:25,onChange:s=>{d(s),P(null)},text:a})),t("div",{style:{marginTop:24}},t(he,{rows:I.calls.map((s,k)=>({label:"#"+(r+k+1),index:k,value:W(s,q)})),money:o,text:a,label:a("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:s=>{i(s.index),document.getElementById("cm-stat-call-"+s.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),I.calls.map((s,k)=>t("details",{key:r+k,id:"cm-stat-call-"+k,className:"cm-stat-call",open:C===k,onToggle:D=>{D.currentTarget.open?i(k):i(U=>U===k?-1:U)}},t("summary",null,"#"+(r+k+1)+" · "+B(s)+(s.step==null?"":a(" / 步骤 "," / step ")+s.step)+" · "+(R[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?_(W(s,q),nt):"—")+" · "+J)),C===k?t(Oe,{key:(s.sessionId||n.sessionId)+":"+(s.logSeq??k),call:s,sessionId:n.sessionId,api:e,revision:l,money:o,text:a,names:H}):null)),t(xt,{offset:r,count:I.totalCalls,size:50,onChange:s=>{b(s),i(-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]=A(o),[m,u]=A(!1),[r,b]=A("");return ct(()=>{m||a(o())},[e.statisticsBasis,e.showTotalWithPlan,m]),{basis:c,choose:async i=>{if(!(m||!["api","plan","total"].includes(i))){a(i),u(!0),b("");try{await n.saveStatisticsBasis(i)}catch{b(l("计费口径保存失败,请重试。","Could not save the cost basis. Try again."))}finally{u(!1)}}},saving:m,error:r}}function Ce({state:e,api:n,sessionId:l,formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:m}){const u=(y,v)=>(a?a(e.config):e.config.locale)==="en"?v:y,[r,b]=A(0),C=Ne(e.config,n,u),{basis:i}=C,M=Rt(e,r),d=y=>o(y,{...e.config,decimals:Math.max(y!==0&&Math.abs(y)<.01?8:4,e.config.decimals??2)}),w={sessionId:l,from:"",to:"",provider:"",model:"",basis:i,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(y=>y+1))),t(Vt,{key:l+":"+i,api:n,query:w,revision:M,money:d,formatTokens:c,text:u,overview:!0},t(Et,{key:l,api:n,sessionId:l,revision:M,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:i,disabled:C.saving,onChange:y=>C.choose(y.target.value)},...[["api",u("API 费用","API cost")],["plan",u("Plan 等值","Plan equivalent")],["total",u("API + Plan 等值","API + Plan equivalent")]].map(([y,v])=>t("option",{key:y,value:y},v))))),C.error?lt(C.error):null,m?t(Qt,m):null))}function we({state:e,api:n,sessionId:l="",formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:m}){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,C]=A(l?"all":"week"),[i,M]=A(null),[d,w]=A({id:l,title:l}),[y,v]=A(""),[j,$]=A(""),P=Ne(e.config,n,r),{basis:S}=P,[z,E]=A(0),[g,O]=A(0),[V,I]=A(!1),q=e.meta.dayKey||new Date().toISOString().slice(0,10),H=b==="all"?"":b==="custom"?i?.from||q:Xt(q,b==="week"?-6:b==="month"?-29:0),R=b==="custom"&&i?.to||q,L={from:H,to:R,provider:y,model:j,basis:S,sessionId:d.id,offset:z},p=Rt(e,g),T=vt(n,"getBillingStatistics",L,p),h=T.value,B=f=>o(f,{...e.config,decimals:Math.max(f!==0&&Math.abs(f)<.01?8:4,e.config.decimals??2)}),G=f=>{C(f),E(0)},et=f=>{w(f),E(0),v(""),$("")},nt=S==="total"?r("API + Plan 等值","API + Plan equivalent"):S==="plan"?r("Plan 等值","Plan equivalent"):r("API 费用","API cost"),pt=(f,X,st,kt,Nt=!1)=>t("label",null,f,t("select",{value:X,disabled:Nt,onChange:mt=>{st(mt.target.value),E(0)}},kt.map(([mt,it])=>t("option",{key:mt,value:mt},it)))),_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),J=h?.totals,ut=(f,X,st)=>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"},st));return t("div",{className:"cm-stat"},t("style",null,re),m?t(Qt,m):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"),()=>O(f=>f+1))),d.id?Y(r("← 全部对话","← All conversations"),()=>et({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,()=>G(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"?H:R,onChange:X=>{M({from:H,to:R,[f]:X.target.value}),E(0)}})))):null,t("div",{className:"cm-stat-controls"},pt(r("计费口径","Cost basis"),S,P.choose,[["api",r("API 费用","API cost")],["plan",r("Plan 等值","Plan equivalent")],["total",r("API + Plan 等值","API + Plan equivalent")]],P.saving),pt(r("提供商","Provider"),y,f=>{v(f),$("")},[["",r("全部提供商","All providers")],...[...new Set([y,...h?.providers??[]])].filter(Boolean).map(f=>[f,f])]),pt(r("模型","Model"),j,$,[["",r("全部模型","All models")],...[...new Set([j,...h?.modelOptions??[]])].filter(Boolean).map(f=>[f,f])])),P.error?lt(P.error):null,Pt(T)?T.loading?t("p",{className:"cm-stat-empty",role:"status"},r("加载统计…","Loading statistics…")):lt(T.error):h?t(Z,null,T.failed?lt(T.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(J.apiCost),r("已入账估算","Recorded estimate")),ut(r("Plan 等值费用","Plan equivalent"),B(Math.max(0,J.cost-J.apiCost)),""),ut(r("调用次数","Calls"),J.calls.toLocaleString(),h.sessionCount+r(" 个对话 · 平均 "," conversations · average ")+B(J.calls?W(J,S)/J.calls:0)),ut(r("缓存命中率","Cache hit rate"),_(J.cacheRead,J.input+J.cacheRead+J.cacheWrite),c(gt(J))+" Tokens")),d.id?t("section",{className:"cm-stat-panel"},t(Et,{key:d.id,api:n,sessionId:d.id,revision:p,money:B,text:r})):null,d.id?t(Vt,{key:JSON.stringify([d.id,H,R,y,j,S]),api:n,query:{...L,from:h.from,to:h.to,offset:0},revision:p,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,!J.calls&&!J.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,S),money:B,text:r,label:r("费用趋势 · ","Cost over time · ")+nt,onSelect:f=>{M({from:f.from,to:f.to}),G("custom")}})),t("div",{className:"cm-stat-grid"},yt(r("模型费用排行","Cost by model"),t(Z,null,t("ol",{className:"cm-stat-rank"},(V?h.models:h.models.slice(0,8)).map(f=>t("li",{key:f.key},t("button",{type:"button",onClick:()=>{v(f.provider),$(f.model),E(0)},title:f.key},t("div",{className:"cm-stat-rankline"},t("span",null,f.model),t("span",{className:"cm-stat-number"},B(W(f,S))+(f.priced?"":" + ?"))),t("div",{className:"cm-stat-sub"},f.provider+" · "+f.calls+r(" 次 · "," calls · ")+_(W(f,S),W(J,S))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_(W(f,S),W(J,S))}}))))),h.models.length>8?Y(V?r("收起","Show less"):r("显示全部模型","Show all models"),()=>I(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(Z,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(J[f]))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_(J[f],gt(J)),background:f.startsWith("cache")?"var(--cm-plan)":void 0}}))))),t("p",{className:"cm-stat-sub"},r("单独上报的推理 Token:","Reported reasoning tokens: ")+c(J.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:()=>et({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:z,count:h.sessionCount,size:25,onChange:E,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"),m=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getCallInspection","getContextCosts","getSessionTrajectory"].map(b=>[b,async C=>{const i=await a[b]((b==="getSessionTrajectory"?se:b==="getContextCosts"?zt:b==="getCallInspection"?oe:b==="getTurnInspection"?ne:ce)(C));if(!i?.ok)throw new Error(i?.error?.message||"Statistics request failed");return{getBillingStatistics:Bt,getSessionBilling:Dt,getTurnInspection:St,getCallInspection:Zt,getContextCosts:Ut,getSessionTrajectory:ae}[b](i.value)}]));m.saveStatisticsBasis=async b=>{const C=await a.updateConfig({statisticsBasis:b});if(!C?.ok||C.value?.config?.statisticsBasis!==b)throw new Error("Cost basis setting failed");n?.set?.({status:"ready",error:null,state:C.value})};let u;if(n?.subscribe&&typeof e.get("slots")?.entries=="function"){m.getContextIntegration=async()=>{const i=await a.getContextIntegration();if(!i?.ok)throw new Error("Integration check failed");return ee(i.value)},m.saveIntegration=async i=>{const M=await a.updateConfig({contextCostsEnabled:i,contextCostsPromptSeen:!0});if(!M?.ok||!M.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:M.value})},u=ge(e,m,n,o,Ht("react-dom").createPortal),e.effect(()=>u.dispose,"cost-meter: optional dsh-context integration");const b=e.get("slots"),C=()=>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",C),"cost-meter: context preview prompt")}const r=b=>t(b.sessionId?Ce:we,{...b,api:m,contextIntegration:u?{manager:u,getLocale:o}:null});return r.prefetch=b=>Se(m,b),e.effect(()=>()=>Ft.delete(m),"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}}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cost-meter",
3
- "version": "1.8.21",
3
+ "version": "1.8.23",
4
4
  "description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(11 家,含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching), Coding Plan quota queries & display for 11 vendors (incl. Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",