dsh-cost-meter 1.8.13 → 1.8.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -6
- package/README.zh-CN.md +8 -6
- package/docs/billing-statistics.md +4 -0
- package/docs/ledger-lock-recovery.md +45 -0
- package/lib/client.js +4 -4
- package/lib/client.statistics.js +2 -2
- package/lib/ledger-lock-owner.js +79 -0
- package/lib/ledger-persistence.js +12 -5
- package/package.json +2 -1
package/lib/client.statistics.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:
|
|
1
|
+
window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:At=>{const Rt=At("react"),{createElement:t,useState:k,useEffect:zt,Fragment:$}=Rt,jt=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],O=(a,l)=>l==="total"?a.cost:l==="plan"?Math.max(0,a.cost-a.apiCost):a.apiCost,ct=a=>a.input+a.cacheRead+a.cacheWrite+a.output,D=(a,l)=>l>0?(100*a/l).toFixed(1)+"%":"—",qt=(a,l)=>new Date(Date.parse(a)+l*864e5).toISOString().slice(0,10),it=a=>l=>{if(typeof l!==a||a==="number"&&!Number.isFinite(l))throw new Error("Invalid statistics "+a);return l},p=it("number"),d=it("string"),I=it("boolean"),J=a=>a===null?null:p(a),T=a=>l=>{if(!Array.isArray(l))throw new Error("Invalid statistics array");return l.map(a)},N=a=>l=>{if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Invalid statistics object");return Object.fromEntries(Object.entries(a).map(([c,o])=>[c,o(l[c])]))},B=Object.fromEntries(jt.map(a=>[a,p])),ft=N(B),bt=N({provider:d,model:d,bucket:d,tokens:p,rate:p,cost:p,priced:I,plan:I}),ot=a=>d(a??""),Et=N({sessionId:ot,kind:d,turn:J,step:J,provider:d,model:d,atMs:p,cost:p,apiCost:p,plan:I,priced:I,longContext:I,rows:T(bt)}),dt=N({from:d,to:d,retainedFrom:d,retainedTo:d,totals:ft,days:T(N({...B,date:d})),models:T(N({...B,key:d,provider:d,model:d,priced:I})),sessions:T(N({...B,id:d,title:d})),providers:T(d),modelOptions:T(d),sessionCount:p,offset:p,unassignedCost:p,unmodeledCost:p}),mt=N({found:I,cost:p,apiCost:p,rows:T(bt),calls:T(Et),totalCalls:p,offset:p,recorded:ft,agents:a=>T(N({...B,id:d,title:d}))(a??[]),kinds:T(N({...B,kind:d,unpriced:I})),turns:T(N({...B,sessionId:ot,turn:J,unpriced:I})),totalTurns:p,turnOffset:p,stepShares:N(Object.fromEntries(["cost","calls"].map(a=>[a,T(N({...B,sessionId:ot,turn:J,step:J,other:I,unpriced:I}))])))}),pt=N({found:I,turn:p,input:d,inputTruncated:I,totalTools:p,offset:p,tools:T(N({seq:p,step:J,name:d,callId:d,atMs:p,arguments:d,result:d,truncated:I,status:d}))}),vt=a=>{const l=N({sessionId:d,turn:p,offset:p})({...a,offset:a.offset??0});if(!l.sessionId||l.sessionId.length>512||![l.turn,l.offset].every(c=>Number.isSafeInteger(c)&&c>=0)||l.offset>1e7)throw new Error("Invalid turn inspection query");return l},yt=a=>{const l=N({from:d,to:d,provider:d,model:d,sessionId:d,basis:d,offset:p})(a);if(l.turnOffset=p(a.turnOffset??0),!["api","plan","total"].includes(l.basis)||![l.offset,l.turnOffset].every(c=>Number.isSafeInteger(c)&&c>=0&&c<=1e7))throw new Error("Invalid statistics query");return l},xt=(a,l)=>{const c={parse:l};return{mode:"strict",typeSymbol:"dsh-cost-meter#"+a,schema:c,create:()=>c}},kt={package:"dsh-cost-meter/statistics",descriptors:[["getBillingStatistics","BillingStatistics",dt],["getSessionBilling","SessionBilling",mt],["getTurnInspection","TurnInspection",pt,vt]].map(([a,l,c,o])=>({id:"dsh-cost-meter#costMeter/"+a,service:"costMeter",namespace:"costMeter",method:a,invocation:{kind:"direct"},parameters:[{name:"query",wire:"query",source:"json",codec:xt(o?"TurnInspectionQuery":"StatisticsQuery",o??yt)}],result:xt(l,c)}))},Bt=`
|
|
2
2
|
.cm-stat{--cm-accent:var(--dsw-alias-state-business-primary,#4d6bfe);--cm-plan:var(--dsw-alias-label-tertiary,#8b9099);--cm-muted:var(--dsw-alias-label-tertiary,#858a94);--cm-border:var(--dsw-alias-border-l3,#e9eaed);--cm-surface:var(--dsw-alias-bg-layer-1,#f7f8fa);color:var(--dsw-alias-label-primary,#25262b);font-family:var(--ds-font-family-sans,inherit);font-size:13px;line-height:1.55;container-type:inline-size}
|
|
3
3
|
.cm-stat *{box-sizing:border-box}.cm-stat h2,.cm-stat h3,.cm-stat p{margin:0}.cm-stat h2{font-size:18px;font-weight:600;letter-spacing:0}.cm-stat h3{font-size:14px;font-weight:500}
|
|
4
4
|
.cm-stat-head{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0 0 18px}.cm-stat-sub{font-size:12px;color:var(--cm-muted)}
|
|
@@ -20,4 +20,4 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
|
|
|
20
20
|
dialog:has(.cm-stat){padding:24px!important;border-color:var(--dsw-alias-border-l3,#e9eaed)!important;box-shadow:var(--dsw-elevation-prominent,0 20px 90px #0002)}dialog:has(.cm-stat)::backdrop{background:#0005}dialog:has(.cm-stat)>.cm-btn{border:0;border-radius:8px;background:transparent;font-size:20px;line-height:24px;width:28px;height:28px;padding:0;margin-left:12px}
|
|
21
21
|
@container(max-width:700px){.cm-stat-shares{grid-template-columns:1fr;gap:20px}.cm-stat-step-list{columns:1}.cm-stat-turn-toggle{align-items:flex-start}.cm-stat-turn-toggle>span:last-child{max-width:60%}.cm-stat-metric{padding:10px!important}.cm-stat-metric:nth-child(2){border:0}.cm-stat-page{gap:8px}}
|
|
22
22
|
@container(max-width:700px){.cm-stat-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.cm-stat-grid{grid-template-columns:1fr}.cm-stat-panel{padding:12px}.cm-stat-head{align-items:start}.cm-stat-controls label{flex:1}.cm-stat input,.cm-stat select{max-width:100%;width:100%}.cm-stat-value{font-size:23px}}
|
|
23
|
-
`;function it(e,r,i,m){const[c,n]=x({value:null,error:"",loading:!0}),d=JSON.stringify(i);return St(()=>{let s=!0;return n({value:null,error:"",loading:!0}),e[r](JSON.parse(d)).then(b=>{s&&n({value:b,error:"",loading:!1})},b=>{s&&n({value:null,error:String(b.message??b),loading:!1})}),()=>{s=!1}},[e,r,d,m]),c}const E=(e,r,i={})=>t("button",{type:"button",className:"cm-stat-btn",onClick:r,...i},e);function V({offset:e,count:r,size:i,onChange:m,text:c}){return t("div",{className:"cm-stat-page"},t("span",{className:"cm-stat-sub"},r?`${e+1}–${Math.min(e+i,r)} / ${r}`:"0"),E(c("上一页","Previous"),()=>m(Math.max(0,e-i)),{disabled:!e}),E(c("下一页","Next"),()=>m(e+i),{disabled:e+i>=r}))}function ft({rows:e,money:r,text:i,onSelect:m,label:c}){const n=Math.max(0,...e.map(s=>s.value)),d=e.reduce((s,b)=>s+b.value,0);return t("div",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c),t("span",{className:"cm-stat-sub"},i("最高 ","Peak ")+r(n)+" · "+i("合计 ","Total ")+r(d))),t("div",{className:"cm-stat-chart",role:"group","aria-label":c},e.map((s,b)=>t("button",{key:b,type:"button",className:"cm-stat-bar",title:s.label+" · "+r(s.value),"aria-label":s.label+" · "+r(s.value),onClick:()=>m(s)},t("span",{style:{height:n?Math.max(1,s.value/n*100)+"%":"0%",opacity:s.value?void 0:.2}})))),t("div",{className:"cm-stat-axis"},t("span",null,e[0]?.label),t("span",null,e.at(-1)?.label)))}function vt(e,r){const i=Math.max(1,Math.ceil(e.length/60)),m=[];for(let c=0;c<e.length;c+=i){const n=e.slice(c,c+i),d=n[0].date,s=n.at(-1).date;m.push({from:d,to:s,label:d===s?d:d+" – "+s,value:n.reduce((b,A)=>b+M(A,r),0)})}return m}function G({title:e,rows:r,total:i,format:m,text:c,columns:n=!1}){return t("section",{"aria-label":e},t("h3",null,e),i<=0?t("p",{className:"cm-stat-sub"},c("暂无可计算的占比","No measurable share yet")):t("ol",{className:"cm-stat-share-list"+(n?" cm-stat-step-list":"")},r.map((d,s)=>t("li",{key:s,"data-other":d.other||void 0},t("div",{className:"cm-stat-share-head"},t("span",null,d.label),t("span",{className:"cm-stat-share-value"},m(d.value)+(d.unpriced?" + ?":"")+" · "+D(d.value,i))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{className:"cm-stat-share-fill",style:{width:Math.min(100,100*d.value/i)+"%"}}))))))}function yt({api:e,sessionId:r,turn:i,revision:m,text:c}){const[n,d]=x(0),[s,b]=x(0),A=it(e,"getTurnInspection",{sessionId:r,turn:i,offset:n},m+":"+s);if(A.loading)return t("p",{className:"cm-stat-empty",role:"status"},c("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…"));if(A.error)return t("div",{className:"cm-stat-inspection"},t("p",{className:"cm-stat-error",role:"alert"},A.error),E(c("重试","Retry"),()=>b(k=>k+1)));const S=A.value;return S.found?t("div",{className:"cm-stat-inspection"},t("h4",null,c("本轮用户输入","User input for this turn")),S.input?t("pre",{className:"cm-stat-pre"},S.input):t("p",{className:"cm-stat-sub"},c("日志未记录本轮用户输入。","No user input is recorded for this turn.")),S.inputTruncated?t("p",{className:"cm-stat-truncated"},c("输入过长,此处显示前 16,000 个字符。","Showing the first 16,000 characters of this input.")):null,t("h4",null,c("工具调用","Tool calls")+" · "+S.totalTools),S.totalTools?null:t("p",{className:"cm-stat-sub"},c("这一轮没有工具调用记录。","No tool calls are recorded in this turn.")),S.tools.map(k=>t("details",{key:k.seq,className:"cm-stat-tool"},t("summary",null,t("span",null,(k.step==null?"":c("步骤 ","Step ")+k.step+" · ")+k.name),t("span",{className:"cm-stat-sub"},{complete:c("已完成","Completed"),error:c("调用失败","Failed"),pending:c("未记录结果","No recorded result")}[k.status])),t("h4",{style:{marginTop:12}},c("调用参数","Arguments")),t("pre",{className:"cm-stat-pre"},k.arguments),t("h4",null,c("返回结果","Result")),t("pre",{className:"cm-stat-pre"},k.result||c("没有可显示的文本结果","No text result is available")),k.truncated?t("p",{className:"cm-stat-truncated"},c("长内容显示前 16,000 个字符;完整内容保留在会话轨迹中。","Long content is limited to 16,000 characters here; the full content remains in the conversation trajectory.")):null)),t(V,{offset:n,count:S.totalTools,size:20,onChange:d,text:c}),t("p",{className:"cm-stat-sub"},c("这里显示整轮原始记录,不受上方模型或计费筛选影响。附件仅显示类型。","Shows the whole turn, independent of model and cost filters above. Attachments are represented by type."))):t("p",{className:"cm-stat-note"},c("这一轮的原始日志不可用。","Original records for this turn are unavailable."))}function xt({api:e,query:r,revision:i,money:m,formatTokens:c,text:n}){const[d,s]=x(0),[b,A]=x(-1),[S,k]=x(0),[I,X]=x(null),[O,$]=x("cost"),R=it(e,"getSessionBilling",{...r,offset:d,turnOffset:S},i),p=R.value,f=r.basis,U={input:n("输入","Input"),output:n("输出","Output"),cacheRead:n("缓存读取","Cache read"),cacheWrite:n("缓存写入","Cache write"),reasoning:n("推理","Reasoning")},J={model:n("模型调用","Model call"),compaction:n("上下文压缩","Compaction"),search:n("原生搜索","Native search")},L=a=>a==null?n("未标明轮次","Turn not recorded"):n("轮次 ","Turn ")+a;if(R.loading)return t("p",{className:"cm-stat-empty",role:"status"},n("正在读取本对话的用量明细…","Loading this conversation’s usage records…"));if(R.error)return t("p",{className:"cm-stat-error",role:"alert"},R.error);if(!p.found)return t("p",{className:"cm-stat-note"},n("没有可用的调用日志。上方账本统计仍然有效;明细不会按零费用处理。","Call logs are unavailable. The ledger totals above remain valid; missing details do not mean zero cost."));const H=a=>!a||a===r.sessionId?n("主会话","Main conversation"):n("子代理 ","Subagent ")+((p.agents??[]).find(h=>h.id===a)?.title||a).slice(0,80),j=a=>JSON.stringify([a.sessionId||r.sessionId,a.turn]),Q=a=>((p.agents?.length??0)>1?H(a.sessionId)+" · ":"")+L(a.turn),ot=a=>f==="total"||(f==="plan"?a.plan:!a.plan),W=Object.keys(U).map(a=>{const h=p.rows.filter(C=>C.bucket===a&&ot(C));return{bucket:a,tokens:h.reduce((C,v)=>C+v.tokens,0),cost:h.reduce((C,v)=>C+v.cost,0),unpriced:h.some(C=>!C.priced)}}),z=M(p,f),B=M(p.recorded,f),Y=Math.abs(z-B)>Math.max(1e-8,Math.abs(B)*1e-8)||p.totalCalls!==p.recorded.calls,_=(a,h)=>t("p",{key:h,className:"cm-stat-sub"},U[a.bucket]+": "+a.tokens.toLocaleString()+" × "+(a.priced?m(a.rate):"?")+" / 1,000,000 = "+(a.priced?m(a.cost):"?")),g=(a,h,C)=>t("div",{className:"cm-stat-scroll",style:{marginTop:20}},t("h3",null,a),t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[a,n("调用次数","Calls"),n("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",n("Plan 等值","Plan equivalent")].map(v=>t("th",{key:v},v)))),t("tbody",null,h.map((v,K)=>t("tr",{key:K},t("td",null,C(v)),t("td",null,v.calls),t("td",null,[v.input,v.cacheRead+v.cacheWrite,v.output].map(c).join(" / ")),t("td",null,m(v.apiCost)+(v.unpriced?" + ?":"")),t("td",null,m(Math.max(0,v.cost-v.apiCost))+(v.unpriced?" + ?":"")))))));return t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,n("单对话费用明细","Conversation cost details")),t("span",{className:"cm-stat-sub"},(p.agents?.length??0)>1?n("包含子代理及其后代","Includes subagents and their descendants"):n("本会话自身的调用","Own conversation calls"))),t("details",{className:"cm-stat-help"},t("summary",null,n("统计口径","How these amounts are calculated")),t("p",null,n("明细按日志中的调用时间、用量和当前配置的历史价格规则计算。上方汇总采用已入账金额;调整价格后两者可能不同。","Details use logged usage and call times with the currently configured historical price rules. The summary above uses recorded ledger amounts; changing prices can produce a difference."))),Y?t("p",{className:"cm-stat-note"},n("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+m(B)+" / "+p.recorded.calls+n(" 次;明细 "," calls; details ")+m(z)+" / "+p.totalCalls+n(" 次。"," calls.")):null,(p.agents?.length??0)>1?g(n("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),p.agents,a=>H(a.id)):null,t("div",{className:"cm-stat-shares"},t(G,{title:n("费用构成","Cost composition"),rows:W.map(a=>({label:U[a.bucket],value:a.cost,unpriced:a.unpriced})),total:z,format:m,text:n}),t(G,{title:n("调用类型占比 · 次数","Call type share · count"),rows:p.kinds.map(a=>({label:J[a.kind]??a.kind,value:a.calls})),total:p.totalCalls,format:a=>a.toLocaleString()+n(" 次"," calls"),text:n})),t("section",{className:"cm-stat-breakdown"},t("div",{className:"cm-stat-panel-head"},t("h3",null,n("各步骤占比","Share by step")),t("div",{className:"cm-stat-periods"},...[["cost",n("费用","Cost")],["calls",n("调用次数","Calls")]].map(([a,h])=>E(h,()=>$(a),{key:a,"aria-pressed":O===a})))),t(G,{title:O==="cost"?n("费用占比 · 全部调用","Cost share · all calls"):n("调用次数占比 · 全部调用","Call count share · all calls"),rows:(p.stepShares?.[O]??[]).map(a=>({label:a.other?n("其余步骤合计","All other steps"):Q(a)+(a.step==null?"":n(" · 步骤 "," · step ")+a.step),value:O==="cost"?M(a,f):a.calls,unpriced:O==="cost"&&a.unpriced,other:a.other})),total:O==="cost"?z:p.totalCalls,format:O==="cost"?m:a=>a.toLocaleString(),text:n,columns:!0}),t("p",{className:"cm-stat-sub",style:{marginTop:12}},n("分母包含所选范围的全部调用,跨页合计。显示前 12 项,其余合并;无步骤编号的调用单列。工具本身不额外算作模型调用。","Shares use all calls in the selected range, across pages. Top 12 entries are shown; the rest are combined. Missing step IDs remain explicit. Tools are not counted as extra model calls."))),t("details",{className:"cm-stat-help"},t("summary",null,n("单价与 Token 明细","Rates and token details")),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[n("费用构成","Cost component"),"Tokens",n("费用","Cost"),n("费用占比","Cost share")].map(a=>t("th",{key:a},a)))),t("tbody",null,W.map(a=>t("tr",{key:a.bucket},t("td",null,U[a.bucket]),t("td",null,a.tokens.toLocaleString()),t("td",null,m(a.cost)+(a.unpriced?" + ?":"")),t("td",null,D(a.cost,z))))))),t("p",{className:"cm-stat-sub",style:{marginTop:10}},n("推理 Token 可能包含在输出中;单价为 0 时不另收推理费。未定价用量显示 ?。","Reasoning tokens may overlap output; a zero reasoning rate adds no separate charge. Unpriced usage is marked ?.")),g(n("按调用类型统计","Cost by call type"),p.kinds,a=>J[a.kind]??a.kind)),t("section",{className:"cm-stat-turns"},t("div",{className:"cm-stat-panel-head"},t("h3",null,n("按轮次统计","Cost by turn")),t("span",{className:"cm-stat-sub"},n("展开查看输入和工具调用","Expand to inspect input and tool calls"))),p.turns.map(a=>t("div",{key:j(a),className:"cm-stat-turn"},t("button",{type:"button",className:"cm-stat-turn-toggle",disabled:a.turn==null,"aria-expanded":a.turn!=null&&I===j(a),onClick:()=>X(h=>h===j(a)?null:j(a))},t("span",null,(a.turn==null?"":I===j(a)?"⌄ ":"› ")+Q(a)),t("span",null,a.calls+n(" 次调用"," calls")+" · "+c(et(a))+" tok · "+m(M(a,f))+(a.unpriced?" + ?":""))),a.turn!=null&&I===j(a)?t(yt,{key:j(a),api:e,sessionId:a.sessionId||r.sessionId,turn:a.turn,revision:i,text:n}):null))),t("p",{className:"cm-stat-sub"},n("轮次沿用日志编号;未记录轮次的调用单列。每轮包含其全部调用,跨调用分页也不会拆分。","Turn numbers come from the log; calls without one are listed separately. Each turn includes all its calls, across call pages.")),t(V,{offset:S,count:p.totalTurns,size:25,onChange:a=>{k(a),X(null)},text:n}),t("div",{style:{marginTop:24}},t(ft,{rows:p.calls.map((a,h)=>({label:"#"+(d+h+1),index:h,value:M(a,f)})),money:m,text:n,label:n("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:a=>{A(a.index),document.getElementById("cm-stat-call-"+a.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),p.calls.map((a,h)=>t("details",{key:h,id:"cm-stat-call-"+h,className:"cm-stat-call",open:b===h,onToggle:C=>{!C.currentTarget.open&&b===h&&A(-1)}},t("summary",null,"#"+(d+h+1)+" · "+Q(a)+(a.step==null?"":n(" / 步骤 "," / step ")+a.step)+" · "+(J[a.kind]??a.kind)+" · "+a.provider+" / "+a.model+" · "+(a.plan?"Plan ":"API ")+(a.priced?m(a.cost):"?")+(a.longContext?n(" · 长上下文价"," · long-context rate"):"")),t("p",{className:"cm-stat-sub"},new Date(a.atMs).toLocaleString()),a.rows.map(_))),t(V,{offset:d,count:p.totalCalls,size:50,onChange:a=>{s(a),A(-1)},text:n}))}function Nt({state:e,api:r,sessionId:i="",formatMoneyUsd:m,formatTokens:c,resolveLocale:n}){const d=n?n(e.config)==="en":e.config.locale==="en"||e.config.locale!=="zh"&&(e.config.activeLocale||e.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",s=(l,P)=>d?P:l,[b,A]=x(i?"all":"week"),[S,k]=x(null),[I,X]=x({id:i,title:i}),[O,$]=x(""),[R,p]=x(""),[f,U]=x(e.config.showTotalWithPlan?"total":"api"),[J,L]=x(0),[H,j]=x(0),[Q,ot]=x(!1),W=e.meta.dayKey||new Date().toISOString().slice(0,10),z=b==="all"?"":b==="custom"?S?.from||W:Tt(W,b==="week"?-6:b==="month"?-29:0),B=b==="custom"&&S?.to||W,Y={from:z,to:B,provider:O,model:R,basis:f,sessionId:I.id,offset:J},_=it(r,"getBillingStatistics",Y,H+":"+e.meta.now),g=_.value,a=l=>m(l,{...e.config,decimals:Math.max(l!==0&&Math.abs(l)<.01?8:4,e.config.decimals??2)}),h=l=>{A(l),L(0)},C=l=>{X(l),L(0),$(""),p("")},v=f==="total"?s("API + Plan 等值","API + Plan equivalent"):f==="plan"?s("Plan 等值","Plan equivalent"):s("API 费用","API cost"),K=(l,P,mt,zt)=>t("label",null,l,t("select",{value:P,onChange:tt=>{mt(tt.target.value),L(0)}},zt.map(([tt,Rt])=>t("option",{key:tt,value:tt},Rt)))),Ot={input:s("未缓存输入","Uncached input"),cacheRead:s("缓存读取","Cache read"),cacheWrite:s("缓存写入","Cache write"),output:s("输出","Output")},kt=(l,P)=>t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,l)),P),y=g?.totals,Z=(l,P,mt)=>t("div",{className:"cm-stat-metric",key:l},t("div",{className:"cm-stat-sub"},l),t("div",{className:"cm-stat-value"},P),t("div",{className:"cm-stat-sub"},mt));return t("div",{className:"cm-stat"},t("style",null,Mt),t("header",{className:"cm-stat-head"},t("div",null,t("h2",null,s("计费统计","Cost statistics")),t("p",{className:"cm-stat-sub"},I.id?s("单对话 · ","Conversation · ")+(I.title===I.id&&g?.sessions[0]?.title||I.title):s("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),E(s("刷新","Refresh"),()=>j(l=>l+1))),I.id?E(s("← 全部对话","← All conversations"),()=>C({id:"",title:""})):null,t("div",{className:"cm-stat-controls"},t("div",{className:"cm-stat-periods"},...[["today",s("今天","Today")],["week",s("近 7 天","Last 7 days")],["month",s("近 30 天","Last 30 days")],["all",s("全部记录","All retained")],["custom",s("自定义","Custom")]].map(([l,P])=>E(P,()=>h(l),{key:l,"aria-pressed":b===l})))),b==="custom"?t("div",{className:"cm-stat-controls"},...["from","to"].map(l=>t("label",{key:l},l==="from"?s("开始日期","From"):s("结束日期","To"),t("input",{type:"date",value:l==="from"?z:B,onChange:P=>{k({from:z,to:B,[l]:P.target.value}),L(0)}})))):null,t("div",{className:"cm-stat-controls"},K(s("计费口径","Cost basis"),f,U,[["api",s("API 费用","API cost")],["plan",s("Plan 等值","Plan equivalent")],["total",s("API + Plan 等值","API + Plan equivalent")]]),K(s("提供商","Provider"),O,l=>{$(l),p("")},[["",s("全部提供商","All providers")],...[...new Set([O,...g?.providers??[]])].filter(Boolean).map(l=>[l,l])]),K(s("模型","Model"),R,p,[["",s("全部模型","All models")],...[...new Set([R,...g?.modelOptions??[]])].filter(Boolean).map(l=>[l,l])])),t("details",{className:"cm-stat-help"},t("summary",null,s("计费说明","About billing")),t("p",null,s("按宿主时区归日:","Days use the host timezone: ")+(e.meta.timezone||"UTC")+" · "+s("API 金额是按已记录用量和配置单价计算的估算;Plan 为订阅用量的 API 等值,不是订阅账单。外部导入用量在原概览中单列。","API amounts estimate recorded usage at configured rates; Plan is API-equivalent usage, not the subscription invoice. External usage remains separate in Overview."))),_.loading?t("p",{className:"cm-stat-empty",role:"status"},s("加载统计…","Loading statistics…")):_.error?t("p",{className:"cm-stat-error",role:"alert"},_.error):g?t(at,null,t("p",{className:"cm-stat-sub",style:{marginTop:8}},g.from+" – "+g.to+(g.retainedFrom?" · "+s("账本保留范围 ","Retained ledger ")+g.retainedFrom+" – "+g.retainedTo:"")),t("div",{className:"cm-stat-metrics"},Z(s("API 费用","API cost"),a(y.apiCost),s("已入账估算","Recorded estimate")),Z(s("Plan 等值费用","Plan equivalent"),a(Math.max(0,y.cost-y.apiCost)),s("不代表实际扣款","Not an actual debit")),Z(s("调用次数","Calls"),y.calls.toLocaleString(),g.sessionCount+s(" 个对话 · 平均 "," conversations · average ")+a(y.calls?M(y,f)/y.calls:0)),Z(s("缓存命中率","Cache hit rate"),D(y.cacheRead,y.input+y.cacheRead+y.cacheWrite),c(et(y))+" Tokens")),I.id?t(xt,{key:JSON.stringify([I.id,z,B,O,R,f]),api:r,query:{...Y,from:g.from,to:g.to,offset:0},revision:H,money:a,formatTokens:c,text:s}):null,g.models.some(l=>!l.priced)?t("p",{className:"cm-stat-note"},s("部分模型当前未配置价格,金额可能不完整;未定价不等于免费。","Some models have no configured price. Amounts may be incomplete; unpriced usage is not free.")):null,!y.calls&&!y.cost?t("p",{className:"cm-stat-empty"},s("所选范围没有已记录的用量。","No recorded usage in this range.")):null,t("section",{className:"cm-stat-panel"},t(ft,{rows:vt(g.days,f),money:a,text:s,label:s("费用趋势 · ","Cost over time · ")+v,onSelect:l=>{k({from:l.from,to:l.to}),h("custom")}}),t("p",{className:"cm-stat-sub",style:{marginTop:12}},s("点击柱形查看该日期范围。长区间按相邻日期合并,保留全部金额。","Select a bar to inspect its date range. Long ranges group adjacent days without dropping costs."))),t("div",{className:"cm-stat-grid"},kt(s("模型费用排行","Cost by model"),t(at,null,t("ol",{className:"cm-stat-rank"},(Q?g.models:g.models.slice(0,8)).map(l=>t("li",{key:l.key},t("button",{type:"button",onClick:()=>{$(l.provider),p(l.model),L(0)},title:l.key},t("div",{className:"cm-stat-rankline"},t("span",null,l.model),t("span",{className:"cm-stat-number"},a(M(l,f))+(l.priced?"":" + ?"))),t("div",{className:"cm-stat-sub"},l.provider+" · "+l.calls+s(" 次 · "," calls · ")+D(M(l,f),M(y,f))),t("div",{className:"cm-stat-track"},t("span",{style:{width:D(M(l,f),M(y,f))}}))))),g.models.length>8?E(Q?s("收起","Show less"):s("显示全部模型","Show all models"),()=>ot(l=>!l)):null,g.unmodeledCost>1e-8?t("p",{className:"cm-stat-note"},s("历史未分配到模型的费用:","Historical cost without a model: ")+a(g.unmodeledCost)):null)),kt(s("Token 构成","Token composition"),t(at,null,t("ol",{className:"cm-stat-rank"},Object.entries(Ot).map(([l,P])=>t("li",{key:l},t("div",{className:"cm-stat-rankline"},t("span",null,P),t("span",{className:"cm-stat-number"},c(y[l]))),t("div",{className:"cm-stat-track"},t("span",{style:{width:D(y[l],et(y)),background:l.startsWith("cache")?"var(--cm-plan)":void 0}}))))),t("p",{className:"cm-stat-note"},s("这里展示 Token 数量占比,不是费用占比。缓存写入计入输入分母,不算缓存命中。","These are token shares, not cost shares. Cache writes count as input, not cache hits.")),t("p",{className:"cm-stat-sub"},s("单独上报的推理 Token:","Reported reasoning tokens: ")+c(y.reasoning))))),I.id?null:t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,s("对话费用排行","Cost by conversation")),t("span",{className:"cm-stat-sub"},e.config.includeSubagentCost?s("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):s("点击对话查看明细","Select a conversation for details"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[s("对话","Conversation"),s("调用","Calls"),"API",s("Plan 等值","Plan equivalent"),s("缓存命中","Cache hits")].map(l=>t("th",{key:l},l)))),t("tbody",null,g.sessions.map(l=>t("tr",{key:l.id},t("td",null,t("button",{type:"button",title:l.id,onClick:()=>C({id:l.id,title:l.title})},l.title)),t("td",null,l.calls.toLocaleString()),t("td",null,a(l.apiCost)),t("td",null,a(Math.max(0,l.cost-l.apiCost))),t("td",null,D(l.cacheRead,l.input+l.cacheRead+l.cacheWrite))))))),g.unassignedCost>1e-8?t("p",{className:"cm-stat-note"},s("未关联对话的费用:","Cost not linked to a conversation: ")+a(g.unassignedCost)):null,t(V,{offset:J,count:g.sessionCount,size:25,onChange:L,text:s})))):null)}async function At(e){const r=await e.get("remote").$mount(bt);e.effect(()=>()=>r(),"cost-meter: statistics contribution");const i=e.get("remote.costMeter"),m=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection"].map(c=>[c,async n=>{const d=await i[c]((c==="getTurnInspection"?ut:gt)(n));if(!d?.ok)throw new Error(d?.error?.message||"Statistics request failed");return{getBillingStatistics:lt,getSessionBilling:rt,getTurnInspection:ct}[c](d.value)}]));return c=>t(Nt,{...c,api:m})}return{mount:At,Statistics:Nt,SessionDetail:xt,TurnInspection:yt,ShareChart:G,CONTRIBUTION:bt,parseStatistics:lt,parseDetail:rt,parseInspection:ct,dailyChartRows:vt}}});
|
|
23
|
+
`;function Nt(a,l){return a.key===l?{...a,error:"",failed:!1,loading:!0}:{value:null,error:"",failed:!1,loading:!0,key:l}}function Ct(a,l){return{value:l,error:"",failed:!1,loading:!1,key:a}}function wt(a,l,c){return{value:a.key===l?a.value:null,error:String(c?.message??c),failed:!0,loading:!1,key:l}}function tt(a){return!a.value&&(a.loading||a.failed===!0)}function St(a,l){const c=[a.meta.dayKey,a.total?.calls,a.total?.cost,a.total?.apiCost,a.today?.calls,a.today?.cost,a.today?.apiCost].join(":"),o=JSON.stringify([a.config.prices,a.config.priceOverrides,a.config.priceMatch,a.config.planBilling,a.config.codingPlans,a.config.goQuota?.enabled,a.config.peakEnabled,a.config.peakEffectiveAt,a.config.peakWindows,a.config.peakHolidays,a.config.fetchedAt,a.config.priceSource,a.config.currency,a.config.exchangeRate,a.config.decimals,a.config.showTotalWithPlan,a.config.includeSubagentCost]);return l+":"+c+":"+o}function ut(a,l,c,o){const[i,n]=k({value:null,error:"",failed:!1,loading:!0,key:null}),m=JSON.stringify(c);return zt(()=>{let s=!0;return n(h=>Nt(h,m)),a[l](JSON.parse(m)).then(h=>{s&&n(Ct(m,h))},h=>{s&&n(S=>wt(S,m,h))}),()=>{s=!1}},[a,l,m,o]),i}const E=(a,l,c={})=>t("button",{type:"button",className:"cm-stat-btn",onClick:l,...c},a),H=a=>t("p",{className:"cm-stat-error",role:"alert"},a);function at({offset:a,count:l,size:c,onChange:o,text:i}){return t("div",{className:"cm-stat-page"},t("span",{className:"cm-stat-sub"},l?`${a+1}–${Math.min(a+c,l)} / ${l}`:"0"),E(i("上一页","Previous"),()=>o(Math.max(0,a-c)),{disabled:!a}),E(i("下一页","Next"),()=>o(a+c),{disabled:a+c>=l}))}function It({rows:a,money:l,text:c,onSelect:o,label:i}){const n=Math.max(0,...a.map(s=>s.value)),m=a.reduce((s,h)=>s+h.value,0);return t("div",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,i),t("span",{className:"cm-stat-sub"},c("最高 ","Peak ")+l(n)+" · "+c("合计 ","Total ")+l(m))),t("div",{className:"cm-stat-chart",role:"group","aria-label":i},a.map((s,h)=>t("button",{key:h,type:"button",className:"cm-stat-bar",title:s.label+" · "+l(s.value),"aria-label":s.label+" · "+l(s.value),onClick:()=>o(s)},t("span",{style:{height:n?Math.max(1,s.value/n*100)+"%":"0%",opacity:s.value?void 0:.2}})))),t("div",{className:"cm-stat-axis"},t("span",null,a[0]?.label),t("span",null,a.at(-1)?.label)))}function Tt(a,l){const c=Math.max(1,Math.ceil(a.length/60)),o=[];for(let i=0;i<a.length;i+=c){const n=a.slice(i,i+c),m=n[0].date,s=n.at(-1).date;o.push({from:m,to:s,label:m===s?m:m+" – "+s,value:n.reduce((h,S)=>h+O(S,l),0)})}return o}function et({title:a,rows:l,total:c,format:o,text:i,columns:n=!1}){return t("section",{"aria-label":a},t("h3",null,a),c<=0?t("p",{className:"cm-stat-sub"},i("暂无可计算的占比","No measurable share yet")):t("ol",{className:"cm-stat-share-list"+(n?" cm-stat-step-list":"")},l.map((m,s)=>t("li",{key:s,"data-other":m.other||void 0},t("div",{className:"cm-stat-share-head"},t("span",null,m.label),t("span",{className:"cm-stat-share-value"},o(m.value)+(m.unpriced?" + ?":"")+" · "+D(m.value,c))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{className:"cm-stat-share-fill",style:{width:Math.min(100,100*m.value/c)+"%"}}))))))}function Pt({api:a,sessionId:l,turn:c,revision:o,text:i}){const[n,m]=k(0),[s,h]=k(0),S=ut(a,"getTurnInspection",{sessionId:l,turn:c,offset:n},o+":"+s),F=()=>E(i("重试","Retry"),()=>h(b=>b+1)),K=t("div",{className:"cm-stat-inspection"},H(S.error),F()),C=S.failed?K:null;if(tt(S))return S.loading?t("p",{className:"cm-stat-empty",role:"status"},i("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…")):K;const P=S.value;return P.found?t("div",{className:"cm-stat-inspection"},C,t("h4",null,i("本轮用户输入","User input for this turn")),P.input?t("pre",{className:"cm-stat-pre"},P.input):t("p",{className:"cm-stat-sub"},i("日志未记录本轮用户输入。","No user input is recorded for this turn.")),P.inputTruncated?t("p",{className:"cm-stat-truncated"},i("输入过长,此处显示前 16,000 个字符。","Showing the first 16,000 characters of this input.")):null,t("h4",null,i("工具调用","Tool calls")+" · "+P.totalTools),P.totalTools?null:t("p",{className:"cm-stat-sub"},i("这一轮没有工具调用记录。","No tool calls are recorded in this turn.")),P.tools.map(b=>t("details",{key:b.seq,className:"cm-stat-tool"},t("summary",null,t("span",null,(b.step==null?"":i("步骤 ","Step ")+b.step+" · ")+b.name),t("span",{className:"cm-stat-sub"},{complete:i("已完成","Completed"),error:i("调用失败","Failed"),pending:i("未记录结果","No recorded result")}[b.status])),t("h4",{style:{marginTop:12}},i("调用参数","Arguments")),t("pre",{className:"cm-stat-pre"},b.arguments),t("h4",null,i("返回结果","Result")),t("pre",{className:"cm-stat-pre"},b.result||i("没有可显示的文本结果","No text result is available")),b.truncated?t("p",{className:"cm-stat-truncated"},i("长内容显示前 16,000 个字符;完整内容保留在会话轨迹中。","Long content is limited to 16,000 characters here; the full content remains in the conversation trajectory.")):null)),t(at,{offset:n,count:P.totalTools,size:20,onChange:m,text:i}),t("p",{className:"cm-stat-sub"},i("这里显示整轮原始记录,不受上方模型或计费筛选影响。附件仅显示类型。","Shows the whole turn, independent of model and cost filters above. Attachments are represented by type."))):t($,null,C,t("p",{className:"cm-stat-note"},i("这一轮的原始日志不可用。","Original records for this turn are unavailable.")))}function Mt({api:a,query:l,revision:c,money:o,formatTokens:i,text:n}){const[m,s]=k(0),[h,S]=k(-1),[F,K]=k(0),[C,P]=k(null),[b,V]=k("cost"),[Q,U]=k(0),x=ut(a,"getSessionBilling",{...l,offset:m,turnOffset:F},c+":"+Q),g=x.value,j=l.basis,z={input:n("输入","Input"),output:n("输出","Output"),cacheRead:n("缓存读取","Cache read"),cacheWrite:n("缓存写入","Cache write"),reasoning:n("推理","Reasoning")},G={model:n("模型调用","Model call"),compaction:n("上下文压缩","Compaction"),search:n("原生搜索","Native search")},gt=e=>e==null?n("未标明轮次","Turn not recorded"):n("轮次 ","Turn ")+e;if(tt(x))return x.loading?t("p",{className:"cm-stat-empty",role:"status"},n("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):H(x.error);const X=x.failed?t("div",null,H(x.error),E(n("重试","Retry"),()=>U(e=>e+1))):null;if(!g.found)return t($,null,X,t("p",{className:"cm-stat-note"},n("没有可用的调用日志。上方账本统计仍然有效;明细不会按零费用处理。","Call logs are unavailable. The ledger totals above remain valid; missing details do not mean zero cost.")));const st=e=>!e||e===l.sessionId?n("主会话","Main conversation"):n("子代理 ","Subagent ")+((g.agents??[]).find(f=>f.id===e)?.title||e).slice(0,80),A=e=>JSON.stringify([e.sessionId||l.sessionId,e.turn]),L=e=>((g.agents?.length??0)>1?st(e.sessionId)+" · ":"")+gt(e.turn),_=e=>j==="total"||(j==="plan"?e.plan:!e.plan),Y=Object.keys(z).map(e=>{const f=g.rows.filter(w=>w.bucket===e&&_(w));return{bucket:e,tokens:f.reduce((w,v)=>w+v.tokens,0),cost:f.reduce((w,v)=>w+v.cost,0),unpriced:f.some(w=>!w.priced)}}),W=O(g,j),q=O(g.recorded,j),u=Math.abs(W-q)>Math.max(1e-8,Math.abs(q)*1e-8)||g.totalCalls!==g.recorded.calls,R=(e,f)=>t("p",{key:f,className:"cm-stat-sub"},z[e.bucket]+": "+e.tokens.toLocaleString()+" × "+(e.priced?o(e.rate):"?")+" / 1,000,000 = "+(e.priced?o(e.cost):"?")),Z=(e,f,w)=>t("div",{className:"cm-stat-scroll",style:{marginTop:20}},t("h3",null,e),t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[e,n("调用次数","Calls"),n("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",n("Plan 等值","Plan equivalent")].map(v=>t("th",{key:v},v)))),t("tbody",null,f.map((v,nt)=>t("tr",{key:nt},t("td",null,w(v)),t("td",null,v.calls),t("td",null,[v.input,v.cacheRead+v.cacheWrite,v.output].map(i).join(" / ")),t("td",null,o(v.apiCost)+(v.unpriced?" + ?":"")),t("td",null,o(Math.max(0,v.cost-v.apiCost))+(v.unpriced?" + ?":"")))))));return t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,n("单对话费用明细","Conversation cost details")),t("span",{className:"cm-stat-sub"},(g.agents?.length??0)>1?n("包含子代理及其后代","Includes subagents and their descendants"):n("本会话自身的调用","Own conversation calls"))),X,t("details",{className:"cm-stat-help"},t("summary",null,n("统计口径","How these amounts are calculated")),t("p",null,n("明细按日志中的调用时间、用量和当前配置的历史价格规则计算。上方汇总采用已入账金额;调整价格后两者可能不同。","Details use logged usage and call times with the currently configured historical price rules. The summary above uses recorded ledger amounts; changing prices can produce a difference."))),u?t("p",{className:"cm-stat-note"},n("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+o(q)+" / "+g.recorded.calls+n(" 次;明细 "," calls; details ")+o(W)+" / "+g.totalCalls+n(" 次。"," calls.")):null,(g.agents?.length??0)>1?Z(n("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),g.agents,e=>st(e.id)):null,t("div",{className:"cm-stat-shares"},t(et,{title:n("费用构成","Cost composition"),rows:Y.map(e=>({label:z[e.bucket],value:e.cost,unpriced:e.unpriced})),total:W,format:o,text:n}),t(et,{title:n("调用类型占比 · 次数","Call type share · count"),rows:g.kinds.map(e=>({label:G[e.kind]??e.kind,value:e.calls})),total:g.totalCalls,format:e=>e.toLocaleString()+n(" 次"," calls"),text:n})),t("section",{className:"cm-stat-breakdown"},t("div",{className:"cm-stat-panel-head"},t("h3",null,n("各步骤占比","Share by step")),t("div",{className:"cm-stat-periods"},...[["cost",n("费用","Cost")],["calls",n("调用次数","Calls")]].map(([e,f])=>E(f,()=>V(e),{key:e,"aria-pressed":b===e})))),t(et,{title:b==="cost"?n("费用占比 · 全部调用","Cost share · all calls"):n("调用次数占比 · 全部调用","Call count share · all calls"),rows:(g.stepShares?.[b]??[]).map(e=>({label:e.other?n("其余步骤合计","All other steps"):L(e)+(e.step==null?"":n(" · 步骤 "," · step ")+e.step),value:b==="cost"?O(e,j):e.calls,unpriced:b==="cost"&&e.unpriced,other:e.other})),total:b==="cost"?W:g.totalCalls,format:b==="cost"?o:e=>e.toLocaleString(),text:n,columns:!0}),t("p",{className:"cm-stat-sub",style:{marginTop:12}},n("分母包含所选范围的全部调用,跨页合计。显示前 12 项,其余合并;无步骤编号的调用单列。工具本身不额外算作模型调用。","Shares use all calls in the selected range, across pages. Top 12 entries are shown; the rest are combined. Missing step IDs remain explicit. Tools are not counted as extra model calls."))),t("details",{className:"cm-stat-help"},t("summary",null,n("单价与 Token 明细","Rates and token details")),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[n("费用构成","Cost component"),"Tokens",n("费用","Cost"),n("费用占比","Cost share")].map(e=>t("th",{key:e},e)))),t("tbody",null,Y.map(e=>t("tr",{key:e.bucket},t("td",null,z[e.bucket]),t("td",null,e.tokens.toLocaleString()),t("td",null,o(e.cost)+(e.unpriced?" + ?":"")),t("td",null,D(e.cost,W))))))),t("p",{className:"cm-stat-sub",style:{marginTop:10}},n("推理 Token 可能包含在输出中;单价为 0 时不另收推理费。未定价用量显示 ?。","Reasoning tokens may overlap output; a zero reasoning rate adds no separate charge. Unpriced usage is marked ?.")),Z(n("按调用类型统计","Cost by call type"),g.kinds,e=>G[e.kind]??e.kind)),t("section",{className:"cm-stat-turns"},t("div",{className:"cm-stat-panel-head"},t("h3",null,n("按轮次统计","Cost by turn")),t("span",{className:"cm-stat-sub"},n("展开查看输入和工具调用","Expand to inspect input and tool calls"))),g.turns.map(e=>t("div",{key:A(e),className:"cm-stat-turn"},t("button",{type:"button",className:"cm-stat-turn-toggle",disabled:e.turn==null,"aria-expanded":e.turn!=null&&C===A(e),onClick:()=>P(f=>f===A(e)?null:A(e))},t("span",null,(e.turn==null?"":C===A(e)?"⌄ ":"› ")+L(e)),t("span",null,e.calls+n(" 次调用"," calls")+" · "+i(ct(e))+" tok · "+o(O(e,j))+(e.unpriced?" + ?":""))),e.turn!=null&&C===A(e)?t(Pt,{key:A(e),api:a,sessionId:e.sessionId||l.sessionId,turn:e.turn,revision:c,text:n}):null))),t("p",{className:"cm-stat-sub"},n("轮次沿用日志编号;未记录轮次的调用单列。每轮包含其全部调用,跨调用分页也不会拆分。","Turn numbers come from the log; calls without one are listed separately. Each turn includes all its calls, across call pages.")),t(at,{offset:F,count:g.totalTurns,size:25,onChange:e=>{K(e),P(null)},text:n}),t("div",{style:{marginTop:24}},t(It,{rows:g.calls.map((e,f)=>({label:"#"+(m+f+1),index:f,value:O(e,j)})),money:o,text:n,label:n("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:e=>{S(e.index),document.getElementById("cm-stat-call-"+e.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),g.calls.map((e,f)=>t("details",{key:f,id:"cm-stat-call-"+f,className:"cm-stat-call",open:h===f,onToggle:w=>{!w.currentTarget.open&&h===f&&S(-1)}},t("summary",null,"#"+(m+f+1)+" · "+L(e)+(e.step==null?"":n(" / 步骤 "," / step ")+e.step)+" · "+(G[e.kind]??e.kind)+" · "+e.provider+" / "+e.model+" · "+(e.plan?"Plan ":"API ")+(e.priced?o(e.cost):"?")+(e.longContext?n(" · 长上下文价"," · long-context rate"):"")),t("p",{className:"cm-stat-sub"},new Date(e.atMs).toLocaleString()),e.rows.map(R))),t(at,{offset:m,count:g.totalCalls,size:50,onChange:e=>{s(e),S(-1)},text:n}))}function Ot({state:a,api:l,sessionId:c="",formatMoneyUsd:o,formatTokens:i,resolveLocale:n}){const m=n?n(a.config)==="en":a.config.locale==="en"||a.config.locale!=="zh"&&(a.config.activeLocale||a.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",s=(r,M)=>m?M:r,[h,S]=k(c?"all":"week"),[F,K]=k(null),[C,P]=k({id:c,title:c}),[b,V]=k(""),[Q,U]=k(""),[x,g]=k(a.config.showTotalWithPlan?"total":"api"),[j,z]=k(0),[G,gt]=k(0),[X,st]=k(!1),A=a.meta.dayKey||new Date().toISOString().slice(0,10),L=h==="all"?"":h==="custom"?F?.from||A:qt(A,h==="week"?-6:h==="month"?-29:0),_=h==="custom"&&F?.to||A,Y={from:L,to:_,provider:b,model:Q,basis:x,sessionId:C.id,offset:j},W=St(a,G),q=ut(l,"getBillingStatistics",Y,W),u=q.value,R=r=>o(r,{...a.config,decimals:Math.max(r!==0&&Math.abs(r)<.01?8:4,a.config.decimals??2)}),Z=r=>{S(r),z(0)},e=r=>{P(r),z(0),V(""),U("")},f=x==="total"?s("API + Plan 等值","API + Plan equivalent"):x==="plan"?s("Plan 等值","Plan equivalent"):s("API 费用","API cost"),w=(r,M,ht,Wt)=>t("label",null,r,t("select",{value:M,onChange:rt=>{ht(rt.target.value),z(0)}},Wt.map(([rt,Dt])=>t("option",{key:rt,value:rt},Dt)))),v={input:s("未缓存输入","Uncached input"),cacheRead:s("缓存读取","Cache read"),cacheWrite:s("缓存写入","Cache write"),output:s("输出","Output")},nt=(r,M)=>t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,r)),M),y=u?.totals,lt=(r,M,ht)=>t("div",{className:"cm-stat-metric",key:r},t("div",{className:"cm-stat-sub"},r),t("div",{className:"cm-stat-value"},M),t("div",{className:"cm-stat-sub"},ht));return t("div",{className:"cm-stat"},t("style",null,Bt),t("header",{className:"cm-stat-head"},t("div",null,t("h2",null,s("计费统计","Cost statistics")),t("p",{className:"cm-stat-sub"},C.id?s("单对话 · ","Conversation · ")+(C.title===C.id&&u?.sessions[0]?.title||C.title):s("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),E(s("刷新","Refresh"),()=>gt(r=>r+1))),C.id?E(s("← 全部对话","← All conversations"),()=>e({id:"",title:""})):null,t("div",{className:"cm-stat-controls"},t("div",{className:"cm-stat-periods"},...[["today",s("今天","Today")],["week",s("近 7 天","Last 7 days")],["month",s("近 30 天","Last 30 days")],["all",s("全部记录","All retained")],["custom",s("自定义","Custom")]].map(([r,M])=>E(M,()=>Z(r),{key:r,"aria-pressed":h===r})))),h==="custom"?t("div",{className:"cm-stat-controls"},...["from","to"].map(r=>t("label",{key:r},r==="from"?s("开始日期","From"):s("结束日期","To"),t("input",{type:"date",value:r==="from"?L:_,onChange:M=>{K({from:L,to:_,[r]:M.target.value}),z(0)}})))):null,t("div",{className:"cm-stat-controls"},w(s("计费口径","Cost basis"),x,g,[["api",s("API 费用","API cost")],["plan",s("Plan 等值","Plan equivalent")],["total",s("API + Plan 等值","API + Plan equivalent")]]),w(s("提供商","Provider"),b,r=>{V(r),U("")},[["",s("全部提供商","All providers")],...[...new Set([b,...u?.providers??[]])].filter(Boolean).map(r=>[r,r])]),w(s("模型","Model"),Q,U,[["",s("全部模型","All models")],...[...new Set([Q,...u?.modelOptions??[]])].filter(Boolean).map(r=>[r,r])])),t("details",{className:"cm-stat-help"},t("summary",null,s("计费说明","About billing")),t("p",null,s("按宿主时区归日:","Days use the host timezone: ")+(a.meta.timezone||"UTC")+" · "+s("API 金额是按已记录用量和配置单价计算的估算;Plan 为订阅用量的 API 等值,不是订阅账单。外部导入用量在原概览中单列。","API amounts estimate recorded usage at configured rates; Plan is API-equivalent usage, not the subscription invoice. External usage remains separate in Overview."))),tt(q)?q.loading?t("p",{className:"cm-stat-empty",role:"status"},s("加载统计…","Loading statistics…")):H(q.error):u?t($,null,q.failed?H(q.error):null,t("p",{className:"cm-stat-sub",style:{marginTop:8}},u.from+" – "+u.to+(u.retainedFrom?" · "+s("账本保留范围 ","Retained ledger ")+u.retainedFrom+" – "+u.retainedTo:"")),t("div",{className:"cm-stat-metrics"},lt(s("API 费用","API cost"),R(y.apiCost),s("已入账估算","Recorded estimate")),lt(s("Plan 等值费用","Plan equivalent"),R(Math.max(0,y.cost-y.apiCost)),s("不代表实际扣款","Not an actual debit")),lt(s("调用次数","Calls"),y.calls.toLocaleString(),u.sessionCount+s(" 个对话 · 平均 "," conversations · average ")+R(y.calls?O(y,x)/y.calls:0)),lt(s("缓存命中率","Cache hit rate"),D(y.cacheRead,y.input+y.cacheRead+y.cacheWrite),i(ct(y))+" Tokens")),C.id?t(Mt,{key:JSON.stringify([C.id,L,_,b,Q,x]),api:l,query:{...Y,from:u.from,to:u.to,offset:0},revision:W,money:R,formatTokens:i,text:s}):null,u.models.some(r=>!r.priced)?t("p",{className:"cm-stat-note"},s("部分模型当前未配置价格,金额可能不完整;未定价不等于免费。","Some models have no configured price. Amounts may be incomplete; unpriced usage is not free.")):null,!y.calls&&!y.cost?t("p",{className:"cm-stat-empty"},s("所选范围没有已记录的用量。","No recorded usage in this range.")):null,t("section",{className:"cm-stat-panel"},t(It,{rows:Tt(u.days,x),money:R,text:s,label:s("费用趋势 · ","Cost over time · ")+f,onSelect:r=>{K({from:r.from,to:r.to}),Z("custom")}}),t("p",{className:"cm-stat-sub",style:{marginTop:12}},s("点击柱形查看该日期范围。长区间按相邻日期合并,保留全部金额。","Select a bar to inspect its date range. Long ranges group adjacent days without dropping costs."))),t("div",{className:"cm-stat-grid"},nt(s("模型费用排行","Cost by model"),t($,null,t("ol",{className:"cm-stat-rank"},(X?u.models:u.models.slice(0,8)).map(r=>t("li",{key:r.key},t("button",{type:"button",onClick:()=>{V(r.provider),U(r.model),z(0)},title:r.key},t("div",{className:"cm-stat-rankline"},t("span",null,r.model),t("span",{className:"cm-stat-number"},R(O(r,x))+(r.priced?"":" + ?"))),t("div",{className:"cm-stat-sub"},r.provider+" · "+r.calls+s(" 次 · "," calls · ")+D(O(r,x),O(y,x))),t("div",{className:"cm-stat-track"},t("span",{style:{width:D(O(r,x),O(y,x))}}))))),u.models.length>8?E(X?s("收起","Show less"):s("显示全部模型","Show all models"),()=>st(r=>!r)):null,u.unmodeledCost>1e-8?t("p",{className:"cm-stat-note"},s("历史未分配到模型的费用:","Historical cost without a model: ")+R(u.unmodeledCost)):null)),nt(s("Token 构成","Token composition"),t($,null,t("ol",{className:"cm-stat-rank"},Object.entries(v).map(([r,M])=>t("li",{key:r},t("div",{className:"cm-stat-rankline"},t("span",null,M),t("span",{className:"cm-stat-number"},i(y[r]))),t("div",{className:"cm-stat-track"},t("span",{style:{width:D(y[r],ct(y)),background:r.startsWith("cache")?"var(--cm-plan)":void 0}}))))),t("p",{className:"cm-stat-note"},s("这里展示 Token 数量占比,不是费用占比。缓存写入计入输入分母,不算缓存命中。","These are token shares, not cost shares. Cache writes count as input, not cache hits.")),t("p",{className:"cm-stat-sub"},s("单独上报的推理 Token:","Reported reasoning tokens: ")+i(y.reasoning))))),C.id?null:t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,s("对话费用排行","Cost by conversation")),t("span",{className:"cm-stat-sub"},a.config.includeSubagentCost?s("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):s("点击对话查看明细","Select a conversation for details"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[s("对话","Conversation"),s("调用","Calls"),"API",s("Plan 等值","Plan equivalent"),s("缓存命中","Cache hits")].map(r=>t("th",{key:r},r)))),t("tbody",null,u.sessions.map(r=>t("tr",{key:r.id},t("td",null,t("button",{type:"button",title:r.id,onClick:()=>e({id:r.id,title:r.title})},r.title)),t("td",null,r.calls.toLocaleString()),t("td",null,R(r.apiCost)),t("td",null,R(Math.max(0,r.cost-r.apiCost))),t("td",null,D(r.cacheRead,r.input+r.cacheRead+r.cacheWrite))))))),u.unassignedCost>1e-8?t("p",{className:"cm-stat-note"},s("未关联对话的费用:","Cost not linked to a conversation: ")+R(u.unassignedCost)):null,t(at,{offset:j,count:u.sessionCount,size:25,onChange:z,text:s})))):null)}async function Lt(a){const l=await a.get("remote").$mount(kt);a.effect(()=>()=>l(),"cost-meter: statistics contribution");const c=a.get("remote.costMeter"),o=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection"].map(i=>[i,async n=>{const m=await c[i]((i==="getTurnInspection"?vt:yt)(n));if(!m?.ok)throw new Error(m?.error?.message||"Statistics request failed");return{getBillingStatistics:dt,getSessionBilling:mt,getTurnInspection:pt}[i](m.value)}]));return i=>t(Ot,{...i,api:o})}return{mount:Lt,Statistics:Ot,SessionDetail:Mt,TurnInspection:Pt,ShareChart:et,CONTRIBUTION:kt,parseStatistics:dt,parseDetail:mt,parseInspection:pt,dailyChartRows:Tt,requestStart:Nt,requestValue:Ct,requestFailure:wt,showsPlaceholder:tt,refreshKeyOf:St}}});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Process identity for local ledger locks; PID liveness alone cannot detect reuse. */
|
|
2
|
+
import { readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
3
|
+
import { execFileSync } from 'node:child_process'
|
|
4
|
+
import { hostname } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const host = hostname()
|
|
8
|
+
const ownStartMs = Date.now() - process.uptime() * 1000
|
|
9
|
+
const commandOptions = { encoding: 'utf8', timeout: 2000, maxBuffer: 1024, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }
|
|
10
|
+
let ownIdentity, clockTicks
|
|
11
|
+
|
|
12
|
+
function processIdentity(pid, legacy = false) {
|
|
13
|
+
try {
|
|
14
|
+
if (process.platform === 'linux') {
|
|
15
|
+
// comm can itself contain spaces and ')'; field 22 follows its last ')'.
|
|
16
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
|
|
17
|
+
const start = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)[19]
|
|
18
|
+
if (!/^\d+$/.test(start ?? '')) return null
|
|
19
|
+
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
|
|
20
|
+
const namespace = readlinkSync(`/proc/${pid}/ns/pid`)
|
|
21
|
+
if (!/^[a-f0-9-]{36}$/.test(boot) || !namespace) return null
|
|
22
|
+
let startedAtMs = pid === process.pid ? ownStartMs : null
|
|
23
|
+
if (legacy && pid !== process.pid) {
|
|
24
|
+
clockTicks ??= Number(execFileSync('getconf', ['CLK_TCK'], commandOptions).trim())
|
|
25
|
+
const bootTime = readFileSync('/proc/stat', 'utf8').match(/^btime (\d+)$/m)?.[1]
|
|
26
|
+
if (Number.isFinite(clockTicks) && clockTicks > 0 && bootTime) startedAtMs = (Number(bootTime) + Number(start) / clockTicks) * 1000
|
|
27
|
+
}
|
|
28
|
+
return { platform: 'linux', boot, namespace, start, startedAtMs }
|
|
29
|
+
}
|
|
30
|
+
if (process.platform === 'win32') {
|
|
31
|
+
const powershell = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
|
32
|
+
const start = execFileSync(powershell, ['-NoProfile', '-NonInteractive', '-Command',
|
|
33
|
+
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`], commandOptions).trim()
|
|
34
|
+
if (!/^\d+$/.test(start)) return null
|
|
35
|
+
return { platform: 'win32', start, startedAtMs: Number(BigInt(start) / 10000n - 62135596800000n) }
|
|
36
|
+
}
|
|
37
|
+
} catch { /* Missing process, permissions or OS tools: ownership remains unknown. */ }
|
|
38
|
+
return null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function localIdentity() {
|
|
42
|
+
if (ownIdentity === undefined) ownIdentity = processIdentity(process.pid)
|
|
43
|
+
return ownIdentity
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function ledgerLockOwner() {
|
|
47
|
+
return JSON.stringify({ version: 1, host, identity: localIdentity() })
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Only dead processes, changed native identities or pre-birth legacy files qualify. */
|
|
51
|
+
export function staleLedgerLockOwner(path, pid, identities = new Map()) {
|
|
52
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || pid > 2147483647) return false
|
|
53
|
+
const text = readFileSync(path, 'utf8')
|
|
54
|
+
let previous
|
|
55
|
+
if (text !== '') {
|
|
56
|
+
try { previous = JSON.parse(text) } catch { /* Incomplete owner write is not stale. */ }
|
|
57
|
+
if (previous?.host && previous.host !== host) return false
|
|
58
|
+
const local = localIdentity()
|
|
59
|
+
// Same-boot locks in another PID namespace cannot be probed from this one.
|
|
60
|
+
if (previous?.identity?.platform === 'linux' && local?.platform === 'linux'
|
|
61
|
+
&& previous.identity.boot === local.boot && previous.identity.namespace !== local.namespace) return false
|
|
62
|
+
}
|
|
63
|
+
try { process.kill(pid, 0) } catch (error) { return error.code === 'ESRCH' }
|
|
64
|
+
if (pid !== process.pid && !identities.has(pid)) identities.set(pid, processIdentity(pid, text === ''))
|
|
65
|
+
const current = pid === process.pid ? localIdentity() : identities.get(pid)
|
|
66
|
+
if (text === '') {
|
|
67
|
+
// v1.8.13 and earlier wrote empty owner files. Allow for timestamp precision
|
|
68
|
+
// and startup-time estimation; ordinary old locks are never expired by age.
|
|
69
|
+
const start = pid === process.pid ? (current?.startedAtMs ?? ownStartMs) : current?.startedAtMs
|
|
70
|
+
return Number.isFinite(start) && statSync(path).mtimeMs < start - 2000
|
|
71
|
+
}
|
|
72
|
+
const identity = previous?.version === 1 && previous.identity
|
|
73
|
+
if (!identity || !current || identity.platform !== current.platform || typeof identity.start !== 'string' || !/^\d+$/.test(identity.start)) return false
|
|
74
|
+
if (current.platform === 'linux') {
|
|
75
|
+
if (typeof identity.boot !== 'string' || typeof identity.namespace !== 'string') return false
|
|
76
|
+
return identity.boot !== current.boot || identity.start !== current.start
|
|
77
|
+
}
|
|
78
|
+
return identity.start !== current.start
|
|
79
|
+
}
|
|
@@ -5,6 +5,7 @@ import { randomUUID } from 'node:crypto'
|
|
|
5
5
|
import { repairDailySessionTotals } from './ledger-totals.js'
|
|
6
6
|
import { isDeepStrictEqual as equal } from 'node:util'
|
|
7
7
|
import { appendHourBucket, pruneHourBuckets, PLAN_SAMPLE_CAP, PLAN_SAMPLE_MAX_AGE_MS } from './plan-billing.js'
|
|
8
|
+
import { ledgerLockOwner, staleLedgerLockOwner } from './ledger-lock-owner.js'
|
|
8
9
|
|
|
9
10
|
const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost']
|
|
10
11
|
const safe = key => !['__proto__', 'constructor', 'prototype'].includes(key)
|
|
@@ -12,16 +13,22 @@ const object = value => value !== null && typeof value === 'object' && !Array.is
|
|
|
12
13
|
const clone = value => value === undefined ? undefined : structuredClone(value)
|
|
13
14
|
const pause = new Int32Array(new SharedArrayBuffer(4))
|
|
14
15
|
|
|
15
|
-
/** mkdir is exclusive on Windows and POSIX. A live owner is never
|
|
16
|
+
/** mkdir is exclusive on Windows and POSIX. A matching live owner is never expired. */
|
|
16
17
|
export function withLedgerLock(path, action, timeoutMs = 5000) {
|
|
17
18
|
mkdirSync(dirname(path), { recursive: true })
|
|
18
19
|
const lock = `${path}.lock`
|
|
19
20
|
const owner = `${process.pid}-${randomUUID()}`
|
|
21
|
+
const record = ledgerLockOwner()
|
|
22
|
+
const identities = new Map()
|
|
20
23
|
const deadline = Date.now() + timeoutMs
|
|
21
24
|
for (;;) {
|
|
22
25
|
try {
|
|
23
26
|
mkdirSync(lock)
|
|
24
|
-
try { writeFileSync(join(lock, owner), '') } catch (error) {
|
|
27
|
+
try { writeFileSync(join(lock, owner), record, { flag: 'wx' }) } catch (error) {
|
|
28
|
+
try { unlinkSync(join(lock, owner)) } catch {}
|
|
29
|
+
rmdirSync(lock)
|
|
30
|
+
throw error
|
|
31
|
+
}
|
|
25
32
|
break
|
|
26
33
|
} catch (error) {
|
|
27
34
|
// Windows can briefly report EPERM while another process finishes removing
|
|
@@ -31,11 +38,11 @@ export function withLedgerLock(path, action, timeoutMs = 5000) {
|
|
|
31
38
|
const names = readdirSync(lock)
|
|
32
39
|
const previous = names.length === 1 && names[0].match(/^(\d+)-[a-f0-9-]+$/)
|
|
33
40
|
if (previous) {
|
|
34
|
-
let dead = false
|
|
35
|
-
try { process.kill(Number(previous[1]), 0) } catch (probe) { dead = probe.code === 'ESRCH' }
|
|
36
41
|
// Only the contender that removes this unique owner file may remove the
|
|
37
42
|
// directory. Other contenders cannot accidentally unlink a new lock.
|
|
38
|
-
if (
|
|
43
|
+
if (staleLedgerLockOwner(join(lock, names[0]), Number(previous[1]), identities)) {
|
|
44
|
+
unlinkSync(join(lock, names[0])); rmdirSync(lock); continue
|
|
45
|
+
}
|
|
39
46
|
} else if (names.length === 0 && Date.now() - statSync(lock).mtimeMs > 30_000) {
|
|
40
47
|
rmdirSync(lock) // Also recovers a process killed between mkdir and owner creation.
|
|
41
48
|
continue
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cost-meter",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.15",
|
|
4
4
|
"description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(11 家,含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching), Coding Plan quota queries & display for 11 vendors (incl. Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -96,6 +96,7 @@
|
|
|
96
96
|
"cordis.patch.yml",
|
|
97
97
|
"docs/provider-pricing.json",
|
|
98
98
|
"docs/billing-statistics.md",
|
|
99
|
+
"docs/ledger-lock-recovery.md",
|
|
99
100
|
"docs/external-usage.md",
|
|
100
101
|
"docs/qwen-cli-quota.md",
|
|
101
102
|
"docs/session-sidebar-recovery.md",
|