opencode-codebuddy-quota 0.0.0-stage → 0.1.2

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lscar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,82 @@
1
- # Temporary Holding Version
1
+ # opencode-codebuddy-quota
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenCode 插件:在状态栏显示 CodeBuddy 额度胶囊,并把 CodeBuddy 的模型接入模型选择器。
4
+
5
+ 支持 **国内站**(`copilot.tencent.com`)与 **国际站**(`www.codebuddy.ai`),两站各自登录、各自额度、在一个弹窗里切换。
6
+
7
+ ## 功能
8
+
9
+ - **额度胶囊**:会话标题栏显示本周期剩余积分、使用节奏(快于/慢于时间)、到期/重置时间;需要登录时显示琥珀色角标。
10
+ - **额度弹窗**:点击胶囊打开,可切换国内/国际站、手动刷新、登录。样式跟随 OpenCode 主题,带克制的柔光与动效。
11
+ - **模型接入**:按 WorkBuddy 客户端逻辑从 `/v3/config` 自动生成模型清单——国际站过滤 Pro-only 模型、同名模型保留免费版、名称标注倍率;国内站同理。模型数据随上游自动更新,不写死。
12
+ - **内置代理**:本地 `127.0.0.1:7688`,按 `/cn/v2`、`/intl/v2` 选站并注入 JWT;国际站自动补齐渠道校验头与身份提示词。
13
+ - **自包含登录**:浮层点「登录」→ 浏览器授权 → 轮询获取凭据,写入自己的缓存,不依赖 CodeBuddy CLI,也不读写 CLI 的认证文件。
14
+ - **JWT 自动刷新**:凭据过期前自动续期;失败冷却、登录后强制回填额度等边界均已处理。
15
+
16
+ ## 安装
17
+
18
+ 在 OpenCode 全局配置(`~/.config/opencode/opencode.jsonc` 或 `.json`)里加入本插件:
19
+
20
+ ```jsonc
21
+ {
22
+ "plugins": ["opencode-codebuddy-quota"]
23
+ }
24
+ ```
25
+
26
+ 固定版本时写成 `"opencode-codebuddy-quota@<version>"`。
27
+
28
+ 插件首次运行会把模型写入 provider `codebuddy-cn` / `codebuddy-intl`;在 `/model` 里选择对应模型即可对话。
29
+
30
+ ## 登录
31
+
32
+ 1. 点击状态栏的额度胶囊打开弹窗。
33
+ 2. 在需要登录的站点标签上点「登录」,浏览器会打开授权页。
34
+ 3. 完成授权后插件自行轮询获取凭据,胶囊与弹窗自动刷新。
35
+
36
+ 凭据缓存位于 `~/.config/opencode/codebuddy-quota-auth.json`,可删除后重新登录。
37
+
38
+ ## 配置
39
+
40
+ 高级映射配置位于 `~/.config/opencode/codebuddy-quota.json`(可选):
41
+
42
+ ```jsonc
43
+ {
44
+ "models": {
45
+ "<codebuddy-id>": { "provider": "<models.dev-provider>", "model": "<model-id>" }
46
+ },
47
+ "excluded_models": ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
48
+ "package_version": "2.0.90"
49
+ }
50
+ ```
51
+
52
+ - `models`:CodeBuddy 模型 id → models.dev 坐标;未映射的模型不会进入选择器。
53
+ - `excluded_models`:硬排除的模型 id(含虚拟路由档位 `auto` / `max-model`)。
54
+ - `package_version`:写入 provider 的 `@ai-sdk/openai-compatible` 版本。
55
+
56
+ 默认配置见 `config.default.json`。
57
+
58
+ ## 开发
59
+
60
+ 前置:本机有 `bun`。
61
+
62
+ ```sh
63
+ bun install
64
+ bun run check # typecheck + 全部测试
65
+ bun run build:gui # 构建桌面端 GUI(dist/gui-experimental.cjs)
66
+ ```
67
+
68
+ 插件由三部分构成(同一个 npm 包):
69
+
70
+ - `server.ts` / `src/server/*`:额度取数、模型导入、本地代理、RPC。
71
+ - `src/gui.tsx` / `src/gui/*`:桌面端 GUI(状态栏胶囊与弹窗),SolidJS。
72
+ - `rpc.ts`:服务端与 GUI 之间的契约。
73
+
74
+ ## 限制
75
+
76
+ - 每站本期至多一个账号;数据结构预留了多账号,但本期不提供切换 UI。
77
+ - 本地代理是 "confused deputy":本机任意进程都能借它用 JWT 调上游,接受此风险。
78
+ - 模型倍率名称来自上游 `credits` 字段;上游未声明时倍率标签会省略。
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,41 @@
1
+ {
2
+ "models": {
3
+ "deepseek-v4-pro": { "provider": "deepseek", "model": "deepseek-v4-pro" },
4
+ "deepseek-v4.1-flash": { "provider": "deepseek", "model": "deepseek-v4-flash" },
5
+ "glm-5.3-flash": { "provider": "zhipuai", "model": "glm-5.3-flash" },
6
+ "glm-5.3-flashx": { "provider": "zhipuai", "model": "glm-5.3-flashx" },
7
+ "minimax-m3.1-flash": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
8
+ "step-5-preview": { "provider": "stepfun", "model": "step-5-preview" },
9
+ "mimo-v2.6-pro": { "provider": "xiaomi", "model": "mimo-v2.6-pro" },
10
+ "hy4std": { "provider": "tencent-tokenhub", "model": "hy4" },
11
+ "hy4flash-free": { "provider": "tencent-tokenhub", "model": "hy4" },
12
+ "hy4flash": { "provider": "tencent-tokenhub", "model": "hy4" },
13
+ "hy4free": { "provider": "tencent-tokenhub", "model": "hy4" },
14
+ "hy3": { "provider": "tencent-tokenhub", "model": "hy3" },
15
+ "hy3-x": { "provider": "tencent-tokenhub", "model": "hy3" },
16
+ "space-bunny": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
17
+ "hy4-preview": { "provider": "tencent-tokenhub", "model": "hy4-preview" },
18
+ "deepseek-v4.1-flash-sg": { "provider": "deepseek", "model": "deepseek-v4-flash" },
19
+ "gpt-6-astra": { "provider": "openai", "model": "gpt-6-astra" },
20
+ "gpt-6.1-sol": { "provider": "openai", "model": "gpt-6.1-sol" },
21
+ "gpt-6-sol": { "provider": "openai", "model": "gpt-6-sol" },
22
+ "gpt-6-luna": { "provider": "openai", "model": "gpt-6-luna" },
23
+ "gpt-5.6-sol": { "provider": "openai", "model": "gpt-5.6-sol" },
24
+ "gpt-5.6-terra": { "provider": "openai", "model": "gpt-5.6-terra" },
25
+ "gpt-5.5": { "provider": "openai", "model": "gpt-5.5" },
26
+ "gpt-5.4": { "provider": "openai", "model": "gpt-5.4" },
27
+ "gpt-5.6-luna": { "provider": "openai", "model": "gpt-5.6-luna" },
28
+ "grok-4.7": { "provider": "xai", "model": "grok-4.7" },
29
+ "gemini-3.8-flash": { "provider": "google", "model": "gemini-3.8-flash" },
30
+ "glm-5.3": { "provider": "zhipuai", "model": "glm-5.3" },
31
+ "glm-5.4": { "provider": "tencent-token-plan", "model": "glm-5.4" },
32
+ "glm-5.2": { "provider": "zhipuai", "model": "glm-5.2" },
33
+ "kimi-k3.1-pro": { "provider": "moonshotai", "model": "kimi-k3.1-pro" },
34
+ "kimi-k3": { "provider": "moonshotai", "model": "kimi-k3" },
35
+ "kimi-k3.1-pro-highspeed": { "provider": "moonshotai", "model": "kimi-k3.1-pro-highspeed" }
36
+ },
37
+ "excluded_models": ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
38
+ "package_version": "2.0.90",
39
+ "embedding_model": "bge-m3",
40
+ "local_embedding_model": ""
41
+ }
@@ -0,0 +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;
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "opencode-codebuddy-quota",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "OpenCode plugin: dual-site (CN/INTL) CodeBuddy providers with dynamic JWT and a quota capsule that switches sites",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "bun": ">=1.4.0"
9
+ },
10
+ "files": [
11
+ "server.ts",
12
+ "rpc.ts",
13
+ "src",
14
+ "config.default.json",
15
+ "dist",
16
+ "!**/*.test.ts"
17
+ ],
18
+ "exports": {
19
+ ".": "./server.ts",
20
+ "./rpc": "./rpc.ts",
21
+ "./gui-experimental": "./dist/gui-experimental.cjs"
22
+ },
23
+ "scripts": {
24
+ "typecheck": "bunx tsc --noEmit",
25
+ "test": "bun test",
26
+ "check": "bun run typecheck && bun test",
27
+ "build": "bun run build:gui",
28
+ "build:gui": "vite build",
29
+ "build:server": "bun -e \"console.log('server runs straight from TypeScript; bun install is all it needs')\"",
30
+ "prepublishOnly": "bun run check && bun run build:gui"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/lscar/opencode-codebuddy-quota.git"
35
+ },
36
+ "homepage": "https://github.com/lscar/opencode-codebuddy-quota#readme",
37
+ "bugs": "https://github.com/lscar/opencode-codebuddy-quota/issues",
38
+ "dependencies": {
39
+ "@huggingface/transformers": "^4.3.2",
40
+ "@opencode/plugin": "2.2.5"
41
+ },
42
+ "devDependencies": {
43
+ "@types/bun": "^1.4.4",
44
+ "solid-js": "^1.9.0",
45
+ "typescript": "5",
46
+ "vite": "^8.0.0",
47
+ "vite-plugin-solid": "^2.11.0"
48
+ }
49
+ }
package/rpc.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { Rpc } from "@opencode/plugin/rpc"
2
+
3
+ /**
4
+ * The RPC contract between this plugin's server part and its GUI part.
5
+ *
6
+ * Schemas are written as plain JSON Schema on purpose. The GUI bundle may only
7
+ * import `@opencode/plugin/rpc`, which does not re-export `effect`, so an
8
+ * Effect `Schema` here would not even bundle. JSON Schema also keeps both
9
+ * sides' inferred types at `unknown`, which stops the GUI call from growing a
10
+ * phantom required argument.
11
+ *
12
+ * This file must not import anything but `Rpc`: the server part runs it as
13
+ * TypeScript directly, and the GUI part bundles it into a window.
14
+ */
15
+ const nullableString = { type: ["string", "null"] } as const
16
+ const nullableNumber = { type: ["number", "null"] } as const
17
+
18
+ const siteEnum = { type: "string", enum: ["cn", "intl"] } as const
19
+ const siteInfoSchema = {
20
+ type: "object",
21
+ properties: {
22
+ site: siteEnum,
23
+ available: { type: "boolean" },
24
+ accounts: {
25
+ type: "array",
26
+ items: {
27
+ type: "object",
28
+ properties: { id: { type: "string" }, label: { type: "string" } },
29
+ required: ["id", "label"],
30
+ additionalProperties: false,
31
+ },
32
+ },
33
+ activeId: nullableString,
34
+ },
35
+ required: ["site", "available", "accounts", "activeId"],
36
+ additionalProperties: false,
37
+ } as const
38
+
39
+ export const CodebuddyQuota = Rpc.define({
40
+ id: "codebuddy-quota",
41
+ methods: {
42
+ read: {
43
+ input: {
44
+ type: "object",
45
+ properties: { site: siteEnum },
46
+ additionalProperties: false,
47
+ },
48
+ output: {
49
+ type: "object",
50
+ properties: {
51
+ // `ok` is true whenever any reading was ever obtained; `stale` then
52
+ // says whether the latest attempt to refresh it failed.
53
+ ok: { type: "boolean" },
54
+ stale: { type: "boolean" },
55
+ // The answer came from the server's 30-second cache, so the numbers are
56
+ // real but this call did not reach the upstream.
57
+ cached: { type: "boolean" },
58
+ ageSeconds: nullableNumber,
59
+ remaining: nullableNumber,
60
+ used: nullableNumber,
61
+ total: nullableNumber,
62
+ cycleStart: nullableString,
63
+ cycleEnd: nullableString,
64
+ resetAt: nullableString,
65
+ // When the upstream call that produced these numbers succeeded.
66
+ fetchedAt: nullableString,
67
+ error: nullableString,
68
+ // Which site these numbers belong to, and both sites' availability.
69
+ site: siteEnum,
70
+ sites: { type: "array", items: siteInfoSchema },
71
+ },
72
+ required: ["ok", "stale", "cached", "site", "sites"],
73
+ additionalProperties: false,
74
+ },
75
+ },
76
+ login: {
77
+ input: {
78
+ type: "object",
79
+ properties: { site: siteEnum },
80
+ required: ["site"],
81
+ additionalProperties: false,
82
+ },
83
+ output: {
84
+ type: "object",
85
+ properties: { ok: { type: "boolean" }, error: nullableString },
86
+ required: ["ok", "error"],
87
+ additionalProperties: false,
88
+ },
89
+ },
90
+ },
91
+ events: {},
92
+ })
package/server.ts ADDED
@@ -0,0 +1,251 @@
1
+ import { existsSync, writeFileSync } from "node:fs"
2
+ import { Plugin } from "@opencode/plugin"
3
+ import { CodebuddyQuota } from "./rpc"
4
+ import type { Site } from "./src/shared"
5
+ import { fetchCatalog } from "./src/server/catalog"
6
+ import { loadConfig, opencodeConfigPath, type QuotaConfig } from "./src/server/config"
7
+ import { writeProvider } from "./src/server/config-writer"
8
+ import { clearLocalEmbedderMemo, createLocalEmbedder, type LocalEmbedding } from "./src/server/embedding-local"
9
+ import { resolveEmbeddingMode } from "./src/server/embedding-mode"
10
+ import { setupGateway } from "./src/server/gateway-setup"
11
+ import { ensureGateway, releaseGateway } from "./src/server/gateway-owner"
12
+ import type { SiteAuth } from "./src/server/login"
13
+ import { createDedupedLogger } from "./src/server/logger"
14
+ import { buildModels } from "./src/server/model-info"
15
+ import { warmLocalModel, type PrewarmDeps } from "./src/server/model-prewarm"
16
+ import { createModelsCache, type ModelsListResponse } from "./src/server/models-endpoint"
17
+ import { readModelsDevCatalog } from "./src/server/models-dev"
18
+ import type { ModelsDevCatalog } from "./src/server/pricing"
19
+ import { latestTaggedVersion } from "./src/server/package-version"
20
+ import { createProxy } from "./src/server/proxy"
21
+ import { createQuotaSource } from "./src/server/quota-source"
22
+ import { makeRpcHandlers } from "./src/server/rpc-handlers"
23
+ import { anySignal, timeoutSignal } from "./src/server/signal"
24
+ import { createTokenStore } from "./src/server/token-store"
25
+ import { fetchUpstream } from "./src/server/upstream"
26
+
27
+ const PROXY_PORT = 7688
28
+ const UPSTREAM_TIMEOUT_MS = 15_000
29
+
30
+ /** Offline inputs the /v2/models list is built from; injected so the seam is testable. */
31
+ export interface ModelsSourceDeps {
32
+ loadConfig: () => QuotaConfig
33
+ readModelsDevCatalog: () => ModelsDevCatalog | null
34
+ getAuth: (site: Site) => SiteAuth | null
35
+ fetchCatalog: typeof fetchCatalog
36
+ buildModels: typeof buildModels
37
+ log: (message: string) => void
38
+ }
39
+
40
+ /**
41
+ * Build the per-site model source for GET /v2/models. Only offline inputs are
42
+ * resolved: a registry/version lookup would add latency and an npm dependency
43
+ * to a request that only needs the mapped model ids (provider writes still do
44
+ * the version lookup through `importDeps`).
45
+ */
46
+ export function createModelsSource(deps: ModelsSourceDeps): (site: Site) => Promise<ModelsListResponse> {
47
+ const cache = createModelsCache(async (site) => {
48
+ const auth = deps.getAuth(site)
49
+ if (!auth) throw new Error(`no account for ${site}`)
50
+ const catalog = await deps.fetchCatalog({ site, auth })
51
+ return deps.buildModels({
52
+ catalog,
53
+ config: deps.loadConfig(),
54
+ modelsDev: deps.readModelsDevCatalog(),
55
+ log: deps.log,
56
+ })
57
+ })
58
+ return (site) => cache.get(site)
59
+ }
60
+
61
+ /** Injected seams so the startup decision can be tested without a real build. */
62
+ export interface StartPrewarmDeps {
63
+ warmLocalModel: (deps: PrewarmDeps) => Promise<LocalEmbedding>
64
+ createLocalEmbedder: (modelId?: string) => LocalEmbedding
65
+ clearLocalEmbedderMemo: () => void
66
+ log: (message: string) => void
67
+ }
68
+
69
+ /**
70
+ * Decide the embedding mode from one loaded config and, in local mode, start a
71
+ * fire-and-forget model warmup. Pure apart from the injected warmup: it never
72
+ * blocks startup, never throws (rejections are logged and swallowed), and on
73
+ * cloud mode touches no local-model code at all. The returned mode is what the
74
+ * proxy must use so routing and warmup agree on the same config.
75
+ */
76
+ export function startPrewarm(
77
+ config: QuotaConfig,
78
+ deps: StartPrewarmDeps,
79
+ ): ReturnType<typeof resolveEmbeddingMode> {
80
+ const mode = resolveEmbeddingMode(config)
81
+ if (mode === "local") {
82
+ void deps
83
+ .warmLocalModel({
84
+ model: config.local_embedding_model,
85
+ build: async () => {
86
+ // Use the SAME id the cache verifier checks, so the pipeline downloads
87
+ // into the directory that is about to be verified.
88
+ const embedder = deps.createLocalEmbedder(config.local_embedding_model)
89
+ // Trigger the real (memoised) pipeline before handing it back.
90
+ await embedder.embed(["ok"])
91
+ return embedder
92
+ },
93
+ // Delete-and-rebuild repair must re-download: drop the memoised pipeline
94
+ // so the next build above starts fresh. The cold build is untouched and
95
+ // still populates the memo shared with proxy requests.
96
+ onCacheRepair: deps.clearLocalEmbedderMemo,
97
+ log: deps.log,
98
+ })
99
+ .catch((error) =>
100
+ deps.log(
101
+ `[codebuddy-quota] local model prewarm failed: ${String((error as Error)?.message ?? error)}`,
102
+ ),
103
+ )
104
+ }
105
+ return mode
106
+ }
107
+
108
+ export default Plugin.define({
109
+ id: "codebuddy-quota",
110
+ async setup(ctx) {
111
+ const log = createDedupedLogger((line) => console.warn(line), "[codebuddy-quota]")
112
+
113
+ // Restore both sites' credentials from the plugin-owned cache; no CLI auth
114
+ // file is read, and no token ever reaches the GUI.
115
+ const store = createTokenStore()
116
+
117
+ const source = createQuotaSource({
118
+ readForSite: (site, signal) => {
119
+ const timeout = timeoutSignal(UPSTREAM_TIMEOUT_MS)
120
+ return store
121
+ .ensureFresh(site)
122
+ .then((auth) =>
123
+ fetchUpstream({ auth, signal: signal ? anySignal([signal, timeout]) : timeout }),
124
+ )
125
+ },
126
+ })
127
+
128
+ /**
129
+ * Model import: for every site that has an account, fetch its cli-whitelist
130
+ * catalog with that site's JWT and write a dedicated provider block. The
131
+ * legacy `codebuddy` provider is never touched.
132
+ */
133
+ /** Shared inputs for a model import, resolved once per import pass. */
134
+ const importDeps = async () => {
135
+ const config = loadConfig()
136
+ const modelsDev = readModelsDevCatalog()
137
+ const latest = await latestTaggedVersion()
138
+ return {
139
+ target: opencodeConfigPath(),
140
+ config,
141
+ modelsDev,
142
+ packageVersion: latest ?? config.package_version,
143
+ }
144
+ }
145
+
146
+ // GET /v2/models is generated locally from the same mapped catalog the
147
+ // provider import uses, so the advertised ids match what OpenCode can call.
148
+ const models = createModelsSource({
149
+ loadConfig,
150
+ readModelsDevCatalog,
151
+ getAuth: (site) => store.get(site),
152
+ fetchCatalog,
153
+ buildModels,
154
+ log,
155
+ })
156
+
157
+ // One config read feeds both the warmup decision and proxy routing, so the
158
+ // two can never disagree. startPrewarm fires the warmup asynchronously and
159
+ // swallows its failures; it never blocks startup.
160
+ const config = loadConfig()
161
+ const embeddingMode = startPrewarm(config, {
162
+ warmLocalModel, createLocalEmbedder, clearLocalEmbedderMemo, log,
163
+ })
164
+
165
+ /** Import one site's models; reused after login so a new account lands in config. */
166
+ const importSite = async (
167
+ site: Site,
168
+ deps: Awaited<ReturnType<typeof importDeps>>,
169
+ ) => {
170
+ const auth = store.get(site)
171
+ if (!auth) {
172
+ log(`no ${site} account; skipping its model import`)
173
+ return
174
+ }
175
+ try {
176
+ const catalog = await fetchCatalog({ site, auth })
177
+ const models = buildModels({ catalog, config: deps.config, modelsDev: deps.modelsDev, log })
178
+ if (models.length === 0) {
179
+ log(`${site} catalog produced no models; skipping write`)
180
+ return
181
+ }
182
+ const result = writeProvider({
183
+ jsoncPath: deps.target,
184
+ providerId: site === "cn" ? "codebuddy-cn" : "codebuddy-intl",
185
+ models,
186
+ packageVersion: deps.packageVersion,
187
+ proxyPort: PROXY_PORT,
188
+ backup: (path, content) => {
189
+ const backupPath = `${path}.codebuddy-quota.bak`
190
+ try {
191
+ // Only the first backup is kept, so the pre-plugin original survives.
192
+ if (!existsSync(backupPath)) writeFileSync(backupPath, content, "utf8")
193
+ } catch {
194
+ // Backup is best-effort; never block the provider write.
195
+ }
196
+ },
197
+ })
198
+ if (result.status === "skipped") log(`${site} provider write skipped: ${result.reason}`)
199
+ else if (result.status === "written") log(`${site} provider written`)
200
+ } catch (error) {
201
+ log(`${site} model import failed: ${String((error as Error)?.message ?? error)}`)
202
+ }
203
+ }
204
+
205
+ const importModels = async () => {
206
+ const deps = await importDeps()
207
+ for (const site of ["cn", "intl"] as Site[]) await importSite(site, deps)
208
+ }
209
+ // Fire-and-forget: keep a future init failure from becoming an unhandled
210
+ // rejection (importSite already catches its own site-level errors).
211
+ void importModels().catch((error) =>
212
+ log(`model import failed: ${String((error as Error)?.message ?? error)}`),
213
+ )
214
+
215
+ const handlers = makeRpcHandlers({
216
+ store,
217
+ source,
218
+ log,
219
+ afterLogin: async (site) => importSite(site, await importDeps()),
220
+ })
221
+ // Local reverse proxy: providers point here; the proxy injects the current
222
+ // site's JWT on each request. The first plugin instance binds the port; a
223
+ // reload reuses the process-wide server, so there is no dispose/setup
224
+ // listen gap. Port conflicts are logged by the owner and stay non-fatal.
225
+ // The proxy's lazy fallback must target the configured id too, otherwise a
226
+ // request would build a different model from the one prewarm verified.
227
+ let registration: { dispose(): void } | null = null
228
+ const gw = await setupGateway({
229
+ ensureGateway,
230
+ releaseGateway,
231
+ createServer: () =>
232
+ createProxy({
233
+ store, log, models, embeddingMode,
234
+ localEmbeddingModel: config.local_embedding_model,
235
+ }),
236
+ register: async () => {
237
+ const result = await ctx.rpc.register(CodebuddyQuota, handlers)
238
+ registration = result
239
+ return result
240
+ },
241
+ log,
242
+ })
243
+
244
+ return () => {
245
+ registration?.dispose()
246
+ // Only drop our reference; the owner closes the shared server after the
247
+ // last holder is gone and its grace window has elapsed.
248
+ void gw.dispose()
249
+ }
250
+ },
251
+ })