opencode-glm-plugin 0.0.0-stage → 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI码上到
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,99 @@
1
- # Temporary Holding Version
1
+ # opencode-glm-plugin
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
+ [![npm](https://img.shields.io/npm/v/opencode-glm-plugin)](https://www.npmjs.com/package/opencode-glm-plugin)
4
+ [![license](https://img.shields.io/npm/l/opencode-glm-plugin)](./LICENSE)
5
+
6
+ GLM Coding Plan(智谱)额度面板,OpenCode Desktop 插件。
7
+
8
+ 在桌面端 GUI 的右侧边栏添加「GLM 额度」标签页:套餐限额(5 小时窗口 / 周期积分 / 月度工具额度)、是否已限额、今天与最近 7 天 / 30 天用量(Token、调用次数、按模型分解、逐时段趋势图)。另附侧边栏 + 菜单启动项与标题栏用量徽标(悬停显示百分比,点击打开面板)。
9
+
10
+ ## 安装
11
+
12
+ ```sh
13
+ opencode plugin add opencode-glm-plugin@latest
14
+ ```
15
+
16
+ 也可以直接写进全局 `~/.config/opencode/opencode.json`:
17
+
18
+ ```json
19
+ {
20
+ "plugins": ["opencode-glm-plugin@latest"]
21
+ }
22
+ ```
23
+
24
+ `@latest` 让 OpenCode 在启动时检查更新(每 24 小时一次);只写包名则会停在已安装的版本。
25
+
26
+ 装好后打开桌面端:**Settings → Extensions → Plugins** 里能看到它,侧边栏 **+ 菜单 → GLM 额度**,或点标题栏徽标。
27
+
28
+ > 如果之前用本地目录(`file://…/opencode-glm-plugin`)加载过,先把那一项从 `plugins` 里删掉,再添加 npm 包,避免同一个插件被加载两次。
29
+
30
+ API Key 自动从 OpenCode 登录凭据读取(`~/.local/share/opencode/auth.json` 的 `zhipuai-coding-plan`),也可用环境变量 `GLM_API_KEY` 或插件 options 覆盖。
31
+
32
+ ## Options
33
+
34
+ ```json
35
+ {
36
+ "plugins": [
37
+ {
38
+ "package": "opencode-glm-plugin@latest",
39
+ "options": {
40
+ "apiKey": "可选,覆盖 auth.json",
41
+ "baseUrl": "可选,默认 https://open.bigmodel.cn;国际版 https://api.z.ai",
42
+ "organization": "org-xxx,新版积分套餐需要",
43
+ "project": "proj_xxx,新版积分套餐需要",
44
+ "planType": 1
45
+ }
46
+ }
47
+ ]
48
+ }
49
+ ```
50
+
51
+ `planType`:新版积分套餐查询参数(1 个人 / 2 团队)。若面板提示「服务端未返回额度数据」,请到 bigmodel.cn 控制台(DevTools 里 `quota/limit` 请求)抄下 `bigmodel-organization` / `bigmodel-project` 头与 `type` 参数填入。
52
+
53
+ 修改 options 后插件会自动重载,不需要重启应用。
54
+
55
+ ## 数据源
56
+
57
+ - `GET {base}/api/monitor/usage/quota/limit` — 套餐窗口限额与重置时间
58
+ - `GET {base}/api/monitor/usage/model-usage?startTime=&endTime=` — 用量序列与按模型汇总
59
+
60
+ 鉴权:`Authorization: <裸 key>`(无 Bearer 前缀)。
61
+
62
+ ## 兼容性
63
+
64
+ - 面向 OpenCode Desktop **2.4.x**(`@opencode/plugin` 固定 2.4.1)构建。
65
+ - GUI 插件 API 仍标注 experimental,桌面端大版本升级后建议先更新插件。
66
+ - 只支持智谱官方的 GLM Coding Plan 套餐;第三方中转或非官方计费渠道没有对应的用量接口。
67
+
68
+ ## 架构
69
+
70
+ - `src/index.ts` — server 半部(仅声明插件 id)
71
+ - `src/gui.tsx` — `./gui-experimental` 入口,窗口跑 `setup`、Electron 主进程跑 `main`
72
+ - `src/gui/main.ts` — 主进程拉取并缓存数据(Node fetch 无 CORS),经 `Ipc` 契约给窗口
73
+ - `src/gui/window.tsx` — 注册 Panel / MenuItem / TitlebarItem,5 分钟自动刷新
74
+ - `src/gui/panel.tsx` — 额度面板 UI(Solid),进度条 / 倒计时 / SVG 趋势图
75
+
76
+ ## 开发
77
+
78
+ ```sh
79
+ npm install
80
+ npm run dev # vite build --watch,改动后窗口内热重载
81
+ npm run smoke # 用宿主 stub 评估 bundle 并跑真实数据链路
82
+ npm run typecheck
83
+ ```
84
+
85
+ 本地目录加载(开发时):在 `plugins` 里写 `"file://E:/opencodeProject/opencode-glm-plugin"`,改完代码 `npm run dev` 会热重载。
86
+
87
+ ## 发布
88
+
89
+ ```sh
90
+ npm whoami # 先确认已登录
91
+ npm run check # typecheck + build + smoke
92
+ npm publish # prepack 会再跑一遍 typecheck 和 build
93
+ ```
94
+
95
+ `files` 只带 `src` 和 `dist`,`prepack` 保证 tarball 里的 `dist/gui-experimental.cjs` 是最新构建产物。
96
+
97
+ ## License
98
+
99
+ MIT
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const q=require("@opencode/plugin/gui"),L=require("effect"),tt=require("node:fs"),et=require("node:os"),j=require("node:path"),e=require("solid-js/web"),h=require("solid-js"),nt={"panel.title":"GLM Quota","panel.refresh":"Refresh","pill.label":"GLM {{pct}}% used","pill.loading":"GLM …","menu.open":"GLM quota","section.today":"Today","section.quota":"Plan quota","section.7d":"Last 7 days","section.30d":"Last 30 days","usage.tokens":"Tokens","usage.calls":"Calls","usage.models":"By model","usage.empty":"No usage data","chart.byHour":"Hourly","chart.byDay":"Daily","limit.tokens-5h":"5-hour window","limit.credit-5h":"5-hour credits","limit.credit-week":"Weekly credits","limit.credit-month":"Monthly credits","limit.time-month":"Monthly tools (MCP)","limit.other":"Quota","state.used":"Used","state.usedPct":"{{pct}}% used","state.freePct":"{{pct}}% available","state.remaining":"Left","state.limited":"Limited","state.resetIn":"Resets {{time}}","state.loading":"Loading…","state.noKey":"No GLM API key found","state.noKeyHint":"Sign in to the zhipuai-coding-plan provider in OpenCode, or set apiKey in this plugin's options in opencode.json.","state.error":"Request failed","state.empty":"No quota data returned","state.emptyHint":"Newer credit-based plans may need organization, project and planType in this plugin's options (see the bigmodel.cn console).","foot.updated":"Updated {{time}}","foot.auto":"Auto-refreshes every 5 min"},N={"panel.title":"GLM 额度","panel.refresh":"刷新","pill.label":"GLM 已用 {{pct}}%","pill.loading":"GLM …","menu.open":"GLM 额度","section.today":"今天","section.quota":"套餐额度","section.7d":"最近 7 天","section.30d":"最近 30 天","usage.tokens":"Token 用量","usage.calls":"调用次数","usage.models":"按模型","usage.empty":"暂无用量数据","chart.byHour":"按小时","chart.byDay":"按天","limit.tokens-5h":"5 小时窗口","limit.credit-5h":"5 小时积分","limit.credit-week":"每周积分","limit.credit-month":"每月积分","limit.time-month":"月度工具 (MCP)","limit.other":"额度","state.used":"已用","state.usedPct":"已用 {{pct}}%","state.freePct":"可用 {{pct}}%","state.remaining":"剩余","state.limited":"已限额","state.resetIn":"{{time}}重置","state.loading":"加载中…","state.noKey":"未找到 GLM API Key","state.noKeyHint":"请先在 OpenCode 中登录智谱 (zhipuai-coding-plan),或在 opencode.json 的插件 options 里配置 apiKey。","state.error":"请求失败","state.empty":"服务端未返回额度数据","state.emptyHint":"新版积分套餐可能需要在插件 options 里配置 organization / project / planType(见 bigmodel.cn 控制台)。","foot.updated":"更新于 {{time}}","foot.auto":"每 5 分钟自动刷新"},rt=q.Plugin.define({i18n:{en:nt,zh:N,zht:N}}),Y=q.Ipc.define({id:"opencode-glm-plugin.quota",methods:{snapshot:{output:L.Schema.Unknown},refresh:{output:L.Schema.Unknown}}}),it="https://open.bigmodel.cn",ot="https://api.z.ai",D=["zhipuai-coding-plan","zai-coding-plan","zai-coding-cn"],at=/z(ai|hipu)/i;function st(t){if(!t||typeof t!="object")return{};const n=t,r=i=>typeof i=="string"&&i.trim()?i.trim():void 0,o=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{apiKey:r(n.apiKey),baseUrl:r(n.baseUrl),organization:r(n.organization),project:r(n.project),planType:o(n.planType)}}function lt(t){const n=W(),r=t.apiKey??V()??n?.key;if(!r)return{error:"no-key"};let o=t.baseUrl;if(!o){const i=ct(t);o=i&&i.startsWith("zai")&&!i.includes("hipu")?ot:it}return{baseUrl:o.replace(/\/+$/,""),apiKey:r,organization:t.organization,project:t.project,planType:t.planType}}function ct(t){if(!(t.apiKey||V()))return W()?.provider}function V(){for(const t of["GLM_API_KEY","ZHIPU_CODING_PLAN_API_KEY","ZHIPUAI_CODING_PLAN_API_KEY","ZAI_CODING_CN_API_KEY"]){const n=process.env[t];if(n&&n.trim())return n.trim()}}function ut(){const t=et.homedir();return[j.join(t,".local","share","opencode","auth.json"),j.join(t,"Library","Application Support","opencode","auth.json")]}function W(){for(const t of ut()){let n;try{n=JSON.parse(tt.readFileSync(t,"utf8"))}catch{continue}if(!n||typeof n!="object")continue;const r=n,o=[...D,...Object.keys(r)];for(const i of o){const a=r[i],c=a&&typeof a=="object"&&"key"in a&&typeof a.key=="string"?a.key.trim():void 0;if(c&&(D.includes(i)||at.test(i)))return{key:c,provider:i}}}}class Q extends Error{constructor(){super("no quota limits in response")}}const S=t=>String(t).padStart(2,"0");function E(t){return`${t.getFullYear()}-${S(t.getMonth()+1)}-${S(t.getDate())} ${S(t.getHours())}:${S(t.getMinutes())}:${S(t.getSeconds())}`}async function Z(t,n){const r={Authorization:t.apiKey,"Content-Type":"application/json","Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8"};t.organization&&(r["bigmodel-organization"]=t.organization),t.project&&(r["bigmodel-project"]=t.project);const o=await fetch(n,{headers:r}),i=await o.json().catch(()=>{});if(!o.ok)throw new Error(i?.msg??`HTTP ${o.status}`);if(!i||i.success===!1||typeof i.code=="number"&&i.code!==200)throw new Error(i?.msg??"unexpected response");return i.data}async function dt(t){const n=t.planType===void 0?"":`?type=${t.planType}`,r=await Z(t,`${t.baseUrl}/api/monitor/usage/quota/limit${n}`),o=Array.isArray(r?.limits)?r.limits:[];if(o.length===0)throw new Q;const i=o.map((a,c)=>mt(a,c));return{level:typeof r?.level=="string"?r.level:void 0,limits:i}}function mt(t,n){const r=typeof t.type=="string"?t.type:"",o=typeof t.unit=="number"?t.unit:void 0,i=z(t.usage),a=z(t.currentValue),c=z(t.remaining),l=z(t.percentage)??(i&&i>0&&a!==void 0?a/i*100:void 0);let m="other";return r==="TOKENS_LIMIT"?m="tokens-5h":r==="CREDIT_LIMIT"?m=o===6?"credit-week":o===5?"credit-month":"credit-5h":r==="TIME_LIMIT"&&(m="time-month"),{id:`${r||"limit"}-${o??"x"}-${n}`,kind:m,percentage:l,usage:i,currentValue:a,remaining:c,nextResetTime:z(t.nextResetTime)}}function z(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}async function U(t,n){const r=new Date,o=new Date(r.getTime()-n*864e5);return J(t,o,r,96)}async function gt(t){const n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate());return J(t,r,n,0)}async function J(t,n,r,o){const i=`startTime=${encodeURIComponent(E(n))}&endTime=${encodeURIComponent(E(r))}`,a=await Z(t,`${t.baseUrl}/api/monitor/usage/model-usage?${i}`),c=Array.isArray(a?.x_time)?a.x_time:[],s=Array.isArray(a?.tokensUsage)?a.tokensUsage:[],l=c.map((d,g)=>({time:d,tokens:Number(s[g]??0)})),m=a?.totalUsage??{},p=Array.isArray(a?.modelSummaryList)?a.modelSummaryList.map(d=>({name:String(d.modelName??"?"),tokens:Number(d.totalTokens??0)})).sort((d,g)=>g.tokens-d.tokens):[],u=l.reduce((d,g)=>d+g.tokens,0);return{totalTokens:typeof m.totalTokensUsage=="number"?m.totalTokensUsage:u,totalCalls:typeof m.totalModelCallCount=="number"?m.totalModelCallCount:0,granularity:typeof a?.granularity=="string"?a.granularity:"hourly",buckets:o>0?pt(l,o):l,models:p}}function pt(t,n){if(t.length<=n)return t;const r=Math.ceil(t.length/n),o=[];for(let i=0;i<t.length;i+=r){const a=t.slice(i,i+r);o.push({time:a[0].time,tokens:a.reduce((c,s)=>c+s.tokens,0)})}return o}async function ht(t){const n=st(t),r=Date.now();try{const o=lt(n);if("error"in o)return{status:"no-key",limits:[],fetchedAt:r};const[i,a,c,s]=await Promise.all([dt(o),gt(o).catch(()=>{}),U(o,7).catch(()=>{}),U(o,30).catch(()=>{})]);return{status:"ok",level:i.level,limits:i.limits,usageToday:a,usage7d:c,usage30d:s,fetchedAt:r}}catch(o){return o instanceof Q?{status:"empty",hint:"org-project",limits:[],fetchedAt:r}:{status:"error",message:o instanceof Error?o.message:String(o),limits:[],fetchedAt:r}}}const ft=9e4,vt=t=>{let n,r;const o=a=>{const c=n?Date.now()-n.fetchedAt:Number.POSITIVE_INFINITY;return!a&&n&&c<ft?Promise.resolve(n):r||(r=ht(t.options).then(s=>(n=s,s)).finally(()=>{r=void 0}),r)},i=t.provide(Y,{snapshot:()=>o(!1),refresh:()=>o(!0)});return o(!1).catch(()=>{}),()=>i.dispose()},[bt,yt]=h.createSignal(void 0),[K,R]=h.createSignal(!1);let P,M;const x={snapshot:bt,busy:K,attach(t){P=t},pull(t){if(!P||K())return;R(!0),(t?P.refresh():P.snapshot()).then(r=>yt(r)).catch(()=>{}).finally(()=>R(!1))},start(t){this.pull(!1),M||(M=setInterval(()=>this.pull(!1),t))},stop(){M&&clearInterval(M),M=void 0}},I=340;function xt(t){if(t!==void 0)return t>=95?"danger":t>=80?"warn":"ok"}function qt(t){if(t==="danger")return"var(--icon-critical-base, #e5484d)";if(t==="warn")return"var(--icon-warning-base, #f5a524)";if(t==="ok")return"var(--icon-success-base, #46a758)"}function H(t){if(!t||t.status!=="ok")return;const n=["tokens-5h","credit-5h","credit-week","credit-month","time-month","other"];for(const r of n){const o=t.limits.find(i=>i.kind===r);if(o?.percentage!==void 0)return o.percentage}return t.limits.find(r=>r.percentage!==void 0)?.percentage}function $t(t){return t?t.limits.some(n=>(n.percentage??0)>=100):!1}function $(t,n){return Number.isFinite(t)?n?t>=1e8?`${T(t/1e8)} 亿`:t>=1e4?`${T(t/1e4)} 万`:String(Math.round(t)):t>=1e9?`${T(t/1e9)}B`:t>=1e6?`${T(t/1e6)}M`:t>=1e3?`${T(t/1e3)}K`:String(Math.round(t)):"0"}function T(t){return t>=100?String(Math.round(t)):t.toFixed(1).replace(/\.0$/,"")}function kt(t,n){if(t<=0)return n?"即将重置":"any moment";const r=Math.round(t/6e4);if(r<60)return n?`${Math.max(1,r)} 分钟`:`${Math.max(1,r)} min`;const o=Math.round(r/60);if(o<48)return n?`${o} 小时`:`${o} h`;const i=Math.round(o/24);return n?`${i} 天`:`${i} d`}var wt=e.template("<span class=glmq-level>"),_t=e.template("<span class=glmq-flag>"),Ct=e.template("<div class=glmq><header class=glmq-head><span class=glmq-title></span><button type=button class=glmq-refresh>"),St=e.template("<div class=glmq-body><section class=glmq-card><div class=glmq-card-title></div></section><footer class=glmq-foot> · "),F=e.template("<div class=glmq-status-detail>"),zt=e.template("<div class=glmq-card><div class=glmq-status><div class=glmq-status-title>"),X=e.template("<span>"),Mt=e.template("<div class=glmq-limit><div class=glmq-limit-head><span class=glmq-limit-name></span><span class=glmq-limit-pct></span></div><div class=glmq-bar role=progressbar><div class=glmq-fill></div></div><div class=glmq-sub><span>"),Tt=e.template("<span class=glmq-gran>"),It=e.template("<div class=glmq-totals><div class=glmq-total><b></b><span></span></div><div class=glmq-total><b></b><span>"),Pt=e.template("<div class=glmq-models><div class=glmq-models-title>"),At=e.template("<section class=glmq-card><div class=glmq-card-row><div class=glmq-card-title>"),Lt=e.template("<div class=glmq-none>"),jt=e.template("<div class=glmq-chart><div class=glmq-plot><div class=glmq-gutter></div><div class=glmq-area><svg class=glmq-bars preserveAspectRatio=none aria-hidden=true></svg></div></div><div class=glmq-xlabels>"),Nt=e.template("<span class=glmq-ylabel>"),Dt=e.template("<span class=glmq-gridline>"),Et=e.template("<svg><rect width=0.82 rx=0.25 fill=currentColor><title></svg>",!1,!0,!1),Ut=e.template("<div class=glmq-model><div class=glmq-model-head><span class=glmq-model-name></span><span class=glmq-model-tokens></span></div><span class=glmq-model-bar><span class=glmq-model-fill>");const Kt=6e4;function Rt(){const t=q.usePlugin(),n=()=>t.locale.locale().startsWith("zh"),r=()=>{const s=t.layout.side.width("quota");(s===void 0||s>I)&&t.layout.side.resize("quota",I)},[o,i]=h.createSignal(Date.now());h.onMount(()=>{const s=setInterval(()=>i(Date.now()),1e3);h.onCleanup(()=>clearInterval(s)),r();const l=x.snapshot();(!l||Date.now()-l.fetchedAt>Kt)&&x.pull(!0)});const a=()=>x.snapshot(),c=()=>$t(a());return(()=>{var s=Ct(),l=s.firstChild,m=l.firstChild,p=m.nextSibling;return e.insert(m,()=>t.t("panel.title")),e.insert(l,e.createComponent(h.Show,{get when(){return a()?.level},get children(){var u=wt();return e.insert(u,()=>a().level),u}}),p),e.insert(l,e.createComponent(h.Show,{get when(){return c()},get children(){var u=_t();return e.insert(u,()=>t.t("state.limited")),u}}),p),p.$$click=()=>x.pull(!0),e.insert(p,e.createComponent(t.ui.Icon,{name:"refresh",size:"small"})),e.insert(s,e.createComponent(h.Show,{get when(){return a()},get fallback(){return e.createComponent(G,{kind:"loading"})},children:u=>e.createComponent(h.Show,{get when(){return u().status==="ok"},get fallback(){return e.createComponent(G,{get kind(){return u().status},get message(){return u().message}})},get children(){var d=St(),g=d.firstChild,b=g.firstChild,v=g.nextSibling,f=v.firstChild;return e.insert(b,()=>t.t("section.quota")),e.insert(g,e.createComponent(h.For,{get each(){return u().limits},children:y=>e.createComponent(Ht,{limit:y,get now(){return o()},get zh(){return n()}})}),null),e.insert(d,e.createComponent(A,{get title(){return t.t("section.today")},get range(){return u().usageToday},get zh(){return n()},chart:{minSpan:24,hourTicks:!0}}),v),e.insert(d,e.createComponent(A,{get title(){return t.t("section.7d")},get range(){return u().usage7d},get zh(){return n()}}),v),e.insert(d,e.createComponent(A,{get title(){return t.t("section.30d")},get range(){return u().usage30d},get zh(){return n()}}),v),e.insert(v,()=>t.t("foot.updated",{time:Yt(u().fetchedAt)}),f),e.insert(v,()=>t.t("foot.auto"),null),d}})}),null),e.effect(u=>{var d=t.t("panel.refresh"),g=t.t("panel.refresh"),b=x.busy();return d!==u.e&&e.setAttribute(p,"title",u.e=d),g!==u.t&&e.setAttribute(p,"aria-label",u.t=g),b!==u.a&&(p.disabled=u.a=b),u},{e:void 0,t:void 0,a:void 0}),s})()}function G(t){const n=q.usePlugin(),r=()=>{if(t.kind==="no-key")return n.t("state.noKeyHint");if(t.kind==="empty")return n.t("state.emptyHint")},o=()=>t.kind==="loading"?n.t("state.loading"):t.kind==="no-key"?n.t("state.noKey"):t.kind==="empty"?n.t("state.empty"):n.t("state.error");return(()=>{var i=zt(),a=i.firstChild,c=a.firstChild;return e.insert(c,o),e.insert(a,e.createComponent(h.Show,{get when(){return t.message},get children(){var s=F();return e.insert(s,()=>t.message),s}}),null),e.insert(a,e.createComponent(h.Show,{get when(){return r()},get children(){var s=F();return e.insert(s,r),s}}),null),e.effect(()=>a.classList.toggle("glmq-status-error",t.kind==="error")),i})()}function Ht(t){const n=q.usePlugin(),r=()=>t.limit.percentage,o=()=>xt(r()),i=()=>qt(o())??"var(--v2-icon-icon-accent)",a=()=>{const l=t.limit.nextResetTime;if(l)return n.t("state.resetIn",{time:kt(l-t.now,t.zh)})},s=()=>{const l=t.limit.currentValue,m=t.limit.usage,p=t.limit.remaining,u=[];return l!==void 0&&m!==void 0&&m>0?u.push(`${n.t("state.used")} ${$(l,t.zh)} / ${$(m,t.zh)}`):p!==void 0&&m!==void 0&&m>0?u.push(`${n.t("state.remaining")} ${$(p,t.zh)}`):r()!==void 0&&u.push(n.t("state.freePct",{pct:100-Math.round(r())})),u.join(" · ")};return(()=>{var l=Mt(),m=l.firstChild,p=m.firstChild,u=p.nextSibling,d=m.nextSibling,g=d.firstChild,b=d.nextSibling,v=b.firstChild;return e.insert(p,()=>n.t(`limit.${t.limit.kind}`)),e.insert(u,(()=>{var f=e.memo(()=>r()!==void 0);return()=>f()?n.t("state.usedPct",{pct:Math.round(r())}):"—"})()),e.insert(v,()=>s()||" "),e.insert(b,e.createComponent(h.Show,{get when(){return a()},get children(){var f=X();return e.insert(f,a),f}}),null),e.effect(f=>{var y=i(),w=r()!==void 0?Math.round(r()):void 0,_=`${Math.min(100,Math.max(0,r()??0))}%`,C=i();return y!==f.e&&e.setStyleProperty(u,"color",f.e=y),w!==f.t&&e.setAttribute(d,"aria-valuenow",f.t=w),_!==f.a&&e.setStyleProperty(g,"width",f.a=_),C!==f.o&&e.setStyleProperty(g,"background",f.o=C),f},{e:void 0,t:void 0,a:void 0,o:void 0}),l})()}function A(t){const n=q.usePlugin(),r=()=>!!t.range&&(t.range.totalTokens>0||t.range.totalCalls>0),o=()=>t.range?.granularity==="daily";return(()=>{var i=At(),a=i.firstChild,c=a.firstChild;return e.insert(c,()=>t.title),e.insert(a,e.createComponent(h.Show,{get when(){return r()},get children(){var s=Tt();return e.insert(s,(()=>{var l=e.memo(()=>!!o());return()=>l()?n.t("chart.byDay"):n.t("chart.byHour")})()),s}}),null),e.insert(i,e.createComponent(h.Show,{get when(){return r()},get fallback(){return(()=>{var s=Lt();return e.insert(s,()=>n.t("usage.empty")),s})()},get children(){return[(()=>{var s=It(),l=s.firstChild,m=l.firstChild,p=m.nextSibling,u=l.nextSibling,d=u.firstChild,g=d.nextSibling;return e.insert(m,()=>$(t.range.totalTokens,t.zh)),e.insert(p,()=>n.t("usage.tokens")),e.insert(d,()=>Bt(t.range.totalCalls)),e.insert(g,()=>n.t("usage.calls")),s})(),e.createComponent(Ft,{get buckets(){return t.range.buckets},get zh(){return t.zh},get span(){return t.chart}}),e.createComponent(h.Show,{get when(){return t.range.models.length>0},get children(){var s=Pt(),l=s.firstChild;return e.insert(l,()=>n.t("usage.models")),e.insert(s,e.createComponent(h.For,{get each(){return t.range.models.slice(0,5)},children:m=>e.createComponent(Ot,{get name(){return m.name},get tokens(){return m.tokens},get total(){return t.range.totalTokens},get zh(){return t.zh}})}),null),s}})]}}),null),i})()}function Ft(t){const n=()=>t.buckets.length,r=()=>Math.max(1,...t.buckets.map(c=>c.tokens)),o=()=>Math.max(n(),t.span?.minSpan??1),i=()=>[{top:"0%",label:$(r(),t.zh)},{top:"50%",label:$(r()/2,t.zh)},{top:"100%",label:"0"}],a=()=>{const c=n();if(c===0)return[];const s=c<8?c===1?[0]:[0,c-1]:[0,Math.round((c-1)/3),Math.round((c-1)*2/3),c-1];return[...new Set(s)].map(l=>({index:l,label:Gt(t.buckets[l].time,t.span?.hourTicks)}))};return(()=>{var c=jt(),s=c.firstChild,l=s.firstChild,m=l.nextSibling,p=m.firstChild,u=s.nextSibling;return e.insert(l,e.createComponent(h.For,{get each(){return i()},children:d=>(()=>{var g=Nt();return e.insert(g,()=>d.label),e.effect(b=>e.setStyleProperty(g,"top",d.top)),g})()})),e.insert(m,e.createComponent(h.For,{get each(){return i()},children:d=>(()=>{var g=Dt();return e.effect(b=>e.setStyleProperty(g,"top",d.top)),g})()}),p),e.insert(p,e.createComponent(h.For,{get each(){return t.buckets},children:(d,g)=>{const b=()=>Math.max(d.tokens>0?1.5:0,d.tokens/r()*97);return(()=>{var v=Et(),f=v.firstChild;return e.insert(f,()=>`${d.time} · ${$(d.tokens,t.zh)}`),e.effect(y=>{var w=g()+.09,_=100-b(),C=b();return w!==y.e&&e.setAttribute(v,"x",y.e=w),_!==y.t&&e.setAttribute(v,"y",y.t=_),C!==y.a&&e.setAttribute(v,"height",y.a=C),y},{e:void 0,t:void 0,a:void 0}),v})()}})),e.insert(u,e.createComponent(h.For,{get each(){return a()},children:d=>(()=>{var g=X();return e.insert(g,()=>d.label),g})()})),e.effect(()=>e.setAttribute(p,"viewBox",`0 0 ${o()} 100`)),c})()}function Gt(t,n){return n&&t.slice(11,16)||O(t)}function Ot(t){const n=()=>t.total>0?Math.max(2,t.tokens/t.total*100):0;return(()=>{var r=Ut(),o=r.firstChild,i=o.firstChild,a=i.nextSibling,c=o.nextSibling,s=c.firstChild;return e.insert(i,()=>t.name),e.insert(a,()=>$(t.tokens,t.zh)),e.effect(l=>{var m=t.name,p=`${n()}%`;return m!==l.e&&e.setAttribute(i,"title",l.e=m),p!==l.t&&e.setStyleProperty(s,"width",l.t=p),l},{e:void 0,t:void 0}),r})()}function O(t){const n=t.slice(5,10);return n.includes("-")?n.replace("-","/"):n}function Bt(t){return new Intl.NumberFormat(void 0,{notation:t>=1e5?"compact":"standard"}).format(t)}function Yt(t){return new Date(t).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}e.delegateEvents(["click"]);const Vt=".glmq{display:flex;flex-direction:column;gap:10px;padding:12px;font-size:12px;line-height:1.45;color:var(--v2-text-text-base);height:100%;overflow-y:auto}.glmq-head{display:flex;align-items:center;gap:6px;padding:0 2px}.glmq-title{font-weight:620;font-size:12px}.glmq-level{padding:1px 7px;border-radius:999px;background:var(--v2-background-bg-deep);color:var(--v2-text-text-muted);font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.glmq-flag{padding:1px 7px;border-radius:999px;background:color-mix(in srgb,var(--icon-critical-base, #e5484d) 14%,transparent);color:var(--icon-critical-base, #e5484d);font-size:10px;font-weight:600}.glmq-refresh{margin-left:auto;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;border:none;border-radius:6px;background:none;color:var(--v2-icon-icon-base);cursor:pointer}.glmq-refresh:hover:not(:disabled){background:var(--v2-background-bg-deep);color:var(--v2-icon-icon-accent)}.glmq-refresh:disabled{opacity:.45;cursor:default}.glmq-body{display:flex;flex-direction:column;gap:10px}.glmq-card{display:flex;flex-direction:column;gap:8px;padding:10px 12px 12px;border:1px solid var(--v2-border-border-muted, transparent);border-radius:10px;background:color-mix(in srgb,var(--v2-background-bg-deep) 55%,transparent)}.glmq-card-row{display:flex;align-items:baseline;justify-content:space-between;gap:8px}.glmq-card-title{font-size:11px;font-weight:620;color:var(--v2-text-text-muted)}.glmq-gran{font-size:10px;color:var(--v2-text-text-faint)}.glmq-limit+.glmq-limit{border-top:1px solid var(--v2-border-border-muted, transparent);padding-top:10px;margin-top:2px}.glmq-limit-head{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:5px}.glmq-limit-name{color:var(--v2-text-text-base)}.glmq-limit-pct{font-variant-numeric:tabular-nums;font-weight:620}.glmq-bar{height:6px;border-radius:999px;background:var(--v2-background-bg-deep);overflow:hidden}.glmq-fill{height:100%;border-radius:999px;transition:width .3s ease}.glmq-sub{display:flex;justify-content:space-between;gap:8px;margin-top:4px;font-size:11px;color:var(--v2-text-text-muted);min-height:1em}.glmq-totals{display:flex;gap:18px}.glmq-total b{display:block;font-size:15px;font-weight:620;font-variant-numeric:tabular-nums}.glmq-total span{font-size:10px;color:var(--v2-text-text-muted)}.glmq-chart{display:flex;flex-direction:column;margin-top:2px}.glmq-plot{position:relative;display:flex;height:84px;margin-top:10px}.glmq-gutter{position:relative;flex:none;width:36px}.glmq-ylabel{position:absolute;right:5px;transform:translateY(-50%);font-size:9px;line-height:1;color:var(--v2-text-text-faint);white-space:nowrap;font-variant-numeric:tabular-nums;pointer-events:none}.glmq-area{position:relative;flex:1;min-width:0}.glmq-gridline{position:absolute;left:0;right:0;height:1px;background:color-mix(in srgb,var(--v2-border-border-muted, currentColor) 45%,transparent);pointer-events:none}.glmq-bars{position:absolute;inset:0;width:100%;height:100%;display:block;color:var(--v2-icon-icon-accent);opacity:.9}.glmq-xlabels{display:flex;justify-content:space-between;margin-top:3px;margin-left:36px;font-size:9px;line-height:1;color:var(--v2-text-text-faint);font-variant-numeric:tabular-nums}.glmq-models{margin-top:4px;display:flex;flex-direction:column;gap:7px}.glmq-models-title{font-size:10px;color:var(--v2-text-text-faint)}.glmq-model{display:flex;flex-direction:column;gap:3px;font-size:11px}.glmq-model-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}.glmq-model-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--v2-text-text-base)}.glmq-model-bar{display:block;width:100%;height:4px;border-radius:999px;background:var(--v2-background-bg-deep);overflow:hidden}.glmq-model-fill{display:block;height:100%;border-radius:999px;background:var(--v2-icon-icon-accent)}.glmq-model-tokens{flex:none;font-variant-numeric:tabular-nums;color:var(--v2-text-text-muted);text-align:end}.glmq-none{font-size:11px;color:var(--v2-text-text-faint)}.glmq-status-title{font-weight:620;color:var(--v2-text-text-base);margin-bottom:4px}.glmq-status-detail{font-size:11px;margin-top:4px;color:var(--v2-text-text-muted)}.glmq-status-error .glmq-status-title{color:var(--icon-critical-base, #e5484d)}.glmq-foot{font-size:10px;color:var(--v2-text-text-faint);padding:0 2px}",Wt=5*6e4,k="quota";function B(t){const n=t.layout.side.width(k);(n===void 0||n>I)&&t.layout.side.resize(k,I)}const Qt=t=>{if(!t.desktop)return;x.attach(t.main(Y)),x.start(Wt),h.onCleanup(()=>x.stop()),B(t),t.add(q.Style,Vt);const n=()=>{const o=t.sessions.current();o&&t.layout.open(`${t.id}:${k}`,o)},r={id:k,get title(){return t.t("panel.title")},closable:"compact"};t.add(q.Panel,{id:k,region:"side",width:I,list:o=>o.open.includes(k)?[r]:[],focus:()=>B(t),render:()=>e.createComponent(Rt,{})}),t.add(q.MenuItem,()=>{const o=t.sessions.current(),i=H(x.snapshot());return{menu:"session.panel",id:"open",get title(){return t.t("menu.open")},icon:"status",...i!==void 0?{description:t.t("state.usedPct",{pct:Math.round(i)})}:{},opened:!!o&&t.layout.state(`${t.id}:${k}`,o)!=="closed",run:n}}),t.add(q.TitlebarItem,()=>{const o=x.snapshot(),i=H(o);return i===void 0?x.busy()&&!o?{id:"quota",label:t.t("pill.loading"),icon:"status",busy:!0,run:n}:void 0:{id:"quota",label:t.t("pill.label",{pct:Math.round(i)}),icon:"status",busy:x.busy(),run:n}})},Zt=q.Plugin.define({...rt,setup:Qt,main:vt});exports.default=Zt;
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "opencode-glm-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "GLM Coding Plan quota panel for OpenCode Desktop: plan limits, rate-limit status, 7-day and 30-day usage.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "huanlis",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/huanlis/opencode-glm-plugin.git"
11
+ },
12
+ "homepage": "https://github.com/huanlis/opencode-glm-plugin#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/huanlis/opencode-glm-plugin/issues"
15
+ },
16
+ "keywords": [
17
+ "opencode",
18
+ "opencode-plugin",
19
+ "glm",
20
+ "zhipu",
21
+ "bigmodel",
22
+ "coding-plan",
23
+ "quota",
24
+ "usage"
25
+ ],
26
+ "exports": {
27
+ ".": "./src/index.ts",
28
+ "./gui-experimental": "./dist/gui-experimental.cjs"
29
+ },
30
+ "files": [
31
+ "src",
32
+ "dist"
33
+ ],
34
+ "scripts": {
35
+ "build": "vite build",
36
+ "dev": "vite build --watch",
37
+ "smoke": "node scripts/smoke.cjs",
38
+ "typecheck": "tsc --noEmit",
39
+ "check": "npm run typecheck && npm run build && npm run smoke",
40
+ "prepack": "npm run typecheck && npm run build"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@opencode/plugin": "2.4.1"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^24",
50
+ "effect": "4.1.0",
51
+ "solid-js": "^1.9.0",
52
+ "typescript": "^5.9.0",
53
+ "vite": "^7.0.0",
54
+ "vite-plugin-solid": "^2.11.0"
55
+ }
56
+ }
@@ -0,0 +1,328 @@
1
+ import fs from "node:fs"
2
+ import os from "node:os"
3
+ import path from "node:path"
4
+
5
+ /**
6
+ * BigModel (GLM Coding Plan) usage endpoints and response shapes.
7
+ * Runs only in the desktop app's main process: plain Node fetch, no CORS.
8
+ */
9
+
10
+ /** Options a user may set on the plugin entry in `opencode.json`. */
11
+ export interface GlmOptions {
12
+ readonly apiKey?: string
13
+ readonly baseUrl?: string
14
+ readonly organization?: string
15
+ readonly project?: string
16
+ /** Plan type query for reformed credit plans: 1 personal, 2 team. */
17
+ readonly planType?: number
18
+ }
19
+
20
+ export interface GlmConfig {
21
+ readonly baseUrl: string
22
+ readonly apiKey: string
23
+ readonly organization?: string
24
+ readonly project?: string
25
+ readonly planType?: number
26
+ }
27
+
28
+ /** One quota line: a window the plan meters, e.g. the 5-hour token window. */
29
+ export interface QuotaLimit {
30
+ readonly id: string
31
+ readonly kind: "tokens-5h" | "credit-5h" | "credit-week" | "credit-month" | "time-month" | "other"
32
+ /** Used percentage, 0-100, when the server reports or implies one. */
33
+ readonly percentage?: number
34
+ readonly usage?: number
35
+ readonly currentValue?: number
36
+ readonly remaining?: number
37
+ /** Epoch ms when the window resets. */
38
+ readonly nextResetTime?: number
39
+ }
40
+
41
+ export interface UsageBucket {
42
+ readonly time: string
43
+ readonly tokens: number
44
+ }
45
+
46
+ export interface UsageRange {
47
+ readonly totalTokens: number
48
+ readonly totalCalls: number
49
+ readonly granularity: string
50
+ readonly buckets: readonly UsageBucket[]
51
+ readonly models: readonly { readonly name: string; readonly tokens: number }[]
52
+ }
53
+
54
+ export type SnapshotStatus = "ok" | "no-key" | "error" | "empty"
55
+
56
+ export interface Snapshot {
57
+ readonly status: SnapshotStatus
58
+ readonly message?: string
59
+ /** Extra guidance the panel renders for `empty` (new credit plans) states. */
60
+ readonly hint?: "org-project"
61
+ readonly level?: string
62
+ readonly limits: readonly QuotaLimit[]
63
+ readonly usageToday?: UsageRange
64
+ readonly usage7d?: UsageRange
65
+ readonly usage30d?: UsageRange
66
+ readonly fetchedAt: number
67
+ }
68
+
69
+ const ZHIPU_BASE = "https://open.bigmodel.cn"
70
+ const ZAI_BASE = "https://api.z.ai"
71
+ /** Provider ids in auth.json whose key talks to the GLM coding plan. */
72
+ const PROVIDER_IDS = ["zhipuai-coding-plan", "zai-coding-plan", "zai-coding-cn"]
73
+ const PROVIDER_PATTERN = /z(ai|hipu)/i
74
+
75
+ /** Reads the plugin entry's options loosely, so a malformed entry never throws. */
76
+ export function readOptions(raw: unknown): GlmOptions {
77
+ if (!raw || typeof raw !== "object") return {}
78
+ const o = raw as Record<string, unknown>
79
+ const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined)
80
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined)
81
+ return {
82
+ apiKey: str(o.apiKey),
83
+ baseUrl: str(o.baseUrl),
84
+ organization: str(o.organization),
85
+ project: str(o.project),
86
+ planType: num(o.planType),
87
+ }
88
+ }
89
+
90
+ /** Key resolution: plugin options, then environment, then opencode's auth.json. */
91
+ export function resolveConfig(options: GlmOptions): GlmConfig | { error: "no-key" } {
92
+ const fromAuth = readAuthKey()
93
+ const apiKey = options.apiKey ?? readEnvKey() ?? fromAuth?.key
94
+ if (!apiKey) return { error: "no-key" }
95
+
96
+ let baseUrl = options.baseUrl
97
+ if (!baseUrl) {
98
+ const provider = authProviderId(options)
99
+ baseUrl = provider && provider.startsWith("zai") && !provider.includes("hipu") ? ZAI_BASE : ZHIPU_BASE
100
+ }
101
+
102
+ return {
103
+ baseUrl: baseUrl.replace(/\/+$/, ""),
104
+ apiKey,
105
+ organization: options.organization,
106
+ project: options.project,
107
+ planType: options.planType,
108
+ }
109
+ }
110
+
111
+ function authProviderId(options: GlmOptions): string | undefined {
112
+ if (options.apiKey || readEnvKey()) return undefined
113
+ return readAuthKey()?.provider
114
+ }
115
+
116
+ function readEnvKey(): string | undefined {
117
+ for (const name of ["GLM_API_KEY", "ZHIPU_CODING_PLAN_API_KEY", "ZHIPUAI_CODING_PLAN_API_KEY", "ZAI_CODING_CN_API_KEY"]) {
118
+ const value = process.env[name]
119
+ if (value && value.trim()) return value.trim()
120
+ }
121
+ return undefined
122
+ }
123
+
124
+ function authPaths(): string[] {
125
+ const home = os.homedir()
126
+ return [
127
+ path.join(home, ".local", "share", "opencode", "auth.json"),
128
+ // macOS app-sandboxed default, just in case.
129
+ path.join(home, "Library", "Application Support", "opencode", "auth.json"),
130
+ ]
131
+ }
132
+
133
+ function readAuthKey(): { key: string; provider: string } | undefined {
134
+ for (const file of authPaths()) {
135
+ let auth: unknown
136
+ try {
137
+ auth = JSON.parse(fs.readFileSync(file, "utf8"))
138
+ } catch {
139
+ continue
140
+ }
141
+ if (!auth || typeof auth !== "object") continue
142
+ const entries = auth as Record<string, unknown>
143
+ const ids = [...PROVIDER_IDS, ...Object.keys(entries)]
144
+ for (const id of ids) {
145
+ const entry = entries[id]
146
+ const key =
147
+ entry && typeof entry === "object" && "key" in entry && typeof (entry as { key?: unknown }).key === "string"
148
+ ? (entry as { key: string }).key.trim()
149
+ : undefined
150
+ if (key && (PROVIDER_IDS.includes(id) || PROVIDER_PATTERN.test(id))) return { key, provider: id }
151
+ }
152
+ }
153
+ return undefined
154
+ }
155
+
156
+ class EmptyQuotaError extends Error {
157
+ constructor() {
158
+ super("no quota limits in response")
159
+ }
160
+ }
161
+
162
+ const pad = (n: number) => String(n).padStart(2, "0")
163
+
164
+ /** The endpoints take local time as `yyyy-MM-dd HH:mm:ss`. */
165
+ function formatLocal(date: Date): string {
166
+ return (
167
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
168
+ ` ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
169
+ )
170
+ }
171
+
172
+ async function getJson(config: GlmConfig, url: string): Promise<unknown> {
173
+ const headers: Record<string, string> = {
174
+ Authorization: config.apiKey,
175
+ "Content-Type": "application/json",
176
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
177
+ }
178
+ if (config.organization) headers["bigmodel-organization"] = config.organization
179
+ if (config.project) headers["bigmodel-project"] = config.project
180
+
181
+ const response = await fetch(url, { headers })
182
+ const body = (await response.json().catch(() => undefined)) as
183
+ | { code?: number; msg?: string; success?: boolean; data?: unknown }
184
+ | undefined
185
+
186
+ if (!response.ok) throw new Error(body?.msg ?? `HTTP ${response.status}`)
187
+ if (!body || body.success === false || (typeof body.code === "number" && body.code !== 200))
188
+ throw new Error(body?.msg ?? "unexpected response")
189
+ return body.data
190
+ }
191
+
192
+ /** `/api/monitor/usage/quota/limit`: every window the plan meters. */
193
+ async function fetchQuota(config: GlmConfig): Promise<{ level?: string; limits: QuotaLimit[] }> {
194
+ const query = config.planType === undefined ? "" : `?type=${config.planType}`
195
+ const data = (await getJson(config, `${config.baseUrl}/api/monitor/usage/quota/limit${query}`)) as
196
+ | { level?: string; limits?: unknown }
197
+ | undefined
198
+
199
+ const raw = Array.isArray(data?.limits) ? (data!.limits as Record<string, unknown>[]) : []
200
+ if (raw.length === 0) throw new EmptyQuotaError()
201
+
202
+ const limits = raw.map((entry, index) => toLimit(entry, index))
203
+ return { level: typeof data?.level === "string" ? data.level : undefined, limits }
204
+ }
205
+
206
+ function toLimit(entry: Record<string, unknown>, index: number): QuotaLimit {
207
+ const type = typeof entry.type === "string" ? entry.type : ""
208
+ const unit = typeof entry.unit === "number" ? entry.unit : undefined
209
+ const usage = num(entry.usage)
210
+ const current = num(entry.currentValue)
211
+ const remaining = num(entry.remaining)
212
+ const reported = num(entry.percentage)
213
+ const percentage = reported ?? (usage && usage > 0 && current !== undefined ? (current / usage) * 100 : undefined)
214
+
215
+ let kind: QuotaLimit["kind"] = "other"
216
+ if (type === "TOKENS_LIMIT") kind = "tokens-5h"
217
+ else if (type === "CREDIT_LIMIT") kind = unit === 6 ? "credit-week" : unit === 5 ? "credit-month" : "credit-5h"
218
+ else if (type === "TIME_LIMIT") kind = "time-month"
219
+
220
+ return {
221
+ id: `${type || "limit"}-${unit ?? "x"}-${index}`,
222
+ kind,
223
+ percentage,
224
+ usage,
225
+ currentValue: current,
226
+ remaining,
227
+ nextResetTime: num(entry.nextResetTime),
228
+ }
229
+ }
230
+
231
+ function num(value: unknown): number | undefined {
232
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined
233
+ }
234
+
235
+ /** `/api/monitor/usage/model-usage`: buckets, totals and a per-model breakdown. */
236
+ async function fetchUsage(config: GlmConfig, days: number): Promise<UsageRange> {
237
+ const end = new Date()
238
+ const start = new Date(end.getTime() - days * 86_400_000)
239
+ return fetchUsageBetween(config, start, end, 96)
240
+ }
241
+
242
+ /** Today since local midnight; the chart grows across a fixed 24-bucket day. */
243
+ async function fetchToday(config: GlmConfig): Promise<UsageRange> {
244
+ const end = new Date()
245
+ const start = new Date(end.getFullYear(), end.getMonth(), end.getDate())
246
+ return fetchUsageBetween(config, start, end, 0)
247
+ }
248
+
249
+ async function fetchUsageBetween(config: GlmConfig, start: Date, end: Date, downsampleMax: number): Promise<UsageRange> {
250
+ const query = `startTime=${encodeURIComponent(formatLocal(start))}&endTime=${encodeURIComponent(formatLocal(end))}`
251
+ const data = (await getJson(config, `${config.baseUrl}/api/monitor/usage/model-usage?${query}`)) as
252
+ | {
253
+ x_time?: unknown
254
+ tokensUsage?: unknown
255
+ totalUsage?: unknown
256
+ modelSummaryList?: unknown
257
+ granularity?: unknown
258
+ }
259
+ | undefined
260
+
261
+ const times = Array.isArray(data?.x_time) ? (data!.x_time as string[]) : []
262
+ const tokens = Array.isArray(data?.tokensUsage) ? (data!.tokensUsage as number[]) : []
263
+ const buckets = times.map((time, index) => ({ time, tokens: Number(tokens[index] ?? 0) }))
264
+
265
+ const totals = (data?.totalUsage ?? {}) as { totalTokensUsage?: number; totalModelCallCount?: number }
266
+ const models = Array.isArray(data?.modelSummaryList)
267
+ ? (data!.modelSummaryList as { modelName?: string; totalTokens?: number }[])
268
+ .map((m) => ({ name: String(m.modelName ?? "?"), tokens: Number(m.totalTokens ?? 0) }))
269
+ .sort((a, b) => b.tokens - a.tokens)
270
+ : []
271
+
272
+ const sum = buckets.reduce((total, bucket) => total + bucket.tokens, 0)
273
+ return {
274
+ totalTokens: typeof totals.totalTokensUsage === "number" ? totals.totalTokensUsage : sum,
275
+ totalCalls: typeof totals.totalModelCallCount === "number" ? totals.totalModelCallCount : 0,
276
+ granularity: typeof data?.granularity === "string" ? data.granularity : "hourly",
277
+ buckets: downsampleMax > 0 ? downsample(buckets, downsampleMax) : buckets,
278
+ models,
279
+ }
280
+ }
281
+
282
+ /** Keeps the sparkline light on long ranges by merging buckets into at most `max` slices. */
283
+ function downsample(buckets: UsageBucket[], max: number): UsageBucket[] {
284
+ if (buckets.length <= max) return buckets
285
+ const groupSize = Math.ceil(buckets.length / max)
286
+ const merged: UsageBucket[] = []
287
+ for (let i = 0; i < buckets.length; i += groupSize) {
288
+ const group = buckets.slice(i, i + groupSize)
289
+ merged.push({
290
+ time: group[0]!.time,
291
+ tokens: group.reduce((total, bucket) => total + bucket.tokens, 0),
292
+ })
293
+ }
294
+ return merged
295
+ }
296
+
297
+ /** Fetches everything the panel shows. Never rejects: failures become a status. */
298
+ export async function fetchSnapshot(rawOptions: unknown): Promise<Snapshot> {
299
+ const options = readOptions(rawOptions)
300
+ const fetchedAt = Date.now()
301
+ try {
302
+ const config = resolveConfig(options)
303
+ if ("error" in config)
304
+ return { status: "no-key", limits: [], fetchedAt }
305
+
306
+ const [quota, usageToday, usage7d, usage30d] = await Promise.all([
307
+ fetchQuota(config),
308
+ fetchToday(config).catch(() => undefined),
309
+ fetchUsage(config, 7).catch(() => undefined),
310
+ fetchUsage(config, 30).catch(() => undefined),
311
+ ])
312
+
313
+ return {
314
+ status: "ok",
315
+ level: quota.level,
316
+ limits: quota.limits,
317
+ usageToday,
318
+ usage7d,
319
+ usage30d,
320
+ fetchedAt,
321
+ }
322
+ } catch (cause) {
323
+ if (cause instanceof EmptyQuotaError)
324
+ return { status: "empty", hint: "org-project", limits: [], fetchedAt }
325
+ const message = cause instanceof Error ? cause.message : String(cause)
326
+ return { status: "error", message, limits: [], fetchedAt }
327
+ }
328
+ }
@@ -0,0 +1,17 @@
1
+ import { Schema } from "effect"
2
+ import { Ipc } from "@opencode/plugin/gui"
3
+
4
+ /**
5
+ * Window → main bridge. main implements it (`ctx.provide`) with the BigModel
6
+ * client; windows call it with `ctx.main`. Values cross as JSON, so the schemas
7
+ * stay permissive and the window casts to the shared types.
8
+ */
9
+ export const GlmQuota = Ipc.define({
10
+ id: "opencode-glm-plugin.quota",
11
+ methods: {
12
+ /** The cached snapshot, fetching one when the cache is older than ~90s. */
13
+ snapshot: { output: Schema.Unknown },
14
+ /** Forces a fetch, bypassing the throttle. */
15
+ refresh: { output: Schema.Unknown },
16
+ },
17
+ })
@@ -0,0 +1,11 @@
1
+ import { Plugin } from "@opencode/plugin/gui"
2
+ import en from "./i18n/en"
3
+ import zh from "./i18n/zh"
4
+
5
+ /**
6
+ * The plugin's declarations: copy only. (2.3.2 has no `icons` field; the panel
7
+ * and shell use the app's own catalog icons.)
8
+ */
9
+ export const definition = Plugin.define({
10
+ i18n: { en, zh, zht: zh },
11
+ })
@@ -0,0 +1,41 @@
1
+ const en = {
2
+ "panel.title": "GLM Quota",
3
+ "panel.refresh": "Refresh",
4
+ "pill.label": "GLM {{pct}}% used",
5
+ "pill.loading": "GLM …",
6
+ "menu.open": "GLM quota",
7
+ "section.today": "Today",
8
+ "section.quota": "Plan quota",
9
+ "section.7d": "Last 7 days",
10
+ "section.30d": "Last 30 days",
11
+ "usage.tokens": "Tokens",
12
+ "usage.calls": "Calls",
13
+ "usage.models": "By model",
14
+ "usage.empty": "No usage data",
15
+ "chart.byHour": "Hourly",
16
+ "chart.byDay": "Daily",
17
+ "limit.tokens-5h": "5-hour window",
18
+ "limit.credit-5h": "5-hour credits",
19
+ "limit.credit-week": "Weekly credits",
20
+ "limit.credit-month": "Monthly credits",
21
+ "limit.time-month": "Monthly tools (MCP)",
22
+ "limit.other": "Quota",
23
+ "state.used": "Used",
24
+ "state.usedPct": "{{pct}}% used",
25
+ "state.freePct": "{{pct}}% available",
26
+ "state.remaining": "Left",
27
+ "state.limited": "Limited",
28
+ "state.resetIn": "Resets {{time}}",
29
+ "state.loading": "Loading…",
30
+ "state.noKey": "No GLM API key found",
31
+ "state.noKeyHint":
32
+ "Sign in to the zhipuai-coding-plan provider in OpenCode, or set apiKey in this plugin's options in opencode.json.",
33
+ "state.error": "Request failed",
34
+ "state.empty": "No quota data returned",
35
+ "state.emptyHint":
36
+ "Newer credit-based plans may need organization, project and planType in this plugin's options (see the bigmodel.cn console).",
37
+ "foot.updated": "Updated {{time}}",
38
+ "foot.auto": "Auto-refreshes every 5 min",
39
+ }
40
+
41
+ export default en