dsh-cost-meter 1.9.74 → 1.9.76
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 +4 -4
- package/README.zh-CN.md +4 -4
- package/docs/custom-balance-sources.en.md +2 -0
- package/docs/custom-balance-sources.md +2 -0
- package/docs/plugin-compatibility-watch.md +4 -0
- package/docs/web-request-fees.md +5 -3
- package/lib/agy-link-quota.js +95 -0
- package/lib/aliyun-balance.js +329 -28
- package/lib/backfill.js +6 -5
- package/lib/client.js +10 -10
- package/lib/client.plan-settings.js +1 -1
- package/lib/coding-plans.js +20 -10
- package/lib/gateway-quotas.js +1 -1
- package/lib/index.js +34 -10
- package/lib/ledger-writer-worker.js +1 -1
- package/lib/native-search-manual.js +2 -2
- package/lib/store.js +9 -8
- package/lib/turn-cost.js +3 -1
- package/lib/typert.host.js +3 -3
- package/lib/web-request-pricing.js +12 -3
- package/lib/zai-credentials.js +25 -0
- package/package.json +2 -2
- package/docs/update-notes-1.9.74.md +0 -31
|
@@ -1 +1 @@
|
|
|
1
|
-
;(function(e){const S=window.__ModuleLoader__,H=S[Symbol.for("@dsh-plugin/dsh-loader:load-wrap")];return(e.id==="dsh-cost-meter"&&S.load===H?.ours&&typeof H.original=="function"?H.original:S.load).call(S,e)})({id:"dsh-cost-meter",chunk:"client.plan-settings.js",factory:ae=>{const{createElement:e,useState:S,useEffect:H,useRef:ne,Fragment:R}=ae("react"),J={kimi:{checkedAt:"2026-10-28",sourceUrl:"https://www.kimi.com/code/docs/kimi-code/membership.html",tiers:["Go","Plus","Pro","Max","Ultra"],legacyTiers:["Andante","Moderato","Allegretto","Vivace"],models:["k3.1-pro","k3.1-pro-highspeed","k3","k3-256k","kimi-for-coding","kimi-for-coding-highspeed"],zh:"新套餐:Go、Plus、Pro、Max、Ultra。Plus 起提供 Kimi Code,Pro 起提供高速版和 1M 上下文。新套餐使用 5 小时窗口及月总额度;老套餐保留周窗口。",en:"Current tiers: Go, Plus, Pro, Max and Ultra. Kimi Code starts at Plus; Pro adds Highspeed and 1M context. New plans use a 5-hour window and monthly total; legacy plans retain weekly limits."},minimax:{checkedAt:"2026-10-28",sourceUrl:"https://platform.minimax.io/docs/m-plan/intro",tiers:["Go","Explore","Build"],legacyTiers:["Plus","Max","Ultra"],models:["MiniMax-M3.1-Flash"],zh:"M Plan:Go、Explore、Build,均包含 M3.1 Flash;Explore、Build 另含 H3 视频。原 Token Plan 的 Plus、Max、Ultra 保留。使用现有 MiniMax 查询凭据。",en:"M Plan: Go, Explore and Build, all including M3.1 Flash. Explore and Build also include H3 video. Legacy Token Plan Plus, Max and Ultra remain. Uses the existing MiniMax quota credential."},go:{checkedAt:"2026-10-28",sourceUrl:"https://opencode.ai/v2/docs/console/go/",tiers:["Go","Go Plus"],models:["kimi-k3.1-pro","minimax-m3.1-flash","step-5-preview","gemini-4-argon","beam-free","iceman-contributor-free"],zh:"Go 为 $10/月,Go Plus 为 $40/月。新增 Kimi K3.1 Pro、MiniMax M3.1 Flash 等模型,各模型使用独立的月度额度标准。",en:"Go costs $10/month; Go Plus costs $40/month. Includes Kimi K3.1 Pro, MiniMax M3.1 Flash and other additions, with model-specific monthly allowances."},"tencent-token":{checkedAt:"2026-10-28",sourceUrl:"https://cloud.tencent.com/document/product/1823/130060",tiers:["Lite","Standard","Pro","Max"],products:["Token Plan","Hy Token Plan"],zh:"腾讯通用 Token Plan 与 Hy Token Plan 共用 API Key 和请求地址,按模型从对应套餐扣减积分。当前支持套餐归属统计。",en:"Tencent Token Plan and Hy Token Plan share an API key and endpoints; credits are deducted from the applicable plan for each model. Plan classification is supported."}};return{mount(ie){const{useQuotaRefresh:Q,miniMaxWindowsOf:Y,MiniMaxPlanCard:re,barDirectionOf:z,quotaWindowRow:ue,codingPlanWindowLabel:de,codingPlanWindowEntries:me,numInput:te,CredentialField:le,QuotaCard:se,resolveLocale:L,formatMoneyUsd:oe,formatBalanceMoney:pe,quotaPlacementValue:ge,quotaPlacementPatch:be,quotaPlacementOptions:he,displayOptions:fe,BalanceBar:ye,segmentsForCustomBalance:ve,customBalanceUnitOf:Ne,customBalanceDetailText:ce,formatCustomBalanceMoney:Ce,resolveCustomBalanceLabel:ke}=ie;function we(k){const{state:u,api:w,t:a,entry:n,index:h,canRemove:l,onPatch:f,onRemove:N}=k,T=n.adapter==="aliyun",o=n.adapter==="tokenrhythm",r=n.adapter==="openai-credits",A=T||o||r,[c,p]=S(!1),q=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[M,O]=S(q),[B,I]=S(()=>(n.allowedHosts??[]).join(", ")),[U,x]=S({}),C=ne(!1),y=u.config,P=(Array.isArray(u.customBalances)?u.customBalances:[]).find(t=>t.index===h)??null,i=n.enabled===!0,v=()=>{p(t=>!t)};H(()=>{c&&!C.current&&(O(q()),I((n.allowedHosts??[]).join(", ")),x({})),C.current=c},[c]);const g=(t,m)=>f({[t]:m}),K=(t,m)=>f({request:{...n.request??{},[t]:m}}),G=T?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:o?["TOKENRHYTHM_COOKIE"]:r?["DSH_OPENAI_COST_ADMIN_KEY"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(t=>typeof t=="string"?[...t.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(m=>m[1]):[]))],$=(t,m)=>{O(b=>({...b,[t]:m}));try{const b=t==="body",E=b&&!m.trim()?void 0:JSON.parse(m);if(!b&&(E===null||typeof E!="object"||Array.isArray(E)))throw new Error("invalid");if(t==="headers"&&Object.values(E).some(D=>typeof D!="string"))throw new Error("invalid");x(D=>({...D,[t]:""})),t==="extract"?g(t,E):K(t,b?E===void 0?void 0:m:E)}catch{x(b=>({...b,[t]:a("customBalanceInvalidJson")}))}},j=(t,m,b,E)=>!A&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(m)),E&&e("span",{className:"cm-hint"},a(E)),e("textarea",{className:"cm-input",rows:b,value:M[t],onChange:D=>$(t,D.target.value)}),U[t]?e("span",{className:"cm-hint err"},U[t]):null),Z=t=>{I(t);const m=t.split(/[\s,;]+/).map(b=>b.trim()).filter(b=>b.length>0);g("allowedHosts",m)},[_,X,ee]=Q(a,()=>(y.customBalances??[])[h]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):w.refreshCustomBalance(h)),s=P!==null&&P.status==="ok"?r?e("div",{className:"cm-bal-line"},ce(P,y,a,u,y.customBalances?.[h]??n)):e(R,null,y.balance?.showProgressBar===!0&&!o?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(ye,{segments:ve(u,y,P,n),direction:z(y,"balance")}),e("div",{className:"cm-bal-line"},ce(P,y,a,u,n))):e("div",{className:"cm-bal-line"},a("customBalanceRemaining",{amount:Ce(P.remaining,y,P,n)}))):P!==null&&P.status==="error"?e("div",{className:"cm-bal-line err"},P.message||a("unknownError")):e("div",{className:"cm-bal-line"},P?.message||a("balanceNotQueried")),d=e(R,null,e("p",{className:"cm-note"},a(r?"openAiCreditNote":o?"tokenRhythmBalanceNote":T?"aliyunBalanceNote":"customBalanceConfigNote")),!o&&!r&&e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:Ne(y,P,n)!=="USD",onChange:t=>g("convertToDisplayCurrency",t.target.checked)}),a("customBalanceConvert")),!o&&!r&&e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},r?e(R,null,e("label",{className:"cm-field"},a("openAiCreditAmount"),e("input",{className:"cm-input",type:"number",min:0,step:"0.01",value:n.grantAmount||"",onChange:t=>g("grantAmount",t.target.valueAsNumber||0)})),...[["grantStart","openAiCreditStart"],["grantExpiry","openAiCreditExpiry"]].map(([t,m])=>e("label",{className:"cm-field",key:t},a(m),e("input",{className:"cm-input",type:"date",value:n[t]??"",onChange:b=>g(t,b.target.value)}))),e("a",{href:n.dashboardUrl,target:"_blank",rel:"noopener noreferrer"},a("openAiCreditBilling"))):[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([t,m])=>e("div",{key:t,className:"cm-field"},e("label",null,a(m)),e("input",{className:"cm-input",value:n[t]??"",onChange:b=>g(t,b.target.value)}))),!r&&e("label",{className:"cm-field"},e("span",null,L(y)==="en"?"Dashboard link (optional)":"跳转链接(可选)"),e("input",{className:"cm-input",type:"url","aria-label":L(y)==="en"?"Dashboard link":"跳转链接",value:n.dashboardUrl??"",placeholder:"https://example.com/account",onChange:t=>g("dashboardUrl",t.target.value)})),!A&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:t=>g("unit",t.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:t=>g("display",t.target.value)},...fe(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),te({value:n.refreshMinutes??15},t=>g("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(t)))))),!A&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:t=>K("method",t.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!A&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"/plugins/dsh-workbuddy-connect/status",onChange:t=>K("url",t.target.value)}),e("span",{className:"cm-hint"},a("customBalanceUrlHint"))),j("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&j("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,r?"OpenAI Admin API Key":o?"Token Rhythm Cookie":a("customBalanceCredentialsTitle")),G.length>0?e(R,null,!A&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),G.map(t=>e(le,{key:"cb-var-"+t,target:"customVar:"+t,configured:(u.customVarStatus?.[t]?.configured??!1)===!0,source:u.customVarStatus?.[t]?.source??"",t:a,api:w,placeholder:r?"sk-admin-…":o?"tr_session=…":"{{"+t+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!A&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:B,placeholder:"api.example.com, relay.example.org",onChange:t=>Z(t.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),!A&&e("label",{className:"cm-check",style:{gridColumn:"1 / -1"}},e("input",{type:"checkbox",checked:n.allowInsecureHttp===!0,onChange:t=>g("allowInsecureHttp",t.target.checked)}),a("customBalanceHttp")),j("extract","customBalanceExtract",8)));return e(se,{name:`#${h+1} · `+(ke(n,L(y))||a("customBalanceTitle")),enabled:i,saved:JSON.stringify(n)===JSON.stringify(y.customBalances?.[h])?y.customBalances[h]:null,busy:_,open:c,statusNode:s,configNode:d,errorMsg:X,onToggle:t=>g("enabled",t),onRefresh:ee,onRemove:l?N:null,onToggleOpen:v,t:a})}function V(k){const{state:u,draft:w,setDraft:a,target:n,api:h}=k,l=(i,v)=>L(u.config)==="en"?v:i,f=n.replace(/\.(ak|sk)$/,""),N=f==="balance"?l("当前账号","Current account"):l("查询并显示的账号","Account to query and display"),T=(w??u.config).queryAccounts??{},o=T[f]??{selected:"default",accounts:[]},r=u.config.queryAccounts?.[f]?.selected??"default",[A,c]=S(""),[p,q]=S(!1),[M,O]=S(""),B=o.accounts.find(i=>i.id===o.selected),[I,U]=S(B?.label??"");H(()=>U(B?.label??""),[B?.id,B?.label]);const x=r!==o.selected||w===null||p,C=i=>a({...w,queryAccounts:{...T,[f]:i}}),y=()=>{const i=A.trim();if(!i||o.accounts.length>=10||x)return;if(o.accounts.some(g=>g.label.toLowerCase()===i.toLowerCase())){O(l("账号名称已存在","Account name already exists"));return}const v=crypto.randomUUID();C({selected:v,accounts:[...o.accounts,{id:v,label:i}]}),c(""),O("")},F=()=>{const i=I.trim();if(!(!i||x||!B)){if(o.accounts.some(v=>v.id!==B.id&&v.label.toLowerCase()===i.toLowerCase())){O(l("账号名称已存在","Account name already exists"));return}C({...o,accounts:o.accounts.map(v=>v.id===B.id?{...v,label:i}:v)}),O("")}},P=async()=>{if(!(x||o.selected==="default")){q(!0),O("");try{const i=f==="codingPlans.volcengine"?[f+".ak",f+".sk"]:[f];for(const g of i)await h.clearCredential(g+"@"+o.selected);const v=o.accounts.filter(g=>g.id!==o.selected);C({selected:f==="balance"?v[0]?.id??"default":"default",accounts:v})}catch(i){O(String(i?.message??i))}finally{q(!1)}}};return e("div",{"data-query-account":n},n.endsWith(".sk")?null:e("div",{className:"cm-field"},e("label",null,N,e("select",{className:"cm-input","aria-label":N,value:o.selected,disabled:p||w===null,onChange:i=>C({...o,selected:i.target.value})},e("option",{value:"default"},l("默认账号(现有配置)","Default account (existing configuration)")),...o.accounts.map(i=>e("option",{key:i.id,value:i.id},i.label)))),e("div",{className:"cm-buttons"},e("input",{className:"cm-input",type:"text",value:A,maxLength:64,autoComplete:"off","aria-label":l("新账号名称","New account name"),placeholder:l("如:工作账号","e.g. Work account"),disabled:x,onChange:i=>c(i.target.value),style:{minWidth:0,flex:1}}),e("button",{className:"cm-btn small",type:"button",disabled:x||!A.trim()||o.accounts.length>=10,onClick:y},l("添加账号","Add account")),o.selected!=="default"?e("button",{className:"cm-btn small",type:"button",disabled:x,onClick:P},l("移除账号","Remove account")):null),B?e("div",{className:"cm-buttons"},e("input",{className:"cm-input",value:I,maxLength:64,"aria-label":l("账号名称","Account name"),disabled:x,onChange:i=>U(i.target.value),style:{minWidth:0,flex:1}}),e("button",{className:"cm-btn small",type:"button",disabled:x||!I.trim()||I.trim()===B.label,onClick:F},l("保存名称","Save name"))):null,f==="balance"&&u.balanceAccounts?.length?e("div",{className:"cm-scroll","data-balance-accounts":!0},...u.balanceAccounts.map(i=>e("div",{key:i.id,style:{display:"flex",gap:10,alignItems:"center",padding:"8px 10px"}},e("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"}},i.label),e("span",{className:"cm-num",title:i.message||void 0},i.status==="ok"?pe(i.totalBalance,u.config,i.currency):l("查询失败","Query failed")),e("button",{className:"cm-btn small",type:"button",disabled:x||i.id===o.selected,onClick:()=>C({...o,selected:i.id})},i.id===o.selected?l("当前","Current"):l("切换","Use"))))):null,M?e("p",{role:"alert",className:"cm-msg err"},M):null),e(le,{...k,key:n+"@"+o.selected,target:n+"@"+o.selected,disabled:k.disabled||x,configured:!x&&k.configured}))}function Pe({live:k,config:u,setPlan:w,state:a}){const n=(c,p)=>L(a.config)==="en"?p:c,h=k.workbuddy,l=h?.accounts??[],f=u.accountScope??"current",N=new Set(u.accountIds??[]),T=l.filter(c=>f==="all"||(f==="current"?c.current:N.has(c.id))),o=c=>typeof c=="number"&&Number.isFinite(c)?c.toLocaleString(void 0,{maximumFractionDigits:4}):"—",r=c=>T.length&&T.every(p=>typeof p[c]=="number")?T.reduce((p,q)=>p+q[c],0):null,A=c=>Object.entries(c?.byProviderModel??{}).reduce((p,[q,M])=>/^(workbuddy|workbuddy-ai|workbuddy-global|workbuddy-subscription|xdpool|xdpool-global):/.test(q)?p+(M.cost??0):p,0);return e("section",{className:"cm-workbuddy-accounts",style:{minWidth:0}},e("div",{className:"cm-field"},e("label",null,n("积分来源","Credit source")),e("select",{className:"cm-input","aria-label":n("积分来源","Credit source"),value:u.accountSource??"auto",onChange:c=>w("accountSource",c.target.value)},...[["auto",n("自动识别","Automatic")],["connect",n("WorkBuddy 连接插件","WorkBuddy connectors")],["xdpool","dsh-xdpool"]].map(([c,p])=>e("option",{value:c,key:c},p))),e("p",{className:"cm-note"},n("自动识别优先读取连接插件的账号列表,其次读取 XD Pool。两者同时使用时可指定来源。","Automatic uses connector accounts first, then XD Pool. Select a source when using both."))),e("div",{className:"cm-field"},e("label",null,n("统计账号","Accounts to include")),e("select",{className:"cm-input","aria-label":n("统计账号","Accounts to include"),value:f,onChange:c=>w("accountScope",c.target.value)},...[["current",n("当前账号(各区域)","Current account per region")],["all",n("全部账号","All accounts")],["selected",n("勾选账号","Select accounts")]].map(([c,p])=>e("option",{value:c,key:c},p)))),h?.incomplete?e("p",{className:"cm-note",role:"status"},n("部分区域查询失败,当前汇总不完整。","Some regions could not be queried; totals are incomplete.")):null,h?.historyUnavailable?e("p",{className:"cm-note",role:"status"},n("历史统计暂时无法读取,原记录已保留;余额仍可查看。","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((c,p)=>e("label",{key:c.id,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",minWidth:0}},e("input",{type:"checkbox",checked:f==="all"||(f==="current"?c.current:N.has(c.id)),disabled:f!=="selected","aria-label":c.name||n("账号 ","Account ")+(p+1),onChange:q=>{const M=new Set(N);q.target.checked?M.add(c.id):M.delete(c.id),w("accountIds",[...M])}}),e("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"}},c.name||n("账号 ","Account ")+(p+1),e("small",{style:{display:"block",opacity:.65}},c.region==="cn"?n("国内","CN"):n("国际","Global"))),e("span",{style:{textAlign:"right",flexShrink:0}},o(c.remaining),e("small",{style:{display:"block",opacity:.65}},n("今日减少 ","Decrease today ")+o(c.observedToday)))))):e("p",{className:"cm-note"},n("刷新后显示账号。旧连接插件未提供账号列表时,仍可查看当前账号积分。","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",n("剩余积分","Credits remaining")],["observedToday",n("今日观测减少","Observed decrease today")],["observedWeek",n("近 7 天观测减少","Observed decrease, 7 days")],["observedTotal",n("启用以来观测减少","Observed decrease since enabled")]].map(([c,p])=>e("div",{key:c,style:{padding:8,borderRadius:6,background:"var(--dsw-alias-bg-layer-1)",minWidth:0,overflowWrap:"anywhere"}},e("small",null,p),e("strong",{style:{display:"block"}},o(h?.incomplete?null:r(c)))))),e("p",{className:"cm-note"},n("从首次成功查询开始记录;充值或赠送不计为减少,积分过期可能计入减少。不是官方扣费账单,积分不折算成人民币。","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"},n("全部 WorkBuddy 调用 API 等值:今日 ","API-equivalent value of all WorkBuddy calls: today ")+oe(A(a.today),a.config)+n(";累计 ","; total ")+oe(A(a.total),a.config)+n("。调用记录没有账号标识,此项不随账号筛选。",". Call records have no account identifiers; this value is not filtered by account.")))}function Ae(k){const{state:u,api:w,t:a,draft:n,setDraft:h,planId:l,labelKey:f}=k,N=u.config,T=u.codingPlans??{},o=n?.codingPlans?.[l]??N.codingPlans?.[l]??{},r=T[l]??{status:"off",message:"",fetchedAt:0,windows:{}},A=o.enabled===!0,[c,p]=S(k.targeted===!0),q=l==="qwen"&&N.codingPlans?.qwen?.quotaSource==="bailian"&&o.quotaSource==="bailian"&&r.quotaSource==="bailian"&&r.loginRequired===!0,[M,O,B]=Q(a,()=>q?w.loginCodingPlan(l):w.refreshCodingPlan(l)),[I,U,x]=Q(a,()=>w.loginOpenDesign()),C=(s,d)=>{if(n===null)return;const t=n.codingPlans??N.codingPlans??{};h({...n,codingPlans:{...t,[l]:{...t[l]??{},[s]:d}}})},[y,F]=S(""),[P,i]=S({}),v=s=>s?.rates!==null&&typeof s?.rates=="object"&&!Array.isArray(s.rates)?s.rates:{},g=["input","cachedInput","output"],K=s=>P[s]??v(o)[s]??{},G=s=>g.every(d=>Number.isFinite(Number(s[d]))&&Number(s[d])>0),$=(s,d,t)=>{if(n===null)return;const m={...K(s),[d]:String(t)};i(W=>({...W,[s]:m}));const b=g.every(W=>String(m[W]??"").trim()==="");if(!b&&!G(m))return;const E=n.codingPlans??N.codingPlans??{},D={...(E.qwen??{}).rates??{}};b?delete D[s]:D[s]=Object.fromEntries(g.map(W=>[W,Number(m[W])])),h({...n,codingPlans:{...E,qwen:{...E.qwen??{},rates:D}}})},j=s=>{n!==null&&i(d=>({...d,[s]:d[s]??v(o)[s]??{}}))},Z=s=>{if(n===null)return;i(m=>{const b={...m};return delete b[s],b});const d=n.codingPlans??N.codingPlans??{},t={...(d.qwen??{}).rates??{}};delete t[s],h({...n,codingPlans:{...d,qwen:{...d.qwen??{},rates:t}}})},_=r.windows!==null&&typeof r.windows=="object"?r.windows:{},X=A===!1?e("p",{className:"cm-note"},L(u.config)==="en"?"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.":"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。"):r.status==="ok"?e("div",{className:"cm-go-list"},r.message?e("p",{className:"cm-note"},r.message):null,Object.keys(_).length>0?l==="minimax"&&(Y(_).five!=null||Y(_).seven!=null)?e(re,{five:Y(_).five,seven:Y(_).seven,fetchedAt:r.fetchedAt,t:a,wide:!0,direction:z(N,"plan")}):me(_,l).map(([s,d])=>ue(a,de(s,a),d,z(N,"plan"),!1,s)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:r.fetchedAt>0?new Date(r.fetchedAt).toLocaleTimeString():"—"}))):r.status==="error"?e("div",{className:"cm-bal-line err"},r.message||a("unknownError")):r.status==="off"&&r.message?e("p",{className:"cm-note"},r.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),ee=e(R,null,J[l]?e("p",{className:"cm-note","data-cm-plan-catalog":l},J[l][L(u.config)==="en"?"en":"zh"]," ",e("a",{href:J[l].sourceUrl,target:"_blank",rel:"noopener noreferrer",style:{whiteSpace:"nowrap"}},L(u.config)==="en"?"Plan details":"套餐详情")):null,l==="opendesign"?e("div",{className:"cm-field"},e("label",null,a("opendesignWorkspace")),e("input",{className:"cm-input","aria-label":a("opendesignWorkspace"),value:o.workspaceId??"",onChange:s=>C("workspaceId",s.target.value)}),e("p",{className:"cm-note"},a("opendesignNote"))):null,l==="opendesign"?e("div",{className:"cm-field"},e("button",{type:"button",className:"cm-btn small","data-cm-action":"opendesign-login",disabled:I,onClick:x},a(I?"loggingIn":"opendesignLogin")),U?e("p",{className:"cm-note"},U.text):null):null,l==="factory"?e(R,null,e("div",{className:"cm-field"},e("label",null,a("factoryPool")),e("select",{className:"cm-input","aria-label":a("factoryPool"),value:o.factoryPool??"standard",onChange:s=>C("factoryPool",s.target.value)},e("option",{value:"standard"},"Standard"),e("option",{value:"core"},"Droid Core"),e("option",{value:"both"},a("factoryPoolBoth")))),e("div",{className:"cm-field"},e("label",null,a("factoryOrg")),e("input",{className:"cm-input","aria-label":a("factoryOrg"),value:o.orgId??"",onChange:s=>C("orgId",s.target.value)}))):null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:o.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:s=>C("baseUrl",s.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:o.quotaSource??"local",onChange:s=>C("quotaSource",s.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(o.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input","aria-label":a("codingPlanDisplayLabel"),value:ge(o,(n??N).quotaStrip,"plans"),onChange:s=>{if(n===null)return;const d=n.codingPlans??N.codingPlans??{};h({...n,codingPlans:{...d,[l]:{...o,...be(s.target.value)}}})}},...he(a)),e("span",{className:"cm-hint"},L(u.config)==="en"?"Choose the sidebar, settings, the area above the input box, or a combination. Individual placement overrides strip defaults.":"可单独选择侧栏、设置页或输入框上方,也可同时显示。单家位置优先于横条默认设置。")),l!=="scnet"&&(l!=="qwen"||(o.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),te({value:typeof o.refreshMinutes=="number"&&Number.isFinite(o.refreshMinutes)&&o.refreshMinutes>0?o.refreshMinutes:15},s=>{C("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(s))))})):null,l==="scnet"||l==="qwen"&&(o.quotaSource??"local")==="local"?e(R,null,e("div",{className:"cm-field"},e("label",null,a(l==="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:l==="qwen"?5e5:24e4,onChange:s=>{const d=Number(s.target.value);Number.isFinite(d)&&d>0&&C("planCredits",Math.floor(d))}})),e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof o.planStart=="string"?o.planStart:"",onChange:s=>C("planStart",s.target.value)})),l==="qwen"?e(R,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(v(o)),...Object.keys(P)])].sort().map(s=>e("div",{key:s,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},s),g.map(d=>e("input",{key:d,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:K(s)[d]??"",placeholder:a("qwenRate_"+d),"aria-label":s+" · "+a("qwenRate_"+d),onChange:t=>{const m=t.target.value;$(s,d,m)}})),e("button",{className:"cm-btn small",onClick:()=>Z(s)},a("overrideRemove")),s in P&&!G(K(s))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:y,onChange:s=>F(s.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const s=y.trim();s.length!==0&&(j(s),F(""))},disabled:y.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(R,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(V,{state:u,draft:n,setDraft:h,target:"codingPlans.volcengine.ak",configured:r.keyConfigured===!0,source:r.keySource,t:a,api:w,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(V,{state:u,draft:n,setDraft:h,target:"codingPlans.volcengine.sk",configured:r.keyConfigured===!0,source:r.keySource,t:a,api:w,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},L(u.config)==="en"?"Volcano Ark needs AK/SK, ArkReadOnlyAccess and BillingCenterReadOnlyAccess. Enter credentials or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Only open.volcengineapi.com is contacted.":"火山方舟需 AK/SK、ArkReadOnlyAccess 和 BillingCenterReadOnlyAccess;可填凭据或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。只连接 open.volcengineapi.com。")):l==="workbuddy"?e(R,null,e("p",{className:"cm-note"},a("wbH")),e(Pe,{live:r,config:o,setPlan:C,state:u})):e(R,null,e("div",{className:"cm-field"},e("label",null,l==="baidu-coding"?"Cookie (console.bce.baidu.com)":l==="mimo"?"Cookie (platform.xiaomimimo.com)":l==="factory"?"Factory Token":l==="opendesign"?"OpenDesign Cookie / Control Key":a("codingPlanKeyLabel"))),e(V,{state:u,draft:n,setDraft:h,target:"codingPlans."+l,configured:r.keyConfigured===!0,source:r.keySource,t:a,api:w,placeholder:l==="baidu-coding"?"BAIDU_QIANFAN_COOKIE":l==="mimo"?"api-platform_serviceToken=…; userId=…":l==="factory"?"FACTORY_API_KEY":l==="opendesign"?"Cookie: name=value; … / vela_ctrl_…":"sk-…"}),l==="baidu-coding"?e("p",{className:"cm-note"},L(u.config)==="en"?"Sign in at console.bce.baidu.com, open Token Plan → browser Network → tokenPlanPersonal/resource, and copy the full Cookie request header. Supports Personal credits and Tokens; excludes add-on packs. API keys cannot query quotas.":"登录 console.bce.baidu.com,打开 Token Plan 页面,在浏览器网络面板找到 tokenPlanPersonal/resource,复制完整 Cookie 请求头。支持个人版积分制与 Token 制套餐,不含加油包;API Key 不用于额度查询。"):null));return e(se,{planId:l,targeted:k.targeted,name:a(f),enabled:A,saved:N.codingPlans?.[l],busy:M,open:c,errorMsg:O?.text===r.message?null:O,statusNode:X,configNode:ee,onToggle:s=>C("enabled",s),onRefresh:B,onLogin:B,loginRequired:q,onToggleOpen:()=>p(s=>!s),t:a})}return k=>k.mode==="credential"?e(V,k):k.mode==="custom-balance"?e(we,k):e(Ae,k)}}}});
|
|
1
|
+
;(function(e){const S=window.__ModuleLoader__,H=S[Symbol.for("@dsh-plugin/dsh-loader:load-wrap")];return(e.id==="dsh-cost-meter"&&S.load===H?.ours&&typeof H.original=="function"?H.original:S.load).call(S,e)})({id:"dsh-cost-meter",chunk:"client.plan-settings.js",factory:ne=>{const{createElement:e,useState:S,useEffect:H,useRef:te,Fragment:R}=ne("react"),J={kimi:{checkedAt:"2026-10-28",sourceUrl:"https://www.kimi.com/code/docs/kimi-code/membership.html",tiers:["Go","Plus","Pro","Max","Ultra"],legacyTiers:["Andante","Moderato","Allegretto","Vivace"],models:["k3.1-pro","k3.1-pro-highspeed","k3","k3-256k","kimi-for-coding","kimi-for-coding-highspeed"],zh:"新套餐:Go、Plus、Pro、Max、Ultra。Plus 起提供 Kimi Code,Pro 起提供高速版和 1M 上下文。新套餐使用 5 小时窗口及月总额度;老套餐保留周窗口。",en:"Current tiers: Go, Plus, Pro, Max and Ultra. Kimi Code starts at Plus; Pro adds Highspeed and 1M context. New plans use a 5-hour window and monthly total; legacy plans retain weekly limits."},minimax:{checkedAt:"2026-10-28",sourceUrl:"https://platform.minimax.io/docs/m-plan/intro",tiers:["Go","Explore","Build"],legacyTiers:["Plus","Max","Ultra"],models:["MiniMax-M3.1-Flash"],zh:"M Plan:Go、Explore、Build,均包含 M3.1 Flash;Explore、Build 另含 H3 视频。原 Token Plan 的 Plus、Max、Ultra 保留。使用现有 MiniMax 查询凭据。",en:"M Plan: Go, Explore and Build, all including M3.1 Flash. Explore and Build also include H3 video. Legacy Token Plan Plus, Max and Ultra remain. Uses the existing MiniMax quota credential."},go:{checkedAt:"2026-10-28",sourceUrl:"https://opencode.ai/v2/docs/console/go/",tiers:["Go","Go Plus"],models:["kimi-k3.1-pro","minimax-m3.1-flash","step-5-preview","gemini-4-argon","beam-free","iceman-contributor-free"],zh:"Go 为 $10/月,Go Plus 为 $40/月。新增 Kimi K3.1 Pro、MiniMax M3.1 Flash 等模型,各模型使用独立的月度额度标准。",en:"Go costs $10/month; Go Plus costs $40/month. Includes Kimi K3.1 Pro, MiniMax M3.1 Flash and other additions, with model-specific monthly allowances."},"tencent-token":{checkedAt:"2026-10-28",sourceUrl:"https://cloud.tencent.com/document/product/1823/130060",tiers:["Lite","Standard","Pro","Max"],products:["Token Plan","Hy Token Plan"],zh:"腾讯通用 Token Plan 与 Hy Token Plan 共用 API Key 和请求地址,按模型从对应套餐扣减积分。当前支持套餐归属统计。",en:"Tencent Token Plan and Hy Token Plan share an API key and endpoints; credits are deducted from the applicable plan for each model. Plan classification is supported."}};return{mount(ie){const{useQuotaRefresh:Q,miniMaxWindowsOf:Y,MiniMaxPlanCard:re,barDirectionOf:z,quotaWindowRow:ue,codingPlanWindowLabel:de,codingPlanWindowEntries:me,numInput:le,CredentialField:se,QuotaCard:oe,resolveLocale:L,formatMoneyUsd:ce,formatBalanceMoney:pe,quotaPlacementValue:ge,quotaPlacementPatch:be,quotaPlacementOptions:he,displayOptions:fe,BalanceBar:ye,segmentsForCustomBalance:ve,customBalanceUnitOf:Ne,customBalanceDetailText:$,formatCustomBalanceMoney:Ce,resolveCustomBalanceLabel:ke}=ie;function we(w){const{state:u,api:P,t:a,entry:n,index:h,canRemove:l,onPatch:f,onRemove:N}=w,T=n.adapter==="aliyun",o=n.adapter==="tokenrhythm",r=n.adapter==="openai-credits",A=T||o||r,[c,p]=S(!1),q=()=>({headers:JSON.stringify(n.request?.headers??{},null,2),extract:JSON.stringify(n.extract??{},null,2),body:typeof n.request?.body=="string"?n.request.body:JSON.stringify(n.request?.body,null,2)??""}),[M,O]=S(q),[B,I]=S(()=>(n.allowedHosts??[]).join(", ")),[U,x]=S({}),C=te(!1),y=u.config,k=(Array.isArray(u.customBalances)?u.customBalances:[]).find(t=>t.index===h)??null,i=n.enabled===!0,v=()=>{p(t=>!t)};H(()=>{c&&!C.current&&(O(q()),I((n.allowedHosts??[]).join(", ")),x({})),C.current=c},[c]);const g=(t,m)=>f({[t]:m}),K=(t,m)=>f({request:{...n.request??{},[t]:m}}),G=T?["ALIBABA_CLOUD_ACCESS_KEY_ID","ALIBABA_CLOUD_ACCESS_KEY_SECRET","ALIBABA_CLOUD_SECURITY_TOKEN"]:o?["TOKENRHYTHM_COOKIE"]:r?["DSH_OPENAI_COST_ADMIN_KEY"]:[...new Set(Object.values(n.request?.headers??{}).flatMap(t=>typeof t=="string"?[...t.matchAll(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g)].map(m=>m[1]):[]))],Z=(t,m)=>{O(b=>({...b,[t]:m}));try{const b=t==="body",E=b&&!m.trim()?void 0:JSON.parse(m);if(!b&&(E===null||typeof E!="object"||Array.isArray(E)))throw new Error("invalid");if(t==="headers"&&Object.values(E).some(D=>typeof D!="string"))throw new Error("invalid");x(D=>({...D,[t]:""})),t==="extract"?g(t,E):K(t,b?E===void 0?void 0:m:E)}catch{x(b=>({...b,[t]:a("customBalanceInvalidJson")}))}},j=(t,m,b,E)=>!A&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a(m)),E&&e("span",{className:"cm-hint"},a(E)),e("textarea",{className:"cm-input",rows:b,value:M[t],onChange:D=>Z(t,D.target.value)}),U[t]?e("span",{className:"cm-hint err"},U[t]):null),X=t=>{I(t);const m=t.split(/[\s,;]+/).map(b=>b.trim()).filter(b=>b.length>0);g("allowedHosts",m)},[_,ee,ae]=Q(a,()=>(y.customBalances??[])[h]?.enabled!==!0?Promise.resolve({ok:!1,message:a("quotaEnableFirst")}):P.refreshCustomBalance(h)),s=k!==null&&k.status==="ok"?r?e("div",{className:"cm-bal-line"},$(k,y,a,u,y.customBalances?.[h]??n)):e(R,null,y.balance?.showProgressBar===!0&&!o?e("div",{className:"cm-budget",style:{marginTop:"8px"}},e(ye,{segments:ve(u,y,k,n),direction:z(y,"balance")}),e("div",{className:"cm-bal-line"},$(k,y,a,u,n))):e("div",{className:"cm-bal-line"},T?$(k,y,a,u,n):a("customBalanceRemaining",{amount:Ce(k.remaining,y,k,n)}))):k!==null&&k.status==="error"?e("div",{className:"cm-bal-line err"},k.message||a("unknownError")):e("div",{className:"cm-bal-line"},k?.message||a("balanceNotQueried")),d=e(R,null,e("p",{className:"cm-note"},a(r?"openAiCreditNote":o?"tokenRhythmBalanceNote":T?"aliyunBalanceNote":"customBalanceConfigNote")),!o&&!r&&e("label",{className:"cm-check"},e("input",{type:"checkbox",checked:n.convertToDisplayCurrency===!0,disabled:Ne(y,k,n)!=="USD",onChange:t=>g("convertToDisplayCurrency",t.target.checked)}),a("customBalanceConvert")),!o&&!r&&e("p",{className:"cm-note"},a("customBalanceConvertNote")),e("div",{className:"cm-grid"},r?e(R,null,e("label",{className:"cm-field"},a("openAiCreditAmount"),e("input",{className:"cm-input",type:"number",min:0,step:"0.01",value:n.grantAmount||"",onChange:t=>g("grantAmount",t.target.valueAsNumber||0)})),...[["grantStart","openAiCreditStart"],["grantExpiry","openAiCreditExpiry"]].map(([t,m])=>e("label",{className:"cm-field",key:t},a(m),e("input",{className:"cm-input",type:"date",value:n[t]??"",onChange:b=>g(t,b.target.value)}))),e("a",{href:n.dashboardUrl,target:"_blank",rel:"noopener noreferrer"},a("openAiCreditBilling"))):[["label","customBalanceLabelZh"],["labelEn","customBalanceLabelEn"]].map(([t,m])=>e("div",{key:t,className:"cm-field"},e("label",null,a(m)),e("input",{className:"cm-input",value:n[t]??"",onChange:b=>g(t,b.target.value)}))),!r&&e("label",{className:"cm-field"},e("span",null,L(y)==="en"?"Dashboard link (optional)":"跳转链接(可选)"),e("input",{className:"cm-input",type:"url","aria-label":L(y)==="en"?"Dashboard link":"跳转链接",value:n.dashboardUrl??"",placeholder:"https://example.com/account",onChange:t=>g("dashboardUrl",t.target.value)})),!A&&e("div",{className:"cm-field"},e("label",null,a("customBalanceUnitLabel")),e("select",{className:"cm-input",value:["CNY","EUR","CREDITS"].includes(n.unit)?n.unit:"USD",onChange:t=>g("unit",t.target.value)},e("option",{value:"USD"},"USD ($)"),e("option",{value:"CNY"},"CNY (¥)"),e("option",{value:"EUR"},"EUR (€)"),e("option",{value:"CREDITS"},"CREDITS"))),e("div",{className:"cm-field"},e("label",null,a("customBalanceDisplayLabel")),e("select",{className:"cm-input",value:n.display??"both",onChange:t=>g("display",t.target.value)},...fe(a))),e("div",{className:"cm-field"},e("label",null,a("customBalanceRefreshInterval")),le({value:n.refreshMinutes??15},t=>g("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(t)))))),!A&&e("div",{className:"cm-field"},e("label",null,a("customBalanceMethod")),e("select",{className:"cm-input",value:n.request?.method??"GET",onChange:t=>K("method",t.target.value)},e("option",{value:"GET"},"GET"),e("option",{value:"POST"},"POST"))),!A&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceUrl")),e("input",{className:"cm-input",value:n.request?.url??"",placeholder:"/plugins/dsh-workbuddy-connect/status",onChange:t=>K("url",t.target.value)}),e("span",{className:"cm-hint"},a("customBalanceUrlHint"))),j("headers","customBalanceHeaders",5,"customBalanceHeadersVarNote"),!["GET","HEAD"].includes((n.request?.method??"GET").toUpperCase())&&j("body","customBalanceBody",5,"customBalanceBodyNote"),e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,r?"OpenAI Admin API Key":o?"Token Rhythm Cookie":a("customBalanceCredentialsTitle")),G.length>0?e(R,null,!A&&e("span",{className:"cm-hint"},a("customBalanceCredentialsHint")),G.map(t=>e(se,{key:"cb-var-"+t,target:"customVar:"+t,configured:(u.customVarStatus?.[t]?.configured??!1)===!0,source:u.customVarStatus?.[t]?.source??"",t:a,api:P,placeholder:r?"sk-admin-…":o?"tr_session=…":"{{"+t+"}}"}))):e("span",{className:"cm-hint"},a("customBalanceNoPlaceholders"))),!A&&e("div",{className:"cm-field",style:{gridColumn:"1 / -1"}},e("label",null,a("customBalanceAllowedHosts")),e("input",{className:"cm-input",value:B,placeholder:"api.example.com, relay.example.org",onChange:t=>X(t.target.value)}),e("span",{className:"cm-hint"},a("customBalanceAllowedHostsHint"))),!A&&e("label",{className:"cm-check",style:{gridColumn:"1 / -1"}},e("input",{type:"checkbox",checked:n.allowInsecureHttp===!0,onChange:t=>g("allowInsecureHttp",t.target.checked)}),a("customBalanceHttp")),j("extract","customBalanceExtract",8)));return e(oe,{name:`#${h+1} · `+(ke(n,L(y))||a("customBalanceTitle")),enabled:i,saved:JSON.stringify(n)===JSON.stringify(y.customBalances?.[h])?y.customBalances[h]:null,busy:_,open:c,statusNode:s,configNode:d,errorMsg:ee,onToggle:t=>g("enabled",t),onRefresh:ae,onRemove:l?N:null,onToggleOpen:v,t:a})}function V(w){const{state:u,draft:P,setDraft:a,target:n,api:h}=w,l=(i,v)=>L(u.config)==="en"?v:i,f=n.replace(/\.(ak|sk)$/,""),N=f==="balance"?l("当前账号","Current account"):l("查询并显示的账号","Account to query and display"),T=(P??u.config).queryAccounts??{},o=T[f]??{selected:"default",accounts:[]},r=u.config.queryAccounts?.[f]?.selected??"default",[A,c]=S(""),[p,q]=S(!1),[M,O]=S(""),B=o.accounts.find(i=>i.id===o.selected),[I,U]=S(B?.label??"");H(()=>U(B?.label??""),[B?.id,B?.label]);const x=r!==o.selected||P===null||p,C=i=>a({...P,queryAccounts:{...T,[f]:i}}),y=()=>{const i=A.trim();if(!i||o.accounts.length>=10||x)return;if(o.accounts.some(g=>g.label.toLowerCase()===i.toLowerCase())){O(l("账号名称已存在","Account name already exists"));return}const v=crypto.randomUUID();C({selected:v,accounts:[...o.accounts,{id:v,label:i}]}),c(""),O("")},F=()=>{const i=I.trim();if(!(!i||x||!B)){if(o.accounts.some(v=>v.id!==B.id&&v.label.toLowerCase()===i.toLowerCase())){O(l("账号名称已存在","Account name already exists"));return}C({...o,accounts:o.accounts.map(v=>v.id===B.id?{...v,label:i}:v)}),O("")}},k=async()=>{if(!(x||o.selected==="default")){q(!0),O("");try{const i=f==="codingPlans.volcengine"?[f+".ak",f+".sk"]:[f];for(const g of i)await h.clearCredential(g+"@"+o.selected);const v=o.accounts.filter(g=>g.id!==o.selected);C({selected:f==="balance"?v[0]?.id??"default":"default",accounts:v})}catch(i){O(String(i?.message??i))}finally{q(!1)}}};return e("div",{"data-query-account":n},n.endsWith(".sk")?null:e("div",{className:"cm-field"},e("label",null,N,e("select",{className:"cm-input","aria-label":N,value:o.selected,disabled:p||P===null,onChange:i=>C({...o,selected:i.target.value})},e("option",{value:"default"},l("默认账号(现有配置)","Default account (existing configuration)")),...o.accounts.map(i=>e("option",{key:i.id,value:i.id},i.label)))),e("div",{className:"cm-buttons"},e("input",{className:"cm-input",type:"text",value:A,maxLength:64,autoComplete:"off","aria-label":l("新账号名称","New account name"),placeholder:l("如:工作账号","e.g. Work account"),disabled:x,onChange:i=>c(i.target.value),style:{minWidth:0,flex:1}}),e("button",{className:"cm-btn small",type:"button",disabled:x||!A.trim()||o.accounts.length>=10,onClick:y},l("添加账号","Add account")),o.selected!=="default"?e("button",{className:"cm-btn small",type:"button",disabled:x,onClick:k},l("移除账号","Remove account")):null),B?e("div",{className:"cm-buttons"},e("input",{className:"cm-input",value:I,maxLength:64,"aria-label":l("账号名称","Account name"),disabled:x,onChange:i=>U(i.target.value),style:{minWidth:0,flex:1}}),e("button",{className:"cm-btn small",type:"button",disabled:x||!I.trim()||I.trim()===B.label,onClick:F},l("保存名称","Save name"))):null,f==="balance"&&u.balanceAccounts?.length?e("div",{className:"cm-scroll","data-balance-accounts":!0},...u.balanceAccounts.map(i=>e("div",{key:i.id,style:{display:"flex",gap:10,alignItems:"center",padding:"8px 10px"}},e("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"}},i.label),e("span",{className:"cm-num",title:i.message||void 0},i.status==="ok"?pe(i.totalBalance,u.config,i.currency):l("查询失败","Query failed")),e("button",{className:"cm-btn small",type:"button",disabled:x||i.id===o.selected,onClick:()=>C({...o,selected:i.id})},i.id===o.selected?l("当前","Current"):l("切换","Use"))))):null,M?e("p",{role:"alert",className:"cm-msg err"},M):null),e(se,{...w,key:n+"@"+o.selected,target:n+"@"+o.selected,disabled:w.disabled||x,configured:!x&&w.configured}))}function Pe({live:w,config:u,setPlan:P,state:a}){const n=(c,p)=>L(a.config)==="en"?p:c,h=w.workbuddy,l=h?.accounts??[],f=u.accountScope??"current",N=new Set(u.accountIds??[]),T=l.filter(c=>f==="all"||(f==="current"?c.current:N.has(c.id))),o=c=>typeof c=="number"&&Number.isFinite(c)?c.toLocaleString(void 0,{maximumFractionDigits:4}):"—",r=c=>T.length&&T.every(p=>typeof p[c]=="number")?T.reduce((p,q)=>p+q[c],0):null,A=c=>Object.entries(c?.byProviderModel??{}).reduce((p,[q,M])=>/^(workbuddy|workbuddy-ai|workbuddy-global|workbuddy-subscription|xdpool|xdpool-global):/.test(q)?p+(M.cost??0):p,0);return e("section",{className:"cm-workbuddy-accounts",style:{minWidth:0}},e("div",{className:"cm-field"},e("label",null,n("积分来源","Credit source")),e("select",{className:"cm-input","aria-label":n("积分来源","Credit source"),value:u.accountSource??"auto",onChange:c=>P("accountSource",c.target.value)},...[["auto",n("自动识别","Automatic")],["connect",n("WorkBuddy 连接插件","WorkBuddy connectors")],["xdpool","dsh-xdpool"]].map(([c,p])=>e("option",{value:c,key:c},p))),e("p",{className:"cm-note"},n("自动识别优先读取连接插件的账号列表,其次读取 XD Pool。两者同时使用时可指定来源。","Automatic uses connector accounts first, then XD Pool. Select a source when using both."))),e("div",{className:"cm-field"},e("label",null,n("统计账号","Accounts to include")),e("select",{className:"cm-input","aria-label":n("统计账号","Accounts to include"),value:f,onChange:c=>P("accountScope",c.target.value)},...[["current",n("当前账号(各区域)","Current account per region")],["all",n("全部账号","All accounts")],["selected",n("勾选账号","Select accounts")]].map(([c,p])=>e("option",{value:c,key:c},p)))),h?.incomplete?e("p",{className:"cm-note",role:"status"},n("部分区域查询失败,当前汇总不完整。","Some regions could not be queried; totals are incomplete.")):null,h?.historyUnavailable?e("p",{className:"cm-note",role:"status"},n("历史统计暂时无法读取,原记录已保留;余额仍可查看。","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((c,p)=>e("label",{key:c.id,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",minWidth:0}},e("input",{type:"checkbox",checked:f==="all"||(f==="current"?c.current:N.has(c.id)),disabled:f!=="selected","aria-label":c.name||n("账号 ","Account ")+(p+1),onChange:q=>{const M=new Set(N);q.target.checked?M.add(c.id):M.delete(c.id),P("accountIds",[...M])}}),e("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"}},c.name||n("账号 ","Account ")+(p+1),e("small",{style:{display:"block",opacity:.65}},c.region==="cn"?n("国内","CN"):n("国际","Global"))),e("span",{style:{textAlign:"right",flexShrink:0}},o(c.remaining),e("small",{style:{display:"block",opacity:.65}},n("今日减少 ","Decrease today ")+o(c.observedToday)))))):e("p",{className:"cm-note"},n("刷新后显示账号。旧连接插件未提供账号列表时,仍可查看当前账号积分。","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",n("剩余积分","Credits remaining")],["observedToday",n("今日观测减少","Observed decrease today")],["observedWeek",n("近 7 天观测减少","Observed decrease, 7 days")],["observedTotal",n("启用以来观测减少","Observed decrease since enabled")]].map(([c,p])=>e("div",{key:c,style:{padding:8,borderRadius:6,background:"var(--dsw-alias-bg-layer-1)",minWidth:0,overflowWrap:"anywhere"}},e("small",null,p),e("strong",{style:{display:"block"}},o(h?.incomplete?null:r(c)))))),e("p",{className:"cm-note"},n("从首次成功查询开始记录;充值或赠送不计为减少,积分过期可能计入减少。不是官方扣费账单,积分不折算成人民币。","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"},n("全部 WorkBuddy 调用 API 等值:今日 ","API-equivalent value of all WorkBuddy calls: today ")+ce(A(a.today),a.config)+n(";累计 ","; total ")+ce(A(a.total),a.config)+n("。调用记录没有账号标识,此项不随账号筛选。",". Call records have no account identifiers; this value is not filtered by account.")))}function Ae(w){const{state:u,api:P,t:a,draft:n,setDraft:h,planId:l,labelKey:f}=w,N=u.config,T=u.codingPlans??{},o=n?.codingPlans?.[l]??N.codingPlans?.[l]??{},r=T[l]??{status:"off",message:"",fetchedAt:0,windows:{}},A=o.enabled===!0,[c,p]=S(w.targeted===!0),q=l==="qwen"&&N.codingPlans?.qwen?.quotaSource==="bailian"&&o.quotaSource==="bailian"&&r.quotaSource==="bailian"&&r.loginRequired===!0,[M,O,B]=Q(a,()=>q?P.loginCodingPlan(l):P.refreshCodingPlan(l)),[I,U,x]=Q(a,()=>P.loginOpenDesign()),C=(s,d)=>{if(n===null)return;const t=n.codingPlans??N.codingPlans??{};h({...n,codingPlans:{...t,[l]:{...t[l]??{},[s]:d}}})},[y,F]=S(""),[k,i]=S({}),v=s=>s?.rates!==null&&typeof s?.rates=="object"&&!Array.isArray(s.rates)?s.rates:{},g=["input","cachedInput","output"],K=s=>k[s]??v(o)[s]??{},G=s=>g.every(d=>Number.isFinite(Number(s[d]))&&Number(s[d])>0),Z=(s,d,t)=>{if(n===null)return;const m={...K(s),[d]:String(t)};i(W=>({...W,[s]:m}));const b=g.every(W=>String(m[W]??"").trim()==="");if(!b&&!G(m))return;const E=n.codingPlans??N.codingPlans??{},D={...(E.qwen??{}).rates??{}};b?delete D[s]:D[s]=Object.fromEntries(g.map(W=>[W,Number(m[W])])),h({...n,codingPlans:{...E,qwen:{...E.qwen??{},rates:D}}})},j=s=>{n!==null&&i(d=>({...d,[s]:d[s]??v(o)[s]??{}}))},X=s=>{if(n===null)return;i(m=>{const b={...m};return delete b[s],b});const d=n.codingPlans??N.codingPlans??{},t={...(d.qwen??{}).rates??{}};delete t[s],h({...n,codingPlans:{...d,qwen:{...d.qwen??{},rates:t}}})},_=r.windows!==null&&typeof r.windows=="object"?r.windows:{},ee=A===!1?e("p",{className:"cm-note"},L(u.config)==="en"?"Disabled. Enable it to query this vendor's coding plan quota on the refresh interval and show it here.":"未启用。开启后将按刷新间隔查询该厂商的 coding plan 额度并显示在这里。"):r.status==="ok"?e("div",{className:"cm-go-list"},r.message?e("p",{className:"cm-note"},r.message):null,Object.keys(_).length>0?l==="minimax"&&(Y(_).five!=null||Y(_).seven!=null)?e(re,{five:Y(_).five,seven:Y(_).seven,fetchedAt:r.fetchedAt,t:a,wide:!0,direction:z(N,"plan")}):me(_,l).map(([s,d])=>ue(a,de(s,a),d,z(N,"plan"),!1,s)):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),e("div",{className:"cm-go-time"},a("goQuotaFetchedAt",{time:r.fetchedAt>0?new Date(r.fetchedAt).toLocaleTimeString():"—"}))):r.status==="error"?e("div",{className:"cm-bal-line err"},r.message||a("unknownError")):r.status==="loading"?e("div",{className:"cm-bal-line"},a("refreshing")):r.status==="off"&&r.message?e("p",{className:"cm-note"},r.message):e("div",{className:"cm-bal-line"},a("codingPlanNotQueried")),ae=e(R,null,J[l]?e("p",{className:"cm-note","data-cm-plan-catalog":l},J[l][L(u.config)==="en"?"en":"zh"]," ",e("a",{href:J[l].sourceUrl,target:"_blank",rel:"noopener noreferrer",style:{whiteSpace:"nowrap"}},L(u.config)==="en"?"Plan details":"套餐详情")):null,l==="opendesign"?e("div",{className:"cm-field"},e("label",null,a("opendesignWorkspace")),e("input",{className:"cm-input","aria-label":a("opendesignWorkspace"),value:o.workspaceId??"",onChange:s=>C("workspaceId",s.target.value)}),e("p",{className:"cm-note"},a("opendesignNote"))):null,l==="opendesign"?e("div",{className:"cm-field"},e("button",{type:"button",className:"cm-btn small","data-cm-action":"opendesign-login",disabled:I,onClick:x},a(I?"loggingIn":"opendesignLogin")),U?e("p",{className:"cm-note"},U.text):null):null,l==="factory"?e(R,null,e("div",{className:"cm-field"},e("label",null,a("factoryPool")),e("select",{className:"cm-input","aria-label":a("factoryPool"),value:o.factoryPool??"standard",onChange:s=>C("factoryPool",s.target.value)},e("option",{value:"standard"},"Standard"),e("option",{value:"core"},"Droid Core"),e("option",{value:"both"},a("factoryPoolBoth")))),e("div",{className:"cm-field"},e("label",null,a("factoryOrg")),e("input",{className:"cm-input","aria-label":a("factoryOrg"),value:o.orgId??"",onChange:s=>C("orgId",s.target.value)}))):null,l==="minimax"?e("div",{className:"cm-field"},e("label",null,a("minimaxOrigin")),e("input",{className:"cm-input",type:"url",value:o.baseUrl??"",placeholder:"https://www.minimax.cn","aria-label":a("minimaxOrigin"),onChange:s=>C("baseUrl",s.target.value)}),e("p",{className:"cm-note"},a("minimaxOriginNote"))):null,l==="qwen"?e("div",{className:"cm-field"},e("label",null,a("qwenSource")),e("select",{className:"cm-input",value:o.quotaSource??"local",onChange:s=>C("quotaSource",s.target.value)},e("option",{value:"local"},a("qwenSourceLocal")),e("option",{value:"cli"},a("qwenSourceCli")),e("option",{value:"bailian"},a("qwenSourceBailian"))),e("p",{className:"cm-note"},a(o.quotaSource==="bailian"?"qwenBailianNote":"qwenCliNote"))):null,e("div",{className:"cm-field"},e("label",null,a("codingPlanDisplayLabel")),e("select",{className:"cm-input","aria-label":a("codingPlanDisplayLabel"),value:ge(o,(n??N).quotaStrip,"plans"),onChange:s=>{if(n===null)return;const d=n.codingPlans??N.codingPlans??{};h({...n,codingPlans:{...d,[l]:{...o,...be(s.target.value)}}})}},...he(a)),e("span",{className:"cm-hint"},L(u.config)==="en"?"Choose the sidebar, settings, the area above the input box, or a combination. Individual placement overrides strip defaults.":"可单独选择侧栏、设置页或输入框上方,也可同时显示。单家位置优先于横条默认设置。")),l!=="scnet"&&(l!=="qwen"||(o.quotaSource??"local")!=="local")?e("div",{className:"cm-field"},e("label",null,a("codingPlanRefreshIntervalLabel")),le({value:typeof o.refreshMinutes=="number"&&Number.isFinite(o.refreshMinutes)&&o.refreshMinutes>0?o.refreshMinutes:15},s=>{C("refreshMinutes",Math.min(1440,Math.max(1,Math.floor(s))))})):null,l==="scnet"||l==="qwen"&&(o.quotaSource??"local")==="local"?e(R,null,e("div",{className:"cm-field"},e("label",null,a(l==="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:l==="qwen"?5e5:24e4,onChange:s=>{const d=Number(s.target.value);Number.isFinite(d)&&d>0&&C("planCredits",Math.floor(d))}})),e("div",{className:"cm-field"},e("label",null,a(l==="qwen"?"qwenPlanStartLabel":"scnetPlanStartLabel")),e("input",{className:"cm-input",type:"date",value:typeof o.planStart=="string"?o.planStart:"",onChange:s=>C("planStart",s.target.value)})),l==="qwen"?e(R,null,e("div",{className:"cm-field"},e("label",null,a("qwenRatesLabel"))),[...new Set([...Object.keys(v(o)),...Object.keys(k)])].sort().map(s=>e("div",{key:s,className:"cm-match-row"},e("span",{style:{minWidth:"120px"}},s),g.map(d=>e("input",{key:d,className:"cm-input narrow",type:"number",min:"0",step:"0.1",value:K(s)[d]??"",placeholder:a("qwenRate_"+d),"aria-label":s+" · "+a("qwenRate_"+d),onChange:t=>{const m=t.target.value;Z(s,d,m)}})),e("button",{className:"cm-btn small",onClick:()=>X(s)},a("overrideRemove")),s in k&&!G(K(s))?e("span",{className:"cm-note"},a("qwenRateDraftNote")):null)),e("div",{className:"cm-buttons"},e("input",{className:"cm-input narrow",type:"text",placeholder:a("qwenRatesModelPlaceholder"),value:y,onChange:s=>F(s.target.value)}),e("button",{className:"cm-btn small",onClick:()=>{const s=y.trim();s.length!==0&&(j(s),F(""))},disabled:y.trim().length===0},a("qwenRatesAdd")))):null,e("p",{className:"cm-note"},a(l==="qwen"?"qwenLocalNote":"scnetLocalNote"))):l==="qwen"?null:l==="volcengine"?e(R,null,e("div",{className:"cm-field"},e("label",null,a("volcengineAccessKeyIdLabel"))),e(V,{state:u,draft:n,setDraft:h,target:"codingPlans.volcengine.ak",configured:r.keyConfigured===!0,source:r.keySource,t:a,api:P,placeholder:a("volcengineAccessKeyPlaceholder")}),e("div",{className:"cm-field"},e("label",null,a("volcengineSecretAccessKeyLabel"))),e(V,{state:u,draft:n,setDraft:h,target:"codingPlans.volcengine.sk",configured:r.keyConfigured===!0,source:r.keySource,t:a,api:P,placeholder:a("volcengineSecretPlaceholder")}),e("p",{className:"cm-note"},L(u.config)==="en"?"Volcano Ark needs AK/SK, ArkReadOnlyAccess and BillingCenterReadOnlyAccess. Enter credentials or export VOLC_ACCESSKEY/VOLC_SECRETKEY. Only open.volcengineapi.com is contacted.":"火山方舟需 AK/SK、ArkReadOnlyAccess 和 BillingCenterReadOnlyAccess;可填凭据或导出 VOLC_ACCESSKEY/VOLC_SECRETKEY。只连接 open.volcengineapi.com。")):l==="workbuddy"?e(R,null,e("p",{className:"cm-note"},a("wbH")),e(Pe,{live:r,config:o,setPlan:C,state:u})):e(R,null,e("div",{className:"cm-field"},e("label",null,l==="baidu-coding"?"Cookie (console.bce.baidu.com)":l==="mimo"?"Cookie (platform.xiaomimimo.com)":l==="factory"?"Factory Token":l==="opendesign"?"OpenDesign Cookie / Control Key":a(l==="zai"?"zaiPlanKeyLabel":"codingPlanKeyLabel"))),e(V,{state:u,draft:n,setDraft:h,target:"codingPlans."+l,configured:r.keyConfigured===!0,source:r.keySource,t:a,api:P,placeholder:l==="baidu-coding"?"BAIDU_QIANFAN_COOKIE":l==="mimo"?"api-platform_serviceToken=…; userId=…":l==="factory"?"FACTORY_API_KEY":l==="opendesign"?"Cookie: name=value; … / vela_ctrl_…":"sk-…"}),l==="baidu-coding"?e("p",{className:"cm-note"},L(u.config)==="en"?"Sign in at console.bce.baidu.com, open Token Plan → browser Network → tokenPlanPersonal/resource, and copy the full Cookie request header. Supports Personal credits and Tokens; excludes add-on packs. API keys cannot query quotas.":"登录 console.bce.baidu.com,打开 Token Plan 页面,在浏览器网络面板找到 tokenPlanPersonal/resource,复制完整 Cookie 请求头。支持个人版积分制与 Token 制套餐,不含加油包;API Key 不用于额度查询。"):null));return e(oe,{planId:l,targeted:w.targeted,name:a(f),enabled:A,saved:N.codingPlans?.[l],busy:M,open:c,errorMsg:O?.text===r.message?null:O,statusNode:ee,configNode:ae,onToggle:s=>C("enabled",s),onRefresh:B,onLogin:B,loginRequired:q,onToggleOpen:()=>p(s=>!s),t:a})}return w=>w.mode==="credential"?e(V,w):w.mode==="custom-balance"?e(we,w):e(Ae,w)}}}});
|
package/lib/coding-plans.js
CHANGED
|
@@ -62,7 +62,7 @@ export const CODING_PLAN_PROVIDERS = {
|
|
|
62
62
|
},
|
|
63
63
|
zai: {
|
|
64
64
|
label: 'Z.ai / 智谱 GLM Coding Plan',
|
|
65
|
-
credentialEnvs: ['ZAI_API_KEY', 'BIGMODEL_API_KEY'],
|
|
65
|
+
credentialEnvs: ['ZAI_API_KEY', 'BIGMODEL_API_KEY', 'ZHIPU_API_KEY'],
|
|
66
66
|
keyHint: 'Coding Plan 专属 API Key(z.ai / bigmodel.cn 控制台)',
|
|
67
67
|
},
|
|
68
68
|
minimax: {
|
|
@@ -263,13 +263,17 @@ export function parseZaiUsage(data) {
|
|
|
263
263
|
// 的 percentage/currentValue/usage 与 unit 语义完全一致,一并接受。
|
|
264
264
|
if (limit === null || typeof limit !== 'object' || (limit.type !== 'TOKENS_LIMIT' && limit.type !== 'CREDIT_LIMIT')) continue
|
|
265
265
|
// percentage 已是 0-100 百分数;缺失时用 currentValue/usage 反推。
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
266
|
+
const numeric = value => typeof value === 'number' || typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
|
|
267
|
+
const explicitPct = numeric(limit.percentage)
|
|
268
|
+
const total = numeric(limit.usage)
|
|
269
|
+
const used = numeric(limit.currentValue)
|
|
270
|
+
const remaining = numeric(limit.remaining)
|
|
271
|
+
const derivedPct = total > 0 ? (Number.isFinite(used) ? used : total - remaining) / total * 100 : NaN
|
|
272
|
+
const percent = Number.isFinite(explicitPct) ? explicitPct : derivedPct
|
|
273
|
+
if (!Number.isFinite(percent)) continue
|
|
274
|
+
const pct = clampPct(percent)
|
|
271
275
|
const resetsAt = normalizeResetAt(limit.nextResetTime)
|
|
272
|
-
const unit =
|
|
276
|
+
const unit = numeric(limit.unit)
|
|
273
277
|
if (unit === 3 && monWindows.fiveHour === undefined) monWindows.fiveHour = { percent: pct, resetsAt }
|
|
274
278
|
else if (unit === 6 && monWindows.weekly === undefined) monWindows.weekly = { percent: pct, resetsAt }
|
|
275
279
|
else if (!Number.isFinite(unit)) rest.push({ pct, resetsAt, resetMs: Number(limit.nextResetTime) })
|
|
@@ -1354,6 +1358,8 @@ export function normalizeVolcengineKey(key) {
|
|
|
1354
1358
|
export async function queryCodingPlan(provider, key, locale, t, { baseUrl, orgId, workspaceId, factoryPool, workbuddyConfig, signal, onAttempt } = {}) {
|
|
1355
1359
|
const meta = CODING_PLAN_PROVIDERS[provider]
|
|
1356
1360
|
if (meta === undefined) throw new Error(t(locale, 'codingPlanUnknown', { provider: String(provider) }))
|
|
1361
|
+
const zaiOrigin = provider === 'zai' && typeof key === 'object' ? key?.origin : undefined
|
|
1362
|
+
if (zaiOrigin === 'https://open.bigmodel.cn' || zaiOrigin === 'https://api.z.ai') key = key.apiKey
|
|
1357
1363
|
if (provider === 'opendesign') {
|
|
1358
1364
|
// Issue #274: usage and wallet are read independently in lib/opendesign.js. A partial answer
|
|
1359
1365
|
// (wallet-only after a usage 401, or usage-only after a wallet failure) is still a successful
|
|
@@ -1552,11 +1558,12 @@ export async function queryCodingPlan(provider, key, locale, t, { baseUrl, orgId
|
|
|
1552
1558
|
return { windows, ...(credits.workbuddy ? { workbuddy: credits.workbuddy } : {}), endpoint: credits.endpoint ?? workbuddyBillingBase(credential) }
|
|
1553
1559
|
}
|
|
1554
1560
|
if (key === null || typeof key !== 'string' || key.trim().length === 0) {
|
|
1555
|
-
const error = new Error(t(locale, 'codingPlanKeyMissing', { provider: meta.label }))
|
|
1561
|
+
const error = new Error(t(locale, provider === 'zai' ? 'zaiPlanKeyMissing' : 'codingPlanKeyMissing', { provider: meta.label }))
|
|
1556
1562
|
error.soft = true
|
|
1557
1563
|
throw error
|
|
1558
1564
|
}
|
|
1559
|
-
const
|
|
1565
|
+
const candidates = provider === 'minimax' ? miniMaxEndpoints(baseUrl) : CODING_PLAN_ENDPOINTS[provider]
|
|
1566
|
+
const urls = zaiOrigin ? candidates.filter(url => new URL(url).origin === zaiOrigin) : candidates
|
|
1560
1567
|
const attempts = []
|
|
1561
1568
|
const trace = (url, status, stage, code) => {
|
|
1562
1569
|
if (provider !== 'zai') return
|
|
@@ -1588,8 +1595,11 @@ export async function queryCodingPlan(provider, key, locale, t, { baseUrl, orgId
|
|
|
1588
1595
|
const parse = isKimiCoding ? parseKimiCodingUsage : CODING_PLAN_PARSERS[provider]
|
|
1589
1596
|
let response
|
|
1590
1597
|
try {
|
|
1598
|
+
// Z.ai's official usage plugin sends the configured token as-is to quota/limit.
|
|
1599
|
+
// The older billing endpoints retain their Bearer authentication.
|
|
1600
|
+
const zaiMonitor = provider === 'zai' && url.endsWith('/api/monitor/usage/quota/limit')
|
|
1591
1601
|
const headers = {
|
|
1592
|
-
authorization: `Bearer ${key.trim()}`,
|
|
1602
|
+
authorization: zaiMonitor ? key.trim() : `Bearer ${key.trim()}`,
|
|
1593
1603
|
'user-agent': 'dsh-cost-meter/1.4 (DeepSeek Harness plugin)',
|
|
1594
1604
|
}
|
|
1595
1605
|
if (isKimiCoding) {
|
package/lib/gateway-quotas.js
CHANGED
|
@@ -677,7 +677,7 @@ export async function queryGatewayQuota(ctx, rawSource, options = {}) {
|
|
|
677
677
|
}
|
|
678
678
|
|
|
679
679
|
export function gatewaySourceUsesVar(source, varName) {
|
|
680
|
-
return managementKeyVarOf(source) === varName
|
|
680
|
+
return source?.type !== 'agy-link' && managementKeyVarOf(source) === varName
|
|
681
681
|
}
|
|
682
682
|
|
|
683
683
|
export const __test = {
|
package/lib/index.js
CHANGED
|
@@ -33,6 +33,7 @@ import { createLlmStreamBilling } from './billing-stream.js'
|
|
|
33
33
|
import { contextActivity } from './context-activity.js'
|
|
34
34
|
import { installBillionContextBilling, syncBillionContextBilling, billionContextBillingStatus } from './billion-context-billing.js'
|
|
35
35
|
import { installNativeSearchBilling, nativeSearchReconcile, isNativeSearchUsageEvent } from './native-search-billing.js'
|
|
36
|
+
import { requestFeeCostCny } from './web-request-pricing.js'
|
|
36
37
|
import { OFFICIAL_PRICING_URL, OFFICIAL_PRICING_URL_ZH, LEGACY_BASE_BOUNDARY, FLASH_PRICE_EFFECTIVE_AT, parsePricingHtml, repairDefaultPeakPrice, upgradeDeepSeekPriceTable, mountMissingDeepSeekFlashModels, costOf, providerPriceEntryFor, buildPriceCatalog, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
|
|
37
38
|
import { createUsageDeduper, USAGE_DEDUP_WINDOW_MS, usageFingerprint } from './usage-dedup.js'
|
|
38
39
|
import { CODING_PLAN_PROVIDERS, CODING_PLAN_PROVIDER_IDS, queryCodingPlan, scnetTokenPlanWindows, qwenTokenPlanWindows, emptyCustomBalance, queryCustomBalance, normalizeVolcengineKey } from './coding-plans.js'
|
|
@@ -64,6 +65,8 @@ import { detectChatgptSubscription, ensureChatgptSubscriptionPlan } from './chat
|
|
|
64
65
|
// JSONL 文件,回填/导入/重定价改由统一记录源读数据库;探测失败按 JSONL 兼容。
|
|
65
66
|
import { createSessionRecordSource, probeSessionStorage } from './session-storage-compat.js'
|
|
66
67
|
import { customBalanceCredentialVars, customBalanceHostOrigin, isHostRelativeBalanceUrl } from './custom-balance.js'
|
|
68
|
+
import { queryAgyLinkQuota } from './agy-link-quota.js'
|
|
69
|
+
import { discoverZaiClaudeCredential } from './zai-credentials.js'
|
|
67
70
|
import { readScnetSnapshot } from './scnet-snapshot.js'
|
|
68
71
|
import { readExternalUsageSnapshot, externalTodayCostForReconcile } from './external-usage.js'
|
|
69
72
|
import { queryQwenCli } from './qwen-cli.js'
|
|
@@ -166,6 +169,7 @@ const SERVER_MESSAGES = {
|
|
|
166
169
|
openrouterRefreshed: 'OpenRouter 模型价格已刷新:{count} 个模型',
|
|
167
170
|
openrouterRefreshFailed: 'OpenRouter 价格刷新失败(已保留本地快照):{error}',
|
|
168
171
|
codingPlanKeyMissing: '未找到 {provider} 的凭据。请在下方填写 API Key,或配置对应环境变量/CLI 登录态;没有订阅可关闭该家的「启用」开关。',
|
|
172
|
+
zaiPlanKeyMissing: '请填写智谱个人或团队 Coding Plan 的 API Key。',
|
|
169
173
|
codingPlanUnauthorized: '{provider} 凭据无效或没有生效的订阅(接口返回 {code})。没有订阅可关闭该家的「启用」开关。',
|
|
170
174
|
codingPlanHttp: '{provider} 额度接口 HTTP {code}({url})',
|
|
171
175
|
codingPlanNoSubscription: '{provider} 当前没有生效的套餐订阅(未订阅或已到期)。',
|
|
@@ -275,6 +279,7 @@ const SERVER_MESSAGES = {
|
|
|
275
279
|
openrouterRefreshed: 'OpenRouter model prices refreshed: {count} models',
|
|
276
280
|
openrouterRefreshFailed: 'OpenRouter price refresh failed (kept local snapshot): {error}',
|
|
277
281
|
codingPlanKeyMissing: 'No credentials found for {provider}. Enter the API key below, or configure the matching environment variable / CLI login; turn off the Enable switch if you have no subscription.',
|
|
282
|
+
zaiPlanKeyMissing: 'Enter the API key for your personal or team GLM Coding Plan.',
|
|
278
283
|
codingPlanUnauthorized: '{provider} credentials are invalid or no active subscription was detected (API returned {code}). Turn off the Enable switch if you have no subscription.',
|
|
279
284
|
codingPlanHttp: '{provider} quota API returned HTTP {code} ({url})',
|
|
280
285
|
codingPlanNoSubscription: '{provider} has no active plan subscription (not subscribed or expired).',
|
|
@@ -714,7 +719,7 @@ function makeCostUsageProjection(ledger) {
|
|
|
714
719
|
})
|
|
715
720
|
const peak = { enabled: pricing?.peakEnabled === true, effectiveAtMs: Date.parse(pricing?.peakEffectiveAt ?? ''), windows: pricing?.peakWindows, holidays: pricing?.peakHolidays }
|
|
716
721
|
peak.enabled = ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && peak.enabled
|
|
717
|
-
const priced = requestFee ? requestFee
|
|
722
|
+
const priced = requestFee ? requestFeeCostCny(requestFee, atMs) : resolved.priced ? costOf(buckets, resolved.entry, pricedAtMs, peak) : 0
|
|
718
723
|
const billed = usdFromCost(priced, resolved.currency, fxRatesOf(pricing).CNY)
|
|
719
724
|
// 同一 (turn, step) 的最终样本替换流式样本,先减后加,避免重复计数。
|
|
720
725
|
const totals = { ...state.totals, reasoning: state.totals.reasoning ?? 0 }
|
|
@@ -1046,7 +1051,8 @@ async function resolveCodingPlanKey(ctx, provider, config) {
|
|
|
1046
1051
|
if (token !== null) return token
|
|
1047
1052
|
}
|
|
1048
1053
|
const legacy = String(config?.codingPlans?.[provider]?.apiKey ?? '').trim()
|
|
1049
|
-
|
|
1054
|
+
if (legacy) return legacy
|
|
1055
|
+
return provider === 'zai' ? discoverZaiClaudeCredential() : null
|
|
1050
1056
|
}
|
|
1051
1057
|
|
|
1052
1058
|
/**
|
|
@@ -1388,7 +1394,7 @@ async function buildState(ledger, balance = emptyBalance(), goQuota = emptyGoQuo
|
|
|
1388
1394
|
for (const name of customBalanceCredentialVars(entry)) names.add(name)
|
|
1389
1395
|
}
|
|
1390
1396
|
for (const source of (Array.isArray(ledger.config?.gatewayQuotas?.sources) ? ledger.config.gatewayQuotas.sources : [])) {
|
|
1391
|
-
names.add(managementKeyVarOf(source))
|
|
1397
|
+
if (source.type !== 'agy-link') names.add(managementKeyVarOf(source))
|
|
1392
1398
|
}
|
|
1393
1399
|
if (credentials !== undefined) {
|
|
1394
1400
|
for (const name of names) {
|
|
@@ -1460,7 +1466,7 @@ async function buildState(ledger, balance = emptyBalance(), goQuota = emptyGoQuo
|
|
|
1460
1466
|
// 网关来源透传派生变量名(issue #87):让客户端直接定位 write-only 凭据目标,
|
|
1461
1467
|
// 避免客户端按前缀猜测 collision(home vs home-cpa)。
|
|
1462
1468
|
...(rawConfig.gatewayQuotas !== null && typeof rawConfig.gatewayQuotas === 'object' && !Array.isArray(rawConfig.gatewayQuotas)
|
|
1463
|
-
? { gatewayQuotas: { ...rawConfig.gatewayQuotas, sources: (Array.isArray(rawConfig.gatewayQuotas.sources) ? rawConfig.gatewayQuotas.sources : []).map(source => source
|
|
1469
|
+
? { gatewayQuotas: { ...rawConfig.gatewayQuotas, sources: (Array.isArray(rawConfig.gatewayQuotas.sources) ? rawConfig.gatewayQuotas.sources : []).map(source => source?.type === 'cliproxyapi' ? { ...source, keyVar: managementKeyVarOf(source) } : source) } }
|
|
1464
1470
|
: {}),
|
|
1465
1471
|
...(clientCodingPlans !== undefined ? { codingPlans: clientCodingPlans } : {}),
|
|
1466
1472
|
}
|
|
@@ -1661,7 +1667,9 @@ async function describePlanKey(credentials, id, config) {
|
|
|
1661
1667
|
} catch { /* Try the remaining sources, just like the resolver. */ }
|
|
1662
1668
|
}
|
|
1663
1669
|
if (refs.some(ref => String(process.env[ref] ?? '').trim().length > 0)) return { keyConfigured: true, keySource: 'env' }
|
|
1664
|
-
|
|
1670
|
+
if (legacy) return { keyConfigured: true, keySource: 'legacy' }
|
|
1671
|
+
const discovered = id === 'zai' && config.codingPlans?.zai?.enabled === true ? discoverZaiClaudeCredential() : null
|
|
1672
|
+
return discovered ? { keyConfigured: true, keySource: discovered.source } : fallback
|
|
1665
1673
|
}
|
|
1666
1674
|
|
|
1667
1675
|
/**
|
|
@@ -1810,6 +1818,10 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
1810
1818
|
if (String(ref).startsWith('DSH_COST_METER_ACCOUNT_BALANCE_') || ref === 'DEEPSEEK_BALANCE_API_KEY') balanceAccounts.reset()
|
|
1811
1819
|
const selected = queryAccountTarget(ledger.config, 'balance', secretRefOf)
|
|
1812
1820
|
if (ref === selected?.ref || usesModelBalanceRoute() && ref === balanceRoute.apiKeyEnv) invalidateAccountBalance()
|
|
1821
|
+
const zai = queryAccountTarget(ledger.config, 'codingPlans.zai', secretRefOf)
|
|
1822
|
+
if (ref === zai?.ref || zai?.id === 'default' && CODING_PLAN_PROVIDERS.zai.credentialEnvs.includes(ref)) {
|
|
1823
|
+
resetQueryCache('codingPlans.zai')
|
|
1824
|
+
}
|
|
1813
1825
|
})
|
|
1814
1826
|
ctx.on('settings/document-updated', ns => {
|
|
1815
1827
|
if (ns === balanceRoute.settingsNs || ns === 'llm-deepseek' || ns === 'llm-deepseek-api-key') syncBalanceModelRoute(true)
|
|
@@ -1865,6 +1877,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
1865
1877
|
gatewayQuotaCaches = next
|
|
1866
1878
|
}
|
|
1867
1879
|
const resolveGatewayKeyConfigured = async (serviceCtx, source) => {
|
|
1880
|
+
if (source.type === 'agy-link') return false
|
|
1868
1881
|
const varName = managementKeyVarOf(source)
|
|
1869
1882
|
const credentials = serviceCtx?.get?.('credentials')
|
|
1870
1883
|
if (credentials !== undefined) {
|
|
@@ -2436,7 +2449,10 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2436
2449
|
}).finally(() => {
|
|
2437
2450
|
if (codingPlanCaches[id]?.inFlight === task) delete codingPlanCaches[id].inFlight
|
|
2438
2451
|
})
|
|
2439
|
-
|
|
2452
|
+
const existing = codingPlanCaches[id]
|
|
2453
|
+
const value = id === 'zai' && !(existing?.value?.fetchedAt > 0)
|
|
2454
|
+
? { ...emptyCodingPlan(), status: 'loading' } : existing?.value ?? emptyCodingPlan()
|
|
2455
|
+
codingPlanCaches[id] = { fetchedAt: existing?.fetchedAt ?? 0, value, inFlight: task, controller }
|
|
2440
2456
|
await task
|
|
2441
2457
|
}
|
|
2442
2458
|
|
|
@@ -2463,7 +2479,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2463
2479
|
gatewayQuotaCaches[id] = cache
|
|
2464
2480
|
}
|
|
2465
2481
|
const interval = Math.max(1, Number(source.refreshMinutes) || 15) * 60_000
|
|
2466
|
-
if (!force && Date.now() - cache.fetchedAt < interval && gatewayCacheHasLkg(cache, source)) return cache.value
|
|
2482
|
+
if (!force && Date.now() - cache.fetchedAt < interval && (source.type === 'agy-link' || gatewayCacheHasLkg(cache, source))) return cache.value
|
|
2467
2483
|
if (cache.inFlight !== undefined) {
|
|
2468
2484
|
const current = cache.inFlight
|
|
2469
2485
|
if (!force) {
|
|
@@ -2477,7 +2493,12 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2477
2493
|
if (cache === undefined || cache.inFlight !== undefined) return ensureGatewayQuota(source, true)
|
|
2478
2494
|
}
|
|
2479
2495
|
const controller = new AbortController()
|
|
2480
|
-
const
|
|
2496
|
+
const signal = controller.signal
|
|
2497
|
+
const query = source.type === 'agy-link'
|
|
2498
|
+
? queryAgyLinkQuota({ ...emptyGatewayForSource(source), attemptedAt: Date.now() },
|
|
2499
|
+
{ hostOrigin: customBalanceHostOrigin(ctx), force, locale: localeOf(ledger.config, ctx), signal })
|
|
2500
|
+
: queryGatewayQuota(ctx, source, { signal })
|
|
2501
|
+
const task = query.then(value => {
|
|
2481
2502
|
const active = gatewayQuotaCaches[id]
|
|
2482
2503
|
if (active?.inFlight !== task || active.sourceFingerprint !== fingerprint) return value
|
|
2483
2504
|
const ok = gatewayValueIsLastGood(value)
|
|
@@ -2487,7 +2508,7 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
2487
2508
|
message: typeof value?.message === 'string' ? value.message : '', attemptedAt: value?.attemptedAt ?? Date.now(),
|
|
2488
2509
|
keyConfigured: value?.keyConfigured === true, keySource: typeof value?.keySource === 'string' ? value.keySource : 'none',
|
|
2489
2510
|
}
|
|
2490
|
-
gatewayQuotaCaches[id] = { ...active, fetchedAt: ok ? Date.now() : (active.fetchedAt ?? 0), value: next, lastGood }
|
|
2511
|
+
gatewayQuotaCaches[id] = { ...active, fetchedAt: ok || source.type === 'agy-link' ? Date.now() : (active.fetchedAt ?? 0), value: next, lastGood }
|
|
2491
2512
|
return next
|
|
2492
2513
|
}).catch(error => {
|
|
2493
2514
|
const active = gatewayQuotaCaches[id]
|
|
@@ -3067,7 +3088,10 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
|
|
|
3067
3088
|
invalidateCustomBalanceCachesForVar(customVar)
|
|
3068
3089
|
for (const source of gatewaySourceConfigs()) if (managementKeyVarOf(source) === customVar) { gatewayQuotaCaches[source.id]?.controller?.abort(); delete gatewayQuotaCaches[source.id] }
|
|
3069
3090
|
}
|
|
3070
|
-
else if (account.id === selectedQueryAccount(ledger.config, account.source))
|
|
3091
|
+
else if (account.id === selectedQueryAccount(ledger.config, account.source)) {
|
|
3092
|
+
resetQueryCache(account.source, { keepLogin: account.source === 'codingPlans.opendesign' })
|
|
3093
|
+
if (account.source === 'codingPlans.zai') void ensureCodingPlan('zai').catch(() => {})
|
|
3094
|
+
}
|
|
3071
3095
|
if (account?.source === 'balance') balanceAccounts.reset()
|
|
3072
3096
|
if (account?.source === 'balance' && account.id === selectedQueryAccount(ledger.config, 'balance')) {
|
|
3073
3097
|
ledger.balanceRef = null
|