@anthonyhan/token-pilot 0.4.5 → 0.4.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/dist/cli/index.js +19 -0
- package/dist/cli/serve.js +6 -28
- package/dist/core/aggregate.js +71 -17
- package/dist/core/quota/credentials.js +15 -5
- package/dist/core/quota/providers/catalog.js +130 -52
- package/dist/core/quota/providers/declarative.js +45 -5
- package/package.json +1 -1
- package/web/dashboard.html +210 -41
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 {
|
|
122
|
-
const
|
|
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',
|
package/dist/core/aggregate.js
CHANGED
|
@@ -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 {
|
|
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
|
-
//
|
|
854
|
-
|
|
855
|
-
|
|
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[
|
|
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 [
|
|
865
|
-
if (shown.has(
|
|
872
|
+
// 用户自己配过但不在内置目录里的(自定义端点等)也要显示,否则存了看不见
|
|
873
|
+
for (const [slot, key] of Object.entries(stored)) {
|
|
874
|
+
if (shown.has(slot))
|
|
866
875
|
continue;
|
|
867
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
/**
|
|
18
|
-
|
|
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
|
|
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
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
3
|
+
// 关键设计:**余额和订阅是两件事,用两套 key、两套端点**。
|
|
4
|
+
// - 余额(balance):现金账户还剩多少钱
|
|
5
|
+
// - 订阅(subscription):套餐用了多少、什么时候重置,往往要 admin key
|
|
6
|
+
// 很多平台两者权限不同(MiniMax 就是典型:普通 key 能查订阅,查余额要 admin key),
|
|
7
|
+
// 所以 key 按 `平台:场景` 分别存,互不覆盖。
|
|
7
8
|
//
|
|
8
|
-
// ⚠️ verified
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
// 没验过的一律 verified: null,运行时跳过并在 doctor 里标出来。
|
|
9
|
+
// ⚠️ verified 是硬门槛:
|
|
10
|
+
// 只探测到 401 不算数——很多网关对不存在的路径也返 401(GLM 踩过)。
|
|
11
|
+
// 必须用真实 key 打出真实 JSON、确认字段路径无误,才填日期。
|
|
12
|
+
// 没验过的一律 null,运行时不启用。
|
|
13
13
|
/**
|
|
14
14
|
* 内置目录。
|
|
15
15
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
16
|
+
* 调研范围(2026-11):国内 8 家 + 海外 6 家实测。结论:
|
|
17
|
+
* - 大多数平台**没有公开余额接口**(百川/零一万物/商汤/腾讯混元/阿里百炼 全 404)
|
|
18
|
+
* - OpenAI / Anthropic 只有组织级 admin 接口
|
|
19
|
+
* - 能接的不多不是做得少,是平台没开放
|
|
20
|
+
* 未验证条目保留在表里不是摆设:记录探测结果避免重复调研,
|
|
21
|
+
* 也方便拿到 key 时直接补测。
|
|
19
22
|
*/
|
|
20
|
-
export const
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
//
|
|
51
|
-
//
|
|
52
|
-
//
|
|
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,122 @@ 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: '无公开余额接口(实测 8 个路径全 404,key 本身有效)',
|
|
111
|
+
},
|
|
112
|
+
// ───────── 订阅 / 额度 ─────────
|
|
113
|
+
{
|
|
114
|
+
id: 'glm',
|
|
115
|
+
displayName: '智谱 GLM',
|
|
116
|
+
scenario: 'subscription',
|
|
117
|
+
endpoint: 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',
|
|
118
|
+
auth: 'bearer',
|
|
119
|
+
amount: { path: 'data.limits[0].remaining', kind: 'remaining' },
|
|
120
|
+
currency: 'CNY',
|
|
121
|
+
keyUrl: 'https://open.bigmodel.cn/usercenter/apikeys',
|
|
122
|
+
keyKind: 'normal',
|
|
123
|
+
verified: null,
|
|
124
|
+
note: '已由独立 provider 处理(多额度窗口),此处保留端点记录',
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
id: 'minimax',
|
|
128
|
+
displayName: 'MiniMax',
|
|
129
|
+
scenario: 'subscription',
|
|
66
130
|
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
131
|
auth: 'bearer',
|
|
71
|
-
//
|
|
132
|
+
// 实测 2026-11-05:必须 Bearer,裸 key 报 1004「login fail」
|
|
133
|
+
//(看着像 key 无效,其实是鉴权头格式错)
|
|
72
134
|
amount: { path: 'model_remains[0].current_interval_total_count', kind: 'remaining' },
|
|
73
135
|
currency: 'CNY',
|
|
74
136
|
keyUrl: 'https://platform.minimaxi.com/user-center/basic-information/interface-key',
|
|
137
|
+
keyKind: 'normal',
|
|
75
138
|
verified: null,
|
|
76
|
-
|
|
139
|
+
// 实测 2026-11-05:key 有效(能过鉴权),但该账号无生效订阅,
|
|
140
|
+
// 返回 2062 no active token plan subscription,拿不到 model_remains 结构,
|
|
141
|
+
// 所以无法确认字段路径,暂不启用。
|
|
142
|
+
note: '账号无生效 Token Plan 订阅(2062),字段结构未实测',
|
|
77
143
|
},
|
|
78
144
|
];
|
|
79
|
-
/**
|
|
80
|
-
export function
|
|
81
|
-
return
|
|
145
|
+
/** 按场景取条目 */
|
|
146
|
+
export function specsFor(scenario) {
|
|
147
|
+
return API_CATALOG.filter((s) => s.scenario === scenario);
|
|
148
|
+
}
|
|
149
|
+
/** 已启用的条目(verified 非空) */
|
|
150
|
+
export function verifiedSpecs(scenario) {
|
|
151
|
+
return API_CATALOG.filter((s) => s.verified !== null && (!scenario || s.scenario === scenario));
|
|
152
|
+
}
|
|
153
|
+
/** 未验证的条目(doctor 用) */
|
|
154
|
+
export function unverifiedSpecs() {
|
|
155
|
+
return API_CATALOG.filter((s) => s.verified === null);
|
|
156
|
+
}
|
|
157
|
+
export function specById(id, scenario) {
|
|
158
|
+
return API_CATALOG.find((s) => s.id === id && s.scenario === scenario);
|
|
82
159
|
}
|
|
83
|
-
/**
|
|
84
|
-
export function
|
|
85
|
-
return
|
|
160
|
+
/** key 在 config 里的存储键:平台 + 场景 */
|
|
161
|
+
export function keySlot(id, scenario) {
|
|
162
|
+
return `${id}:${scenario}`;
|
|
86
163
|
}
|
|
87
|
-
/** 按路径从 JSON 取数,支持 a.b[0].c
|
|
164
|
+
/** 按路径从 JSON 取数,支持 a.b[0].c 写法 */
|
|
88
165
|
export function readPath(obj, pathStr) {
|
|
89
166
|
let cur = obj;
|
|
90
167
|
for (const raw of pathStr.split('.')) {
|
|
91
168
|
if (cur == null)
|
|
92
169
|
return undefined;
|
|
93
|
-
// 处理 key[0] 形式
|
|
94
170
|
const m = raw.match(/^([^[\]]*)((?:\[\d+\])*)$/);
|
|
95
171
|
if (!m)
|
|
96
172
|
return undefined;
|
|
@@ -108,7 +184,7 @@ export function readPath(obj, pathStr) {
|
|
|
108
184
|
}
|
|
109
185
|
return cur;
|
|
110
186
|
}
|
|
111
|
-
/**
|
|
187
|
+
/** 把任意值转成有限数字;转不了返回 null(不猜、不默认 0) */
|
|
112
188
|
export function toNumber(v) {
|
|
113
189
|
if (typeof v === 'number')
|
|
114
190
|
return Number.isFinite(v) ? v : null;
|
|
@@ -118,20 +194,20 @@ export function toNumber(v) {
|
|
|
118
194
|
}
|
|
119
195
|
return null;
|
|
120
196
|
}
|
|
121
|
-
/**
|
|
122
|
-
export function
|
|
197
|
+
/** 从响应里取金额,取不到返回 null(UI 显示解析失败,绝不显示 0) */
|
|
198
|
+
export function extractAmount(spec, data) {
|
|
123
199
|
const raw = readPath(data, spec.amount.path);
|
|
124
200
|
let n = toNumber(raw);
|
|
125
201
|
if (n === null)
|
|
126
202
|
return null;
|
|
127
|
-
// 两字段相减:任一字段缺失或非数字就不算——宁可报错也不猜余额
|
|
128
203
|
if (spec.amount.subtractPath) {
|
|
129
204
|
const sub = toNumber(readPath(data, spec.amount.subtractPath));
|
|
130
205
|
if (sub === null)
|
|
131
206
|
return null;
|
|
132
|
-
n
|
|
207
|
+
n -= sub;
|
|
133
208
|
}
|
|
134
|
-
|
|
209
|
+
if (spec.amount.scale)
|
|
210
|
+
n *= spec.amount.scale;
|
|
135
211
|
let currency = spec.currency ?? 'CNY';
|
|
136
212
|
if (spec.currencyPath) {
|
|
137
213
|
const c = readPath(data, spec.currencyPath);
|
|
@@ -140,5 +216,7 @@ export function extractBalance(spec, data) {
|
|
|
140
216
|
else if (typeof c === 'string' && c.toUpperCase() === 'CNY')
|
|
141
217
|
currency = 'CNY';
|
|
142
218
|
}
|
|
143
|
-
return { amount:
|
|
219
|
+
return { amount: n, currency };
|
|
144
220
|
}
|
|
221
|
+
/** 兼容旧调用名 */
|
|
222
|
+
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 {
|
|
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 =
|
|
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
|
|
219
|
+
return API_CATALOG.filter((s) => s.verified === null);
|
|
180
220
|
}
|
package/package.json
CHANGED
package/web/dashboard.html
CHANGED
|
@@ -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">+
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1111
|
-
|
|
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=
|
|
1115
|
-
var
|
|
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+
|
|
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
|
-
/*
|
|
1126
|
-
|
|
1165
|
+
/* 添加平台:一个下拉选平台 + 一个输入框填 key,两步搞定。
|
|
1166
|
+
比原来的「填名称/端点/字段路径/鉴权方式」四条强太多——
|
|
1167
|
+
绝大多数用户只想「选个平台、粘个 key」。 */
|
|
1168
|
+
function showAddPlatform(){
|
|
1127
1169
|
if(!settings)return;
|
|
1128
|
-
var
|
|
1129
|
-
if(!
|
|
1130
|
-
|
|
1131
|
-
var
|
|
1132
|
-
if(!
|
|
1133
|
-
|
|
1134
|
-
|
|
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
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
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
|
-
|
|
1156
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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",
|
|
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
|
-
|
|
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
|
-
|
|
1255
|
-
|
|
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 里)
|