opencode-codebuddy-quota 0.1.4 → 0.1.5
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/config.default.json +2 -1
- package/dist/gui-experimental.cjs +1 -1
- package/package.json +1 -1
- package/rpc.ts +24 -0
- package/server.ts +21 -15
- package/src/gui/dialog-helpers.ts +33 -0
- package/src/gui/dialog.css +8 -0
- package/src/gui/dialog.tsx +39 -3
- package/src/gui/quota.ts +37 -6
- package/src/gui/store.ts +146 -76
- package/src/gui.tsx +17 -0
- package/src/server/config.ts +14 -0
- package/src/server/proxy.ts +66 -0
- package/src/server/rate-limit-store.ts +102 -0
- package/src/server/rpc-handlers.ts +16 -2
- package/src/server/setup-order.ts +17 -0
- package/src/server/wire.ts +6 -2
- package/src/shared.ts +9 -0
package/config.default.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});let e=require("solid-js/web"),t=require("@opencode/plugin/gui"),n=require("solid-js"),r=require("@opencode/plugin/rpc");var i={type:[`string`,`null`]},a={type:[`number`,`null`]},o={type:`string`,enum:[`cn`,`intl`]},s={type:`object`,properties:{site:o,available:{type:`boolean`},accounts:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`}},required:[`id`,`label`],additionalProperties:!1}},activeId:i},required:[`site`,`available`,`accounts`,`activeId`],additionalProperties:!1},c=r.Rpc.define({id:`codebuddy-quota`,methods:{read:{input:{type:`object`,properties:{site:o},additionalProperties:!1},output:{type:`object`,properties:{ok:{type:`boolean`},stale:{type:`boolean`},cached:{type:`boolean`},ageSeconds:a,remaining:a,used:a,total:a,cycleStart:i,cycleEnd:i,resetAt:i,fetchedAt:i,error:i,site:o,sites:{type:`array`,items:s}},required:[`ok`,`stale`,`cached`,`site`,`sites`],additionalProperties:!1}},login:{input:{type:`object`,properties:{site:o},required:[`site`],additionalProperties:!1},output:{type:`object`,properties:{ok:{type:`boolean`},error:i},required:[`ok`,`error`],additionalProperties:!1}}},events:{}}),l=(0,e.template)(`<span><span></span><span>`),u=`repeating-linear-gradient(45deg, rgba(0,0,0,.22) 0 3px, transparent 3px 6px)`,d=`rgba(127, 137, 156, 0.35)`,f=`rgba(127, 137, 156, 0.22)`,p=e=>e===null?0:Math.max(0,Math.min(100,e));function m(t){let n=()=>t.value===null,r=()=>({position:`relative`,display:`inline-flex`,"align-items":`center`,"justify-content":`center`,width:`52px`,height:`18px`,"border-radius":`6px`,background:n()?f:d,opacity:t.dim?`0.72`:`1`,"box-sizing":`border-box`,"vertical-align":`middle`,overflow:`hidden`}),i=()=>({position:`absolute`,left:`0`,top:`0`,height:`100%`,width:`${p(t.value)}%`,"border-radius":`6px`,background:t.color,"background-image":t.dim?u:void 0,transition:`width 200ms ease-out, background 200ms ease-out`}),a=()=>({position:`relative`,"font-size":`10px`,"font-weight":`700`,"font-variant-numeric":`tabular-nums`,"line-height":`1`,"letter-spacing":`-0.2px`,color:n()?`#8b90a0`:`#0d1117`,"pointer-events":`none`,"text-shadow":n()?`none`:`0 0 2px rgba(0,0,0,.18)`});return(()=>{var o=l(),s=o.firstChild,c=s.nextSibling;return(0,e.insert)(c,(()=>{var r=(0,e.memo)(()=>!!n());return()=>r()?`--`:String(t.value)})()),(0,e.effect)(t=>{var n=r(),l=i(),u=a();return t.e=(0,e.style)(o,n,t.e),t.t=(0,e.style)(s,l,t.t),t.a=(0,e.style)(c,u,t.a),t},{e:void 0,t:void 0,a:void 0}),o})()}var h=`#4ade80`,g=`#f5c246`,_=`#f87171`,v=`#8b90a0`,y=3,b=e=>[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)],x=(e,t,n)=>{let r=b(e),i=b(t);return[Math.round(r[0]+(i[0]-r[0])*n),Math.round(r[1]+(i[1]-r[1])*n),Math.round(r[2]+(i[2]-r[2])*n)]},S=([e,t,n])=>`rgb(${e}, ${t}, ${n})`;function C(e){if(e.diff===null||e.timePct===null)return v;if(e.timePct<y)return h;let t=e.diff;return t>=5?h:t<=-5?_:S(x(g,t<0?_:h,Math.abs(t)/5))}function w(e){return e.diff===null||e.timePct===null?`unknown`:e.timePct<y||e.diff>=5?`normal`:e.diff>=0?`ahead`:e.diff>-5?`fast`:`over`}function T(e){return e===null?`—`:e.toFixed(2)}function E(e){return e===null?`—`:`${e.toFixed(2)}%`}function D(e){return e===null||!Number.isFinite(e)?`—`:e===0?`0.00 pp`:`${e>0?`+`:`-`}${Math.abs(e).toFixed(2)} pp`}var O=e=>e===null||!Number.isFinite(e)?`—`:`${Math.max(0,Math.min(100,Math.round(e)))}%`,k=e=>e===null||!Number.isFinite(e)?0:Math.max(0,Math.min(100,e)),A=e=>e===null||!Number.isFinite(e)?``:` · ${e>=0?`慢于`:`快于`}时间 ${D(Math.abs(e))}`;function j(e){return e.status===`error`?{text:`不可用`,color:`#ff7a7a`}:e.status===`cached`?{text:e.ageSeconds===null?`缓存`:`缓存(${e.ageSeconds} 秒前)`,color:`#ffb84d`}:e.status===`stale`?{text:`过期`,color:`#ff7a7a`}:{text:`实时`,color:`#3ddc97`}}var M=(0,e.template)(`<div class=cq-tag><span class=cq-dot style=display:inline-block;width:6px;height:6px;border-radius:50%;margin-right:6px;vertical-align:middle>`),N=(0,e.template)(`<span style=margin-left:6px;font-size:10px;opacity:0.8>`),P=(0,e.template)(`<div style=min-width:340px><div style=display:flex;gap:4px;margin-bottom:10px></div><div style=display:flex;align-items:center;gap:6px;font-size:10px;margin-bottom:12px><span class=cq-dot style=width:6px;height:6px;border-radius:50%>`),ee=(0,e.template)(`<div style="padding:12px;border-radius:10px;background:color-mix(in oklab, currentColor 5%, transparent);border:1px dashed color-mix(in oklab, currentColor 24%, transparent);font-size:12px;line-height:1.6;text-align:center"><div style="color:var(--sub, #aab3c6);margin-bottom:10px"><b style=color:#ffb84d>未登录</b>或认证已过期</div><div style=font-size:10px;opacity:0.6;margin-top:10px>打开浏览器授权,插件自行轮询获取凭据;无需安装 CodeBuddy CLI。`),te=(0,e.template)(`<div style=display:flex;align-items:baseline;justify-content:space-between;margin-bottom:2px><span style=font-size:12px;opacity:0.72>本周期剩余额度</span><span class=cq-amount style=font-size:26px;font-weight:750;font-variant-numeric:tabular-nums> <small style=font-size:12px;font-weight:500;opacity:0.7>积分`),ne=(0,e.template)(`<div class=cq-track style="position:relative;height:16px;border-radius:6px;background:color-mix(in oklab, currentColor 12%, transparent);margin-top:10px"><div class=cq-fill style=position:absolute;left:0;top:0;bottom:0;border-radius:6px>`),re=(0,e.template)(`<div style=display:flex;justify-content:space-between;font-size:10.5px;opacity:0.8;margin-top:8px><span>● 已用进度 </span><span>▏时间已过 `),ie=(0,e.template)(`<div class=cq-hint style="display:flex;gap:9px;align-items:flex-start;border-radius:9px;padding:10px 12px;font-size:12px;border:1px solid color-mix(in oklab, currentColor 12%, transparent);margin-top:12px"><span style=font-weight:800></span><div><div style=font-weight:700></div><div style=opacity:0.72;font-size:10.5px>积分消耗<!>时间流逝,按当前速度`),F=(0,e.template)(`<div style="margin-top:13px;border-top:1px solid rgba(255,255,255,.1);padding-top:6px"><div class=cq-row><span>已使用</span><span> 积分</span></div><div class=cq-row><span>总额度</span><span> 积分</span></div><div style=border-bottom:none><span>到期 / 重置</span><span>`),I=(0,e.template)(`<div class=cq-marker style=position:absolute;top:-3px;bottom:-3px;width:2px;background:#fff;border-radius:2px;opacity:0.9>`),L={normal:`节奏正常`,ahead:`略慢于时间`,fast:`略快于时间`,over:`超支`,unknown:`—`},R={normal:`normal`,ahead:`normal`,fast:`fast`,over:`over`,unknown:`fast`},z={normal:`#3ddc97`,fast:`#ffb84d`,over:`#ff7a7a`},B={display:`flex`,"justify-content":`space-between`,gap:`12px`,padding:`6px 0`,"font-size":`12px`,"border-bottom":`1px dashed rgba(128,128,128,.25)`},V={opacity:`0.62`},H={"font-variant-numeric":`tabular-nums`},U={cn:`国内站`,intl:`国际站`};function W(t){let r=()=>t.quota,i=()=>r().site,a=()=>r().sites,o=()=>r().status===`error`||r().remaining===null,s=()=>j(r()),[c,l]=(0,n.createSignal)(!1),[u,d]=(0,n.createSignal)(null),f=async e=>{if(!c()){l(!0);try{await t.onRefresh(e)}finally{l(!1)}}},p=async e=>{if(!u()){d(e);try{await t.onLogin(e)}finally{d(null)}}},m=e=>{e!==i()&&f(e)},h=t.ui.Dialog,g=t.ui.Button,_=t=>{let n=t.site===i(),r=n?{flex:`1`,border:`1px solid`,"font-size":`12px`,padding:`8px 6px`,"border-radius":`8px`,cursor:`pointer`,"font-weight":`600`}:{flex:`1`,border:`1px solid`,"border-color":`color-mix(in oklab, currentColor 22%, transparent)`,background:`color-mix(in oklab, currentColor 5%, transparent)`,color:`inherit`,"font-size":`12px`,padding:`8px 6px`,"border-radius":`8px`,cursor:`pointer`,"font-weight":`600`};return(()=>{var i=M(),a=i.firstChild;return i.$$click=()=>t.available?m(t.site):p(t.site),(0,e.setAttribute)(i,`data-active`,n?`true`:`false`),(0,e.insert)(i,()=>U[t.site],null),(0,e.insert)(i,(()=>{var n=(0,e.memo)(()=>!t.available);return()=>n()&&(()=>{var n=N();return(0,e.insert)(n,()=>u()===t.site?`登录中…`:`· 登录`),n})()})(),null),(0,e.effect)(n=>{var o=r,s=t.available?`#3ddc97`:`#ff7a7a`;return n.e=(0,e.style)(i,o,n.e),s!==n.t&&(0,e.setStyleProperty)(a,`background`,n.t=s),n},{e:void 0,t:void 0}),i})()},v=()=>(()=>{var t=P(),n=t.firstChild,c=n.nextSibling,l=c.firstChild;return(0,e.insert)(n,()=>a().map(_)),(0,e.insert)(c,()=>s().text,null),(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!o());return()=>t()?(()=>{var t=ee(),n=t.firstChild,r=n.firstChild,a=r.firstChild,o=n.nextSibling;return(0,e.insert)(r,()=>U[i()],a),(0,e.insert)(t,(0,e.createComponent)(g,{variant:`contrast`,get busy(){return u()===i()},onClick:()=>p(i()),get children(){return[`登录`,(0,e.memo)(()=>U[i()])]}}),o),t})():[(()=>{var t=te(),n=t.firstChild.nextSibling,i=n.firstChild;return i.nextSibling,(0,e.insert)(n,()=>T(r().remaining),i),t})(),(()=>{var t=ne(),n=t.firstChild;return(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>r().timePct!==null);return()=>t()&&(()=>{var t=I();return(0,e.effect)(n=>(0,e.setStyleProperty)(t,`left`,`${k(r().timePct)}%`)),t})()})(),null),(0,e.effect)(t=>{var i=`${Math.max(0,Math.min(100,r().usedPct??0))}%`,a=C(r());return i!==t.e&&(0,e.setStyleProperty)(n,`width`,t.e=i),a!==t.t&&(0,e.setStyleProperty)(n,`color`,t.t=a),t},{e:void 0,t:void 0}),t})(),(()=>{var t=re(),n=t.firstChild;n.firstChild;var i=n.nextSibling;return i.firstChild,(0,e.insert)(n,()=>O(r().usedPct),null),(0,e.insert)(i,()=>O(r().timePct),null),t})(),(()=>{var t=ie(),n=t.firstChild,i=n.nextSibling.firstChild,a=i.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,(0,e.insert)(n,()=>R[w(r())]===`normal`?`✓`:`!`),(0,e.insert)(i,()=>L[w(r())],null),(0,e.insert)(i,()=>A(r().diff),null),(0,e.insert)(a,()=>r().diff!==null&&r().diff<0?`快于`:`慢于`,o),(0,e.insert)(a,()=>r().diff!==null&&r().diff<0?`可能在周期末前用完,建议控制用量。`:`可用到周期末。`,null),(0,e.effect)(t=>{var a=z[R[w(r())]],o=z[R[w(r())]];return a!==t.e&&(0,e.setStyleProperty)(n,`color`,t.e=a),o!==t.t&&(0,e.setStyleProperty)(i,`color`,t.t=o),t},{e:void 0,t:void 0}),t})(),(()=>{var t=F(),n=t.firstChild,i=n.firstChild,a=i.nextSibling,o=a.firstChild,s=n.nextSibling,c=s.firstChild,l=c.nextSibling,u=l.firstChild,d=s.nextSibling,f=d.firstChild,p=f.nextSibling;return(0,e.insert)(a,()=>T(r().used),o),(0,e.insert)(l,()=>T(r().total),u),(0,e.insert)(p,()=>r().resetAt??`—`),(0,e.effect)(t=>{var r=B,o=V,u=H,m=B,h=V,g=H,_={...B},v=V,y=H;return t.e=(0,e.style)(n,r,t.e),t.t=(0,e.style)(i,o,t.t),t.a=(0,e.style)(a,u,t.a),t.o=(0,e.style)(s,m,t.o),t.i=(0,e.style)(c,h,t.i),t.n=(0,e.style)(l,g,t.n),t.s=(0,e.style)(d,_,t.s),t.h=(0,e.style)(f,v,t.h),t.r=(0,e.style)(p,y,t.r),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),t})()]})(),null),(0,e.effect)(t=>{var n=s().color,r=s().color;return n!==t.e&&(0,e.setStyleProperty)(c,`color`,t.e=n),r!==t.t&&(0,e.setStyleProperty)(l,`background`,t.t=r),t},{e:void 0,t:void 0}),t})();return(0,n.onMount)(()=>{f(i())}),(0,e.createComponent)(h,{get title(){return`CodeBuddy 额度 · ${U[i()]}`},size:`fit`,get footer(){return(0,e.createComponent)(g,{variant:`neutral`,get busy(){return c()},onClick:()=>f(i()),children:`刷新`})},get children(){return v()}})}(0,e.delegateEvents)([`click`]);var G=e=>Math.round(e*100)/100;function K(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:null}function q(e){if(typeof e!=`string`)return null;let t=/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(e.trim());if(!t)return null;let[,n,r,i,a,o,s]=t.map(Number),c=new Date(n,r-1,i,a,o,s).getTime();return Number.isFinite(c)?c:null}var J=[{site:`cn`,available:!1,accounts:[],activeId:null},{site:`intl`,available:!1,accounts:[],activeId:null}];function ae(e,t){return{status:e,site:`cn`,sites:J,remaining:null,used:null,total:null,usedPct:null,timePct:null,diff:null,cycleStart:null,cycleEnd:null,resetAt:null,fetchedAt:null,ageSeconds:null,error:t}}function oe(e,t,n){if(e===null||t===null||n===null||t<=e)return null;let r=(n-e)/(t-e)*100;return G(Math.min(100,Math.max(0,r)))}function Y(e,t){let n=(e,n)=>n&&t.fallback?{...t.fallback,status:`stale`,error:e}:ae(`error`,e);if(typeof e!=`object`||!e)return n(typeof e==`string`?`unexpected response: ${e.slice(0,80)}`:`empty response`,!0);let r=e,i=typeof r.error==`string`?r.error:null;if(r.ok!==!0)return n(i??`quota service reported no reading`,!1);let a=K(r.total),o=K(r.used),s=K(r.remaining);if(a===null||a<=0||o===null||s===null)return n(i??`payload is missing a usable total/used/remaining`,!0);let c=typeof r.cycleStart==`string`?r.cycleStart:null,l=typeof r.cycleEnd==`string`?r.cycleEnd:null,u=typeof r.resetAt==`string`?r.resetAt:null,d=typeof r.fetchedAt==`string`?r.fetchedAt:null,f=G(o/a*100),p=d?Date.parse(d):NaN,m=Number.isFinite(p)?p:null,h=oe(q(c),q(u)??q(l),m),g=f!==null&&h!==null&&Number.isFinite(h)?G(h-f):null,_=r.stale===!0?`stale`:r.cached===!0?`cached`:`ok`,v=K(r.ageSeconds);return{status:_,site:r.site===`intl`?`intl`:`cn`,sites:Array.isArray(r.sites)?r.sites.filter(e=>e&&(e.site===`cn`||e.site===`intl`)&&Array.isArray(e.accounts)):J,remaining:s,used:o,total:a,usedPct:f,timePct:h,diff:g,cycleStart:c,cycleEnd:l,resetAt:u,fetchedAt:d,ageSeconds:v===null?null:Math.round(v),error:i??null}}function se(e){if(e.total===null||e.total<=0)return null;let t=e.used;if(t===null)return e.remaining===null?null:Math.min(100,Math.max(0,Math.round(e.remaining/e.total*100)));let n=Math.round((e.total-t)/e.total*100);return Math.min(100,Math.max(0,n))}function X(e){if(e.usedPct===null||e.used===null||e.total===null)return null;let t=100-e.usedPct;return Math.max(0,Math.round(t*100)/100)}var Z=18e5,ce=6e4,le=12e4,Q=(e,t)=>({status:e,site:`cn`,sites:[{site:`cn`,available:!1,accounts:[],activeId:null},{site:`intl`,available:!1,accounts:[],activeId:null}],remaining:null,used:null,total:null,usedPct:null,timePct:null,diff:null,cycleStart:null,cycleEnd:null,resetAt:null,fetchedAt:null,ageSeconds:null,error:t});async function $(e){let t=e.now??Date.now(),n;try{n=await e.client.read(e.site?{site:e.site}:{})}catch(t){let n=String(t?.message??t);return e.fallback?{...e.fallback,status:`stale`,error:n}:Q(`error`,n)}return Y(n,{now:t})}function ue(e){let t=Y(null,{now:Date.now()}),n=0,r=null,i=null,a=!1,o=new Set,s=e=>{t=e;for(let t of o)t(e)},c=async(a={})=>{if(r)return a.site&&(i=a.site),r;let o=Date.now(),l=a.force?0:a.maxAgeMs??Z;if(!(o-n<l))return n=o,r=(async()=>{try{let n=t.remaining===null?null:t,r;try{r=await $({client:e(),fallback:n,site:a.site})}catch(e){let t=String(e?.message??e);r=n?{...n,status:`stale`,error:t}:Q(`error`,t)}s(r)}finally{r=null;let e=i;i=null,e&&e!==t.site&&c({force:!0,site:e})}})(),r};return{read:()=>t,subscribe(e){return o.add(e),()=>o.delete(e)},refresh:c,async login(t){try{let n=e().login;if(!n)return!1;let r=(await n({site:t}))?.ok===!0;return r&&await c({force:!0,site:t}),r}catch{return!1}},start:()=>{if(a)return()=>{};a=!0;let e=globalThis.document!==void 0,t=()=>{e&&globalThis.document.hidden||c()},r=()=>{globalThis.document.hidden||Date.now()-n>=le&&c()},i=setInterval(t,Z);return e&&globalThis.document.addEventListener(`visibilitychange`,r),c({force:!0}),()=>{clearInterval(i),e&&globalThis.document.removeEventListener(`visibilitychange`,r),a=!1}}}}var de=`.cq-tag{--cq-accent:#5b8cff;transition:box-shadow .18s,border-color .18s,background .18s,transform .18s;position:relative;overflow:hidden}.cq-tag:after{content:"";background:linear-gradient(105deg, transparent 30%, color-mix(in srgb, var(--cq-accent) 22%, transparent) 50%, transparent 70%);pointer-events:none;position:absolute;inset:0;transform:translate(-120%)}.cq-tag:hover:after{animation:.7s ease-out cq-sheen}.cq-tag[data-active=true]{background:color-mix(in srgb, var(--cq-accent) 14%, transparent);border-color:color-mix(in srgb, var(--cq-accent) 55%, transparent);color:color-mix(in srgb, var(--cq-accent) 85%, white);box-shadow:0 0 0 1px color-mix(in srgb, var(--cq-accent) 28%, transparent), 0 0 14px -2px color-mix(in srgb, var(--cq-accent) 50%, transparent)}.cq-tag:active{transform:scale(.97)}@keyframes cq-sheen{0%{transform:translate(-120%)}to{transform:translate(120%)}}.cq-dot{box-shadow:0 0 0 3px color-mix(in oklab, currentColor 14%, transparent)}.cq-amount{font-variant-numeric:tabular-nums;text-shadow:0 0 20px color-mix(in oklab, currentColor 22%, transparent)}.cq-track{overflow:hidden;box-shadow:inset 0 1px 3px #0000002e}.cq-fill{background:linear-gradient(100deg, color-mix(in oklab, currentColor 62%, transparent) 0%, currentColor 35%, color-mix(in oklab, white 45%, currentColor) 50%, currentColor 65%, color-mix(in oklab, currentColor 62%, transparent) 100%);box-shadow:0 0 10px -2px color-mix(in oklab, currentColor 65%, transparent);background-size:220% 100%;transition:width .3s cubic-bezier(.22,.8,.3,1),background .3s ease-out;animation:2.6s linear infinite cq-flow}@keyframes cq-flow{0%{background-position:120% 0}to{background-position:-120% 0}}.cq-marker{box-shadow:0 0 6px #ffffffbf}.cq-hint{background:color-mix(in oklab, currentColor 6%, transparent);box-shadow:inset 0 1px 0 color-mix(in oklab, currentColor 12%, transparent)}.cq-row{border-bottom:1px solid color-mix(in oklab, currentColor 14%, transparent)}@media (prefers-reduced-motion:reduce){.cq-tag,.cq-fill{transition:none;animation:none}.cq-tag:after{display:none}}`,fe=(0,e.template)(`<button type=button style="position:relative;background:transparent;border:none;padding:2px 6px 2px 0;margin-left:auto;cursor:pointer;line-height:0">`),pe=(0,e.template)(`<span style="position:absolute;top:0;right:0;width:9px;height:9px;border-radius:50%;background:#ffb84d;border:1.5px solid transparent">`),me=t.Plugin.define({setup(r){r.add(t.Style,de);let i=ue(()=>r.client.rpc(c)),[a,o]=(0,n.createSignal)(i.read());(0,n.onCleanup)(i.subscribe(o)),(0,n.onCleanup)(i.start());let s=()=>{r.dialogs.open(t=>(0,e.createComponent)(()=>{let[a,o]=(0,n.createSignal)(i.read());return(0,n.onCleanup)(i.subscribe(o)),(0,e.createComponent)(W,{get quota(){return a()},get ui(){return r.ui},onRefresh:e=>i.refresh({force:!0,site:e}),onLogin:e=>i.login(e),get close(){return t.close}})},{}))},l=()=>{i.refresh({maxAgeMs:ce,site:i.read().site})},u={cn:`国内站`,intl:`国际站`},d=()=>a().sites.some(e=>!e.available);r.add(t.Slot,{at:`session.header`,order:50,render:()=>(()=>{var t=fe();return t.$$click=s,t.addEventListener(`focus`,l),t.addEventListener(`mouseenter`,l),(0,e.insert)(t,(0,e.createComponent)(m,{get value(){return se(a())},get color(){return C(a())},get dim(){return a().status===`stale`}}),null),(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!d());return()=>t()&&pe()})(),null),(0,e.effect)(()=>(0,e.setAttribute)(t,`title`,X(a())===null?`CodeBuddy 额度 · ${u[a().site]}:暂不可用(点击查看/登录)`:`CodeBuddy 额度 · ${u[a().site]}:剩余 ${E(X(a()))}`)),t})()})}});(0,e.delegateEvents)([`click`]),exports.default=me;
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});let e=require("solid-js/web"),t=require("@opencode/plugin/gui"),n=require("solid-js"),r=require("@opencode/plugin/rpc");var i={type:[`string`,`null`]},a={type:[`number`,`null`]},o={type:`string`,enum:[`cn`,`intl`]},s={type:`object`,properties:{site:o,available:{type:`boolean`},accounts:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`}},required:[`id`,`label`],additionalProperties:!1}},activeId:i},required:[`site`,`available`,`accounts`,`activeId`],additionalProperties:!1},c=r.Rpc.define({id:`codebuddy-quota`,methods:{read:{input:{type:`object`,properties:{site:o},additionalProperties:!1},output:{type:`object`,properties:{ok:{type:`boolean`},stale:{type:`boolean`},cached:{type:`boolean`},ageSeconds:a,remaining:a,used:a,total:a,cycleStart:i,cycleEnd:i,resetAt:i,fetchedAt:i,error:i,site:o,sites:{type:`array`,items:s},rateLimits:{type:`array`,items:{type:`object`,properties:{site:o,model:{type:`string`},message:{type:`string`},unlockAt:a},required:[`site`,`model`,`message`,`unlockAt`],additionalProperties:!1}}},required:[`ok`,`stale`,`cached`,`site`,`sites`],additionalProperties:!1}},login:{input:{type:`object`,properties:{site:o},required:[`site`],additionalProperties:!1},output:{type:`object`,properties:{ok:{type:`boolean`},error:i},required:[`ok`,`error`],additionalProperties:!1}},config:{input:{type:`object`,additionalProperties:!1},output:{type:`object`,properties:{refreshMinutes:{type:`number`}},required:[`refreshMinutes`],additionalProperties:!1}}},events:{}}),l=(0,e.template)(`<span><span></span><span>`),u=`repeating-linear-gradient(45deg, rgba(0,0,0,.22) 0 3px, transparent 3px 6px)`,d=`rgba(127, 137, 156, 0.35)`,f=`rgba(127, 137, 156, 0.22)`,p=e=>e===null?0:Math.max(0,Math.min(100,e));function m(t){let n=()=>t.value===null,r=()=>({position:`relative`,display:`inline-flex`,"align-items":`center`,"justify-content":`center`,width:`52px`,height:`18px`,"border-radius":`6px`,background:n()?f:d,opacity:t.dim?`0.72`:`1`,"box-sizing":`border-box`,"vertical-align":`middle`,overflow:`hidden`}),i=()=>({position:`absolute`,left:`0`,top:`0`,height:`100%`,width:`${p(t.value)}%`,"border-radius":`6px`,background:t.color,"background-image":t.dim?u:void 0,transition:`width 200ms ease-out, background 200ms ease-out`}),a=()=>({position:`relative`,"font-size":`10px`,"font-weight":`700`,"font-variant-numeric":`tabular-nums`,"line-height":`1`,"letter-spacing":`-0.2px`,color:n()?`#8b90a0`:`#0d1117`,"pointer-events":`none`,"text-shadow":n()?`none`:`0 0 2px rgba(0,0,0,.18)`});return(()=>{var o=l(),s=o.firstChild,c=s.nextSibling;return(0,e.insert)(c,(()=>{var r=(0,e.memo)(()=>!!n());return()=>r()?`--`:String(t.value)})()),(0,e.effect)(t=>{var n=r(),l=i(),u=a();return t.e=(0,e.style)(o,n,t.e),t.t=(0,e.style)(s,l,t.t),t.a=(0,e.style)(c,u,t.a),t},{e:void 0,t:void 0,a:void 0}),o})()}var h=`#4ade80`,g=`#f5c246`,_=`#f87171`,v=`#8b90a0`,y=3,b=e=>[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)],x=(e,t,n)=>{let r=b(e),i=b(t);return[Math.round(r[0]+(i[0]-r[0])*n),Math.round(r[1]+(i[1]-r[1])*n),Math.round(r[2]+(i[2]-r[2])*n)]},S=([e,t,n])=>`rgb(${e}, ${t}, ${n})`;function C(e){if(e.diff===null||e.timePct===null)return v;if(e.timePct<y)return h;let t=e.diff;return t>=5?h:t<=-5?_:S(x(g,t<0?_:h,Math.abs(t)/5))}function w(e){return e.diff===null||e.timePct===null?`unknown`:e.timePct<y||e.diff>=5?`normal`:e.diff>=0?`ahead`:e.diff>-5?`fast`:`over`}function T(e){return e===null?`—`:e.toFixed(2)}function E(e){return e===null?`—`:`${e.toFixed(2)}%`}function D(e){return e===null||!Number.isFinite(e)?`—`:e===0?`0.00 pp`:`${e>0?`+`:`-`}${Math.abs(e).toFixed(2)} pp`}var O=e=>e===null||!Number.isFinite(e)?`—`:`${Math.max(0,Math.min(100,Math.round(e)))}%`,k=e=>e===null||!Number.isFinite(e)?0:Math.max(0,Math.min(100,e)),A=e=>e===null||!Number.isFinite(e)?``:` · ${e>=0?`慢于`:`快于`}时间 ${D(Math.abs(e))}`;function j(e,t,n){let r=e.filter(e=>e.unlockAt===null||e.unlockAt>t).sort((e,t)=>(e.unlockAt??1/0)-(t.unlockAt??1/0));return{current:n?r.find(e=>e.model===n):void 0,others:r.filter(e=>e.model!==n)}}function M(e,t){if(e===null)return`解除时间未知,请稍后重试(成功请求后自动消失)`;let n=Math.max(0,Math.ceil((e-t)/1e3)),r=Math.floor(n/60),i=n%60,a=r>0?`${r} 分 ${i} 秒`:`${i} 秒`,o=new Date(e).getHours(),s=new Date(e).getMinutes();return`约 ${a}后解除(${`${String(o).padStart(2,`0`)}:${String(s).padStart(2,`0`)}`} 解除)`}function N(e){return e.status===`error`?{text:`不可用`,color:`#ff7a7a`}:e.status===`cached`?{text:e.ageSeconds===null?`缓存`:`缓存(${e.ageSeconds} 秒前)`,color:`#ffb84d`}:e.status===`stale`?{text:`过期`,color:`#ff7a7a`}:{text:`实时`,color:`#3ddc97`}}var P=(0,e.template)(`<div class=cq-tag><span class=cq-dot style=display:inline-block;width:6px;height:6px;border-radius:50%;margin-right:6px;vertical-align:middle>`),ee=(0,e.template)(`<span style=margin-left:6px;font-size:10px;opacity:0.8>`),te=(0,e.template)(`<div style="padding:10px 12px;border-radius:9px;font-size:12px;line-height:1.6;margin-bottom:8px"><div style=font-weight:700></div><div></div><div style=font-size:10.5px;opacity:0.72>`),ne=(0,e.template)(`<div style=min-width:340px><div style=display:flex;gap:4px;margin-bottom:10px></div><div style=display:flex;align-items:center;gap:6px;font-size:10px;margin-bottom:12px><span class=cq-dot style=width:6px;height:6px;border-radius:50%>`),re=(0,e.template)(`<div style=margin-bottom:12px>`),ie=(0,e.template)(`<div style="padding:12px;border-radius:10px;background:color-mix(in oklab, currentColor 5%, transparent);border:1px dashed color-mix(in oklab, currentColor 24%, transparent);font-size:12px;line-height:1.6;text-align:center"><div style="color:var(--sub, #aab3c6);margin-bottom:10px"><b style=color:#ffb84d>未登录</b>或认证已过期</div><div style=font-size:10px;opacity:0.6;margin-top:10px>打开浏览器授权,插件自行轮询获取凭据;无需安装 CodeBuddy CLI。`),ae=(0,e.template)(`<div style=display:flex;align-items:baseline;justify-content:space-between;margin-bottom:2px><span style=font-size:12px;opacity:0.72>本周期剩余额度</span><span class=cq-amount style=font-size:26px;font-weight:750;font-variant-numeric:tabular-nums> <small style=font-size:12px;font-weight:500;opacity:0.7>积分`),oe=(0,e.template)(`<div class=cq-track style="position:relative;height:16px;border-radius:6px;background:color-mix(in oklab, currentColor 12%, transparent);margin-top:10px"><div class=cq-fill style=position:absolute;left:0;top:0;bottom:0;border-radius:6px>`),F=(0,e.template)(`<div style=display:flex;justify-content:space-between;font-size:10.5px;opacity:0.8;margin-top:8px><span>● 已用进度 </span><span>▏时间已过 `),I=(0,e.template)(`<div class=cq-hint style="display:flex;gap:9px;align-items:flex-start;border-radius:9px;padding:10px 12px;font-size:12px;border:1px solid color-mix(in oklab, currentColor 12%, transparent);margin-top:12px"><span style=font-weight:800></span><div><div style=font-weight:700></div><div style=opacity:0.72;font-size:10.5px>积分消耗<!>时间流逝,按当前速度`),L=(0,e.template)(`<div style="margin-top:13px;border-top:1px solid rgba(255,255,255,.1);padding-top:6px"><div class=cq-row><span>已使用</span><span> 积分</span></div><div class=cq-row><span>总额度</span><span> 积分</span></div><div style=border-bottom:none><span>到期 / 重置</span><span>`),R=(0,e.template)(`<div class=cq-marker style=position:absolute;top:-3px;bottom:-3px;width:2px;background:#fff;border-radius:2px;opacity:0.9>`),z={normal:`节奏正常`,ahead:`略慢于时间`,fast:`略快于时间`,over:`超支`,unknown:`—`},B={normal:`normal`,ahead:`normal`,fast:`fast`,over:`over`,unknown:`fast`},V={normal:`#3ddc97`,fast:`#ffb84d`,over:`#ff7a7a`},H={display:`flex`,"justify-content":`space-between`,gap:`12px`,padding:`6px 0`,"font-size":`12px`,"border-bottom":`1px dashed rgba(128,128,128,.25)`},U={opacity:`0.62`},W={"font-variant-numeric":`tabular-nums`},G={cn:`国内站`,intl:`国际站`};function K(t){let r=()=>t.quota,i=()=>r().site,a=()=>r().sites,o=()=>r().status===`error`||r().remaining===null,s=()=>N(r()),[c,l]=(0,n.createSignal)(!1),[u,d]=(0,n.createSignal)(null),[f,p]=(0,n.createSignal)(Date.now()),m=setInterval(()=>p(Date.now()),1e3);(0,n.onCleanup)(()=>clearInterval(m));let h=()=>j(r().rateLimits,f(),t.currentModel),g=async e=>{if(!c()){l(!0);try{await t.onRefresh(e)}finally{l(!1)}}},_=async e=>{if(!u()){d(e);try{await t.onLogin(e)}finally{d(null)}}},v=e=>{e!==i()&&g(e)},y=t.ui.Dialog,b=t.ui.Button,x=t=>{let n=t.site===i(),r=n?{flex:`1`,border:`1px solid`,"font-size":`12px`,padding:`8px 6px`,"border-radius":`8px`,cursor:`pointer`,"font-weight":`600`}:{flex:`1`,border:`1px solid`,"border-color":`color-mix(in oklab, currentColor 22%, transparent)`,background:`color-mix(in oklab, currentColor 5%, transparent)`,color:`inherit`,"font-size":`12px`,padding:`8px 6px`,"border-radius":`8px`,cursor:`pointer`,"font-weight":`600`};return(()=>{var i=P(),a=i.firstChild;return i.$$click=()=>t.available?v(t.site):_(t.site),(0,e.setAttribute)(i,`data-active`,n?`true`:`false`),(0,e.insert)(i,()=>G[t.site],null),(0,e.insert)(i,(()=>{var n=(0,e.memo)(()=>!t.available);return()=>n()&&(()=>{var n=ee();return(0,e.insert)(n,()=>u()===t.site?`登录中…`:`· 登录`),n})()})(),null),(0,e.effect)(n=>{var o=r,s=t.available?`#3ddc97`:`#ff7a7a`;return n.e=(0,e.style)(i,o,n.e),s!==n.t&&(0,e.setStyleProperty)(a,`background`,n.t=s),n},{e:void 0,t:void 0}),i})()},S=(t,n)=>(()=>{var r=te(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return(0,e.className)(r,n?`cq-rl-alert`:`cq-rl-normal`),(0,e.setStyleProperty)(r,`border`,n?`1px dashed rgba(255,122,122,.55)`:`1px solid rgba(139,148,158,.35)`),(0,e.setStyleProperty)(r,`background`,n?`rgba(255,122,122,.10)`:`rgba(255,184,77,.08)`),(0,e.setStyleProperty)(r,`color`,n?`#ffd5d5`:`var(--sub, #aab3c6)`),(0,e.insert)(i,()=>n?`当前模型限流中 · ${t.model}`:`该站点有限流 · ${t.model}(非当前模型)`),(0,e.insert)(a,()=>M(t.unlockAt,f())),(0,e.insert)(o,()=>t.message),r})(),E=()=>(()=>{var t=ne(),n=t.firstChild,c=n.nextSibling,l=c.firstChild;return(0,e.insert)(n,()=>a().map(x)),(0,e.insert)(t,()=>{let{current:t,others:n}=h();return!t&&n.length===0?null:(()=>{var r=re();return(0,e.insert)(r,()=>t&&S(t,!0),null),(0,e.insert)(r,()=>n.map(e=>S(e,!1)),null),r})()},c),(0,e.insert)(c,()=>s().text,null),(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!o());return()=>t()?(()=>{var t=ie(),n=t.firstChild,r=n.firstChild,a=r.firstChild,o=n.nextSibling;return(0,e.insert)(r,()=>G[i()],a),(0,e.insert)(t,(0,e.createComponent)(b,{variant:`contrast`,get busy(){return u()===i()},onClick:()=>_(i()),get children(){return[`登录`,(0,e.memo)(()=>G[i()])]}}),o),t})():[(()=>{var t=ae(),n=t.firstChild.nextSibling,i=n.firstChild;return i.nextSibling,(0,e.insert)(n,()=>T(r().remaining),i),t})(),(()=>{var t=oe(),n=t.firstChild;return(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>r().timePct!==null);return()=>t()&&(()=>{var t=R();return(0,e.effect)(n=>(0,e.setStyleProperty)(t,`left`,`${k(r().timePct)}%`)),t})()})(),null),(0,e.effect)(t=>{var i=`${Math.max(0,Math.min(100,r().usedPct??0))}%`,a=C(r());return i!==t.e&&(0,e.setStyleProperty)(n,`width`,t.e=i),a!==t.t&&(0,e.setStyleProperty)(n,`color`,t.t=a),t},{e:void 0,t:void 0}),t})(),(()=>{var t=F(),n=t.firstChild;n.firstChild;var i=n.nextSibling;return i.firstChild,(0,e.insert)(n,()=>O(r().usedPct),null),(0,e.insert)(i,()=>O(r().timePct),null),t})(),(()=>{var t=I(),n=t.firstChild,i=n.nextSibling.firstChild,a=i.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,(0,e.insert)(n,()=>B[w(r())]===`normal`?`✓`:`!`),(0,e.insert)(i,()=>z[w(r())],null),(0,e.insert)(i,()=>A(r().diff),null),(0,e.insert)(a,()=>r().diff!==null&&r().diff<0?`快于`:`慢于`,o),(0,e.insert)(a,()=>r().diff!==null&&r().diff<0?`可能在周期末前用完,建议控制用量。`:`可用到周期末。`,null),(0,e.effect)(t=>{var a=V[B[w(r())]],o=V[B[w(r())]];return a!==t.e&&(0,e.setStyleProperty)(n,`color`,t.e=a),o!==t.t&&(0,e.setStyleProperty)(i,`color`,t.t=o),t},{e:void 0,t:void 0}),t})(),(()=>{var t=L(),n=t.firstChild,i=n.firstChild,a=i.nextSibling,o=a.firstChild,s=n.nextSibling,c=s.firstChild,l=c.nextSibling,u=l.firstChild,d=s.nextSibling,f=d.firstChild,p=f.nextSibling;return(0,e.insert)(a,()=>T(r().used),o),(0,e.insert)(l,()=>T(r().total),u),(0,e.insert)(p,()=>r().resetAt??`—`),(0,e.effect)(t=>{var r=H,o=U,u=W,m=H,h=U,g=W,_={...H},v=U,y=W;return t.e=(0,e.style)(n,r,t.e),t.t=(0,e.style)(i,o,t.t),t.a=(0,e.style)(a,u,t.a),t.o=(0,e.style)(s,m,t.o),t.i=(0,e.style)(c,h,t.i),t.n=(0,e.style)(l,g,t.n),t.s=(0,e.style)(d,_,t.s),t.h=(0,e.style)(f,v,t.h),t.r=(0,e.style)(p,y,t.r),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),t})()]})(),null),(0,e.effect)(t=>{var n=s().color,r=s().color;return n!==t.e&&(0,e.setStyleProperty)(c,`color`,t.e=n),r!==t.t&&(0,e.setStyleProperty)(l,`background`,t.t=r),t},{e:void 0,t:void 0}),t})();return(0,n.onMount)(()=>{g(i())}),(0,e.createComponent)(y,{get title(){return`CodeBuddy 额度 · ${G[i()]}`},size:`fit`,get footer(){return(0,e.createComponent)(b,{variant:`neutral`,get busy(){return c()},onClick:()=>g(i()),children:`刷新`})},get children(){return E()}})}(0,e.delegateEvents)([`click`]);var q=e=>Math.round(e*100)/100;function J(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:null}function Y(e){if(typeof e!=`string`)return null;let t=/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(e.trim());if(!t)return null;let[,n,r,i,a,o,s]=t.map(Number),c=new Date(n,r-1,i,a,o,s).getTime();return Number.isFinite(c)?c:null}var X=[{site:`cn`,available:!1,accounts:[],activeId:null},{site:`intl`,available:!1,accounts:[],activeId:null}];function se(e,t,n=[]){return{status:e,site:`cn`,sites:X,remaining:null,used:null,total:null,usedPct:null,timePct:null,diff:null,cycleStart:null,cycleEnd:null,resetAt:null,fetchedAt:null,ageSeconds:null,error:t,rateLimits:n}}function ce(e,t,n){if(e===null||t===null||n===null||t<=e)return null;let r=(n-e)/(t-e)*100;return q(Math.min(100,Math.max(0,r)))}function le(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;(e.site===`cn`||e.site===`intl`)&&typeof e.model==`string`&&typeof e.message==`string`&&(e.unlockAt===null||typeof e.unlockAt==`number`&&Number.isFinite(e.unlockAt))&&t.push({site:e.site,model:e.model,message:e.message,unlockAt:e.unlockAt})}return t}function Z(e,t){let n=(e,n,r)=>n&&t.fallback?{...t.fallback,status:`stale`,error:e,rateLimits:r}:se(`error`,e,r);if(typeof e!=`object`||!e)return n(typeof e==`string`?`unexpected response: ${e.slice(0,80)}`:`empty response`,!0,[]);let r=e,i=le(r.rateLimits),a=typeof r.error==`string`?r.error:null;if(r.ok!==!0)return n(a??`quota service reported no reading`,!1,i);let o=J(r.total),s=J(r.used),c=J(r.remaining);if(o===null||o<=0||s===null||c===null)return n(a??`payload is missing a usable total/used/remaining`,!0,i);let l=typeof r.cycleStart==`string`?r.cycleStart:null,u=typeof r.cycleEnd==`string`?r.cycleEnd:null,d=typeof r.resetAt==`string`?r.resetAt:null,f=typeof r.fetchedAt==`string`?r.fetchedAt:null,p=q(s/o*100),m=f?Date.parse(f):NaN,h=Number.isFinite(m)?m:null,g=ce(Y(l),Y(d)??Y(u),h),_=p!==null&&g!==null&&Number.isFinite(g)?q(g-p):null,v=r.stale===!0?`stale`:r.cached===!0?`cached`:`ok`,y=J(r.ageSeconds);return{status:v,site:r.site===`intl`?`intl`:`cn`,sites:Array.isArray(r.sites)?r.sites.filter(e=>e&&(e.site===`cn`||e.site===`intl`)&&Array.isArray(e.accounts)):X,remaining:c,used:s,total:o,usedPct:p,timePct:g,diff:_,cycleStart:l,cycleEnd:u,resetAt:d,fetchedAt:f,ageSeconds:y===null?null:Math.round(y),error:a??null,rateLimits:i}}function ue(e){if(e.total===null||e.total<=0)return null;let t=e.used;if(t===null)return e.remaining===null?null:Math.min(100,Math.max(0,Math.round(e.remaining/e.total*100)));let n=Math.round((e.total-t)/e.total*100);return Math.min(100,Math.max(0,n))}function Q(e){if(e.usedPct===null||e.used===null||e.total===null)return null;let t=100-e.usedPct;return Math.max(0,Math.round(t*100)/100)}var de=6e5,fe=6e4,pe=12e4,me=5,he=(e,t)=>({status:e,site:`cn`,sites:[{site:`cn`,available:!1,accounts:[],activeId:null},{site:`intl`,available:!1,accounts:[],activeId:null}],remaining:null,used:null,total:null,usedPct:null,timePct:null,diff:null,cycleStart:null,cycleEnd:null,resetAt:null,fetchedAt:null,ageSeconds:null,error:t,rateLimits:[]});async function ge(e){let t=e.now??Date.now(),n;try{n=await e.getClient().read(e.site?{site:e.site}:{})}catch(t){let n=String(t?.message??t);return{kind:`failed`,quota:e.fallback?{...e.fallback,status:`stale`,error:n}:{...he(`error`,n),site:e.site??`cn`}}}let r=Z(n,{now:t});return r.status===`stale`||r.status===`error`?{kind:`failed`,quota:r.status===`error`&&e.fallback&&e.fallback.remaining!==null?{...e.fallback,status:`stale`,error:r.error}:(t=>e.site&&t.remaining===null?{...t,site:e.site}:t)(r)}:{kind:`ok`,quota:r}}function $(e,t=globalThis,n=Date.now){let r=Z(null,{now:n()}),i=de,a=null,o=!1,s=0,c=0,l=null,u={tries:0,timer:null,cancelled:!1},d=new Set,f=e=>{r=e;for(let t of d)t(e)};function p(){t.clearTimeout(u.timer),u.timer=null,u.tries=0,s=n()}function m(e){e.kind===`ok`?p():h(),u.cancelled||f(e.quota)}function h(){if(u.cancelled||!o||u.timer!==null)return;if(u.tries>=me){u.tries=0;return}let e=5e3*2**u.tries;u.tries++,u.timer=t.setTimeout(()=>{u.timer=null,u.cancelled||g()},e)}async function g(t){if(l){if(l.site!==t)return await l.promise,g(t);let e=await l.promise;return e.kind===`ok`&&p(),e}let i=r.remaining!==null&&(t===void 0||r.site===t)?r:null,a={site:t,promise:Promise.resolve()};a.promise=ge({getClient:e,fallback:i,now:n(),site:t}),l=a;try{let e=await a.promise;return m(e),e}finally{l=null}}let _=async(e={})=>{!e.force&&(u.timer!==null||n()-s<(e.maxAgeMs??i))||(c=n(),await g(e.site))},v=globalThis.document!==void 0,y=()=>{v&&globalThis.document.hidden||_()},b=()=>{globalThis.document.hidden||n()-c>=pe&&_()};return{read:()=>r,subscribe(e){return d.add(e),()=>d.delete(e)},refresh:_,async login(t){try{let n=e().login;if(!n)return!1;let r=(await n({site:t}))?.ok===!0;return r&&await _({force:!0,site:t}),r}catch{return!1}},start:()=>o?()=>{}:(o=!0,u.cancelled=!1,a=t.setInterval(y,i),v&&globalThis.document.addEventListener(`visibilitychange`,b),_({force:!0}),()=>{u.cancelled=!0,t.clearTimeout(u.timer),t.clearInterval(a),v&&globalThis.document.removeEventListener(`visibilitychange`,b),o=!1}),setRefreshMs:e=>{i=e,o&&(t.clearInterval(a),a=t.setInterval(y,i))}}}var _e=`.cq-tag{--cq-accent:#5b8cff;transition:box-shadow .18s,border-color .18s,background .18s,transform .18s;position:relative;overflow:hidden}.cq-tag:after{content:"";background:linear-gradient(105deg, transparent 30%, color-mix(in srgb, var(--cq-accent) 22%, transparent) 50%, transparent 70%);pointer-events:none;position:absolute;inset:0;transform:translate(-120%)}.cq-tag:hover:after{animation:.7s ease-out cq-sheen}.cq-tag[data-active=true]{background:color-mix(in srgb, var(--cq-accent) 14%, transparent);border-color:color-mix(in srgb, var(--cq-accent) 55%, transparent);color:color-mix(in srgb, var(--cq-accent) 85%, white);box-shadow:0 0 0 1px color-mix(in srgb, var(--cq-accent) 28%, transparent), 0 0 14px -2px color-mix(in srgb, var(--cq-accent) 50%, transparent)}.cq-tag:active{transform:scale(.97)}@keyframes cq-sheen{0%{transform:translate(-120%)}to{transform:translate(120%)}}.cq-dot{box-shadow:0 0 0 3px color-mix(in oklab, currentColor 14%, transparent)}.cq-amount{font-variant-numeric:tabular-nums;text-shadow:0 0 20px color-mix(in oklab, currentColor 22%, transparent)}.cq-track{overflow:hidden;box-shadow:inset 0 1px 3px #0000002e}.cq-fill{background:linear-gradient(100deg, color-mix(in oklab, currentColor 62%, transparent) 0%, currentColor 35%, color-mix(in oklab, white 45%, currentColor) 50%, currentColor 65%, color-mix(in oklab, currentColor 62%, transparent) 100%);box-shadow:0 0 10px -2px color-mix(in oklab, currentColor 65%, transparent);background-size:220% 100%;transition:width .3s cubic-bezier(.22,.8,.3,1),background .3s ease-out;animation:2.6s linear infinite cq-flow}@keyframes cq-flow{0%{background-position:120% 0}to{background-position:-120% 0}}.cq-marker{box-shadow:0 0 6px #ffffffbf}.cq-hint{background:color-mix(in oklab, currentColor 6%, transparent);box-shadow:inset 0 1px 0 color-mix(in oklab, currentColor 12%, transparent)}.cq-rl-alert{box-shadow:inset 0 1px oklab(73.4642% .150948 .0605703/.18)}.cq-rl-normal{box-shadow:inset 0 1px 0 color-mix(in oklab, currentColor 8%, transparent)}.cq-row{border-bottom:1px solid color-mix(in oklab, currentColor 14%, transparent)}@media (prefers-reduced-motion:reduce){.cq-tag,.cq-fill{transition:none;animation:none}.cq-tag:after{display:none}}`,ve=(0,e.template)(`<button type=button style="position:relative;background:transparent;border:none;padding:2px 6px 2px 0;margin-left:auto;cursor:pointer;line-height:0">`),ye=(0,e.template)(`<span style="position:absolute;top:0;right:0;width:9px;height:9px;border-radius:50%;background:#ffb84d;border:1.5px solid transparent">`),be=t.Plugin.define({setup(r){r.add(t.Style,_e);let i=$(()=>r.client.rpc(c)),[a,o]=(0,n.createSignal)(i.read());(0,n.onCleanup)(i.subscribe(o)),(0,n.onCleanup)(i.start()),r.client.rpc(c).config({}).then(e=>{let{refreshMinutes:t}=e;typeof t==`number`&&Number.isInteger(t)&&t>=1&&t<=30&&i.setRefreshMs(t*6e4)}).catch(()=>{});let s=()=>{r.dialogs.open(t=>(0,e.createComponent)(()=>{let[a,o]=(0,n.createSignal)(i.read());return(0,n.onCleanup)(i.subscribe(o)),(0,e.createComponent)(K,{get quota(){return a()},get ui(){return r.ui},get currentModel(){return r.screen.current()?.composer.model()?.modelID},onRefresh:e=>i.refresh({force:!0,site:e}),onLogin:e=>i.login(e),get close(){return t.close}})},{}))},l=()=>{i.refresh({maxAgeMs:fe,site:i.read().site})},u={cn:`国内站`,intl:`国际站`},d=()=>a().sites.some(e=>!e.available);r.add(t.Slot,{at:`session.header`,order:50,render:()=>(()=>{var t=ve();return t.$$click=s,t.addEventListener(`focus`,l),t.addEventListener(`mouseenter`,l),(0,e.insert)(t,(0,e.createComponent)(m,{get value(){return ue(a())},get color(){return C(a())},get dim(){return a().status===`stale`}}),null),(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!d());return()=>t()&&ye()})(),null),(0,e.effect)(()=>(0,e.setAttribute)(t,`title`,Q(a())===null?`CodeBuddy 额度 · ${u[a().site]}:暂不可用(点击查看/登录)`:`CodeBuddy 额度 · ${u[a().site]}:剩余 ${E(Q(a()))}`)),t})()})}});(0,e.delegateEvents)([`click`]),exports.default=be;
|
package/package.json
CHANGED
package/rpc.ts
CHANGED
|
@@ -68,6 +68,21 @@ export const CodebuddyQuota = Rpc.define({
|
|
|
68
68
|
// Which site these numbers belong to, and both sites' availability.
|
|
69
69
|
site: siteEnum,
|
|
70
70
|
sites: { type: "array", items: siteInfoSchema },
|
|
71
|
+
// Active model-level rate limits for this site (empty when none).
|
|
72
|
+
rateLimits: {
|
|
73
|
+
type: "array",
|
|
74
|
+
items: {
|
|
75
|
+
type: "object",
|
|
76
|
+
properties: {
|
|
77
|
+
site: siteEnum,
|
|
78
|
+
model: { type: "string" },
|
|
79
|
+
message: { type: "string" },
|
|
80
|
+
unlockAt: nullableNumber,
|
|
81
|
+
},
|
|
82
|
+
required: ["site", "model", "message", "unlockAt"],
|
|
83
|
+
additionalProperties: false,
|
|
84
|
+
},
|
|
85
|
+
},
|
|
71
86
|
},
|
|
72
87
|
required: ["ok", "stale", "cached", "site", "sites"],
|
|
73
88
|
additionalProperties: false,
|
|
@@ -87,6 +102,15 @@ export const CodebuddyQuota = Rpc.define({
|
|
|
87
102
|
additionalProperties: false,
|
|
88
103
|
},
|
|
89
104
|
},
|
|
105
|
+
config: {
|
|
106
|
+
input: { type: "object", additionalProperties: false },
|
|
107
|
+
output: {
|
|
108
|
+
type: "object",
|
|
109
|
+
properties: { refreshMinutes: { type: "number" } },
|
|
110
|
+
required: ["refreshMinutes"],
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
},
|
|
113
|
+
},
|
|
90
114
|
},
|
|
91
115
|
events: {},
|
|
92
116
|
})
|
package/server.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { clearLocalEmbedderMemo, createLocalEmbedder, type LocalEmbedding } from
|
|
|
9
9
|
import { resolveEmbeddingMode } from "./src/server/embedding-mode"
|
|
10
10
|
import { setupGateway } from "./src/server/gateway-setup"
|
|
11
11
|
import { ensureGateway, releaseGateway } from "./src/server/gateway-owner"
|
|
12
|
+
import { registerThenGateway } from "./src/server/setup-order"
|
|
12
13
|
import type { SiteAuth } from "./src/server/login"
|
|
13
14
|
import { createDedupedLogger } from "./src/server/logger"
|
|
14
15
|
import { buildModels } from "./src/server/model-info"
|
|
@@ -19,6 +20,7 @@ import type { ModelsDevCatalog } from "./src/server/pricing"
|
|
|
19
20
|
import { latestTaggedVersion } from "./src/server/package-version"
|
|
20
21
|
import { createProxy } from "./src/server/proxy"
|
|
21
22
|
import { createQuotaSource } from "./src/server/quota-source"
|
|
23
|
+
import { createRateLimitStore } from "./src/server/rate-limit-store"
|
|
22
24
|
import { makeRpcHandlers } from "./src/server/rpc-handlers"
|
|
23
25
|
import { anySignal, timeoutSignal } from "./src/server/signal"
|
|
24
26
|
import { createTokenStore } from "./src/server/token-store"
|
|
@@ -124,6 +126,8 @@ export default Plugin.define({
|
|
|
124
126
|
// Restore both sites' credentials from the plugin-owned cache; no CLI auth
|
|
125
127
|
// file is read, and no token ever reaches the GUI.
|
|
126
128
|
const store = createTokenStore()
|
|
129
|
+
// One shared store: the proxy records 429s and the read handler exposes them.
|
|
130
|
+
const rateLimitStore = createRateLimitStore()
|
|
127
131
|
|
|
128
132
|
const source = createQuotaSource({
|
|
129
133
|
readForSite: (site, signal) => {
|
|
@@ -227,6 +231,8 @@ export default Plugin.define({
|
|
|
227
231
|
store,
|
|
228
232
|
source,
|
|
229
233
|
log,
|
|
234
|
+
refreshMinutes: config.refresh_minutes,
|
|
235
|
+
rateLimitStore,
|
|
230
236
|
afterLogin: async (site) => importSite(site, await importDeps()),
|
|
231
237
|
})
|
|
232
238
|
// Local reverse proxy: providers point here; the proxy injects the current
|
|
@@ -235,25 +241,25 @@ export default Plugin.define({
|
|
|
235
241
|
// listen gap. Port conflicts are logged by the owner and stay non-fatal.
|
|
236
242
|
// The proxy's lazy fallback must target the configured id too, otherwise a
|
|
237
243
|
// request would build a different model from the one prewarm verified.
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
244
|
+
const { registration, gw } = await registerThenGateway({
|
|
245
|
+
register: () => ctx.rpc.register(CodebuddyQuota, handlers),
|
|
246
|
+
setupGateway: (deps) =>
|
|
247
|
+
setupGateway({
|
|
248
|
+
ensureGateway,
|
|
249
|
+
releaseGateway,
|
|
250
|
+
createServer: () =>
|
|
251
|
+
createProxy({
|
|
252
|
+
store, log, models, embeddingMode,
|
|
253
|
+
rateLimitStore,
|
|
254
|
+
localEmbeddingModel: config.local_embedding_model,
|
|
255
|
+
}),
|
|
256
|
+
...deps,
|
|
257
|
+
log,
|
|
246
258
|
}),
|
|
247
|
-
register: async () => {
|
|
248
|
-
const result = await ctx.rpc.register(CodebuddyQuota, handlers)
|
|
249
|
-
registration = result
|
|
250
|
-
return result
|
|
251
|
-
},
|
|
252
|
-
log,
|
|
253
259
|
})
|
|
254
260
|
|
|
255
261
|
return () => {
|
|
256
|
-
registration
|
|
262
|
+
void registration.dispose()
|
|
257
263
|
// Only drop our reference; the owner closes the shared server after the
|
|
258
264
|
// last holder is gone and its grace window has elapsed.
|
|
259
265
|
void gw.dispose()
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RateLimitInfo } from "../shared"
|
|
1
2
|
import { signedPp } from "./pace"
|
|
2
3
|
import type { Quota } from "./quota"
|
|
3
4
|
|
|
@@ -20,6 +21,38 @@ export const paceHint = (diff: number | null): string => {
|
|
|
20
21
|
return ` · ${dir}时间 ${signedPp(Math.abs(diff))}`
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Split the active limits for one site into the current model's card (if the
|
|
26
|
+
* selected model is limited) and the rest. Expired entries are dropped here so
|
|
27
|
+
* the ticking clock hides them; a `null` unlock time stays until a successful
|
|
28
|
+
* request clears it server-side. Both `current` and `others` are disjoint.
|
|
29
|
+
*/
|
|
30
|
+
export function activeRateLimits(
|
|
31
|
+
rateLimits: RateLimitInfo[],
|
|
32
|
+
now: number,
|
|
33
|
+
currentModel: string | undefined,
|
|
34
|
+
): { current: RateLimitInfo | undefined; others: RateLimitInfo[] } {
|
|
35
|
+
const active = rateLimits
|
|
36
|
+
.filter((r) => r.unlockAt === null || r.unlockAt > now)
|
|
37
|
+
.sort((a, b) => (a.unlockAt ?? Infinity) - (b.unlockAt ?? Infinity))
|
|
38
|
+
const current = currentModel ? active.find((r) => r.model === currentModel) : undefined
|
|
39
|
+
const others = active.filter((r) => r.model !== currentModel)
|
|
40
|
+
return { current, others }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Countdown copy matching the mockup; null unlock time uses the fallback text. */
|
|
44
|
+
export function countdown(unlockAt: number | null, now: number): string {
|
|
45
|
+
if (unlockAt === null) return "解除时间未知,请稍后重试(成功请求后自动消失)"
|
|
46
|
+
const total = Math.max(0, Math.ceil((unlockAt - now) / 1000))
|
|
47
|
+
const min = Math.floor(total / 60)
|
|
48
|
+
const sec = total % 60
|
|
49
|
+
const body = min > 0 ? `${min} 分 ${sec} 秒` : `${sec} 秒`
|
|
50
|
+
const hh = new Date(unlockAt).getHours()
|
|
51
|
+
const mm = new Date(unlockAt).getMinutes()
|
|
52
|
+
const at = `${String(hh).padStart(2, "0")}:${String(mm).padStart(2, "0")}`
|
|
53
|
+
return `约 ${body}后解除(${at} 解除)`
|
|
54
|
+
}
|
|
55
|
+
|
|
23
56
|
export function freshness(q: Quota): { text: string; color: string } {
|
|
24
57
|
if (q.status === "error") return { text: "不可用", color: "#ff7a7a" }
|
|
25
58
|
if (q.status === "cached") {
|
package/src/gui/dialog.css
CHANGED
|
@@ -72,6 +72,14 @@
|
|
|
72
72
|
box-shadow: inset 0 1px 0 color-mix(in oklab, currentColor 12%, transparent);
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/* Rate-limit notices — the current model's card is a red alert, others are calm. */
|
|
76
|
+
.cq-rl-alert {
|
|
77
|
+
box-shadow: inset 0 1px 0 color-mix(in oklab, #ff7a7a 18%, transparent);
|
|
78
|
+
}
|
|
79
|
+
.cq-rl-normal {
|
|
80
|
+
box-shadow: inset 0 1px 0 color-mix(in oklab, currentColor 8%, transparent);
|
|
81
|
+
}
|
|
82
|
+
|
|
75
83
|
/* Detail rows — soften the separators, keep numbers crisp. */
|
|
76
84
|
.cq-row {
|
|
77
85
|
border-bottom: 1px solid color-mix(in oklab, currentColor 14%, transparent);
|
package/src/gui/dialog.tsx
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import type { JSX } from "solid-js"
|
|
2
|
-
import { createSignal, onMount } from "solid-js"
|
|
2
|
+
import { createSignal, onCleanup, onMount } from "solid-js"
|
|
3
3
|
import type { Ui } from "@opencode/plugin/gui"
|
|
4
|
-
import type { Site, SiteInfo } from "../shared"
|
|
4
|
+
import type { RateLimitInfo, Site, SiteInfo } from "../shared"
|
|
5
5
|
import { formatCredits, paceColor, paceLabel, type PaceLabel } from "./pace"
|
|
6
6
|
import type { Quota } from "./quota"
|
|
7
|
-
import { freshness, paceHint, pctInt, timeMarkerLeft } from "./dialog-helpers"
|
|
7
|
+
import { activeRateLimits, countdown, freshness, paceHint, pctInt, timeMarkerLeft } from "./dialog-helpers"
|
|
8
8
|
|
|
9
9
|
export interface QuotaDialogProps {
|
|
10
10
|
quota: Quota
|
|
11
11
|
onRefresh: (site?: Site) => Promise<void>
|
|
12
12
|
onLogin: (site: Site) => Promise<boolean>
|
|
13
13
|
close: () => void
|
|
14
|
+
/** The model selected in the composer, used to pin the current model's limit card. */
|
|
15
|
+
currentModel?: string
|
|
14
16
|
/** Only the two host components the dialog draws with. */
|
|
15
17
|
ui: Pick<Ui, "Dialog" | "Button">
|
|
16
18
|
}
|
|
@@ -58,6 +60,11 @@ export function QuotaDialog(props: QuotaDialogProps): JSX.Element {
|
|
|
58
60
|
const fresh = () => freshness(q())
|
|
59
61
|
const [busy, setBusy] = createSignal(false)
|
|
60
62
|
const [logging, setLogging] = createSignal<Site | null>(null)
|
|
63
|
+
// Ticks once a second so countdowns advance and expired cards disappear on time.
|
|
64
|
+
const [nowMs, setNowMs] = createSignal(Date.now())
|
|
65
|
+
const timer = setInterval(() => setNowMs(Date.now()), 1000)
|
|
66
|
+
onCleanup(() => clearInterval(timer))
|
|
67
|
+
const active = () => activeRateLimits(q().rateLimits, nowMs(), props.currentModel)
|
|
61
68
|
|
|
62
69
|
const refresh = async (s?: Site) => {
|
|
63
70
|
if (busy()) return
|
|
@@ -132,11 +139,40 @@ export function QuotaDialog(props: QuotaDialogProps): JSX.Element {
|
|
|
132
139
|
)
|
|
133
140
|
}
|
|
134
141
|
|
|
142
|
+
const rateCard = (r: RateLimitInfo, isCurrent: boolean): JSX.Element => (
|
|
143
|
+
<div
|
|
144
|
+
class={isCurrent ? "cq-rl-alert" : "cq-rl-normal"}
|
|
145
|
+
style={{
|
|
146
|
+
padding: "10px 12px", "border-radius": "9px", "font-size": "12px",
|
|
147
|
+
"line-height": "1.6", "margin-bottom": "8px",
|
|
148
|
+
border: isCurrent ? "1px dashed rgba(255,122,122,.55)" : "1px solid rgba(139,148,158,.35)",
|
|
149
|
+
background: isCurrent ? "rgba(255,122,122,.10)" : "rgba(255,184,77,.08)",
|
|
150
|
+
color: isCurrent ? "#ffd5d5" : "var(--sub, #aab3c6)",
|
|
151
|
+
}}
|
|
152
|
+
>
|
|
153
|
+
<div style={{ "font-weight": "700" }}>
|
|
154
|
+
{isCurrent ? `当前模型限流中 · ${r.model}` : `该站点有限流 · ${r.model}(非当前模型)`}
|
|
155
|
+
</div>
|
|
156
|
+
<div>{countdown(r.unlockAt, nowMs())}</div>
|
|
157
|
+
<div style={{ "font-size": "10.5px", opacity: "0.72" }}>{r.message}</div>
|
|
158
|
+
</div>
|
|
159
|
+
)
|
|
160
|
+
|
|
135
161
|
const body = () => (
|
|
136
162
|
<div style={{ "min-width": "340px" }}>
|
|
137
163
|
<div style={{ display: "flex", gap: "4px", "margin-bottom": "10px" }}>
|
|
138
164
|
{sites().map(tag)}
|
|
139
165
|
</div>
|
|
166
|
+
{(() => {
|
|
167
|
+
const { current, others } = active()
|
|
168
|
+
if (!current && others.length === 0) return null
|
|
169
|
+
return (
|
|
170
|
+
<div style={{ "margin-bottom": "12px" }}>
|
|
171
|
+
{current && rateCard(current, true)}
|
|
172
|
+
{others.map((r) => rateCard(r, false))}
|
|
173
|
+
</div>
|
|
174
|
+
)
|
|
175
|
+
})()}
|
|
140
176
|
<div style={{ display: "flex", "align-items": "center", gap: "6px", "font-size": "10px",
|
|
141
177
|
color: fresh().color, "margin-bottom": "12px" }}>
|
|
142
178
|
<span class="cq-dot" style={{ width: "6px", height: "6px", "border-radius": "50%", background: fresh().color }} />
|
package/src/gui/quota.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Site, SiteInfo } from "../shared"
|
|
1
|
+
import type { RateLimitInfo, Site, SiteInfo } from "../shared"
|
|
2
2
|
|
|
3
3
|
export type QuotaStatus = "ok" | "cached" | "stale" | "error"
|
|
4
4
|
|
|
@@ -19,6 +19,8 @@ export interface Quota {
|
|
|
19
19
|
/** Age of the numbers in whole seconds, as the server counted it. */
|
|
20
20
|
ageSeconds: number | null
|
|
21
21
|
error: string | null
|
|
22
|
+
/** Active model-level limits for the current site. */
|
|
23
|
+
rateLimits: RateLimitInfo[]
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
export interface NormalizeContext {
|
|
@@ -52,7 +54,7 @@ const DEFAULT_SITES: SiteInfo[] = [
|
|
|
52
54
|
{ site: "intl", available: false, accounts: [], activeId: null },
|
|
53
55
|
]
|
|
54
56
|
|
|
55
|
-
function empty(status: QuotaStatus, error: string | null): Quota {
|
|
57
|
+
function empty(status: QuotaStatus, error: string | null, rateLimits: RateLimitInfo[] = []): Quota {
|
|
56
58
|
return {
|
|
57
59
|
status,
|
|
58
60
|
site: "cn",
|
|
@@ -69,6 +71,7 @@ function empty(status: QuotaStatus, error: string | null): Quota {
|
|
|
69
71
|
fetchedAt: null,
|
|
70
72
|
ageSeconds: null,
|
|
71
73
|
error,
|
|
74
|
+
rateLimits,
|
|
72
75
|
}
|
|
73
76
|
}
|
|
74
77
|
|
|
@@ -86,6 +89,26 @@ function timeProgress(
|
|
|
86
89
|
return round2(Math.min(100, Math.max(0, pct)))
|
|
87
90
|
}
|
|
88
91
|
|
|
92
|
+
/** Keep only well-formed rate-limit notices from the wire. */
|
|
93
|
+
function readRateLimits(value: unknown): RateLimitInfo[] {
|
|
94
|
+
if (!Array.isArray(value)) return []
|
|
95
|
+
const out: RateLimitInfo[] = []
|
|
96
|
+
for (const item of value) {
|
|
97
|
+
if (!item || typeof item !== "object") continue
|
|
98
|
+
const r = item as Record<string, unknown>
|
|
99
|
+
if (r.site !== "cn" && r.site !== "intl") continue
|
|
100
|
+
if (typeof r.model !== "string" || typeof r.message !== "string") continue
|
|
101
|
+
if (r.unlockAt !== null && (typeof r.unlockAt !== "number" || !Number.isFinite(r.unlockAt))) continue
|
|
102
|
+
out.push({
|
|
103
|
+
site: r.site,
|
|
104
|
+
model: r.model,
|
|
105
|
+
message: r.message,
|
|
106
|
+
unlockAt: r.unlockAt as number | null,
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
return out
|
|
110
|
+
}
|
|
111
|
+
|
|
89
112
|
export function normalizeQuota(payload: unknown, ctx: NormalizeContext): Quota {
|
|
90
113
|
/**
|
|
91
114
|
* `keepFallback` separates two different failures:
|
|
@@ -93,9 +116,14 @@ export function normalizeQuota(payload: unknown, ctx: NormalizeContext): Quota {
|
|
|
93
116
|
* must not be dressed up as merely stale, so the fallback is dropped;
|
|
94
117
|
* - the answer arrived but is unusable — the numbers are bad, not the line,
|
|
95
118
|
* so the last good reading still describes the quota.
|
|
119
|
+
*
|
|
120
|
+
* `rateLimits` is an explicit argument (not a closure read) so the early
|
|
121
|
+
* return below cannot hit a temporal dead zone.
|
|
96
122
|
*/
|
|
97
|
-
const unusable = (error: string, keepFallback: boolean): Quota =>
|
|
98
|
-
keepFallback && ctx.fallback
|
|
123
|
+
const unusable = (error: string, keepFallback: boolean, rateLimits: RateLimitInfo[]): Quota =>
|
|
124
|
+
keepFallback && ctx.fallback
|
|
125
|
+
? { ...ctx.fallback, status: "stale", error, rateLimits }
|
|
126
|
+
: empty("error", error, rateLimits)
|
|
99
127
|
|
|
100
128
|
if (typeof payload !== "object" || payload === null) {
|
|
101
129
|
return unusable(
|
|
@@ -103,19 +131,21 @@ export function normalizeQuota(payload: unknown, ctx: NormalizeContext): Quota {
|
|
|
103
131
|
? `unexpected response: ${payload.slice(0, 80)}`
|
|
104
132
|
: "empty response",
|
|
105
133
|
true,
|
|
134
|
+
[],
|
|
106
135
|
)
|
|
107
136
|
}
|
|
108
137
|
|
|
109
138
|
const data = payload as Record<string, unknown>
|
|
139
|
+
const rateLimits = readRateLimits(data.rateLimits)
|
|
110
140
|
const error = typeof data.error === "string" ? data.error : null
|
|
111
141
|
|
|
112
|
-
if (data.ok !== true) return unusable(error ?? "quota service reported no reading", false)
|
|
142
|
+
if (data.ok !== true) return unusable(error ?? "quota service reported no reading", false, rateLimits)
|
|
113
143
|
|
|
114
144
|
const total = num(data.total)
|
|
115
145
|
const used = num(data.used)
|
|
116
146
|
const remaining = num(data.remaining)
|
|
117
147
|
if (total === null || total <= 0 || used === null || remaining === null) {
|
|
118
|
-
return unusable(error ?? "payload is missing a usable total/used/remaining", true)
|
|
148
|
+
return unusable(error ?? "payload is missing a usable total/used/remaining", true, rateLimits)
|
|
119
149
|
}
|
|
120
150
|
|
|
121
151
|
const cycleStart = typeof data.cycleStart === "string" ? data.cycleStart : null
|
|
@@ -169,6 +199,7 @@ export function normalizeQuota(payload: unknown, ctx: NormalizeContext): Quota {
|
|
|
169
199
|
fetchedAt,
|
|
170
200
|
ageSeconds: ageSeconds === null ? null : Math.round(ageSeconds),
|
|
171
201
|
error: error ?? null,
|
|
202
|
+
rateLimits,
|
|
172
203
|
}
|
|
173
204
|
}
|
|
174
205
|
|
package/src/gui/store.ts
CHANGED
|
@@ -7,19 +7,31 @@ export interface QuotaClient {
|
|
|
7
7
|
login?(input: { site: Site }): Promise<unknown>
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
/** Injectable clock/timers so the backoff state machine can be tested deterministically. */
|
|
11
|
+
export interface Timers {
|
|
12
|
+
setInterval(fn: () => void, ms: number): unknown
|
|
13
|
+
clearInterval(id: unknown): void
|
|
14
|
+
setTimeout(fn: () => void, ms: number): unknown
|
|
15
|
+
clearTimeout(id: unknown): void
|
|
16
|
+
}
|
|
17
|
+
|
|
10
18
|
export interface QuotaStore {
|
|
11
19
|
read(): Quota
|
|
12
20
|
subscribe(listener: (q: Quota) => void): () => void
|
|
13
21
|
refresh(options?: { force?: boolean; maxAgeMs?: number; site?: Site }): Promise<void>
|
|
14
22
|
login(site: Site): Promise<boolean>
|
|
15
23
|
start(): () => void
|
|
24
|
+
setRefreshMs(ms: number): void
|
|
16
25
|
}
|
|
17
26
|
|
|
27
|
+
export type ReadOutcome = { kind: "ok"; quota: Quota } | { kind: "failed"; quota: Quota }
|
|
28
|
+
|
|
18
29
|
/** Background safety net only; the capsule refreshes on hover and the dialog on open. */
|
|
19
|
-
const
|
|
30
|
+
export const DEFAULT_REFRESH_MS = 10 * 60_000
|
|
20
31
|
/** Hover refreshes only when the reading is older than this, so mouse traffic cannot spam. */
|
|
21
32
|
export const HOVER_MIN_AGE_MS = 60_000
|
|
22
33
|
const STALE_AFTER_RESUME_MS = 2 * 60_000
|
|
34
|
+
const MAX_RETRIES = 5
|
|
23
35
|
|
|
24
36
|
const idle = (status: "error", error: string | null): Quota => ({
|
|
25
37
|
status,
|
|
@@ -40,44 +52,65 @@ const idle = (status: "error", error: string | null): Quota => ({
|
|
|
40
52
|
fetchedAt: null,
|
|
41
53
|
ageSeconds: null,
|
|
42
54
|
error,
|
|
55
|
+
rateLimits: [],
|
|
43
56
|
})
|
|
44
57
|
|
|
45
58
|
/**
|
|
46
|
-
* One read of the quota over the plugin RPC.
|
|
59
|
+
* One read of the quota over the plugin RPC. `getClient` is a function because
|
|
60
|
+
* the client changes when the server restarts and can itself throw — evaluating
|
|
61
|
+
* it inside the try keeps that failure in the outcome instead of escaping.
|
|
47
62
|
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* probably fine; `ok: false` is the server saying it has nothing, so the old
|
|
52
|
-
* numbers are dropped rather than dressed up as merely stale.
|
|
63
|
+
* `ok:false` normally drops the fallback (quota.ts), but here the previous
|
|
64
|
+
* numbers are deliberately restored when available: during GUI retries the user
|
|
65
|
+
* should keep seeing the numbers already on screen rather than `--`.
|
|
53
66
|
*/
|
|
54
67
|
export async function readQuota(opts: {
|
|
55
|
-
|
|
68
|
+
getClient: () => QuotaClient
|
|
56
69
|
fallback?: Quota | null
|
|
57
70
|
now?: number
|
|
58
71
|
site?: Site
|
|
59
|
-
}): Promise<
|
|
72
|
+
}): Promise<ReadOutcome> {
|
|
60
73
|
const now = opts.now ?? Date.now()
|
|
61
74
|
let body: unknown
|
|
62
75
|
try {
|
|
63
|
-
body = await opts.
|
|
76
|
+
body = await opts.getClient().read(opts.site ? { site: opts.site } : {})
|
|
64
77
|
} catch (error) {
|
|
65
78
|
const message = String((error as Error)?.message ?? error)
|
|
66
|
-
|
|
67
|
-
? { ...opts.fallback, status: "stale", error: message }
|
|
68
|
-
: idle("error", message)
|
|
79
|
+
const quota = opts.fallback
|
|
80
|
+
? { ...opts.fallback, status: "stale" as const, error: message }
|
|
81
|
+
: { ...idle("error", message), site: opts.site ?? "cn" }
|
|
82
|
+
return { kind: "failed", quota }
|
|
83
|
+
}
|
|
84
|
+
const normalized = normalizeQuota(body, { now })
|
|
85
|
+
// normalizeQuota's empty() hardcodes site "cn"; on a failed read there is no
|
|
86
|
+
// payload to carry the site, so keep the site the user actually requested.
|
|
87
|
+
const withSite = (q: Quota): Quota =>
|
|
88
|
+
opts.site && q.remaining === null ? { ...q, site: opts.site } : q
|
|
89
|
+
if (normalized.status === "stale" || normalized.status === "error") {
|
|
90
|
+
// Restore the fallback only for the explicit `ok:false` case (payload said
|
|
91
|
+
// unavailable). A stale reading already carries the numbers we want.
|
|
92
|
+
const quota =
|
|
93
|
+
normalized.status === "error" && opts.fallback && opts.fallback.remaining !== null
|
|
94
|
+
? { ...opts.fallback, status: "stale" as const, error: normalized.error }
|
|
95
|
+
: withSite(normalized)
|
|
96
|
+
return { kind: "failed", quota }
|
|
69
97
|
}
|
|
70
|
-
|
|
71
|
-
// the fallback is deliberately not offered here.
|
|
72
|
-
return normalizeQuota(body, { now })
|
|
98
|
+
return { kind: "ok", quota: normalized }
|
|
73
99
|
}
|
|
74
100
|
|
|
75
|
-
export function createQuotaStore(
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
101
|
+
export function createQuotaStore(
|
|
102
|
+
client: () => QuotaClient,
|
|
103
|
+
timers: Timers = globalThis,
|
|
104
|
+
now: () => number = Date.now,
|
|
105
|
+
): QuotaStore {
|
|
106
|
+
let current: Quota = normalizeQuota(null, { now: now() })
|
|
107
|
+
let refreshMs = DEFAULT_REFRESH_MS
|
|
108
|
+
let timerId: unknown = null
|
|
80
109
|
let started = false
|
|
110
|
+
let lastSuccessAt = 0
|
|
111
|
+
let lastAttempt = 0
|
|
112
|
+
let inflight: { site?: Site; promise: Promise<ReadOutcome> } | null = null
|
|
113
|
+
const retry = { tries: 0, timer: null as unknown | null, cancelled: false }
|
|
81
114
|
const listeners = new Set<(q: Quota) => void>()
|
|
82
115
|
|
|
83
116
|
const emit = (next: Quota) => {
|
|
@@ -85,78 +118,114 @@ export function createQuotaStore(client: () => QuotaClient): QuotaStore {
|
|
|
85
118
|
for (const listener of listeners) listener(next)
|
|
86
119
|
}
|
|
87
120
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
121
|
+
function clearRetry() {
|
|
122
|
+
timers.clearTimeout(retry.timer)
|
|
123
|
+
retry.timer = null
|
|
124
|
+
retry.tries = 0
|
|
125
|
+
lastSuccessAt = now()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function onOutcome(o: ReadOutcome) {
|
|
129
|
+
if (o.kind === "ok") clearRetry()
|
|
130
|
+
else scheduleRetry()
|
|
131
|
+
// Emit unless explicitly cleaned up. Unit callers refresh() without start(),
|
|
132
|
+
// and gating emission on `started` froze their reading at the initial value.
|
|
133
|
+
if (!retry.cancelled) emit(o.quota)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function scheduleRetry() {
|
|
137
|
+
// start() is the only entry to background scheduling: an unstarted store
|
|
138
|
+
// must not leave pending timers behind (e.g. failed tests).
|
|
139
|
+
if (retry.cancelled || !started) return
|
|
140
|
+
if (retry.timer !== null) return
|
|
141
|
+
if (retry.tries >= MAX_RETRIES) {
|
|
142
|
+
retry.tries = 0
|
|
143
|
+
return
|
|
102
144
|
}
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
145
|
+
const delay = 5_000 * 2 ** retry.tries
|
|
146
|
+
retry.tries++
|
|
147
|
+
retry.timer = timers.setTimeout(() => {
|
|
148
|
+
retry.timer = null
|
|
149
|
+
// A hover may slip into runOnce() as a reuser while this window is open;
|
|
150
|
+
// that is harmless — reusers never start a new request or advance tries.
|
|
151
|
+
if (!retry.cancelled) void runOnce()
|
|
152
|
+
}, delay)
|
|
153
|
+
}
|
|
107
154
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
try {
|
|
114
|
-
// Read the client per request: it changes when the server restarts.
|
|
115
|
-
next = await readQuota({ client: client(), fallback: usable, site: options.site })
|
|
116
|
-
} catch (error) {
|
|
117
|
-
// `client()` itself can throw when the server client is unavailable,
|
|
118
|
-
// which is the same situation as a rejected RPC call.
|
|
119
|
-
const message = String((error as Error)?.message ?? error)
|
|
120
|
-
next = usable ? { ...usable, status: "stale", error: message } : idle("error", message)
|
|
121
|
-
}
|
|
122
|
-
emit(next)
|
|
123
|
-
} finally {
|
|
124
|
-
inflight = null
|
|
125
|
-
const queued = pendingSite
|
|
126
|
-
pendingSite = null
|
|
127
|
-
// Re-run only if the last request was for a different site than the one
|
|
128
|
-
// that just completed; otherwise it is already served.
|
|
129
|
-
if (queued && queued !== current.site) void refresh({ force: true, site: queued })
|
|
155
|
+
async function runOnce(site?: Site): Promise<ReadOutcome> {
|
|
156
|
+
if (inflight) {
|
|
157
|
+
if (inflight.site !== site) {
|
|
158
|
+
await inflight.promise
|
|
159
|
+
return runOnce(site)
|
|
130
160
|
}
|
|
131
|
-
|
|
161
|
+
const o = await inflight.promise
|
|
162
|
+
if (o.kind === "ok") clearRetry()
|
|
163
|
+
return o
|
|
164
|
+
}
|
|
165
|
+
// Only fall back to numbers belonging to the requested site — otherwise a
|
|
166
|
+
// failed intl read would display cn's balance and reroute later hovers to cn.
|
|
167
|
+
const fallback =
|
|
168
|
+
current.remaining !== null && (site === undefined || current.site === site) ? current : null
|
|
169
|
+
const entry: { site?: Site; promise: Promise<ReadOutcome> } = {
|
|
170
|
+
site,
|
|
171
|
+
promise: Promise.resolve() as never,
|
|
172
|
+
}
|
|
173
|
+
entry.promise = readQuota({ getClient: client, fallback, now: now(), site })
|
|
174
|
+
inflight = entry
|
|
175
|
+
try {
|
|
176
|
+
const o = await entry.promise
|
|
177
|
+
onOutcome(o)
|
|
178
|
+
return o
|
|
179
|
+
} finally {
|
|
180
|
+
inflight = null
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const refresh = async (options: { force?: boolean; maxAgeMs?: number; site?: Site } = {}) => {
|
|
185
|
+
if (options.force) {
|
|
186
|
+
// A manual refresh (dialog button) is allowed during backoff and ends it early.
|
|
187
|
+
} else if (retry.timer !== null) {
|
|
188
|
+
return
|
|
189
|
+
} else if (now() - lastSuccessAt < (options.maxAgeMs ?? refreshMs)) {
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
lastAttempt = now()
|
|
193
|
+
await runOnce(options.site)
|
|
194
|
+
}
|
|
132
195
|
|
|
133
|
-
|
|
196
|
+
const hasDocument = typeof globalThis.document !== "undefined"
|
|
197
|
+
const tick = () => {
|
|
198
|
+
if (hasDocument && globalThis.document.hidden) return
|
|
199
|
+
void refresh()
|
|
200
|
+
}
|
|
201
|
+
const onVisible = () => {
|
|
202
|
+
if (globalThis.document.hidden) return
|
|
203
|
+
if (now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
|
|
134
204
|
}
|
|
135
205
|
|
|
136
206
|
const start = () => {
|
|
137
207
|
if (started) return () => {}
|
|
138
208
|
started = true
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
// A hidden window must not poll; on return, refresh only if the data aged.
|
|
142
|
-
if (hasDocument && globalThis.document.hidden) return
|
|
143
|
-
void refresh()
|
|
144
|
-
}
|
|
145
|
-
const onVisible = () => {
|
|
146
|
-
if (globalThis.document.hidden) return
|
|
147
|
-
if (Date.now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
|
|
148
|
-
}
|
|
149
|
-
const timer = setInterval(tick, REFRESH_MS)
|
|
209
|
+
retry.cancelled = false
|
|
210
|
+
timerId = timers.setInterval(tick, refreshMs)
|
|
150
211
|
if (hasDocument) globalThis.document.addEventListener("visibilitychange", onVisible)
|
|
151
|
-
// The one place the capsule gets its first number without any interaction.
|
|
152
212
|
void refresh({ force: true })
|
|
153
213
|
return () => {
|
|
154
|
-
|
|
214
|
+
retry.cancelled = true
|
|
215
|
+
timers.clearTimeout(retry.timer)
|
|
216
|
+
timers.clearInterval(timerId)
|
|
155
217
|
if (hasDocument) globalThis.document.removeEventListener("visibilitychange", onVisible)
|
|
156
218
|
started = false
|
|
157
219
|
}
|
|
158
220
|
}
|
|
159
221
|
|
|
222
|
+
const setRefreshMs = (ms: number) => {
|
|
223
|
+
refreshMs = ms
|
|
224
|
+
if (!started) return
|
|
225
|
+
timers.clearInterval(timerId)
|
|
226
|
+
timerId = timers.setInterval(tick, refreshMs)
|
|
227
|
+
}
|
|
228
|
+
|
|
160
229
|
return {
|
|
161
230
|
read: () => current,
|
|
162
231
|
subscribe(listener) {
|
|
@@ -177,5 +246,6 @@ export function createQuotaStore(client: () => QuotaClient): QuotaStore {
|
|
|
177
246
|
}
|
|
178
247
|
},
|
|
179
248
|
start,
|
|
249
|
+
setRefreshMs,
|
|
180
250
|
}
|
|
181
251
|
}
|
package/src/gui.tsx
CHANGED
|
@@ -21,6 +21,22 @@ export default Plugin.define({
|
|
|
21
21
|
onCleanup(store.subscribe(setQuota))
|
|
22
22
|
onCleanup(store.start())
|
|
23
23
|
|
|
24
|
+
// The interval is configurable on the server; start() already armed the
|
|
25
|
+
// default 10-minute timer, so a successful config read just rebuilds it.
|
|
26
|
+
// config() is fire-and-forget: setup() must stay synchronous (no thenable
|
|
27
|
+
// return), and a failure here keeps the default rather than retrying.
|
|
28
|
+
void ctx.client.rpc(CodebuddyQuota).config({})
|
|
29
|
+
.then((r) => {
|
|
30
|
+
const { refreshMinutes } = r as { refreshMinutes?: number }
|
|
31
|
+
// Do not trust the RPC: match the server's 1..30 integer rule so a NaN
|
|
32
|
+
// or 0 can never turn setInterval into a 0ms hot loop.
|
|
33
|
+
if (typeof refreshMinutes === "number" && Number.isInteger(refreshMinutes)
|
|
34
|
+
&& refreshMinutes >= 1 && refreshMinutes <= 30) {
|
|
35
|
+
store.setRefreshMs(refreshMinutes * 60_000)
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
.catch(() => { /* startup race: keep the default 10 minutes */ })
|
|
39
|
+
|
|
24
40
|
const openDetails = () => {
|
|
25
41
|
// Refreshing here as well as on the dialog's mount would fire two requests
|
|
26
42
|
// for one click, so the dialog owns that refresh.
|
|
@@ -34,6 +50,7 @@ export default Plugin.define({
|
|
|
34
50
|
<QuotaDialog
|
|
35
51
|
quota={live()}
|
|
36
52
|
ui={ctx.ui}
|
|
53
|
+
currentModel={ctx.screen.current()?.composer.model()?.modelID}
|
|
37
54
|
onRefresh={(site) => store.refresh({ force: true, site })}
|
|
38
55
|
onLogin={(site) => store.login(site)}
|
|
39
56
|
close={dialog.close}
|
package/src/server/config.ts
CHANGED
|
@@ -39,6 +39,11 @@ export interface QuotaConfig {
|
|
|
39
39
|
* default: user edits win over later plugin updates.
|
|
40
40
|
*/
|
|
41
41
|
overwrite_config: boolean
|
|
42
|
+
/**
|
|
43
|
+
* Minutes between background quota refreshes. Shorter keeps the capsule
|
|
44
|
+
* fresher but polls more; bounded to a sane 1..30 range.
|
|
45
|
+
*/
|
|
46
|
+
refresh_minutes: number
|
|
42
47
|
}
|
|
43
48
|
|
|
44
49
|
/**
|
|
@@ -106,6 +111,7 @@ export const DEFAULT_CONFIG: QuotaConfig = {
|
|
|
106
111
|
embedding_model: "bge-m3",
|
|
107
112
|
local_embedding_model: "",
|
|
108
113
|
overwrite_config: false,
|
|
114
|
+
refresh_minutes: 10,
|
|
109
115
|
}
|
|
110
116
|
|
|
111
117
|
export const CONFIG_FILE_NAME = "codebuddy-quota.json"
|
|
@@ -301,6 +307,13 @@ function optionalString(value: unknown): string | undefined {
|
|
|
301
307
|
return typeof value === "string" ? value : undefined
|
|
302
308
|
}
|
|
303
309
|
|
|
310
|
+
/** Only an integer in 1..30 is accepted; everything else keeps the default. */
|
|
311
|
+
function refreshMinutes(value: unknown): number | undefined {
|
|
312
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 30
|
|
313
|
+
? value
|
|
314
|
+
: undefined
|
|
315
|
+
}
|
|
316
|
+
|
|
304
317
|
export interface LoadConfigDeps {
|
|
305
318
|
configPath?: string
|
|
306
319
|
readFile?: (path: string) => string
|
|
@@ -340,5 +353,6 @@ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
|
|
|
340
353
|
local_embedding_model:
|
|
341
354
|
optionalString(parsed.local_embedding_model) ?? DEFAULT_CONFIG.local_embedding_model,
|
|
342
355
|
overwrite_config: overwrite ?? DEFAULT_CONFIG.overwrite_config,
|
|
356
|
+
refresh_minutes: refreshMinutes(parsed.refresh_minutes) ?? DEFAULT_CONFIG.refresh_minutes,
|
|
343
357
|
}
|
|
344
358
|
}
|
package/src/server/proxy.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
|
2
2
|
import type { Site } from "../shared"
|
|
3
3
|
import { createLocalEmbedder, isLocalModel, routeEmbedding, type LocalEmbedding } from "./embedding-local"
|
|
4
|
+
import type { RateLimitStore } from "./rate-limit-store"
|
|
4
5
|
import { apiHeaders, channelHeaders } from "./headers"
|
|
5
6
|
import { SITE_ENDPOINTS } from "./login"
|
|
6
7
|
import type { ModelsListResponse } from "./models-endpoint"
|
|
@@ -115,6 +116,26 @@ export interface ProxyResponse {
|
|
|
115
116
|
end(chunk?: string | Uint8Array): void
|
|
116
117
|
}
|
|
117
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Pull a human-readable upstream message from a 429 body. `normalized` is the
|
|
121
|
+
* rewritten OpenAI error (null when the body was already OpenAI-shaped or bad);
|
|
122
|
+
* fall back through the raw text so the notice always carries a string.
|
|
123
|
+
*/
|
|
124
|
+
function extractErrorMessage(normalized: string | null, text: string): string {
|
|
125
|
+
if (normalized) {
|
|
126
|
+
try {
|
|
127
|
+
const m = (JSON.parse(normalized) as { error?: { message?: unknown } }).error?.message
|
|
128
|
+
if (typeof m === "string" && m !== "") return m
|
|
129
|
+
} catch { /* fall through */ }
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(text) as { error?: { message?: unknown }; msg?: unknown }
|
|
133
|
+
if (typeof parsed?.error?.message === "string" && parsed.error.message !== "") return parsed.error.message
|
|
134
|
+
if (typeof parsed?.msg === "string" && parsed.msg !== "") return parsed.msg
|
|
135
|
+
} catch { /* fall through */ }
|
|
136
|
+
return text || "HTTP 429"
|
|
137
|
+
}
|
|
138
|
+
|
|
118
139
|
export interface HandleRequestDeps {
|
|
119
140
|
store: TokenStore
|
|
120
141
|
fetchImpl?: typeof fetch
|
|
@@ -136,6 +157,8 @@ export interface HandleRequestDeps {
|
|
|
136
157
|
embeddingTimeoutMs?: number
|
|
137
158
|
/** Configured backend for embeddings; absent keeps the legacy body-prefix routing. */
|
|
138
159
|
embeddingMode?: "cloud" | "local"
|
|
160
|
+
/** Optional best-effort recorder of model-level 429 limits. */
|
|
161
|
+
rateLimitStore?: RateLimitStore
|
|
139
162
|
}
|
|
140
163
|
|
|
141
164
|
/** Emit OpenAI's error envelope, not a stack trace or a gateway-specific body. */
|
|
@@ -320,6 +343,12 @@ export async function handleRequest(
|
|
|
320
343
|
const readBody = deps.readBody ?? (() => Promise.resolve(""))
|
|
321
344
|
// Read once: `readBody` is an injectable seam and need not be replayable.
|
|
322
345
|
const raw = await readBody(req)
|
|
346
|
+
// The model id identifies the rate-limit bucket; absent on non-chat/malformed bodies.
|
|
347
|
+
let chatModel: string | undefined
|
|
348
|
+
try {
|
|
349
|
+
const parsed = JSON.parse(raw) as { model?: unknown }
|
|
350
|
+
if (typeof parsed?.model === "string" && parsed.model !== "") chatModel = parsed.model
|
|
351
|
+
} catch { /* not a JSON chat body */ }
|
|
323
352
|
const isEmbeddings = pathAfterV2 === EMBEDDINGS_PATH
|
|
324
353
|
// A local-mode embedding (configured, or a legacy `Xenova/*` body id) runs
|
|
325
354
|
// in-process, so it must return before the upstream fetch and before any auth
|
|
@@ -441,6 +470,12 @@ export async function handleRequest(
|
|
|
441
470
|
// Plain OpenAI clients expect a single JSON object. Upstream errors are never
|
|
442
471
|
// aggregated; a chat error that is a JSON envelope gets normalized below so
|
|
443
472
|
// clients can read the real reason instead of the HTTP status phrase.
|
|
473
|
+
// A successful chat request clears any prior limit for this (site, model) —
|
|
474
|
+
// covers both the streaming and aggregate paths, and never runs for a 429.
|
|
475
|
+
if (isChat && upstream.ok && chatModel) {
|
|
476
|
+
try { deps.rateLimitStore?.clear(site, chatModel) } catch { /* best-effort */ }
|
|
477
|
+
}
|
|
478
|
+
|
|
444
479
|
const isAggregate = !wantsStream && upstream.ok && isChat
|
|
445
480
|
if (isAggregate) {
|
|
446
481
|
// Aggregate through a reader rather than `text()`: a client that walks away
|
|
@@ -475,6 +510,35 @@ export async function handleRequest(
|
|
|
475
510
|
)
|
|
476
511
|
}
|
|
477
512
|
|
|
513
|
+
// 429 chat errors: record the model-level limit (best-effort) and rewrite the
|
|
514
|
+
// body so the client sees the upstream reason. `text()` is read exactly once —
|
|
515
|
+
// both the recorder and the response rewrite reuse it.
|
|
516
|
+
if (isChat && upstream.status === 429) {
|
|
517
|
+
const text = await upstream.text()
|
|
518
|
+
if (deps.signal?.aborted) return
|
|
519
|
+
const ct = upstream.headers.get("content-type")
|
|
520
|
+
const normalized = isJsonContentType(ct) ? normalizeUpstreamError(429, ct, text) : null
|
|
521
|
+
if (chatModel) {
|
|
522
|
+
try {
|
|
523
|
+
deps.rateLimitStore?.record(site, chatModel, {
|
|
524
|
+
message: extractErrorMessage(normalized, text),
|
|
525
|
+
retryAfter: upstream.headers.get("retry-after"),
|
|
526
|
+
at: Date.now(),
|
|
527
|
+
})
|
|
528
|
+
} catch { /* rate-limit notice is best-effort */ }
|
|
529
|
+
}
|
|
530
|
+
copyHeaders(upstream.headers, res)
|
|
531
|
+
if (normalized !== null) {
|
|
532
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8")
|
|
533
|
+
res.status(429)
|
|
534
|
+
res.end(normalized)
|
|
535
|
+
return
|
|
536
|
+
}
|
|
537
|
+
res.status(429)
|
|
538
|
+
res.end(text)
|
|
539
|
+
return
|
|
540
|
+
}
|
|
541
|
+
|
|
478
542
|
// Side effect only for chat errors: the AI SDK derives `error.message` from an
|
|
479
543
|
// OpenAI-shaped body and falls back to the status phrase otherwise, which hides
|
|
480
544
|
// the upstream reason ("Too Many Requests"). Keep the status so the client's
|
|
@@ -548,6 +612,7 @@ export function createProxy(deps: {
|
|
|
548
612
|
createLocalEmbedder?: (modelId?: string) => LocalEmbedding
|
|
549
613
|
embeddingTimeoutMs?: number
|
|
550
614
|
embeddingMode?: "cloud" | "local"
|
|
615
|
+
rateLimitStore?: RateLimitStore
|
|
551
616
|
listenOptions?: ListenOptions
|
|
552
617
|
}): ProxyServer {
|
|
553
618
|
const server = createServer((incoming: IncomingMessage, outgoing: ServerResponse) => {
|
|
@@ -602,6 +667,7 @@ export function createProxy(deps: {
|
|
|
602
667
|
createLocalEmbedder: deps.createLocalEmbedder,
|
|
603
668
|
embeddingTimeoutMs: deps.embeddingTimeoutMs,
|
|
604
669
|
embeddingMode: deps.embeddingMode,
|
|
670
|
+
rateLimitStore: deps.rateLimitStore,
|
|
605
671
|
},
|
|
606
672
|
).catch(() => {
|
|
607
673
|
if (controller.signal.aborted) return
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { join } from "node:path"
|
|
2
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
3
|
+
import type { RateLimitInfo, Site } from "../shared"
|
|
4
|
+
import { configDir } from "./config"
|
|
5
|
+
|
|
6
|
+
/** The full record kept on disk; the GUI only receives the 4-field RateLimitInfo. */
|
|
7
|
+
export type StoredRateLimitInfo = RateLimitInfo & { retryAfter: string | null; at: number }
|
|
8
|
+
|
|
9
|
+
export interface RateLimitStore {
|
|
10
|
+
record(site: Site, model: string, input: { message: string; retryAfter: string | null; at: number }): void
|
|
11
|
+
list(site: Site): StoredRateLimitInfo[]
|
|
12
|
+
clear(site: Site, model: string): void
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RateLimitStoreDeps {
|
|
16
|
+
path?: string
|
|
17
|
+
readFile?: (path: string) => string
|
|
18
|
+
writeFile?: (path: string, content: string) => void
|
|
19
|
+
now?: () => number
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const SECONDS = /(\d+)\s*(秒|s|sec|seconds)/i
|
|
23
|
+
const MINUTES = /(\d+)\s*(分|分钟|m|min|minutes)/i
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Resolve the moment a 429 lifts: retry-after first (integer seconds or an HTTP
|
|
27
|
+
* date), then a relative-time phrase in the upstream message, else null (the
|
|
28
|
+
* notice stays until a successful request clears it).
|
|
29
|
+
*/
|
|
30
|
+
export function parseUnlockAt(retryAfter: string | null, message: string, now: number): number | null {
|
|
31
|
+
if (retryAfter) {
|
|
32
|
+
if (/^\d+$/.test(retryAfter.trim())) {
|
|
33
|
+
return now + Number(retryAfter.trim()) * 1000
|
|
34
|
+
}
|
|
35
|
+
const parsed = Date.parse(retryAfter)
|
|
36
|
+
if (Number.isFinite(parsed)) return parsed
|
|
37
|
+
}
|
|
38
|
+
const min = MINUTES.exec(message)
|
|
39
|
+
if (min) return now + Number(min[1]) * 60_000
|
|
40
|
+
const sec = SECONDS.exec(message)
|
|
41
|
+
if (sec) return now + Number(sec[1]) * 1000
|
|
42
|
+
return null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createRateLimitStore(deps: RateLimitStoreDeps = {}): RateLimitStore {
|
|
46
|
+
const path = deps.path ?? join(configDir(), "codebuddy-quota-ratelimit.json")
|
|
47
|
+
const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
|
|
48
|
+
const write = deps.writeFile ?? ((p: string, s: string) => writeFileSync(p, s, "utf8"))
|
|
49
|
+
const now = deps.now ?? Date.now
|
|
50
|
+
|
|
51
|
+
const load = (): StoredRateLimitInfo[] => {
|
|
52
|
+
try {
|
|
53
|
+
const parsed = JSON.parse(read(path)) as { entries?: unknown }
|
|
54
|
+
if (!Array.isArray(parsed.entries)) return []
|
|
55
|
+
return parsed.entries.filter(
|
|
56
|
+
(e): e is StoredRateLimitInfo =>
|
|
57
|
+
!!e &&
|
|
58
|
+
typeof e === "object" &&
|
|
59
|
+
(e as StoredRateLimitInfo).site !== undefined &&
|
|
60
|
+
typeof (e as StoredRateLimitInfo).model === "string" &&
|
|
61
|
+
typeof (e as StoredRateLimitInfo).message === "string",
|
|
62
|
+
)
|
|
63
|
+
} catch {
|
|
64
|
+
return []
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const save = (entries: StoredRateLimitInfo[]) => {
|
|
69
|
+
try {
|
|
70
|
+
write(path, JSON.stringify({ entries }, null, 2))
|
|
71
|
+
} catch {
|
|
72
|
+
// A rate-limit notice is best-effort; a failed write must not affect the proxy.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const matches = (e: StoredRateLimitInfo, site: Site, model: string) =>
|
|
77
|
+
e.site === site && e.model === model
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
record(site, model, input) {
|
|
81
|
+
const entries = load().filter((e) => !matches(e, site, model))
|
|
82
|
+
entries.push({
|
|
83
|
+
site,
|
|
84
|
+
model,
|
|
85
|
+
message: input.message,
|
|
86
|
+
retryAfter: input.retryAfter,
|
|
87
|
+
at: input.at,
|
|
88
|
+
unlockAt: parseUnlockAt(input.retryAfter, input.message, now()),
|
|
89
|
+
})
|
|
90
|
+
save(entries)
|
|
91
|
+
},
|
|
92
|
+
list(site) {
|
|
93
|
+
return load()
|
|
94
|
+
.filter((e) => e.site === site)
|
|
95
|
+
.filter((e) => e.unlockAt === null || e.unlockAt > now())
|
|
96
|
+
.sort((a, b) => (a.unlockAt ?? Infinity) - (b.unlockAt ?? Infinity))
|
|
97
|
+
},
|
|
98
|
+
clear(site, model) {
|
|
99
|
+
save(load().filter((e) => !matches(e, site, model)))
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import type { Site } from "../shared"
|
|
1
|
+
import type { RateLimitInfo, Site } from "../shared"
|
|
2
2
|
import { createLoginGate, type LoginGate } from "./login-gate"
|
|
3
3
|
import { getAuthState, openBrowser, pollToken, type SiteAuth } from "./login"
|
|
4
4
|
import { resolveSite } from "./site-select"
|
|
5
5
|
import { siteInfo } from "./site-state"
|
|
6
6
|
import type { TokenStore } from "./token-store"
|
|
7
|
+
import type { RateLimitStore } from "./rate-limit-store"
|
|
7
8
|
import type { QuotaSource, Reading } from "./quota-source"
|
|
8
9
|
import { toWireReading, type WireReading } from "./wire"
|
|
9
10
|
|
|
@@ -11,6 +12,7 @@ import { toWireReading, type WireReading } from "./wire"
|
|
|
11
12
|
export interface RpcHandlers {
|
|
12
13
|
read(input: unknown, context: { signal: AbortSignal }): Promise<WireReading>
|
|
13
14
|
login(input: unknown): Promise<{ ok: boolean; error: string | null }>
|
|
15
|
+
config(): Promise<{ refreshMinutes: number }>
|
|
14
16
|
}
|
|
15
17
|
|
|
16
18
|
export interface HandlerDeps {
|
|
@@ -26,6 +28,10 @@ export interface HandlerDeps {
|
|
|
26
28
|
* can re-import its provider models. A failure here never fails the login.
|
|
27
29
|
*/
|
|
28
30
|
afterLogin?: (site: Site) => Promise<void>
|
|
31
|
+
/** Background refresh interval in minutes; optional so existing callers need not set it. */
|
|
32
|
+
refreshMinutes?: number
|
|
33
|
+
/** Best-effort source of model-level rate limits; absent yields an empty list. */
|
|
34
|
+
rateLimitStore?: RateLimitStore
|
|
29
35
|
}
|
|
30
36
|
|
|
31
37
|
/**
|
|
@@ -53,7 +59,15 @@ export function makeRpcHandlers(deps: HandlerDeps): RpcHandlers {
|
|
|
53
59
|
// Read the cache AFTER the refresh so a rotated token cannot leave a
|
|
54
60
|
// stale "needs login" tag next to freshly returned numbers.
|
|
55
61
|
const state = deps.store.all()
|
|
56
|
-
|
|
62
|
+
// Project to the 4-field wire shape so `additionalProperties:false` in the
|
|
63
|
+
// RPC schema stays satisfied (the store also keeps retryAfter/at internally).
|
|
64
|
+
const rateLimits: RateLimitInfo[] = (deps.rateLimitStore?.list(site) ?? []).map(
|
|
65
|
+
({ site: s, model, message, unlockAt }) => ({ site: s, model, message, unlockAt }),
|
|
66
|
+
)
|
|
67
|
+
return toWireReading(reading, { site, sites: siteInfo(state, (s) => deps.store.refreshFailed(s)).sites }, rateLimits)
|
|
68
|
+
},
|
|
69
|
+
async config() {
|
|
70
|
+
return { refreshMinutes: deps.refreshMinutes ?? 10 }
|
|
57
71
|
},
|
|
58
72
|
async login(input) {
|
|
59
73
|
const site = (input as { site: Site }).site
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { GatewaySetup } from "./gateway-setup"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Register the RPC handlers before acquiring the gateway. The GUI fires its
|
|
5
|
+
* first quota read the moment it mounts, so a handler that is only registered
|
|
6
|
+
* after the gateway bind leaves a window where that read gets a 400 and the
|
|
7
|
+
* battery shows a stale hatch. Registering first closes that window; the
|
|
8
|
+
* gateway's register callback merely reuses the same registration.
|
|
9
|
+
*/
|
|
10
|
+
export async function registerThenGateway<T>(deps: {
|
|
11
|
+
register(): Promise<T>
|
|
12
|
+
setupGateway(deps: { register(): Promise<T> }): Promise<GatewaySetup>
|
|
13
|
+
}): Promise<{ registration: T; gw: GatewaySetup }> {
|
|
14
|
+
const registration = await deps.register()
|
|
15
|
+
const gw = await deps.setupGateway({ register: async () => registration })
|
|
16
|
+
return { registration, gw }
|
|
17
|
+
}
|
package/src/server/wire.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SiteInfo } from "../shared"
|
|
1
|
+
import type { RateLimitInfo, SiteInfo } from "../shared"
|
|
2
2
|
import type { Reading } from "./quota-source"
|
|
3
3
|
|
|
4
4
|
/** The object the RPC returns; the fields mirror `rpc.ts`'s output schema. */
|
|
@@ -19,6 +19,8 @@ export interface WireReading {
|
|
|
19
19
|
error: string | null
|
|
20
20
|
site: "cn" | "intl"
|
|
21
21
|
sites: SiteInfo[]
|
|
22
|
+
/** Active model-level limits for the requested site; empty when none. */
|
|
23
|
+
rateLimits: RateLimitInfo[]
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
/**
|
|
@@ -31,6 +33,7 @@ export interface WireReading {
|
|
|
31
33
|
export function toWireReading(
|
|
32
34
|
reading: Reading,
|
|
33
35
|
info: { site: "cn" | "intl"; sites: SiteInfo[] },
|
|
36
|
+
rateLimits: RateLimitInfo[] = [],
|
|
34
37
|
): WireReading {
|
|
35
38
|
const numbers = {
|
|
36
39
|
remaining: reading.remaining,
|
|
@@ -58,10 +61,11 @@ export function toWireReading(
|
|
|
58
61
|
fetchedAt: null,
|
|
59
62
|
site: info.site,
|
|
60
63
|
sites: info.sites,
|
|
64
|
+
rateLimits,
|
|
61
65
|
}
|
|
62
66
|
}
|
|
63
67
|
return {
|
|
64
68
|
ok: true, stale: reading.stale, cached: reading.cached, ageSeconds: reading.ageSeconds,
|
|
65
|
-
...numbers, site: info.site, sites: info.sites,
|
|
69
|
+
...numbers, site: info.site, sites: info.sites, rateLimits,
|
|
66
70
|
}
|
|
67
71
|
}
|
package/src/shared.ts
CHANGED
|
@@ -21,3 +21,12 @@ export interface SiteInfo {
|
|
|
21
21
|
accounts: AccountBrief[]
|
|
22
22
|
activeId: string | null
|
|
23
23
|
}
|
|
24
|
+
|
|
25
|
+
/** A rate-limit notice sent to the GUI: one per (site, model). */
|
|
26
|
+
export interface RateLimitInfo {
|
|
27
|
+
site: Site
|
|
28
|
+
model: string
|
|
29
|
+
message: string
|
|
30
|
+
/** Epoch ms when the limit lifts, or null when unknown (cleared on success). */
|
|
31
|
+
unlockAt: number | null
|
|
32
|
+
}
|