dsh-quotacat 0.2.0 → 0.3.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/README.md CHANGED
@@ -2,25 +2,66 @@
2
2
 
3
3
  QuotaCat for DeepSeek Harness — LLM 服务商用量与额度监控插件。
4
4
 
5
- 当前支持 **GLM Coding Plan**(5h 窗口 / 月度 MCP / 套餐等级 / 24h 工具调用),更多 provider 持续接入中。
5
+ 已支持:
6
6
 
7
+ - **GLM Coding Plan**:5h 窗口 / 月度 MCP / 套餐等级 / 24h 工具调用
8
+ - **DeepSeek API**(计费账户):余额 / 赠送金 / 账户状态
9
+
10
+ 更多 provider 持续接入中。
7
11
 
8
12
  ## 功能
9
13
 
10
- - **输入框统计条 pill**:`额度 62%`,百分比按用量分级变色(绿 <60 / 黄 <85 / 红 ≥85),点击弹出详情面板
11
- - **详情面板**:套餐等级、5 小时 token 窗口、本月 MCP 工具用量细分、重置时间,手动刷新
12
- - **`quota` agent 工具**:对话中直接问"额度还剩多少"即可触发
13
- - **右下角悬浮球**:🐱 常驻指示 + 展开面板(旧入口,可按需关闭)
14
+ ### 输入框统计条额度 pill
15
+
16
+ 在输入框下方统计条(轮次/步数、tok/s、缓存命中那一行)的末尾追加一个额度 pill:
17
+
18
+ - 显示当前服务商的 5 小时窗口用量百分比,按用量分级变色(绿 <60% / 黄 <85% / 红 ≥85%)
19
+ - **跟随当前模型**:GLM 显示 5h 百分比,DeepSeek 显示 API 余额;切换到未支持的服务商时半透明置灰
20
+ - 点击弹出详情面板(与宿主统计 pill 同款交互:固定定位、Esc/点外部关闭):
21
+ - 套餐等级、5h 窗口(用量/重置时间,跨天带日期)
22
+ - 24 小时滚动工具调用 + 本月 MCP 工具细分
23
+ - 手动刷新、数据更新时间
24
+
25
+ ### 阈值提醒
26
+
27
+ 5h 用量达到阈值(默认 80%,可调 50–95%)时弹出全局提醒 Toast,回落到阈值下方后自动复位(同一窗口只提醒一次)。阈值与开关可在设置视图里调整。
28
+
29
+ ### `quota` agent 工具
30
+
31
+ 对话中直接问「额度还剩多少」「5h 窗口什么时候重置」,agent 自动调用 `quota` 工具返回结果。
32
+
33
+ ### 设置
34
+
35
+ pill 弹框内切换设置视图:刷新频率(1–60 分钟或仅手动)、阈值提醒开关与阈值。配置热生效,无需重启。
14
36
 
15
37
  ## 零配置
16
38
 
17
- 插件自动通过宿主凭据服务解析 `ZAI_CODING_CN_API_KEY`(DSH 登录 GLM Coding Plan 时自动存入),无需手动配置 API Key。备选顺序:插件配置 `apiKey` → 宿主凭据 → 环境变量(`QUOTACAT_API_KEY` / `GLM_API_KEY` / `ZHIPU_API_KEY`)。
39
+ 无需手动配置 API Key:
18
40
 
19
- ## 指示器跟随模型
41
+ - **GLM Coding Plan**:自动解析 `ZAI_CODING_CN_API_KEY`(DSH 登录时自动存入)
42
+ - **DeepSeek API**:解析 `DEEPSEEK_API_KEY`(API 计费账户的 key;订阅登录无公开余额接口)
43
+ - 兜底顺序:宿主凭据 → 环境变量(对应各家的 `*_API_KEY`)
20
44
 
21
- 监听宿主 `llm/stream` 事件,按会话记录实际使用的 provider;pill 在当前模型不属于 GLM 家族时半透明置灰。
45
+ ## 安装
22
46
 
23
- > 已知局限:客户端无法感知"模型选择器"的当前值,只能跟随实际发生的调用。这是向 DSH 社区提案的方向之一(`conversation.model.changed` 事件 / `model-state` 客户端服务)。
47
+ ```bash
48
+ # 在 DSH profile 目录(~/.dsh/profiles/<profile>)里:
49
+ pnpm add dsh-quotacat
50
+ ```
51
+
52
+ 再在 profile 的 `cordis.patch.yml` 末尾追加:
53
+
54
+ ```yaml
55
+ - insert:
56
+ - id: quotacat
57
+ name: dsh-quotacat
58
+ ```
59
+
60
+ 重启 DSH 生效。
61
+
62
+ ## 指示器跟随模型的已知局限
63
+
64
+ DSH 客户端目前无法感知「模型选择器」的当前值,插件只能跟随**实际发生**的模型调用(监听 `llm/stream` 事件,按会话记录)。同时开多个会话使用不同模型时,pill 显示最近活跃的一家。
24
65
 
