@alecliu/pi-zai-usage 0.0.0-stage → 0.1.6

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,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) Feng-H (original work)
4
+ Copyright (c) Alec (modifications)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,144 @@
1
- # Temporary Holding Version
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.
1
+ # pi-zai-usage
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@alecliu/pi-zai-usage.svg?color=blue)](https://www.npmjs.com/package/@alecliu/pi-zai-usage)
4
+ [![npm downloads](https://img.shields.io/npm/dt/@alecliu/pi-zai-usage.svg?color=green)](https://www.npmjs.com/package/@alecliu/pi-zai-usage)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![pi-package](https://img.shields.io/badge/pi-package-00b57a)](https://pi.dev/packages)
7
+
8
+ > Forked from [Feng-H/pi-zai-usage](https://github.com/Feng-H/pi-zai-usage) — maintained by Alec.
9
+
10
+ **[English](#what-it-is) | [简体中文](#中文说明)**
11
+
12
+ > A [pi](https://pi.dev) extension that shows your **real server-side quota** for Zhipu GLM / Z.ai Coding Plans inline in the footer status bar.
13
+
14
+ ## What it is
15
+
16
+ Displays Zhipu/Z.ai Coding Plan quotas directly in pi's footer — accurate across devices, with reset countdown. No more switching to a web page to check "how much am I down to".
17
+
18
+ ```
19
+ ~/proj (main) ↑1k ↓227 0.6%/200K zai 5h 28% (auto) glm-5.1
20
+ └──── badge
21
+ ```
22
+
23
+ - `zai 5h 28%` — 28% of the 5-hour rolling token window used, colored green/yellow/red by usage
24
+ - When the server API is unreachable, falls back to scanning local session JSONLs for a **local approximation** (distinguished by a `~` prefix)
25
+ - `/usage` toggles a detail popup: plan tier / 5h tokens / weekly quota / tool quotas / reset times
26
+
27
+ ## Data source
28
+
29
+ Zhipu/Z.ai actually exposes a quota endpoint (per cc-switch's coding_plan implementation):
30
+
31
+ ```
32
+ GET {base}/api/monitor/usage/quota/limit
33
+ Authorization: Bearer <api_key>
34
+ ```
35
+
36
+ Response `data.limits[]` (unit semantics from the z.ai frontend source):
37
+
38
+ | type | unit | meaning |
39
+ | -------------- | ---- | ------------------------------------------------------ |
40
+ | `TOKENS_LIMIT` | 3 | 5-hour rolling token window (main badge) |
41
+ | `TOKENS_LIMIT` | 6 | weekly quota (some plans / international site only) |
42
+ | `TIME_LIMIT` | 5 | tools/search (monthly, shown in `/usage`) |
43
+
44
+ `base` is auto-selected per provider (`zai-coding-cn` / containing `bigmodel` → `open.bigmodel.cn`, else `api.z.ai`).
45
+
46
+ ## Install
47
+
48
+ Install via **npm** (recommended):
49
+
50
+ ```bash
51
+ pi install npm:@alecliu/pi-zai-usage
52
+ ```
53
+
54
+ Or install directly from **GitHub**:
55
+
56
+ ```bash
57
+ pi install git:github.com/Alec01/pi-zai-usage
58
+ ```
59
+
60
+ ## Environment variables (optional)
61
+
62
+ | Variable | Default | Meaning |
63
+ | ------------------ | -------------------- | ------------------------------------------ |
64
+ | `PI_USAGE_BASE` | auto per provider | quota endpoint host |
65
+ | `PI_USAGE_WINDOW_H`| `5` | rolling window hours for the local fallback|
66
+ | `PI_USAGE_PROVIDER`| provider or `zai` | provider substring match for local fallback|
67
+
68
+ ## Rendering notes
69
+
70
+ Uses `ctx.ui.setFooter()` with a single-line layout `pwd stats ···· model`; the badge is injected into stats between the context-window % and `(auto)`. On narrow terminals it degrades progressively — provider prefix → path (full → last 2 segments → last segment) → thinking suffix → branch → whole path → cache stats → model name — keeping core stats (badge / context %) intact, with no mid-word `...` truncation.
71
+
72
+ > `setStatus()` pins badges to a separate extension status row that can't merge into the stats line — hence `setFooter`.
73
+
74
+ ---
75
+
76
+ ## 中文说明
77
+
78
+ > pi coding agent 扩展:在 footer 状态行内联显示智谱 GLM / Z.ai Coding Plan 的**真实服务端配额**。
79
+
80
+ ### 这是什么
81
+
82
+ 把智谱/Z.ai Coding Plan 的服务端配额,直接显示在 pi 的底部状态行(footer)里,跨设备准确、带重置倒计时。不再需要切到网页查「我还剩多少额度」。
83
+
84
+ ```
85
+ ~/proj (main) ↑1k ↓227 0.6%/200K zai 5h 28% (auto) glm-5.1
86
+ └──── 徽标
87
+ ```
88
+
89
+ - `zai 5h 28%` — 5 小时滚动 token 窗口已用 28%,绿/黄/红按用量着色
90
+ - 当服务端 API 不可达时,回退到扫描本机会话 JSONL 做**本地近似**(`~` 前缀区分)
91
+ - `/usage` 命令弹出配额明细:套餐档位 / 5h token / 周配额 / 工具额度 / 重置时间,再次执行关闭
92
+
93
+ ### 数据源
94
+
95
+ 智谱/Z.ai 其实开放了配额查询接口(参考 cc-switch 的 coding_plan 实现):
96
+
97
+ ```
98
+ GET {base}/api/monitor/usage/quota/limit
99
+ Authorization: Bearer <api_key>
100
+ ```
101
+
102
+ 响应 `data.limits[]`(unit 含义来自 z.ai 前端源码):
103
+
104
+ | type | unit | 含义 |
105
+ | -------------- | ---- | ------------------------------------------ |
106
+ | `TOKENS_LIMIT` | 3 | 5 小时滚动 token 窗口(徽标主显示) |
107
+ | `TOKENS_LIMIT` | 6 | 周配额(部分套餐/国际站才有,`/usage` 展示)|
108
+ | `TIME_LIMIT` | 5 | 工具/搜索类(月度,`/usage` 展示) |
109
+
110
+ `base` 按 provider 自动选择(`zai-coding-cn`/含 `bigmodel` → `open.bigmodel.cn`,否则 `api.z.ai`)。
111
+
112
+ ### 安装方式
113
+
114
+ 通过 **npm 官方镜像** 安装(推荐):
115
+
116
+ ```bash
117
+ pi install npm:@alecliu/pi-zai-usage
118
+ ```
119
+
120
+ 或者直接从 **GitHub** 安装:
121
+
122
+ ```bash
123
+ pi install git:github.com/Alec01/pi-zai-usage
124
+ ```
125
+
126
+ - npm 官方包页面:[https://www.npmjs.com/package/@alecliu/pi-zai-usage](https://www.npmjs.com/package/@alecliu/pi-zai-usage)
127
+
128
+ ### 环境变量(可选)
129
+
130
+ | 变量 | 默认 | 说明 |
131
+ | ------------------ | --------------------------------- | ------------------------------------------ |
132
+ | `PI_USAGE_BASE` | 按 provider 自动 | 配额端点 host |
133
+ | `PI_USAGE_WINDOW_H`| `5` | 本地回退的滚动窗口小时数 |
134
+ | `PI_USAGE_PROVIDER`| provider 或 `zai` | 本地回退的 provider 匹配子串 |
135
+
136
+ ### 渲染说明
137
+
138
+ 用 `ctx.ui.setFooter()` 接管 footer,采用**单行布局** `pwd stats ···· model`,徽标注入 stats 的「上下文窗口」与「(auto)」之间。窄终端下按可舍弃程度逐级降级:provider 前缀 → 路径(完整 → 末 2 段 → 末 1 段)→ thinking 后缀 → 分支 → 整段路径 → 缓存统计 → 模型名;核心 stats(含徽标 / 上下文%)尽量保完整,不会出现「…」截断。
139
+
140
+ > `setStatus()` 的徽标会被固定到单独的「扩展状态行」,无法并入 stats 行,故用 `setFooter`。
141
+
142
+ ## License
143
+
144
+ MIT
@@ -0,0 +1,565 @@
1
+ /**
2
+ * zai-usage.ts — show your **real server-side quota** for Zhipu GLM / Z.ai Coding Plan
3
+ * inline in pi's footer status bar.
4
+ *
5
+ * Zhipu/Z.ai actually exposes a quota endpoint (per cc-switch's coding_plan implementation):
6
+ * GET {base}/api/monitor/usage/quota/limit
7
+ * Authorization: Bearer <api_key> ← tested: both the CN site (bare key / Bearer) and the
8
+ * international site accept Bearer; always use Bearer.
9
+ * Content-Type: application/json
10
+ * Accept-Language: en-US,en
11
+ * Response data.limits[] (unit semantics from the z.ai frontend source):
12
+ * - TOKENS_LIMIT unit=3: 5-hour rolling token window (main badge)
13
+ * - TOKENS_LIMIT unit=6: weekly quota (some plans / international site only; shown in /usage)
14
+ * - TIME_LIMIT unit=5: tools/search (monthly)
15
+ * This extension uses TOKENS_LIMIT(unit=3) as the main badge — accurate across devices,
16
+ * with reset countdown.
17
+ * When the API is unreachable, falls back to scanning local session JSONLs for a local
18
+ * approximation (distinguished by a ~ prefix).
19
+ *
20
+ * Rendering: takes over the footer with ctx.ui.setFooter(), **single-line layout**
21
+ * `pwd stats ···· model`, badge injected between the context-window % and "(auto)":
22
+ * `~/proj (main) ↑1k ↓227 0.6%/200K zai 5h 28% (auto) glm-5.1`
23
+ * setStatus() pins badges to a separate extension status row that can't merge into the
24
+ * stats line — hence setFooter.
25
+ *
26
+ * Environment variables:
27
+ * PI_USAGE_BASE quota endpoint host (default auto per provider: zai-coding-cn→bigmodel.cn, else z.ai)
28
+ * PI_USAGE_WINDOW_H rolling window hours for the local fallback (default 5)
29
+ * PI_USAGE_PROVIDER provider substring match for the local fallback
30
+ *
31
+ * Command:
32
+ * /usage toggle the quota detail popup (plan tier / 5h tokens / tool quotas / reset times)
33
+ */
34
+ import fs from "node:fs";
35
+ import path from "node:path";
36
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
37
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
38
+
39
+ const WIDGET_KEY = "zai-usage-detail";
40
+
41
+ // ── Compact number formatting ────────────────────────────────────────────
42
+ function fmt(n: number): string {
43
+ if (n < 1000) return `${Math.round(n)}`;
44
+ if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`;
45
+ return `${(n / 1_000_000).toFixed(2)}M`;
46
+ }
47
+ /** Footer token format (mirrors pi's default footer formatTokens) */
48
+ function formatTokens(count: number): string {
49
+ if (count < 1000) return count.toString();
50
+ if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
51
+ if (count < 1_000_000) return `${Math.round(count / 1000)}k`;
52
+ if (count < 10_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
53
+ return `${Math.round(count / 1_000_000)}M`;
54
+ }
55
+ /** cwd → footer display (home replaced with ~) */
56
+ function formatCwdForFooter(cwd: string, home: string | undefined): string {
57
+ if (!home) return cwd;
58
+ const resolvedCwd = path.resolve(cwd);
59
+ const resolvedHome = path.resolve(home);
60
+ const rel = path.relative(resolvedHome, resolvedCwd);
61
+ const inside =
62
+ rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
63
+ if (!inside) return cwd;
64
+ return rel === "" ? "~" : `~${path.sep}${rel}`;
65
+ }
66
+
67
+ // ── Server-side quota ──────────────────────────────────────────────
68
+ interface LimitTier {
69
+ percentage: number;
70
+ resetMs: number | null;
71
+ }
72
+ interface Quota {
73
+ level: string | null; // plan tier: lite / pro / ...
74
+ tokens: LimitTier | null; // TOKENS_LIMIT, unit=3 (5h token window) — main badge
75
+ weekly: LimitTier | null; // TOKENS_LIMIT, unit=6 (weekly quota; some plans / intl site only)
76
+ time: LimitTier | null; // TIME_LIMIT, unit=5 (tools/search, monthly)
77
+ timeDetails?: { model: string; usage: number }[];
78
+ queriedAt: number;
79
+ }
80
+
81
+ /** Fetch the quota endpoint; parse TOKENS_LIMIT(unit=3) and TIME_LIMIT. Uses Bearer auth. */
82
+ async function fetchQuota(base: string, apiKey: string): Promise<Quota | null> {
83
+ let resp: Response;
84
+ try {
85
+ resp = await fetch(`${base}/api/monitor/usage/quota/limit`, {
86
+ method: "GET",
87
+ headers: {
88
+ Authorization: `Bearer ${apiKey}`,
89
+ "Content-Type": "application/json",
90
+ "Accept-Language": "en-US,en",
91
+ },
92
+ signal: AbortSignal.timeout(15000),
93
+ });
94
+ } catch {
95
+ return null;
96
+ }
97
+ if (resp.status === 401 || resp.status === 403) return null;
98
+ if (!resp.ok) return null;
99
+ let body: any;
100
+ try {
101
+ body = await resp.json();
102
+ } catch {
103
+ return null;
104
+ }
105
+ if (body?.success === false) return null;
106
+ const data = body?.data;
107
+ if (!data) return null;
108
+
109
+ let tokens: LimitTier | null = null;
110
+ let weekly: LimitTier | null = null;
111
+ let time: LimitTier | null = null;
112
+ let timeDetails: { model: string; usage: number }[] | undefined;
113
+ for (const lim of data.limits ?? []) {
114
+ if (lim.type === "TOKENS_LIMIT" && lim.unit === 3 && !tokens) {
115
+ tokens = { percentage: Number(lim.percentage) || 0, resetMs: lim.nextResetTime ?? null };
116
+ } else if (lim.type === "TOKENS_LIMIT" && lim.unit === 6 && !weekly) {
117
+ weekly = { percentage: Number(lim.percentage) || 0, resetMs: lim.nextResetTime ?? null };
118
+ } else if (lim.type === "TIME_LIMIT" && !time) {
119
+ time = { percentage: Number(lim.percentage) || 0, resetMs: lim.nextResetTime ?? null };
120
+ timeDetails = (lim.usageDetails ?? []).map((d: any) => ({
121
+ model: String(d.modelCode ?? "?"),
122
+ usage: Number(d.usage) || 0,
123
+ }));
124
+ }
125
+ }
126
+ return {
127
+ level: data.level ? String(data.level) : null,
128
+ tokens,
129
+ weekly,
130
+ time,
131
+ timeDetails,
132
+ queriedAt: Date.now(),
133
+ };
134
+ }
135
+
136
+ // ── Local fallback: scan session JSONLs ────────────────────────────────
137
+ interface LocalTotals {
138
+ total: number;
139
+ input: number;
140
+ output: number;
141
+ cache: number;
142
+ }
143
+ function computeWindowLocal(globalRoot: string, windowMs: number, providerMatch: string): LocalTotals {
144
+ const cutoff = Date.now() - windowMs;
145
+ let total = 0,
146
+ input = 0,
147
+ output = 0,
148
+ cache = 0;
149
+ let projectDirs: string[] = [];
150
+ try {
151
+ projectDirs = fs
152
+ .readdirSync(globalRoot, { withFileTypes: true })
153
+ .filter((d) => d.isDirectory())
154
+ .map((d) => path.join(globalRoot, d.name));
155
+ } catch {
156
+ return { total, input, output, cache };
157
+ }
158
+ for (const dir of projectDirs) {
159
+ let files: string[] = [];
160
+ try {
161
+ files = fs
162
+ .readdirSync(dir)
163
+ .filter((f) => f.endsWith(".jsonl"))
164
+ .map((f) => path.join(dir, f));
165
+ } catch {
166
+ continue;
167
+ }
168
+ for (const file of files) {
169
+ let stat;
170
+ try {
171
+ stat = fs.statSync(file);
172
+ } catch {
173
+ continue;
174
+ }
175
+ if (stat.mtimeMs < cutoff) continue;
176
+ let content: string;
177
+ try {
178
+ content = fs.readFileSync(file, "utf8");
179
+ } catch {
180
+ continue;
181
+ }
182
+ for (const line of content.split("\n")) {
183
+ const t = line.trim();
184
+ if (!t) continue;
185
+ let e: any;
186
+ try {
187
+ e = JSON.parse(t);
188
+ } catch {
189
+ continue;
190
+ }
191
+ if (e.type !== "message") continue;
192
+ const m = e.message;
193
+ if (!m || m.role !== "assistant") continue;
194
+ if (!(typeof m.provider === "string" && m.provider.includes(providerMatch))) continue;
195
+ const ts =
196
+ typeof e.timestamp === "string"
197
+ ? Date.parse(e.timestamp)
198
+ : typeof m.timestamp === "number"
199
+ ? m.timestamp
200
+ : 0;
201
+ if (!ts || ts < cutoff) continue;
202
+ const u = m.usage || {};
203
+ input += u.input || 0;
204
+ output += u.output || 0;
205
+ cache += (u.cacheRead || 0) + (u.cacheWrite || 0);
206
+ total += u.totalTokens ?? (u.input || 0) + (u.output || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0);
207
+ }
208
+ }
209
+ }
210
+ return { total, input, output, cache };
211
+ }
212
+
213
+ export default function (pi: ExtensionAPI) {
214
+ let timer: ReturnType<typeof setInterval> | undefined;
215
+ let widgetOpen = false;
216
+ let capturedTui: any;
217
+
218
+ const windowH = Number(process.env.PI_USAGE_WINDOW_H ?? 5) || 5;
219
+ const windowMs = windowH * 3600 * 1000;
220
+
221
+ let quota: Quota | null = null;
222
+ let local: LocalTotals | null = null; // local fallback
223
+ let lastFetch = 0;
224
+ let fetching = false;
225
+ let autoCompact: boolean | undefined;
226
+
227
+ function providerMatch(ctx: any): string {
228
+ return process.env.PI_USAGE_PROVIDER ?? ctx?.model?.provider ?? "zai";
229
+ }
230
+ function globalRoot(ctx: any): string {
231
+ return path.dirname(ctx.sessionManager.getSessionDir());
232
+ }
233
+ function quotaBase(ctx: any): string {
234
+ if (process.env.PI_USAGE_BASE) return process.env.PI_USAGE_BASE;
235
+ const prov = String(ctx?.model?.provider ?? "");
236
+ // zai-coding-cn / contains bigmodel → CN site; otherwise international site
237
+ if (prov.includes("cn") || prov.includes("bigmodel")) return "https://open.bigmodel.cn";
238
+ return "https://api.z.ai";
239
+ }
240
+
241
+ async function refreshQuota(ctx: any): Promise<void> {
242
+ if (fetching) return;
243
+ // min 30s between fetches so message_end doesn't hammer the API
244
+ if (Date.now() - lastFetch < 30_000 && quota) return;
245
+ fetching = true;
246
+ lastFetch = Date.now();
247
+ try {
248
+ const provider = ctx?.model?.provider;
249
+ let key: string | undefined;
250
+ try {
251
+ key = await ctx.modelRegistry?.getApiKeyForProvider?.(provider);
252
+ } catch {
253
+ /* ignore */
254
+ }
255
+ if (!key) {
256
+ // fallback: read auth.json directly
257
+ try {
258
+ const auth = JSON.parse(
259
+ fs.readFileSync(path.join(path.dirname(globalRoot(ctx)), "auth.json"), "utf8"),
260
+ );
261
+ key = auth?.[provider]?.key;
262
+ } catch {
263
+ /* ignore */
264
+ }
265
+ }
266
+ if (key) {
267
+ const q = await fetchQuota(quotaBase(ctx), key);
268
+ if (q) quota = q;
269
+ }
270
+ // local fallback is always refreshed (feeds /usage details and the API-failure badge)
271
+ local = computeWindowLocal(globalRoot(ctx), windowMs, providerMatch(ctx));
272
+ } catch {
273
+ /* ignore */
274
+ } finally {
275
+ fetching = false;
276
+ capturedTui?.requestRender();
277
+ if (widgetOpen) renderWidget(ctx);
278
+ }
279
+ }
280
+
281
+ function readAutoCompact(ctx: any): boolean {
282
+ if (autoCompact !== undefined) return autoCompact;
283
+ let enabled = true;
284
+ try {
285
+ const agentDir = path.dirname(globalRoot(ctx));
286
+ for (const f of [path.join(agentDir, "settings.json"), path.join(ctx.cwd, ".pi", "settings.json")]) {
287
+ if (fs.existsSync(f)) {
288
+ const s = JSON.parse(fs.readFileSync(f, "utf8"));
289
+ if (s?.compaction?.enabled !== undefined) enabled = !!s.compaction.enabled;
290
+ }
291
+ }
292
+ } catch {
293
+ /* default true */
294
+ }
295
+ autoCompact = enabled;
296
+ return enabled;
297
+ }
298
+
299
+ /** Badge (colored) for the stats line; undefined = omit while quota isn't ready */
300
+ function zaiBadge(ctx: any, theme: any): string | undefined {
301
+ if (quota?.tokens) {
302
+ const pct = quota.tokens.percentage;
303
+ const color = pct >= 90 ? "error" : pct >= 70 ? "warning" : "success";
304
+ return theme.fg(color, `zai ${windowH}h ${Math.round(pct)}%`);
305
+ }
306
+ if (local && local.total > 0) return `zai ${windowH}h ~${fmt(local.total)}`; // ~ marks a local estimate
307
+ return undefined; // loading/failed: omit the badge
308
+ }
309
+
310
+ /** Single-line footer: `pwd stats ···· model`; the zai badge goes between the window % and "(auto)" */
311
+ function renderFooter(ctx: any, theme: any, footerData: any, width: number): string[] {
312
+ const state: any = { model: ctx.model, thinkingLevel: ctx.thinkingLevel };
313
+ let inT = 0,
314
+ outT = 0,
315
+ cacheRead = 0,
316
+ cacheWrite = 0,
317
+ cost = 0;
318
+ let latestCacheHitRate: number | undefined;
319
+ try {
320
+ for (const e of ctx.sessionManager.getEntries()) {
321
+ if (e.type === "message" && e.message?.role === "assistant") {
322
+ const u = e.message.usage || {};
323
+ inT += u.input || 0;
324
+ outT += u.output || 0;
325
+ cacheRead += u.cacheRead || 0;
326
+ cacheWrite += u.cacheWrite || 0;
327
+ cost += u.cost?.total || 0;
328
+ const p = (u.input || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0);
329
+ latestCacheHitRate = p > 0 ? ((u.cacheRead || 0) / p) * 100 : undefined;
330
+ } else if (e.type === "message" && e.message?.role === "toolResult" && e.message?.usage) {
331
+ const u = e.message.usage;
332
+ inT += u.input || 0;
333
+ outT += u.output || 0;
334
+ cacheRead += u.cacheRead || 0;
335
+ cacheWrite += u.cacheWrite || 0;
336
+ cost += u.cost?.total || 0;
337
+ } else if ((e.type === "branch_summary" || e.type === "compaction") && e.usage) {
338
+ const u = e.usage;
339
+ inT += u.input || 0;
340
+ outT += u.output || 0;
341
+ cacheRead += u.cacheRead || 0;
342
+ cacheWrite += u.cacheWrite || 0;
343
+ cost += u.cost?.total || 0;
344
+ }
345
+ }
346
+ } catch {
347
+ /* ignore */
348
+ }
349
+ const contextUsage = ctx.getContextUsage?.();
350
+ const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
351
+ const contextPercentValue = contextUsage?.percent ?? 0;
352
+ const contextPercent =
353
+ contextUsage?.percent !== null && contextUsage?.percent !== undefined
354
+ ? contextPercentValue.toFixed(1)
355
+ : "?";
356
+
357
+ const pwdBase = formatCwdForFooter(ctx.sessionManager.getCwd(), process.env.HOME || process.env.USERPROFILE);
358
+ const branch = footerData.getGitBranch();
359
+ const sessionName = ctx.sessionManager.getSessionName?.();
360
+ const pwdSuffix = `${branch ? ` (${branch})` : ""}${sessionName ? ` • ${sessionName}` : ""}`;
361
+
362
+ const statsHead: string[] = [];
363
+ const statsCache: string[] = []; // cache details — dropped first when the line gets tight
364
+ const statsTail: string[] = [];
365
+ if (inT) statsHead.push(`↑${formatTokens(inT)}`);
366
+ if (outT) statsHead.push(`↓${formatTokens(outT)}`);
367
+ if (cacheRead) statsCache.push(`R${formatTokens(cacheRead)}`);
368
+ if (cacheWrite) statsCache.push(`W${formatTokens(cacheWrite)}`);
369
+ if ((cacheRead > 0 || cacheWrite > 0) && latestCacheHitRate !== undefined) {
370
+ statsCache.push(`CH${latestCacheHitRate.toFixed(1)}%`);
371
+ }
372
+ const usingSubscription = state.model ? state.model.provider === "kimi-coding" : false;
373
+ if (cost || usingSubscription) statsTail.push(`$${cost.toFixed(3)}${usingSubscription ? " (sub)" : ""}`);
374
+
375
+ // context percentage: `pct/window [zai] (auto)`
376
+ const autoIndicator = readAutoCompact(ctx) ? " (auto)" : "";
377
+ const windowStr =
378
+ contextPercent === "?"
379
+ ? `?/${formatTokens(contextWindow)}`
380
+ : `${contextPercent}%/${formatTokens(contextWindow)}`;
381
+ const badge = zaiBadge(ctx, theme);
382
+ const contextPercentDisplay = badge ? `${windowStr} ${badge}${autoIndicator}` : `${windowStr}${autoIndicator}`;
383
+
384
+ let contextPercentStr: string;
385
+ if (contextPercentValue > 90) contextPercentStr = theme.fg("error", contextPercentDisplay);
386
+ else if (contextPercentValue > 70) contextPercentStr = theme.fg("warning", contextPercentDisplay);
387
+ else contextPercentStr = contextPercentDisplay;
388
+ statsTail.push(contextPercentStr);
389
+ if (process.env.PI_EXPERIMENTAL === "1") {
390
+ statsTail.push(`${theme.fg("dim", "•")} ${theme.bold(theme.fg("warning", "xp"))}`);
391
+ }
392
+ let statsLeft = [...statsHead, ...statsCache, ...statsTail].join(" ");
393
+ const statsSlim = [...statsHead, ...statsTail].join(" "); // same line with cache stats dropped
394
+
395
+ // right side: model name (+ thinking / provider)
396
+ const modelName = state.model?.id || "no-model";
397
+ let rightSideWithoutProvider = modelName;
398
+ if (state.model?.reasoning) {
399
+ const thinkingLevel = state.thinkingLevel || "off";
400
+ rightSideWithoutProvider =
401
+ thinkingLevel === "off" ? `${modelName} • thinking off` : `${modelName} • ${thinkingLevel}`;
402
+ }
403
+ let rightSide = rightSideWithoutProvider;
404
+ if (footerData.getAvailableProviderCount() > 1 && state.model) {
405
+ rightSide = `(${state.model.provider}) ${rightSideWithoutProvider}`;
406
+ }
407
+
408
+ // ── single-line footer: `pwd stats ···· model` ──
409
+ // Degrade progressively when the line is tight — most disposable first:
410
+ // provider prefix → path detail (full → last 2 segments → last segment) →
411
+ // thinking suffix → branch/session suffix → whole path → cache stats → model name.
412
+ // Core stats (in/out/cost/context% + zai badge) stay intact; no mid-word "..." —
413
+ // pieces shrink or disappear instead, freeing room for the information that matters.
414
+ const sep = " ";
415
+ const minPad = 2;
416
+ const fits = (p: string, s: string, r: string) =>
417
+ (p === "" ? 0 : visibleWidth(p) + sep.length) + visibleWidth(s) + minPad + visibleWidth(r) <= width;
418
+
419
+ // path-only variants of pwdBase: full → last 2 segments → last segment
420
+ const segs = pwdBase.split(/[\\/]+/).filter(Boolean);
421
+ const psep = pwdBase.includes("\\") ? "\\" : "/";
422
+ const last1 = segs.length ? segs[segs.length - 1] : "";
423
+ const last2 = segs.length > 2 ? segs.slice(-2).join(psep) : "";
424
+
425
+ let pwdStr = pwdBase + pwdSuffix;
426
+ // 1) drop provider prefix
427
+ if (!fits(pwdStr, statsLeft, rightSide)) rightSide = rightSideWithoutProvider;
428
+ // 2) shrink path, keeping the branch/session suffix
429
+ if (!fits(pwdStr, statsLeft, rightSide) && last2) pwdStr = last2 + pwdSuffix;
430
+ if (!fits(pwdStr, statsLeft, rightSide)) pwdStr = last1 + pwdSuffix;
431
+ // 3) drop thinking suffix, keep the bare model name
432
+ if (!fits(pwdStr, statsLeft, rightSide) && rightSide !== modelName) rightSide = modelName;
433
+ // 4) drop branch/session suffix
434
+ if (!fits(pwdStr, statsLeft, rightSide)) pwdStr = last1;
435
+ // 5) drop the path entirely — stats get the room
436
+ if (!fits(pwdStr, statsLeft, rightSide)) pwdStr = "";
437
+ // 6) drop cache stats (R/W/CH) before touching the model name
438
+ if (!fits(pwdStr, statsLeft, rightSide) && statsSlim.length < statsLeft.length) statsLeft = statsSlim;
439
+ // 7) still not fitting → truncate/drop the model name
440
+ const leftW = pwdStr === "" ? visibleWidth(statsLeft) : visibleWidth(pwdStr) + sep.length + visibleWidth(statsLeft);
441
+ if (leftW + minPad + visibleWidth(rightSide) > width) {
442
+ const availForRight = width - leftW - minPad;
443
+ rightSide = availForRight > 4 ? truncateToWidth(rightSide, availForRight, "") : "";
444
+ }
445
+ const rightW = visibleWidth(rightSide);
446
+
447
+ // coloring: pwd / token stats dim, context % keeps its own color
448
+ const pwdColored = pwdStr === "" ? "" : theme.fg("dim", pwdStr) + sep;
449
+ const statsColored = theme.fg("dim", statsLeft);
450
+ const rightColored = rightW === 0 ? "" : theme.fg("dim", rightSide);
451
+ const pad = " ".repeat(Math.max(minPad, width - leftW - rightW));
452
+ const lines = [pwdColored + statsColored + pad + rightColored];
453
+
454
+ const extensionStatuses = footerData.getExtensionStatuses();
455
+ if (extensionStatuses.size > 0) {
456
+ const others = Array.from(extensionStatuses.entries())
457
+ .filter(([key]) => key !== "zai-usage")
458
+ .sort(([a], [b]) => a.localeCompare(b))
459
+ .map(([, text]) => text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim());
460
+ if (others.length > 0) lines.push(truncateToWidth(others.join(" "), width, theme.fg("dim", "...")));
461
+ }
462
+ return lines;
463
+ }
464
+
465
+ function setupFooter(ctx: any): void {
466
+ ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
467
+ capturedTui = tui;
468
+ const unsub = footerData.onBranchChange(() => tui.requestRender());
469
+ return {
470
+ dispose: unsub,
471
+ invalidate() {},
472
+ render: (width: number) => renderFooter(ctx, theme, footerData, width),
473
+ };
474
+ });
475
+ }
476
+
477
+ function renderWidget(ctx: any): void {
478
+ if (!quota && !local) return;
479
+ const th = ctx.ui.theme;
480
+ const lines: string[] = [];
481
+ lines.push(th.fg("accent", `zai · Zhipu GLM Coding Plan quota (${quotaBase(ctx)})`));
482
+ if (quota?.level) lines.push(th.fg("dim", `Plan: ${quota.level}`));
483
+ if (quota?.tokens) {
484
+ const color = quota.tokens.percentage >= 90 ? "error" : quota.tokens.percentage >= 70 ? "warning" : "success";
485
+ lines.push(th.fg(color, `5h token window: ${Math.round(quota.tokens.percentage)}% used`));
486
+ if (quota.tokens.resetMs) {
487
+ const mins = Math.max(0, Math.round((quota.tokens.resetMs - Date.now()) / 60000));
488
+ lines.push(th.fg("dim", ` resets: ${new Date(quota.tokens.resetMs).toLocaleString()} (~${mins} min left)`));
489
+ }
490
+ } else {
491
+ lines.push(th.fg("warning", "5h token window: API unavailable (local estimate only)"));
492
+ }
493
+ if (quota?.weekly) {
494
+ const color = quota.weekly.percentage >= 90 ? "error" : quota.weekly.percentage >= 70 ? "warning" : "success";
495
+ lines.push(th.fg(color, `Weekly quota: ${Math.round(quota.weekly.percentage)}% used`));
496
+ if (quota.weekly.resetMs) {
497
+ const days = Math.max(0, Math.round((quota.weekly.resetMs - Date.now()) / 86400000));
498
+ lines.push(th.fg("dim", ` resets: ${new Date(quota.weekly.resetMs).toLocaleString()} (~${days}d left)`));
499
+ }
500
+ }
501
+ if (quota?.time) {
502
+ const color = quota.time.percentage >= 90 ? "error" : quota.time.percentage >= 70 ? "warning" : "success";
503
+ lines.push(th.fg(color, `Tools/search quota: ${Math.round(quota.time.percentage)}% used`));
504
+ if (quota.timeDetails?.length) {
505
+ lines.push(th.fg("dim", " " + quota.timeDetails.map((d) => `${d.model} ${d.usage}`).join(" · ")));
506
+ }
507
+ }
508
+ if (local && local.total > 0) {
509
+ lines.push(
510
+ th.fg(
511
+ "dim",
512
+ `Local est. (~): ${fmt(local.total)} tok in ${fmt(local.input)} out ${fmt(local.output)} cache ${fmt(local.cache)}`,
513
+ ),
514
+ );
515
+ }
516
+ lines.push(th.fg("muted", "Source: Zhipu /api/monitor/usage/quota/limit · /usage to close"));
517
+ ctx.ui.setWidget(WIDGET_KEY, lines);
518
+ }
519
+
520
+ let lastCtx: any;
521
+
522
+ pi.on("session_start", (_e, ctx) => {
523
+ lastCtx = ctx;
524
+ if (ctx.mode !== "tui") return;
525
+ setupFooter(ctx);
526
+ refreshQuota(ctx);
527
+ if (!timer) {
528
+ // periodic refresh: rolling window slides / quota changes over time
529
+ timer = setInterval(() => {
530
+ if (lastCtx) refreshQuota(lastCtx);
531
+ }, 60_000);
532
+ }
533
+ });
534
+
535
+ pi.on("message_end", (_e, ctx) => {
536
+ lastCtx = ctx;
537
+ refreshQuota(ctx);
538
+ });
539
+
540
+ pi.on("session_shutdown", () => {
541
+ if (timer) {
542
+ clearInterval(timer);
543
+ timer = undefined;
544
+ }
545
+ widgetOpen = false;
546
+ });
547
+
548
+ pi.registerCommand("usage", {
549
+ description: "Toggle Zhipu Coding Plan quota details",
550
+ handler: async (_args, ctx) => {
551
+ if (ctx.mode !== "tui") {
552
+ ctx.ui.notify("This command is only available in the interactive TUI", "info");
553
+ return;
554
+ }
555
+ widgetOpen = !widgetOpen;
556
+ if (!widgetOpen) {
557
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
558
+ ctx.ui.notify("Quota details closed", "info");
559
+ return;
560
+ }
561
+ await refreshQuota(ctx);
562
+ renderWidget(ctx);
563
+ },
564
+ });
565
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
- {
2
- "name": "@alecliu/pi-zai-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@alecliu/pi-zai-usage",
3
+ "version": "0.1.6",
4
+ "description": "pi extension: shows your real server-side quota for Zhipu GLM / Z.ai Coding Plan inline in the footer status bar (5h token window, weekly quota, tool quotas), with a local-session fallback estimate and a /usage detail command.",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "license": "MIT",
9
+ "author": {
10
+ "name": "Alec",
11
+ "url": "https://github.com/Alec01"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/Alec01/pi-zai-usage.git"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/Alec01/pi-zai-usage/issues"
19
+ },
20
+ "homepage": "https://github.com/Alec01/pi-zai-usage#readme",
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "files": [
25
+ "extensions",
26
+ "README.md"
27
+ ],
28
+ "pi": {
29
+ "extensions": [
30
+ "./extensions"
31
+ ]
32
+ },
33
+ "peerDependencies": {
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-tui": "*"
36
+ }
37
+ }