dsh-cost-meter 1.9.2 → 1.9.4

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,7 +1,8 @@
1
- window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:mt=>{const Fe=mt("react"),{createElement:e,useState:M,useEffect:ce,useRef:ge,Fragment:me}=Fe,Vt=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],q=(t,n)=>n==="total"?t.cost:n==="plan"?Math.max(0,t.cost-t.apiCost):t.apiCost,je=t=>t.input+t.cacheRead+t.cacheWrite+t.output,ue=(t,n)=>n>0?(100*t/n).toFixed(1)+"%":"—",ut=(t,n)=>new Date(Date.parse(t)+n*864e5).toISOString().slice(0,10),Qe=t=>n=>{if(typeof n!==t||t==="number"&&!Number.isFinite(n))throw new Error("Invalid statistics "+t);return n},S=Qe("number"),k=Qe("string"),U=Qe("boolean"),fe=t=>t===null?null:S(t),_=t=>n=>{if(!Array.isArray(n))throw new Error("Invalid statistics array");return n.map(t)},G=t=>n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid statistics object");return Object.fromEntries(Object.entries(t).map(([c,l])=>[c,l(n[c])]))},Ie=Object.fromEntries(Vt.map(t=>[t,S])),gt=G(Ie),Ye=t=>({...G({provider:k,model:k,bucket:k,tokens:S,rate:S,cost:S,priced:U,plan:U})(t),...t.requests===void 0?{}:{requests:S(t.requests)}}),Me=t=>({searchRequests:t("搜索请求","Search requests"),fetchRequests:t("抓取请求","Fetch requests")}),Xe=t=>k(t??""),Jt=G({source:k,requestId:k,attempt:S,complete:U,status:k,upstream:k}),Qt=G({sessionId:Xe,logSeq:t=>fe(t??null),kind:k,turn:fe,step:fe,provider:k,model:k,atMs:S,cost:S,apiCost:S,plan:U,priced:U,longContext:U,rows:_(Ye)}),Ue=t=>{const n=Qt(t);return t.metering!=null&&(n.metering=Jt(t.metering)),n},Ze=G({from:k,to:k,retainedFrom:k,retainedTo:k,totals:gt,days:_(G({...Ie,date:k})),models:_(G({...Ie,key:k,provider:k,model:k,priced:U})),sessions:_(G({...Ie,id:k,title:k})),providers:_(k),modelOptions:_(k),sessionCount:S,offset:S,unassignedCost:S,unmodeledCost:S}),Yt=G({refreshing:t=>U(t??!1),generatedAt:t=>S(t??0),refreshFailed:t=>U(t??!1),found:U,cost:S,apiCost:S,rows:_(Ye),calls:_(Ue),totalCalls:S,offset:S,recorded:gt,agents:t=>_(G({...Ie,id:k,title:k}))(t??[]),callShares:t=>_(G({index:S,cost:S,apiCost:S,tokens:S,calls:S,other:U,unpriced:U,call:n=>n==null?null:Ue(n)}))(t??[]),kinds:_(G({...Ie,kind:k,unpriced:U})),turns:_(G({...Ie,sessionId:Xe,turn:fe,unpriced:U})),totalTurns:S,turnOffset:S,stepShares:G(Object.fromEntries(["cost","calls"].map(t=>[t,_(G({...Ie,sessionId:Xe,turn:fe,step:fe,other:U,unpriced:U}))])))}),We=G({found:U,turn:S,input:k,inputTruncated:U,totalTools:S,offset:S,tools:_(G({seq:S,step:fe,name:k,callId:k,atMs:S,arguments:k,result:k,truncated:U,status:k}))}),ft=t=>({...G({found:U,kind:k,input:k,injected:k,skills:k,precedingTools:k,output:k,reasoning:k,truncated:U,totalTools:S,offset:S})(t),tools:We({...t,turn:0,inputTruncated:!1}).tools.map((n,c)=>({...n,durationMs:fe(t.tools[c].durationMs??null)}))}),$e=["system","tools","user","inject","skill","assistant","tool","other"],He=t=>{if(S(t)<0)throw new Error("Invalid context costs amount");return t},et=t=>({...Yt(t),...Object.fromEntries(["costCny","apiCostCny","costEur","apiCostEur"].filter(n=>t[n]!==void 0).map(n=>[n,S(t[n])]))}),bt=G(Object.fromEntries(["input","cacheRead","cacheWrite","output","reasoning"].map(t=>[t,He]))),Xt=t=>t===null?null:bt(t),tt=G({status:k,sessionId:k,generatedAt:S,revision:S,provider:k,model:k,basis:k,priced:U,source:k,linked:U,contextTokens:He,components:_(G({key:t=>{if(!$e.includes(t))throw new Error("Invalid context costs category");return t},tokens:He})),rates:Xt,longContext:t=>t===null?null:{...bt(t),aboveInputTokens:He(t.aboveInputTokens)},lastCall:t=>t===null?null:Ue(t)}),_e=t=>{const n=k(t?.sessionId);if(!n||n.length>512)throw new Error("Invalid context costs session");return{sessionId:n}},ht=G({version:k,compatible:U,reason:k}),qe=G({key:k,kind:k,sessionId:t=>k(t??""),title:t=>k(t??""),tools:_(k),steps:S,calls:t=>S(t??0),cost:S,apiCost:S,unpriced:U,parts:t=>_(G({bucket:k,cost:S,apiCost:S,tokens:S,unpriced:U}))(t??[])}),xt=G({refreshing:t=>U(t??!1),generatedAt:t=>S(t??0),refreshFailed:t=>U(t??!1),cost:S,apiCost:S,totalSteps:S,totalCalls:t=>S(t??0),matchingSteps:t=>t==null?null:S(t),order:t=>k(t??"time"),offset:S,shares:_(G({key:k,sessionId:k,turn:fe,step:fe,kind:k,tools:_(k),cost:S,apiCost:S,unpriced:U,other:U,count:S})),tiles:t=>_(G({key:k,groupKey:k,sessionId:k,turn:fe,step:fe,kind:k,tools:_(k),cost:S,apiCost:S,unpriced:U,other:U,count:S}))(t??[]),groups:_(qe),operations:t=>_(qe)(t??[]),operationGroups:t=>_(n=>({...qe(n),operationKey:k(n.operationKey)}))(t??[]),distribution:t=>_(G({key:k,steps:S,calls:S,cost:S,apiCost:S,unpriced:U}))(t??[]),hierarchy:t=>_(G({id:k,parentId:k,title:k,cost:S,apiCost:S,ownCost:S,ownApiCost:S,steps:S,calls:S,ownSteps:S,ownCalls:S,unpriced:n=>U(n??!1),groups:_(qe),operations:n=>_(qe)(n??[])}))(t??[]),steps:_(G({key:k,groupKey:t=>k(t??""),typeKey:t=>k(t??""),operationKey:t=>k(t??""),operationGroupKey:t=>k(t??""),sessionId:k,turn:fe,step:fe,kind:k,tools:_(k),atMs:S,calls:S,cost:S,apiCost:S,unpriced:U,rows:_(Ye),callRefs:t=>_(Ue)(t??[])}))}),vt=t=>{const n={..._e(t),basis:k(t.basis??"total"),offset:S(t.offset??0),order:k(t.order??"time"),group:k(t.group??""),agent:k(t.agent??""),background:U(t.background??!1),generation:k(t.generation??"")};if(Object.assign(n,{operation:k(t.operation??""),operationGroup:k(t.operationGroup??""),stepKey:k(t.stepKey??""),detail:k(t.detail??"full"),ownOnly:U(t.ownOnly??!1)}),n.operation.length>80||n.operationGroup.length>4096||n.stepKey.length>2048||!["full","map"].includes(n.detail))throw new Error("Invalid step category query");if(!["api","plan","total"].includes(n.basis)||!["cost","time"].includes(n.order)||n.group.length>1024||n.agent.length>512||n.generation.length>96||!Number.isSafeInteger(n.offset)||n.offset<0||n.offset>1e7)throw new Error("Invalid step billing query");if(t.displayCurrency!=null){if(!["USD","CNY","EUR"].includes(t.displayCurrency))throw Error("Invalid display currency");n.displayCurrency=t.displayCurrency}return n},yt=t=>{const n=G({sessionId:k,turn:S,offset:S})({...t,offset:t.offset??0});if(!n.sessionId||n.sessionId.length>512||![n.turn,n.offset].every(c=>Number.isSafeInteger(c)&&c>=0)||n.offset>1e7)throw new Error("Invalid turn inspection query");return n},kt=t=>{const n=G({from:k,to:k,provider:k,model:k,sessionId:k,basis:k,offset:S})(t);if(n.turnOffset=S(t.turnOffset??0),t.background!=null&&(n.background=U(t.background)),t.generation!=null&&(n.generation=k(t.generation)),!["api","plan","total"].includes(n.basis)||![n.offset,n.turnOffset].every(c=>Number.isSafeInteger(c)&&c>=0&&c<=1e7))throw new Error("Invalid statistics query");if(t.displayCurrency!=null){if(!["USD","CNY","EUR"].includes(t.displayCurrency))throw Error("Invalid display currency");n.displayCurrency=t.displayCurrency}return n},wt=t=>{const n={..._e(t),seq:S(t.seq),atMs:S(t.atMs),offset:S(t.offset??0)};if(![n.seq,n.offset].every(c=>Number.isSafeInteger(c)&&c>=0)||n.offset>1e7||n.atMs<=0)throw new Error("Invalid call inspection query");if(t.displayCurrency!=null){if(!["USD","CNY","EUR"].includes(t.displayCurrency))throw Error("Invalid display currency");n.displayCurrency=t.displayCurrency}return n},at=(t,n)=>{const c={parse:n};return{mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:c,create:()=>c}},Ct={package:"dsh-cost-meter/statistics",descriptors:[["getSessionTrajectory","Trajectory",xt,vt],["getBillingStatistics","BillingStatistics",Ze],["getSessionBilling","SessionBilling",et],["getTurnInspection","TurnInspection",We,yt],["getCallInspection","CallInspection",ft,wt],["getContextCosts","ContextCosts",tt,_e]].map(([t,n,c,l])=>({id:"dsh-cost-meter#costMeter/"+t,service:"costMeter",namespace:"costMeter",method:t,invocation:{kind:"direct"},parameters:[{name:"query",wire:"query",source:"json",codec:at(l?n+"Query":"StatisticsQuery",l??kt)}],result:at(n,c)})).concat({id:"dsh-cost-meter#costMeter/getContextIntegration",service:"costMeter",namespace:"costMeter",method:"getContextIntegration",invocation:{kind:"direct"},parameters:[],result:at("ContextIntegration",ht)})},Nt=`
1
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:mt=>{const Fe=mt("react"),{createElement:e,useState:M,useEffect:ce,useRef:ge,Fragment:me}=Fe,Vt=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],q=(t,n)=>n==="total"?t.cost:n==="plan"?Math.max(0,t.cost-t.apiCost):t.apiCost,je=t=>t.input+t.cacheRead+t.cacheWrite+t.output,ue=(t,n)=>n>0?(100*t/n).toFixed(1)+"%":"—",ut=(t,n)=>new Date(Date.parse(t)+n*864e5).toISOString().slice(0,10),Qe=t=>n=>{if(typeof n!==t||t==="number"&&!Number.isFinite(n))throw new Error("Invalid statistics "+t);return n},S=Qe("number"),k=Qe("string"),U=Qe("boolean"),fe=t=>t===null?null:S(t),H=t=>n=>{if(!Array.isArray(n))throw new Error("Invalid statistics array");return n.map(t)},G=t=>n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid statistics object");return Object.fromEntries(Object.entries(t).map(([c,l])=>[c,l(n[c])]))},Ie=Object.fromEntries(Vt.map(t=>[t,S])),gt=G(Ie),Ye=t=>({...G({provider:k,model:k,bucket:k,tokens:S,rate:S,cost:S,priced:U,plan:U})(t),...t.requests===void 0?{}:{requests:S(t.requests)}}),Me=t=>({searchRequests:t("搜索请求","Search requests"),fetchRequests:t("抓取请求","Fetch requests")}),Xe=t=>k(t??""),Jt=G({source:k,requestId:k,attempt:S,complete:U,status:k,upstream:k}),Qt=G({sessionId:Xe,logSeq:t=>fe(t??null),kind:k,turn:fe,step:fe,provider:k,model:k,atMs:S,cost:S,apiCost:S,plan:U,priced:U,longContext:U,rows:H(Ye)}),Ue=t=>{const n=Qt(t);return t.metering!=null&&(n.metering=Jt(t.metering)),n},Ze=G({from:k,to:k,retainedFrom:k,retainedTo:k,totals:gt,days:H(G({...Ie,date:k})),models:H(G({...Ie,key:k,provider:k,model:k,priced:U})),sessions:H(G({...Ie,id:k,title:k})),providers:H(k),modelOptions:H(k),sessionCount:S,offset:S,unassignedCost:S,unmodeledCost:S}),Yt=G({refreshing:t=>U(t??!1),generatedAt:t=>S(t??0),refreshFailed:t=>U(t??!1),found:U,cost:S,apiCost:S,rows:H(Ye),calls:H(Ue),totalCalls:S,offset:S,recorded:gt,agents:t=>H(G({...Ie,id:k,title:k}))(t??[]),callShares:t=>H(G({index:S,cost:S,apiCost:S,tokens:S,calls:S,other:U,unpriced:U,call:n=>n==null?null:Ue(n)}))(t??[]),kinds:H(G({...Ie,kind:k,unpriced:U})),turns:H(G({...Ie,sessionId:Xe,turn:fe,unpriced:U})),totalTurns:S,turnOffset:S,stepShares:G(Object.fromEntries(["cost","calls"].map(t=>[t,H(G({...Ie,sessionId:Xe,turn:fe,step:fe,other:U,unpriced:U}))])))}),We=G({found:U,turn:S,input:k,inputTruncated:U,totalTools:S,offset:S,tools:H(G({seq:S,step:fe,name:k,callId:k,atMs:S,arguments:k,result:k,truncated:U,status:k}))}),ft=t=>({...G({found:U,kind:k,input:k,injected:k,skills:k,precedingTools:k,output:k,reasoning:k,truncated:U,totalTools:S,offset:S})(t),tools:We({...t,turn:0,inputTruncated:!1}).tools.map((n,c)=>({...n,durationMs:fe(t.tools[c].durationMs??null)}))}),_e=["system","tools","user","inject","skill","assistant","tool","other"],$e=t=>{if(S(t)<0)throw new Error("Invalid context costs amount");return t},et=t=>({...Yt(t),...Object.fromEntries(["costCny","apiCostCny","costEur","apiCostEur"].filter(n=>t[n]!==void 0).map(n=>[n,S(t[n])]))}),bt=G(Object.fromEntries(["input","cacheRead","cacheWrite","output","reasoning"].map(t=>[t,$e]))),Xt=t=>t===null?null:bt(t),tt=G({status:k,sessionId:k,generatedAt:S,revision:S,provider:k,model:k,basis:k,priced:U,source:k,linked:U,contextTokens:$e,components:H(G({key:t=>{if(!_e.includes(t))throw new Error("Invalid context costs category");return t},tokens:$e})),rates:Xt,longContext:t=>t===null?null:{...bt(t),aboveInputTokens:$e(t.aboveInputTokens)},lastCall:t=>t===null?null:Ue(t)}),He=t=>{const n=k(t?.sessionId);if(!n||n.length>512)throw new Error("Invalid context costs session");return{sessionId:n}},ht=G({version:k,compatible:U,reason:k}),qe=G({key:k,kind:k,sessionId:t=>k(t??""),title:t=>k(t??""),tools:H(k),steps:S,calls:t=>S(t??0),cost:S,apiCost:S,unpriced:U,parts:t=>H(G({bucket:k,cost:S,apiCost:S,tokens:S,unpriced:U}))(t??[])}),xt=G({refreshing:t=>U(t??!1),generatedAt:t=>S(t??0),refreshFailed:t=>U(t??!1),cost:S,apiCost:S,totalSteps:S,totalCalls:t=>S(t??0),matchingSteps:t=>t==null?null:S(t),order:t=>k(t??"time"),offset:S,shares:H(G({key:k,sessionId:k,turn:fe,step:fe,kind:k,tools:H(k),cost:S,apiCost:S,unpriced:U,other:U,count:S})),tiles:t=>H(G({key:k,groupKey:k,sessionId:k,turn:fe,step:fe,kind:k,tools:H(k),cost:S,apiCost:S,unpriced:U,other:U,count:S}))(t??[]),groups:H(qe),operations:t=>H(qe)(t??[]),operationGroups:t=>H(n=>({...qe(n),operationKey:k(n.operationKey)}))(t??[]),distribution:t=>H(G({key:k,steps:S,calls:S,cost:S,apiCost:S,unpriced:U}))(t??[]),hierarchy:t=>H(G({id:k,parentId:k,title:k,cost:S,apiCost:S,ownCost:S,ownApiCost:S,steps:S,calls:S,ownSteps:S,ownCalls:S,unpriced:n=>U(n??!1),groups:H(qe),operations:n=>H(qe)(n??[])}))(t??[]),steps:H(G({key:k,groupKey:t=>k(t??""),typeKey:t=>k(t??""),operationKey:t=>k(t??""),operationGroupKey:t=>k(t??""),sessionId:k,turn:fe,step:fe,kind:k,tools:H(k),atMs:S,calls:S,cost:S,apiCost:S,unpriced:U,rows:H(Ye),callRefs:t=>H(Ue)(t??[])}))}),vt=t=>{const n={...He(t),basis:k(t.basis??"total"),offset:S(t.offset??0),order:k(t.order??"time"),group:k(t.group??""),agent:k(t.agent??""),background:U(t.background??!1),generation:k(t.generation??"")};if(Object.assign(n,{operation:k(t.operation??""),operationGroup:k(t.operationGroup??""),stepKey:k(t.stepKey??""),detail:k(t.detail??"full"),ownOnly:U(t.ownOnly??!1)}),n.operation.length>80||n.operationGroup.length>4096||n.stepKey.length>2048||!["full","map"].includes(n.detail))throw new Error("Invalid step category query");if(!["api","plan","total"].includes(n.basis)||!["cost","time"].includes(n.order)||n.group.length>1024||n.agent.length>512||n.generation.length>96||!Number.isSafeInteger(n.offset)||n.offset<0||n.offset>1e7)throw new Error("Invalid step billing query");if(t.displayCurrency!=null){if(!["USD","CNY","EUR"].includes(t.displayCurrency))throw Error("Invalid display currency");n.displayCurrency=t.displayCurrency}return n},yt=t=>{const n=G({sessionId:k,turn:S,offset:S})({...t,offset:t.offset??0});if(!n.sessionId||n.sessionId.length>512||![n.turn,n.offset].every(c=>Number.isSafeInteger(c)&&c>=0)||n.offset>1e7)throw new Error("Invalid turn inspection query");return n},kt=t=>{const n=G({from:k,to:k,provider:k,model:k,sessionId:k,basis:k,offset:S})(t);if(n.turnOffset=S(t.turnOffset??0),t.background!=null&&(n.background=U(t.background)),t.generation!=null&&(n.generation=k(t.generation)),!["api","plan","total"].includes(n.basis)||![n.offset,n.turnOffset].every(c=>Number.isSafeInteger(c)&&c>=0&&c<=1e7))throw new Error("Invalid statistics query");if(t.displayCurrency!=null){if(!["USD","CNY","EUR"].includes(t.displayCurrency))throw Error("Invalid display currency");n.displayCurrency=t.displayCurrency}return n},wt=t=>{const n={...He(t),seq:S(t.seq),atMs:S(t.atMs),offset:S(t.offset??0)};if(![n.seq,n.offset].every(c=>Number.isSafeInteger(c)&&c>=0)||n.offset>1e7||n.atMs<=0)throw new Error("Invalid call inspection query");if(t.displayCurrency!=null){if(!["USD","CNY","EUR"].includes(t.displayCurrency))throw Error("Invalid display currency");n.displayCurrency=t.displayCurrency}return n},at=(t,n)=>{const c={parse:n};return{mode:"strict",typeSymbol:"dsh-cost-meter#"+t,schema:c,create:()=>c}},Ct={package:"dsh-cost-meter/statistics",descriptors:[["getSessionTrajectory","Trajectory",xt,vt],["getBillingStatistics","BillingStatistics",Ze],["getSessionBilling","SessionBilling",et],["getTurnInspection","TurnInspection",We,yt],["getCallInspection","CallInspection",ft,wt],["getContextCosts","ContextCosts",tt,He]].map(([t,n,c,l])=>({id:"dsh-cost-meter#costMeter/"+t,service:"costMeter",namespace:"costMeter",method:t,invocation:{kind:"direct"},parameters:[{name:"query",wire:"query",source:"json",codec:at(l?n+"Query":"StatisticsQuery",l??kt)}],result:at(n,c)})).concat({id:"dsh-cost-meter#costMeter/getContextIntegration",service:"costMeter",namespace:"costMeter",method:"getContextIntegration",invocation:{kind:"direct"},parameters:[],result:at("ContextIntegration",ht)})},Nt=`
2
2
  .cm-stat{background:var(--cm-opaque-base,#fff);background:rgb(from var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,#fff)) r g b / 1);--cm-label:var(--dsw-alias-label-primary,#25262b);--cm-bg:var(--dsw-alias-bg-base,#fff);--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)}
5
+ .cm-stat-options{font-size:12px;color:var(--cm-muted);margin:8px 0 14px}.cm-stat-options>summary{cursor:pointer;list-style-position:inside;padding:3px 0}.cm-stat-options[open]>summary{margin-bottom:8px}.cm-stat-options .cm-stat-note{margin:0 0 8px!important;padding:8px 10px}.cm-stat-options .cm-context-setting{padding:8px 10px;margin:0}
5
6
  .cm-stat button,.cm-stat select,.cm-stat input{font:inherit;color:inherit}.cm-stat button{cursor:pointer}.cm-stat button:disabled{cursor:default;opacity:.45}.cm-stat button:focus-visible,.cm-stat select:focus-visible,.cm-stat input:focus-visible{outline:2px solid var(--cm-accent);outline-offset:3px}
6
7
  .cm-stat-controls{display:flex;flex-wrap:wrap;gap:10px;align-items:end;margin:14px 0}.cm-stat-controls label{display:grid;gap:4px;font-size:11px;color:var(--cm-muted)}
7
8
  .cm-stat input,.cm-stat select{background:var(--dsw-alias-bg-base,#fff);border:.5px solid var(--cm-border);border-radius:var(--dsw-radius-sm,8px);padding:6px 9px;max-width:210px;min-width:0}
@@ -43,7 +44,7 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
43
44
 
44
45
  .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)}
45
46
  @container(max-width:740px){.cm-spend-grid{grid-template-columns:1fr}}
46
- `;function Oe({rows:t,total:n,label:c,text:l,onSelect:o,amounts:a=!1,ranked:i=!1,centerValue:d}){const[r,y]=M(""),[C,b]=M(""),m=t.find(x=>x.key===(r||C)),g=x=>x.unpriced&&x.value===0?"—":n>0?ue(x.value,n):"—",u=x=>x.meta??(x.tokens??0).toLocaleString()+" tokens",N=x=>({"data-active":m?.key===x.key,onMouseEnter:()=>y(x.key),onMouseLeave:()=>y(""),onFocus:T=>{T.currentTarget.matches(":focus-visible")&&b(x.key)},onBlur:()=>b(""),onPointerDown:()=>b(""),onClick:()=>o?.(x),onKeyDown:T=>{T.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(T.key)&&(T.preventDefault(),o?.(x))}});let z=0;const E=t.filter(x=>x.value>0&&n>0).map(x=>{const T=Math.min(100,x.value/n*100),P=z;z+=T;const j=Math.min(.8,T*.15);return e("circle",{...N(x),key:x.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":x.label+" · "+g(x)+" · "+x.amount+" · "+u(x),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:x.color,strokeWidth:18,strokeDasharray:T-j+" "+(100-T+j),strokeDashoffset:-P-j/2,transform:"rotate(-90 78 78)"})});return e("div",{className:"cm-cost-chart","aria-label":c,"data-inspecting":!!m,onMouseLeave:()=>y("")},e("div",{className:"cm-cost-donut"},e("svg",{viewBox:"0 0 156 156","aria-label":c},e("circle",{cx:78,cy:78,r:61,fill:"none",stroke:"var(--cmp-bg)",strokeWidth:16}),...E),e("div",{className:"cm-cost-center","aria-hidden":!0},e("b",null,m?g(m):d??(n>0?"100%":"—")),e("small",null,m?.label??c))),e("div",{className:"cm-cost-legend"},...t.map(x=>e("button",{...N(x),type:"button",key:x.key,className:"cm-cost-key","aria-label":x.label+" "+g(x)},e("i",{className:"cm-plan-dot",style:{background:x.color}}),e("span",{className:"cm-cost-key-label"},x.label,a?e("small",{className:"cm-cost-key-amount"},x.amount,x.caption?" · "+x.caption:""):null,i?e("span",{className:"cm-fee-share-track","aria-hidden":!0},e("i",{style:{width:(n>0?x.value/n*100:0)+"%",background:x.color}})):null),e("span",{className:"cm-cost-key-share"},g(x))))),e("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},m?e(me,null,e("strong",null,m.label),e("span",null,u(m)),e("strong",null,m.amount)):null))}function Je({api:t,sessionId:n,revision:c="",text:l=(r,y)=>y,money:o=r=>"$"+r.toLocaleString("en-US",{maximumFractionDigits:6}),integrated:a=!1,compact:i=!1,expanded:d=!1}){const r=ge(null),y=ge(()=>{}),C=ge(c);C.current=c;const[b,m]=M(()=>({value:Le(Ae(t,"getContextCosts",{sessionId:n}),c),error:"",busy:!0}));ce(()=>{let h=!0,R=!1,te=typeof IntersectionObserver!="function";const W=async(p=!1)=>{if(!(!h||R||!te||document.hidden)){R=!0,m(v=>({...v,busy:!0}));try{const v=await Re(t,"getContextCosts",{sessionId:n},C.current,p===!0);if(v.sessionId!==n)throw new Error("Context costs session mismatch");h&&m({value:v,error:"",busy:!1})}catch{h&&m(v=>({...v,busy:!1,error:l("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{R=!1}}};y.current=W;const F=typeof IntersectionObserver=="function"?new IntersectionObserver(p=>{te=p.some(v=>v.isIntersecting),te&&W()}):null;r.current&&F?.observe(r.current),W();const J=setInterval(W,1e4);return document.addEventListener("visibilitychange",W),()=>{h=!1,clearInterval(J),F?.disconnect(),document.removeEventListener("visibilitychange",W)}},[t,n]),ce(()=>{const h=setTimeout(()=>y.current(),250);return()=>clearTimeout(h)},[c]);const g=b.value?.sessionId===n?b.value:null,u=e("div",{className:"cm-plan-head"},e("h3",null,l("上下文费用构成","Context cost breakdown")),e("div",null,a&&t.disableIntegration?e("button",{type:"button",onClick:t.disableIntegration},l("关闭联动","Turn off integration")):null,e("button",{type:"button",onClick:()=>y.current(!0),disabled:b.busy},l("刷新","Refresh")))),N=h=>e("section",{className:"cm-plan"+(i?" cm-context-compact":""),ref:r,"aria-label":l("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},e("style",null,Be),u,a?e("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,b.error?e("p",{role:"alert",className:"cm-plan-error"},b.error):null,h);if(!g||g.status!=="ready")return N(e("p",{className:"cm-plan-note"},g?g.status==="busy"?l("正在生成或摘要,完成后自动更新上下文费用。","Generation or compaction is running. Context costs refresh after it finishes."):g.status==="route-unavailable"?l("完成一次请求后,可显示该模型的上下文费用。","Complete a request to see context costs at that model’s rates."):g.status==="session-unavailable"?l("打开此会话后可读取当前上下文。","Open this conversation to read its current context."):l("当前宿主未提供上下文测量;已发生费用仍可在费用明细中查看。","Context measurement is unavailable on this host. Recorded costs remain available in billing details."):b.error?l("点击刷新重试。","Select Refresh to retry."):l("正在读取当前上下文…","Reading current context…")));const z=zt(g),E=g.priced&&!!z.rates,x=[l("系统提示","System prompt"),l("工具定义","Tool schemas"),l("用户输入","User messages"),l("注入内容","Injected context"),l("技能","Skills"),l("历史回复","Prior replies"),l("工具结果","Tool results"),l("其他","Other")],T=h=>Math.round(h).toLocaleString(),P=h=>E?"≈ "+o(h):l("未定价","Unpriced"),j=g.lastCall,B={input:l("非缓存输入","Uncached input"),cacheRead:l("缓存读取","Cache reads"),cacheWrite:l("缓存写入","Cache writes"),output:l("输出(含推理 Token)","Output (including reasoning tokens)"),reasoning:l("单独推理费用","Separate reasoning fees")};return N(e("div",{className:"cm-context-columns"},e("div",{className:"cm-context-current"},e("p",{className:"cm-plan-sub"},g.provider+" / "+g.model),e("div",{className:"cm-plan-summary"},e("div",null,e("div",{className:"cm-plan-sub"},l("当前上下文","Current context")),e("div",{className:"cm-plan-amount"},"≈ "+T(g.contextTokens)+" tokens")),e("div",null,e("div",{className:"cm-plan-sub"},g.basis==="plan"?l("Plan 输入等值","Plan input equivalent"):l("非缓存输入估算","Uncached input estimate")),e("div",{className:"cm-plan-amount"},P(z.cost)))),e("p",{className:"cm-plan-note"},l("按当前上下文全部作为非缓存输入发送一次估算,不含缓存折扣和输出费用,也不是本会话累计费用。","Estimates one send of the current context as uncached input, excluding cache discounts and output costs. This is not the session total.")),e("p",{className:"cm-plan-sub"},g.source==="usage"?l("总量按提供商最近用量及后续上下文变化校准;各部分 Token 和费用按组成比例估算,不代表压缩后的逐段实际用量。","The total follows reported usage plus subsequent context changes. Component tokens and costs are proportional estimates, not measured post-compression usage for each part."):l("总量及各部分均为本地估算,尚无可用的提供商用量校准。","The total and components are local estimates without an available provider-usage anchor.")),e(Oe,{rows:z.parts.filter(h=>h.tokens>0).map(h=>({key:h.key,label:x[$e.indexOf(h.key)],tokens:Math.round(h.tokens),value:E?h.cost:h.tokens,amount:P(h.cost),color:we[$e.indexOf(h.key)]})),total:E?z.cost:g.contextTokens,label:E?l("参考费用占比","Reference cost share"):l("Token 占比","Token share"),text:l}),e("details",{className:"cm-cost-table",open:d},e("summary",null,l("各部分计费","Component costs")),e("ul",{className:"cm-plan-parts"},...z.parts.filter(h=>h.tokens>0).map(h=>{const R=$e.indexOf(h.key);return e("li",{key:h.key},e("div",{className:"cm-plan-part-head"},e("span",null,e("i",{className:"cm-plan-dot",style:{background:we[R]}}),x[R]),e("span",null,P(h.cost))),e("div",{className:"cm-plan-part-meta"},e("span",null,"≈ "+T(h.tokens)+" tokens"),e("span",null,E?ue(h.cost,z.cost):"—")))})))),j?e("section",{className:"cm-plan-last"},e("h3",null,l("最近一次调用 · 用量计费","Latest call · usage-based costs")),e("p",{className:"cm-plan-sub"},j.provider+" / "+j.model+" · "+new Date(j.atMs).toLocaleString()),e(Oe,{rows:j.rows.filter(h=>h.tokens>0&&(h.bucket!=="reasoning"||h.rate>0)).map(h=>({key:h.bucket,label:B[h.bucket]??h.bucket,tokens:h.tokens,value:h.cost,amount:j.priced?o(h.cost):l("未定价","Unpriced"),color:we[st[h.bucket]??7]})),total:j.priced?j.cost:0,label:l("费用占比","Cost share"),text:l}),e("details",{className:"cm-cost-table",open:d},e("summary",null,l("调用计费明细","Call billing details")),e("ul",{className:"cm-plan-parts",style:{marginTop:12}},...j.rows.filter(h=>h.bucket!=="reasoning"||h.rate>0).map(h=>e("li",{key:h.bucket},e("div",{className:"cm-plan-part-head"},e("span",null,B[h.bucket]??h.bucket),e("span",null,j.priced?o(h.cost):l("未定价","Unpriced"))),e("div",{className:"cm-plan-part-meta"},e("span",null,T(h.tokens)+" tokens"),e("span",null,j.priced?ue(h.cost,j.cost):"—")))))),e("p",{className:"cm-plan-total"},l("合计 ","Total ")+(j.priced?o(j.cost):l("未定价","Unpriced"))+(j.plan?l(" · Plan 的 API 等值"," · Plan API equivalent"):""))):e("p",{className:"cm-plan-note"},l("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),E?null:e("p",{className:"cm-plan-note"},l("未配置模型单价","Model rates not configured"))))}const ot=[["conversation.view","id","context"],["sidebar.right.pane.tab","key","dsh-context"],["conversation.input.overlay","id","context-modal"]];function Mt(t,n,c,l,o){const a=t.get("slots");if(!["entries","subscribe","register","entriesOfSlot"].every(b=>typeof a?.[b]=="function"))return()=>{};const i=[],d=new Map;let r=!0;function y(b){return function(g){o&&Fe.useSyncExternalStore(o.subscribe,c);const u=ge(null),[N,z]=M(null),E=g.useProjection?.("contextBreakdown"),x=g.useProjection?.("tokenUsage"),T=g.useProjection?.("contextPressure"),P=JSON.stringify([E,x,T]);ce(()=>{const h=b?u.current:u.current?.closest("[data-conversation-session]");if(!h||!b&&h.dataset.conversationSession!==g.sessionId||typeof MutationObserver!="function")return;const R=document.createElement("div");R.className="cm-plan-host",R.dataset.cmContextCosts="";let te=null;const W=()=>{if(R.isConnected&&te?.matches("[data-lc-current]")&&h.contains(te))return;const J=b?h.querySelector("[data-lc-current]"):[...h.querySelectorAll('[data-slot="conversation.view"] [data-lc-current]')].find(p=>p.closest("[data-conversation-session]")===h);if(!J){R.remove(),z(null);return}R.parentElement!==J&&(te=J,J.appendChild(R),z(R))},F=new MutationObserver(W);return F.observe(h,{childList:!0,subtree:!0}),W(),()=>{F.disconnect(),R.remove()}},[g.sessionId]);const j=(h,R)=>c()==="en"?R:h,B=N&&g.sessionId?l(e(Je,{key:g.sessionId,api:n,sessionId:g.sessionId,integrated:!0,text:j,revision:P}),N):null;return b?e("div",{ref:u,style:{display:"contents"},"data-cm-context-bridge":g.sessionId},e(b,g),B):e(me,null,e("span",{ref:u,hidden:!0}),B)}}const C=()=>{r=!1;for(const b of i)b();for(const b of d.values())b.dispose();d.clear()};try{for(const[b,m,g]of ot){const u=b==="conversation.view",N=u?"conversation.input.overlay":b;let z=!1;const E=()=>{if(!(!r||z)){z=!0;try{const x=a.entries(b).filter(R=>R.locale==="dsh-context"&&R.options[m]===g&&R.registrant!=="dsh-cost-meter-context-bridge"),T=x.length===1?x[0]:null,P=d.get(b),j=a.entriesOfSlot(b).find(R=>R.options[m]===g);if(P?.original===T&&a.entries(N).some(R=>R.component===P.component)&&(u?j===T:j?.component===P.component)||(P?.dispose(),d.delete(b),!T||T.children||T.store||typeof T.component!="function")||a.entriesOfSlot(b).find(R=>R.options[m]===g)!==T||u&&typeof a.spec=="function"&&!a.spec(N))return;const B=y(u?null:T.component),h=a.register(u?{name:N,id:"cost-meter-context-main",registrant:"dsh-cost-meter-context-bridge"}:{name:b,...T.options,inject:T.inject,locale:T.locale,priority:(T.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},B);d.set(b,{original:T,component:B,dispose:h})}finally{z=!1}}};i.push(a.subscribe(b,E)),u&&i.push(a.subscribe(N,E)),E()}}catch(b){throw C(),b}return C}const lt="dsh-cost-meter:context-intro-seen",Rt=()=>{try{return localStorage.getItem(lt)==="1"}catch{return!1}},ea=()=>{try{localStorage.setItem(lt,"1")}catch{}};function Ot(t,n,c,l,o){const a=t.get("slots"),i=new Set,d=[];let r=!0,y=null,C=[],b=!1,m=0,g=Rt(),u=null,N=0,z=Promise.resolve(),E=!1,x=!1,T={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const P=["entries","entriesOfSlot","register","subscribe"].every(p=>typeof a?.[p]=="function"),j=p=>{T={...T,...p};for(const v of i)v()},B=()=>{if(r){if(E){x=!0;return}E=!0;try{do{x=!1;const p=c.getSnapshot().state?.config,v=P&&T.peer.compatible&&C.length>0,A=v&&!T.saving&&(u??p?.contextCostsEnabled)===!0;if(!A&&y){const L=y;y=null,L()}if(A&&!y){const L=Mt(t,{...n,disableIntegration:()=>{te(!1)}},l,o,c);r?y=L:L()}const D=T.prompt&&(T.manual||v);r&&j({available:v,enabled:A,prompt:D||!!(p&&v&&!p.contextCostsPromptSeen&&!p.contextCostsEnabled&&!g)})}while(r&&x)}finally{E=!1}}},h=async(p=!1)=>{if(!r||!P)return;const v=ot.flatMap(([D,L,Z])=>a.entries(D).filter(Q=>Q.locale==="dsh-context"&&Q.options[L]===Z&&Q.registrant!=="dsh-cost-meter-context-bridge"&&!Q.children&&!Q.store&&typeof Q.component=="function"));if(!p&&b&&v.length===C.length&&v.every((D,L)=>D===C[L]))return;C=v,b=!0;const A=++m;j({peer:{version:"",compatible:!1,reason:v.length?"unavailable":"missing"}}),B();try{const D=await n.getContextIntegration();r&&A===m&&(j({peer:D}),B())}catch{r&&A===m&&B()}};function R(){g=!0,ea()}async function te(p,v=!1){if(!r||p&&!T.available&&!v)return;const A=++N;R(),u=p,j({prompt:!1,manual:!1,saving:!0,error:""}),B();const D=z.catch(()=>{}).then(()=>n.saveIntegration(p));z=D;try{await D,r&&A===N&&(u=null,j({saving:!1}),B())}catch{r&&A===N&&(u=!1,j({saving:!1,error:"save"}),B())}}if(d.push(c.subscribe(B)),P)for(const[p]of ot)d.push(a.subscribe(p,()=>{h()}));const W=()=>{document.hidden||h(!0)};document.addEventListener("visibilitychange",W);const F=p=>{p.key===lt&&p.newValue==="1"&&!g&&(g=!0,j({prompt:!1}),B())};return window.addEventListener("storage",F),h(),B(),{getSnapshot:()=>T,subscribe:p=>(i.add(p),()=>i.delete(p)),choose:te,dismiss:()=>te(T.manual?c.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:R,preview:()=>j({prompt:!0,manual:!0}),refresh:()=>{h(!0)},dispose:()=>{r=!1,++m;for(const p of d)p();y?.(),i.clear(),document.removeEventListener("visibilitychange",W),window.removeEventListener("storage",F)}}}const Pt=`
47
+ `;function Oe({rows:t,total:n,label:c,text:l,onSelect:o,amounts:a=!1,ranked:i=!1,centerValue:d}){const[r,y]=M(""),[C,b]=M(""),m=t.find(x=>x.key===(r||C)),g=x=>x.unpriced&&x.value===0?"—":n>0?ue(x.value,n):"—",u=x=>x.meta??(x.tokens??0).toLocaleString()+" tokens",N=x=>({"data-active":m?.key===x.key,onMouseEnter:()=>y(x.key),onMouseLeave:()=>y(""),onFocus:T=>{T.currentTarget.matches(":focus-visible")&&b(x.key)},onBlur:()=>b(""),onPointerDown:()=>b(""),onClick:()=>o?.(x),onKeyDown:T=>{T.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(T.key)&&(T.preventDefault(),o?.(x))}});let z=0;const E=t.filter(x=>x.value>0&&n>0).map(x=>{const T=Math.min(100,x.value/n*100),P=z;z+=T;const j=Math.min(.8,T*.15);return e("circle",{...N(x),key:x.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":x.label+" · "+g(x)+" · "+x.amount+" · "+u(x),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:x.color,strokeWidth:18,strokeDasharray:T-j+" "+(100-T+j),strokeDashoffset:-P-j/2,transform:"rotate(-90 78 78)"})});return e("div",{className:"cm-cost-chart","aria-label":c,"data-inspecting":!!m,onMouseLeave:()=>y("")},e("div",{className:"cm-cost-donut"},e("svg",{viewBox:"0 0 156 156","aria-label":c},e("circle",{cx:78,cy:78,r:61,fill:"none",stroke:"var(--cmp-bg)",strokeWidth:16}),...E),e("div",{className:"cm-cost-center","aria-hidden":!0},e("b",null,m?g(m):d??(n>0?"100%":"—")),e("small",null,m?.label??c))),e("div",{className:"cm-cost-legend"},...t.map(x=>e("button",{...N(x),type:"button",key:x.key,className:"cm-cost-key","aria-label":x.label+" "+g(x)},e("i",{className:"cm-plan-dot",style:{background:x.color}}),e("span",{className:"cm-cost-key-label"},x.label,a?e("small",{className:"cm-cost-key-amount"},x.amount,x.caption?" · "+x.caption:""):null,i?e("span",{className:"cm-fee-share-track","aria-hidden":!0},e("i",{style:{width:(n>0?x.value/n*100:0)+"%",background:x.color}})):null),e("span",{className:"cm-cost-key-share"},g(x))))),e("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},m?e(me,null,e("strong",null,m.label),e("span",null,u(m)),e("strong",null,m.amount)):null))}function Je({api:t,sessionId:n,revision:c="",text:l=(r,y)=>y,money:o=r=>"$"+r.toLocaleString("en-US",{maximumFractionDigits:6}),integrated:a=!1,compact:i=!1,expanded:d=!1}){const r=ge(null),y=ge(()=>{}),C=ge(c);C.current=c;const[b,m]=M(()=>({value:Le(Ae(t,"getContextCosts",{sessionId:n}),c),error:"",busy:!0}));ce(()=>{let h=!0,R=!1,te=typeof IntersectionObserver!="function";const W=async(p=!1)=>{if(!(!h||R||!te||document.hidden)){R=!0,m(v=>({...v,busy:!0}));try{const v=await Re(t,"getContextCosts",{sessionId:n},C.current,p===!0);if(v.sessionId!==n)throw new Error("Context costs session mismatch");h&&m({value:v,error:"",busy:!1})}catch{h&&m(v=>({...v,busy:!1,error:l("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{R=!1}}};y.current=W;const F=typeof IntersectionObserver=="function"?new IntersectionObserver(p=>{te=p.some(v=>v.isIntersecting),te&&W()}):null;r.current&&F?.observe(r.current),W();const J=setInterval(W,1e4);return document.addEventListener("visibilitychange",W),()=>{h=!1,clearInterval(J),F?.disconnect(),document.removeEventListener("visibilitychange",W)}},[t,n]),ce(()=>{const h=setTimeout(()=>y.current(),250);return()=>clearTimeout(h)},[c]);const g=b.value?.sessionId===n?b.value:null,u=e("div",{className:"cm-plan-head"},e("h3",null,l("上下文费用构成","Context cost breakdown")),e("div",null,a&&t.disableIntegration?e("button",{type:"button",onClick:t.disableIntegration},l("关闭联动","Turn off integration")):null,e("button",{type:"button",onClick:()=>y.current(!0),disabled:b.busy},l("刷新","Refresh")))),N=h=>e("section",{className:"cm-plan"+(i?" cm-context-compact":""),ref:r,"aria-label":l("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},e("style",null,Be),u,a?e("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,b.error?e("p",{role:"alert",className:"cm-plan-error"},b.error):null,h);if(!g||g.status!=="ready")return N(e("p",{className:"cm-plan-note"},g?g.status==="busy"?l("正在生成或摘要,完成后自动更新上下文费用。","Generation or compaction is running. Context costs refresh after it finishes."):g.status==="route-unavailable"?l("完成一次请求后,可显示该模型的上下文费用。","Complete a request to see context costs at that model’s rates."):g.status==="session-unavailable"?l("打开此会话后可读取当前上下文。","Open this conversation to read its current context."):l("当前宿主未提供上下文测量;已发生费用仍可在费用明细中查看。","Context measurement is unavailable on this host. Recorded costs remain available in billing details."):b.error?l("点击刷新重试。","Select Refresh to retry."):l("正在读取当前上下文…","Reading current context…")));const z=zt(g),E=g.priced&&!!z.rates,x=[l("系统提示","System prompt"),l("工具定义","Tool schemas"),l("用户输入","User messages"),l("注入内容","Injected context"),l("技能","Skills"),l("历史回复","Prior replies"),l("工具结果","Tool results"),l("其他","Other")],T=h=>Math.round(h).toLocaleString(),P=h=>E?"≈ "+o(h):l("未定价","Unpriced"),j=g.lastCall,B={input:l("非缓存输入","Uncached input"),cacheRead:l("缓存读取","Cache reads"),cacheWrite:l("缓存写入","Cache writes"),output:l("输出(含推理 Token)","Output (including reasoning tokens)"),reasoning:l("单独推理费用","Separate reasoning fees")};return N(e("div",{className:"cm-context-columns"},e("div",{className:"cm-context-current"},e("p",{className:"cm-plan-sub"},g.provider+" / "+g.model),e("div",{className:"cm-plan-summary"},e("div",null,e("div",{className:"cm-plan-sub"},l("当前上下文","Current context")),e("div",{className:"cm-plan-amount"},"≈ "+T(g.contextTokens)+" tokens")),e("div",null,e("div",{className:"cm-plan-sub"},g.basis==="plan"?l("Plan 输入等值","Plan input equivalent"):l("非缓存输入估算","Uncached input estimate")),e("div",{className:"cm-plan-amount"},P(z.cost)))),e("p",{className:"cm-plan-note"},l("按当前上下文全部作为非缓存输入发送一次估算,不含缓存折扣和输出费用,也不是本会话累计费用。","Estimates one send of the current context as uncached input, excluding cache discounts and output costs. This is not the session total.")),e("p",{className:"cm-plan-sub"},g.source==="usage"?l("总量按提供商最近用量及后续上下文变化校准;各部分 Token 和费用按组成比例估算,不代表压缩后的逐段实际用量。","The total follows reported usage plus subsequent context changes. Component tokens and costs are proportional estimates, not measured post-compression usage for each part."):l("总量及各部分均为本地估算,尚无可用的提供商用量校准。","The total and components are local estimates without an available provider-usage anchor.")),e(Oe,{rows:z.parts.filter(h=>h.tokens>0).map(h=>({key:h.key,label:x[_e.indexOf(h.key)],tokens:Math.round(h.tokens),value:E?h.cost:h.tokens,amount:P(h.cost),color:we[_e.indexOf(h.key)]})),total:E?z.cost:g.contextTokens,label:E?l("参考费用占比","Reference cost share"):l("Token 占比","Token share"),text:l}),e("details",{className:"cm-cost-table",open:d},e("summary",null,l("各部分计费","Component costs")),e("ul",{className:"cm-plan-parts"},...z.parts.filter(h=>h.tokens>0).map(h=>{const R=_e.indexOf(h.key);return e("li",{key:h.key},e("div",{className:"cm-plan-part-head"},e("span",null,e("i",{className:"cm-plan-dot",style:{background:we[R]}}),x[R]),e("span",null,P(h.cost))),e("div",{className:"cm-plan-part-meta"},e("span",null,"≈ "+T(h.tokens)+" tokens"),e("span",null,E?ue(h.cost,z.cost):"—")))})))),j?e("section",{className:"cm-plan-last"},e("h3",null,l("最近一次调用 · 用量计费","Latest call · usage-based costs")),e("p",{className:"cm-plan-sub"},j.provider+" / "+j.model+" · "+new Date(j.atMs).toLocaleString()),e(Oe,{rows:j.rows.filter(h=>h.tokens>0&&(h.bucket!=="reasoning"||h.rate>0)).map(h=>({key:h.bucket,label:B[h.bucket]??h.bucket,tokens:h.tokens,value:h.cost,amount:j.priced?o(h.cost):l("未定价","Unpriced"),color:we[st[h.bucket]??7]})),total:j.priced?j.cost:0,label:l("费用占比","Cost share"),text:l}),e("details",{className:"cm-cost-table",open:d},e("summary",null,l("调用计费明细","Call billing details")),e("ul",{className:"cm-plan-parts",style:{marginTop:12}},...j.rows.filter(h=>h.bucket!=="reasoning"||h.rate>0).map(h=>e("li",{key:h.bucket},e("div",{className:"cm-plan-part-head"},e("span",null,B[h.bucket]??h.bucket),e("span",null,j.priced?o(h.cost):l("未定价","Unpriced"))),e("div",{className:"cm-plan-part-meta"},e("span",null,T(h.tokens)+" tokens"),e("span",null,j.priced?ue(h.cost,j.cost):"—")))))),e("p",{className:"cm-plan-total"},l("合计 ","Total ")+(j.priced?o(j.cost):l("未定价","Unpriced"))+(j.plan?l(" · Plan 的 API 等值"," · Plan API equivalent"):""))):e("p",{className:"cm-plan-note"},l("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),E?null:e("p",{className:"cm-plan-note"},l("未配置模型单价","Model rates not configured"))))}const ot=[["conversation.view","id","context"],["sidebar.right.pane.tab","key","dsh-context"],["conversation.input.overlay","id","context-modal"]];function Mt(t,n,c,l,o){const a=t.get("slots");if(!["entries","subscribe","register","entriesOfSlot"].every(b=>typeof a?.[b]=="function"))return()=>{};const i=[],d=new Map;let r=!0;function y(b){return function(g){o&&Fe.useSyncExternalStore(o.subscribe,c);const u=ge(null),[N,z]=M(null),E=g.useProjection?.("contextBreakdown"),x=g.useProjection?.("tokenUsage"),T=g.useProjection?.("contextPressure"),P=JSON.stringify([E,x,T]);ce(()=>{const h=b?u.current:u.current?.closest("[data-conversation-session]");if(!h||!b&&h.dataset.conversationSession!==g.sessionId||typeof MutationObserver!="function")return;const R=document.createElement("div");R.className="cm-plan-host",R.dataset.cmContextCosts="";let te=null;const W=()=>{if(R.isConnected&&te?.matches("[data-lc-current]")&&h.contains(te))return;const J=b?h.querySelector("[data-lc-current]"):[...h.querySelectorAll('[data-slot="conversation.view"] [data-lc-current]')].find(p=>p.closest("[data-conversation-session]")===h);if(!J){R.remove(),z(null);return}R.parentElement!==J&&(te=J,J.appendChild(R),z(R))},F=new MutationObserver(W);return F.observe(h,{childList:!0,subtree:!0}),W(),()=>{F.disconnect(),R.remove()}},[g.sessionId]);const j=(h,R)=>c()==="en"?R:h,B=N&&g.sessionId?l(e(Je,{key:g.sessionId,api:n,sessionId:g.sessionId,integrated:!0,text:j,revision:P}),N):null;return b?e("div",{ref:u,style:{display:"contents"},"data-cm-context-bridge":g.sessionId},e(b,g),B):e(me,null,e("span",{ref:u,hidden:!0}),B)}}const C=()=>{r=!1;for(const b of i)b();for(const b of d.values())b.dispose();d.clear()};try{for(const[b,m,g]of ot){const u=b==="conversation.view",N=u?"conversation.input.overlay":b;let z=!1;const E=()=>{if(!(!r||z)){z=!0;try{const x=a.entries(b).filter(R=>R.locale==="dsh-context"&&R.options[m]===g&&R.registrant!=="dsh-cost-meter-context-bridge"),T=x.length===1?x[0]:null,P=d.get(b),j=a.entriesOfSlot(b).find(R=>R.options[m]===g);if(P?.original===T&&a.entries(N).some(R=>R.component===P.component)&&(u?j===T:j?.component===P.component)||(P?.dispose(),d.delete(b),!T||T.children||T.store||typeof T.component!="function")||a.entriesOfSlot(b).find(R=>R.options[m]===g)!==T||u&&typeof a.spec=="function"&&!a.spec(N))return;const B=y(u?null:T.component),h=a.register(u?{name:N,id:"cost-meter-context-main",registrant:"dsh-cost-meter-context-bridge"}:{name:b,...T.options,inject:T.inject,locale:T.locale,priority:(T.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},B);d.set(b,{original:T,component:B,dispose:h})}finally{z=!1}}};i.push(a.subscribe(b,E)),u&&i.push(a.subscribe(N,E)),E()}}catch(b){throw C(),b}return C}const lt="dsh-cost-meter:context-intro-seen",Rt=()=>{try{return localStorage.getItem(lt)==="1"}catch{return!1}},ea=()=>{try{localStorage.setItem(lt,"1")}catch{}};function Ot(t,n,c,l,o){const a=t.get("slots"),i=new Set,d=[];let r=!0,y=null,C=[],b=!1,m=0,g=Rt(),u=null,N=0,z=Promise.resolve(),E=!1,x=!1,T={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const P=["entries","entriesOfSlot","register","subscribe"].every(p=>typeof a?.[p]=="function"),j=p=>{T={...T,...p};for(const v of i)v()},B=()=>{if(r){if(E){x=!0;return}E=!0;try{do{x=!1;const p=c.getSnapshot().state?.config,v=P&&T.peer.compatible&&C.length>0,A=v&&!T.saving&&(u??p?.contextCostsEnabled)===!0;if(!A&&y){const L=y;y=null,L()}if(A&&!y){const L=Mt(t,{...n,disableIntegration:()=>{te(!1)}},l,o,c);r?y=L:L()}const D=T.prompt&&(T.manual||v);r&&j({available:v,enabled:A,prompt:D||!!(p&&v&&!p.contextCostsPromptSeen&&!p.contextCostsEnabled&&!g)})}while(r&&x)}finally{E=!1}}},h=async(p=!1)=>{if(!r||!P)return;const v=ot.flatMap(([D,L,Z])=>a.entries(D).filter(Q=>Q.locale==="dsh-context"&&Q.options[L]===Z&&Q.registrant!=="dsh-cost-meter-context-bridge"&&!Q.children&&!Q.store&&typeof Q.component=="function"));if(!p&&b&&v.length===C.length&&v.every((D,L)=>D===C[L]))return;C=v,b=!0;const A=++m;j({peer:{version:"",compatible:!1,reason:v.length?"unavailable":"missing"}}),B();try{const D=await n.getContextIntegration();r&&A===m&&(j({peer:D}),B())}catch{r&&A===m&&B()}};function R(){g=!0,ea()}async function te(p,v=!1){if(!r||p&&!T.available&&!v)return;const A=++N;R(),u=p,j({prompt:!1,manual:!1,saving:!0,error:""}),B();const D=z.catch(()=>{}).then(()=>n.saveIntegration(p));z=D;try{await D,r&&A===N&&(u=null,j({saving:!1}),B())}catch{r&&A===N&&(u=!1,j({saving:!1,error:"save"}),B())}}if(d.push(c.subscribe(B)),P)for(const[p]of ot)d.push(a.subscribe(p,()=>{h()}));const W=()=>{document.hidden||h(!0)};document.addEventListener("visibilitychange",W);const F=p=>{p.key===lt&&p.newValue==="1"&&!g&&(g=!0,j({prompt:!1}),B())};return window.addEventListener("storage",F),h(),B(),{getSnapshot:()=>T,subscribe:p=>(i.add(p),()=>i.delete(p)),choose:te,dismiss:()=>te(T.manual?c.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:R,preview:()=>j({prompt:!0,manual:!0}),refresh:()=>{h(!0)},dispose:()=>{r=!1,++m;for(const p of d)p();y?.(),i.clear(),document.removeEventListener("visibilitychange",W),window.removeEventListener("storage",F)}}}const Pt=`
47
48
  .cm-context-intro{--cmp-top:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,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(--cm-opaque-base,#fff);background:rgb(from var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,#fff)) r g b / 1);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)}
48
49
  .cm-context-intro[open]{display:flex;flex-direction:column}.cm-context-intro::backdrop{inset:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,0px)) 0 0;background:#0005}.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}
49
50
  .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}
@@ -56,13 +57,13 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
56
57
  .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}
57
58
  @container(max-width:850px){.cm-call-detail-grid{grid-template-columns:1fr}.cm-call-tool-parts{grid-template-columns:1fr}}
58
59
  .cm-call-compact{grid-template-columns:1fr;gap:12px;margin-top:0}.cm-call-compact .cm-call-bill{padding:0;border:0}.cm-call-compact .cm-call-bill .cm-stat-value{font-size:20px}.cm-call-compact .cm-call-bill .cm-stat-panel-head{margin:0}.cm-call-compact .cm-call-bill .cm-stat-sub{font-size:11px;margin:3px 0 8px}.cm-call-compact .cm-call-content{padding:0;border:0}.cm-call-compact .cm-call-content .cm-stat-pre{max-height:320px}.cm-call-compact .cm-call-bill .cm-stat-table td,.cm-call-compact .cm-call-bill .cm-stat-table th{padding:5px 6px}
59
- `),e("section",{className:"cm-plan cm-call-bill","aria-label":a("本次计费明细","Call billing breakdown")},e("div",{className:"cm-stat-panel-head"},e("h3",null,t.plan?a("Plan 等值费用","Plan equivalent"):a("API 费用","API cost")),e("strong",{className:"cm-stat-value"},t.priced?o(t.cost):"?")),e("p",{className:"cm-stat-sub"},t.provider+" / "+t.model+" · "+new Date(t.atMs).toLocaleString()),t.metering?e("p",{className:"cm-stat-note"},"billion-context · "+t.metering.upstream+(t.metering.attempt>1?a(" · 重试 "," · Retry ")+t.metering.attempt:"")+(t.metering.complete?"":a(" · 仅含已收到的用量,未知费用未估补"," · observed usage only; unknown charges are not inferred"))):null,d?null:e(Oe,{rows:b,total:t.cost,label:a("本次费用构成","This call’s costs"),text:a,amounts:!0,onSelect:m=>y(["output","reasoning"].includes(m.key)?"output":"input")}),e("div",{className:"cm-stat-scroll cm-step-rates"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[a("计费项目","Component"),a("用量","Usage"),C.some(m=>m.requests)?a("单价 / 次","Rate / request"):a("单价 / 百万","Rate / 1M"),a("金额","Cost"),a("占比","Share")].map(m=>e("th",{key:m},m)))),e("tbody",null,...C.map(m=>{const g=m.bucket==="reasoning"&&m.priced&&m.rate===0;return e("tr",{key:m.bucket},e("td",null,i[m.bucket]??Me(a)[m.bucket]),e("td",null,m.requests?m.requests+a(" 次"," requests"):m.tokens.toLocaleString()+" tokens"),e("td",null,m.priced?o(m.rate)+(m.requests?a(" / 次"," / request"):" / 1M"):"?"),e("td",null,g?a("未单独计费","No separate charge"):m.priced?o(m.cost):"?"),e("td",null,m.priced&&!g?ue(m.cost,t.cost):"—"))}))))),t.logSeq!=null?e(ta,{api:c,sessionId:t.sessionId||n,seq:t.logSeq,atMs:t.atMs,revision:l,text:a,view:r,onViewChange:y}):e("p",{className:"cm-stat-sub"},a("未保存调用内容","Call content not stored")))}const pt=t=>({read:t("读取文件","Read files"),"local-search":t("本地检索","Local search"),write:t("文件修改","File changes"),command:t("命令执行","Commands"),tool:t("其他工具","Other tools"),model:t("模型回复","Model responses"),search:t("网页搜索","Web search"),fetch:t("网页抓取","Web fetch"),compaction:t("上下文压缩","Compaction"),coordination:t("代理协作","Agent coordination"),"multi-tool":t("多类工具","Mixed tools"),"other-tools":t("其他工具调用","Other tools"),other:t("其他调用","Other calls")}),aa=t=>t.replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,""),xe=(t,n)=>t>0&&n>0&&t/n<.001?"<0.1%":ue(t,n),ke=t=>t.kind==="subagent"?"agent:"+t.sessionId:"type:"+t.kind+":"+t.tools.join("|");function na(t){const n=new Set([...t.groups,...t.operations??[]].map(ke));for(const a of t.hierarchy){n.add("agent:"+a.id);for(const i of a.groups)n.add(ke(i))}const c=["#627bff","#f6b64b","#30c89c","#ad78f5","#fb8c6f","#42b4f5","#24bdc9","#e576a8","#9abd3a","#9c83d9","#c28b4c","#368fc7"],l=new Map,o=new Set;for(const a of[...n].sort()){if(a.startsWith("type:other-tools:")){l.set(a,"#a0aec5");continue}let i=2166136261;for(const y of a)i=Math.imul(i^y.charCodeAt(0),16777619)>>>0;let d=c[i%c.length],r=0;for(;o.has(d)&&r<c.length;)d=c[(i+ ++r)%c.length];o.has(d)&&(d=`hsl(${(i%36e3/100).toFixed(2)} 68% ${56+i%6}%)`),l.set(a,d),o.add(d)}return l}function Pe(t,n,c,l,o){const a=t.filter(C=>C.value>0).sort((C,b)=>b.value-C.value||C.key.localeCompare(b.key));if(!a.length||l<=0||o<=0)return[];if(a.length===1)return[{...a[0],x:n,y:c,width:l,height:o}];const i=a.reduce((C,b)=>C+b.value,0);let d=1,r=a[0].value;for(;d<a.length-1&&Math.abs(r+a[d].value-i/2)<Math.abs(r-i/2);)r+=a[d++].value;const y=r/i;return l>=o?[...Pe(a.slice(0,d),n,c,l*y,o),...Pe(a.slice(d),n+l*y,c,l*(1-y),o)]:[...Pe(a.slice(0,d),n,c,l,o*y),...Pe(a.slice(d),n,c+o*y,l,o*(1-y))]}function sa({value:t,basis:n,colors:c,actorName:l,groupName:o,money:a,text:i,onSelect:d}){const r=ge(null),[y,C]=M(720),[b,m]=M(""),[g,u]=M(null),[N,z]=M("operation"),E=q(t,n),x=t.operations?.length>0,T=(x?N==="operation"?t.operations:t.hierarchy.map(p=>({...p,key:p.id,kind:"subagent",sessionId:p.id,tools:[],cost:p.ownCost,apiCost:p.ownApiCost,steps:p.ownSteps})):t.groups).filter(p=>q(p,n)>0),P=T.find(p=>p.key===b),j=y<500?300:P||t.totalSteps>24?340:160;ce(()=>{const p=()=>{r.current&&C(Math.max(240,r.current.clientWidth))};p();const v=typeof ResizeObserver=="function"?new ResizeObserver(p):null;return v?.observe(r.current),()=>v?.disconnect()},[]);const B=p=>{m(v=>v===p.key?"":p.key),u(null)},h=t.hierarchy.find(p=>!p.parentId),R=p=>{const v=x?N==="operation"?t.operationGroups.filter(A=>A.operationKey===p.key):t.hierarchy.find(A=>A.id===p.sessionId)?.operations??[]:[p];return(v.length?v:[p]).map(A=>({...A,value:q(A,n),label:N==="agent"?o(A):A.tools.join(" + ")||o(A),filter:x?N==="agent"?{agent:p.sessionId,operation:A.key}:{operation:p.key,operationGroup:A.operationKey?A.key:""}:{group:p.key}}))},te=p=>p.label+" · "+a(p.value)+(p.unpriced?" + ?":"")+" · "+xe(p.value,E),W=p=>v=>{["Enter"," "].includes(v.key)&&(v.preventDefault(),p())},J=Pe((P?[P]:T).map(p=>({...p,value:q(p,n),label:o(p)})),0,0,y,j).map(p=>{const v=p.x+1,A=p.y+1,D=Math.max(0,p.width-2),L=Math.max(0,p.height-2),Z=c.get(ke(p)),Q=L>40&&D>90?27:0,le=Pe(R(p),v+1,A+Q+1,Math.max(0,D-2),Math.max(0,L-Q-2));return e("g",{key:p.key,className:"cm-fee-category","data-fee-group":p.key},e("rect",{x:v,y:A,width:D,height:L,rx:6,fill:`color-mix(in srgb, ${Z} 17%, var(--cm-bg))`}),...le.map((H,ne)=>{const ee=H.x+.6,oe=H.y+.6,$=Math.max(0,H.width-1.2),pe=Math.max(0,H.height-1.2),w=$>58&&pe>30,se=pe>56,be=()=>d(H.filter,p.label+" · "+H.label);return e("g",{key:H.key,className:"cm-fee-tile",role:"button",tabIndex:0,"data-fee-operation":H.key,"aria-label":te(H),onMouseEnter:()=>u(H),onFocus:()=>u(H),onBlur:()=>u(null),onClick:be,onKeyDown:W(be)},e("title",null,te(H)),e("rect",{x:ee,y:oe,width:$,height:pe,rx:2,fill:`color-mix(in srgb, ${N==="agent"&&c.get(ke(H))||Z} ${60+ne%5*6}%, var(--cm-bg))`,stroke:"var(--cm-bg)",strokeWidth:.5}),w?e("foreignObject",{x:ee+7,y:oe+5,width:Math.max(0,$-14),height:Math.max(0,pe-10),pointerEvents:"none"},e("div",{className:"cm-fee-call-caption"},e("b",null,H.label),se?e("span",null,a(H.value)+(H.unpriced?" + ?":"")):null,pe>85?e("small",null,xe(H.value,E)):null)):null)}),Q?e("g",{className:"cm-fee-category-head",role:"button",tabIndex:0,"aria-label":p.label,"aria-pressed":P?.key===p.key,onClick:()=>B(p),onKeyDown:W(()=>B(p)),onMouseEnter:()=>u(p),onFocus:()=>u(p),onBlur:()=>u(null)},e("title",null,te(p)),e("rect",{x:v,y:A,width:D,height:Q,fill:"transparent",rx:6}),e("foreignObject",{x:v+7,y:A+3,width:Math.max(0,D-14),height:Q-6,pointerEvents:"none"},e("div",{className:"cm-fee-category-caption"},e("b",null,p.label),D>150?e("span",null,xe(p.value,E)):null))):null)});return e("div",{className:"cm-fee-map",ref:r},e("div",{className:"cm-fee-map-summary"},e("nav",{className:"cm-fee-breadcrumb","aria-label":i("费用归属路径","Cost ownership path")},ae(h?l(h.id):i("全部费用","All costs"),()=>{m(""),u(null)}),P?e(me,null,e("span",null,"›"),e("b",null,o(P))):null),x?e("div",{className:"cm-fee-grouping",role:"group","aria-label":i("分类方式","Grouping")},...[["operation",i("按用途","By activity")],["agent",i("按代理","By agent")]].map(([p,v])=>ae(v,()=>{z(p),m(""),u(null)},{key:p,"aria-pressed":N===p}))):null,e("span",{className:"cm-fee-map-total"},a(P?q(P,n):E))),e("div",{className:"cm-fee-map-meter","aria-hidden":!0},...T.map(p=>e("i",{key:p.key,style:{width:q(p,n)/E*100+"%",background:c.get(ke(p))}}))),T.length?e("svg",{viewBox:`0 0 ${y} ${j}`,style:{height:j},"aria-label":i("矩形费用分布","Cost treemap"),onMouseLeave:()=>u(null)},...J):e("p",{className:"cm-stat-sub"},i("没有已定价费用","No priced cost")),e("div",{className:"cm-fee-map-legend"},...(P?[P]:T).map(p=>e("button",{key:p.key,type:"button",title:te({...p,label:o(p),value:q(p,n)}),onClick:()=>B(p)},e("i",{className:"cm-plan-dot",style:{background:c.get(ke(p))}}),e("span",null,o(p)),e("small",null,xe(q(p,n),E))))),e("div",{className:"cm-fee-map-status",role:"status"},g?te(g):""))}function oa({value:t,basis:n,colors:c,actorName:l,groupName:o,money:a,text:i,onSelect:d}){const[r,y]=M([]),C=t.hierarchy.find(u=>!u.parentId),b=q(t,n),m=[],g=(u,N,z)=>{if(m.push({...u,key:"agent:"+u.id,label:l(u.id),color:c.get("agent:"+u.id),depth:N,parentTotal:z,actor:!0,filter:{agent:u.parentId?u.id:"",group:""}}),u!==C&&!r.includes(u.id))return;const E=[...(u.operations?.length?u.operations:u.groups).map(x=>({...x,key:u.id+":"+x.key,label:o(x),color:c.get(ke(x)),filter:{agent:u.id,...u.operations?.length?{operation:x.key}:{group:x.key}}})),...t.hierarchy.filter(x=>x.parentId===u.id).map(x=>({...x,actor:!0}))].sort((x,T)=>q(T,n)-q(x,n)||String(x.key??x.id).localeCompare(String(T.key??T.id)));for(const x of E)x.actor?g(x,N+1,q(u,n)):m.push({...x,depth:N+1,parentTotal:q(u,n)})};return C&&g(C,0,b),e("div",{className:"cm-stat-scroll cm-fee-tree"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[i("费用归属","Cost ownership"),i("步数","Steps"),i("调用","Calls"),i("费用","Cost"),i("占对话","Of conversation"),i("占父级","Of parent")].map((u,N)=>e("th",{key:u,className:N===5?"cm-fee-parent":""},u)))),e("tbody",null,...m.map(u=>e("tr",{key:u.key,"data-fee-agent":u.actor?u.id:void 0},e("td",null,e("div",{className:"cm-fee-tree-name",style:{paddingLeft:Math.min(u.depth,8)*18}},u.actor?e("button",{type:"button",className:"cm-fee-tree-toggle","aria-label":u.label,"aria-expanded":u.id===C.id||r.includes(u.id),disabled:u.id===C.id,onClick:()=>y(N=>N.includes(u.id)?N.filter(z=>z!==u.id):[...N,u.id])},u.id===C.id||r.includes(u.id)?"⌄":"›"):e("span",{className:"cm-fee-tree-toggle"}),e("i",{className:"cm-plan-dot",style:{background:u.color}}),e("button",{type:"button",className:"cm-fee-link",title:u.label,onClick:()=>d(u.filter,u.label)},u.label))),e("td",null,u.steps.toLocaleString()),e("td",null,u.calls.toLocaleString()),e("td",null,a(q(u,n))+(u.unpriced?" + ?":"")),e("td",null,xe(q(u,n),b)),e("td",{className:"cm-fee-parent"},xe(q(u,n),u.parentTotal)))))))}function Dt({title:t,text:n,onClose:c,children:l}){const o=ge(null),a=ge(document.activeElement);return ce(()=>{const i=o.current;return i&&!i.open&&i.showModal(),()=>{i?.close(),a.current?.isConnected&&a.current.focus({preventScroll:!0})}},[]),e("dialog",{ref:o,className:"cm-fee-dialog","aria-label":n("费用详细信息","Fee details"),onCancel:i=>{i.preventDefault(),i.stopPropagation(),c()},onClick:i=>{if(i.stopPropagation(),i.target!==i.currentTarget)return;const d=i.currentTarget.getBoundingClientRect();(i.clientX<d.left||i.clientX>d.right||i.clientY<d.top||i.clientY>d.bottom)&&c()}},e("style",null,`
60
+ `),e("section",{className:"cm-plan cm-call-bill","aria-label":a("本次计费明细","Call billing breakdown")},e("div",{className:"cm-stat-panel-head"},e("h3",null,t.plan?a("Plan 等值费用","Plan equivalent"):a("API 费用","API cost")),e("strong",{className:"cm-stat-value"},t.priced?o(t.cost):"?")),e("p",{className:"cm-stat-sub"},t.provider+" / "+t.model+" · "+new Date(t.atMs).toLocaleString()),t.metering?e("p",{className:"cm-stat-note"},"billion-context · "+t.metering.upstream+(t.metering.attempt>1?a(" · 重试 "," · Retry ")+t.metering.attempt:"")+(t.metering.complete?"":a(" · 仅含已收到的用量,未知费用未估补"," · observed usage only; unknown charges are not inferred"))):null,d?null:e(Oe,{rows:b,total:t.cost,label:a("本次费用构成","This call’s costs"),text:a,amounts:!0,onSelect:m=>y(["output","reasoning"].includes(m.key)?"output":"input")}),e("div",{className:"cm-stat-scroll cm-step-rates"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[a("计费项目","Component"),a("用量","Usage"),C.some(m=>m.requests)?a("单价 / 次","Rate / request"):a("单价 / 百万","Rate / 1M"),a("金额","Cost"),a("占比","Share")].map(m=>e("th",{key:m},m)))),e("tbody",null,...C.map(m=>{const g=m.bucket==="reasoning"&&m.priced&&m.rate===0;return e("tr",{key:m.bucket},e("td",null,i[m.bucket]??Me(a)[m.bucket]),e("td",null,m.requests?m.requests+a(" 次"," requests"):m.tokens.toLocaleString()+" tokens"),e("td",null,m.priced?o(m.rate)+(m.requests?a(" / 次"," / request"):" / 1M"):"?"),e("td",null,g?a("未单独计费","No separate charge"):m.priced?o(m.cost):"?"),e("td",null,m.priced&&!g?ue(m.cost,t.cost):"—"))}))))),t.logSeq!=null?e(ta,{api:c,sessionId:t.sessionId||n,seq:t.logSeq,atMs:t.atMs,revision:l,text:a,view:r,onViewChange:y}):e("p",{className:"cm-stat-sub"},a("未保存调用内容","Call content not stored")))}const pt=t=>({read:t("读取文件","Read files"),"local-search":t("本地检索","Local search"),write:t("文件修改","File changes"),command:t("命令执行","Commands"),tool:t("其他工具","Other tools"),model:t("模型回复","Model responses"),search:t("网页搜索","Web search"),fetch:t("网页抓取","Web fetch"),compaction:t("上下文压缩","Compaction"),coordination:t("代理协作","Agent coordination"),"multi-tool":t("多类工具","Mixed tools"),"other-tools":t("其他工具调用","Other tools"),other:t("其他调用","Other calls")}),aa=t=>t.replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,""),xe=(t,n)=>t>0&&n>0&&t/n<.001?"<0.1%":ue(t,n),ke=t=>t.kind==="subagent"?"agent:"+t.sessionId:"type:"+t.kind+":"+t.tools.join("|");function na(t){const n=new Set([...t.groups,...t.operations??[]].map(ke));for(const a of t.hierarchy){n.add("agent:"+a.id);for(const i of a.groups)n.add(ke(i))}const c=["#627bff","#f6b64b","#30c89c","#ad78f5","#fb8c6f","#42b4f5","#24bdc9","#e576a8","#9abd3a","#9c83d9","#c28b4c","#368fc7"],l=new Map,o=new Set;for(const a of[...n].sort()){if(a.startsWith("type:other-tools:")){l.set(a,"#a0aec5");continue}let i=2166136261;for(const y of a)i=Math.imul(i^y.charCodeAt(0),16777619)>>>0;let d=c[i%c.length],r=0;for(;o.has(d)&&r<c.length;)d=c[(i+ ++r)%c.length];o.has(d)&&(d=`hsl(${(i%36e3/100).toFixed(2)} 68% ${56+i%6}%)`),l.set(a,d),o.add(d)}return l}function Pe(t,n,c,l,o){const a=t.filter(C=>C.value>0).sort((C,b)=>b.value-C.value||C.key.localeCompare(b.key));if(!a.length||l<=0||o<=0)return[];if(a.length===1)return[{...a[0],x:n,y:c,width:l,height:o}];const i=a.reduce((C,b)=>C+b.value,0);let d=1,r=a[0].value;for(;d<a.length-1&&Math.abs(r+a[d].value-i/2)<Math.abs(r-i/2);)r+=a[d++].value;const y=r/i;return l>=o?[...Pe(a.slice(0,d),n,c,l*y,o),...Pe(a.slice(d),n+l*y,c,l*(1-y),o)]:[...Pe(a.slice(0,d),n,c,l,o*y),...Pe(a.slice(d),n,c+o*y,l,o*(1-y))]}function sa({value:t,basis:n,colors:c,actorName:l,groupName:o,money:a,text:i,onSelect:d}){const r=ge(null),[y,C]=M(720),[b,m]=M(""),[g,u]=M(null),[N,z]=M("operation"),E=q(t,n),x=t.operations?.length>0,T=(x?N==="operation"?t.operations:t.hierarchy.map(p=>({...p,key:p.id,kind:"subagent",sessionId:p.id,tools:[],cost:p.ownCost,apiCost:p.ownApiCost,steps:p.ownSteps})):t.groups).filter(p=>q(p,n)>0),P=T.find(p=>p.key===b),j=y<500?300:P||t.totalSteps>24?340:160;ce(()=>{const p=()=>{r.current&&C(Math.max(240,r.current.clientWidth))};p();const v=typeof ResizeObserver=="function"?new ResizeObserver(p):null;return v?.observe(r.current),()=>v?.disconnect()},[]);const B=p=>{m(v=>v===p.key?"":p.key),u(null)},h=t.hierarchy.find(p=>!p.parentId),R=p=>{const v=x?N==="operation"?t.operationGroups.filter(A=>A.operationKey===p.key):t.hierarchy.find(A=>A.id===p.sessionId)?.operations??[]:[p];return(v.length?v:[p]).map(A=>({...A,value:q(A,n),label:N==="agent"?o(A):A.tools.join(" + ")||o(A),filter:x?N==="agent"?{agent:p.sessionId,operation:A.key}:{operation:p.key,operationGroup:A.operationKey?A.key:""}:{group:p.key}}))},te=p=>p.label+" · "+a(p.value)+(p.unpriced?" + ?":"")+" · "+xe(p.value,E),W=p=>v=>{["Enter"," "].includes(v.key)&&(v.preventDefault(),p())},J=Pe((P?[P]:T).map(p=>({...p,value:q(p,n),label:o(p)})),0,0,y,j).map(p=>{const v=p.x+1,A=p.y+1,D=Math.max(0,p.width-2),L=Math.max(0,p.height-2),Z=c.get(ke(p)),Q=L>40&&D>90?27:0,le=Pe(R(p),v+1,A+Q+1,Math.max(0,D-2),Math.max(0,L-Q-2));return e("g",{key:p.key,className:"cm-fee-category","data-fee-group":p.key},e("rect",{x:v,y:A,width:D,height:L,rx:6,fill:`color-mix(in srgb, ${Z} 17%, var(--cm-bg))`}),...le.map(($,ne)=>{const ee=$.x+.6,oe=$.y+.6,_=Math.max(0,$.width-1.2),pe=Math.max(0,$.height-1.2),w=_>58&&pe>30,se=pe>56,be=()=>d($.filter,p.label+" · "+$.label);return e("g",{key:$.key,className:"cm-fee-tile",role:"button",tabIndex:0,"data-fee-operation":$.key,"aria-label":te($),onMouseEnter:()=>u($),onFocus:()=>u($),onBlur:()=>u(null),onClick:be,onKeyDown:W(be)},e("title",null,te($)),e("rect",{x:ee,y:oe,width:_,height:pe,rx:2,fill:`color-mix(in srgb, ${N==="agent"&&c.get(ke($))||Z} ${60+ne%5*6}%, var(--cm-bg))`,stroke:"var(--cm-bg)",strokeWidth:.5}),w?e("foreignObject",{x:ee+7,y:oe+5,width:Math.max(0,_-14),height:Math.max(0,pe-10),pointerEvents:"none"},e("div",{className:"cm-fee-call-caption"},e("b",null,$.label),se?e("span",null,a($.value)+($.unpriced?" + ?":"")):null,pe>85?e("small",null,xe($.value,E)):null)):null)}),Q?e("g",{className:"cm-fee-category-head",role:"button",tabIndex:0,"aria-label":p.label,"aria-pressed":P?.key===p.key,onClick:()=>B(p),onKeyDown:W(()=>B(p)),onMouseEnter:()=>u(p),onFocus:()=>u(p),onBlur:()=>u(null)},e("title",null,te(p)),e("rect",{x:v,y:A,width:D,height:Q,fill:"transparent",rx:6}),e("foreignObject",{x:v+7,y:A+3,width:Math.max(0,D-14),height:Q-6,pointerEvents:"none"},e("div",{className:"cm-fee-category-caption"},e("b",null,p.label),D>150?e("span",null,xe(p.value,E)):null))):null)});return e("div",{className:"cm-fee-map",ref:r},e("div",{className:"cm-fee-map-summary"},e("nav",{className:"cm-fee-breadcrumb","aria-label":i("费用归属路径","Cost ownership path")},ae(h?l(h.id):i("全部费用","All costs"),()=>{m(""),u(null)}),P?e(me,null,e("span",null,"›"),e("b",null,o(P))):null),x?e("div",{className:"cm-fee-grouping",role:"group","aria-label":i("分类方式","Grouping")},...[["operation",i("按用途","By activity")],["agent",i("按代理","By agent")]].map(([p,v])=>ae(v,()=>{z(p),m(""),u(null)},{key:p,"aria-pressed":N===p}))):null,e("span",{className:"cm-fee-map-total"},a(P?q(P,n):E))),e("div",{className:"cm-fee-map-meter","aria-hidden":!0},...T.map(p=>e("i",{key:p.key,style:{width:q(p,n)/E*100+"%",background:c.get(ke(p))}}))),T.length?e("svg",{viewBox:`0 0 ${y} ${j}`,style:{height:j},"aria-label":i("矩形费用分布","Cost treemap"),onMouseLeave:()=>u(null)},...J):e("p",{className:"cm-stat-sub"},i("没有已定价费用","No priced cost")),e("div",{className:"cm-fee-map-legend"},...(P?[P]:T).map(p=>e("button",{key:p.key,type:"button",title:te({...p,label:o(p),value:q(p,n)}),onClick:()=>B(p)},e("i",{className:"cm-plan-dot",style:{background:c.get(ke(p))}}),e("span",null,o(p)),e("small",null,xe(q(p,n),E))))),e("div",{className:"cm-fee-map-status",role:"status"},g?te(g):""))}function oa({value:t,basis:n,colors:c,actorName:l,groupName:o,money:a,text:i,onSelect:d}){const[r,y]=M([]),C=t.hierarchy.find(u=>!u.parentId),b=q(t,n),m=[],g=(u,N,z)=>{if(m.push({...u,key:"agent:"+u.id,label:l(u.id),color:c.get("agent:"+u.id),depth:N,parentTotal:z,actor:!0,filter:{agent:u.parentId?u.id:"",group:""}}),u!==C&&!r.includes(u.id))return;const E=[...(u.operations?.length?u.operations:u.groups).map(x=>({...x,key:u.id+":"+x.key,label:o(x),color:c.get(ke(x)),filter:{agent:u.id,...u.operations?.length?{operation:x.key}:{group:x.key}}})),...t.hierarchy.filter(x=>x.parentId===u.id).map(x=>({...x,actor:!0}))].sort((x,T)=>q(T,n)-q(x,n)||String(x.key??x.id).localeCompare(String(T.key??T.id)));for(const x of E)x.actor?g(x,N+1,q(u,n)):m.push({...x,depth:N+1,parentTotal:q(u,n)})};return C&&g(C,0,b),e("div",{className:"cm-stat-scroll cm-fee-tree"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[i("费用归属","Cost ownership"),i("步数","Steps"),i("调用","Calls"),i("费用","Cost"),i("占对话","Of conversation"),i("占父级","Of parent")].map((u,N)=>e("th",{key:u,className:N===5?"cm-fee-parent":""},u)))),e("tbody",null,...m.map(u=>e("tr",{key:u.key,"data-fee-agent":u.actor?u.id:void 0},e("td",null,e("div",{className:"cm-fee-tree-name",style:{paddingLeft:Math.min(u.depth,8)*18}},u.actor?e("button",{type:"button",className:"cm-fee-tree-toggle","aria-label":u.label,"aria-expanded":u.id===C.id||r.includes(u.id),disabled:u.id===C.id,onClick:()=>y(N=>N.includes(u.id)?N.filter(z=>z!==u.id):[...N,u.id])},u.id===C.id||r.includes(u.id)?"⌄":"›"):e("span",{className:"cm-fee-tree-toggle"}),e("i",{className:"cm-plan-dot",style:{background:u.color}}),e("button",{type:"button",className:"cm-fee-link",title:u.label,onClick:()=>d(u.filter,u.label)},u.label))),e("td",null,u.steps.toLocaleString()),e("td",null,u.calls.toLocaleString()),e("td",null,a(q(u,n))+(u.unpriced?" + ?":"")),e("td",null,xe(q(u,n),b)),e("td",{className:"cm-fee-parent"},xe(q(u,n),u.parentTotal)))))))}function Dt({title:t,text:n,onClose:c,children:l}){const o=ge(null),a=ge(document.activeElement);return ce(()=>{const i=o.current;return i&&!i.open&&i.showModal(),()=>{i?.close(),a.current?.isConnected&&a.current.focus({preventScroll:!0})}},[]),e("dialog",{ref:o,className:"cm-fee-dialog","aria-label":n("费用详细信息","Fee details"),onCancel:i=>{i.preventDefault(),i.stopPropagation(),c()},onClick:i=>{if(i.stopPropagation(),i.target!==i.currentTarget)return;const d=i.currentTarget.getBoundingClientRect();(i.clientX<d.left||i.clientX>d.right||i.clientY<d.top||i.clientY>d.bottom)&&c()}},e("style",null,`
60
61
  dialog.cm-fee-dialog{padding:0;border:1px solid var(--cm-border);border-radius:14px;background:var(--cm-opaque-base,#fff);background:rgb(from var(--dsw-alias-bg-layer-2,var(--cm-bg)) r g b / 1);color:var(--cm-label);width:min(1080px,calc(100vw - 32px));max-width:none;max-height:calc(100dvh - 96px);margin:auto;box-shadow:0 18px 70px #0003;overflow:hidden;font:13px/1.5 var(--ds-font-family-sans,system-ui);container-type:inline-size}
61
62
  dialog.cm-fee-dialog[open]{display:flex;flex-direction:column}dialog.cm-fee-dialog::backdrop{background:#0005}
62
63
  .cm-fee-dialog-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:15px 20px;border-bottom:1px solid var(--cm-border);flex:none}.cm-fee-dialog-head h3{font-size:15px;font-weight:600;margin:0;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-fee-dialog-head .cm-stat-btn{padding:0;width:30px;height:30px;border:0;font-size:23px;line-height:1;background:transparent;color:var(--cm-muted);flex:none}.cm-fee-dialog-head .cm-stat-btn:hover{background:var(--cm-surface);color:var(--cm-label)}
63
64
  .cm-fee-dialog-body{padding:18px 20px;overflow:auto;overscroll-behavior:contain;min-height:0}.cm-fee-popup-columns{display:grid;grid-template-columns:250px minmax(0,1fr);gap:20px;align-items:start}.cm-fee-popup-list{max-height:65vh;overflow:auto;overscroll-behavior:contain;padding-right:8px;border-right:1px solid var(--cm-border)}.cm-fee-popup-list-head{display:flex;justify-content:space-between;font-size:11px;color:var(--cm-muted);margin:0 6px 8px}.cm-fee-popup-detail{min-width:0}.cm-fee-dialog .cm-fee-popup-step{display:block;width:100%;padding:9px 10px;margin:2px 0;text-align:left;border:0;border-radius:7px;background:transparent;color:var(--cm-label);font:inherit;cursor:pointer}.cm-fee-popup-step>span{display:flex;justify-content:space-between;gap:8px;font-size:12px}.cm-fee-popup-step b{font-weight:500;white-space:nowrap;font-variant-numeric:tabular-nums}.cm-fee-popup-step small{display:block;margin-top:3px;font-size:11px;color:var(--cm-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-fee-dialog .cm-fee-popup-step:hover{background:var(--cm-surface)}.cm-fee-dialog .cm-fee-popup-step[aria-pressed=true]{background:color-mix(in srgb,var(--cm-accent) 10%,var(--cm-bg));box-shadow:inset 2px 0 var(--cm-accent)}.cm-fee-popup-call-select{display:flex;align-items:center;gap:8px;margin-bottom:12px}.cm-fee-popup-call-select select{min-width:0;max-width:100%;padding:5px 8px;border:1px solid var(--cm-border);border-radius:7px;background:var(--cm-bg);color:var(--cm-label)}
64
65
  @container(max-width:700px){.cm-fee-popup-columns{grid-template-columns:1fr;gap:14px}.cm-fee-popup-list{max-height:160px;border-right:0;border-bottom:1px solid var(--cm-border);padding:0 0 8px}.cm-fee-dialog-body{padding:12px}.cm-fee-dialog-head{padding:12px}.cm-fee-dialog .cm-call-tool-parts{grid-template-columns:1fr}}
65
- `),e("header",{className:"cm-fee-dialog-head"},e("h3",{title:t},t),ae("×",c,{"aria-label":n("关闭详细信息","Close fee details")})),e("div",{className:"cm-fee-dialog-body"},l))}function Kt({api:t,sessionId:n,basis:c,revision:l,row:o,money:a,text:i}){const[d,r]=M(0),[y,C]=M(0),b=Te(t,"getSessionTrajectory",{sessionId:n,basis:c,stepKey:o.key,background:!0,generation:String(l).slice(0,96)},l+":"+y),m=b.value?.steps.find(z=>z.key===o.key),g={input:i("非缓存输入","Uncached input"),output:i("输出","Output"),cacheRead:i("缓存读取","Cache read"),cacheWrite:i("缓存写入","Cache write"),reasoning:i("推理","Reasoning"),...Me(i)},u=(m?.callRefs??[]).filter(z=>c==="total"||(c==="plan"?z.plan:!z.plan)),N=u[d]??u[0];return e("section",{className:"cm-fee-popup-detail","aria-label":i("选中步骤费用","Selected step cost")},b.error?e(me,null,ye(b.error),ae(i("重试","Retry"),()=>C(z=>z+1))):null,m?e(me,null,u.length>1?e("label",{className:"cm-fee-popup-call-select"},i("本步骤调用","Calls in this step"),e("select",{value:d,onChange:z=>r(Number(z.target.value))},...u.map((z,E)=>e("option",{key:E,value:E},"#"+(E+1)+" · "+z.model+" · "+a(z.cost))))):null,N?e(it,{key:[N.sessionId,N.logSeq,N.atMs].join(":"),call:N,sessionId:o.sessionId||n,api:t,revision:l,money:a,text:i,names:g,compact:!0}):e("p",{className:"cm-stat-sub"},i("未保存调用内容","Call content not stored"))):b.error?null:e("span",{className:"cm-stat-sub",role:"status"},b.loading||b.value?.refreshing?i("读取调用明细…","Loading call details…"):i("未找到该步骤的调用记录","Call records for this step are unavailable")))}function la({api:t,sessionId:n,basis:c,revision:l,selection:o,actorName:a,money:i,text:d}){const[r,y]=M(0),[C,b]=M(40),[m,g]=M([]),[u,N]=M(""),[z,E]=M(0),x=Te(t,"getSessionTrajectory",{sessionId:n,basis:c,...o,offset:r,order:"cost",detail:"map",background:!0,generation:String(l).slice(0,96)},l+":"+z);ce(()=>{y(0),b(40),g([])},[l]),ce(()=>{x.value?.offset===r&&g(h=>r===0?x.value.steps:[...new Map([...h,...x.value.steps].map(R=>[R.key,R])).values()])},[x.value,r]);const T=m.length?m:x.value?.steps??[],P=T.find(h=>h.key===u)??T[0],j=pt(d),B=h=>h.turn==null?j[h.kind]||h.kind:d("轮次 ","Turn ")+h.turn+(h.step==null?"":d(" · 步骤 "," · step ")+h.step);return e("div",{className:"cm-fee-popup-columns"},e("div",{className:"cm-fee-popup-list"},e("div",{className:"cm-fee-popup-list-head"},e("span",null,d("金额从高到低","Highest cost first")),e("span",null,(x.value?.matchingSteps??T.length).toLocaleString()+d(" 步"," steps"))),x.error?e(me,null,ye(x.error),ae(d("重试","Retry"),()=>E(h=>h+1))):null,!T.length&&x.loading?e("p",{role:"status"},d("读取调用列表…","Loading calls…")):null,...T.slice(0,C).map(h=>e("button",{type:"button",key:h.key,className:"cm-fee-popup-step","aria-pressed":P?.key===h.key,onClick:()=>N(h.key)},e("span",null,B(h),e("b",null,i(q(h,c))+(h.unpriced?" + ?":""))),e("small",{title:a(h.sessionId)+" · "+h.tools.join(" + ")},a(h.sessionId)+" · "+(h.tools.join(" + ")||j[h.kind]||h.kind)))),C<(x.value?.matchingSteps??0)?ae(d("展开更多","Show more"),()=>{b(h=>h+40),C>=T.length&&y(T.length)},{disabled:x.loading}):null),P?e(Kt,{key:P.key,api:t,sessionId:n,basis:c,revision:l,row:P,money:i,text:d}):!x.loading&&!x.error?e("p",{className:"cm-stat-sub"},d("没有可用的调用","No available calls")):null)}function ca({api:t,sessionId:n,revision:c,row:l,money:o,text:a,names:i,onClose:d}){const r=l.call;return e(Dt,{title:a("调用 #","Call #")+(l.index+1),text:a,onClose:d},r?e(it,{key:[r.sessionId,r.logSeq,r.atMs].join(":"),call:r,sessionId:n,api:t,revision:c,money:o,text:a,names:i,compact:!0}):e("p",{className:"cm-stat-sub"},a("该调用的详细记录尚未载入,请刷新费用页面。","Refresh the cost view to load this call’s details.")))}function ra({api:t,sessionId:n,basis:c,revision:l,value:o,colors:a,actorName:i,money:d,text:r,onInspect:y}){const[C,b]=M("time"),[m,g]=M(""),[u,N]=M(""),[z,E]=M(0),[x,T]=M(720),[P,j]=M(0),[B,h]=M(null),[R,te]=M({}),[W,F]=M(""),[J,p]=M(o.totalSteps),[v,A]=M(""),D=ge(null),L=ge(null),Z=String(l).slice(0,96),Q=JSON.stringify([n,c,l,C,m,u,z]),le=ge(Q),H=ge(new Map),ne=Math.max(8,Math.floor((x-16)/20)),ee=(x-16)/ne,oe=244,$=Math.max(0,Math.floor(P/ee)-2)*ne,pe=Math.min(J,(Math.ceil((P+oe)/ee)+2)*ne),w=Math.floor($/400)*400,se=Math.floor(Math.max($,pe-1)/400)*400;ce(()=>{const I=()=>{D.current&&T(Math.max(190,D.current.clientWidth))};I();const K=typeof ResizeObserver=="function"?new ResizeObserver(I):null;return D.current&&K?.observe(D.current),()=>K?.disconnect()},[]),ce(()=>{le.current=Q,H.current=new Map,te({}),j(0),h(null),F(""),p(o.totalSteps),D.current&&(D.current.scrollTop=0)},[Q]),ce(()=>{let I=!0,K;const de=async f=>{try{await Promise.all(Array.from({length:(se-w)/400+1},(V,ie)=>w+ie*400).map(async V=>{if(!f&&H.current.has(V))return;const ie=await Re(t,"getSessionTrajectory",{sessionId:n,basis:c,order:C,operation:m,agent:u,ownOnly:!0,detail:"map",offset:V,background:!0,generation:Z},l+":grid:"+z,f);if(!(!I||le.current!==Q)){for(H.current.set(V,ie.steps);H.current.size>6;){const ve=[...H.current.keys()].sort((Se,ze)=>Math.abs(ze-w)-Math.abs(Se-w))[0];H.current.delete(ve)}te(Object.fromEntries(H.current)),p(ie.matchingSteps),F(""),ie.refreshing&&!K&&(K=setTimeout(()=>{K=null,de(!0)},900))}}))}catch(V){I&&F(String(V?.message??V))}};return de(!1),()=>{I=!1,clearTimeout(K)}},[t,Q,w,se]);const be=I=>{const K=Math.max(0,Math.min(J-1,I)),de=Math.floor(K/ne)*ee;if(D.current){L.current=K,D.current.scrollTop=de,j(D.current.scrollTop);const f=D.current.querySelector('[data-grid-index="'+K+'"]');f&&!f.disabled&&(f.focus({preventScroll:!0}),L.current=null)}};ce(()=>{if(L.current==null)return;const I=D.current?.querySelector('[data-grid-index="'+L.current+'"]');I&&!I.disabled&&(I.focus({preventScroll:!0}),L.current=null)},[R,P]);const he=pt(r),Ce=Math.max(...o.shares.filter(I=>!I.other).map(I=>q(I,c)),0),re=I=>i(I.sessionId)+" · "+(I.turn==null?he[I.kind]||I.kind:r("轮次 ","Turn ")+I.turn+(I.step==null?"":r(" · 步骤 "," · step ")+I.step))+" · "+(I.tools.join(" + ")||he[I.operationKey]||he[I.kind]||I.kind),Ne=[];for(let I=$;I<pe;I++){const K=le.current===Q?R[Math.floor(I/400)*400]?.[I%400]:null,de=K?q(K,c):0,f=K?a.get(ke(o.operations?.find(ve=>ve.key===K.operationKey)??{kind:K.kind,tools:[]}))||"#627bff":"var(--cm-border)",V=de>0&&Ce>0?30+70*Math.sqrt(Math.min(1,de/Ce)):0,ie=K?re(K)+" · "+d(de)+(K.unpriced?" + ?":"")+" · "+xe(de,q(o,c)):r("读取中","Loading");Ne.push(e("button",{key:I,type:"button",className:"cm-step-cell",disabled:!K,"data-grid-index":I,"data-grid-step":K?.key,"aria-label":ie,title:ie,"aria-haspopup":"dialog","data-unpriced":K?.unpriced||void 0,style:{position:"absolute",left:8+I%ne*ee,top:Math.floor(I/ne)*ee,width:ee-3,height:ee-3,background:K?`color-mix(in srgb, ${f} ${V}%, var(--cm-bg))`:"var(--cm-surface)",borderColor:K&&!de?f:"transparent"},onMouseEnter:()=>K&&h({...K,label:re(K)}),onFocus:()=>K&&h({...K,label:re(K)}),onBlur:()=>h(null),onClick:()=>K&&y({...K,label:re(K)}),onKeyDown:ve=>{const Se={ArrowLeft:-1,ArrowRight:1,ArrowUp:-ne,ArrowDown:ne}[ve.key];if(!Se)return;ve.preventDefault();const ze=Math.max(0,Math.min(J-1,I+Se)),s=D.current?.querySelector('[data-grid-index="'+ze+'"]');s&&!s.disabled?s.focus():be(ze)}}))}return e("div",{className:"cm-step-grid"},e("div",{className:"cm-grid-controls"},e("select",{value:m,onChange:I=>g(I.target.value),"aria-label":r("步骤类别","Step category")},e("option",{value:""},r("全部用途","All activities")),...(o.operations??[]).map(I=>e("option",{key:I.key,value:I.key},he[I.kind]||I.kind))),e("select",{value:u,onChange:I=>N(I.target.value),"aria-label":r("步骤代理","Step agent")},e("option",{value:""},r("全部代理","All agents")),...o.hierarchy.map(I=>e("option",{key:I.id,value:I.id},i(I.id)))),e("select",{value:C,onChange:I=>b(I.target.value),"aria-label":r("热力图排序","Grid order")},e("option",{value:"time"},r("轨迹顺序","Trajectory order")),e("option",{value:"cost"},r("金额从高到低","Highest cost first"))),e("form",{onSubmit:I=>{I.preventDefault(),Number.isSafeInteger(Number(v))&&Number(v)>0&&be(Number(v)-1)}},e("input",{type:"number",min:1,max:Math.max(1,J),value:v,onChange:I=>A(I.target.value),placeholder:r("序号","Index"),"aria-label":r("定位步骤序号","Locate step index")}),ae(r("定位","Go"),void 0,{type:"submit"}))),e("div",{className:"cm-grid-caption"},e("span",null,r("每格一步 · 颜色区分类别,深浅表示费用","One cell per step · hue = activity, shade = cost")),e("span",null,J.toLocaleString()+r(" 步"," steps"))),W?e("div",null,ye(W),ae(r("重试","Retry"),()=>E(I=>I+1))):null,e("div",{className:"cm-grid-viewport",ref:D,style:{height:Math.min(oe,Math.max(60,Math.ceil(J/ne)*ee))},onScroll:I=>j(I.currentTarget.scrollTop),onMouseLeave:()=>h(null),role:"group","aria-label":r("逐步费用热力图","Step cost heatmap")},e("div",{style:{position:"relative",height:Math.ceil(J/ne)*ee,minHeight:60}},...Ne),J===0?e("p",{className:"cm-stat-empty"},r("没有符合条件的步骤","No matching steps")):null),e("div",{className:"cm-fee-map-status",role:"status"},B?B.label+" · "+d(q(B,c))+(B.unpriced?" + ?":""):""),e("div",{className:"cm-fee-map-legend"},...(o.operations??[]).map(I=>e("button",{key:I.key,type:"button","aria-pressed":m===I.key,onClick:()=>g(K=>K===I.key?"":I.key)},e("i",{className:"cm-plan-dot",style:{background:a.get(ke(I))}}),he[I.kind]||I.kind))))}const Ft=`
66
+ `),e("header",{className:"cm-fee-dialog-head"},e("h3",{title:t},t),ae("×",c,{"aria-label":n("关闭详细信息","Close fee details")})),e("div",{className:"cm-fee-dialog-body"},l))}function Kt({api:t,sessionId:n,basis:c,revision:l,row:o,money:a,text:i}){const[d,r]=M(0),[y,C]=M(0),b=Te(t,"getSessionTrajectory",{sessionId:n,basis:c,stepKey:o.key,background:!0,generation:String(l).slice(0,96)},l+":"+y),m=b.value?.steps.find(z=>z.key===o.key),g={input:i("非缓存输入","Uncached input"),output:i("输出","Output"),cacheRead:i("缓存读取","Cache read"),cacheWrite:i("缓存写入","Cache write"),reasoning:i("推理","Reasoning"),...Me(i)},u=(m?.callRefs??[]).filter(z=>c==="total"||(c==="plan"?z.plan:!z.plan)),N=u[d]??u[0];return e("section",{className:"cm-fee-popup-detail","aria-label":i("选中步骤费用","Selected step cost")},b.error?e(me,null,ye(b.error),ae(i("重试","Retry"),()=>C(z=>z+1))):null,m?e(me,null,u.length>1?e("label",{className:"cm-fee-popup-call-select"},i("本步骤调用","Calls in this step"),e("select",{value:d,onChange:z=>r(Number(z.target.value))},...u.map((z,E)=>e("option",{key:E,value:E},"#"+(E+1)+" · "+z.model+" · "+a(z.cost))))):null,N?e(it,{key:[N.sessionId,N.logSeq,N.atMs].join(":"),call:N,sessionId:o.sessionId||n,api:t,revision:l,money:a,text:i,names:g,compact:!0}):e("p",{className:"cm-stat-sub"},i("未保存调用内容","Call content not stored"))):b.error?null:e("span",{className:"cm-stat-sub",role:"status"},b.loading||b.value?.refreshing?i("读取调用明细…","Loading call details…"):i("未找到该步骤的调用记录","Call records for this step are unavailable")))}function la({api:t,sessionId:n,basis:c,revision:l,selection:o,actorName:a,money:i,text:d}){const[r,y]=M(0),[C,b]=M(40),[m,g]=M([]),[u,N]=M(""),[z,E]=M(0),x=Te(t,"getSessionTrajectory",{sessionId:n,basis:c,...o,offset:r,order:"cost",detail:"map",background:!0,generation:String(l).slice(0,96)},l+":"+z);ce(()=>{y(0),b(40),g([])},[l]),ce(()=>{x.value?.offset===r&&g(h=>r===0?x.value.steps:[...new Map([...h,...x.value.steps].map(R=>[R.key,R])).values()])},[x.value,r]);const T=m.length?m:x.value?.steps??[],P=T.find(h=>h.key===u)??T[0],j=pt(d),B=h=>h.turn==null?j[h.kind]||h.kind:d("轮次 ","Turn ")+h.turn+(h.step==null?"":d(" · 步骤 "," · step ")+h.step);return e("div",{className:"cm-fee-popup-columns"},e("div",{className:"cm-fee-popup-list"},e("div",{className:"cm-fee-popup-list-head"},e("span",null,d("金额从高到低","Highest cost first")),e("span",null,(x.value?.matchingSteps??T.length).toLocaleString()+d(" 步"," steps"))),x.error?e(me,null,ye(x.error),ae(d("重试","Retry"),()=>E(h=>h+1))):null,!T.length&&x.loading?e("p",{role:"status"},d("读取调用列表…","Loading calls…")):null,...T.slice(0,C).map(h=>e("button",{type:"button",key:h.key,className:"cm-fee-popup-step","aria-pressed":P?.key===h.key,onClick:()=>N(h.key)},e("span",null,B(h),e("b",null,i(q(h,c))+(h.unpriced?" + ?":""))),e("small",{title:a(h.sessionId)+" · "+h.tools.join(" + ")},a(h.sessionId)+" · "+(h.tools.join(" + ")||j[h.kind]||h.kind)))),C<(x.value?.matchingSteps??0)?ae(d("展开更多","Show more"),()=>{b(h=>h+40),C>=T.length&&y(T.length)},{disabled:x.loading}):null),P?e(Kt,{key:P.key,api:t,sessionId:n,basis:c,revision:l,row:P,money:i,text:d}):!x.loading&&!x.error?e("p",{className:"cm-stat-sub"},d("没有可用的调用","No available calls")):null)}function ca({api:t,sessionId:n,revision:c,row:l,money:o,text:a,names:i,onClose:d}){const r=l.call;return e(Dt,{title:a("调用 #","Call #")+(l.index+1),text:a,onClose:d},r?e(it,{key:[r.sessionId,r.logSeq,r.atMs].join(":"),call:r,sessionId:n,api:t,revision:c,money:o,text:a,names:i,compact:!0}):e("p",{className:"cm-stat-sub"},a("该调用的详细记录尚未载入,请刷新费用页面。","Refresh the cost view to load this call’s details.")))}function ra({api:t,sessionId:n,basis:c,revision:l,value:o,colors:a,actorName:i,money:d,text:r,onInspect:y}){const[C,b]=M("time"),[m,g]=M(""),[u,N]=M(""),[z,E]=M(0),[x,T]=M(720),[P,j]=M(0),[B,h]=M(null),[R,te]=M({}),[W,F]=M(""),[J,p]=M(o.totalSteps),[v,A]=M(""),D=ge(null),L=ge(null),Z=String(l).slice(0,96),Q=JSON.stringify([n,c,l,C,m,u,z]),le=ge(Q),$=ge(new Map),ne=Math.max(8,Math.floor((x-16)/20)),ee=(x-16)/ne,oe=244,_=Math.max(0,Math.floor(P/ee)-2)*ne,pe=Math.min(J,(Math.ceil((P+oe)/ee)+2)*ne),w=Math.floor(_/400)*400,se=Math.floor(Math.max(_,pe-1)/400)*400;ce(()=>{const I=()=>{D.current&&T(Math.max(190,D.current.clientWidth))};I();const K=typeof ResizeObserver=="function"?new ResizeObserver(I):null;return D.current&&K?.observe(D.current),()=>K?.disconnect()},[]),ce(()=>{le.current=Q,$.current=new Map,te({}),j(0),h(null),F(""),p(o.totalSteps),D.current&&(D.current.scrollTop=0)},[Q]),ce(()=>{let I=!0,K;const de=async f=>{try{await Promise.all(Array.from({length:(se-w)/400+1},(V,ie)=>w+ie*400).map(async V=>{if(!f&&$.current.has(V))return;const ie=await Re(t,"getSessionTrajectory",{sessionId:n,basis:c,order:C,operation:m,agent:u,ownOnly:!0,detail:"map",offset:V,background:!0,generation:Z},l+":grid:"+z,f);if(!(!I||le.current!==Q)){for($.current.set(V,ie.steps);$.current.size>6;){const ve=[...$.current.keys()].sort((Se,ze)=>Math.abs(ze-w)-Math.abs(Se-w))[0];$.current.delete(ve)}te(Object.fromEntries($.current)),p(ie.matchingSteps),F(""),ie.refreshing&&!K&&(K=setTimeout(()=>{K=null,de(!0)},900))}}))}catch(V){I&&F(String(V?.message??V))}};return de(!1),()=>{I=!1,clearTimeout(K)}},[t,Q,w,se]);const be=I=>{const K=Math.max(0,Math.min(J-1,I)),de=Math.floor(K/ne)*ee;if(D.current){L.current=K,D.current.scrollTop=de,j(D.current.scrollTop);const f=D.current.querySelector('[data-grid-index="'+K+'"]');f&&!f.disabled&&(f.focus({preventScroll:!0}),L.current=null)}};ce(()=>{if(L.current==null)return;const I=D.current?.querySelector('[data-grid-index="'+L.current+'"]');I&&!I.disabled&&(I.focus({preventScroll:!0}),L.current=null)},[R,P]);const he=pt(r),Ce=Math.max(...o.shares.filter(I=>!I.other).map(I=>q(I,c)),0),re=I=>i(I.sessionId)+" · "+(I.turn==null?he[I.kind]||I.kind:r("轮次 ","Turn ")+I.turn+(I.step==null?"":r(" · 步骤 "," · step ")+I.step))+" · "+(I.tools.join(" + ")||he[I.operationKey]||he[I.kind]||I.kind),Ne=[];for(let I=_;I<pe;I++){const K=le.current===Q?R[Math.floor(I/400)*400]?.[I%400]:null,de=K?q(K,c):0,f=K?a.get(ke(o.operations?.find(ve=>ve.key===K.operationKey)??{kind:K.kind,tools:[]}))||"#627bff":"var(--cm-border)",V=de>0&&Ce>0?30+70*Math.sqrt(Math.min(1,de/Ce)):0,ie=K?re(K)+" · "+d(de)+(K.unpriced?" + ?":"")+" · "+xe(de,q(o,c)):r("读取中","Loading");Ne.push(e("button",{key:I,type:"button",className:"cm-step-cell",disabled:!K,"data-grid-index":I,"data-grid-step":K?.key,"aria-label":ie,title:ie,"aria-haspopup":"dialog","data-unpriced":K?.unpriced||void 0,style:{position:"absolute",left:8+I%ne*ee,top:Math.floor(I/ne)*ee,width:ee-3,height:ee-3,background:K?`color-mix(in srgb, ${f} ${V}%, var(--cm-bg))`:"var(--cm-surface)",borderColor:K&&!de?f:"transparent"},onMouseEnter:()=>K&&h({...K,label:re(K)}),onFocus:()=>K&&h({...K,label:re(K)}),onBlur:()=>h(null),onClick:()=>K&&y({...K,label:re(K)}),onKeyDown:ve=>{const Se={ArrowLeft:-1,ArrowRight:1,ArrowUp:-ne,ArrowDown:ne}[ve.key];if(!Se)return;ve.preventDefault();const ze=Math.max(0,Math.min(J-1,I+Se)),s=D.current?.querySelector('[data-grid-index="'+ze+'"]');s&&!s.disabled?s.focus():be(ze)}}))}return e("div",{className:"cm-step-grid"},e("div",{className:"cm-grid-controls"},e("select",{value:m,onChange:I=>g(I.target.value),"aria-label":r("步骤类别","Step category")},e("option",{value:""},r("全部用途","All activities")),...(o.operations??[]).map(I=>e("option",{key:I.key,value:I.key},he[I.kind]||I.kind))),e("select",{value:u,onChange:I=>N(I.target.value),"aria-label":r("步骤代理","Step agent")},e("option",{value:""},r("全部代理","All agents")),...o.hierarchy.map(I=>e("option",{key:I.id,value:I.id},i(I.id)))),e("select",{value:C,onChange:I=>b(I.target.value),"aria-label":r("热力图排序","Grid order")},e("option",{value:"time"},r("轨迹顺序","Trajectory order")),e("option",{value:"cost"},r("金额从高到低","Highest cost first"))),e("form",{onSubmit:I=>{I.preventDefault(),Number.isSafeInteger(Number(v))&&Number(v)>0&&be(Number(v)-1)}},e("input",{type:"number",min:1,max:Math.max(1,J),value:v,onChange:I=>A(I.target.value),placeholder:r("序号","Index"),"aria-label":r("定位步骤序号","Locate step index")}),ae(r("定位","Go"),void 0,{type:"submit"}))),e("div",{className:"cm-grid-caption"},e("span",null,r("每格一步 · 颜色区分类别,深浅表示费用","One cell per step · hue = activity, shade = cost")),e("span",null,J.toLocaleString()+r(" 步"," steps"))),W?e("div",null,ye(W),ae(r("重试","Retry"),()=>E(I=>I+1))):null,e("div",{className:"cm-grid-viewport",ref:D,style:{height:Math.min(oe,Math.max(60,Math.ceil(J/ne)*ee))},onScroll:I=>j(I.currentTarget.scrollTop),onMouseLeave:()=>h(null),role:"group","aria-label":r("逐步费用热力图","Step cost heatmap")},e("div",{style:{position:"relative",height:Math.ceil(J/ne)*ee,minHeight:60}},...Ne),J===0?e("p",{className:"cm-stat-empty"},r("没有符合条件的步骤","No matching steps")):null),e("div",{className:"cm-fee-map-status",role:"status"},B?B.label+" · "+d(q(B,c))+(B.unpriced?" + ?":""):""),e("div",{className:"cm-fee-map-legend"},...(o.operations??[]).map(I=>e("button",{key:I.key,type:"button","aria-pressed":m===I.key,onClick:()=>g(K=>K===I.key?"":I.key)},e("i",{className:"cm-plan-dot",style:{background:a.get(ke(I))}}),he[I.kind]||I.kind))))}const Ft=`
66
67
  .cm-fee-tree .cm-fee-link{border:0;padding:3px 0;border-radius:0;background:transparent}.cm-fee-tree .cm-fee-link:hover{color:var(--cm-accent);background:transparent}.cm-fee-tree .cm-fee-tree-toggle{border:0;padding:0;background:transparent;width:18px;height:24px}.cm-fee-tree .cm-stat-table th:first-child{width:48%}.cm-fee-tree .cm-stat-table th:not(:first-child),.cm-fee-tree .cm-stat-table td:not(:first-child){text-align:right}
67
68
  .cm-fee-grouping{display:flex;gap:2px;margin-left:auto}.cm-fee-grouping .cm-stat-btn{padding:2px 7px;font-size:11px;border-color:transparent}.cm-fee-map-summary{flex-wrap:wrap}.cm-grid-controls{display:flex;gap:6px;flex-wrap:wrap;align-items:center}.cm-grid-controls select{font-size:11px;padding:4px 6px;max-width:175px}.cm-grid-controls form{display:flex;gap:4px;margin-left:auto}.cm-grid-controls input{width:70px;padding:3px 6px;font-size:11px}.cm-grid-controls button{padding:3px 7px;font-size:11px}.cm-grid-caption{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--cm-muted);margin:9px 0}.cm-grid-viewport{overflow:auto;overscroll-behavior:contain;border:1px solid var(--cm-border);border-radius:8px;padding-top:5px;background:var(--cm-bg);scrollbar-gutter:stable}.cm-step-cell{border:1px solid transparent;border-radius:3px;padding:0;cursor:pointer}.cm-step-cell:hover{box-shadow:0 0 0 2px var(--cm-accent);z-index:1}.cm-step-cell[aria-pressed=true]{box-shadow:0 0 0 2px var(--cm-label);z-index:1}.cm-step-cell[data-unpriced=true]{background-image:repeating-linear-gradient(135deg,transparent 0 3px,var(--cm-muted) 3px 4px)!important}.cm-grid-inspector{border-top:1px solid var(--cm-border);margin-top:12px;padding-top:10px}.cm-grid-inspector>.cm-fee-toolbar{gap:6px;margin-bottom:4px}.cm-grid-inspector>.cm-fee-toolbar>span{flex:1;min-width:150px;font-size:12px}.cm-grid-inspector>.cm-fee-toolbar>b{font-variant-numeric:tabular-nums;font-weight:500}.cm-grid-inspector>.cm-fee-toolbar>button{border:0;font-size:18px;padding:0 6px}.cm-grid-inspector .cm-stat-table td,.cm-grid-inspector .cm-stat-table th{padding:5px 7px}.cm-fee-view-tabs{flex-wrap:wrap}
68
69
  .cm-fee-wide{grid-column:1/-1}.cm-stat-session .cm-step-costs{margin:10px 0}.cm-fee-components{padding:8px 0;border-bottom:1px solid var(--cm-border)}.cm-fee-components>summary{cursor:pointer;color:var(--cm-muted);font-size:12px}.cm-fee-components .cm-cost-card{margin:8px 0}.cm-fee-placeholder{display:flex;gap:6px;min-height:100px;align-items:center;justify-content:center}.cm-fee-placeholder i{width:5px;height:5px;border-radius:50%;background:var(--dsw-alias-label-tertiary,#9da3ae);opacity:.4}.cm-fee-updating{font-size:10px;font-weight:400;color:var(--cm-muted);margin-left:9px}
@@ -73,4 +74,4 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
73
74
  .cm-fee-distribution{margin:12px 0;padding:10px 12px;border:1px solid var(--cm-border);border-radius:10px}.cm-fee-distribution h3{margin:0 0 8px;font-size:12px;font-weight:500}.cm-fee-distribution-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.cm-fee-bin{min-width:0;font-size:10px;color:var(--cm-muted)}.cm-fee-bin-head{display:flex;justify-content:space-between;align-items:center;gap:6px}.cm-fee-bin-head b{font-size:14px;color:var(--cm-label);font-weight:500;font-variant-numeric:tabular-nums}.cm-fee-bin-track{height:5px;background:var(--cm-surface);border-radius:4px;overflow:hidden;margin:5px 0}.cm-fee-bin-track i{display:block;height:100%;background:var(--cm-accent);border-radius:4px}.cm-fee-bin small{font-size:10px;white-space:nowrap;font-variant-numeric:tabular-nums}
74
75
  .cm-individual-steps>summary{padding:9px 0;font-size:13px}.cm-fee-rank-controls{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin:4px 0 8px}.cm-fee-rank-controls select{font:inherit;color:var(--cm-label);background:var(--cm-bg);border:1px solid var(--cm-border);border-radius:7px;padding:4px 7px;max-width:100%}.cm-fee-filter{display:flex;align-items:center;gap:8px;min-width:0;font-size:11px;color:var(--cm-muted)}.cm-fee-filter span{max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cm-fee-rank .cm-stat-table td,.cm-fee-rank .cm-stat-table th{font-size:11px;padding:7px 6px}.cm-fee-rank .cm-step-name{display:flex;align-items:center;gap:6px;border:0;background:transparent;color:inherit;text-align:left;font:inherit;cursor:pointer;min-width:145px;padding:0}.cm-fee-rank .cm-step-name small{display:block;font-size:10px;color:var(--cm-muted)}.cm-fee-rank .cm-step-amount{font-variant-numeric:tabular-nums;white-space:nowrap}.cm-fee-rank .cm-step-detail{padding:10px 14px;background:var(--cm-surface)}.cm-step-detail-grid{display:grid;grid-template-columns:220px minmax(0,1fr);gap:14px;align-items:start}.cm-step-detail .cm-cost-chart{grid-template-columns:86px minmax(0,1fr);gap:5px 10px}.cm-step-detail .cm-cost-donut{width:86px;height:86px}.cm-step-detail .cm-cost-center{inset:23px 12px}.cm-step-detail .cm-cost-center b{font-size:16px}.cm-step-detail .cm-cost-legend{grid-template-columns:1fr}.cm-step-detail .cm-cost-key{font-size:10px}.cm-step-detail .cm-cost-inspect{font-size:10px;min-height:14px}.cm-step-more{text-align:center;margin:8px 0}.cm-fee-rank .cm-stat-table td:not(:first-child){white-space:nowrap}
75
76
  @container(max-width:680px){.cm-fee-views .cm-cost-legend{grid-template-columns:1fr}.cm-fee-views .cm-cost-chart{grid-template-columns:112px minmax(0,1fr);gap:6px 10px}.cm-fee-views .cm-cost-donut{width:112px;height:112px}.cm-fee-views .cm-cost-center{inset:28px 8px}.cm-fee-views .cm-cost-center b{font-size:16px}.cm-fee-tree .cm-fee-parent{display:none}}@media(max-width:600px){.cm-fee-views{padding:10px}.cm-fee-toolbar{gap:8px}.cm-fee-view-tabs{width:100%;justify-content:space-between}.cm-fee-view-tabs .cm-stat-btn{flex:1}.cm-fee-distribution-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.cm-step-detail-grid{grid-template-columns:1fr}.cm-fee-rank .cm-rank-calls{display:none}}
76
- `;function Ut({api:t,sessionId:n,revision:c,money:l,text:o,basis:a,composition:i,detailed:d=!1}){const[r,y]=M(0),[C,b]=M({key:"",rows:[]}),[m,g]=M(null),[u,N]=M(!1),[z,E]=M(0),[x,T]=M("blocks"),[P,j]=M("cost"),[B,h]=M(20),[R,te]=M({agent:"",group:"",label:""}),W=JSON.stringify([n,a,c,P,R.agent,R.group,R.operation,R.operationGroup,R.stepKey]),F=Te(t,"getSessionTrajectory",{sessionId:n,offset:r,basis:a,order:P,agent:R.agent,group:R.group,operation:R.operation??"",operationGroup:R.operationGroup??"",stepKey:R.stepKey??"",background:!0,generation:String(c).slice(0,96)},c+":"+z),J=ge(null);ce(()=>g(null),[n,a]),F.value&&(J.current={sessionId:n,basis:a,revision:c,value:F.value});const p=J.current;ce(()=>{y(0),b({key:W,rows:[]}),h(R.stepKey?40:20)},[W]),ce(()=>{F.value?.offset===r&&b(f=>({key:W,rows:r===0?F.value.steps:[...new Map([...f.key===W?f.rows:[],...F.value.steps].map(V=>[V.key,V])).values()]}))},[F.value,r,W]);const v=F.value??(p?.sessionId===n&&p.basis===a&&p.revision===c?p.value:null),A=f=>aa(l(f)),D={input:o("输入","Input"),cacheRead:o("缓存读取","Cache read"),cacheWrite:o("缓存写入","Cache write"),output:o("输出","Output"),reasoning:o("推理","Reasoning"),...Me(o)},L=pt(o);if(!v)return F.error?e("p",{className:"cm-stat-sub"},F.error,ae(o("重试","Retry"),()=>E(f=>f+1))):e("div",{className:"cm-fee-placeholder",role:"status","aria-label":o("费用分类正在后台更新","Cost categories updating in background")},e("style",null,Ft),e("i"),e("i"),e("i"));const Z=q(v,a),Q=v.hierarchy??[],le=na({...v,hierarchy:Q}),H=[...new Set([...Q.map(f=>f.id),...v.groups.filter(f=>f.kind==="subagent").map(f=>f.sessionId)])].filter(f=>f!==n).sort(),ne=f=>{if(f===n)return o("当前对话","This conversation");const V=Q.find(ie=>ie.id===f)?.title||v.groups.find(ie=>ie.sessionId===f)?.title||"";return o("子代理 ","Subagent ")+(H.indexOf(f)+1)+(V?" · "+(V.length>32?V.slice(0,32)+"…":V):"")},ee=f=>f.kind==="subagent"?ne(f.sessionId):f.kind==="tool"&&f.tools.length?f.tools.join(" + "):L[f.kind]??f.kind,oe=(f,V)=>g({selection:f,label:V}),$=f=>g({row:f,label:f.label||o("步骤费用明细","Step billing details")}),pe=v.operations?.length?v.operations:v.groups,w=pe.map(f=>({key:f.key,label:ee(f),value:q(f,a),unpriced:f.unpriced,amount:A(q(f,a))+(f.unpriced?" + ?":""),caption:f.steps+o(" 步"," steps"),meta:f.steps+o(" 步 · "," steps · ")+f.calls+o(" 次调用 · 单步均值 "," calls · average per step ")+A(f.steps?q(f,a)/f.steps:0),color:le.get(ke(f))})),se=C.key===W&&C.rows.length?C.rows:F.value?.steps??[],be=se.slice(0,B),he=F.value?.matchingSteps??0,Ce=v.shares.filter(f=>!f.other).slice(0,10).reduce((f,V)=>f+q(V,a),0),re=e("div",{className:"cm-fee-stats"},e("span",null,o("步骤","Steps"),e("b",null,v.totalSteps.toLocaleString())),e("span",null,o("调用","Calls"),e("b",null,v.totalCalls.toLocaleString())),e("span",null,o("单步均值","Average per step"),e("b",null,A(v.totalSteps?Z/v.totalSteps:0))),e("span",null,o("最高 10 步占比","Top 10 steps"),e("b",null,xe(Ce,Z)))),Ne=e("section",{className:"cm-fee-views cm-trajectory-pie cm-fee-wide","aria-label":o("费用类型构成","Cost by category")},e("div",{className:"cm-fee-toolbar"},e("h3",null,o("费用类型构成","Cost by category"),v.refreshing?e("span",{className:"cm-fee-updating",role:"status"},o("更新中","Updating")):v.refreshFailed?ae("↻",()=>E(f=>f+1),{title:o("更新未完成,点击重试","Refresh incomplete, click to retry")}):null),e("div",{className:"cm-fee-view-tabs",role:"group","aria-label":o("费用视图","Cost views")},...[["types",o("归类占比","Categories")],["blocks",o("矩形分布","Treemap")],["tree",o("父子归属","Ownership")],["grid",o("步骤热力图","Step heatmap")]].map(([f,V])=>ae(V,()=>T(f),{key:f,"aria-pressed":x===f})))),x==="types"?e(Oe,{rows:w,total:Z,label:o("对话总费用","Conversation total"),centerValue:A(Z)+(w.some(f=>f.unpriced)?" + ?":""),text:o,ranked:!0,amounts:!0,onSelect:f=>oe(v.operations?.length?{operation:f.key}:{group:f.key},f.label)}):x==="blocks"?e(sa,{value:{...v,hierarchy:Q},basis:a,colors:le,actorName:ne,groupName:ee,money:A,text:o,onSelect:oe}):x==="grid"?e(ra,{api:t,sessionId:n,basis:a,revision:c,value:v,colors:le,actorName:ne,money:A,text:o,onInspect:$}):e(oa,{value:{...v,hierarchy:Q},basis:a,colors:le,actorName:ne,groupName:ee,money:A,text:o,onSelect:oe}),re,pe.some(f=>f.kind==="fetch")?e("p",{className:"cm-stat-note"},o("网页抓取分类包含相关模型步骤;DeepSeek Fetch API 的成功请求另计次数费,本地 HTTP 抓取不另收费。","Web fetch includes related model steps. Successful DeepSeek Fetch API requests have a separate request fee; local HTTP fetching has no separate fee.")):null),I={tiny:"<0.1%",small:"0.1%–1%",medium:"1%–5%",large:"≥5%",free:o("零费用","Zero cost"),unpriced:o("含未定价","Includes unpriced")},K=v.distribution?.length?e("section",{className:"cm-fee-distribution","aria-label":o("单步费用占比分布","Step cost share distribution")},e("h3",null,o("单步费用占比分布","Step cost share distribution")),e("div",{className:"cm-fee-distribution-grid"},...v.distribution.map(f=>e("div",{className:"cm-fee-bin",key:f.key},e("div",{className:"cm-fee-bin-head"},e("span",null,I[f.key]??f.key),e("b",null,f.steps+o(" 步"," steps"))),e("div",{className:"cm-fee-bin-track","aria-hidden":!0},e("i",{style:{width:(v.totalSteps?f.steps/v.totalSteps*100:0)+"%"}})),e("small",null,A(q(f,a))+(f.unpriced?" + ?":"")+" · "+xe(q(f,a),Z)))))):null,de=be.map((f,V)=>{const ie=q(f,a),ve=(f.sessionId!==n?ne(f.sessionId)+" · ":"")+(f.turn==null?L[f.kind]??f.kind:o("轮次 ","Turn ")+f.turn+(f.step==null?"":o(" · 步骤 "," · step ")+f.step));return e("tr",{key:f.key,"data-step-key":f.key,"data-step-amount":ie},e("td",null,V+1),e("td",null,e("button",{type:"button",className:"cm-step-name","aria-haspopup":"dialog",onClick:()=>$({...f,label:ve})},e("i",{className:"cm-plan-dot",style:{background:le.get(f.sessionId!==n?"agent:"+f.sessionId:ke(v.groups.find(Se=>Se.key===f.groupKey)??{kind:f.kind,tools:f.tools}))}}),e("span",null,ve,e("small",null,f.tools.join(" + ")||L[f.kind]||f.kind)))),e("td",{className:"cm-rank-calls"},f.calls),e("td",{className:"cm-step-amount"},A(ie)+(f.unpriced?" + ?":"")),e("td",null,xe(ie,Z)))});return e("section",{className:(d?"cm-step-cards":"cm-step-costs")+" cm-plan","aria-label":o("归类计费明细","Categorized billing details")},e("style",null,Be+Ft),F.error?e("p",{className:"cm-stat-error"},F.error):null,Ne,i?e("details",{className:"cm-fee-components"},e("summary",null,o("输入与输出费用构成","Input and output costs")),i):null,d?K:null,m?e(Dt,{title:m.label,text:o,onClose:()=>g(null)},m.row?e(Kt,{key:m.row.key,api:t,sessionId:n,basis:a,revision:c,row:m.row,money:A,text:o}):e(la,{key:JSON.stringify(m.selection),api:t,sessionId:n,basis:a,revision:c,selection:m.selection,actorName:ne,money:A,text:o})):null,e("details",{className:"cm-individual-steps",open:u,onToggle:f=>{f.target===f.currentTarget&&N(f.currentTarget.open)}},e("summary",null,o("逐步费用明细","Step cost details")+" · "+(F.value?he.toLocaleString():"…")),u?e("div",{className:"cm-fee-rank","aria-busy":F.loading},e("div",{className:"cm-fee-rank-controls"},e("div",{className:"cm-fee-filter"},e("span",null,R.label||o("全部步骤","All steps")),R.agent||R.group||R.operation||R.operationGroup||R.stepKey?ae(o("全部","All"),()=>te({agent:"",group:"",label:""})):null),e("select",{"aria-label":o("步骤排序","Step order"),value:P,onChange:f=>j(f.target.value)},e("option",{value:"cost"},o("金额从高到低","Highest cost first")),e("option",{value:"time"},o("轨迹顺序","Trajectory order")))),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[o("排名","Rank"),o("步骤 / 工具","Step / tool"),o("调用","Calls"),o("费用","Cost"),o("占对话","Of conversation")].map((f,V)=>e("th",{key:f,className:V===2?"cm-rank-calls":""},f)))),e("tbody",null,...de))),be.length<he?e("div",{className:"cm-step-more"},ae(F.loading?o("读取中…","Loading…"):o("展开更多步骤","Show more steps"),()=>{h(f=>f+20),B>=se.length&&y(se.length)},{disabled:F.loading})):null):null))}function dt({api:t,query:n,revision:c,money:l,formatTokens:o,text:a,overview:i=!1,children:d}){const[r,y]=M(0),[C,b]=M(-1),[m,g]=M(0),[u,N]=M("summary"),[z,E]=M(!1),[x,T]=M(null),[P,j]=M(null),[B,h]=M("cost"),[R,te]=M(0),W=Te(t,"getSessionBilling",{...n,offset:r,turnOffset:m,background:!0,generation:String(c).slice(0,96)},c+":"+R),F=ge(!1);ce(()=>T(null),[n.sessionId,n.basis]),ce(()=>{F.current&&!W.loading&&C>=0&&(document.getElementById("cm-stat-call-"+C)?.scrollIntoView({block:"nearest"}),F.current=!1)},[W.loading,W.value,r,C,u]);const J=i&&!W.value,p=n.basis,v=W.value??(i?{found:!0,rows:[],calls:[],cost:0,apiCost:0,totalCalls:0,recorded:{cost:0,apiCost:0,calls:0},agents:[],turns:[],kinds:[],totalTurns:0,offset:0,turnOffset:0,stepShares:{}}:null),A={input:a("非缓存输入","Uncached input"),output:a("输出","Output"),cacheRead:a("缓存读取","Cache read"),cacheWrite:a("缓存写入","Cache write"),reasoning:a("推理","Reasoning"),...Me(a)},D={model:a("模型调用","Model call"),compaction:a("上下文压缩","Compaction"),search:a("原生搜索","Native search"),fetch:a("网页抓取","Web fetch")},L=s=>s==null?a("未标明轮次","Turn not recorded"):a("轮次 ","Turn ")+s;if(Ge(W)&&!i)return W.loading?e("p",{className:"cm-stat-empty",role:"status"},a("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):ye(W.error);const Z=W.failed||v?.refreshFailed?e("div",null,ye(W.error||a("后台更新未完成","Background refresh incomplete")),ae(a("重试","Retry"),()=>te(s=>s+1))):null;if(!v.found)return e(me,null,Z,e("p",{className:"cm-stat-note"},a("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),d);const Q=s=>!s||s===n.sessionId?a("主会话","Main conversation"):a("子代理 ","Subagent ")+((v.agents??[]).find(O=>O.id===s)?.title||s).slice(0,80),le=s=>JSON.stringify([s.sessionId||n.sessionId,s.turn]),H=s=>((v.agents?.length??0)>1?Q(s.sessionId)+" · ":"")+L(s.turn),ne=s=>p==="total"||(p==="plan"?s.plan:!s.plan),ee=Object.keys(A).map(s=>{const O=v.rows.filter(Y=>Y.bucket===s&&ne(Y));return{bucket:s,tokens:O.reduce((Y,X)=>Y+X.tokens,0),requests:O.reduce((Y,X)=>Y+(X.requests??0),0),cost:O.reduce((Y,X)=>Y+X.cost,0),unpriced:O.some(Y=>!Y.priced)}}),oe=q(v,p),$=q(v.recorded,p),pe=Math.abs(oe-$)>Math.max(1e-8,Math.abs($)*1e-8)||v.totalCalls!==v.recorded.calls,w=ee.some(s=>s.unpriced),se=w?a("已知费用占比","Known cost share"):a("费用占比","Cost share"),be=s=>T(s),he=s=>({key:s.bucket,label:A[s.bucket]??Me(a)[s.bucket],tokens:s.tokens,...s.requests?{meta:s.requests+a(" 次请求"," requests")}:{},value:s.cost,unpriced:s.unpriced,amount:s.unpriced&&!s.cost?a("未定价","Unpriced"):l(s.cost)+(s.unpriced?" + ?":""),color:we[st[s.bucket]??7]}),Ce=new Map;for(const s of v.rows.filter(ne)){const O=JSON.stringify([s.provider,s.model]),Y=Ce.get(O)??{key:O,label:s.model,provider:s.provider,tokens:0,value:0,unpriced:!1};Y.value+=s.cost,Y.tokens+=s.bucket==="reasoning"?0:s.tokens,Y.unpriced||=!s.priced,Ce.set(O,Y)}const re=[...Ce.values()].sort((s,O)=>O.value-s.value).map((s,O)=>({...s,label:s.provider+" / "+s.label,amount:s.unpriced&&!s.value?a("未定价","Unpriced"):l(s.value)+(s.unpriced?" + ?":""),color:we[O%7]}));if(re.length>7){const s=re.splice(7),O=s.reduce((X,Ke)=>X+Ke.value,0),Y=s.some(X=>X.unpriced);re.push({key:"other-models",label:a("其余 ","Other ")+s.length+a(" 个模型"," models"),value:O,tokens:s.reduce((X,Ke)=>X+Ke.tokens,0),unpriced:Y,amount:Y&&!O?a("未定价","Unpriced"):l(O)+(Y?" + ?":""),color:we[7]})}const Ne=ee.find(s=>s.bucket==="cacheRead"),I=ee.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)),K=Ne.tokens>0?e("div",{className:"cm-cache-compare"},e("h3",null,a("缓存读取的占比","Cache read share")),...[[a("输入 Token","Input tokens"),Ne.tokens,I.reduce((s,O)=>s+O.tokens,0)],[a("输入费用","Input cost"),Ne.cost,I.some(s=>s.unpriced)?0:I.reduce((s,O)=>s+O.cost,0)]].map(([s,O,Y])=>e("div",{key:s},e("div",{className:"cm-stat-share-head"},e("span",null,s),e("span",null,ue(O,Y))),e("div",{className:"cm-stat-share-track","aria-hidden":!0},e("span",{style:{display:"block",height:"100%",width:(Y>0?O/Y*100:0)+"%",borderRadius:9,background:we[6]}}))))):null,de=(s,O,Y={},X=null)=>e("section",{className:"cm-spend-card","aria-label":s},e("h3",null,s),e(Oe,{rows:O,total:oe,label:se,text:a,amounts:!0,...Y}),X),f=(v.callShares??[]).filter(s=>!s.other),V=v.callShares?.find(s=>s.other),ie=Math.max(0,...f.map(s=>q(s,p))),ve=f.reduce((s,O)=>s+q(O,p),0),Se=f.length?e("section",{className:"cm-spend-card cm-call-ranking","aria-label":a("高额调用","Highest-cost calls")},e("h3",null,a("高额调用","Highest-cost calls")),...f.map((s,O)=>e("button",{type:"button",className:"cm-call-rank-row",key:s.index,onClick:()=>be(s),"aria-haspopup":"dialog"},e("span",{className:"cm-call-rank-index"},O+1),e("span",{className:"cm-call-rank-main"},e("span",{className:"cm-call-rank-caption"},e("span",null,a("调用 #","Call #")+(s.index+1)),e("span",null,l(q(s,p))+(s.unpriced?" + ?":""),e("small",null,xe(q(s,p),oe)))),e("span",{className:"cm-call-rank-track","aria-hidden":!0},e("i",{style:{width:(ie>0?q(s,p)/ie*100:0)+"%"}}))))),e("div",{className:"cm-call-rank-footer"},e("span",null,a("前 ","Top ")+f.length+a(" 次合计 "," calls ")+l(ve)),e("span",null,a("占对话 ","Of conversation ")+xe(ve,oe))),V?e("div",{className:"cm-call-rank-rest"},a("其余 ","Other ")+V.calls+a(" 次调用"," calls"),e("span",null,l(q(V,p))+(V.unpriced?" + ?":""))):null):null,ze=(s,O,Y)=>e("div",{className:"cm-stat-scroll",style:{marginTop:20}},e("h3",null,s),e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[s,a("调用次数","Calls"),a("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",a("Plan 等值","Plan equivalent")].map(X=>e("th",{key:X},X)))),e("tbody",null,O.map((X,Ke)=>e("tr",{key:Ke},e("td",null,Y(X)),e("td",null,X.calls),e("td",null,[X.input,X.cacheRead+X.cacheWrite,X.output].map(o).join(" / ")),e("td",null,l(X.apiCost)+(X.unpriced?" + ?":"")),e("td",null,l(Math.max(0,X.cost-X.apiCost))+(X.unpriced?" + ?":"")))))));return e("section",{className:"cm-stat-panel"},e("style",null,Be+Zt),x!=null?e(ca,{key:[n.sessionId,p,x.index].join(":"),api:t,sessionId:n.sessionId,revision:c,row:x,money:l,text:a,names:A,onClose:()=>T(null)}):null,i?e("nav",{className:"cm-session-tabs","aria-label":a("费用视图","Cost views")},...[["summary",a("费用概览","Overview")],["context",a("费用明细","Cost details")]].map(([s,O])=>ae(O,()=>{N(s),b(-1),E(!1)},{key:s,"aria-pressed":u===s}))):null,i?e("div",{className:"cm-stat-metrics"},...[[p==="total"?a("API + Plan 等值","API + Plan equivalent"):p==="plan"?a("Plan 等值","Plan equivalent"):a("API 费用","API cost"),l(oe)+(ee.some(s=>s.unpriced)?" + ?":""),a("按本对话调用日志估算","Estimated from this conversation’s call logs")],[a("调用次数","Calls"),v.totalCalls.toLocaleString(),(v.agents?.length??0)>1?a("包含子代理","Includes subagents"):a("本会话","This conversation")],[a("Token 用量","Token usage"),o(ee.reduce((s,O)=>s+(O.bucket==="reasoning"?0:O.tokens),0)),a("输入、缓存与输出","Input, cache and output")],[a("缓存命中率","Cache hit rate"),ue(ee.find(s=>s.bucket==="cacheRead")?.tokens??0,ee.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)).reduce((s,O)=>s+O.tokens,0)),a("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([s,O,Y])=>e("div",{className:"cm-stat-metric",key:s},e("div",{className:"cm-stat-sub"},s),e("div",{className:"cm-stat-value"},J?"—":O),e("div",{className:"cm-stat-sub"},J?"":Y)))):null,i&&u==="context"?e(Ut,{api:t,sessionId:n.sessionId,revision:c,money:l,text:a,basis:p,detailed:!0}):null,i?u==="context"?e("details",{className:"cm-stat-secondary"},e("summary",{style:{padding:"8px 0"}},a("上下文费用参考","Context cost reference")),d):null:d,i?null:e("div",{className:"cm-stat-panel-head"},e("h3",null,i?a("已发生费用 · 调用明细","Recorded costs · call details"):a("单对话费用明细","Conversation cost details")),e("span",{className:"cm-stat-sub"},(v.agents?.length??0)>1?a("包含子代理及其后代","Includes subagents and their descendants"):a("本会话自身的调用","Own conversation calls"))),Z,!i&&pe?e("p",{className:"cm-stat-note"},a("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+l($)+" / "+v.recorded.calls+a(" 次;明细 "," calls; details ")+l(oe)+" / "+v.totalCalls+a(" 次。"," calls.")):null,(!i||u==="calls")&&(v.agents?.length??0)>1?ze(a("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),v.agents,s=>Q(s.id)):null,i?null:e("div",{className:"cm-plan cm-spend"},w?e("p",{className:"cm-plan-sub"},a("存在未定价调用","Some calls are unpriced")):null,e("div",{className:"cm-spend-grid"},de(a("费用构成","Cost composition"),ee.filter(s=>(s.tokens>0||s.requests>0)&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(he),{},K),Se,re.length>1?de(a("模型费用分布","Cost by model"),re):null,v.kinds.length>1?de(a("各环节费用占比","Cost by activity"),v.kinds.map((s,O)=>({key:s.kind,label:D[s.kind]??s.kind,value:q(s,p),tokens:je(s),meta:s.calls+a(" 次调用"," calls")+" · "+o(je(s))+" tok",unpriced:s.unpriced,amount:l(q(s,p))+(s.unpriced?" + ?":""),color:we[O]}))):null)),i&&u==="summary"?e(Ut,{api:t,sessionId:n.sessionId,revision:c,money:l,text:a,basis:p,composition:J?null:de(a("费用构成","Cost composition"),ee.filter(s=>(s.tokens>0||s.requests>0)&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(he))}):null,!J&&(!i||u==="summary")?e("details",{className:"cm-call-section",open:!i||z||C>=0,onToggle:s=>{s.target===s.currentTarget&&(E(s.currentTarget.open),s.currentTarget.open||b(-1))}},e("summary",{style:{padding:"10px 0",fontSize:13}},a("逐次调用明细","Individual calls")+" · "+v.totalCalls),i?e("div",{className:"cm-plan cm-spend-grid"},Se,re.length>1?de(a("模型费用分布","Cost by model"),re):K):null,i?null:e("details",{className:"cm-stat-secondary",open:!i},e("summary",null,a("轮次、步骤与单价","Turns, steps and rates")),e("section",{className:"cm-stat-breakdown"},e("div",{className:"cm-stat-panel-head"},e("h3",null,a("各步骤占比","Share by step")),e("div",{className:"cm-stat-periods"},...[["cost",a("费用","Cost")],["calls",a("调用次数","Calls")]].map(([s,O])=>ae(O,()=>h(s),{key:s,"aria-pressed":B===s})))),e(Lt,{title:B==="cost"?a("费用占比 · 全部调用","Cost share · all calls"):a("调用次数占比 · 全部调用","Call count share · all calls"),rows:(v.stepShares?.[B]??[]).map(s=>({label:s.other?a("其余步骤合计","All other steps"):H(s)+(s.step==null?"":a(" · 步骤 "," · step ")+s.step),value:B==="cost"?q(s,p):s.calls,unpriced:B==="cost"&&s.unpriced,other:s.other})),total:B==="cost"?oe:v.totalCalls,format:B==="cost"?l:s=>s.toLocaleString(),text:a,columns:!0})),e("details",{className:"cm-stat-help"},e("summary",null,a("单价与 Token 明细","Rates and token details")),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[a("费用构成","Cost component"),"Tokens",a("费用","Cost"),a("费用占比","Cost share")].map(s=>e("th",{key:s},s)))),e("tbody",null,ee.map(s=>e("tr",{key:s.bucket},e("td",null,A[s.bucket]),e("td",null,s.requests?s.requests+a(" 次"," requests"):s.tokens.toLocaleString()),e("td",null,l(s.cost)+(s.unpriced?" + ?":"")),e("td",null,ue(s.cost,oe))))))),ze(a("按调用类型统计","Cost by call type"),v.kinds,s=>D[s.kind]??s.kind)),e("section",{className:"cm-stat-turns"},e("div",{className:"cm-stat-panel-head"},e("h3",null,a("按轮次统计","Cost by turn")),e("span",{className:"cm-stat-sub"},a("展开查看输入和工具调用","Expand to inspect input and tool calls"))),v.turns.map(s=>e("div",{key:le(s),className:"cm-stat-turn"},e("button",{type:"button",className:"cm-stat-turn-toggle",disabled:s.turn==null,"aria-expanded":s.turn!=null&&P===le(s),onClick:()=>j(O=>O===le(s)?null:le(s))},e("span",null,(s.turn==null?"":P===le(s)?"⌄ ":"› ")+H(s)),e("span",null,s.calls+a(" 次调用"," calls")+" · "+o(je(s))+" tok · "+l(q(s,p))+(s.unpriced?" + ?":"")+" · "+ue(q(s,p),oe))),s.turn!=null&&P===le(s)?e(Bt,{key:le(s),api:t,sessionId:s.sessionId||n.sessionId,turn:s.turn,revision:c,text:a}):null))),e(De,{offset:m,count:v.totalTurns,size:25,onChange:s=>{g(s),j(null)},text:a})),e("div",{style:{marginTop:24}},e(Et,{rows:v.calls.map((s,O)=>({label:"#"+(r+O+1),index:O,value:q(s,p)})),money:l,text:a,label:a("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:s=>{b(s.index),document.getElementById("cm-stat-call-"+s.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),v.calls.map((s,O)=>e("details",{key:r+O,id:"cm-stat-call-"+O,className:"cm-stat-call",open:C===O,onToggle:Y=>{Y.currentTarget.open?b(O):b(X=>X===O?-1:X)}},e("summary",null,"#"+(r+O+1)+" · "+H(s)+(s.step==null?"":a(" / 步骤 "," / step ")+s.step)+" · "+(D[s.kind]??s.kind)+" · "+s.provider+" / "+s.model+" · "+(s.plan?"Plan ":"API ")+(s.priced?l(s.cost):"?")+(s.longContext?a(" · 长上下文价"," · long-context rate"):""),e("span",{className:"cm-call-share"},(s.priced?ue(q(s,p),oe):"—")+" · "+se)),C===O?e(it,{key:(s.sessionId||n.sessionId)+":"+(s.logSeq??O),call:s,sessionId:n.sessionId,api:t,revision:c,money:l,text:a,names:A}):null)),e(De,{offset:r,count:v.totalCalls,size:50,onChange:s=>{y(s),b(-1)},text:a})):null)}function Wt(t,n){if(!window.__BILI__&&!n?.connected)return null;let c;try{const l=new URL(window.__BILI__?.origin);["http:","https:"].includes(l.protocol)&&!l.username&&!l.password&&(c=l.origin+"/__bili/")}catch{}return e("p",{className:"cm-stat-note","data-billing-coverage":"billion-context"},n?.connected?t("已接入 billion-context 的逐次请求,包括内部压缩、重试和追加请求。只从启用后开始采集,启用前的缺失记录无法补齐。","billion-context request metering is connected, including internal compression, retries and additional calls. Collection starts when enabled; earlier missing records cannot be recovered.")+(n.failed?t(" 用量读取失败,保留已有金额。"," Usage refresh failed; saved amounts are retained."):"")+(n.uncovered?t(" 未建立完整采集的请求:"," Requests without the full metering bridge: ")+n.uncovered+t(";这些请求沿用 DSH 用量。","; these requests retain DSH usage accounting."):"")+(n.unreported||n.partial?t(" 没有完整用量回执的请求:"," Requests without complete usage: ")+(n.unreported+n.partial)+t(";这些请求的未知费用没有估补。","; unknown charges are not inferred."):""):t("已检测到 billion-context。此处统计它上报给 DSH 的用量;代理内部未上报的压缩、重试和追加请求未计入。","billion-context detected. These totals use its reported DSH usage; unreported internal compression, retries and additional requests are excluded."),c?e("a",{href:c,target:"_blank",rel:"noopener noreferrer",style:{marginInlineStart:8}},t("查看代理统计","Open proxy statistics")):null)}function $t(t,n,c){const l=()=>["api","plan","total"].includes(t.statisticsBasis)?t.statisticsBasis:t.showTotalWithPlan?"total":"api",[o,a]=M(l),[i,d]=M(!1),[r,y]=M("");return ce(()=>{i||a(l())},[t.statisticsBasis,t.showTotalWithPlan,i]),{basis:o,choose:async b=>{if(!(i||!["api","plan","total"].includes(b))){a(b),d(!0),y("");try{await n.saveStatisticsBasis(b)}catch{y(c("计费口径保存失败,请重试。","Could not save the cost basis. Try again."))}finally{d(!1)}}},saving:i,error:r}}function Ht({state:t,api:n,sessionId:c,formatMoneyUsd:l,formatTokens:o,resolveLocale:a,contextIntegration:i}){const d=(N,z)=>(a?a(t.config):t.config.locale)==="en"?z:N,[r,y]=M(0),C=$t(t.config,n,d),{basis:b}=C,m=Ve(t,r),g=N=>l(N,{...t.config,decimals:Math.max(N!==0&&Math.abs(N)<.01?8:4,t.config.decimals??2)}),u={sessionId:c,from:"",to:"",provider:"",model:"",basis:b,offset:0};return e("div",{className:"cm-stat cm-stat-session","data-session-id":c},e("style",null,Nt),Wt(d,t.billionContext),e("div",{className:"cm-stat-panel-head"},e("p",{className:"cm-stat-sub"},d("当前对话 · 全部调用","This conversation · all calls")),ae(d("刷新","Refresh"),()=>y(N=>N+1))),e(dt,{key:c+":"+b,api:n,query:u,revision:m,money:g,formatTokens:o,text:d,overview:!0},e(Je,{key:c,api:n,sessionId:c,revision:m,money:g,text:d,compact:!0,expanded:!0})),e("details",{className:"cm-session-options"},e("summary",null,d("显示与联动设置","Display and integration settings")),e("div",{className:"cm-stat-controls"},e("label",null,d("计费口径","Cost basis"),e("select",{value:b,disabled:C.saving,onChange:N=>C.choose(N.target.value)},...[["api",d("API 费用","API cost")],["plan",d("Plan 等值","Plan equivalent")],["total",d("API + Plan 等值","API + Plan equivalent")]].map(([N,z])=>e("option",{key:N,value:N},z))))),C.error?ye(C.error):null,i?e(rt,i):null))}function _t({state:t,api:n,sessionId:c="",formatMoneyUsd:l,formatTokens:o,resolveLocale:a,contextIntegration:i}){const d=a?a(t.config)==="en":t.config.locale==="en"||t.config.locale!=="zh"&&(t.config.activeLocale||t.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",r=(w,se)=>d?se:w,[y,C]=M(c?"all":"week"),[b,m]=M(null),[g,u]=M({id:c,title:c}),[N,z]=M(""),[E,x]=M(""),T=$t(t.config,n,r),{basis:P}=T,[j,B]=M(0),[h,R]=M(0),[te,W]=M(!1),F=t.meta.dayKey||new Date().toISOString().slice(0,10),J=y==="all"?"":y==="custom"?b?.from||F:ut(F,y==="week"?-6:y==="month"?-29:0),p=y==="custom"&&b?.to||F,v={from:J,to:p,provider:N,model:E,basis:P,sessionId:g.id,offset:j},A=Ve(t,h),D=Te(n,"getBillingStatistics",v,A),L=D.value,Z=w=>l(w,{...t.config,decimals:Math.max(w!==0&&Math.abs(w)<.01?8:4,t.config.decimals??2)}),Q=w=>{C(w),B(0)},le=w=>{u(w),B(0),z(""),x("")},H=P==="total"?r("API + Plan 等值","API + Plan equivalent"):P==="plan"?r("Plan 等值","Plan equivalent"):r("API 费用","API cost"),ne=(w,se,be,he,Ce=!1)=>e("label",null,w,e("select",{value:se,disabled:Ce,onChange:re=>{be(re.target.value),B(0)}},he.map(([re,Ne])=>e("option",{key:re,value:re},Ne)))),ee={input:r("未缓存输入","Uncached input"),cacheRead:r("缓存读取","Cache read"),cacheWrite:r("缓存写入","Cache write"),output:r("输出","Output")},oe=(w,se)=>e("section",{className:"cm-stat-panel"},e("div",{className:"cm-stat-panel-head"},e("h3",null,w)),se),$=L?.totals,pe=(w,se,be)=>e("div",{className:"cm-stat-metric",key:w},e("div",{className:"cm-stat-sub"},w),e("div",{className:"cm-stat-value"},se),e("div",{className:"cm-stat-sub"},be));return e("div",{className:"cm-stat"},e("style",null,Nt),Wt(r,t.billionContext),i?e(rt,i):null,e("header",{className:"cm-stat-head"},e("div",null,e("h2",null,r("计费统计","Cost statistics")),e("p",{className:"cm-stat-sub"},g.id?r("单对话 · ","Conversation · ")+(g.title===g.id&&L?.sessions[0]?.title||g.title):r("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),ae(r("刷新","Refresh"),()=>R(w=>w+1))),g.id?ae(r("← 全部对话","← All conversations"),()=>le({id:"",title:""})):null,e("div",{className:"cm-stat-controls"},e("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(([w,se])=>ae(se,()=>Q(w),{key:w,"aria-pressed":y===w})))),y==="custom"?e("div",{className:"cm-stat-controls"},...["from","to"].map(w=>e("label",{key:w},w==="from"?r("开始日期","From"):r("结束日期","To"),e("input",{type:"date",value:w==="from"?J:p,onChange:se=>{m({from:J,to:p,[w]:se.target.value}),B(0)}})))):null,e("div",{className:"cm-stat-controls"},ne(r("计费口径","Cost basis"),P,T.choose,[["api",r("API 费用","API cost")],["plan",r("Plan 等值","Plan equivalent")],["total",r("API + Plan 等值","API + Plan equivalent")]],T.saving),ne(r("提供商","Provider"),N,w=>{z(w),x("")},[["",r("全部提供商","All providers")],...[...new Set([N,...L?.providers??[]])].filter(Boolean).map(w=>[w,w])]),ne(r("模型","Model"),E,x,[["",r("全部模型","All models")],...[...new Set([E,...L?.modelOptions??[]])].filter(Boolean).map(w=>[w,w])])),T.error?ye(T.error):null,Ge(D)?D.loading?e("p",{className:"cm-stat-empty",role:"status"},r("加载统计…","Loading statistics…")):ye(D.error):L?e(me,null,D.failed?ye(D.error):null,e("p",{className:"cm-stat-sub",style:{marginTop:8}},L.from+" – "+L.to+(L.retainedFrom?" · "+r("账本保留范围 ","Retained ledger ")+L.retainedFrom+" – "+L.retainedTo:"")),e("div",{className:"cm-stat-metrics"},pe(r("API 费用","API cost"),Z($.apiCost),r("已入账估算","Recorded estimate")),pe(r("Plan 等值费用","Plan equivalent"),Z(Math.max(0,$.cost-$.apiCost)),""),pe(r("调用次数","Calls"),$.calls.toLocaleString(),L.sessionCount+r(" 个对话 · 平均 "," conversations · average ")+Z($.calls?q($,P)/$.calls:0)),pe(r("缓存命中率","Cache hit rate"),ue($.cacheRead,$.input+$.cacheRead+$.cacheWrite),o(je($))+" Tokens")),g.id?e("section",{className:"cm-stat-panel"},e(Je,{key:g.id,api:n,sessionId:g.id,revision:A,money:Z,text:r})):null,g.id?e(dt,{key:JSON.stringify([g.id,J,p,N,E,P]),api:n,query:{...v,from:L.from,to:L.to,offset:0},revision:A,money:Z,formatTokens:o,text:r}):null,L.models.some(w=>!w.priced)?e("p",{className:"cm-stat-note"},r("部分模型未配置价格","Some models have no rates")):null,!$.calls&&!$.cost?e("p",{className:"cm-stat-empty"},r("所选范围没有已记录的用量。","No recorded usage in this range.")):null,e("section",{className:"cm-stat-panel"},e(Et,{rows:At(L.days,P),money:Z,text:r,label:r("费用趋势 · ","Cost over time · ")+H,onSelect:w=>{m({from:w.from,to:w.to}),Q("custom")}})),e("div",{className:"cm-stat-grid"},oe(r("模型费用排行","Cost by model"),e(me,null,e("ol",{className:"cm-stat-rank"},(te?L.models:L.models.slice(0,8)).map(w=>e("li",{key:w.key},e("button",{type:"button",onClick:()=>{z(w.provider),x(w.model),B(0)},title:w.key},e("div",{className:"cm-stat-rankline"},e("span",null,w.model),e("span",{className:"cm-stat-number"},Z(q(w,P))+(w.priced?"":" + ?"))),e("div",{className:"cm-stat-sub"},w.provider+" · "+w.calls+r(" 次 · "," calls · ")+ue(q(w,P),q($,P))),e("div",{className:"cm-stat-track"},e("span",{style:{width:ue(q(w,P),q($,P))}}))))),L.models.length>8?ae(te?r("收起","Show less"):r("显示全部模型","Show all models"),()=>W(w=>!w)):null,L.unmodeledCost>1e-8?e("p",{className:"cm-stat-note"},r("历史未分配到模型的费用:","Historical cost without a model: ")+Z(L.unmodeledCost)):null)),oe(r("Token 构成","Token composition"),e(me,null,e("ol",{className:"cm-stat-rank"},Object.entries(ee).map(([w,se])=>e("li",{key:w},e("div",{className:"cm-stat-rankline"},e("span",null,se),e("span",{className:"cm-stat-number"},o($[w]))),e("div",{className:"cm-stat-track"},e("span",{style:{width:ue($[w],je($)),background:w.startsWith("cache")?"var(--cm-plan)":void 0}}))))),e("p",{className:"cm-stat-sub"},r("单独上报的推理 Token:","Reported reasoning tokens: ")+o($.reasoning))))),g.id?null:e("section",{className:"cm-stat-panel"},e("div",{className:"cm-stat-panel-head"},e("h3",null,r("对话费用排行","Cost by conversation")),e("span",{className:"cm-stat-sub"},t.config.includeSubagentCost?r("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):r("点击对话查看明细","Select a conversation for details"))),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[r("对话","Conversation"),r("调用","Calls"),"API",r("Plan 等值","Plan equivalent"),r("缓存命中","Cache hits")].map(w=>e("th",{key:w},w)))),e("tbody",null,L.sessions.map(w=>e("tr",{key:w.id},e("td",null,e("button",{type:"button",title:w.id,onClick:()=>le({id:w.id,title:w.title})},w.title)),e("td",null,w.calls.toLocaleString()),e("td",null,Z(w.apiCost)),e("td",null,Z(Math.max(0,w.cost-w.apiCost))),e("td",null,ue(w.cacheRead,w.input+w.cacheRead+w.cacheWrite))))))),L.unassignedCost>1e-8?e("p",{className:"cm-stat-note"},r("未关联对话的费用:","Cost not linked to a conversation: ")+Z(L.unassignedCost)):null,e(De,{offset:j,count:L.sessionCount,size:25,onChange:B,text:r})))):null)}function Gt(t,{state:n,sessionId:c=""}={}){if(!n||document.hidden)return;const l=Ve(n,0),o=n.meta.dayKey||new Date().toISOString().slice(0,10),a={sessionId:c,from:c?"":ut(o,-6),to:c?"":o,provider:"",model:"",basis:["api","plan","total"].includes(n.config.statisticsBasis)?n.config.statisticsBasis:n.config.showTotalWithPlan?"total":"api",offset:0};return Promise.allSettled(c?[Re(t,"getSessionBilling",{...a,turnOffset:0,background:!0,generation:String(l).slice(0,96)},l+":0"),Re(t,"getSessionTrajectory",{sessionId:c,offset:0,basis:a.basis,order:"cost",agent:"",group:"",operation:"",operationGroup:"",stepKey:"",background:!0,generation:String(l).slice(0,96)},l+":0")]:[Re(t,"getBillingStatistics",a,l+":0")])}async function ia(t,n,c){const l=typeof n=="function"?n:()=>n&&c?c(n.getSnapshot().state?.config??{activeLocale:n.getSnapshot().locale}):"en",o=await t.get("remote").$mount(Ct);t.effect(()=>()=>o(),"cost-meter: statistics contribution");const a=t.get("remote.costMeter"),i=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getCallInspection","getContextCosts","getSessionTrajectory"].map(y=>[y,async C=>{const b=n?.getSnapshot?.()?.state?.config?.currency,m=(y==="getSessionTrajectory"?vt:y==="getContextCosts"?_e:y==="getCallInspection"?wt:y==="getTurnInspection"?yt:kt)(C),g=await a[y]({...m,...["getBillingStatistics","getSessionBilling","getSessionTrajectory"].includes(y)&&["CNY","EUR","USD"].includes(b)?{displayCurrency:b}:{}});if(!g?.ok)throw new Error(g?.error?.message||"Statistics request failed");return{getBillingStatistics:Ze,getSessionBilling:et,getTurnInspection:We,getCallInspection:ft,getContextCosts:tt,getSessionTrajectory:xt}[y](g.value)}]));i.saveStatisticsBasis=async y=>{const C=await a.updateConfig({statisticsBasis:y});if(!C?.ok||C.value?.config?.statisticsBasis!==y)throw new Error("Cost basis setting failed");n?.set?.({status:"ready",error:null,state:C.value})};let d;if(n?.subscribe&&typeof t.get("slots")?.entries=="function"){i.getContextIntegration=async()=>{const b=await a.getContextIntegration();if(!b?.ok)throw new Error("Integration check failed");return ht(b.value)},i.saveIntegration=async b=>{const m=await a.updateConfig({contextCostsEnabled:b,contextCostsPromptSeen:!0});if(!m?.ok||!m.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:m.value})},d=Ot(t,i,n,l,mt("react-dom").createPortal),t.effect(()=>d.dispose,"cost-meter: optional dsh-context integration");const y=t.get("slots"),C=()=>y.register({name:"shell.overlay",id:"cost-meter-context-intro",order:50},()=>e(qt,{manager:d,getLocale:l}));typeof y.inject=="function"&&t.effect(()=>y.inject("shell.overlay",C),"cost-meter: context preview prompt")}const r=y=>e(y.sessionId?Ht:_t,{...y,api:i,contextIntegration:d?{manager:d,getLocale:l}:null});return r.BillionCompatibilityNotice=jt,r.prefetch=y=>Gt(i,y),t.effect(()=>()=>nt.delete(i),"cost-meter: statistics cache cleanup"),r}return{mount:ia,prefetchStatistics:Gt,Statistics:_t,SessionStatistics:Ht,SessionDetail:dt,TurnInspection:Bt,ShareChart:Lt,ContextCosts:Je,BillionCompatibilityNotice:jt,ContextPrompt:qt,ContextPreview:ct,ContextIntegrationSettings:rt,createContextIntegration:Ot,contextCostBreakdown:zt,installContextCosts:Mt,CONTRIBUTION:Ct,parseContextCosts:tt,parseStatistics:Ze,parseDetail:et,parseInspection:We,dailyChartRows:At,requestStart:St,requestValue:Ee,requestFailure:It,showsPlaceholder:Ge,refreshKeyOf:Ve}}});
77
+ `;function Ut({api:t,sessionId:n,revision:c,money:l,text:o,basis:a,composition:i,detailed:d=!1}){const[r,y]=M(0),[C,b]=M({key:"",rows:[]}),[m,g]=M(null),[u,N]=M(!1),[z,E]=M(0),[x,T]=M("blocks"),[P,j]=M("cost"),[B,h]=M(20),[R,te]=M({agent:"",group:"",label:""}),W=JSON.stringify([n,a,c,P,R.agent,R.group,R.operation,R.operationGroup,R.stepKey]),F=Te(t,"getSessionTrajectory",{sessionId:n,offset:r,basis:a,order:P,agent:R.agent,group:R.group,operation:R.operation??"",operationGroup:R.operationGroup??"",stepKey:R.stepKey??"",background:!0,generation:String(c).slice(0,96)},c+":"+z),J=ge(null);ce(()=>g(null),[n,a]),F.value&&(J.current={sessionId:n,basis:a,revision:c,value:F.value});const p=J.current;ce(()=>{y(0),b({key:W,rows:[]}),h(R.stepKey?40:20)},[W]),ce(()=>{F.value?.offset===r&&b(f=>({key:W,rows:r===0?F.value.steps:[...new Map([...f.key===W?f.rows:[],...F.value.steps].map(V=>[V.key,V])).values()]}))},[F.value,r,W]);const v=F.value??(p?.sessionId===n&&p.basis===a&&p.revision===c?p.value:null),A=f=>aa(l(f)),D={input:o("输入","Input"),cacheRead:o("缓存读取","Cache read"),cacheWrite:o("缓存写入","Cache write"),output:o("输出","Output"),reasoning:o("推理","Reasoning"),...Me(o)},L=pt(o);if(!v)return F.error?e("p",{className:"cm-stat-sub"},F.error,ae(o("重试","Retry"),()=>E(f=>f+1))):e("div",{className:"cm-fee-placeholder",role:"status","aria-label":o("费用分类正在后台更新","Cost categories updating in background")},e("style",null,Ft),e("i"),e("i"),e("i"));const Z=q(v,a),Q=v.hierarchy??[],le=na({...v,hierarchy:Q}),$=[...new Set([...Q.map(f=>f.id),...v.groups.filter(f=>f.kind==="subagent").map(f=>f.sessionId)])].filter(f=>f!==n).sort(),ne=f=>{if(f===n)return o("当前对话","This conversation");const V=Q.find(ie=>ie.id===f)?.title||v.groups.find(ie=>ie.sessionId===f)?.title||"";return o("子代理 ","Subagent ")+($.indexOf(f)+1)+(V?" · "+(V.length>32?V.slice(0,32)+"…":V):"")},ee=f=>f.kind==="subagent"?ne(f.sessionId):f.kind==="tool"&&f.tools.length?f.tools.join(" + "):L[f.kind]??f.kind,oe=(f,V)=>g({selection:f,label:V}),_=f=>g({row:f,label:f.label||o("步骤费用明细","Step billing details")}),pe=v.operations?.length?v.operations:v.groups,w=pe.map(f=>({key:f.key,label:ee(f),value:q(f,a),unpriced:f.unpriced,amount:A(q(f,a))+(f.unpriced?" + ?":""),caption:f.steps+o(" 步"," steps"),meta:f.steps+o(" 步 · "," steps · ")+f.calls+o(" 次调用 · 单步均值 "," calls · average per step ")+A(f.steps?q(f,a)/f.steps:0),color:le.get(ke(f))})),se=C.key===W&&C.rows.length?C.rows:F.value?.steps??[],be=se.slice(0,B),he=F.value?.matchingSteps??0,Ce=v.shares.filter(f=>!f.other).slice(0,10).reduce((f,V)=>f+q(V,a),0),re=e("div",{className:"cm-fee-stats"},e("span",null,o("步骤","Steps"),e("b",null,v.totalSteps.toLocaleString())),e("span",null,o("调用","Calls"),e("b",null,v.totalCalls.toLocaleString())),e("span",null,o("单步均值","Average per step"),e("b",null,A(v.totalSteps?Z/v.totalSteps:0))),e("span",null,o("最高 10 步占比","Top 10 steps"),e("b",null,xe(Ce,Z)))),Ne=e("section",{className:"cm-fee-views cm-trajectory-pie cm-fee-wide","aria-label":o("费用类型构成","Cost by category")},e("div",{className:"cm-fee-toolbar"},e("h3",null,o("费用类型构成","Cost by category"),v.refreshing?e("span",{className:"cm-fee-updating",role:"status"},o("更新中","Updating")):v.refreshFailed?ae("↻",()=>E(f=>f+1),{title:o("更新未完成,点击重试","Refresh incomplete, click to retry")}):null),e("div",{className:"cm-fee-view-tabs",role:"group","aria-label":o("费用视图","Cost views")},...[["types",o("归类占比","Categories")],["blocks",o("矩形分布","Treemap")],["tree",o("父子归属","Ownership")],["grid",o("步骤热力图","Step heatmap")]].map(([f,V])=>ae(V,()=>T(f),{key:f,"aria-pressed":x===f})))),x==="types"?e(Oe,{rows:w,total:Z,label:o("对话总费用","Conversation total"),centerValue:A(Z)+(w.some(f=>f.unpriced)?" + ?":""),text:o,ranked:!0,amounts:!0,onSelect:f=>oe(v.operations?.length?{operation:f.key}:{group:f.key},f.label)}):x==="blocks"?e(sa,{value:{...v,hierarchy:Q},basis:a,colors:le,actorName:ne,groupName:ee,money:A,text:o,onSelect:oe}):x==="grid"?e(ra,{api:t,sessionId:n,basis:a,revision:c,value:v,colors:le,actorName:ne,money:A,text:o,onInspect:_}):e(oa,{value:{...v,hierarchy:Q},basis:a,colors:le,actorName:ne,groupName:ee,money:A,text:o,onSelect:oe}),re,pe.some(f=>f.kind==="fetch")?e("p",{className:"cm-stat-note"},o("网页抓取分类包含相关模型步骤;DeepSeek Fetch API 的成功请求另计次数费,本地 HTTP 抓取不另收费。","Web fetch includes related model steps. Successful DeepSeek Fetch API requests have a separate request fee; local HTTP fetching has no separate fee.")):null),I={tiny:"<0.1%",small:"0.1%–1%",medium:"1%–5%",large:"≥5%",free:o("零费用","Zero cost"),unpriced:o("含未定价","Includes unpriced")},K=v.distribution?.length?e("section",{className:"cm-fee-distribution","aria-label":o("单步费用占比分布","Step cost share distribution")},e("h3",null,o("单步费用占比分布","Step cost share distribution")),e("div",{className:"cm-fee-distribution-grid"},...v.distribution.map(f=>e("div",{className:"cm-fee-bin",key:f.key},e("div",{className:"cm-fee-bin-head"},e("span",null,I[f.key]??f.key),e("b",null,f.steps+o(" 步"," steps"))),e("div",{className:"cm-fee-bin-track","aria-hidden":!0},e("i",{style:{width:(v.totalSteps?f.steps/v.totalSteps*100:0)+"%"}})),e("small",null,A(q(f,a))+(f.unpriced?" + ?":"")+" · "+xe(q(f,a),Z)))))):null,de=be.map((f,V)=>{const ie=q(f,a),ve=(f.sessionId!==n?ne(f.sessionId)+" · ":"")+(f.turn==null?L[f.kind]??f.kind:o("轮次 ","Turn ")+f.turn+(f.step==null?"":o(" · 步骤 "," · step ")+f.step));return e("tr",{key:f.key,"data-step-key":f.key,"data-step-amount":ie},e("td",null,V+1),e("td",null,e("button",{type:"button",className:"cm-step-name","aria-haspopup":"dialog",onClick:()=>_({...f,label:ve})},e("i",{className:"cm-plan-dot",style:{background:le.get(f.sessionId!==n?"agent:"+f.sessionId:ke(v.groups.find(Se=>Se.key===f.groupKey)??{kind:f.kind,tools:f.tools}))}}),e("span",null,ve,e("small",null,f.tools.join(" + ")||L[f.kind]||f.kind)))),e("td",{className:"cm-rank-calls"},f.calls),e("td",{className:"cm-step-amount"},A(ie)+(f.unpriced?" + ?":"")),e("td",null,xe(ie,Z)))});return e("section",{className:(d?"cm-step-cards":"cm-step-costs")+" cm-plan","aria-label":o("归类计费明细","Categorized billing details")},e("style",null,Be+Ft),F.error?e("p",{className:"cm-stat-error"},F.error):null,Ne,i?e("details",{className:"cm-fee-components"},e("summary",null,o("输入与输出费用构成","Input and output costs")),i):null,d?K:null,m?e(Dt,{title:m.label,text:o,onClose:()=>g(null)},m.row?e(Kt,{key:m.row.key,api:t,sessionId:n,basis:a,revision:c,row:m.row,money:A,text:o}):e(la,{key:JSON.stringify(m.selection),api:t,sessionId:n,basis:a,revision:c,selection:m.selection,actorName:ne,money:A,text:o})):null,e("details",{className:"cm-individual-steps",open:u,onToggle:f=>{f.target===f.currentTarget&&N(f.currentTarget.open)}},e("summary",null,o("逐步费用明细","Step cost details")+" · "+(F.value?he.toLocaleString():"…")),u?e("div",{className:"cm-fee-rank","aria-busy":F.loading},e("div",{className:"cm-fee-rank-controls"},e("div",{className:"cm-fee-filter"},e("span",null,R.label||o("全部步骤","All steps")),R.agent||R.group||R.operation||R.operationGroup||R.stepKey?ae(o("全部","All"),()=>te({agent:"",group:"",label:""})):null),e("select",{"aria-label":o("步骤排序","Step order"),value:P,onChange:f=>j(f.target.value)},e("option",{value:"cost"},o("金额从高到低","Highest cost first")),e("option",{value:"time"},o("轨迹顺序","Trajectory order")))),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[o("排名","Rank"),o("步骤 / 工具","Step / tool"),o("调用","Calls"),o("费用","Cost"),o("占对话","Of conversation")].map((f,V)=>e("th",{key:f,className:V===2?"cm-rank-calls":""},f)))),e("tbody",null,...de))),be.length<he?e("div",{className:"cm-step-more"},ae(F.loading?o("读取中…","Loading…"):o("展开更多步骤","Show more steps"),()=>{h(f=>f+20),B>=se.length&&y(se.length)},{disabled:F.loading})):null):null))}function dt({api:t,query:n,revision:c,money:l,formatTokens:o,text:a,overview:i=!1,children:d}){const[r,y]=M(0),[C,b]=M(-1),[m,g]=M(0),[u,N]=M("summary"),[z,E]=M(!1),[x,T]=M(null),[P,j]=M(null),[B,h]=M("cost"),[R,te]=M(0),W=Te(t,"getSessionBilling",{...n,offset:r,turnOffset:m,background:!0,generation:String(c).slice(0,96)},c+":"+R),F=ge(!1);ce(()=>T(null),[n.sessionId,n.basis]),ce(()=>{F.current&&!W.loading&&C>=0&&(document.getElementById("cm-stat-call-"+C)?.scrollIntoView({block:"nearest"}),F.current=!1)},[W.loading,W.value,r,C,u]);const J=i&&!W.value,p=n.basis,v=W.value??(i?{found:!0,rows:[],calls:[],cost:0,apiCost:0,totalCalls:0,recorded:{cost:0,apiCost:0,calls:0},agents:[],turns:[],kinds:[],totalTurns:0,offset:0,turnOffset:0,stepShares:{}}:null),A={input:a("非缓存输入","Uncached input"),output:a("输出","Output"),cacheRead:a("缓存读取","Cache read"),cacheWrite:a("缓存写入","Cache write"),reasoning:a("推理","Reasoning"),...Me(a)},D={model:a("模型调用","Model call"),compaction:a("上下文压缩","Compaction"),search:a("原生搜索","Native search"),fetch:a("网页抓取","Web fetch")},L=s=>s==null?a("未标明轮次","Turn not recorded"):a("轮次 ","Turn ")+s;if(Ge(W)&&!i)return W.loading?e("p",{className:"cm-stat-empty",role:"status"},a("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):ye(W.error);const Z=W.failed||v?.refreshFailed?e("div",null,ye(W.error||a("后台更新未完成","Background refresh incomplete")),ae(a("重试","Retry"),()=>te(s=>s+1))):null;if(!v.found)return e(me,null,Z,e("p",{className:"cm-stat-note"},a("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),d);const Q=s=>!s||s===n.sessionId?a("主会话","Main conversation"):a("子代理 ","Subagent ")+((v.agents??[]).find(O=>O.id===s)?.title||s).slice(0,80),le=s=>JSON.stringify([s.sessionId||n.sessionId,s.turn]),$=s=>((v.agents?.length??0)>1?Q(s.sessionId)+" · ":"")+L(s.turn),ne=s=>p==="total"||(p==="plan"?s.plan:!s.plan),ee=Object.keys(A).map(s=>{const O=v.rows.filter(Y=>Y.bucket===s&&ne(Y));return{bucket:s,tokens:O.reduce((Y,X)=>Y+X.tokens,0),requests:O.reduce((Y,X)=>Y+(X.requests??0),0),cost:O.reduce((Y,X)=>Y+X.cost,0),unpriced:O.some(Y=>!Y.priced)}}),oe=q(v,p),_=q(v.recorded,p),pe=Math.abs(oe-_)>Math.max(1e-8,Math.abs(_)*1e-8)||v.totalCalls!==v.recorded.calls,w=ee.some(s=>s.unpriced),se=w?a("已知费用占比","Known cost share"):a("费用占比","Cost share"),be=s=>T(s),he=s=>({key:s.bucket,label:A[s.bucket]??Me(a)[s.bucket],tokens:s.tokens,...s.requests?{meta:s.requests+a(" 次请求"," requests")}:{},value:s.cost,unpriced:s.unpriced,amount:s.unpriced&&!s.cost?a("未定价","Unpriced"):l(s.cost)+(s.unpriced?" + ?":""),color:we[st[s.bucket]??7]}),Ce=new Map;for(const s of v.rows.filter(ne)){const O=JSON.stringify([s.provider,s.model]),Y=Ce.get(O)??{key:O,label:s.model,provider:s.provider,tokens:0,value:0,unpriced:!1};Y.value+=s.cost,Y.tokens+=s.bucket==="reasoning"?0:s.tokens,Y.unpriced||=!s.priced,Ce.set(O,Y)}const re=[...Ce.values()].sort((s,O)=>O.value-s.value).map((s,O)=>({...s,label:s.provider+" / "+s.label,amount:s.unpriced&&!s.value?a("未定价","Unpriced"):l(s.value)+(s.unpriced?" + ?":""),color:we[O%7]}));if(re.length>7){const s=re.splice(7),O=s.reduce((X,Ke)=>X+Ke.value,0),Y=s.some(X=>X.unpriced);re.push({key:"other-models",label:a("其余 ","Other ")+s.length+a(" 个模型"," models"),value:O,tokens:s.reduce((X,Ke)=>X+Ke.tokens,0),unpriced:Y,amount:Y&&!O?a("未定价","Unpriced"):l(O)+(Y?" + ?":""),color:we[7]})}const Ne=ee.find(s=>s.bucket==="cacheRead"),I=ee.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)),K=Ne.tokens>0?e("div",{className:"cm-cache-compare"},e("h3",null,a("缓存读取的占比","Cache read share")),...[[a("输入 Token","Input tokens"),Ne.tokens,I.reduce((s,O)=>s+O.tokens,0)],[a("输入费用","Input cost"),Ne.cost,I.some(s=>s.unpriced)?0:I.reduce((s,O)=>s+O.cost,0)]].map(([s,O,Y])=>e("div",{key:s},e("div",{className:"cm-stat-share-head"},e("span",null,s),e("span",null,ue(O,Y))),e("div",{className:"cm-stat-share-track","aria-hidden":!0},e("span",{style:{display:"block",height:"100%",width:(Y>0?O/Y*100:0)+"%",borderRadius:9,background:we[6]}}))))):null,de=(s,O,Y={},X=null)=>e("section",{className:"cm-spend-card","aria-label":s},e("h3",null,s),e(Oe,{rows:O,total:oe,label:se,text:a,amounts:!0,...Y}),X),f=(v.callShares??[]).filter(s=>!s.other),V=v.callShares?.find(s=>s.other),ie=Math.max(0,...f.map(s=>q(s,p))),ve=f.reduce((s,O)=>s+q(O,p),0),Se=f.length?e("section",{className:"cm-spend-card cm-call-ranking","aria-label":a("高额调用","Highest-cost calls")},e("h3",null,a("高额调用","Highest-cost calls")),...f.map((s,O)=>e("button",{type:"button",className:"cm-call-rank-row",key:s.index,onClick:()=>be(s),"aria-haspopup":"dialog"},e("span",{className:"cm-call-rank-index"},O+1),e("span",{className:"cm-call-rank-main"},e("span",{className:"cm-call-rank-caption"},e("span",null,a("调用 #","Call #")+(s.index+1)),e("span",null,l(q(s,p))+(s.unpriced?" + ?":""),e("small",null,xe(q(s,p),oe)))),e("span",{className:"cm-call-rank-track","aria-hidden":!0},e("i",{style:{width:(ie>0?q(s,p)/ie*100:0)+"%"}}))))),e("div",{className:"cm-call-rank-footer"},e("span",null,a("前 ","Top ")+f.length+a(" 次合计 "," calls ")+l(ve)),e("span",null,a("占对话 ","Of conversation ")+xe(ve,oe))),V?e("div",{className:"cm-call-rank-rest"},a("其余 ","Other ")+V.calls+a(" 次调用"," calls"),e("span",null,l(q(V,p))+(V.unpriced?" + ?":""))):null):null,ze=(s,O,Y)=>e("div",{className:"cm-stat-scroll",style:{marginTop:20}},e("h3",null,s),e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[s,a("调用次数","Calls"),a("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",a("Plan 等值","Plan equivalent")].map(X=>e("th",{key:X},X)))),e("tbody",null,O.map((X,Ke)=>e("tr",{key:Ke},e("td",null,Y(X)),e("td",null,X.calls),e("td",null,[X.input,X.cacheRead+X.cacheWrite,X.output].map(o).join(" / ")),e("td",null,l(X.apiCost)+(X.unpriced?" + ?":"")),e("td",null,l(Math.max(0,X.cost-X.apiCost))+(X.unpriced?" + ?":"")))))));return e("section",{className:"cm-stat-panel"},e("style",null,Be+Zt),x!=null?e(ca,{key:[n.sessionId,p,x.index].join(":"),api:t,sessionId:n.sessionId,revision:c,row:x,money:l,text:a,names:A,onClose:()=>T(null)}):null,i?e("nav",{className:"cm-session-tabs","aria-label":a("费用视图","Cost views")},...[["summary",a("费用概览","Overview")],["context",a("费用明细","Cost details")]].map(([s,O])=>ae(O,()=>{N(s),b(-1),E(!1)},{key:s,"aria-pressed":u===s}))):null,i?e("div",{className:"cm-stat-metrics"},...[[p==="total"?a("API + Plan 等值","API + Plan equivalent"):p==="plan"?a("Plan 等值","Plan equivalent"):a("API 费用","API cost"),l(oe)+(ee.some(s=>s.unpriced)?" + ?":""),a("按本对话调用日志估算","Estimated from this conversation’s call logs")],[a("调用次数","Calls"),v.totalCalls.toLocaleString(),(v.agents?.length??0)>1?a("包含子代理","Includes subagents"):a("本会话","This conversation")],[a("Token 用量","Token usage"),o(ee.reduce((s,O)=>s+(O.bucket==="reasoning"?0:O.tokens),0)),a("输入、缓存与输出","Input, cache and output")],[a("缓存命中率","Cache hit rate"),ue(ee.find(s=>s.bucket==="cacheRead")?.tokens??0,ee.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)).reduce((s,O)=>s+O.tokens,0)),a("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([s,O,Y])=>e("div",{className:"cm-stat-metric",key:s},e("div",{className:"cm-stat-sub"},s),e("div",{className:"cm-stat-value"},J?"—":O),e("div",{className:"cm-stat-sub"},J?"":Y)))):null,i&&u==="context"?e(Ut,{api:t,sessionId:n.sessionId,revision:c,money:l,text:a,basis:p,detailed:!0}):null,i?u==="context"?e("details",{className:"cm-stat-secondary"},e("summary",{style:{padding:"8px 0"}},a("上下文费用参考","Context cost reference")),d):null:d,i?null:e("div",{className:"cm-stat-panel-head"},e("h3",null,i?a("已发生费用 · 调用明细","Recorded costs · call details"):a("单对话费用明细","Conversation cost details")),e("span",{className:"cm-stat-sub"},(v.agents?.length??0)>1?a("包含子代理及其后代","Includes subagents and their descendants"):a("本会话自身的调用","Own conversation calls"))),Z,!i&&pe?e("p",{className:"cm-stat-note"},a("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+l(_)+" / "+v.recorded.calls+a(" 次;明细 "," calls; details ")+l(oe)+" / "+v.totalCalls+a(" 次。"," calls.")):null,(!i||u==="calls")&&(v.agents?.length??0)>1?ze(a("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),v.agents,s=>Q(s.id)):null,i?null:e("div",{className:"cm-plan cm-spend"},w?e("p",{className:"cm-plan-sub"},a("存在未定价调用","Some calls are unpriced")):null,e("div",{className:"cm-spend-grid"},de(a("费用构成","Cost composition"),ee.filter(s=>(s.tokens>0||s.requests>0)&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(he),{},K),Se,re.length>1?de(a("模型费用分布","Cost by model"),re):null,v.kinds.length>1?de(a("各环节费用占比","Cost by activity"),v.kinds.map((s,O)=>({key:s.kind,label:D[s.kind]??s.kind,value:q(s,p),tokens:je(s),meta:s.calls+a(" 次调用"," calls")+" · "+o(je(s))+" tok",unpriced:s.unpriced,amount:l(q(s,p))+(s.unpriced?" + ?":""),color:we[O]}))):null)),i&&u==="summary"?e(Ut,{api:t,sessionId:n.sessionId,revision:c,money:l,text:a,basis:p,composition:J?null:de(a("费用构成","Cost composition"),ee.filter(s=>(s.tokens>0||s.requests>0)&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(he))}):null,!J&&(!i||u==="summary")?e("details",{className:"cm-call-section",open:!i||z||C>=0,onToggle:s=>{s.target===s.currentTarget&&(E(s.currentTarget.open),s.currentTarget.open||b(-1))}},e("summary",{style:{padding:"10px 0",fontSize:13}},a("逐次调用明细","Individual calls")+" · "+v.totalCalls),i?e("div",{className:"cm-plan cm-spend-grid"},Se,re.length>1?de(a("模型费用分布","Cost by model"),re):K):null,i?null:e("details",{className:"cm-stat-secondary",open:!i},e("summary",null,a("轮次、步骤与单价","Turns, steps and rates")),e("section",{className:"cm-stat-breakdown"},e("div",{className:"cm-stat-panel-head"},e("h3",null,a("各步骤占比","Share by step")),e("div",{className:"cm-stat-periods"},...[["cost",a("费用","Cost")],["calls",a("调用次数","Calls")]].map(([s,O])=>ae(O,()=>h(s),{key:s,"aria-pressed":B===s})))),e(Lt,{title:B==="cost"?a("费用占比 · 全部调用","Cost share · all calls"):a("调用次数占比 · 全部调用","Call count share · all calls"),rows:(v.stepShares?.[B]??[]).map(s=>({label:s.other?a("其余步骤合计","All other steps"):$(s)+(s.step==null?"":a(" · 步骤 "," · step ")+s.step),value:B==="cost"?q(s,p):s.calls,unpriced:B==="cost"&&s.unpriced,other:s.other})),total:B==="cost"?oe:v.totalCalls,format:B==="cost"?l:s=>s.toLocaleString(),text:a,columns:!0})),e("details",{className:"cm-stat-help"},e("summary",null,a("单价与 Token 明细","Rates and token details")),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[a("费用构成","Cost component"),"Tokens",a("费用","Cost"),a("费用占比","Cost share")].map(s=>e("th",{key:s},s)))),e("tbody",null,ee.map(s=>e("tr",{key:s.bucket},e("td",null,A[s.bucket]),e("td",null,s.requests?s.requests+a(" 次"," requests"):s.tokens.toLocaleString()),e("td",null,l(s.cost)+(s.unpriced?" + ?":"")),e("td",null,ue(s.cost,oe))))))),ze(a("按调用类型统计","Cost by call type"),v.kinds,s=>D[s.kind]??s.kind)),e("section",{className:"cm-stat-turns"},e("div",{className:"cm-stat-panel-head"},e("h3",null,a("按轮次统计","Cost by turn")),e("span",{className:"cm-stat-sub"},a("展开查看输入和工具调用","Expand to inspect input and tool calls"))),v.turns.map(s=>e("div",{key:le(s),className:"cm-stat-turn"},e("button",{type:"button",className:"cm-stat-turn-toggle",disabled:s.turn==null,"aria-expanded":s.turn!=null&&P===le(s),onClick:()=>j(O=>O===le(s)?null:le(s))},e("span",null,(s.turn==null?"":P===le(s)?"⌄ ":"› ")+$(s)),e("span",null,s.calls+a(" 次调用"," calls")+" · "+o(je(s))+" tok · "+l(q(s,p))+(s.unpriced?" + ?":"")+" · "+ue(q(s,p),oe))),s.turn!=null&&P===le(s)?e(Bt,{key:le(s),api:t,sessionId:s.sessionId||n.sessionId,turn:s.turn,revision:c,text:a}):null))),e(De,{offset:m,count:v.totalTurns,size:25,onChange:s=>{g(s),j(null)},text:a})),e("div",{style:{marginTop:24}},e(Et,{rows:v.calls.map((s,O)=>({label:"#"+(r+O+1),index:O,value:q(s,p)})),money:l,text:a,label:a("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:s=>{b(s.index),document.getElementById("cm-stat-call-"+s.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),v.calls.map((s,O)=>e("details",{key:r+O,id:"cm-stat-call-"+O,className:"cm-stat-call",open:C===O,onToggle:Y=>{Y.currentTarget.open?b(O):b(X=>X===O?-1:X)}},e("summary",null,"#"+(r+O+1)+" · "+$(s)+(s.step==null?"":a(" / 步骤 "," / step ")+s.step)+" · "+(D[s.kind]??s.kind)+" · "+s.provider+" / "+s.model+" · "+(s.plan?"Plan ":"API ")+(s.priced?l(s.cost):"?")+(s.longContext?a(" · 长上下文价"," · long-context rate"):""),e("span",{className:"cm-call-share"},(s.priced?ue(q(s,p),oe):"—")+" · "+se)),C===O?e(it,{key:(s.sessionId||n.sessionId)+":"+(s.logSeq??O),call:s,sessionId:n.sessionId,api:t,revision:c,money:l,text:a,names:A}):null)),e(De,{offset:r,count:v.totalCalls,size:50,onChange:s=>{y(s),b(-1)},text:a})):null)}function Wt(t,n){if(!window.__BILI__&&!n?.connected)return null;let c;try{const l=new URL(window.__BILI__?.origin);["http:","https:"].includes(l.protocol)&&!l.username&&!l.password&&(c=l.origin+"/__bili/")}catch{}return e("p",{className:"cm-stat-note","data-billing-coverage":"billion-context"},n?.connected?t("已接入 billion-context 的逐次请求,包括内部压缩、重试和追加请求。只从启用后开始采集,启用前的缺失记录无法补齐。","billion-context request metering is connected, including internal compression, retries and additional calls. Collection starts when enabled; earlier missing records cannot be recovered.")+(n.failed?t(" 用量读取失败,保留已有金额。"," Usage refresh failed; saved amounts are retained."):"")+(n.uncovered?t(" 未建立完整采集的请求:"," Requests without the full metering bridge: ")+n.uncovered+t(";这些请求沿用 DSH 用量。","; these requests retain DSH usage accounting."):"")+(n.unreported||n.partial?t(" 没有完整用量回执的请求:"," Requests without complete usage: ")+(n.unreported+n.partial)+t(";这些请求的未知费用没有估补。","; unknown charges are not inferred."):""):t("已检测到 billion-context。此处统计它上报给 DSH 的用量;代理内部未上报的压缩、重试和追加请求未计入。","billion-context detected. These totals use its reported DSH usage; unreported internal compression, retries and additional requests are excluded."),c?e("a",{href:c,target:"_blank",rel:"noopener noreferrer",style:{marginInlineStart:8}},t("查看代理统计","Open proxy statistics")):null)}function _t(t,n,c){const l=()=>["api","plan","total"].includes(t.statisticsBasis)?t.statisticsBasis:t.showTotalWithPlan?"total":"api",[o,a]=M(l),[i,d]=M(!1),[r,y]=M("");return ce(()=>{i||a(l())},[t.statisticsBasis,t.showTotalWithPlan,i]),{basis:o,choose:async b=>{if(!(i||!["api","plan","total"].includes(b))){a(b),d(!0),y("");try{await n.saveStatisticsBasis(b)}catch{y(c("计费口径保存失败,请重试。","Could not save the cost basis. Try again."))}finally{d(!1)}}},saving:i,error:r}}function $t({state:t,api:n,sessionId:c,formatMoneyUsd:l,formatTokens:o,resolveLocale:a,contextIntegration:i}){const d=(N,z)=>(a?a(t.config):t.config.locale)==="en"?z:N,[r,y]=M(0),C=_t(t.config,n,d),{basis:b}=C,m=Ve(t,r),g=N=>l(N,{...t.config,decimals:Math.max(N!==0&&Math.abs(N)<.01?8:4,t.config.decimals??2)}),u={sessionId:c,from:"",to:"",provider:"",model:"",basis:b,offset:0};return e("div",{className:"cm-stat cm-stat-session","data-session-id":c},e("style",null,Nt),Wt(d,t.billionContext),e("div",{className:"cm-stat-panel-head"},e("p",{className:"cm-stat-sub"},d("当前对话 · 全部调用","This conversation · all calls")),ae(d("刷新","Refresh"),()=>y(N=>N+1))),e(dt,{key:c+":"+b,api:n,query:u,revision:m,money:g,formatTokens:o,text:d,overview:!0},e(Je,{key:c,api:n,sessionId:c,revision:m,money:g,text:d,compact:!0,expanded:!0})),e("details",{className:"cm-session-options"},e("summary",null,d("显示与联动设置","Display and integration settings")),e("div",{className:"cm-stat-controls"},e("label",null,d("计费口径","Cost basis"),e("select",{value:b,disabled:C.saving,onChange:N=>C.choose(N.target.value)},...[["api",d("API 费用","API cost")],["plan",d("Plan 等值","Plan equivalent")],["total",d("API + Plan 等值","API + Plan equivalent")]].map(([N,z])=>e("option",{key:N,value:N},z))))),C.error?ye(C.error):null,i?e(rt,i):null))}function Ht({state:t,api:n,sessionId:c="",formatMoneyUsd:l,formatTokens:o,resolveLocale:a,contextIntegration:i}){const d=a?a(t.config)==="en":t.config.locale==="en"||t.config.locale!=="zh"&&(t.config.activeLocale||t.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",r=(w,se)=>d?se:w,[y,C]=M(c?"all":"week"),[b,m]=M(null),[g,u]=M({id:c,title:c}),[N,z]=M(""),[E,x]=M(""),T=_t(t.config,n,r),{basis:P}=T,[j,B]=M(0),[h,R]=M(0),[te,W]=M(!1),F=t.meta.dayKey||new Date().toISOString().slice(0,10),J=y==="all"?"":y==="custom"?b?.from||F:ut(F,y==="week"?-6:y==="month"?-29:0),p=y==="custom"&&b?.to||F,v={from:J,to:p,provider:N,model:E,basis:P,sessionId:g.id,offset:j},A=Ve(t,h),D=Te(n,"getBillingStatistics",v,A),L=D.value,Z=w=>l(w,{...t.config,decimals:Math.max(w!==0&&Math.abs(w)<.01?8:4,t.config.decimals??2)}),Q=w=>{C(w),B(0)},le=w=>{u(w),B(0),z(""),x("")},$=P==="total"?r("API + Plan 等值","API + Plan equivalent"):P==="plan"?r("Plan 等值","Plan equivalent"):r("API 费用","API cost"),ne=(w,se,be,he,Ce=!1)=>e("label",null,w,e("select",{value:se,disabled:Ce,onChange:re=>{be(re.target.value),B(0)}},he.map(([re,Ne])=>e("option",{key:re,value:re},Ne)))),ee={input:r("未缓存输入","Uncached input"),cacheRead:r("缓存读取","Cache read"),cacheWrite:r("缓存写入","Cache write"),output:r("输出","Output")},oe=(w,se)=>e("section",{className:"cm-stat-panel"},e("div",{className:"cm-stat-panel-head"},e("h3",null,w)),se),_=L?.totals,pe=(w,se,be)=>e("div",{className:"cm-stat-metric",key:w},e("div",{className:"cm-stat-sub"},w),e("div",{className:"cm-stat-value"},se),e("div",{className:"cm-stat-sub"},be));return e("div",{className:"cm-stat"},e("style",null,Nt),e("header",{className:"cm-stat-head"},e("div",null,e("h2",null,r("计费统计","Cost statistics")),e("p",{className:"cm-stat-sub"},g.id?r("单对话 · ","Conversation · ")+(g.title===g.id&&L?.sessions[0]?.title||g.title):r("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),ae(r("刷新","Refresh"),()=>R(w=>w+1))),i||window.__BILI__||t.billionContext?.connected?e("details",{className:"cm-stat-options"},e("summary",null,r("计费与联动设置","Billing and integration settings")),Wt(r,t.billionContext),i?e(rt,i):null):null,g.id?ae(r("← 全部对话","← All conversations"),()=>le({id:"",title:""})):null,e("div",{className:"cm-stat-controls"},e("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(([w,se])=>ae(se,()=>Q(w),{key:w,"aria-pressed":y===w})))),y==="custom"?e("div",{className:"cm-stat-controls"},...["from","to"].map(w=>e("label",{key:w},w==="from"?r("开始日期","From"):r("结束日期","To"),e("input",{type:"date",value:w==="from"?J:p,onChange:se=>{m({from:J,to:p,[w]:se.target.value}),B(0)}})))):null,e("div",{className:"cm-stat-controls"},ne(r("计费口径","Cost basis"),P,T.choose,[["api",r("API 费用","API cost")],["plan",r("Plan 等值","Plan equivalent")],["total",r("API + Plan 等值","API + Plan equivalent")]],T.saving),ne(r("提供商","Provider"),N,w=>{z(w),x("")},[["",r("全部提供商","All providers")],...[...new Set([N,...L?.providers??[]])].filter(Boolean).map(w=>[w,w])]),ne(r("模型","Model"),E,x,[["",r("全部模型","All models")],...[...new Set([E,...L?.modelOptions??[]])].filter(Boolean).map(w=>[w,w])])),T.error?ye(T.error):null,Ge(D)?D.loading?e("p",{className:"cm-stat-empty",role:"status"},r("加载统计…","Loading statistics…")):ye(D.error):L?e(me,null,D.failed?ye(D.error):null,e("p",{className:"cm-stat-sub",style:{marginTop:8}},L.from+" – "+L.to+(L.retainedFrom?" · "+r("账本保留范围 ","Retained ledger ")+L.retainedFrom+" – "+L.retainedTo:"")),e("div",{className:"cm-stat-metrics"},pe(r("API 费用","API cost"),Z(_.apiCost),r("已入账估算","Recorded estimate")),pe(r("Plan 等值费用","Plan equivalent"),Z(Math.max(0,_.cost-_.apiCost)),""),pe(r("调用次数","Calls"),_.calls.toLocaleString(),L.sessionCount+r(" 个对话 · 平均 "," conversations · average ")+Z(_.calls?q(_,P)/_.calls:0)),pe(r("缓存命中率","Cache hit rate"),ue(_.cacheRead,_.input+_.cacheRead+_.cacheWrite),o(je(_))+" Tokens")),g.id?e("section",{className:"cm-stat-panel"},e(Je,{key:g.id,api:n,sessionId:g.id,revision:A,money:Z,text:r})):null,g.id?e(dt,{key:JSON.stringify([g.id,J,p,N,E,P]),api:n,query:{...v,from:L.from,to:L.to,offset:0},revision:A,money:Z,formatTokens:o,text:r}):null,L.models.some(w=>!w.priced)?e("p",{className:"cm-stat-note"},r("部分模型未配置价格","Some models have no rates")):null,!_.calls&&!_.cost?e("p",{className:"cm-stat-empty"},r("所选范围没有已记录的用量。","No recorded usage in this range.")):null,e("section",{className:"cm-stat-panel"},e(Et,{rows:At(L.days,P),money:Z,text:r,label:r("费用趋势 · ","Cost over time · ")+$,onSelect:w=>{m({from:w.from,to:w.to}),Q("custom")}})),e("div",{className:"cm-stat-grid"},oe(r("模型费用排行","Cost by model"),e(me,null,e("ol",{className:"cm-stat-rank"},(te?L.models:L.models.slice(0,8)).map(w=>e("li",{key:w.key},e("button",{type:"button",onClick:()=>{z(w.provider),x(w.model),B(0)},title:w.key},e("div",{className:"cm-stat-rankline"},e("span",null,w.model),e("span",{className:"cm-stat-number"},Z(q(w,P))+(w.priced?"":" + ?"))),e("div",{className:"cm-stat-sub"},w.provider+" · "+w.calls+r(" 次 · "," calls · ")+ue(q(w,P),q(_,P))),e("div",{className:"cm-stat-track"},e("span",{style:{width:ue(q(w,P),q(_,P))}}))))),L.models.length>8?ae(te?r("收起","Show less"):r("显示全部模型","Show all models"),()=>W(w=>!w)):null,L.unmodeledCost>1e-8?e("p",{className:"cm-stat-note"},r("历史未分配到模型的费用:","Historical cost without a model: ")+Z(L.unmodeledCost)):null)),oe(r("Token 构成","Token composition"),e(me,null,e("ol",{className:"cm-stat-rank"},Object.entries(ee).map(([w,se])=>e("li",{key:w},e("div",{className:"cm-stat-rankline"},e("span",null,se),e("span",{className:"cm-stat-number"},o(_[w]))),e("div",{className:"cm-stat-track"},e("span",{style:{width:ue(_[w],je(_)),background:w.startsWith("cache")?"var(--cm-plan)":void 0}}))))),e("p",{className:"cm-stat-sub"},r("单独上报的推理 Token:","Reported reasoning tokens: ")+o(_.reasoning))))),g.id?null:e("section",{className:"cm-stat-panel"},e("div",{className:"cm-stat-panel-head"},e("h3",null,r("对话费用排行","Cost by conversation")),e("span",{className:"cm-stat-sub"},t.config.includeSubagentCost?r("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):r("点击对话查看明细","Select a conversation for details"))),e("div",{className:"cm-stat-scroll"},e("table",{className:"cm-stat-table"},e("thead",null,e("tr",null,...[r("对话","Conversation"),r("调用","Calls"),"API",r("Plan 等值","Plan equivalent"),r("缓存命中","Cache hits")].map(w=>e("th",{key:w},w)))),e("tbody",null,L.sessions.map(w=>e("tr",{key:w.id},e("td",null,e("button",{type:"button",title:w.id,onClick:()=>le({id:w.id,title:w.title})},w.title)),e("td",null,w.calls.toLocaleString()),e("td",null,Z(w.apiCost)),e("td",null,Z(Math.max(0,w.cost-w.apiCost))),e("td",null,ue(w.cacheRead,w.input+w.cacheRead+w.cacheWrite))))))),L.unassignedCost>1e-8?e("p",{className:"cm-stat-note"},r("未关联对话的费用:","Cost not linked to a conversation: ")+Z(L.unassignedCost)):null,e(De,{offset:j,count:L.sessionCount,size:25,onChange:B,text:r})))):null)}function Gt(t,{state:n,sessionId:c=""}={}){if(!n||document.hidden)return;const l=Ve(n,0),o=n.meta.dayKey||new Date().toISOString().slice(0,10),a={sessionId:c,from:c?"":ut(o,-6),to:c?"":o,provider:"",model:"",basis:["api","plan","total"].includes(n.config.statisticsBasis)?n.config.statisticsBasis:n.config.showTotalWithPlan?"total":"api",offset:0};return Promise.allSettled(c?[Re(t,"getSessionBilling",{...a,turnOffset:0,background:!0,generation:String(l).slice(0,96)},l+":0"),Re(t,"getSessionTrajectory",{sessionId:c,offset:0,basis:a.basis,order:"cost",agent:"",group:"",operation:"",operationGroup:"",stepKey:"",background:!0,generation:String(l).slice(0,96)},l+":0")]:[Re(t,"getBillingStatistics",a,l+":0")])}async function ia(t,n,c){const l=typeof n=="function"?n:()=>n&&c?c(n.getSnapshot().state?.config??{activeLocale:n.getSnapshot().locale}):"en",o=await t.get("remote").$mount(Ct);t.effect(()=>()=>o(),"cost-meter: statistics contribution");const a=t.get("remote.costMeter"),i=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getCallInspection","getContextCosts","getSessionTrajectory"].map(y=>[y,async C=>{const b=n?.getSnapshot?.()?.state?.config?.currency,m=(y==="getSessionTrajectory"?vt:y==="getContextCosts"?He:y==="getCallInspection"?wt:y==="getTurnInspection"?yt:kt)(C),g=await a[y]({...m,...["getBillingStatistics","getSessionBilling","getSessionTrajectory"].includes(y)&&["CNY","EUR","USD"].includes(b)?{displayCurrency:b}:{}});if(!g?.ok)throw new Error(g?.error?.message||"Statistics request failed");return{getBillingStatistics:Ze,getSessionBilling:et,getTurnInspection:We,getCallInspection:ft,getContextCosts:tt,getSessionTrajectory:xt}[y](g.value)}]));i.saveStatisticsBasis=async y=>{const C=await a.updateConfig({statisticsBasis:y});if(!C?.ok||C.value?.config?.statisticsBasis!==y)throw new Error("Cost basis setting failed");n?.set?.({status:"ready",error:null,state:C.value})};let d;if(n?.subscribe&&typeof t.get("slots")?.entries=="function"){i.getContextIntegration=async()=>{const b=await a.getContextIntegration();if(!b?.ok)throw new Error("Integration check failed");return ht(b.value)},i.saveIntegration=async b=>{const m=await a.updateConfig({contextCostsEnabled:b,contextCostsPromptSeen:!0});if(!m?.ok||!m.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:m.value})},d=Ot(t,i,n,l,mt("react-dom").createPortal),t.effect(()=>d.dispose,"cost-meter: optional dsh-context integration");const y=t.get("slots"),C=()=>y.register({name:"shell.overlay",id:"cost-meter-context-intro",order:50},()=>e(qt,{manager:d,getLocale:l}));typeof y.inject=="function"&&t.effect(()=>y.inject("shell.overlay",C),"cost-meter: context preview prompt")}const r=y=>e(y.sessionId?$t:Ht,{...y,api:i,contextIntegration:d?{manager:d,getLocale:l}:null});return r.BillionCompatibilityNotice=jt,r.prefetch=y=>Gt(i,y),t.effect(()=>()=>nt.delete(i),"cost-meter: statistics cache cleanup"),r}return{mount:ia,prefetchStatistics:Gt,Statistics:Ht,SessionStatistics:$t,SessionDetail:dt,TurnInspection:Bt,ShareChart:Lt,ContextCosts:Je,BillionCompatibilityNotice:jt,ContextPrompt:qt,ContextPreview:ct,ContextIntegrationSettings:rt,createContextIntegration:Ot,contextCostBreakdown:zt,installContextCosts:Mt,CONTRIBUTION:Ct,parseContextCosts:tt,parseStatistics:Ze,parseDetail:et,parseInspection:We,dailyChartRows:At,requestStart:St,requestValue:Ee,requestFailure:It,showsPlaceholder:Ge,refreshKeyOf:Ve}}});
@@ -126,6 +126,25 @@ export function detectCodexSubscription(options = {}) {
126
126
  return detectSubscriptionPackage(CODEX_SUBSCRIPTION_PACKAGE, options)
127
127
  }
128
128
 
129
+ /** Current host runtime, including disabled parent groups. No credentials or requests. */
130
+ export function codexRuntimeEnabled(ctx) {
131
+ try {
132
+ const loader = typeof ctx?.get === 'function' ? ctx.get('loader') : ctx?.loader
133
+ if (typeof loader?.entries === 'function') {
134
+ for (const entry of loader.entries()) {
135
+ if (entry.options?.name !== CODEX_SUBSCRIPTION_PACKAGE && entry.fiber?.runtime?.name !== 'codex-subscription') continue
136
+ if (!entry.disabled && entry.options?.disabled !== true && entry.fiber?.state === 2) return true
137
+ }
138
+ return false
139
+ }
140
+ for (const runtime of ctx?.registry?.values?.() ?? []) {
141
+ if (runtime.name !== 'codex-subscription') continue
142
+ for (const fiber of runtime.fibers ?? []) if (fiber.state === 2 && !fiber.entry?.disabled) return true
143
+ }
144
+ } catch {}
145
+ return false
146
+ }
147
+
129
148
  /**
130
149
  * 统计账本中「按当前 plan 归属规则属于 codex」的全部历史用量。
131
150
  *
@@ -183,20 +202,22 @@ function planClassOf(ledger) {
183
202
  * @param ledger - 账本。
184
203
  * @param detection - detectCodexSubscription() 结果(整个插件生命周期复用)。
185
204
  */
186
- export function codexCompatStatus(ledger, detection) {
205
+ export function codexCompatStatus(ledger, detection, active = detection?.installed === true) {
187
206
  const info = detection !== null && typeof detection === 'object' ? detection : NOT_INSTALLED
188
207
  const installed = info.installed === true
208
+ const enabled = installed && active === true
189
209
  const historyAppliedAt = positiveOr0(ledger?.config?.codexCompatHistoryAppliedAt)
190
210
  const promptDismissed = ledger?.config?.codexCompatPromptDismissed === true
191
211
  return {
192
212
  installed,
213
+ enabled,
193
214
  version: typeof info.version === 'string' ? info.version : '',
194
215
  detection: ['package', 'profile', 'none'].includes(info.detection) ? info.detection : 'none',
195
216
  planClass: planClassOf(ledger),
196
217
  usage: codexUsageOf(ledger),
197
218
  historyAppliedAt,
198
219
  promptDismissed,
199
- promptDue: installed && !promptDismissed && historyAppliedAt === 0,
220
+ promptDue: enabled && !promptDismissed && historyAppliedAt === 0,
200
221
  }
201
222
  }
202
223