25
66
  ## 开发
26
67
 
@@ -40,25 +81,18 @@ npm test # placePanel 定位纯函数 + slot 注册单测
40
81
 
41
82
  类型限定 `feat` / `fix` / `docs` / `test` / `refactor` / `chore` / `perf`;主题与正文一律英文;一个提交只做一件事。
42
83
 
43
- 本地安装到 profile(`~/.dsh/profiles/desktop/package.json`):
44
-
45
- ```json
46
- { "dependencies": { "dsh-quotacat": "file:<本项目路径>" } }
47
- ```
48
-
49
- 再在 profile 的 `cordis.patch.yml` 加插件行(见 `cordis.patch.yml`)。
50
-
51
- ## 结构
84
+ ### 结构
52
85
 
53
86
  ```
54
- src/index.ts host 侧:GLM 查询/缓存/HTTP 路由/quota 工具
55
- src/glm.ts GLM API 客户端
87
+ src/index.ts host 侧:查询/缓存/HTTP 路由/quota 工具/阈值
88
+ src/glm.ts GLM API 客户端(额度 + 24h 工具用量)
56
89
  src/shared/api.ts 类型与路由常量(host/client 共用)
57
90
  src/client.tsx 浏览器模块入口(ModuleLoader 格式)
58
- src/client/main.tsx client 装配:locale + composer dock pill
59
- src/client/QuotaCatFooter.ts pill + 详情面板
60
- src/client/anchoredPosition.ts 面板定位纯函数(含单测)
61
- src/client/registerQuota.ts slot 注册
91
+ src/client/main.tsx client 装配:locale + pill + toast
92
+ src/client/QuotaCatFooter.ts pill + 详情/设置双视图弹框
93
+ src/client/QuotaAlertToast.ts 阈值提醒 Toast
94
+ src/client/anchoredPosition.ts 面板定位纯函数(含单测)
95
+ src/client/registerQuota.ts slot 注册
62
96
  src/client/runtime.ts React/react-dom/require 运行时注入容器
63
97
  src/client/model.ts host API 封装
64
98
  src/client/styles.ts 主题变量样式(对齐宿主 stat-dialog 规格)
package/cordis.patch.yml CHANGED
@@ -5,9 +5,6 @@
5
5
  - id: quotacat
6
6
  name: dsh-quotacat
7
7
  config:
8
- # GLM API Key:默认自动获取(宿主登录凭据 → 环境变量),一般无需填写;
9
- # 此字段仅作显式覆盖用
10
- apiKey: ''
11
8
  # 自动刷新间隔(分钟),0 = 只在打开面板/调用工具时拉取
12
9
  refreshMinutes: 10
13
10
  baseURL: 'https://open.bigmodel.cn'
package/dist/client.js CHANGED
@@ -508,8 +508,12 @@ button.qc-pill[aria-expanded="true"] { background: var(--dsw-alias-interactive-b
508
508
  }, [open]);
509
509
  const fiveHour = model.report?.windows.find((w) => w.kind === "fiveHourTokens");
510
510
  const pct = fiveHour !== void 0 ? Math.round(fiveHour.percentage * 100) : void 0;
511
- const dim = !isGlmLike(active.provider);
512
- const pillText = dim ? "额度" : "额度";
511
+ const isDeepseek = active.provider !== void 0 && /deepseek/i.test(active.provider);
512
+ const dsBalance = model.deepseek?.balance;
513
+ const dim = isDeepseek ? model.deepseek === void 0 : !isGlmLike(active.provider);
514
+ const pillValue = isDeepseek ? dsBalance !== void 0 ? `${dsBalance.totalBalance.toFixed(2)} ${dsBalance.currency === "CNY" ? "¥" : dsBalance.currency}` : void 0 : pct !== void 0 ? `${pct}%` : void 0;
515
+ const pillValueColor = isDeepseek ? "inherit" : severity(pct ?? 0);
516
+ const pillTitle = isDeepseek ? dim ? "DeepSeek API key 未配置(余额监控未启用)" : dsBalance !== void 0 ? `DeepSeek API 余额 ${pillValue}` : `DeepSeek 查询中/失败:${model.deepseek?.error ?? ""}` : dim ? `当前模型 ${active.model ?? active.provider ?? ""} 暂无额度服务` : `GLM 5 小时窗口 ${pct ?? "—"}%`;
513
517
  const toggle = () => {
514
518
  setOpen((v) => {
515
519
  if (v) {
@@ -529,12 +533,12 @@ button.qc-pill[aria-expanded="true"] { background: var(--dsw-alias-interactive-b
529
533
  style: dim ? { opacity: .55 } : void 0,
530
534
  "aria-haspopup": "dialog",
531
535
  "aria-expanded": open,
532
- title: dim ? `当前模型 ${active.model ?? active.provider ?? ""} 暂无额度服务` : `GLM 5 小时窗口 ${pct ?? "—"}%`,
536
+ title: pillTitle,
533
537
  onClick: toggle
534
- }, GaugeIcon(), React.createElement("span", { className: "qc-pill-label" }, pillText), !dim && pct !== void 0 ? React.createElement("span", {
538
+ }, GaugeIcon(), React.createElement("span", { className: "qc-pill-label" }, "额度"), !dim && pillValue !== void 0 ? React.createElement("span", {
535
539
  className: "qc-pill-value",
536
- style: { color: severity(pct) }
537
- }, `${pct}%`) : null), open && getReactDOM().createPortal(renderDialog(React, model, dim, active, panelRef, pos, view, setView, () => {
540
+ style: { color: pillValueColor }
541
+ }, pillValue) : null), open && getReactDOM().createPortal(renderDialog(React, model, dim, active, panelRef, pos, view, setView, () => {
538
542
  fetchReport(true).then(setModel).catch(() => {});
539
543
  }), document.body));
540
544
  }
@@ -680,6 +684,11 @@ button.qc-pill[aria-expanded="true"] { background: var(--dsw-alias-interactive-b
680
684
  function renderDialog(React, model, dim, active, panelRef, pos, view, setView, refresh) {
681
685
  const r = model.report;
682
686
  const rows = [];
687
+ const ds = model.deepseek;
688
+ if (ds !== void 0) {
689
+ if (ds.balance !== void 0) rows.push(React.createElement("dt", { key: "ds-b" }, "DeepSeek 余额"), React.createElement("dd", { key: "ds-bv" }, `${ds.balance.totalBalance.toFixed(2)} ${ds.balance.currency}`), React.createElement("dt", { key: "ds-g" }, "· 赠送金"), React.createElement("dd", { key: "ds-gv" }, ds.balance.grantBalance.toFixed(2)), ...ds.balance.isAvailable ? [] : [React.createElement("dt", { key: "ds-a" }, "状态"), React.createElement("dd", { key: "ds-av" }, "不可用")]);
690
+ else if (ds.error !== void 0) rows.push(React.createElement("dt", { key: "ds-e" }, "DeepSeek"), React.createElement("dd", { key: "ds-ev" }, `查询失败:${ds.error.slice(0, 40)}`));
691
+ }
683
692
  if (dim) rows.push(React.createElement("dt", { key: "p" }, "当前模型"), React.createElement("dd", { key: "pv" }, active.model ?? active.provider ?? "—"), React.createElement("dt", { key: "n" }, "额度服务"), React.createElement("dd", { key: "nv" }, "暂不支持"));
684
693
  else if (r !== void 0) {
685
694
  rows.push(React.createElement("dt", { key: "tier" }, "套餐"), React.createElement("dd", { key: "tierv" }, r.planTier.toUpperCase()), ...model.toolUsage24h !== void 0 ? [
package/dist/index.js CHANGED
@@ -114,6 +114,37 @@ async function fetchGlmUsage(apiKey, baseURL, timeoutMs = 15e3) {
114
114
  if (envelope.data === null || envelope.data === void 0) throw new QuotaCatError("响应缺少 data", "empty");
115
115
  return mapPayload(envelope.data, Date.now());
116
116
  }
117
+ // src/deepseek.ts
118
+ function num(value) {
119
+ const n = Number.parseFloat(value ?? "");
120
+ return Number.isFinite(n) ? n : 0;
121
+ }
122
+ async function fetchDeepseekBalance(apiKey, timeoutMs = 15e3) {
123
+ const controller = new AbortController();
124
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
125
+ let resp;
126
+ try {
127
+ resp = await fetch("https://api.deepseek.com/user/balance", {
128
+ headers: { Authorization: `Bearer ${apiKey}` },
129
+ signal: controller.signal
130
+ });
131
+ } catch (e) {
132
+ throw new QuotaCatError(`DeepSeek 网络错误:${e.message}`, "network");
133
+ } finally {
134
+ clearTimeout(timer);
135
+ }
136
+ if (resp.status === 401 || resp.status === 403) throw new QuotaCatError("DeepSeek API Key 无效(401/403)", "unauthorized");
137
+ if (!(resp.status >= 200 && resp.status < 300)) throw new QuotaCatError(`DeepSeek HTTP ${resp.status}`);
138
+ const data = await resp.json().catch(() => null);
139
+ if (data === null) throw new QuotaCatError("DeepSeek 响应不是合法 JSON", "server");
140
+ const info = data.balance_infos?.[0] ?? {};
141
+ return {
142
+ isAvailable: data.is_available ?? true,
143
+ currency: info.currency ?? "CNY",
144
+ totalBalance: num(info.total_balance),
145
+ grantBalance: num(info.grant_balance)
146
+ };
147
+ }
117
148
  // src/shared/api.ts
118
149
  const API_BASE = "/api/quotacat";
119
150
  const API = {
@@ -157,6 +188,8 @@ const CREDENTIAL_REFS = [
157
188
  "GLM_API_KEY",
158
189
  "ZAI_CODING_CN_API_KEY"
159
190
  ];
191
+ /** DeepSeek API 余额用的凭据名(API key 计费账户,非订阅登录)。 */
192
+ const DEEPSEEK_CREDENTIAL_REFS = ["DEEPSEEK_API_KEY", "DEEPSEEK_KEY"];
160
193
  function isLiveConfig(value) {
161
194
  return typeof value === "object" && value !== null && "get" in value && typeof value.get === "function";
162
195
  }
@@ -192,9 +225,6 @@ function disposeOnStop(ctx, disposer) {
192
225
  function apply(ctx, config) {
193
226
  const logger = ctx.logger(name);
194
227
  const cfg = {
195
- get apiKey() {
196
- return config.apiKey ?? "";
197
- },
198
228
  get refreshMinutes() {
199
229
  return liveValue(config.refreshMinutes, 10);
200
230
  },
@@ -294,7 +324,6 @@ function apply(ctx, config) {
294
324
  }
295
325
  }
296
326
  async function resolveKey() {
297
- if (cfg.apiKey.length > 0) return cfg.apiKey;
298
327
  const credentials = getCredentials();
299
328
  if (credentials !== void 0) for (const ref of CREDENTIAL_REFS) try {
300
329
  const value = (await credentials.resolve(ref))?.value;
@@ -302,25 +331,39 @@ function apply(ctx, config) {
302
331
  } catch {}
303
332
  return process.env.QUOTACAT_API_KEY || process.env.GLM_API_KEY || process.env.ZHIPU_API_KEY || "";
304
333
  }
334
+ async function resolveDeepseekKey() {
335
+ const credentials = getCredentials();
336
+ if (credentials !== void 0) for (const ref of DEEPSEEK_CREDENTIAL_REFS) try {
337
+ const value = (await credentials.resolve(ref))?.value;
338
+ if (typeof value === "string" && value.length > 0) return value;
339
+ } catch {}
340
+ return process.env.DEEPSEEK_API_KEY || "";
341
+ }
305
342
  async function refresh() {
306
- const key = await resolveKey();
307
- if (key.length === 0) {
343
+ const [key, deepseekKey] = await Promise.all([resolveKey(), resolveDeepseekKey()]);
344
+ if (key.length === 0 && deepseekKey.length === 0) {
308
345
  state.error = void 0;
309
346
  return;
310
347
  }
311
- try {
312
- const [report, toolResult] = await Promise.all([fetchGlmUsage(key, cfg.baseURL), fetchGlmToolUsage(key, cfg.baseURL).then((t) => t, () => void 0)]);
348
+ const glmTask = key.length > 0 ? fetchGlmUsage(key, cfg.baseURL).then(async (report) => {
313
349
  state.report = report;
314
- state.toolUsage24h = toolResult;
315
- state.fetchedAt = Date.now();
316
- state.error = void 0;
317
- updateThresholdState();
318
- logger.info("refreshed GLM usage");
319
- } catch (e) {
320
- const err = e;
321
- state.error = err.message;
322
- logger.warn("refresh failed: %s", err.message);
323
- }
350
+ state.toolUsage24h = await fetchGlmToolUsage(key, cfg.baseURL).then((t) => t, () => void 0);
351
+ }).catch((e) => {
352
+ state.error = e.message;
353
+ logger.warn("GLM refresh failed: %s", e.message);
354
+ }) : Promise.resolve();
355
+ const deepseekTask = deepseekKey.length > 0 ? fetchDeepseekBalance(deepseekKey).then((b) => {
356
+ state.deepseek = b;
357
+ state.deepseekError = void 0;
358
+ }).catch((e) => {
359
+ state.deepseekError = e.message;
360
+ logger.warn("DeepSeek refresh failed: %s", e.message);
361
+ }) : Promise.resolve();
362
+ await Promise.all([glmTask, deepseekTask]);
363
+ state.fetchedAt = Date.now();
364
+ if (key.length === 0) state.error = void 0;
365
+ updateThresholdState();
366
+ logger.info("refreshed usage");
324
367
  }
325
368
  /** 阈值提醒状态机:达到阈值触发一次,回落到阈值下方后复位。 */
326
369
  function updateThresholdState() {
@@ -360,6 +403,10 @@ function apply(ctx, config) {
360
403
  error: state.error,
361
404
  report: state.report,
362
405
  toolUsage24h: state.toolUsage24h,
406
+ deepseek: state.deepseek === void 0 && state.deepseekError === void 0 ? void 0 : {
407
+ balance: state.deepseek,
408
+ error: state.deepseekError
409
+ },
363
410
  threshold: thresholdAlert()
364
411
  };
365
412
  }
@@ -426,17 +473,12 @@ function apply(ctx, config) {
426
473
  provider,
427
474
  ...v
428
475
  })),
429
- configKey: cfg.apiKey.length > 0,
430
476
  baseURL: cfg.baseURL
431
477
  });
432
478
  }
433
479
  }));
434
480
  /** 密钥当前来源(不回传明文)。 */
435
481
  async function describeKey() {
436
- if (cfg.apiKey.length > 0) return {
437
- source: "config",
438
- masked: `${cfg.apiKey.slice(0, 5)}…${cfg.apiKey.slice(-4)}`
439
- };
440
482
  const credentials = getCredentials();
441
483
  if (credentials !== void 0) for (const ref of CREDENTIAL_REFS) try {
442
484
  if (credentials.describe === void 0) break;
@@ -577,14 +619,22 @@ function apply(ctx, config) {
577
619
  const resp = await buildResponse();
578
620
  if (resp.error !== void 0) return `查询失败:${resp.error}`;
579
621
  const r = resp.report;
580
- if (r === void 0) return "暂无数据";
581
- return [`GLM Coding Plan(${r.planTier})· 更新于 ${new Date(r.fetchedAt).toLocaleString()}`, ...r.windows.map((w) => {
622
+ const lines = [];
623
+ if (r !== void 0) lines.push(`GLM Coding Plan(${r.planTier})· 更新于 ${new Date(r.fetchedAt).toLocaleString()}`, ...r.windows.map((w) => {
582
624
  const pct = `${Math.round(w.percentage * 100)}%`;
583
625
  const reset = w.resetsAt !== void 0 ? `,重置于 ${new Date(w.resetsAt).toLocaleTimeString()}` : "";
584
626
  const detail = w.kind === "fiveHourTokens" ? `(已用 ${w.currentUsage}/${w.total} tokens)` : "";
585
627
  const mcp = w.mcpToolBreakdown?.length ? ` [${w.mcpToolBreakdown.map((m) => `${m.tool}:${m.count}`).join(", ")}]` : "";
586
628
  return `- ${w.label}:${pct}${detail}${reset}${mcp}`;
587
- })].join("\n");
629
+ }));
630
+ const ds = resp.deepseek;
631
+ if (ds !== void 0) {
632
+ if (ds.balance !== void 0) {
633
+ const b = ds.balance;
634
+ lines.push(`DeepSeek API · 余额 ${b.totalBalance.toFixed(2)} ${b.currency}(含赠送 ${b.grantBalance.toFixed(2)})${b.isAvailable ? "" : " · 账户不可用"}`);
635
+ } else if (ds.error !== void 0) lines.push(`DeepSeek API · 查询失败:${ds.error}`);
636
+ }
637
+ return lines.length > 0 ? lines.join("\n") : "暂无数据";
588
638
  }
589
639
  }));
590
640
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-quotacat",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "QuotaCat for DeepSeek Harness — LLM provider usage & quota monitoring: composer-dock pill, detail dialog, threshold alerts, and a quota agent tool. GLM Coding Plan supported today; more providers on the way.",
5
5
  "license": "MIT",
6
6
  "type": "module",