dsh-cost-meter 1.9.37 → 1.9.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +588 -586
- package/README.zh-CN.md +592 -590
- package/docs/update-notes-1.9.31.md +1 -1
- package/docs/update-notes-1.9.38.md +31 -0
- package/docs/update-notes-1.9.39.md +33 -0
- package/lib/billing-export.js +49 -13
- package/lib/billion-context-billing.js +82 -58
- package/lib/billion-context-history.js +5 -2
- package/lib/billion-context-inventory.js +8 -5
- package/lib/client.js +1 -1
- package/lib/client.plan-settings.js +1 -1
- package/lib/coding-plans.js +1 -1
- package/lib/external-usage.js +119 -119
- package/lib/gateway-quotas.js +33 -14
- package/lib/index.js +22 -13
- package/lib/journal-storage.js +7 -1
- package/lib/ledger-totals.js +57 -57
- package/lib/ledger-writer-worker.js +1 -1
- package/lib/plan-billing.js +1 -1
- package/lib/pricing.js +6 -5
- package/lib/store.js +2 -0
- package/lib/typert.host.js +1 -0
- package/lib/workbuddy-accounts.js +32 -12
- package/package.json +5 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.plan-settings.js",factory:U=>{const{createElement:e,useState:O,Fragment:y}=U("react");return{mount(G){const{useQuotaRefresh:H,miniMaxWindowsOf:R,MiniMaxPlanCard:Y,barDirectionOf:_,quotaWindowRow:V,codingPlanWindowLabel:z,codingPlanWindowEntries:J,numInput:X,CredentialField:A,QuotaCard:Z,resolveLocale:$,formatMoneyUsd:E,quotaPlacementValue:ee,quotaPlacementPatch:ae,quotaPlacementOptions:ne}=G;function te({live:q,config:N,setPlan:p,state:n}){const l=(s,r)=>$(n.config)==="en"?r:s,m=q.workbuddy,t=m?.accounts??[],b=N.accountScope??"current",u=new Set(N.accountIds??[]),k=t.filter(s=>b==="all"||(b==="current"?s.current:u.has(s.id))),o=s=>typeof s=="number"&&Number.isFinite(s)?s.toLocaleString(void 0,{maximumFractionDigits:4}):"—",i=s=>k.length&&k.every(r=>typeof r[s]=="number")?k.reduce((r,f)=>r+f[s],0):null,C=s=>Object.entries(s?.byProviderModel??{}).reduce((r,[f,h])=>/^(workbuddy|workbuddy-ai|workbuddy-global|workbuddy-subscription):/.test(f)?r+(h.cost??0):r,0);return e("section",{className:"cm-workbuddy-accounts",style:{minWidth:0}},e("div",{className:"cm-field"},e("label",null,l("统计账号","Accounts to include")),e("select",{className:"cm-input","aria-label":l("统计账号","Accounts to include"),value:b,onChange:s=>p("accountScope",s.target.value)},...[["current",l("当前账号(各区域)","Current account per region")],["all",l("全部账号","All accounts")],["selected",l("勾选账号","Select accounts")]].map(([s,r])=>e("option",{value:s,key:s},r)))),m?.incomplete?e("p",{className:"cm-note",role:"status"},l("部分区域查询失败,当前汇总不完整。","Some regions could not be queried; totals are incomplete.")):null,m?.historyUnavailable?e("p",{className:"cm-note",role:"status"},l("历史统计暂时无法读取,原记录已保留;余额仍可查看。","History is unavailable and has been preserved; balances are still available.")):null,t.length?e("div",{style:{maxHeight:260,overflow:"auto",border:"1px solid var(--dsw-alias-border-l1)",borderRadius:8}},...t.map((s,r)=>e("label",{key:s.id,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",minWidth:0}},e("input",{type:"checkbox",checked:b==="all"||(b==="current"?s.current:u.has(s.id)),disabled:b!=="selected","aria-label":s.name||l("账号 ","Account ")+(r+1),onChange:f=>{const h=new Set(u);f.target.checked?h.add(s.id):h.delete(s.id),p("accountIds",[...h])}}),e("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"}},s.name||l("账号 ","Account ")+(r+1),e("small",{style:{display:"block",opacity:.65}},s.region==="cn"?l("国内","CN"):l("国际","Global"))),e("span",{style:{textAlign:"right",flexShrink:0}},o(s.remaining),e("small",{style:{display:"block",opacity:.65}},l("今日减少 ","Decrease today ")+o(s.observedToday)))))):e("p",{className:"cm-note"},l("刷新后显示账号。旧连接插件未提供账号列表时,仍可查看当前账号积分。","Refresh to load accounts. Older connectors can still show current credits without an account list.")),e("div",{style:{display:"grid",gridTemplateColumns:"repeat(2,minmax(0,1fr))",gap:8,marginTop:10}},...[["remaining",l("剩余积分","Credits remaining")],["observedToday",l("今日观测减少","Observed decrease today")],["observedWeek",l("近 7 天观测减少","Observed decrease, 7 days")],["observedTotal",l("启用以来观测减少","Observed decrease since enabled")]].map(([s,r])=>e("div",{key:s,style:{padding:8,borderRadius:6,background:"var(--dsw-alias-bg-layer-1)",minWidth:0,overflowWrap:"anywhere"}},e("small",null,r),e("strong",{style:{display:"block"}},o(m?.incomplete?null:i(s)))))),e("p",{className:"cm-note"},l("从首次成功查询开始记录;充值或赠送不计为减少,积分过期可能计入减少。不是官方扣费账单,积分不折算成人民币。","Recorded from the first successful query. Grants are not decreases; expiry may be. This is not an official charge statement and credits are not converted to currency.")),e("p",{className:"cm-note"},l("全部 WorkBuddy 调用 API 等值:今日 ","API-equivalent value of all WorkBuddy calls: today ")+E(C(n.today),n.config)+l(";累计 ","; total ")+E(C(n.total),n.config)+l("。调用记录没有账号标识,此项不随账号筛选。",". Call records have no account identifiers; this value is not filtered by account.")))}function le(q){const{state:N,api:p,t:n,draft:l,setDraft:m,planId:t,labelKey:b}=q,u=N.config,k=N.codingPlans??{},o=l?.codingPlans?.[t]??u.codingPlans?.[t]??{},i=k[t]??{status:"off",message:"",fetchedAt:0,windows:{}},C=o.enabled===!0,[s,r]=O(q.targeted===!0),f=t==="qwen"&&u.codingPlans?.qwen?.quotaSource==="bailian"&&o.quotaSource==="bailian"&&i.quotaSource==="bailian"&&i.loginRequired===!0,[h,j,K]=H(n,()=>f?p.loginCodingPlan(t):p.refreshCodingPlan(t)),d=(a,c)=>{if(l===null)return;const g=l.codingPlans??u.codingPlans??{};m({...l,codingPlans:{...g,[t]:{...g[t]??{},[a]:c}}})},[L,Q]=O(""),[M,I]=O({}),W=a=>a?.rates!==null&&typeof a?.rates=="object"&&!Array.isArray(a.rates)?a.rates:{},x=["input","cachedInput","output"],D=a=>M[a]??W(o)[a]??{},B=a=>x.every(c=>Number.isFinite(Number(a[c]))&&Number(a[c])>0),se=(a,c,g)=>{if(l===null)return;const v={...D(a),[c]:String(g)};I(P=>({...P,[a]:v}));const S=x.every(P=>String(v[P]??"").trim()==="");if(!S&&!B(v))return;const T=l.codingPlans??u.codingPlans??{},F={...(T.qwen??{}).rates??{}};S?delete F[a]:F[a]=Object.fromEntries(x.map(P=>[P,Number(v[P])])),m({...l,codingPlans:{...T,qwen:{...T.qwen??{},rates:F}}})},oe=a=>{l!==null&&I(c=>({...c,[a]:c[a]??W(o)[a]??{}}))},ce=a=>{if(l===null)return;I(v=>{const S={...v};return delete S[a],S});const c=l.codingPlans??u.codingPlans??{},g={...(c.qwen??{}).rates??{}};delete g[a],m({...l,codingPlans:{...c,qwen:{...c.qwen??{},rates:g}}})},w=i.windows!==null&&typeof i.windows=="object"?i.windows:{},ie=C===!1?e("p",{className:"cm-note"},n("codingPlanDisabledNote")):i.status==="ok"?e("div",{className:"cm-go-list"},i.message?e("p",{className:"cm-note"},i.message):null,Object.keys(w).length>0?t==="minimax"&&(R(w).five!=null||R(w).seven!=null)?e(Y,{five:R(w).five,seven:R(w).seven,fetchedAt:i.fetchedAt,t:n,wide:!0,direction:_(u,"plan")}):J(w,t).map(([a,c])=>V(n,z(a,n),c,_(u,"plan"),!1,a)):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried")),e("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:i.fetchedAt>0?new Date(i.fetchedAt).toLocaleTimeString():"—"}))):i.status==="error"?e("div",{className:"cm-bal-line err"},i.message||n("unknownError")):i.status==="off"&&i.message?e("p",{className:"cm-note"},i.message):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried")),re=e(y,null,t==="opendesign"?e("div",{className:"cm-field"},e("label",null,n("opendesignWorkspace")),e("input",{className:"cm-input","aria-label":n("opendesignWorkspace"),value:o.workspaceId??"",onChange:a=>d("workspaceId",a.target.value)}),e("p",{className:"cm-note"},n("opendesignNote"))):null,t==="factory"?e(y,null,e("div",{className:"cm-field"},e("label",null,n("factoryPool")),e("select",{className:"cm-input","aria-label":n("factoryPool"),value:o.factoryPool??"standard",onChange:a=>d("factoryPool",a.target.value)},e("option",{value:"standard"},"Standard"),e("option",{value:"core"},"Droid Core"),e("option",{value:"both"},n("factoryPoolBoth")))),e("div",{className:"cm-field"},e("label",null,n("factoryOrg")),e("input",{className:"cm-input","aria-label":n("factoryOrg"),value:o.orgId??"",onChange:a=>d("orgId",a.target.value)}))):null,t==="minimax"?e("div",{className:"cm-field"},e("label",null,n("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:o.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":n("minimaxOrigin"),onChange:a=>d("baseUrl",a.target.value)}),e("p",{className:"cm-note"},n("minimaxOriginNote"))):null,t==="qwen"?e("div",{className:"cm-field"},e("label",null,n("qwenSource")),e("select",{className:"cm-input",value:o.quotaSource??"local",onChange:a=>d("quotaSource",a.target.value)},e("option",{value:"local"},n("qwenSourceLocal")),e("option",{value:"cli"},n("qwenSourceCli")),e("option",{value:"bailian"},n("qwenSourceBailian"))),e("p",{className:"cm-note"},n(o.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,n("codingPlanDisplayLabel")),e("select",{className:"cm-input","aria-label":n("codingPlanDisplayLabel"),value:ee(o,(l??u).quotaStrip,"plans"),onChange:a=>{if(l===null)return;const c=l.codingPlans??u.codingPlans??{};m({...l,codingPlans:{...c,[t]:{...o,...ae(a.target.value)}}})}},...ne(n)),e("span",{className:"cm-hint"},n("codingPlanDisplayNote"))),t!=="scnet"&&(t!=="qwen"||(o.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,n("codingPlanRefreshIntervalLabel")),X({value:typeof o.refreshMinutes=="number"&&Number.isFinite(o.refreshMinutes)&&o.refreshMinutes>0?o.refreshMinutes:15},a=>{d("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(a))))})):null,t==="scnet"||t==="qwen"&&(o.quotaSource??"local")==="local"?e(y,null,e("div",{className:"cm-field"},e("label",null,n(t==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof o.planCredits=="number"&&Number.isFinite(o.planCredits)&&o.planCredits>0?o.planCredits:t==="qwen"?5e5:24e4,onChange:a=>{const c=Number(a.target.value);Number.isFinite(c)&&c>0&&d("planCredits",Math.floor(c))}})),e("div",{className:"cm-field"},e("label",null,n(t==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof o.planStart=="string"?o.planStart:"",onChange:a=>d("planStart",a.target.value)})),t==="qwen"?e(y,null,e("div",{className:"cm-field"},e("label",null,n("qwenRatesLabel"))),[...new Set([...Object.keys(W(o)),...Object.keys(M)])].sort().map(a=>e("div",{key:a,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},a),x.map(c=>e("input",{key:c,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:D(a)[c]??"",placeholder:n("qwenRate_"+c),"aria-label":a+" · "+n("qwenRate_"+c),onChange:g=>{const v=g.target.value;se(a,c,v)}})),e("button",{className:"cm-btn small",onClick:()=>ce(a)},n("overrideRemove")),a in M&&!B(D(a))?e("span",{className:"cm-note"},n("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:n("qwenRatesModelPlaceholder"),value:L,onChange:a=>Q(a.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const a=L.trim();a.length!==0&&(oe(a),Q(""))},disabled:L.trim().length===0},n("qwenRatesAdd")))):null,e("p",{className:"cm-note"},n(t==="qwen"?"qwenLocalNote":"scnetLocalNote"))):t==="qwen"?null:t==="volcengine"?e(y,null,e("div",{className:"cm-field"},e("label",null,n("volcengineAccessKeyIdLabel"))),e(A,{target:"codingPlans.volcengine.ak",configured:i.keyConfigured===!0,source:i.keySource,t:n,api:p,placeholder:n("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,n("volcengineSecretAccessKeyLabel"))),e(A,{target:"codingPlans.volcengine.sk",configured:i.keyConfigured===!0,source:i.keySource,t:n,api:p,placeholder:n("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},n("volcengineNote"))):t==="workbuddy"?e(y,null,e("p",{className:"cm-note"},n("wbH")),e(te,{live:i,config:o,setPlan:d,state:N})):e(y,null,e("div",{className:"cm-field"},e("label",null,t==="mimo"?"Cookie (platform.xiaomimimo.com)":t==="factory"?"Factory Token":t==="opendesign"?"OpenDesign Control Key":n("codingPlanKeyLabel"))),e(A,{target:"codingPlans."+t,configured:i.keyConfigured===!0,source:i.keySource,t:n,api:p,placeholder:t==="mimo"?"api-platform_serviceToken=…; userId=…":t==="factory"?"FACTORY_API_KEY":t==="opendesign"?"OPENDESIGN_CONTROL_KEY":"sk-…"})));return e(Z,{planId:t,targeted:q.targeted,name:n(b),enabled:C,saved:u.codingPlans?.[t],busy:h,open:s,errorMsg:j?.text===i.message?null:j,statusNode:ie,configNode:re,onToggle:a=>d("enabled",a),onRefresh:K,onLogin:K,loginRequired:f,onToggleOpen:()=>r(a=>!a),t:n})}return le}}}});
|
|
1
|
+
window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.plan-settings.js",factory:U=>{const{createElement:e,useState:A,Fragment:v}=U("react");return{mount(G){const{useQuotaRefresh:H,miniMaxWindowsOf:x,MiniMaxPlanCard:Y,barDirectionOf:_,quotaWindowRow:X,codingPlanWindowLabel:V,codingPlanWindowEntries:z,numInput:J,CredentialField:O,QuotaCard:Z,resolveLocale:$,formatMoneyUsd:E,quotaPlacementValue:ee,quotaPlacementPatch:ae,quotaPlacementOptions:ne}=G;function te({live:q,config:h,setPlan:m,state:n}){const t=(o,r)=>$(n.config)==="en"?r:o,g=q.workbuddy,l=g?.accounts??[],b=h.accountScope??"current",u=new Set(h.accountIds??[]),k=l.filter(o=>b==="all"||(b==="current"?o.current:u.has(o.id))),s=o=>typeof o=="number"&&Number.isFinite(o)?o.toLocaleString(void 0,{maximumFractionDigits:4}):"—",i=o=>k.length&&k.every(r=>typeof r[o]=="number")?k.reduce((r,f)=>r+f[o],0):null,C=o=>Object.entries(o?.byProviderModel??{}).reduce((r,[f,N])=>/^(workbuddy|workbuddy-ai|workbuddy-global|workbuddy-subscription|xdpool|xdpool-global):/.test(f)?r+(N.cost??0):r,0);return e("section",{className:"cm-workbuddy-accounts",style:{minWidth:0}},e("div",{className:"cm-field"},e("label",null,t("积分来源","Credit source")),e("select",{className:"cm-input","aria-label":t("积分来源","Credit source"),value:h.accountSource??"auto",onChange:o=>m("accountSource",o.target.value)},...[["auto",t("自动识别","Automatic")],["connect",t("WorkBuddy 连接插件","WorkBuddy connectors")],["xdpool","dsh-xdpool"]].map(([o,r])=>e("option",{value:o,key:o},r))),e("p",{className:"cm-note"},t("自动识别优先读取连接插件的账号列表,其次读取 XD Pool。两者同时使用时可指定来源。","Automatic uses connector accounts first, then XD Pool. Select a source when using both."))),e("div",{className:"cm-field"},e("label",null,t("统计账号","Accounts to include")),e("select",{className:"cm-input","aria-label":t("统计账号","Accounts to include"),value:b,onChange:o=>m("accountScope",o.target.value)},...[["current",t("当前账号(各区域)","Current account per region")],["all",t("全部账号","All accounts")],["selected",t("勾选账号","Select accounts")]].map(([o,r])=>e("option",{value:o,key:o},r)))),g?.incomplete?e("p",{className:"cm-note",role:"status"},t("部分区域查询失败,当前汇总不完整。","Some regions could not be queried; totals are incomplete.")):null,g?.historyUnavailable?e("p",{className:"cm-note",role:"status"},t("历史统计暂时无法读取,原记录已保留;余额仍可查看。","History is unavailable and has been preserved; balances are still available.")):null,l.length?e("div",{style:{maxHeight:260,overflow:"auto",border:"1px solid var(--dsw-alias-border-l1)",borderRadius:8}},...l.map((o,r)=>e("label",{key:o.id,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",minWidth:0}},e("input",{type:"checkbox",checked:b==="all"||(b==="current"?o.current:u.has(o.id)),disabled:b!=="selected","aria-label":o.name||t("账号 ","Account ")+(r+1),onChange:f=>{const N=new Set(u);f.target.checked?N.add(o.id):N.delete(o.id),m("accountIds",[...N])}}),e("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"}},o.name||t("账号 ","Account ")+(r+1),e("small",{style:{display:"block",opacity:.65}},o.region==="cn"?t("国内","CN"):t("国际","Global"))),e("span",{style:{textAlign:"right",flexShrink:0}},s(o.remaining),e("small",{style:{display:"block",opacity:.65}},t("今日减少 ","Decrease today ")+s(o.observedToday)))))):e("p",{className:"cm-note"},t("刷新后显示账号。旧连接插件未提供账号列表时,仍可查看当前账号积分。","Refresh to load accounts. Older connectors can still show current credits without an account list.")),e("div",{style:{display:"grid",gridTemplateColumns:"repeat(2,minmax(0,1fr))",gap:8,marginTop:10}},...[["remaining",t("剩余积分","Credits remaining")],["observedToday",t("今日观测减少","Observed decrease today")],["observedWeek",t("近 7 天观测减少","Observed decrease, 7 days")],["observedTotal",t("启用以来观测减少","Observed decrease since enabled")]].map(([o,r])=>e("div",{key:o,style:{padding:8,borderRadius:6,background:"var(--dsw-alias-bg-layer-1)",minWidth:0,overflowWrap:"anywhere"}},e("small",null,r),e("strong",{style:{display:"block"}},s(g?.incomplete?null:i(o)))))),e("p",{className:"cm-note"},t("从首次成功查询开始记录;充值或赠送不计为减少,积分过期可能计入减少。不是官方扣费账单,积分不折算成人民币。","Recorded from the first successful query. Grants are not decreases; expiry may be. This is not an official charge statement and credits are not converted to currency.")),e("p",{className:"cm-note"},t("全部 WorkBuddy 调用 API 等值:今日 ","API-equivalent value of all WorkBuddy calls: today ")+E(C(n.today),n.config)+t(";累计 ","; total ")+E(C(n.total),n.config)+t("。调用记录没有账号标识,此项不随账号筛选。",". Call records have no account identifiers; this value is not filtered by account.")))}function le(q){const{state:h,api:m,t:n,draft:t,setDraft:g,planId:l,labelKey:b}=q,u=h.config,k=h.codingPlans??{},s=t?.codingPlans?.[l]??u.codingPlans?.[l]??{},i=k[l]??{status:"off",message:"",fetchedAt:0,windows:{}},C=s.enabled===!0,[o,r]=A(q.targeted===!0),f=l==="qwen"&&u.codingPlans?.qwen?.quotaSource==="bailian"&&s.quotaSource==="bailian"&&i.quotaSource==="bailian"&&i.loginRequired===!0,[N,j,B]=H(n,()=>f?m.loginCodingPlan(l):m.refreshCodingPlan(l)),d=(a,c)=>{if(t===null)return;const p=t.codingPlans??u.codingPlans??{};g({...t,codingPlans:{...p,[l]:{...p[l]??{},[a]:c}}})},[L,K]=A(""),[M,W]=A({}),D=a=>a?.rates!==null&&typeof a?.rates=="object"&&!Array.isArray(a.rates)?a.rates:{},R=["input","cachedInput","output"],I=a=>M[a]??D(s)[a]??{},Q=a=>R.every(c=>Number.isFinite(Number(a[c]))&&Number(a[c])>0),oe=(a,c,p)=>{if(t===null)return;const y={...I(a),[c]:String(p)};W(P=>({...P,[a]:y}));const S=R.every(P=>String(y[P]??"").trim()==="");if(!S&&!Q(y))return;const T=t.codingPlans??u.codingPlans??{},F={...(T.qwen??{}).rates??{}};S?delete F[a]:F[a]=Object.fromEntries(R.map(P=>[P,Number(y[P])])),g({...t,codingPlans:{...T,qwen:{...T.qwen??{},rates:F}}})},se=a=>{t!==null&&W(c=>({...c,[a]:c[a]??D(s)[a]??{}}))},ce=a=>{if(t===null)return;W(y=>{const S={...y};return delete S[a],S});const c=t.codingPlans??u.codingPlans??{},p={...(c.qwen??{}).rates??{}};delete p[a],g({...t,codingPlans:{...c,qwen:{...c.qwen??{},rates:p}}})},w=i.windows!==null&&typeof i.windows=="object"?i.windows:{},ie=C===!1?e("p",{className:"cm-note"},n("codingPlanDisabledNote")):i.status==="ok"?e("div",{className:"cm-go-list"},i.message?e("p",{className:"cm-note"},i.message):null,Object.keys(w).length>0?l==="minimax"&&(x(w).five!=null||x(w).seven!=null)?e(Y,{five:x(w).five,seven:x(w).seven,fetchedAt:i.fetchedAt,t:n,wide:!0,direction:_(u,"plan")}):z(w,l).map(([a,c])=>X(n,V(a,n),c,_(u,"plan"),!1,a)):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried")),e("div",{className:"cm-go-time"},n("goQuotaFetchedAt",{time:i.fetchedAt>0?new Date(i.fetchedAt).toLocaleTimeString():"—"}))):i.status==="error"?e("div",{className:"cm-bal-line err"},i.message||n("unknownError")):i.status==="off"&&i.message?e("p",{className:"cm-note"},i.message):e("div",{className:"cm-bal-line"},n("codingPlanNotQueried")),re=e(v,null,l==="opendesign"?e("div",{className:"cm-field"},e("label",null,n("opendesignWorkspace")),e("input",{className:"cm-input","aria-label":n("opendesignWorkspace"),value:s.workspaceId??"",onChange:a=>d("workspaceId",a.target.value)}),e("p",{className:"cm-note"},n("opendesignNote"))):null,l==="factory"?e(v,null,e("div",{className:"cm-field"},e("label",null,n("factoryPool")),e("select",{className:"cm-input","aria-label":n("factoryPool"),value:s.factoryPool??"standard",onChange:a=>d("factoryPool",a.target.value)},e("option",{value:"standard"},"Standard"),e("option",{value:"core"},"Droid Core"),e("option",{value:"both"},n("factoryPoolBoth")))),e("div",{className:"cm-field"},e("label",null,n("factoryOrg")),e("input",{className:"cm-input","aria-label":n("factoryOrg"),value:s.orgId??"",onChange:a=>d("orgId",a.target.value)}))):null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,n("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:s.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":n("minimaxOrigin"),onChange:a=>d("baseUrl",a.target.value)}),e("p",{className:"cm-note"},n("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,n("qwenSource")),e("select",{className:"cm-input",value:s.quotaSource??"local",onChange:a=>d("quotaSource",a.target.value)},e("option",{value:"local"},n("qwenSourceLocal")),e("option",{value:"cli"},n("qwenSourceCli")),e("option",{value:"bailian"},n("qwenSourceBailian"))),e("p",{className:"cm-note"},n(s.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,n("codingPlanDisplayLabel")),e("select",{className:"cm-input","aria-label":n("codingPlanDisplayLabel"),value:ee(s,(t??u).quotaStrip,"plans"),onChange:a=>{if(t===null)return;const c=t.codingPlans??u.codingPlans??{};g({...t,codingPlans:{...c,[l]:{...s,...ae(a.target.value)}}})}},...ne(n)),e("span",{className:"cm-hint"},n("codingPlanDisplayNote"))),l!=="scnet"&&(l!=="qwen"||(s.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,n("codingPlanRefreshIntervalLabel")),J({value:typeof s.refreshMinutes=="number"&&Number.isFinite(s.refreshMinutes)&&s.refreshMinutes>0?s.refreshMinutes:15},a=>{d("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(a))))})):null,l==="scnet"||l==="qwen"&&(s.quotaSource??"local")==="local"?e(v,null,e("div",{className:"cm-field"},e("label",null,n(l==="qwen"?"qwenPlanCreditsLabel":"scnetPlanCreditsLabel")),e("input",{className:"cm-input",type:"number",min:"1",step:"1000",value:typeof s.planCredits=="number"&&Number.isFinite(s.planCredits)&&s.planCredits>0?s.planCredits:l==="qwen"?5e5:24e4,onChange:a=>{const c=Number(a.target.value);Number.isFinite(c)&&c>0&&d("planCredits",Math.floor(c))}})),e("div",{className:"cm-field"},e("label",null,n(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof s.planStart=="string"?s.planStart:"",onChange:a=>d("planStart",a.target.value)})),l==="qwen"?e(v,null,e("div",{className:"cm-field"},e("label",null,n("qwenRatesLabel"))),[...new Set([...Object.keys(D(s)),...Object.keys(M)])].sort().map(a=>e("div",{key:a,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},a),R.map(c=>e("input",{key:c,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:I(a)[c]??"",placeholder:n("qwenRate_"+c),"aria-label":a+" · "+n("qwenRate_"+c),onChange:p=>{const y=p.target.value;oe(a,c,y)}})),e("button",{className:"cm-btn small",onClick:()=>ce(a)},n("overrideRemove")),a in M&&!Q(I(a))?e("span",{className:"cm-note"},n("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:n("qwenRatesModelPlaceholder"),value:L,onChange:a=>K(a.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const a=L.trim();a.length!==0&&(se(a),K(""))},disabled:L.trim().length===0},n("qwenRatesAdd")))):null,e("p",{className:"cm-note"},n(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(v,null,e("div",{className:"cm-field"},e("label",null,n("volcengineAccessKeyIdLabel"))),e(O,{target:"codingPlans.volcengine.ak",configured:i.keyConfigured===!0,source:i.keySource,t:n,api:m,placeholder:n("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,n("volcengineSecretAccessKeyLabel"))),e(O,{target:"codingPlans.volcengine.sk",configured:i.keyConfigured===!0,source:i.keySource,t:n,api:m,placeholder:n("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},n("volcengineNote"))):l==="workbuddy"?e(v,null,e("p",{className:"cm-note"},n("wbH")),e(te,{live:i,config:s,setPlan:d,state:h})):e(v,null,e("div",{className:"cm-field"},e("label",null,l==="mimo"?"Cookie (platform.xiaomimimo.com)":l==="factory"?"Factory Token":l==="opendesign"?"OpenDesign Control Key":n("codingPlanKeyLabel"))),e(O,{target:"codingPlans."+l,configured:i.keyConfigured===!0,source:i.keySource,t:n,api:m,placeholder:l==="mimo"?"api-platform_serviceToken=…; userId=…":l==="factory"?"FACTORY_API_KEY":l==="opendesign"?"OPENDESIGN_CONTROL_KEY":"sk-…"})));return e(Z,{planId:l,targeted:q.targeted,name:n(b),enabled:C,saved:u.codingPlans?.[l],busy:N,open:o,errorMsg:j?.text===i.message?null:j,statusNode:ie,configNode:re,onToggle:a=>d("enabled",a),onRefresh:B,onLogin:B,loginRequired:f,onToggleOpen:()=>r(a=>!a),t:n})}return le}}}});
|
package/lib/coding-plans.js
CHANGED
|
@@ -130,7 +130,7 @@ export const CODING_PLAN_PROVIDERS = {
|
|
|
130
130
|
label: 'WorkBuddy 积分',
|
|
131
131
|
// 优先读取连接插件状态;旧版明文文件仅用于未注册状态接口的环境。
|
|
132
132
|
credentialEnvs: [],
|
|
133
|
-
keyHint: '
|
|
133
|
+
keyHint: '无需复制凭据;支持 dsh-workbuddy-connect / dsh-connect-workbuddy / dsh-xdpool,兼容旧版明文登录文件',
|
|
134
134
|
},
|
|
135
135
|
}
|
|
136
136
|
|
package/lib/external-usage.js
CHANGED
|
@@ -1,119 +1,119 @@
|
|
|
1
|
-
import { constants } from 'node:fs'
|
|
2
|
-
import { open } from 'node:fs/promises'
|
|
3
|
-
import { localDayKey, zeroDay } from './store.js'
|
|
4
|
-
import { fxRatesOf } from './exchange-rates.js'
|
|
5
|
-
import { costOf, providerPriceEntryFor, usdFromCost } from './pricing.js'
|
|
6
|
-
|
|
7
|
-
export const EXTERNAL_USAGE_MAX_BYTES = 512 * 1024
|
|
8
|
-
const MAX_AGE = 30 * 86400000
|
|
9
|
-
const FRESH_AGE = 86400000
|
|
10
|
-
const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost']
|
|
11
|
-
const object = v => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
12
|
-
const count = v => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 1e12
|
|
13
|
-
const money = v => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1e9
|
|
14
|
-
const dateKey = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v + 'T00:00:00Z')) && new Date(v + 'T00:00:00Z').toISOString().slice(0, 10) === v
|
|
15
|
-
const timestamp = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(v) && dateKey(v.slice(0, 10)) ? Date.parse(v) : NaN
|
|
16
|
-
|
|
17
|
-
function add(into, day) {
|
|
18
|
-
for (const key of fields) into[key] += day[key]
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function summary(days, dayKey) {
|
|
22
|
-
const today = zeroDay(dayKey)
|
|
23
|
-
const month = zeroDay(dayKey.slice(0, 7))
|
|
24
|
-
const total = zeroDay('total')
|
|
25
|
-
const history = Object.values(days).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 90)
|
|
26
|
-
for (const day of Object.values(days)) {
|
|
27
|
-
add(total, day)
|
|
28
|
-
if (day.date.startsWith(dayKey.slice(0, 7))) add(month, day)
|
|
29
|
-
if (day.date === dayKey) add(today, day)
|
|
30
|
-
}
|
|
31
|
-
return { today, month, total, history }
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** A snapshot replaces its predecessor; it never mutates the DSH ledger. */
|
|
35
|
-
export function parseExternalUsageSnapshot(value, config, nowMs = Date.now()) {
|
|
36
|
-
if (!object(value)) return null
|
|
37
|
-
if (Object.hasOwn(value, 'sources') && !Array.isArray(value.sources)) return null
|
|
38
|
-
const fetchedAt = timestamp(value.fetchedAt)
|
|
39
|
-
if (!Number.isFinite(fetchedAt) || fetchedAt > nowMs + 300000 || nowMs - fetchedAt > MAX_AGE) return null
|
|
40
|
-
const entries = Array.isArray(value.sources) ? value.sources : [value]
|
|
41
|
-
if (entries.length < 1 || entries.length > 8) return null
|
|
42
|
-
const seen = new Set()
|
|
43
|
-
const sources = []
|
|
44
|
-
const combinedDays = {}
|
|
45
|
-
let recordCount = 0
|
|
46
|
-
for (const entry of entries) {
|
|
47
|
-
if (!object(entry) || typeof entry.source !== 'string' || entry.source.length < 1 || entry.source.length > 64 || seen.has(entry.source)) return null
|
|
48
|
-
seen.add(entry.source)
|
|
49
|
-
if (object(entry.days) === Array.isArray(entry.records)) return null // exactly one input mode
|
|
50
|
-
const days = {}
|
|
51
|
-
if (object(entry.days)) {
|
|
52
|
-
if (Object.keys(entry.days).length > 3660) return null
|
|
53
|
-
for (const [date, raw] of Object.entries(entry.days)) {
|
|
54
|
-
if (!dateKey(date) || date > localDayKey(nowMs) || !object(raw) || !count(raw.input) || !count(raw.output) || !count(raw.cached) || !count(raw.calls) || !money(raw.costUsd)) return null
|
|
55
|
-
if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
|
|
56
|
-
if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
|
|
57
|
-
days[date] = { ...zeroDay(date), input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0, calls: raw.calls, cost: raw.costUsd, apiCost: raw.costUsd }
|
|
58
|
-
}
|
|
59
|
-
} else {
|
|
60
|
-
recordCount += entry.records.length
|
|
61
|
-
if (recordCount > 5000) return null
|
|
62
|
-
const ids = new Set()
|
|
63
|
-
for (const raw of entry.records) {
|
|
64
|
-
if (!object(raw) || typeof raw.id !== 'string' || raw.id.length < 1 || raw.id.length > 128 || ids.has(raw.id)) return null
|
|
65
|
-
ids.add(raw.id)
|
|
66
|
-
const at = timestamp(raw.at)
|
|
67
|
-
if (!Number.isFinite(at) || at > nowMs + 300000 || !count(raw.input) || !count(raw.output) || !count(raw.cached)) return null
|
|
68
|
-
if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
|
|
69
|
-
if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
|
|
70
|
-
if (typeof raw.provider !== 'string' || !raw.provider || typeof raw.model !== 'string' || !raw.model) return null
|
|
71
|
-
const resolved = providerPriceEntryFor(raw.provider, raw.model, config?.prices, {
|
|
72
|
-
mode: config?.priceMatch === 'exact' ? 'exact' : 'auto', overrides: config?.priceOverrides,
|
|
73
|
-
})
|
|
74
|
-
if (!resolved.priced) return null
|
|
75
|
-
const peak = { enabled: ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && config?.peakEnabled === true,
|
|
76
|
-
effectiveAtMs: Date.parse(config?.peakEffectiveAt ?? ''), windows: config?.peakWindows, holidays: config?.peakHolidays }
|
|
77
|
-
const tokens = { input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0 }
|
|
78
|
-
const priced = costOf(tokens, resolved.entry, at, peak)
|
|
79
|
-
const usd = usdFromCost(priced, resolved.currency, fxRatesOf(config).CNY)
|
|
80
|
-
const date = localDayKey(at)
|
|
81
|
-
const day = days[date] ?? (days[date] = zeroDay(date))
|
|
82
|
-
for (const key of ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']) day[key] += tokens[key]
|
|
83
|
-
day.calls++
|
|
84
|
-
day.cost += usd
|
|
85
|
-
day.apiCost += usd
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
for (const [date, day] of Object.entries(days)) add(combinedDays[date] ?? (combinedDays[date] = zeroDay(date)), day)
|
|
89
|
-
sources.push({ source: entry.source, ...summary(days, localDayKey(nowMs)) })
|
|
90
|
-
}
|
|
91
|
-
return { fetchedAt, stale: nowMs - fetchedAt > FRESH_AGE, sources,
|
|
92
|
-
combined: summary(combinedDays, localDayKey(nowMs)) }
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Bounded, fail-closed read of a regular file. Producers should write a temp file and rename it. */
|
|
96
|
-
export async function readExternalUsageSnapshot(path, config, nowMs = Date.now()) {
|
|
97
|
-
let file
|
|
98
|
-
try {
|
|
99
|
-
file = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
|
|
100
|
-
const stat = await file.stat()
|
|
101
|
-
if (!stat.isFile() || stat.size > EXTERNAL_USAGE_MAX_BYTES) return null
|
|
102
|
-
const buffer = Buffer.alloc(EXTERNAL_USAGE_MAX_BYTES + 1)
|
|
103
|
-
let length = 0
|
|
104
|
-
while (length < buffer.length) {
|
|
105
|
-
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null)
|
|
106
|
-
if (!bytesRead) break
|
|
107
|
-
length += bytesRead
|
|
108
|
-
}
|
|
109
|
-
if (length > EXTERNAL_USAGE_MAX_BYTES) return null
|
|
110
|
-
return parseExternalUsageSnapshot(JSON.parse(buffer.subarray(0, length).toString('utf8')), config, nowMs)
|
|
111
|
-
} catch { return null } finally { await file?.close().catch(() => {}) }
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Fresh external usage participates in same-account balance reconciliation. */
|
|
115
|
-
export function externalTodayCostForReconcile(snapshot) {
|
|
116
|
-
if (snapshot?.stale === true) return null
|
|
117
|
-
const cost = snapshot?.combined?.today?.cost
|
|
118
|
-
return Number.isFinite(cost) && cost >= 0 ? cost : 0
|
|
119
|
-
}
|
|
1
|
+
import { constants } from 'node:fs'
|
|
2
|
+
import { open } from 'node:fs/promises'
|
|
3
|
+
import { localDayKey, zeroDay } from './store.js'
|
|
4
|
+
import { fxRatesOf } from './exchange-rates.js'
|
|
5
|
+
import { costOf, providerPriceEntryFor, usdFromCost } from './pricing.js'
|
|
6
|
+
|
|
7
|
+
export const EXTERNAL_USAGE_MAX_BYTES = 512 * 1024
|
|
8
|
+
const MAX_AGE = 30 * 86400000
|
|
9
|
+
const FRESH_AGE = 86400000
|
|
10
|
+
const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls', 'cost', 'apiCost']
|
|
11
|
+
const object = v => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
12
|
+
const count = v => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 1e12
|
|
13
|
+
const money = v => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1e9
|
|
14
|
+
const dateKey = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v + 'T00:00:00Z')) && new Date(v + 'T00:00:00Z').toISOString().slice(0, 10) === v
|
|
15
|
+
const timestamp = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(v) && dateKey(v.slice(0, 10)) ? Date.parse(v) : NaN
|
|
16
|
+
|
|
17
|
+
function add(into, day) {
|
|
18
|
+
for (const key of fields) into[key] += day[key]
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function summary(days, dayKey) {
|
|
22
|
+
const today = zeroDay(dayKey)
|
|
23
|
+
const month = zeroDay(dayKey.slice(0, 7))
|
|
24
|
+
const total = zeroDay('total')
|
|
25
|
+
const history = Object.values(days).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 90)
|
|
26
|
+
for (const day of Object.values(days)) {
|
|
27
|
+
add(total, day)
|
|
28
|
+
if (day.date.startsWith(dayKey.slice(0, 7))) add(month, day)
|
|
29
|
+
if (day.date === dayKey) add(today, day)
|
|
30
|
+
}
|
|
31
|
+
return { today, month, total, history }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A snapshot replaces its predecessor; it never mutates the DSH ledger. */
|
|
35
|
+
export function parseExternalUsageSnapshot(value, config, nowMs = Date.now()) {
|
|
36
|
+
if (!object(value)) return null
|
|
37
|
+
if (Object.hasOwn(value, 'sources') && !Array.isArray(value.sources)) return null
|
|
38
|
+
const fetchedAt = timestamp(value.fetchedAt)
|
|
39
|
+
if (!Number.isFinite(fetchedAt) || fetchedAt > nowMs + 300000 || nowMs - fetchedAt > MAX_AGE) return null
|
|
40
|
+
const entries = Array.isArray(value.sources) ? value.sources : [value]
|
|
41
|
+
if (entries.length < 1 || entries.length > 8) return null
|
|
42
|
+
const seen = new Set()
|
|
43
|
+
const sources = []
|
|
44
|
+
const combinedDays = {}
|
|
45
|
+
let recordCount = 0
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
if (!object(entry) || typeof entry.source !== 'string' || entry.source.length < 1 || entry.source.length > 64 || seen.has(entry.source)) return null
|
|
48
|
+
seen.add(entry.source)
|
|
49
|
+
if (object(entry.days) === Array.isArray(entry.records)) return null // exactly one input mode
|
|
50
|
+
const days = {}
|
|
51
|
+
if (object(entry.days)) {
|
|
52
|
+
if (Object.keys(entry.days).length > 3660) return null
|
|
53
|
+
for (const [date, raw] of Object.entries(entry.days)) {
|
|
54
|
+
if (!dateKey(date) || date > localDayKey(nowMs) || !object(raw) || !count(raw.input) || !count(raw.output) || !count(raw.cached) || !count(raw.calls) || !money(raw.costUsd)) return null
|
|
55
|
+
if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
|
|
56
|
+
if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
|
|
57
|
+
days[date] = { ...zeroDay(date), input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0, calls: raw.calls, cost: raw.costUsd, apiCost: raw.costUsd }
|
|
58
|
+
}
|
|
59
|
+
} else {
|
|
60
|
+
recordCount += entry.records.length
|
|
61
|
+
if (recordCount > 5000) return null
|
|
62
|
+
const ids = new Set()
|
|
63
|
+
for (const raw of entry.records) {
|
|
64
|
+
if (!object(raw) || typeof raw.id !== 'string' || raw.id.length < 1 || raw.id.length > 128 || ids.has(raw.id)) return null
|
|
65
|
+
ids.add(raw.id)
|
|
66
|
+
const at = timestamp(raw.at)
|
|
67
|
+
if (!Number.isFinite(at) || at > nowMs + 300000 || !count(raw.input) || !count(raw.output) || !count(raw.cached)) return null
|
|
68
|
+
if (raw.cacheWrite !== undefined && !count(raw.cacheWrite)) return null
|
|
69
|
+
if (raw.reasoning !== undefined && !count(raw.reasoning)) return null
|
|
70
|
+
if (typeof raw.provider !== 'string' || !raw.provider || typeof raw.model !== 'string' || !raw.model) return null
|
|
71
|
+
const resolved = providerPriceEntryFor(raw.provider, raw.model, config?.prices, {
|
|
72
|
+
mode: config?.priceMatch === 'exact' ? 'exact' : 'auto', overrides: config?.priceOverrides,
|
|
73
|
+
})
|
|
74
|
+
if (!resolved.priced) return null
|
|
75
|
+
const peak = { enabled: ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && config?.peakEnabled === true,
|
|
76
|
+
effectiveAtMs: Date.parse(config?.peakEffectiveAt ?? ''), windows: config?.peakWindows, holidays: config?.peakHolidays }
|
|
77
|
+
const tokens = { input: raw.input, output: raw.output, cacheRead: raw.cached, cacheWrite: raw.cacheWrite ?? 0, reasoning: raw.reasoning ?? 0 }
|
|
78
|
+
const priced = costOf(tokens, resolved.entry, at, peak)
|
|
79
|
+
const usd = usdFromCost(priced, resolved.currency, fxRatesOf(config).CNY)
|
|
80
|
+
const date = localDayKey(at)
|
|
81
|
+
const day = days[date] ?? (days[date] = zeroDay(date))
|
|
82
|
+
for (const key of ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']) day[key] += tokens[key]
|
|
83
|
+
day.calls++
|
|
84
|
+
day.cost += usd
|
|
85
|
+
day.apiCost += usd
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
for (const [date, day] of Object.entries(days)) add(combinedDays[date] ?? (combinedDays[date] = zeroDay(date)), day)
|
|
89
|
+
sources.push({ source: entry.source, ...summary(days, localDayKey(nowMs)) })
|
|
90
|
+
}
|
|
91
|
+
return { fetchedAt, stale: nowMs - fetchedAt > FRESH_AGE, sources,
|
|
92
|
+
combined: summary(combinedDays, localDayKey(nowMs)) }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Bounded, fail-closed read of a regular file. Producers should write a temp file and rename it. */
|
|
96
|
+
export async function readExternalUsageSnapshot(path, config, nowMs = Date.now()) {
|
|
97
|
+
let file
|
|
98
|
+
try {
|
|
99
|
+
file = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
|
|
100
|
+
const stat = await file.stat()
|
|
101
|
+
if (!stat.isFile() || stat.size > EXTERNAL_USAGE_MAX_BYTES) return null
|
|
102
|
+
const buffer = Buffer.alloc(EXTERNAL_USAGE_MAX_BYTES + 1)
|
|
103
|
+
let length = 0
|
|
104
|
+
while (length < buffer.length) {
|
|
105
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null)
|
|
106
|
+
if (!bytesRead) break
|
|
107
|
+
length += bytesRead
|
|
108
|
+
}
|
|
109
|
+
if (length > EXTERNAL_USAGE_MAX_BYTES) return null
|
|
110
|
+
return parseExternalUsageSnapshot(JSON.parse(buffer.subarray(0, length).toString('utf8')), config, nowMs)
|
|
111
|
+
} catch { return null } finally { await file?.close().catch(() => {}) }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Fresh external usage participates in same-account balance reconciliation. */
|
|
115
|
+
export function externalTodayCostForReconcile(snapshot) {
|
|
116
|
+
if (snapshot?.stale === true) return null
|
|
117
|
+
const cost = snapshot?.combined?.today?.cost
|
|
118
|
+
return Number.isFinite(cost) && cost >= 0 ? cost : 0
|
|
119
|
+
}
|
package/lib/gateway-quotas.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { createHash } from 'node:crypto'
|
|
11
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
11
12
|
import { credentialRef } from '@deepseek-ai/dsh-credentials'
|
|
12
13
|
import { fetchWithRetry, readJsonBounded } from './net.js'
|
|
13
14
|
import {
|
|
@@ -227,14 +228,14 @@ function gatewayRetryDelay(response) {
|
|
|
227
228
|
return retryAfterMs(response) || GATEWAY_RETRY_DELAY_MS
|
|
228
229
|
}
|
|
229
230
|
|
|
230
|
-
const sleep = ms
|
|
231
|
+
const sleep = (ms, signal) => delay(ms, undefined, { signal })
|
|
231
232
|
|
|
232
233
|
async function discardResponse(response) {
|
|
233
234
|
// 重试前释放未消费的错误响应,避免多账号轮询占住连接池。
|
|
234
235
|
try { await response?.body?.cancel() } catch { /* 清理失败不掩盖原始 HTTP 错误。 */ }
|
|
235
236
|
}
|
|
236
237
|
|
|
237
|
-
async function readJsonResponse(response, phase, { maxBytes = MAX_BODY_BYTES } = {}) {
|
|
238
|
+
async function readJsonResponse(response, phase, { maxBytes = MAX_BODY_BYTES, signal } = {}) {
|
|
238
239
|
if (!response || typeof response.ok !== 'boolean') throw errorOf('CPA_RESPONSE_INVALID', `${phase} response is invalid`)
|
|
239
240
|
if (!response.ok) {
|
|
240
241
|
await discardResponse(response)
|
|
@@ -246,8 +247,11 @@ async function readJsonResponse(response, phase, { maxBytes = MAX_BODY_BYTES } =
|
|
|
246
247
|
await discardResponse(response)
|
|
247
248
|
throw errorOf('CPA_RESPONSE_INVALID', `${phase} response is too large`)
|
|
248
249
|
}
|
|
249
|
-
|
|
250
|
+
const body = await readJsonBounded(response, maxBytes, { signal })
|
|
251
|
+
signal?.throwIfAborted()
|
|
252
|
+
return body
|
|
250
253
|
} catch (error) {
|
|
254
|
+
signal?.throwIfAborted()
|
|
251
255
|
if (error?.code === 'CPA_RESPONSE_INVALID') throw error
|
|
252
256
|
throw errorOf('CPA_RESPONSE_INVALID', error?.code === 'RESPONSE_TOO_LARGE'
|
|
253
257
|
? `${phase} response is too large` : `${phase} response body is not readable JSON`)
|
|
@@ -256,18 +260,20 @@ async function readJsonResponse(response, phase, { maxBytes = MAX_BODY_BYTES } =
|
|
|
256
260
|
|
|
257
261
|
export async function cpaManagementFetch(url, key, init = {}, options = {}) {
|
|
258
262
|
const fetchImpl = options.fetchImpl ?? fetch
|
|
263
|
+
const signal = init.signal ?? options.signal
|
|
259
264
|
const headers = { ...(init.headers ?? {}), 'X-Management-Key': key }
|
|
260
265
|
let response
|
|
261
266
|
try {
|
|
262
|
-
response = await fetchWithRetry(url, { ...init, headers, redirect: 'manual' }, {
|
|
267
|
+
response = await fetchWithRetry(url, { ...init, headers, redirect: 'manual', signal }, {
|
|
263
268
|
attempts: 2, timeoutMs: init.timeoutMs ?? 15_000, fetchImpl,
|
|
264
269
|
})
|
|
265
270
|
} catch (error) {
|
|
271
|
+
signal?.throwIfAborted()
|
|
266
272
|
if (error?.code) throw error
|
|
267
273
|
throw errorOf('CPA_OUTER_HTTP_ERROR', 'management request failed', { status: 0 })
|
|
268
274
|
}
|
|
269
|
-
if (response.status >= 300 && response.status < 400) throw errorOf('CPA_REDIRECT_REFUSED', 'CPA redirect refused', { status: response.status })
|
|
270
|
-
return readJsonResponse(response, new URL(url).pathname)
|
|
275
|
+
if (response.status >= 300 && response.status < 400) { await discardResponse(response); throw errorOf('CPA_REDIRECT_REFUSED', 'CPA redirect refused', { status: response.status }) }
|
|
276
|
+
return readJsonResponse(response, new URL(url).pathname, { signal })
|
|
271
277
|
}
|
|
272
278
|
|
|
273
279
|
async function fetchManagement(source, path, managementKey, options = {}) {
|
|
@@ -281,21 +287,22 @@ async function fetchManagement(source, path, managementKey, options = {}) {
|
|
|
281
287
|
for (let attempt = 0; attempt < GATEWAY_RESPONSE_ATTEMPTS; attempt++) {
|
|
282
288
|
let response
|
|
283
289
|
try {
|
|
284
|
-
response = await fetchWithRetry(url, { method: 'GET', headers, redirect: 'manual' }, {
|
|
290
|
+
response = await fetchWithRetry(url, { method: 'GET', headers, redirect: 'manual', signal: options.signal }, {
|
|
285
291
|
attempts: 2, timeoutMs: 15_000, fetchImpl,
|
|
286
292
|
})
|
|
287
293
|
} catch (error) {
|
|
294
|
+
options.signal?.throwIfAborted()
|
|
288
295
|
if (error?.code) throw error
|
|
289
296
|
throw errorOf('CPA_OUTER_HTTP_ERROR', 'management request failed', { status: 0 })
|
|
290
297
|
}
|
|
291
|
-
if (response.status >= 300 && response.status < 400) throw errorOf('CPA_REDIRECT_REFUSED', 'CPA redirect refused', { status: response.status })
|
|
298
|
+
if (response.status >= 300 && response.status < 400) { await discardResponse(response); throw errorOf('CPA_REDIRECT_REFUSED', 'CPA redirect refused', { status: response.status }) }
|
|
292
299
|
// 管理端临时过载/限流时按 Retry-After 或短退避再试一次。
|
|
293
300
|
if (isRetryableGatewayStatus(response.status) && attempt + 1 < GATEWAY_RESPONSE_ATTEMPTS) {
|
|
294
301
|
await discardResponse(response)
|
|
295
|
-
await sleep(gatewayRetryDelay(response))
|
|
302
|
+
await sleep(gatewayRetryDelay(response), options.signal)
|
|
296
303
|
continue
|
|
297
304
|
}
|
|
298
|
-
return { payload: await readJsonResponse(response, path), serverVersion: headerValue(response.headers, 'x-cpa-version') }
|
|
305
|
+
return { payload: await readJsonResponse(response, path, options), serverVersion: headerValue(response.headers, 'x-cpa-version') }
|
|
299
306
|
}
|
|
300
307
|
throw errorOf('CPA_OUTER_HTTP_ERROR', 'management request failed', { status: 0 })
|
|
301
308
|
}
|
|
@@ -415,6 +422,7 @@ function normalizeInnerEnvelope(payload, phase) {
|
|
|
415
422
|
}
|
|
416
423
|
|
|
417
424
|
async function apiCall(source, managementKey, account, request, options = {}) {
|
|
425
|
+
options.signal?.throwIfAborted()
|
|
418
426
|
const fetchImpl = options.fetchImpl ?? fetch
|
|
419
427
|
// 副作用端点硬闸(FORBIDDEN_REQUEST_MARKERS 的实际执行点):任何请求(URL 或
|
|
420
428
|
// body 序列化)命中消费/补全端点标记即拒绝发出——深度防御,防未来 adapter
|
|
@@ -448,25 +456,27 @@ async function apiCall(source, managementKey, account, request, options = {}) {
|
|
|
448
456
|
signal: options.signal,
|
|
449
457
|
}, { attempts: 2, timeoutMs: 30_000, fetchImpl })
|
|
450
458
|
} catch (error) {
|
|
459
|
+
options.signal?.throwIfAborted()
|
|
451
460
|
if (error?.code) throw error
|
|
452
461
|
throw errorOf('CPA_OUTER_HTTP_ERROR', 'CPA api-call failed')
|
|
453
462
|
}
|
|
454
|
-
if (response.status >= 300 && response.status < 400) throw errorOf('CPA_REDIRECT_REFUSED', 'CPA redirect refused', { status: response.status })
|
|
463
|
+
if (response.status >= 300 && response.status < 400) { await discardResponse(response); throw errorOf('CPA_REDIRECT_REFUSED', 'CPA redirect refused', { status: response.status }) }
|
|
455
464
|
// api-call 是副作用闸门已校验的只读额度请求;仅对暂态管理端状态重放一次。
|
|
456
465
|
if (isRetryableGatewayStatus(response.status) && attempt + 1 < GATEWAY_RESPONSE_ATTEMPTS) {
|
|
457
466
|
await discardResponse(response)
|
|
458
|
-
await sleep(gatewayRetryDelay(response))
|
|
467
|
+
await sleep(gatewayRetryDelay(response), options.signal)
|
|
459
468
|
continue
|
|
460
469
|
}
|
|
461
470
|
try {
|
|
462
|
-
const envelope = await readJsonResponse(response, 'api-call')
|
|
471
|
+
const envelope = await readJsonResponse(response, 'api-call', options)
|
|
463
472
|
return normalizeInnerEnvelope(envelope, 'api-call')
|
|
464
473
|
} catch (error) {
|
|
474
|
+
options.signal?.throwIfAborted()
|
|
465
475
|
// CPA 把上游 HTTP 状态装进 JSON envelope。429/5xx 同样属于暂态,
|
|
466
476
|
// 但认证、策略与格式错误绝不重试。
|
|
467
477
|
if (error?.code === 'CPA_INNER_HTTP_ERROR' && isRetryableGatewayStatus(error.status)
|
|
468
478
|
&& attempt + 1 < GATEWAY_RESPONSE_ATTEMPTS) {
|
|
469
|
-
await sleep(GATEWAY_RETRY_DELAY_MS)
|
|
479
|
+
await sleep(GATEWAY_RETRY_DELAY_MS, options.signal)
|
|
470
480
|
continue
|
|
471
481
|
}
|
|
472
482
|
throw error
|
|
@@ -476,6 +486,7 @@ async function apiCall(source, managementKey, account, request, options = {}) {
|
|
|
476
486
|
}
|
|
477
487
|
|
|
478
488
|
async function queryApiAccount(source, managementKey, account, options = {}) {
|
|
489
|
+
options.signal?.throwIfAborted()
|
|
479
490
|
const adapter = GATEWAY_PROVIDER_ADAPTERS[account.provider]
|
|
480
491
|
if (!adapter || typeof adapter.requests !== 'function') return publicAccount(account, { status: 'unsupported', message: 'provider adapter is unavailable' })
|
|
481
492
|
if (account.provider === 'codex' && !account.authIndex) return publicAccount(account, { status: 'capability_missing', message: 'PROVIDER_CAPABILITY_MISSING: Codex account metadata is missing' })
|
|
@@ -490,6 +501,7 @@ async function queryApiAccount(source, managementKey, account, options = {}) {
|
|
|
490
501
|
bodies[index] = await apiCall(source, managementKey, account, requests[index], options)
|
|
491
502
|
if (account.provider !== 'xai') break
|
|
492
503
|
} catch (error) {
|
|
504
|
+
options.signal?.throwIfAborted()
|
|
493
505
|
lastError = error
|
|
494
506
|
if (account.provider === 'antigravity' && (error.code === 'CPA_INNER_HTTP_ERROR' || error.status === 404 || error.status === 403)) continue
|
|
495
507
|
if (account.provider === 'xai') continue
|
|
@@ -546,6 +558,7 @@ async function queryApiAccount(source, managementKey, account, options = {}) {
|
|
|
546
558
|
)
|
|
547
559
|
return publicAccount(account, { status: 'ok', windows: parsed.windows, plan: parsed.plan })
|
|
548
560
|
} catch (error) {
|
|
561
|
+
options.signal?.throwIfAborted()
|
|
549
562
|
const code = error?.code || 'PROVIDER_PARSE_ERROR'
|
|
550
563
|
return publicAccount(account, { status: 'error', message: safeMessage(code, error?.message) })
|
|
551
564
|
}
|
|
@@ -581,6 +594,7 @@ async function queryWorkBuddy(source, managementKey, discovered, options = {}) {
|
|
|
581
594
|
})
|
|
582
595
|
})
|
|
583
596
|
} catch (error) {
|
|
597
|
+
options.signal?.throwIfAborted()
|
|
584
598
|
const code = error?.status === 404 ? 'WORKBUDDY_PLUGIN_UNAVAILABLE' : error?.code || 'CPA_OUTER_HTTP_ERROR'
|
|
585
599
|
return discovered.map(account => publicAccount(account, { status: 'error', message: safeMessage(code, error?.message) }))
|
|
586
600
|
}
|
|
@@ -608,10 +622,12 @@ export const emptyGatewayQuotaSource = emptyGatewayQuota
|
|
|
608
622
|
|
|
609
623
|
/** Query one source. The returned object is safe for strict public state. */
|
|
610
624
|
export async function queryGatewayQuota(ctx, rawSource, options = {}) {
|
|
625
|
+
options.signal?.throwIfAborted()
|
|
611
626
|
const source = validateGatewaySource(rawSource)
|
|
612
627
|
const clock = typeof options.now === 'function' ? options.now : () => typeof options.now === 'number' ? options.now : Date.now()
|
|
613
628
|
const attemptedAt = Number(clock()) || Date.now()
|
|
614
629
|
const key = await resolveManagementKey(ctx, source)
|
|
630
|
+
options.signal?.throwIfAborted()
|
|
615
631
|
const base = { ...emptyGatewayQuota(source), attemptedAt, keyConfigured: key.configured, keySource: key.source }
|
|
616
632
|
if (!source.enabled || source.display === 'off') return { ...base, status: 'off' }
|
|
617
633
|
if (!key.configured) return { ...base, status: 'error', message: 'CPA_AUTH_FAILED: management key is not configured' }
|
|
@@ -623,6 +639,7 @@ export async function queryGatewayQuota(ctx, rawSource, options = {}) {
|
|
|
623
639
|
authPayload = response.payload
|
|
624
640
|
version = response.serverVersion
|
|
625
641
|
} catch (error) {
|
|
642
|
+
options.signal?.throwIfAborted()
|
|
626
643
|
return { ...base, status: 'error', message: safeMessage(error?.code || 'CPA_OUTER_HTTP_ERROR', error?.message) }
|
|
627
644
|
}
|
|
628
645
|
let discovery
|
|
@@ -634,7 +651,9 @@ export async function queryGatewayQuota(ctx, rawSource, options = {}) {
|
|
|
634
651
|
const normal = discovery.accounts.filter(account => account.provider !== 'workbuddy')
|
|
635
652
|
const work = discovery.accounts.filter(account => account.provider === 'workbuddy')
|
|
636
653
|
const apiAccounts = await runLimited(normal, DEFAULT_CONCURRENCY, account => queryApiAccount(source, key.value, account, { ...options, fetchImpl }))
|
|
654
|
+
options.signal?.throwIfAborted()
|
|
637
655
|
const workAccounts = work.length > 0 ? await queryWorkBuddy(source, key.value, work, { ...options, fetchImpl }) : []
|
|
656
|
+
options.signal?.throwIfAborted()
|
|
638
657
|
const accounts = [...apiAccounts, ...workAccounts]
|
|
639
658
|
const successes = accounts.filter(account => account.status === 'ok').length
|
|
640
659
|
const failures = accounts.filter(account => account.status === 'error' || account.status === 'capability_missing').length
|
package/lib/index.js
CHANGED
|
@@ -164,9 +164,9 @@ const SERVER_MESSAGES = {
|
|
|
164
164
|
mimoCookieMissing: '未找到 {provider} 的凭据。请粘贴小米开放平台控制台的 Cookie(登录 platform.xiaomimimo.com 后 F12→网络→balanceAlertConfig→请求头 cookie 整段复制),或配置 MIMO_COOKIE 环境变量;tp-*/ttp-* 专用 Key 无用量端点,不支持额度查询。',
|
|
165
165
|
mimoCookieInvalid: '{provider} 的 Cookie 缺少必需字段(需要 serviceToken 与 userId)。请从浏览器重新复制整段 cookie 请求头;tp-*/ttp-* 专用 Key 不支持额度查询。',
|
|
166
166
|
mimoLoginExpired: '{provider} 的控制台登录态已过期。请重新登录 platform.xiaomimimo.com 并复制新的 Cookie。',
|
|
167
|
-
workbuddyNotInstalled: '未找到 {provider}
|
|
168
|
-
workbuddyAuthEncrypted: '{provider} 的登录文件已加密。请在当前 DSH 中启用
|
|
169
|
-
workbuddyConnectUnavailable: '无法读取 WorkBuddy
|
|
167
|
+
workbuddyNotInstalled: '未找到 {provider} 的登录凭据。请先在 WorkBuddy App 登录,并启用 WorkBuddy 连接插件或 dsh-xdpool。',
|
|
168
|
+
workbuddyAuthEncrypted: '{provider} 的登录文件已加密。请在当前 DSH 中启用 WorkBuddy 连接插件或 dsh-xdpool,然后刷新积分。',
|
|
169
|
+
workbuddyConnectUnavailable: '无法读取 WorkBuddy 积分来源,请确认所选连接插件或 dsh-xdpool 已启用并完成启动。',
|
|
170
170
|
workbuddyConnectLoginFailed: 'WorkBuddy 连接插件无法读取登录状态。请在其插件卡片查看登录诊断,并检查 WorkBuddy App 的安装路径与登录状态。',
|
|
171
171
|
workbuddyConnectCreditsFailed: 'WorkBuddy 已登录,但连接插件未返回有效积分。请在对应 WorkBuddy 连接插件卡片刷新并查看查询结果。',
|
|
172
172
|
workbuddyTokenExpired: '{provider} 的登录态已过期。请打开 WorkBuddy App 重新登录后重试。',
|
|
@@ -265,9 +265,9 @@ const SERVER_MESSAGES = {
|
|
|
265
265
|
mimoCookieMissing: 'No credentials found for {provider}. Paste the Xiaomi MiMo console cookie (log in at platform.xiaomimimo.com, then F12 → Network → balanceAlertConfig → copy the full cookie request header), or set the MIMO_COOKIE environment variable; tp-*/ttp-* plan keys have no usage endpoint and cannot query quotas.',
|
|
266
266
|
mimoCookieInvalid: 'The {provider} cookie is missing required fields (serviceToken and userId). Copy the full cookie request header from your browser again; tp-*/ttp-* plan keys cannot query quotas.',
|
|
267
267
|
mimoLoginExpired: 'The {provider} console login has expired. Log in at platform.xiaomimimo.com again and copy a fresh cookie.',
|
|
268
|
-
workbuddyNotInstalled: 'No {provider} login credential found. Sign in
|
|
269
|
-
workbuddyAuthEncrypted: 'The {provider} auth file is encrypted. Enable
|
|
270
|
-
workbuddyConnectUnavailable: 'Cannot read the WorkBuddy
|
|
268
|
+
workbuddyNotInstalled: 'No {provider} login credential found. Sign in to the WorkBuddy app and enable a WorkBuddy connector or dsh-xdpool.',
|
|
269
|
+
workbuddyAuthEncrypted: 'The {provider} auth file is encrypted. Enable a WorkBuddy connector or dsh-xdpool in this DSH host, then refresh credits.',
|
|
270
|
+
workbuddyConnectUnavailable: 'Cannot read the WorkBuddy credit source. Check that the selected connector or dsh-xdpool is enabled and has finished starting.',
|
|
271
271
|
workbuddyConnectLoginFailed: 'The WorkBuddy connector cannot read the login. Check its plugin card diagnostics and the WorkBuddy app installation path and login.',
|
|
272
272
|
workbuddyConnectCreditsFailed: 'WorkBuddy is signed in, but the connector returned no valid credits. Refresh its plugin card and check the query result.',
|
|
273
273
|
workbuddyTokenExpired: 'The {provider} login has expired. Open the WorkBuddy app, sign in again, and retry.',
|
|
@@ -1627,6 +1627,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
1627
1627
|
ctx.effect(() => () => {
|
|
1628
1628
|
active = false
|
|
1629
1629
|
qwenLogin?.controller.abort()
|
|
1630
|
+
for (const cache of Object.values(gatewayQuotaCaches)) cache.controller?.abort()
|
|
1630
1631
|
gatewayQuotaCaches = {}
|
|
1631
1632
|
resetQueryCache('balance')
|
|
1632
1633
|
resetQueryCache('goQuota')
|
|
@@ -1697,6 +1698,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
1697
1698
|
next[source.id] = previous
|
|
1698
1699
|
}
|
|
1699
1700
|
}
|
|
1701
|
+
for (const [id, cache] of Object.entries(gatewayQuotaCaches)) if (next[id] !== cache) cache.controller?.abort()
|
|
1700
1702
|
gatewayQuotaCaches = next
|
|
1701
1703
|
}
|
|
1702
1704
|
const resolveGatewayKeyConfigured = async (serviceCtx, source) => {
|
|
@@ -2247,8 +2249,8 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2247
2249
|
if (!currentSource()) return emptyGatewayForSource(source)
|
|
2248
2250
|
let cache = gatewayQuotaCaches[id]
|
|
2249
2251
|
if (cache === undefined || cache.configFingerprint !== configFingerprint || cache.keyConfigured !== configured) {
|
|
2250
|
-
//
|
|
2251
|
-
|
|
2252
|
+
// A changed source cancels its old request and starts with an empty cache.
|
|
2253
|
+
cache?.controller?.abort()
|
|
2252
2254
|
cache = { fetchedAt: 0, value: emptyGatewayForSource(source), lastGood: null, sourceFingerprint: fingerprint,
|
|
2253
2255
|
configFingerprint, keyConfigured: configured }
|
|
2254
2256
|
gatewayQuotaCaches[id] = cache
|
|
@@ -2267,7 +2269,8 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2267
2269
|
cache = gatewayQuotaCaches[id]
|
|
2268
2270
|
if (cache === undefined || cache.inFlight !== undefined) return ensureGatewayQuota(source, true)
|
|
2269
2271
|
}
|
|
2270
|
-
const
|
|
2272
|
+
const controller = new AbortController()
|
|
2273
|
+
const task = queryGatewayQuota(ctx, source, { signal: controller.signal }).then(value => {
|
|
2271
2274
|
const active = gatewayQuotaCaches[id]
|
|
2272
2275
|
if (active?.inFlight !== task || active.sourceFingerprint !== fingerprint) return value
|
|
2273
2276
|
const ok = gatewayValueIsLastGood(value)
|
|
@@ -2288,11 +2291,11 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2288
2291
|
return next
|
|
2289
2292
|
}).finally(() => {
|
|
2290
2293
|
if (gatewayQuotaCaches[id]?.inFlight === task) {
|
|
2291
|
-
const { inFlight: _drop, ...rest } = gatewayQuotaCaches[id]
|
|
2294
|
+
const { inFlight: _drop, controller: _controller, ...rest } = gatewayQuotaCaches[id]
|
|
2292
2295
|
gatewayQuotaCaches[id] = rest
|
|
2293
2296
|
}
|
|
2294
2297
|
})
|
|
2295
|
-
gatewayQuotaCaches[id] = { ...cache, inFlight: task, sourceFingerprint: fingerprint }
|
|
2298
|
+
gatewayQuotaCaches[id] = { ...cache, inFlight: task, controller, sourceFingerprint: fingerprint }
|
|
2296
2299
|
return task
|
|
2297
2300
|
}
|
|
2298
2301
|
|
|
@@ -2726,7 +2729,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2726
2729
|
// 的下一次刷新才会真正带上新密钥(否则 15 分钟内仍展示旧值/旧错误)。
|
|
2727
2730
|
if (customVar !== null) {
|
|
2728
2731
|
invalidateCustomBalanceCachesForVar(customVar)
|
|
2729
|
-
for (const source of gatewaySourceConfigs()) if (managementKeyVarOf(source) === customVar) delete gatewayQuotaCaches[source.id]
|
|
2732
|
+
for (const source of gatewaySourceConfigs()) if (managementKeyVarOf(source) === customVar) { gatewayQuotaCaches[source.id]?.controller?.abort(); delete gatewayQuotaCaches[source.id] }
|
|
2730
2733
|
}
|
|
2731
2734
|
else resetQueryCache(key)
|
|
2732
2735
|
if (key === 'balance') {
|
|
@@ -2772,7 +2775,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2772
2775
|
}
|
|
2773
2776
|
if (customVar !== null) {
|
|
2774
2777
|
invalidateCustomBalanceCachesForVar(customVar)
|
|
2775
|
-
for (const source of gatewaySourceConfigs()) if (managementKeyVarOf(source) === customVar) delete gatewayQuotaCaches[source.id]
|
|
2778
|
+
for (const source of gatewaySourceConfigs()) if (managementKeyVarOf(source) === customVar) { gatewayQuotaCaches[source.id]?.controller?.abort(); delete gatewayQuotaCaches[source.id] }
|
|
2776
2779
|
}
|
|
2777
2780
|
else resetQueryCache(key)
|
|
2778
2781
|
if (key === 'balance') {
|
|
@@ -3556,6 +3559,12 @@ export async function runStartupImports(ledger, sessionsRoot, sessionSource = nu
|
|
|
3556
3559
|
ledger.migrations.push('workbuddy-global-provider-split-v1')
|
|
3557
3560
|
ledger.scheduleWrite()
|
|
3558
3561
|
}
|
|
3562
|
+
// XD Pool's CN/global lanes consume WorkBuddy credits; aggregate lanes are separate.
|
|
3563
|
+
if (!ledger.migrations.includes('xdpool-workbuddy-provider-split-v1')) {
|
|
3564
|
+
splitLedgerApiCost(ledger)
|
|
3565
|
+
ledger.migrations.push('xdpool-workbuddy-provider-split-v1')
|
|
3566
|
+
ledger.scheduleWrite()
|
|
3567
|
+
}
|
|
3559
3568
|
if (ledger.migrations.includes(SEPTEMBER_PRICE_PENDING)) {
|
|
3560
3569
|
const options = { mode: ledger.config.priceMatch, overrides: ledger.config.priceOverrides }
|
|
3561
3570
|
const boundaries = new Set([FLASH_PRICE_EFFECTIVE_AT])
|