@anthonyhan/token-pilot 0.4.5 → 0.4.7

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
@@ -126,14 +126,32 @@ npm test # 69 个单元测试(定价/采集口径
126
126
 
127
127
  账单回答「花了多少钱」,额度回答「还能用多少」。后者来自平台自己的接口,不是本地推算。
128
128
 
129
+ **已实测可用**(用真实 key 打出真实数据验证过):
130
+
129
131
  | 平台 | 能拿到什么 | 数据来源 |
130
132
  |---|---|---|
131
133
  | **OpenCode Go** | 滚动 / 本周 / 本月三个窗口的已用百分比 | 官方接口,用 OpenCode 自己的登录态 |
132
134
  | **火山方舟** | Agent Plan 的额度绝对值 + 百分比;Coding Plan 的百分比 | 官方 CLI `arkcli usage plan` |
133
135
  | **智谱 GLM** | 额度窗口 + 套餐档位 | 官方接口 |
134
- | **DeepSeek / Moonshot** | 现金余额 | 官方余额接口 |
135
- | **OpenRouter** | 剩余额度(累计充值 − 累计已用) | 官方接口,实测确认 |
136
- | **MiniMax** | Token Plan 剩余量 | 官方接口 |
136
+ | **DeepSeek** | 现金余额 | `GET /user/balance` |
137
+ | **Moonshot / Kimi** | 可用余额(代金券 + 现金) | `GET /v1/users/me/balance` |
138
+ | **OpenRouter** | 剩余额度(累计充值 − 累计已用) | `GET /api/v1/credits` |
139
+
140
+ **已探到端点、等待实测**(界面上标「待验证」,拿到对应 key 就能启用):
141
+
142
+ | 平台 | 需要什么 | 卡在哪 |
143
+ |---|---|---|
144
+ | MiniMax 余额 | **admin key** | 普通 key 报 `token_type_mismatch` |
145
+ | MiniMax Token Plan | 有效订阅 | 账号无订阅时返回 `2062`,拿不到字段结构 |
146
+ | Kimi Code 订阅 | Kimi Code 订阅账号 | 端点与字段链已知,待验证 |
147
+ | Novita AI | 普通 key | 端点存在,字段待验证 |
148
+ | 阶跃 StepFun | — | **无公开余额接口**(16 个路径全 404,文档只有 chat) |
149
+ | SiliconFlow | — | **国内站接口已废弃**(410 deprecated) |
150
+
151
+ > 为什么分两栏:探到 401 不代表接口能用——很多网关对不存在的路径也返 401。
152
+ > 只有用真实 key 拿到真实 JSON、确认字段语义无误的,才算「可用」。
153
+ > 这个原则避免了两次误判:OpenRouter 的「累计充值」差点被当成余额
154
+ > (会显示「还剩 $0.34」而实际已用光),MiniMax 的鉴权头格式错差点被当成 key 无效。
137
155
 
138
156
  **凭证从哪来**(三级降级,装了哪个用哪个):
139
157
 
@@ -141,9 +159,24 @@ npm test # 69 个单元测试(定价/采集口径
141
159
  2. 平台自己的登录凭据(如 OpenCode 的 `~/.local/share/opencode/auth.json`)—— 装了该工具就有
142
160
  3. [CC Switch](https://github.com/farion1231/cc-switch) 的配置 —— **装了才自动读取,不装完全可以正常用**
143
161
 
144
- > 第 3 层是便利不是依赖:不装 CC Switch 的用户,填一次 key 就能获得全部额度功能。
162
+ > 第 3 层是便利不是依赖:不装 CC Switch 的用户,点「+ 添加平台」填一次 key 就能获得全部额度功能。
163
+ > CC Switch 里配过的平台会自动回填成「CC Switch 读取」并设为只读,避免你手填一遍算两次。
164
+
165
+ **怎么加平台**:
166
+
167
+ 1. 设置里点「+ 添加平台」→ 下拉选平台 → 粘贴 key → 确定。余额和订阅是两套 key,分开填
168
+ 2. 内置列表没有的,选「添加自定义平台」,填「名称 + 接口地址 + 金额字段路径(如 `data.balance`)」即可
169
+ 3. 内置平台的端点定义在 [`catalog.ts`](src/core/quota/providers/catalog.ts),加一条数据就是加一个平台
170
+
171
+ **余额和订阅是两件事**,所以分开配置、分开显示:
172
+
173
+ | | 余额 | 订阅 |
174
+ |---|---|---|
175
+ | 回答 | 账户还剩多少钱 | 套餐用了多少、何时重置 |
176
+ | key | 通常普通 key 即可 | 部分平台要 admin key |
177
+ | 例子 | DeepSeek ¥20.10 | 火山 Coding Plan 本月 29% |
145
178
 
146
- **自己加平台**:设置里「添加自定义平台」,填「名称 + 余额接口地址 + 金额字段路径(如 `data.balance`)」就能查任意提供余额接口的服务,不用等我发版。内置平台的端点定义在 [`catalog.ts`](src/core/quota/providers/catalog.ts),加一条就是加一个平台。
179
+ 同一个平台可以两套都配(比如 MiniMax 查订阅用普通 key、查余额用 admin key),key 按「平台 + 场景」分开存,互不覆盖。
147
180
 
148
181
  **关于接口字段的坑**:有些平台不返回「余额」,只给「累计充值」和「累计已用」两个数(OpenRouter 就是这样)。直接拿累计充值当余额会显示成「还剩 $0.34」,而实际一分不剩——所以这类平台会做减法。没验证过字段语义的接口一律标为未启用,不会拿错的数字糊弄你。
149
182
 
@@ -242,7 +275,7 @@ token-pilot 免费且 MIT。如果它帮你省下了 AI 账单,可以请我喝
242
275
  - [x] Cursor spike(结论:无 token 用量数据,ai-code-tracking 是代码追踪非用量 → 诚实归「仅检测」)
243
276
  - [x] 云端用量 API:Doubao 火山(arkcli usage stats,日粒度)
244
277
  - [⏸] 云端用量 API:OpenAI / Kimi 开放平台
245
- - **实测结论**(2026-11 探测):Kimi 开放平台**没有公开的用量查询端点**——`/v1/users/me/balance` 存在(401 需鉴权),但 `/v1/usage`、`/v1/users/me/usage`、`/api/v1/usage` 全部 404。目前只能查余额,查不到「今天用了多少」
278
+ - **实测结论**(2026-11):Kimi 的**余额已接通**(`GET /v1/users/me/balance` → `data.available_balance`,真实 key 验证通过)。但**没有用量查询端点**——`/v1/usage`、`/v1/users/me/usage`、`/api/v1/usage` 全部 404。所以「还剩多少」能查,「今天花了多少」查不到
246
279
  - OpenAI 有 `/v1/organization/usage/*` 这类用量端点,但都是组织级接口,需要 Organization Admin key 才能调。**我没有 admin key,无法验证个人 key 是否也可用**——所以这项标「卡住」而不是「简单待办」
247
280
  - 如果你手上有 OpenAI 的 admin key 或知道 Kimi 的用量接口,发我实测一次,验证通过我当天就能接上
248
281
 
package/dist/cli/index.js CHANGED
@@ -288,6 +288,25 @@ async function main() {
288
288
  console.log(formatQuota(snap));
289
289
  return;
290
290
  }
291
+ // 测试连接:桌面端(无 serve)靠这个命令跑,输出 JSON 给前端渲染。
292
+ // 参数从 stdin 读 {keys, customs},避免把 key 放进命令行参数——
293
+ // 那样会出现在 ps 输出和历史里。
294
+ if (cmd === 'quota-test') {
295
+ const chunks = [];
296
+ for await (const c of process.stdin)
297
+ chunks.push(c);
298
+ let payload = {};
299
+ try {
300
+ payload = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
301
+ }
302
+ catch {
303
+ /* 空输入按空对象处理 */
304
+ }
305
+ const { testEndpoints } = await import('../core/quota/providers/declarative.js');
306
+ const results = await testEndpoints(payload.keys ?? {}, Array.isArray(payload.customs) ? payload.customs : []);
307
+ console.log(JSON.stringify({ results }));
308
+ return;
309
+ }
291
310
  if (cmd === 'doctor') {
292
311
  const { runDoctor, formatDoctor } = await import('../core/doctor.js');
293
312
  const report = await runDoctor();
package/dist/cli/serve.js CHANGED
@@ -115,36 +115,14 @@ export async function serve(port = 17895) {
115
115
  }
116
116
  // 测试连接:用「本次输入的 key」直接打一次接口。
117
117
  // 必须先于保存就能测——否则用户得先存一个可能错的 key 才能验证。
118
+ // 测试连接:用「本次输入的 key」直接打一次接口。
119
+ // 必须先于保存就能测——否则用户得先存一个可能错的 key 才能验证。
120
+ // 逻辑在 core 里(testEndpoints),桌面端通过 Tauri 命令走同一条路径。
118
121
  if (url === '/api/quota/test' && req.method === 'POST') {
119
122
  const body = await readBody(req);
120
- const { keys } = JSON.parse(body || '{}');
121
- const { verifiedSpecs } = await import('../core/quota/providers/catalog.js');
122
- const { fetchDeclarativeBalance, loadCustomEndpoints } = await import('../core/quota/providers/declarative.js');
123
- // 自定义端点也转成同样形状的 spec,复用同一套请求/解析
124
- const customs = (await loadCustomEndpoints()).map((c) => ({
125
- id: c.id,
126
- displayName: c.displayName,
127
- endpoint: c.endpoint,
128
- auth: c.auth,
129
- amount: { path: c.amountPath, kind: 'balance' },
130
- currency: c.currency ?? 'CNY',
131
- keyUrl: '',
132
- verified: 'custom',
133
- }));
134
- const specs = [...verifiedSpecs(), ...customs];
135
- const results = await Promise.all(specs.map(async (spec) => {
136
- const override = keys?.[spec.id]?.trim();
137
- const probe = await fetchDeclarativeBalance(spec, override || undefined);
138
- return {
139
- id: spec.id,
140
- displayName: spec.displayName,
141
- ok: probe.ok,
142
- detail: probe.ok && probe.balance
143
- ? `${probe.balance.currency === 'CNY' ? '¥' : '$'}${probe.balance.amount.toFixed(2)}`
144
- : undefined,
145
- error: probe.ok ? undefined : probe.error,
146
- };
147
- }));
123
+ const { keys, customs } = JSON.parse(body || '{}');
124
+ const { testEndpoints } = await import('../core/quota/providers/declarative.js');
125
+ const results = await testEndpoints(keys ?? {}, Array.isArray(customs) ? customs : []);
148
126
  res.writeHead(200, {
149
127
  'content-type': 'application/json; charset=utf-8',
150
128
  'cache-control': 'no-store',
@@ -6,7 +6,7 @@ import { detectRetryLoops } from './retry-detector.js';
6
6
  import { savingsAdvice } from './savings.js';
7
7
  import { computeCompression } from './compression.js';
8
8
  import { buildAdapterTiers, HOST_TIERS } from './registry.js';
9
- import { BALANCE_CATALOG } from './quota/providers/catalog.js';
9
+ import { API_CATALOG, keySlot } from './quota/providers/catalog.js';
10
10
  import { APP_VERSION } from './version.js';
11
11
  /**
12
12
  * 目录里挑一批「大概率会用到」的模型,给全新用户做默认单价行。
@@ -534,14 +534,11 @@ export async function buildDashboardData(rawEvents, cfg, pricing, contentEvents
534
534
  }
535
535
  // ---------- 适配器状态 ----------
536
536
  const adapters = await buildAdapterTiers(cfg);
537
- // ---------- 设置 ----------
538
- const settings = await buildSettings(events, cfg, pricing, fx, d30);
539
- // ---------- 托盘 ----------
540
- const trayTitle = budget
541
- ? `${fmtCny(today.costUsd * fx)} · ${Math.round(budget.pct)}%`
542
- : fmtCny(today.costUsd * fx);
543
537
  // 额度是可选能力:外部接口慢或挂掉都不能拖住账单。
544
538
  // 8 秒超时,超时就给 null,看板照常显示。
539
+ //
540
+ // 注意顺序:必须先于 buildSettings 采集——订阅登记要据此判断
541
+ // 「这个平台的月费已经能自动识别」,拿不到额度就只能退回手填。
545
542
  let quota = null;
546
543
  try {
547
544
  const { collectQuota } = await import('./quota/index.js');
@@ -553,6 +550,12 @@ export async function buildDashboardData(rawEvents, cfg, pricing, contentEvents
553
550
  catch {
554
551
  quota = null;
555
552
  }
553
+ // ---------- 设置 ----------
554
+ const settings = await buildSettings(events, cfg, pricing, fx, d30, quota);
555
+ // ---------- 托盘 ----------
556
+ const trayTitle = budget
557
+ ? `${fmtCny(today.costUsd * fx)} · ${Math.round(budget.pct)}%`
558
+ : fmtCny(today.costUsd * fx);
556
559
  return {
557
560
  appVersion: APP_VERSION,
558
561
  generatedAt: nowMs,
@@ -850,25 +853,76 @@ function buildKeyStatus(cfg) {
850
853
  // 太短的 key 全遮,防止「后 4 位就是全部」
851
854
  return t.length <= 8 ? '••••' : `••••${t.slice(-4)}`;
852
855
  };
853
- // 内置平台:即使没配 key 也列出,给用户「去哪申请」的入口
854
- for (const spec of BALANCE_CATALOG) {
855
- shown.add(spec.id);
856
+ // 内置平台:每个「平台 × 场景」一行。余额和订阅是两套 key,
857
+ // 必须分开列——MiniMax 就是普通 key 能查订阅、admin key 才能查余额。
858
+ for (const spec of API_CATALOG) {
859
+ const slot = keySlot(spec.id, spec.scenario);
860
+ shown.add(slot);
856
861
  rows.push({
857
862
  id: spec.id,
863
+ scenario: spec.scenario,
858
864
  displayName: spec.displayName,
859
- masked: mask(stored[spec.id]),
865
+ masked: mask(stored[slot]),
860
866
  keyUrl: spec.keyUrl || undefined,
867
+ keyKind: spec.keyKind,
868
+ needsAdmin: spec.keyKind === 'admin',
869
+ implemented: spec.verified !== null,
861
870
  });
862
871
  }
863
- // 用户自己配过但不在内置目录里的(自定义端点等)也要显示,否则用户存了看不见
864
- for (const [id, key] of Object.entries(stored)) {
865
- if (shown.has(id))
872
+ // 用户自己配过但不在内置目录里的(自定义端点等)也要显示,否则存了看不见
873
+ for (const [slot, key] of Object.entries(stored)) {
874
+ if (shown.has(slot))
866
875
  continue;
867
- rows.push({ id, displayName: id, masked: mask(key) });
876
+ const [id, sc] = slot.split(':');
877
+ rows.push({
878
+ id: slot,
879
+ scenario: sc ?? 'balance',
880
+ displayName: id,
881
+ masked: mask(key),
882
+ });
868
883
  }
869
884
  return rows;
870
885
  }
871
- async function buildSettings(events, cfg, pricing, fx, d30) {
886
+ /**
887
+ * 订阅登记:把「用户手填的」和「接口已能自动识别的」分开处理,避免重复计费。
888
+ *
889
+ * 问题:一个平台的订阅月费如果既从接口查到(Token Plan)、又被用户在
890
+ * 「订阅登记」里手填一遍,账单会把同一笔钱算两次。
891
+ *
892
+ * 规则:
893
+ * - 接口能查到套餐且价格确定 → 标记 autoDetected,带上接口给的月费和套餐名,
894
+ * 前端显示「已自动识别,无需手填」,用户不能再手填覆盖
895
+ * - 接口查不到 / 价格不确定 → 保持手填(autoDetected: false)
896
+ *
897
+ * 注意:现在还没有任何平台在接口里返回价格(MiniMax 只回用量不回价格),
898
+ * 所以这条通路目前只有在 provider 显式填了 monthlyCny 时才生效。
899
+ * 不编数字——宁可让用户手填,也不猜一个价格自动算进账单。
900
+ */
901
+ export function buildSubscriptions(cfg, quota) {
902
+ const manual = cfg.subscriptions ?? [];
903
+ const auto = [];
904
+ for (const p of quota?.providers ?? []) {
905
+ const tp = p.tokenPlan;
906
+ // 只有「确实查到了套餐」且「价格明确」才算自动识别
907
+ if (!p.ok || !tp?.planName || tp.monthlyCny == null)
908
+ continue;
909
+ auto.push({
910
+ name: tp.planName,
911
+ monthlyCny: tp.monthlyCny,
912
+ origin: 'api',
913
+ providerId: p.id,
914
+ });
915
+ }
916
+ // 自动识别的平台,把用户可能手填过的同名条目过滤掉,防止重复计费
917
+ const autoNames = new Set(auto.map((a) => a.name.toLowerCase()));
918
+ const autoIds = new Set(auto.map((a) => a.providerId));
919
+ const kept = manual.filter((m) => !autoNames.has(m.name.toLowerCase()) && !autoIds.has(m.name.toLowerCase()));
920
+ return [
921
+ ...auto,
922
+ ...kept.map((m) => ({ name: m.name, monthlyCny: m.monthlyCny, origin: 'manual' })),
923
+ ];
924
+ }
925
+ async function buildSettings(events, cfg, pricing, fx, d30, quota = null) {
872
926
  // RTK 状态:区分「本工具装的 rtk-oss」与「别的来源的 rtk」,前端据此如实展示
873
927
  const rtkSt = await import('./rtk.js')
874
928
  .then((m) => m.rtkStatus())
@@ -915,7 +969,7 @@ async function buildSettings(events, cfg, pricing, fx, d30) {
915
969
  models,
916
970
  overrideNames: Object.keys(cfg.priceOverrides ?? {}),
917
971
  cloudApis: cfg.cloudApis ?? [],
918
- subscriptions: cfg.subscriptions ?? [],
972
+ subscriptions: buildSubscriptions(cfg, quota),
919
973
  quotaKeys: buildKeyStatus(cfg),
920
974
  monthlyBudgetCny: monthlyBudgetCny(cfg) ?? null,
921
975
  usdToCny: fx,
@@ -14,10 +14,20 @@ import os from 'node:os';
14
14
  import path from 'node:path';
15
15
  import { loadConfig } from '../config.js';
16
16
  const execFileP = promisify(execFile);
17
- /** 从 token-pilot 自己的配置读(优先级最高,用户显式填的) */
18
- export function fromConfig(providerId) {
17
+ /**
18
+ * 从 token-pilot 自己的配置读(优先级最高,用户显式填的)。
19
+ *
20
+ * 存储键是 `平台:场景`(如 `minimax:balance` / `minimax:subscription`),
21
+ * 因为余额和订阅往往要不同的 key(MiniMax 查余额要 admin key)。
22
+ *
23
+ * 兼容旧数据:早先只按平台名存(`deepseek`),读不到新键时回退到旧键,
24
+ * 这样升级后用户已填的 key 不会失效。
25
+ */
26
+ export function fromConfig(providerId, scenario) {
19
27
  const cfg = loadConfig();
20
- const key = cfg.quotaKeys?.[providerId];
28
+ const store = cfg.quotaKeys ?? {};
29
+ const slot = scenario ? `${providerId}:${scenario}` : providerId;
30
+ const key = store[slot] ?? store[providerId];
21
31
  if (!key || !key.trim())
22
32
  return null;
23
33
  return { key: key.trim(), origin: 'config', detail: '来自 token-pilot 设置' };
@@ -116,8 +126,8 @@ print('')
116
126
  /**
117
127
  * 三层依次尝试。全部失败返回 null,调用方负责给出「去哪里填」的提示。
118
128
  */
119
- export async function resolveKey(providerId, ccSwitchPattern) {
120
- return (fromConfig(providerId) ??
129
+ export async function resolveKey(providerId, ccSwitchPattern, scenario) {
130
+ return (fromConfig(providerId, scenario) ??
121
131
  fromNative(providerId) ??
122
132
  (ccSwitchPattern ? await fromCcSwitch(ccSwitchPattern) : null));
123
133
  }
@@ -1,56 +1,49 @@
1
- // 内置平台目录 —— 声明式描述「怎么查这个平台的余额/额度」。
1
+ // 平台余额 / 订阅查询目录 —— 声明式描述「怎么查」。
2
2
  //
3
- // 为什么要有这个文件:原来的 balance.ts 是**每个平台一个专用函数**,
4
- // 加一个平台就要写代码 + 发版,用户也没法自己加。
5
- // 现在把「端点 + 鉴权方式 + 怎么从 JSON 里取数」抽成数据,
6
- // 加平台 = 往这个数组里加一条,不用改逻辑。
3
+ // 关键设计:**余额和订阅是两件事,用两套 key、两套端点**。
4
+ // - 余额(balance):现金账户还剩多少钱
5
+ // - 订阅(subscription):套餐用了多少、什么时候重置,往往要 admin key
6
+ // 很多平台两者权限不同(MiniMax 就是典型:普通 key 能查订阅,查余额要 admin key),
7
+ // 所以 key 按 `平台:场景` 分别存,互不覆盖。
7
8
  //
8
- // ⚠️ verified 字段是硬门槛:
9
- // 只写「端点存在」不够——很多网关对不存在的路径也返回 401,
10
- // 光看状态码会把不存在的接口当成存在(踩过一次:GLM 的 401 是误判)。
11
- // 所以只有用**真实 key 打出真实 JSON**、确认字段路径无误的平台才填日期,
12
- // 没验过的一律 verified: null,运行时跳过并在 doctor 里标出来。
9
+ // ⚠️ verified 是硬门槛:
10
+ // 只探测到 401 不算数——很多网关对不存在的路径也返 401(GLM 踩过)。
11
+ // 必须用真实 key 打出真实 JSON、确认字段路径无误,才填日期。
12
+ // 没验过的一律 null,运行时不启用。
13
13
  /**
14
14
  * 内置目录。
15
15
  *
16
- * 目前只有 verified 非空的会被启用。表里保留未验证条目不是摆设——
17
- * 它们记录了「端点探测结果」,避免以后重复调研,
18
- * 也方便有人提供 key 时直接补测。
16
+ * 调研范围(2026-11):国内 8 家 + 海外 6 家实测。结论:
17
+ * - 大多数平台**没有公开余额接口**(百川/零一万物/商汤/腾讯混元/阿里百炼 全 404)
18
+ * - OpenAI / Anthropic 只有组织级 admin 接口
19
+ * - 能接的不多不是做得少,是平台没开放
20
+ * 未验证条目保留在表里不是摆设:记录探测结果避免重复调研,
21
+ * 也方便拿到 key 时直接补测。
19
22
  */
20
- export const BALANCE_CATALOG = [
23
+ export const API_CATALOG = [
24
+ // ───────── 余额 ─────────
21
25
  {
22
26
  id: 'deepseek',
23
27
  displayName: 'DeepSeek',
28
+ scenario: 'balance',
24
29
  endpoint: 'https://api.deepseek.com/user/balance',
25
30
  auth: 'bearer',
26
- // 返回结构:{"is_available":true,"balance_infos":[{"currency":"CNY","total_balance":"11.40"}]}
31
+ // {"is_available":true,"balance_infos":[{"currency":"CNY","total_balance":"11.40"}]}
27
32
  amount: { path: 'balance_infos[0].total_balance', kind: 'balance' },
28
33
  currencyPath: 'balance_infos[0].currency',
29
34
  keyUrl: 'https://platform.deepseek.com/api_keys',
30
- // 历史实现已在生产使用,结构由真实 key 确认
35
+ keyKind: 'normal',
31
36
  verified: '2026-10-29',
32
37
  },
33
- {
34
- id: 'moonshot',
35
- displayName: 'Moonshot / Kimi',
36
- endpoint: 'https://api.moonshot.cn/v1/users/me/balance',
37
- auth: 'bearer',
38
- // 返回结构:{"code":0,"data":{"available_balance":<number>,"voucher_balance":...,"cash_balance":...}}
39
- amount: { path: 'data.available_balance', kind: 'balance' },
40
- currency: 'CNY',
41
- keyUrl: 'https://platform.moonshot.cn/console/api-keys',
42
- verified: null, // 端点存在(401)但尚未用真实 key 验证字段路径
43
- note: '待用真实 key 核实字段名',
44
- },
45
38
  {
46
39
  id: 'openrouter',
47
40
  displayName: 'OpenRouter',
41
+ scenario: 'balance',
48
42
  endpoint: 'https://openrouter.ai/api/v1/credits',
49
43
  auth: 'bearer',
50
- // 实测(2026-11-05,真实 key):{"data":{"total_credits":0.339163134,
51
- // "total_usage":0.339163134}}
52
- // 注意:total_credits 是**累计充值**不是余额,必须减去 total_usage。
53
- // 直接拿 credits 当余额会显示「还剩 $0.34」,而实际剩余是 0。
44
+ // 实测 2026-11-05:{"data":{"total_credits":0.339,"total_usage":0.339}}
45
+ // total_credits 是累计充值不是余额,必须减去 total_usage;
46
+ // 直接当余额会显示「还剩 $0.34」而实际剩余是 0
54
47
  amount: {
55
48
  path: 'data.total_credits',
56
49
  subtractPath: 'data.total_usage',
@@ -58,39 +51,177 @@ export const BALANCE_CATALOG = [
58
51
  },
59
52
  currency: 'USD',
60
53
  keyUrl: 'https://openrouter.ai/keys',
54
+ keyKind: 'normal',
55
+ verified: '2026-11-05',
56
+ },
57
+ {
58
+ id: 'moonshot',
59
+ displayName: 'Moonshot / Kimi',
60
+ scenario: 'balance',
61
+ endpoint: 'https://api.moonshot.cn/v1/users/me/balance',
62
+ auth: 'bearer',
63
+ // 实测 2026-11-05(真实 key):
64
+ // {"code":0,"data":{"available_balance":15,"voucher_balance":15,"cash_balance":0}}
65
+ // available_balance = 代金券 + 现金,即真正可用的总额——就该显示它,
66
+ // 单看 cash_balance 会显示 0(钱都在代金券里),那是误导。
67
+ amount: { path: 'data.available_balance', kind: 'balance' },
68
+ currency: 'CNY',
69
+ keyUrl: 'https://platform.moonshot.cn/console/api-keys',
70
+ keyKind: 'normal',
61
71
  verified: '2026-11-05',
62
72
  },
63
73
  {
64
74
  id: 'minimax',
65
75
  displayName: 'MiniMax',
76
+ scenario: 'balance',
77
+ endpoint: 'https://api.minimaxi.com/v1/account/balance',
78
+ auth: 'bearer',
79
+ // 实测 2026-11-05:普通 key 返回 403 token_type_mismatch
80
+ // 「api key is not an admin key」——查余额必须 admin key
81
+ amount: { path: 'data.balance', kind: 'balance' },
82
+ currency: 'CNY',
83
+ keyUrl: 'https://platform.minimaxi.com/user-center/basic-information/interface-key',
84
+ keyKind: 'admin',
85
+ verified: null,
86
+ // 实测 2026-11-05:两个普通 key(sk-api-...)都返回
87
+ // 403 {"code":"token_type_mismatch","message":"api key is not an admin key"}。
88
+ // 查余额必须到控制台单独创建 admin key,普通 API key 不行。
89
+ note: '需要 admin key;实测普通 sk-api- key 报 token_type_mismatch',
90
+ },
91
+ {
92
+ id: 'stepfun',
93
+ displayName: '阶跃 StepFun',
94
+ scenario: 'balance',
95
+ endpoint: 'https://api.stepfun.com/v1/accounts/balance',
96
+ auth: 'bearer',
97
+ amount: { path: 'data.balance', kind: 'balance' },
98
+ currency: 'CNY',
99
+ keyUrl: 'https://platform.stepfun.com/interface-key',
100
+ keyKind: 'normal',
101
+ verified: null,
102
+ // 实测 2026-11-05(真实有效 key,/v1/models 返回 200 证明 key 可用):
103
+ // 该端点返回 404 page not found —— 说明此前探测到的 401 是网关对
104
+ // 未认证请求的统一拦截,并不代表端点存在。这正是「401 不能当存在证据」
105
+ // 的又一个案例。
106
+ // 另外试过 /v1/user/balance、/v1/account/balance、/v1/users/me/balance、
107
+ // /v1/finance/balance、/v1/billing/balance、/v1/usage、/v1/open/balance、
108
+ // /v1/dashboard/billing/credit_grants 等 8 个路径,全部 404。
109
+ // 结论:StepFun 目前没有公开的余额查询接口,控制台可见但不能程序化读取。
110
+ note: '无公开余额接口:官方文档(stepfun.mintlify.app)API 参考只有 chat 一个接口,' +
111
+ '16 个管理端点实测全 404,key 本身有效(/v1/models 返回 200)。余额只能到控制台看',
112
+ },
113
+ // ───────── 从 CC Switch 反解出的新平台(2026-11-05)─────────
114
+ // 这些端点是从 CC Switch.app 二进制里提取的(它有 src/commands/balance.rs)。
115
+ // 端点存在性已用无 key 请求确认(返回鉴权错误而非 404),
116
+ // 但字段结构未用真实 key 验证,所以 verified 仍为 null。
117
+ {
118
+ id: 'siliconflow',
119
+ displayName: 'SiliconFlow 硅基流动',
120
+ scenario: 'balance',
121
+ // 官方文档(docs.siliconflow.com)确认端点是 /v1/user/info,字段 totalBalance。
122
+ // 但实测发现国内站该端点已废弃:
123
+ // api.siliconflow.cn/v1/user/info → 410
124
+ // {"code":20092,"message":"This endpoint is deprecated and is no longer available."}
125
+ // 国际站 api.siliconflow.com 同一端点返回 401「Token is invalid」——
126
+ // 说明端点在国际站仍有效,只是国内 key 不跨站。
127
+ // 保留 .cn 是因为国内用户绝大多数用 .cn;等官方恢复或换新路径再启用。
128
+ endpoint: 'https://api.siliconflow.cn/v1/user/info',
129
+ auth: 'bearer',
130
+ amount: { path: 'data.totalBalance', kind: 'balance' },
131
+ currency: 'CNY',
132
+ keyUrl: 'https://cloud.siliconflow.cn/account/ak',
133
+ keyKind: 'normal',
134
+ verified: null,
135
+ note: '国内站 /v1/user/info 已废弃(410 deprecated);国际站同端点有效但 key 不跨站。' +
136
+ 'key 本身有效(/v1/models 返回 200)',
137
+ },
138
+ {
139
+ id: 'novita',
140
+ displayName: 'Novita AI',
141
+ scenario: 'balance',
142
+ endpoint: 'https://api.novita.ai/v3/user/balance',
143
+ auth: 'bearer',
144
+ amount: { path: 'availableBalance', kind: 'balance' },
145
+ currency: 'USD',
146
+ keyUrl: 'https://novita.ai/settings/key-management',
147
+ keyKind: 'normal',
148
+ verified: null,
149
+ note: '端点存在(400 MISSING_API_KEY);字段结构待真实 key 核实',
150
+ },
151
+ // ───────── 订阅 / 额度 ─────────
152
+ {
153
+ id: 'glm',
154
+ displayName: '智谱 GLM',
155
+ scenario: 'subscription',
156
+ endpoint: 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',
157
+ auth: 'bearer',
158
+ amount: { path: 'data.limits[0].remaining', kind: 'remaining' },
159
+ currency: 'CNY',
160
+ keyUrl: 'https://open.bigmodel.cn/usercenter/apikeys',
161
+ keyKind: 'normal',
162
+ verified: null,
163
+ note: '已由独立 provider 处理(多额度窗口),此处保留端点记录',
164
+ },
165
+ {
166
+ id: 'kimi-coding',
167
+ displayName: 'Kimi Code 订阅',
168
+ scenario: 'subscription',
169
+ endpoint: 'https://api.kimi.com/coding/v1/usages',
170
+ auth: 'bearer',
171
+ // CC Switch 解析的字段链:data.limits[].detail → remaining /
172
+ // resetTime / five_hour / weekly_limit,以及 quota_5_hour / quota_7_day
173
+ // (resets_at / used_value_usd / max_value_usd)
174
+ amount: { path: 'data.limits[0].detail.remaining', kind: 'remaining' },
175
+ currency: 'CNY',
176
+ keyUrl: 'https://platform.moonshot.cn/console/api-keys',
177
+ keyKind: 'normal',
178
+ verified: null,
179
+ note: 'Kimi Code 订阅额度(与余额是两个账号体系);字段链来自 CC Switch 解析逻辑,待实测',
180
+ },
181
+ {
182
+ id: 'minimax',
183
+ displayName: 'MiniMax',
184
+ scenario: 'subscription',
66
185
  endpoint: 'https://api.minimaxi.com/v1/token_plan/remains',
67
- // 实测(2026-11-05,真实 key):必须 Bearer,裸 key 会报 1004
68
- // 「login fail: Please carry the API secret key in the 'Authorization' field」。
69
- // 原先这里写成 raw 是错的。
70
186
  auth: 'bearer',
71
- // 这是 Token Plan(预付包),不是现金余额;由现有 minimax provider 处理
187
+ // 实测 2026-11-05:必须 Bearer,裸 key 报 1004「login fail」
188
+ //(看着像 key 无效,其实是鉴权头格式错)
72
189
  amount: { path: 'model_remains[0].current_interval_total_count', kind: 'remaining' },
73
190
  currency: 'CNY',
74
191
  keyUrl: 'https://platform.minimaxi.com/user-center/basic-information/interface-key',
192
+ keyKind: 'normal',
75
193
  verified: null,
76
- note: 'Token Plan 预付费包(非现金余额)。查余额 /v1/account/balance 需要 admin key,普通 key 报 403 token_type_mismatch;无订阅时该接口返回 2062 no active token plan subscription',
194
+ // 实测 2026-11-05:key 有效(能过鉴权),但该账号无生效订阅,
195
+ // 返回 2062 no active token plan subscription,拿不到 model_remains 结构,
196
+ // 所以无法确认字段路径,暂不启用。
197
+ note: '账号无生效 Token Plan 订阅(2062),字段结构未实测',
77
198
  },
78
199
  ];
79
- /** 取已启用的条目(verified 非空) */
80
- export function verifiedSpecs() {
81
- return BALANCE_CATALOG.filter((s) => s.verified !== null);
200
+ /** 按场景取条目 */
201
+ export function specsFor(scenario) {
202
+ return API_CATALOG.filter((s) => s.scenario === scenario);
203
+ }
204
+ /** 已启用的条目(verified 非空) */
205
+ export function verifiedSpecs(scenario) {
206
+ return API_CATALOG.filter((s) => s.verified !== null && (!scenario || s.scenario === scenario));
207
+ }
208
+ /** 未验证的条目(doctor 用) */
209
+ export function unverifiedSpecs() {
210
+ return API_CATALOG.filter((s) => s.verified === null);
211
+ }
212
+ export function specById(id, scenario) {
213
+ return API_CATALOG.find((s) => s.id === id && s.scenario === scenario);
82
214
  }
83
- /** 按 id 取条目 */
84
- export function specById(id) {
85
- return BALANCE_CATALOG.find((s) => s.id === id);
215
+ /** key 在 config 里的存储键:平台 + 场景 */
216
+ export function keySlot(id, scenario) {
217
+ return `${id}:${scenario}`;
86
218
  }
87
- /** 按路径从 JSON 取数,支持 a.b[0].c 这种写法 */
219
+ /** 按路径从 JSON 取数,支持 a.b[0].c 写法 */
88
220
  export function readPath(obj, pathStr) {
89
221
  let cur = obj;
90
222
  for (const raw of pathStr.split('.')) {
91
223
  if (cur == null)
92
224
  return undefined;
93
- // 处理 key[0] 形式
94
225
  const m = raw.match(/^([^[\]]*)((?:\[\d+\])*)$/);
95
226
  if (!m)
96
227
  return undefined;
@@ -108,7 +239,7 @@ export function readPath(obj, pathStr) {
108
239
  }
109
240
  return cur;
110
241
  }
111
- /** 把任意值转成有限数字,转不了返回 null(不猜、不默认 0) */
242
+ /** 把任意值转成有限数字;转不了返回 null(不猜、不默认 0) */
112
243
  export function toNumber(v) {
113
244
  if (typeof v === 'number')
114
245
  return Number.isFinite(v) ? v : null;
@@ -118,20 +249,20 @@ export function toNumber(v) {
118
249
  }
119
250
  return null;
120
251
  }
121
- /** 从响应里取余额,取不到返回 null(UI 显示「解析失败」,绝不显示 0) */
122
- export function extractBalance(spec, data) {
252
+ /** 从响应里取金额,取不到返回 null(UI 显示解析失败,绝不显示 0) */
253
+ export function extractAmount(spec, data) {
123
254
  const raw = readPath(data, spec.amount.path);
124
255
  let n = toNumber(raw);
125
256
  if (n === null)
126
257
  return null;
127
- // 两字段相减:任一字段缺失或非数字就不算——宁可报错也不猜余额
128
258
  if (spec.amount.subtractPath) {
129
259
  const sub = toNumber(readPath(data, spec.amount.subtractPath));
130
260
  if (sub === null)
131
261
  return null;
132
- n = n - sub;
262
+ n -= sub;
133
263
  }
134
- const scaled = spec.amount.scale ? n * spec.amount.scale : n;
264
+ if (spec.amount.scale)
265
+ n *= spec.amount.scale;
135
266
  let currency = spec.currency ?? 'CNY';
136
267
  if (spec.currencyPath) {
137
268
  const c = readPath(data, spec.currencyPath);
@@ -140,5 +271,7 @@ export function extractBalance(spec, data) {
140
271
  else if (typeof c === 'string' && c.toUpperCase() === 'CNY')
141
272
  currency = 'CNY';
142
273
  }
143
- return { amount: scaled, currency };
274
+ return { amount: n, currency };
144
275
  }
276
+ /** 兼容旧调用名 */
277
+ export const extractBalance = extractAmount;
@@ -12,7 +12,7 @@ import path from 'node:path';
12
12
  import os from 'node:os';
13
13
  import { explainQuotaError } from '../errors.js';
14
14
  import { resolveKey } from '../credentials.js';
15
- import { BALANCE_CATALOG, extractBalance, verifiedSpecs, } from './catalog.js';
15
+ import { API_CATALOG, extractAmount, verifiedSpecs, keySlot, } from './catalog.js';
16
16
  const CUSTOM_PATH = path.join(os.homedir(), '.token-pilot', 'custom-endpoints.json');
17
17
  /** 读用户自定义端点。文件不存在或损坏都返回空数组,不抛错。 */
18
18
  export async function loadCustomEndpoints() {
@@ -54,12 +54,13 @@ function customToSpec(c) {
54
54
  return {
55
55
  id: c.id,
56
56
  displayName: c.displayName,
57
+ scenario: c.scenario ?? 'balance',
57
58
  endpoint: c.endpoint,
58
59
  auth: c.auth,
59
60
  amount: { path: c.amountPath, kind: 'balance' },
60
61
  currency: c.currency,
61
62
  keyUrl: '',
62
- verified: 'custom', // 自定义条目不参与「未验证不启用」的过滤,用户自己负责
63
+ verified: 'custom', // 自定义条目不参与「未验证不启用」过滤,用户自己负责
63
64
  note: '自定义端点',
64
65
  };
65
66
  }
@@ -130,7 +131,7 @@ export async function fetchDeclarativeBalance(spec, overrideKey) {
130
131
  };
131
132
  const cred = overrideKey
132
133
  ? { key: overrideKey, origin: 'config', detail: '本次输入的 key' }
133
- : await resolveKey(spec.id);
134
+ : await resolveKey(spec.id, undefined, spec.scenario);
134
135
  if (!cred) {
135
136
  return {
136
137
  ...base,
@@ -141,7 +142,7 @@ export async function fetchDeclarativeBalance(spec, overrideKey) {
141
142
  if (!res.ok) {
142
143
  return { ...base, error: res.error ?? '请求失败' };
143
144
  }
144
- const balance = extractBalance(spec, res.data);
145
+ const balance = extractAmount(spec, res.data);
145
146
  if (!balance) {
146
147
  // 拿到了响应但解析不出钱数:常见于 key 有效但账户没开通、
147
148
  // 或平台改了字段名。把原始响应截一段带上,便于排查,但不猜数字。
@@ -158,6 +159,45 @@ export async function fetchDeclarativeBalance(spec, overrideKey) {
158
159
  note: spec.note ?? cred.detail,
159
160
  };
160
161
  }
162
+ /**
163
+ * 「测试连接」的统一实现。
164
+ *
165
+ * 为什么放在 core 而不是 serve:桌面端(Tauri)里没有本地 serve,
166
+ * 前端 fetch('/api/...') 必然失败。逻辑必须能在两种宿主里复用,
167
+ * 所以抽成纯函数,由 serve 的路由和 Tauri 命令各自调用。
168
+ *
169
+ * @param overrideKeys 本次界面上输入的 key(id → key)。
170
+ * 传了就优先用它们——用户刚粘的 key 还没保存,必须先能验证。
171
+ * @param customs 本次界面上新增、还没落盘的自定义端点。
172
+ */
173
+ export async function testEndpoints(overrideKeys = {}, customs = []) {
174
+ const saved = await loadCustomEndpoints();
175
+ // 界面上新增的 + 已保存的,按 id 去重(界面上的优先,可能是刚改过的)
176
+ const byId = new Map();
177
+ for (const c of saved)
178
+ byId.set(c.id, c);
179
+ for (const c of customs)
180
+ byId.set(c.id, c);
181
+ const specs = [...verifiedSpecs(), ...[...byId.values()].map(customToSpec)];
182
+ return Promise.all(specs.map(async (spec) => {
183
+ // 界面传上来的键是 `平台:场景`,兼容旧的无场景写法
184
+ const override = overrideKeys[keySlot(spec.id, spec.scenario)]?.trim() ?? overrideKeys[spec.id]?.trim();
185
+ const probe = await fetchDeclarativeBalance(spec, override || undefined).catch((e) => ({
186
+ ok: false,
187
+ error: String(e).slice(0, 150),
188
+ }));
189
+ const balance = 'balance' in probe ? probe.balance : undefined;
190
+ return {
191
+ id: spec.id,
192
+ displayName: spec.displayName,
193
+ ok: probe.ok,
194
+ detail: probe.ok && balance
195
+ ? `${balance.currency === 'CNY' ? '¥' : '$'}${balance.amount.toFixed(2)}`
196
+ : undefined,
197
+ error: probe.ok ? undefined : ('error' in probe ? String(probe.error) : '失败'),
198
+ };
199
+ }));
200
+ }
161
201
  /** 全部内置已启用平台 + 用户自定义平台 */
162
202
  export async function fetchAllDeclarative() {
163
203
  const customs = await loadCustomEndpoints();
@@ -176,5 +216,5 @@ export async function fetchAllDeclarative() {
176
216
  }
177
217
  /** 给 doctor 用:列出还没验证、因此未启用的平台 */
178
218
  export function unverifiedSpecs() {
179
- return BALANCE_CATALOG.filter((s) => s.verified === null);
219
+ return API_CATALOG.filter((s) => s.verified === null);
180
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anthonyhan/token-pilot",
3
- "version": "0.4.5",
3
+ "version": "0.4.7",
4
4
  "description": "你所有 AI 工具的本地账单 + 预算控制器 — 只读本地日志,零入侵,不出本机",
5
5
  "type": "module",
6
6
  "bin": {
@@ -360,6 +360,13 @@ footer .notes{max-width:560px}
360
360
  .m-row input:focus-visible{outline:2px solid var(--info);outline-offset:1px}
361
361
  .m-headr{color:var(--muted);font-size:10.5px;font-weight:700}
362
362
  .addrow{color:var(--info);font-weight:700;font-size:12px;padding:4px 0}
363
+ /* 自动识别的订阅行:只读,视觉上区别于可编辑行 */
364
+ .m-row.sub-auto{grid-template-columns:1fr auto auto;background:color-mix(in oklab,var(--pos) 7%,transparent);
365
+ border:1px solid color-mix(in oklab,var(--pos) 22%,var(--border));border-radius:8px;padding:6px 8px}
366
+ .sub-auto-name{font-size:12px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
367
+ .sub-auto-amt{font-size:12px;font-weight:800;color:var(--fg)}
368
+ .sub-auto-tag{font-size:10px;font-weight:700;color:var(--pos-text);background:color-mix(in oklab,var(--pos) 14%,transparent);
369
+ border-radius:6px;padding:1px 6px;white-space:nowrap}
363
370
 
364
371
  /* API Key 区块 */
365
372
  .key-empty-note{font-size:11px;color:var(--muted);background:color-mix(in oklab,var(--info) 8%,transparent);
@@ -377,6 +384,12 @@ footer .notes{max-width:560px}
377
384
  .key-result .kr-ok{color:var(--pos-text);font-weight:700}
378
385
  .key-result .kr-bad{color:var(--warn);font-weight:700}
379
386
  .key-result .kr-line{display:flex;gap:6px}
387
+ /* 平台标签:余额/订阅/需admin/待验证 */
388
+ .key-tag{display:inline-block;font-size:9px;font-weight:700;border-radius:4px;padding:1px 5px;margin-left:5px;vertical-align:middle}
389
+ .key-tag.bal{color:var(--info);background:color-mix(in oklab,var(--info) 13%,transparent)}
390
+ .key-tag.sub{color:var(--accent-2);background:color-mix(in oklab,var(--accent-2) 14%,transparent)}
391
+ .key-tag.admin{color:var(--warn);background:color-mix(in oklab,var(--warn) 14%,transparent)}
392
+ .key-tag.todo{color:var(--muted);background:var(--track)}
380
393
 
381
394
  /* 设置项:复选框 + 标题 + 说明的三层结构 */
382
395
  .opt{display:flex;align-items:flex-start;gap:10px;padding:9px 10px;margin:2px 0;border:1px solid transparent;border-radius:9px;cursor:pointer;transition:background .14s var(--ease),border-color .14s var(--ease)}
@@ -720,7 +733,7 @@ footer .notes{max-width:560px}
720
733
  </div>
721
734
  <div id="mKeys"></div>
722
735
  <div class="key-actions">
723
- <button class="addrow" type="button" id="mAddCustom">+ 添加自定义平台</button>
736
+ <button class="addrow" type="button" id="mAddCustom">+ 添加平台</button>
724
737
  <button class="addrow" type="button" id="mTestKeys">测试连接</button>
725
738
  </div>
726
739
  <div id="mKeyResult" class="key-result"></div>
@@ -732,12 +745,18 @@ footer .notes{max-width:560px}
732
745
  <button class="addrow" type="button" data-add="models">+ 添加模型</button>
733
746
  </div>
734
747
  <div class="m-sec">
735
- <div class="m-lab">云端用量 API <span>按月登记费用</span></div>
748
+ <div class="m-lab">云端用量 API <span>手工登记的固定月费,与下面「订阅登记」性质相同</span></div>
749
+ <div class="key-empty-note">
750
+ 这里只加「固定月费」,不参与按 token 计费。<b>火山方舟的用量已自动采集</b>,若只是为了标记已接入,金额填 0 即可,避免重复计费。
751
+ </div>
736
752
  <div id="mCloud" data-set="cloud"></div>
737
753
  <button class="addrow" type="button" data-add="cloud">+ 添加 API</button>
738
754
  </div>
739
755
  <div class="m-sec">
740
- <div class="m-lab">订阅登记 <span>桌面端 / 会员固定月费</span></div>
756
+ <div class="m-lab">订阅登记 <span>固定月费;接口或 CC Switch 能查到的不需要手填</span></div>
757
+ <div class="key-empty-note">
758
+ 标「接口自动识别」或「CC Switch 读取」的行已自动计入,<b>不要再手填一遍</b>。接口能查到套餐价格的平台会自动出现在这里。
759
+ </div>
741
760
  <div id="mSubs" data-set="subs"></div>
742
761
  <button class="addrow" type="button" data-add="subs">+ 添加订阅</button>
743
762
  </div>
@@ -1088,13 +1107,23 @@ function loadSettingsFromD(){
1088
1107
  settings={
1089
1108
  models:(s.models||[]).map(function(m){return {n:String(m.name),i:String(m.inputCny),o:String(m.outputCny),c:String(m.cacheReadCny)}}),
1090
1109
  cloud:(s.cloudApis||[]).map(function(m){return {n:String(m.name),p:String(m.monthlyCny)}}),
1091
- subs:(s.subscriptions||[]).map(function(m){return {n:String(m.name),p:String(m.monthlyCny)}}),
1110
+ // origin: 'api' / 'ccswitch' 都算自动来的,不允许手改(改了就重复计费)
1111
+ subs:(s.subscriptions||[]).map(function(m){
1112
+ return {n:String(m.name),p:String(m.monthlyCny),origin:m.origin||'manual'};
1113
+ }),
1092
1114
  budget:s.monthlyBudgetCny==null?"":String(s.monthlyBudgetCny),
1093
1115
  autoCompact:(s.autoCompact)||{enabled:false},
1094
1116
  // 每条:{id, displayName, masked, keyUrl, value}
1095
1117
  // value 是用户本次输入的新 key(空串=不改);masked 是已存 key 的掩码
1096
1118
  keys:(s.quotaKeys||[]).map(function(k){
1097
- return {id:k.id,displayName:k.displayName,masked:k.masked,keyUrl:k.keyUrl||"",value:""};
1119
+ // added:已配置 key 的视为已添加,其余默认不出现在列表里
1120
+ // (否则一打开设置就是十几行空输入框,用户根本不知道该填哪个)
1121
+ return {
1122
+ id:k.id, scenario:k.scenario||'balance', displayName:k.displayName,
1123
+ masked:k.masked, keyUrl:k.keyUrl||"", value:"",
1124
+ needsAdmin:!!k.needsAdmin, implemented:k.implemented!==false,
1125
+ added:!!k.masked
1126
+ };
1098
1127
  })
1099
1128
  };
1100
1129
  }
@@ -1107,43 +1136,139 @@ function loadSettingsFromD(){
1107
1136
  function renderKeyRows(){
1108
1137
  var box=$("#mKeys");
1109
1138
  if(!box||!settings)return;
1110
- if(!settings.keys.length){
1111
- box.innerHTML='<div class="key-empty-note">还没有可查询的平台。点下面「添加自定义平台」可以接入任意提供余额接口的服务。</div>';
1139
+ // 只显示「已添加」的平台:用户选了哪个平台才出现哪一行,
1140
+ // 不再把全部内置平台铺开——那样列表又长又吵。
1141
+ var picked = settings.keys.filter(function(k){return k.added || k.masked;});
1142
+ if(!picked.length){
1143
+ box.innerHTML='<div class="key-empty-note">还没有添加平台。点下面「+ 添加平台」,选平台、填 API Key 即可。</div>';
1112
1144
  return;
1113
1145
  }
1114
- box.innerHTML=settings.keys.map(function(k,i){
1115
- var ph = k.masked ? ("已配置 "+k.masked+",留空不修改") : "粘贴 API Key";
1146
+ box.innerHTML=picked.map(function(k){
1147
+ var i=settings.keys.indexOf(k);
1148
+ // 刚添加还没保存的 key 也要让用户看到「已填」
1149
+ var ph = k.masked ? ("已配置 "+k.masked+",留空不修改")
1150
+ : (k.value ? "已填入(未保存),保存后生效" : "粘贴 API Key");
1116
1151
  var link = k.keyUrl ? '<a href="'+esc(k.keyUrl)+'" target="_blank" rel="noopener" style="font-size:11px;color:var(--info);margin-left:6px">去申请</a>' : "";
1152
+ var tags='';
1153
+ if(k.scenario==='subscription')tags+='<span class="key-tag sub">订阅</span>';
1154
+ else tags+='<span class="key-tag bal">余额</span>';
1155
+ if(k.needsAdmin)tags+='<span class="key-tag admin" title="该平台查余额需要 admin key,普通 key 会报权限错误">需 admin key</span>';
1156
+ if(k.implemented===false)tags+='<span class="key-tag todo" title="接口已探到,但字段结构尚未用真实 key 验证,暂不保证可用">待验证</span>';
1117
1157
  return '<div class="key-row">'+
1118
- '<span class="key-name" title="'+esc(k.id)+'">'+esc(k.displayName)+'</span>'+
1158
+ '<span class="key-name" title="'+esc(k.id)+'">'+esc(k.displayName)+tags+'</span>'+
1119
1159
  '<input type="password" data-key="'+i+'" value="" placeholder="'+esc(ph)+'" aria-label="'+esc(k.displayName)+' 的 API Key" autocomplete="off" spellcheck="false">'+
1120
- '<span>'+link+(k.masked?'<button class="key-del" type="button" data-keyclear="'+i+'" aria-label="清除 '+esc(k.displayName)+' 的 key" title="清除已保存的 key">×</button>':'')+'</span>'+
1160
+ '<span>'+link+'<button class="key-del" type="button" data-keyclear="'+i+'" aria-label="移除 '+esc(k.displayName)+'" title="移除该平台">×</button></span>'+
1121
1161
  '</div>';
1122
1162
  }).join("");
1123
1163
  }
1124
1164
 
1125
- /* 自定义平台:id 由名称生成,重复则拒绝 */
1126
- function addCustomEndpoint(){
1165
+ /* 添加平台:一个下拉选平台 + 一个输入框填 key,两步搞定。
1166
+ 比原来的「填名称/端点/字段路径/鉴权方式」四条强太多——
1167
+ 绝大多数用户只想「选个平台、粘个 key」。 */
1168
+ function showAddPlatform(){
1127
1169
  if(!settings)return;
1128
- var name=prompt("平台名称(如「某某云」)");
1129
- if(!name||!name.trim())return;
1130
- name=name.trim();
1131
- var id=name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");
1132
- if(!id){alert("名称里至少要有英文字母或数字,用来做标识");return;}
1133
- if(settings.keys.some(function(k){return k.id===id})){
1134
- alert("已经有同名平台了("+id+")");return;
1170
+ var box=$("#mKeyResult");
1171
+ if(!box)return;
1172
+ // 列出所有已声明、且还没添加的平台,按场景分组
1173
+ var avail=settings.keys.filter(function(k){return !k.added && !k.masked;});
1174
+ if(!avail.length){
1175
+ box.innerHTML='<div class="kr-line"><span class="kr-ok">所有内置平台都已添加</span></div>';
1176
+ return;
1135
1177
  }
1136
- var endpoint=prompt("余额接口地址(https:// 开头)");
1137
- if(!endpoint||!/^https:\/\//.test(endpoint.trim())){alert("需要 https:// 开头的完整地址");return;}
1138
- var path=prompt("金额字段路径(如 data.balance,支持数组下标 a.b[0].c)");
1139
- if(!path||!path.trim())return;
1140
- var auth=prompt("鉴权方式:bearer(默认)/ raw / x-api-key","bearer");
1141
- auth=(auth||"bearer").trim();
1142
- if(["bearer","raw","x-api-key"].indexOf(auth)<0){alert("只能是 bearer / raw / x-api-key");return;}
1143
- // 暂存到 settings.keys 等待用户填 key,同时记录端点信息供保存
1144
- settings.keys.push({id:id,displayName:name,masked:null,keyUrl:"",value:"",_custom:{id:id,displayName:name,endpoint:endpoint.trim(),auth:auth,amountPath:path.trim()}});
1145
- renderKeyRows();
1146
- $("#mKeyResult").innerHTML='<div class="kr-line"><span class="kr-ok">已添加 '+esc(name)+'</span><span>填入 key 后点「测试连接」</span></div>';
1178
+ var optBal=avail.filter(function(k){return k.scenario!=='subscription'});
1179
+ var optSub=avail.filter(function(k){return k.scenario==='subscription'});
1180
+ function optGroup(label,list){
1181
+ if(!list.length)return '';
1182
+ return '<optgroup label="'+esc(label)+'">'+list.map(function(k){
1183
+ return '<option value="'+esc(k.id+'|'+k.scenario)+'">'+esc(k.displayName)+(k.needsAdmin?'(需 admin key)':'')+'</option>';
1184
+ }).join('')+'</optgroup>';
1185
+ }
1186
+ box.innerHTML =
1187
+ '<div class="key-custom">'+
1188
+ '<select id="pkPick" aria-label="选择平台" style="grid-column:1/-1;background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:6px 8px;font:inherit;font-size:12px;color:var(--fg)">'+
1189
+ optGroup('余额查询',optBal)+optGroup('订阅额度',optSub)+
1190
+ '</select>'+
1191
+ '<input id="pkKey" type="password" placeholder="粘贴该平台的 API Key" aria-label="API Key" style="grid-column:1/-1" autocomplete="off" spellcheck="false">'+
1192
+ '</div>'+
1193
+ '<div class="key-actions">'+
1194
+ '<button class="addrow" type="button" id="pkOk">确定</button>'+
1195
+ '<button class="addrow" type="button" id="pkCancel">取消</button>'+
1196
+ '<button class="addrow" type="button" id="pkCustom">添加自定义平台</button>'+
1197
+ '</div>'+
1198
+ '<div id="pkHint" class="kr-line" style="color:var(--muted)">选平台、填 key、点确定即可。不确定去哪拿 key 的,添加后会显示「去申请」链接。</div>';
1199
+ $("#pkCancel").addEventListener("click",function(){box.innerHTML="";});
1200
+ $("#pkCustom").addEventListener("click",addCustomEndpoint);
1201
+ $("#pkOk").addEventListener("click",function(){
1202
+ var v=$("#pkPick").value||"";
1203
+ var key=($("#pkKey").value||"").trim();
1204
+ var hint=$("#pkHint");
1205
+ var parts=v.split("|");
1206
+ var id=parts[0], sc=parts[1];
1207
+ if(!id)return;
1208
+ if(!key){hint.innerHTML='<span class="kr-bad">请粘贴 API Key(留空会添加一个空行,稍后还能填)</span>';}
1209
+ var target=settings.keys.filter(function(k){return k.id===id&&k.scenario===sc})[0];
1210
+ if(target){
1211
+ target.added=true;
1212
+ if(key)target.value=key;
1213
+ }
1214
+ renderKeyRows();
1215
+ box.innerHTML='<div class="kr-line"><span class="kr-ok">已添加 '+(target?target.displayName:id)+'</span>'+
1216
+ (key?'<span>点「测试连接」验证,然后保存</span>':'<span>在列表里填入 key</span>')+'</div>';
1217
+ });
1218
+ }
1219
+
1220
+ /* 自定义平台:展开一个内联表单。
1221
+ 原来用 prompt() 逐项追问,但 Tauri WebView 常静默拦截 prompt,
1222
+ 表现就是「点了没反应」——没有对话框、没有报错、什么都没有。
1223
+ 改成内联表单,看得见、能取消、也不会被拦截。 */
1224
+ function addCustomEndpoint(){
1225
+ if(!settings)return;
1226
+ var box=$("#mKeyResult");
1227
+ if(!box)return;
1228
+ box.innerHTML =
1229
+ '<div class="key-custom">'+
1230
+ '<input id="cxName" placeholder="平台名称,如「某某云」" aria-label="平台名称">'+
1231
+ '<input id="cxEndpoint" placeholder="余额接口 https://..." aria-label="接口地址">'+
1232
+ '<input id="cxPath" placeholder="金额字段路径,如 data.balance" aria-label="字段路径">'+
1233
+ '<select id="cxAuth" aria-label="鉴权方式" style="background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:6px 8px;font:inherit;font-size:12px;color:var(--fg)">'+
1234
+ '<option value="bearer">Authorization: Bearer(多数平台)</option>'+
1235
+ '<option value="raw">Authorization: 直接放 key</option>'+
1236
+ '<option value="x-api-key">x-api-key</option>'+
1237
+ '</select>'+
1238
+ '</div>'+
1239
+ '<div class="key-actions">'+
1240
+ '<button class="addrow" type="button" id="cxOk">确定添加</button>'+
1241
+ '<button class="addrow" type="button" id="cxCancel">取消</button>'+
1242
+ '</div>'+
1243
+ '<div id="cxHint" class="kr-line" style="color:var(--muted)">填完点「确定添加」,然后给这一行填入 API Key 再点「测试连接」</div>';
1244
+ $("#cxCancel").addEventListener("click",function(){box.innerHTML="";});
1245
+ $("#cxOk").addEventListener("click",function(){
1246
+ var name=($("#cxName").value||"").trim();
1247
+ var endpoint=($("#cxEndpoint").value||"").trim();
1248
+ var path=($("#cxPath").value||"").trim();
1249
+ var auth=$("#cxAuth").value;
1250
+ var hint=$("#cxHint");
1251
+ function bad(msg){hint.innerHTML='<span class="kr-bad">'+esc(msg)+'</span>';}
1252
+ if(!name)return bad("请填平台名称");
1253
+ // 纯中文名以前会被替换成空字符串 → id 为空 → 直接返回,什么都不发生。
1254
+ // 中文平台名很常见,不能因此拒绝:ASCII 名转 slug,非 ASCII 名用
1255
+ // 稳定哈希兜底,保证同一个名字永远得到同一个 id。
1256
+ var id=name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");
1257
+ if(!id){
1258
+ var h=0;
1259
+ for(var ci=0;ci<name.length;ci++){h=((h<<5)-h+name.charCodeAt(ci))|0;}
1260
+ id="custom-"+(h>>>0).toString(36);
1261
+ }
1262
+ if(settings.keys.some(function(k){return k.id===id}))return bad("已经有同名平台了("+id+")");
1263
+ if(!/^https:\/\//.test(endpoint))return bad("接口地址要 https:// 开头");
1264
+ if(!path)return bad("请填金额字段路径");
1265
+ settings.keys.push({
1266
+ id:id, displayName:name, masked:null, keyUrl:"", value:"",
1267
+ _custom:{id:id,displayName:name,endpoint:endpoint,auth:auth,amountPath:path}
1268
+ });
1269
+ renderKeyRows();
1270
+ box.innerHTML='<div class="kr-line"><span class="kr-ok">已添加 '+esc(name)+'</span><span>在列表里填入 API Key,再点「测试连接」</span></div>';
1271
+ });
1147
1272
  }
1148
1273
 
1149
1274
  /* 测试连接:只测有 key 的(新填的或已存的) */
@@ -1152,15 +1277,30 @@ async function testKeys(){
1152
1277
  if(!box)return;
1153
1278
  box.innerHTML='<span style="color:var(--muted)">测试中…</span>';
1154
1279
  try{
1155
- var r=await fetch("/api/quota/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keys:collectKeys()})});
1156
- var d=await r.json();
1280
+ // collectKeys() 返回 {keys:{...}, customs:[...]},只把 keys 传过去。
1281
+ // 之前整个对象塞进 {keys: ...},服务端取 keys?.[id] 永远是 undefined。
1282
+ var collected=collectKeys();
1283
+ var payload=JSON.stringify({keys:collected.keys,customs:collected.customs});
1284
+ var d;
1285
+ if(inTauri()){
1286
+ // 桌面端没有本地 serve,fetch('/api/...') 必然失败。
1287
+ // 走 Tauri 命令,内部再喂给 CLI 的 quota-test(key 走 stdin)。
1288
+ var raw=await window.__TAURI__.core.invoke("quota_test",{payload:payload});
1289
+ d=JSON.parse(raw);
1290
+ }else{
1291
+ var r=await fetch("/api/quota/test",{method:"POST",headers:{"Content-Type":"application/json"},body:payload});
1292
+ d=await r.json();
1293
+ }
1157
1294
  if(!d||!d.results){box.innerHTML='<span class="kr-bad">测试失败:接口无响应</span>';return;}
1158
1295
  box.innerHTML=d.results.map(function(x){
1159
1296
  return '<div class="kr-line"><span class="'+(x.ok?"kr-ok":"kr-bad")+'">'+(x.ok?"✓":"✗")+' '+esc(x.displayName)+'</span><span>'+
1160
1297
  (x.ok? esc(x.detail) : esc(x.error||"失败")) +'</span></div>';
1161
1298
  }).join("");
1162
1299
  }catch(e){
1163
- box.innerHTML='<span class="kr-bad">测试失败:'+(e&&e.message?esc(e.message):"网络错误")+'</span><span style="color:var(--muted)">(需要本地 serve 在跑,桌面端点「打开看板」自带)</span>';
1300
+ var why = e && (e.message || e.toString) ? (e.message||String(e)) : "未知错误";
1301
+ box.innerHTML='<span class="kr-bad">测试失败:'+esc(why)+'</span>'+
1302
+ (inTauri()?'<span style="color:var(--muted)">(需要安装 token-pilot 命令行:npm i -g @anthonyhan/token-pilot)</span>'
1303
+ :'<span style="color:var(--muted)">(需要本地 serve 在跑:token-pilot serve)</span>');
1164
1304
  }
1165
1305
  }
1166
1306
 
@@ -1169,7 +1309,8 @@ function collectKeys(){
1169
1309
  if(!settings)return {keys:{}, customs:[]};
1170
1310
  var keys={}, customs=[];
1171
1311
  settings.keys.forEach(function(k){
1172
- if(k.value&&k.value.trim())keys[k.id]=k.value.trim();
1312
+ var slot=k.id+':'+(k.scenario||'balance');
1313
+ if(k.value&&k.value.trim())keys[slot]=k.value.trim();
1173
1314
  if(k._custom)customs.push(k._custom);
1174
1315
  });
1175
1316
  return {keys:keys, customs:customs};
@@ -1178,11 +1319,27 @@ function collectKeys(){
1178
1319
  function renderSet(){
1179
1320
  $("#mModels").innerHTML=settings.models.map(function(r,i){return '<div class="m-row r4"><input data-k="n" data-i="'+i+'" value="'+esc(r.n)+'" aria-label="模型名" placeholder="模型名,如 glm-5.3"><input data-k="i" data-i="'+i+'" value="'+esc(r.i)+'" aria-label="输入单价"><input data-k="o" data-i="'+i+'" value="'+esc(r.o)+'" aria-label="输出单价"><input data-k="c" data-i="'+i+'" value="'+esc(r.c)+'" aria-label="缓存读单价"><button class="delrow" type="button" data-del="models" data-i="'+i+'" aria-label="删除此行">×</button></div>'}).join("");
1180
1321
  $("#mCloud").innerHTML=settings.cloud.map(function(r,i){return '<div class="m-row r2"><input data-k="n" data-i="'+i+'" value="'+esc(r.n)+'" aria-label="名称" placeholder="名称"><input data-k="p" data-i="'+i+'" value="'+esc(r.p)+'" aria-label="月费用"><button class="delrow" type="button" data-del="cloud" data-i="'+i+'" aria-label="删除此行">×</button></div>'}).join("");
1181
- $("#mSubs").innerHTML=settings.subs.map(function(r,i){return '<div class="m-row r2"><input data-k="n" data-i="'+i+'" value="'+esc(r.n)+'" aria-label="名称" placeholder="名称"><input data-k="p" data-i="'+i+'" value="'+esc(r.p)+'" aria-label="月费"><button class="delrow" type="button" data-del="subs" data-i="'+i+'" aria-label="删除此行">×</button></div>'}).join("");
1322
+ var ORIGIN_TAG={api:'接口自动识别',ccswitch:'CC Switch 读取',manual:''};
1323
+ var ORIGIN_TIP={api:'来自平台接口,已计入当月固定费用;手填会重复计费,故不可编辑',
1324
+ ccswitch:'来自本机 CC Switch 配置,自动读取;如需修改请到 CC Switch 里改'};
1325
+ $("#mSubs").innerHTML=settings.subs.map(function(r,i){
1326
+ if(r.origin&&r.origin!=='manual'){
1327
+ // 自动来的(接口或 CC Switch):只读,禁止编辑和删除。
1328
+ // 允许改动会导致「自动拿到一份 + 手填一份」重复计费。
1329
+ return '<div class="m-row r2 sub-auto"><span class="sub-auto-name" title="'+esc(ORIGIN_TIP[r.origin]||'')+'">'+esc(r.n)+'</span>'+
1330
+ '<span class="sub-auto-amt">¥'+esc(r.p)+'</span>'+
1331
+ '<span class="sub-auto-tag">'+esc(ORIGIN_TAG[r.origin]||'自动')+'</span></div>';
1332
+ }
1333
+ return '<div class="m-row r2"><input data-k="n" data-i="'+i+'" value="'+esc(r.n)+'" aria-label="名称" placeholder="名称"><input data-k="p" data-i="'+i+'" value="'+esc(r.p)+'" aria-label="月费"><button class="delrow" type="button" data-del="subs" data-i="'+i+'" aria-label="删除此行">×</button></div>';
1334
+ }).join("");
1182
1335
  renderKeyRows();
1183
1336
  $("#mBudget").value=settings.budget;
1184
1337
  $("#mAutoCompact").checked=!!(settings.autoCompact&&settings.autoCompact.enabled);
1185
- $("#mCompactK").value=String(Math.round((settings.autoCompact&&settings.autoCompact.thresholdTokens)||100000/1000)||100);
1338
+ // 输入框单位是「千 tokens」。原文写作 (x || 100000/1000) || 100,
1339
+ // 运算符优先级导致 x 存在时直接把原始 token 数(如 150000)塞进输入框,
1340
+ // 用户一保存就变成 150000 * 1000 = 1.5 亿,阈值等于永不触发。
1341
+ var thTokens = (settings.autoCompact && settings.autoCompact.thresholdTokens) || 100000;
1342
+ $("#mCompactK").value = String(Math.round(thTokens / 1000));
1186
1343
  $("#mApplyCc").checked=!!(settings.autoCompact&&settings.autoCompact.applyClaudeCode);
1187
1344
  var rtkOn=!!(D&&D.settings&&D.settings.rtkInstalled);
1188
1345
  var rtkSrc=(D&&D.settings&&D.settings.rtkSource)||"none";
@@ -1226,11 +1383,17 @@ modal.addEventListener("click",function(e){
1226
1383
  var d=e.target.closest("[data-del]");
1227
1384
  if(d){settings[d.dataset.del].splice(+d.dataset.i,1);renderSet()}
1228
1385
  });
1229
- $("#mAddCustom").addEventListener("click",addCustomEndpoint);
1386
+ $("#mAddCustom").addEventListener("click",showAddPlatform);
1230
1387
  $("#mTestKeys").addEventListener("click",testKeys);
1231
1388
  $$(".addrow").forEach(function(b){
1389
+ // 只处理带 data-add 的行内「+ 添加」按钮。
1390
+ // 没有这层判断的话,同样用 .addrow 样式的「添加自定义平台」「测试连接」
1391
+ // 也会走进来,settings[undefined].push 直接抛 TypeError,
1392
+ // 看起来就是「点了没反应」。
1393
+ if(!b.dataset.add)return;
1232
1394
  b.addEventListener("click",function(){
1233
1395
  var k=b.dataset.add;
1396
+ if(!settings[k])return;
1234
1397
  settings[k].push(k==="models"?{n:"",i:"",o:"",c:""}:{n:"",p:""});
1235
1398
  renderSet();
1236
1399
  });
@@ -1245,14 +1408,20 @@ $("#settingsSave").addEventListener("click",function(){
1245
1408
  if(changed||wasOverride)payload.priceOverrides[r.n]={input:parseFloat(r.i)||0,output:parseFloat(r.o)||0,cacheRead:parseFloat(r.c)||0};
1246
1409
  });
1247
1410
  settings.cloud.forEach(function(r){if(r.n)payload.cloudApis.push({name:r.n,monthlyCny:parseFloat(r.p)||0})});
1248
- settings.subs.forEach(function(r){if(r.n)payload.subscriptions.push({name:r.n,monthlyCny:parseFloat(r.p)||0})});
1411
+ // 自动识别的条目由接口提供,不写回手填列表——写回去下次就会被当成手填项,
1412
+ // 再叠加接口识别就重复了
1413
+ settings.subs.forEach(function(r){
1414
+ if(r.n&&(!r.origin||r.origin==='manual'))payload.subscriptions.push({name:r.n,monthlyCny:parseFloat(r.p)||0});
1415
+ });
1249
1416
  var b=parseFloat(settings.budget);
1250
1417
  payload.monthlyBudgetCny=isFinite(b)?b:null;
1251
1418
  // API Key:只发本次新填的 + 明确要清除的,不把已有 key 回传
1252
1419
  var qk={};
1253
1420
  settings.keys.forEach(function(k){
1254
- if(k._clear)qk[k.id]="";
1255
- else if(k.value&&k.value.trim())qk[k.id]=k.value.trim();
1421
+ // 余额与订阅两套 key 分开存,键是 `平台:场景`
1422
+ var slot=k.id+':'+(k.scenario||'balance');
1423
+ if(k._clear)qk[slot]="";
1424
+ else if(k.value&&k.value.trim())qk[slot]=k.value.trim();
1256
1425
  });
1257
1426
  if(Object.keys(qk).length)payload.quotaKeys=qk;
1258
1427
  // 自定义端点定义(写入独立文件 custom-endpoints.json,不混在 config 里)