@anthonyhan/token-pilot 0.3.4 → 0.4.1
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 +67 -7
- package/dist/cli/index.js +23 -1
- package/dist/core/aggregate.js +16 -0
- package/dist/core/collector.js +34 -5
- package/dist/core/contract.js +0 -3
- package/dist/core/doctor.js +249 -0
- package/dist/core/quota/credentials.js +139 -0
- package/dist/core/quota/format.js +116 -0
- package/dist/core/quota/index.js +66 -0
- package/dist/core/quota/providers/balance.js +166 -0
- package/dist/core/quota/providers/opencode.js +146 -0
- package/dist/core/quota/providers/volc.js +112 -0
- package/dist/core/quota/types.js +62 -0
- package/dist/core/version.js +25 -0
- package/package.json +1 -1
- package/web/dashboard.html +162 -1
- package/web/panel.html +29 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// 额度快照的终端渲染
|
|
2
|
+
//
|
|
3
|
+
// 参考 TodoBar / TokenBar 的做法:进度条 + 百分比 + 重置倒计时 + 节奏标记。
|
|
4
|
+
// 「节奏」那一列是这套数据的核心价值——单看 60% 没意义,
|
|
5
|
+
// 知道「窗口才过 40% 就已经用了 60%」才知道该不该踩刹车。
|
|
6
|
+
import { paceDelta, untilReset } from './types.js';
|
|
7
|
+
const BAR_WIDTH = 14;
|
|
8
|
+
/** 按终端显示宽度补空格(中文占 2 格) */
|
|
9
|
+
function padDisplay(str, width) {
|
|
10
|
+
let w = 0;
|
|
11
|
+
for (const ch of str)
|
|
12
|
+
w += /[\u4e00-\u9fff\uff00-\uffef]/.test(ch) ? 2 : 1;
|
|
13
|
+
return str + ' '.repeat(Math.max(0, width - w));
|
|
14
|
+
}
|
|
15
|
+
function bar(percent) {
|
|
16
|
+
const p = Math.max(0, Math.min(100, percent));
|
|
17
|
+
const filled = Math.round((p / 100) * BAR_WIDTH);
|
|
18
|
+
return '█'.repeat(filled) + '░'.repeat(BAR_WIDTH - filled);
|
|
19
|
+
}
|
|
20
|
+
function paceMark(w) {
|
|
21
|
+
const d = paceDelta(w);
|
|
22
|
+
if (d === null)
|
|
23
|
+
return '';
|
|
24
|
+
if (d > 15)
|
|
25
|
+
return ` ⚠️ 比线性节奏快 ${Math.round(d)}%`;
|
|
26
|
+
if (d < -15)
|
|
27
|
+
return ` ✓ 比线性节奏慢 ${Math.round(-d)}%`;
|
|
28
|
+
return '';
|
|
29
|
+
}
|
|
30
|
+
function windowLine(w, indent) {
|
|
31
|
+
const out = [];
|
|
32
|
+
const pct = `${w.percent.toFixed(w.percent < 10 ? 1 : 0)}%`.padStart(5);
|
|
33
|
+
// 有绝对值就显示,没有就只显示百分比(Coding Plan 就是这种)
|
|
34
|
+
const abs = typeof w.used === 'number' && typeof w.total === 'number'
|
|
35
|
+
? ` ${w.used}/${w.total}`
|
|
36
|
+
: '';
|
|
37
|
+
const reset = untilReset(w);
|
|
38
|
+
const resetStr = reset ? ` ${reset}刷新` : '';
|
|
39
|
+
out.push(` ${indent}${bar(w.percent)} ${pct}${abs}${resetStr}${paceMark(w)}`);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
export function formatQuota(snap) {
|
|
43
|
+
const lines = [];
|
|
44
|
+
lines.push('');
|
|
45
|
+
lines.push('token-pilot · 订阅额度与余额');
|
|
46
|
+
lines.push('');
|
|
47
|
+
if (snap.cached)
|
|
48
|
+
lines.push(' (缓存结果,5 分钟内不重复请求;--force 强制刷新)');
|
|
49
|
+
if (snap.cached)
|
|
50
|
+
lines.push('');
|
|
51
|
+
if (snap.providers.length === 0) {
|
|
52
|
+
lines.push(' 还没有可监控的平台。');
|
|
53
|
+
lines.push(' → 火山:安装 arkcli 并登录后自动出现');
|
|
54
|
+
lines.push('');
|
|
55
|
+
return lines.join('\n');
|
|
56
|
+
}
|
|
57
|
+
for (const p of snap.providers) {
|
|
58
|
+
lines.push(` ${p.displayName} ${sourceTag(p)}`);
|
|
59
|
+
if (!p.ok) {
|
|
60
|
+
lines.push(` ✗ ${p.error ?? '获取失败'}`);
|
|
61
|
+
lines.push('');
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (p.windows && p.windows.length > 0) {
|
|
65
|
+
for (const w of p.windows) {
|
|
66
|
+
const pct = `${w.percent.toFixed(w.percent < 10 ? 1 : 0)}%`.padStart(5);
|
|
67
|
+
const abs = typeof w.used === 'number' && typeof w.total === 'number' ? ` ${w.used}/${w.total}` : '';
|
|
68
|
+
const reset = untilReset(w);
|
|
69
|
+
const resetStr = reset ? ` ${reset}刷新` : '';
|
|
70
|
+
lines.push(` ${padDisplay(w.label, 14)} ${bar(w.percent)} ${pct}${abs}${resetStr}${paceMark(w)}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (p.tokenPlan) {
|
|
74
|
+
const t = p.tokenPlan;
|
|
75
|
+
const name = t.planName ?? 'Token Plan';
|
|
76
|
+
if (t.percent != null) {
|
|
77
|
+
lines.push(` ${padDisplay(name, 14)} ${bar(t.percent)} ${t.percent.toFixed(0).padStart(3)}%`);
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
lines.push(` ${name}`);
|
|
81
|
+
}
|
|
82
|
+
if (t.remainingTokens != null) {
|
|
83
|
+
lines.push(` 剩余 ${fmtTokens(t.remainingTokens)} tokens`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (p.balance) {
|
|
87
|
+
const sym = p.balance.currency === 'CNY' ? '¥' : '$';
|
|
88
|
+
lines.push(` 余额 ${sym}${p.balance.amount.toFixed(2)}`);
|
|
89
|
+
}
|
|
90
|
+
if (p.note)
|
|
91
|
+
lines.push(` ℹ️ ${p.note}`);
|
|
92
|
+
lines.push('');
|
|
93
|
+
}
|
|
94
|
+
return lines.join('\n');
|
|
95
|
+
}
|
|
96
|
+
function sourceTag(p) {
|
|
97
|
+
switch (p.source) {
|
|
98
|
+
case 'api':
|
|
99
|
+
return '(官方接口)';
|
|
100
|
+
case 'cli':
|
|
101
|
+
return '(官方 CLI)';
|
|
102
|
+
case 'computed':
|
|
103
|
+
return '(本地计算)';
|
|
104
|
+
case 'manual':
|
|
105
|
+
return '(手动登记)';
|
|
106
|
+
default:
|
|
107
|
+
return '';
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function fmtTokens(n) {
|
|
111
|
+
if (n >= 1e8)
|
|
112
|
+
return `${(n / 1e8).toFixed(2)} 亿`;
|
|
113
|
+
if (n >= 1e4)
|
|
114
|
+
return `${(n / 1e4).toFixed(1)} 万`;
|
|
115
|
+
return String(Math.round(n));
|
|
116
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// 额度聚合入口
|
|
2
|
+
//
|
|
3
|
+
// 设计约束:
|
|
4
|
+
// 1. 单个平台失败不影响其它平台(per-provider error isolation)
|
|
5
|
+
// 2. 5 分钟缓存,避免每次刷新看板都去请求外部接口
|
|
6
|
+
// 3. 缓存文件独立于账单数据——账单是确定性计算结果,额度是外部瞬时快照,
|
|
7
|
+
// 混在一起会让对账逻辑变复杂
|
|
8
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { CONFIG_DIR } from '../config.js';
|
|
11
|
+
import { fetchVolcQuota } from './providers/volc.js';
|
|
12
|
+
import { fetchOpencodeQuota } from './providers/opencode.js';
|
|
13
|
+
import { fetchDeepseekBalance, fetchGlmQuota, fetchMinimaxTokenPlan } from './providers/balance.js';
|
|
14
|
+
const CACHE_PATH = path.join(CONFIG_DIR, 'quota-cache.json');
|
|
15
|
+
const TTL_MS = 5 * 60_000;
|
|
16
|
+
export async function collectQuota(force = false) {
|
|
17
|
+
if (!force) {
|
|
18
|
+
const cached = readCache();
|
|
19
|
+
if (cached)
|
|
20
|
+
return { ...cached, cached: true };
|
|
21
|
+
}
|
|
22
|
+
// 目前只有火山有 provider;后续平台在这里追加
|
|
23
|
+
const tasks = [
|
|
24
|
+
fetchVolcQuota(),
|
|
25
|
+
fetchOpencodeQuota(),
|
|
26
|
+
fetchDeepseekBalance(),
|
|
27
|
+
fetchGlmQuota(),
|
|
28
|
+
fetchMinimaxTokenPlan(),
|
|
29
|
+
];
|
|
30
|
+
// allSettled:一个平台抛异常不拖垮其它
|
|
31
|
+
const settled = await Promise.allSettled(tasks);
|
|
32
|
+
const providers = settled.map((r, i) => r.status === 'fulfilled'
|
|
33
|
+
? r.value
|
|
34
|
+
: {
|
|
35
|
+
id: `unknown-${i}`,
|
|
36
|
+
displayName: '未知平台',
|
|
37
|
+
source: 'api',
|
|
38
|
+
ok: false,
|
|
39
|
+
error: String(r.reason).slice(0, 200),
|
|
40
|
+
fetchedAt: Date.now(),
|
|
41
|
+
});
|
|
42
|
+
const snap = { generatedAt: Date.now(), providers };
|
|
43
|
+
writeCache(snap);
|
|
44
|
+
return snap;
|
|
45
|
+
}
|
|
46
|
+
function readCache() {
|
|
47
|
+
try {
|
|
48
|
+
if (!existsSync(CACHE_PATH))
|
|
49
|
+
return null;
|
|
50
|
+
const d = JSON.parse(readFileSync(CACHE_PATH, 'utf8'));
|
|
51
|
+
if (!d.generatedAt || Date.now() - d.generatedAt > TTL_MS)
|
|
52
|
+
return null;
|
|
53
|
+
return d;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function writeCache(snap) {
|
|
60
|
+
try {
|
|
61
|
+
writeFileSync(CACHE_PATH, JSON.stringify(snap), 'utf8');
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
/* 缓存写失败不影响主流程 */
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// 标准余额接口 provider(DeepSeek / Moonshot / 智谱 GLM)
|
|
2
|
+
//
|
|
3
|
+
// 这三个平台的共性是:提供 HTTP 接口查余额,需要用户在设置里填 key 或复用 CC Switch。
|
|
4
|
+
// 与火山的 subprocess 模式、OpenCode 的固定端点不同,这里用一张描述表驱动,
|
|
5
|
+
// 加新平台只需要在 BALANCE_APIS 里加一条,不改逻辑。
|
|
6
|
+
//
|
|
7
|
+
// 实测确认的返回结构:
|
|
8
|
+
// DeepSeek GET /user/balance
|
|
9
|
+
// {"is_available":true,"balance_infos":[{"currency":"CNY","total_balance":"11.40",...}]}
|
|
10
|
+
// 智谱 GLM GET /api/monitor/usage/quota/limit
|
|
11
|
+
// {"code":200,"data":{"limits":[{"type":"CREDIT_LIMIT","usage":2000,"remaining":2000,
|
|
12
|
+
// "percentage":0,"nextResetTime":1793847267998}],"level":"lite"}}
|
|
13
|
+
// (这个其实是「额度」不是现金余额,所以走 RateWindow 而不是 Balance)
|
|
14
|
+
import { execFile } from 'node:child_process';
|
|
15
|
+
import { promisify } from 'node:util';
|
|
16
|
+
import { resolveKey } from '../credentials.js';
|
|
17
|
+
const execFileP = promisify(execFile);
|
|
18
|
+
async function httpJson(url, key, authHeader = 'bearer') {
|
|
19
|
+
const script = `
|
|
20
|
+
import json, sys, urllib.request
|
|
21
|
+
hdr = {
|
|
22
|
+
'User-Agent': 'token-pilot',
|
|
23
|
+
'Accept': 'application/json',
|
|
24
|
+
'Authorization': ('Bearer ' if sys.argv[3] == 'bearer' else '') + sys.argv[2],
|
|
25
|
+
}
|
|
26
|
+
req = urllib.request.Request(sys.argv[1], headers=hdr)
|
|
27
|
+
try:
|
|
28
|
+
with urllib.request.urlopen(req, timeout=15) as r:
|
|
29
|
+
print(r.read().decode())
|
|
30
|
+
except Exception as e:
|
|
31
|
+
print(json.dumps({'__error': str(e)}))
|
|
32
|
+
`;
|
|
33
|
+
try {
|
|
34
|
+
const { stdout } = await execFileP('python3', ['-c', script, url, key, authHeader], { timeout: 20_000 });
|
|
35
|
+
const d = JSON.parse(stdout);
|
|
36
|
+
if (d.__error)
|
|
37
|
+
return { ok: false, error: d.__error };
|
|
38
|
+
return { ok: true, data: d };
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
return { ok: false, error: String(e).slice(0, 150) };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** DeepSeek:现金余额 */
|
|
45
|
+
export async function fetchDeepseekBalance() {
|
|
46
|
+
const base = {
|
|
47
|
+
id: 'deepseek',
|
|
48
|
+
displayName: 'DeepSeek',
|
|
49
|
+
source: 'api',
|
|
50
|
+
ok: false,
|
|
51
|
+
fetchedAt: Date.now(),
|
|
52
|
+
};
|
|
53
|
+
const cred = await resolveKey('deepseek', 'deepseek');
|
|
54
|
+
if (!cred) {
|
|
55
|
+
return { ...base, error: '未配置 API Key(看板设置里填,或装了 CC Switch 可自动读取)' };
|
|
56
|
+
}
|
|
57
|
+
const r = await httpJson('https://api.deepseek.com/user/balance', cred.key);
|
|
58
|
+
if (!r.ok) {
|
|
59
|
+
return {
|
|
60
|
+
...base,
|
|
61
|
+
error: /401|403/.test(r.error) ? 'API Key 无效或已过期' : r.error,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const d = r.data;
|
|
65
|
+
const info = (d.balance_infos ?? [])[0];
|
|
66
|
+
const amount = info?.total_balance ? Number(info.total_balance) : NaN;
|
|
67
|
+
if (!Number.isFinite(amount)) {
|
|
68
|
+
return { ...base, error: '接口没有返回可解析的余额' };
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
...base,
|
|
72
|
+
ok: true,
|
|
73
|
+
balance: { amount, currency: (info?.currency === 'USD' ? 'USD' : 'CNY') },
|
|
74
|
+
note: d.is_available === false ? '账户当前不可用(可能欠费)' : cred.detail,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/** 智谱 GLM:额度(不是现金余额,是积分制套餐) */
|
|
78
|
+
export async function fetchGlmQuota() {
|
|
79
|
+
const base = {
|
|
80
|
+
id: 'glm',
|
|
81
|
+
displayName: '智谱 GLM',
|
|
82
|
+
source: 'api',
|
|
83
|
+
ok: false,
|
|
84
|
+
fetchedAt: Date.now(),
|
|
85
|
+
};
|
|
86
|
+
const cred = await resolveKey('glm', 'GLM');
|
|
87
|
+
if (!cred) {
|
|
88
|
+
return { ...base, error: '未配置 API Key(看板设置里填,或装了 CC Switch 可自动读取)' };
|
|
89
|
+
}
|
|
90
|
+
const r = await httpJson('https://open.bigmodel.cn/api/monitor/usage/quota/limit', cred.key);
|
|
91
|
+
if (!r.ok) {
|
|
92
|
+
return { ...base, error: /401|403/.test(r.error) ? 'API Key 无效或已过期' : r.error };
|
|
93
|
+
}
|
|
94
|
+
const d = r.data;
|
|
95
|
+
const limits = d.data?.limits ?? [];
|
|
96
|
+
if (limits.length === 0) {
|
|
97
|
+
return { ...base, error: '没有查到额度信息(可能未订阅套餐)' };
|
|
98
|
+
}
|
|
99
|
+
// unit/number 组合表示窗口长度,实测没给出明确的天/小时语义,
|
|
100
|
+
// 所以只按出现顺序编号,不猜具体时长(猜错会让「节奏」计算失真)
|
|
101
|
+
const windows = limits.map((l, i) => ({
|
|
102
|
+
id: `glm-${l.type ?? i}`,
|
|
103
|
+
label: `额度窗口 ${i + 1}`,
|
|
104
|
+
percent: typeof l.percentage === 'number' ? l.percentage : 0,
|
|
105
|
+
used: typeof l.usage === 'number' ? l.usage : undefined,
|
|
106
|
+
total: typeof l.usage === 'number' ? l.usage : undefined,
|
|
107
|
+
resetsAt: typeof l.nextResetTime === 'number'
|
|
108
|
+
? new Date(l.nextResetTime).toISOString()
|
|
109
|
+
: undefined,
|
|
110
|
+
unit: 'credits',
|
|
111
|
+
}));
|
|
112
|
+
return {
|
|
113
|
+
...base,
|
|
114
|
+
ok: true,
|
|
115
|
+
windows,
|
|
116
|
+
note: `${cred.detail};套餐档位 ${d.data?.level ?? '未知'}`,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** MiniMax:token plan 剩余额度 */
|
|
120
|
+
export async function fetchMinimaxTokenPlan() {
|
|
121
|
+
const base = {
|
|
122
|
+
id: 'minimax',
|
|
123
|
+
displayName: 'MiniMax',
|
|
124
|
+
source: 'api',
|
|
125
|
+
ok: false,
|
|
126
|
+
fetchedAt: Date.now(),
|
|
127
|
+
};
|
|
128
|
+
const cred = await resolveKey('minimax', 'minimax');
|
|
129
|
+
if (!cred) {
|
|
130
|
+
return { ...base, error: '未配置 API Key(看板设置里填,或装了 CC Switch 可自动读取)' };
|
|
131
|
+
}
|
|
132
|
+
const r = await httpJson('https://api.minimaxi.com/v1/token_plan/remains', cred.key);
|
|
133
|
+
if (!r.ok) {
|
|
134
|
+
return { ...base, error: /401|403/.test(r.error) ? 'API Key 无效或已过期' : r.error };
|
|
135
|
+
}
|
|
136
|
+
const d = r.data;
|
|
137
|
+
const code = d.base_resp?.status_code ?? 0;
|
|
138
|
+
if (code !== 0) {
|
|
139
|
+
// 2062 = 没有生效的 token plan 订阅,这是正常状态而非错误
|
|
140
|
+
const msg = d.base_resp?.status_msg ?? `status_code ${code}`;
|
|
141
|
+
return {
|
|
142
|
+
...base,
|
|
143
|
+
error: /no active token plan/i.test(msg) ? '当前没有生效的 Token Plan 订阅' : msg,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
// model_remains 的实际结构未实测(本机账号无订阅),按可能字段宽松解析
|
|
147
|
+
const mr = d.model_remains;
|
|
148
|
+
if (!mr) {
|
|
149
|
+
return { ...base, error: '接口返回里没有 model_remains 数据' };
|
|
150
|
+
}
|
|
151
|
+
const total = typeof mr.total_tokens === 'number' ? mr.total_tokens : undefined;
|
|
152
|
+
const used = typeof mr.used_tokens === 'number' ? mr.used_tokens : undefined;
|
|
153
|
+
const remaining = typeof mr.remaining_tokens === 'number' ? mr.remaining_tokens : undefined;
|
|
154
|
+
return {
|
|
155
|
+
...base,
|
|
156
|
+
ok: true,
|
|
157
|
+
tokenPlan: {
|
|
158
|
+
planName: 'MiniMax Token Plan',
|
|
159
|
+
usedTokens: used,
|
|
160
|
+
totalTokens: total,
|
|
161
|
+
remainingTokens: remaining,
|
|
162
|
+
percent: total && used != null ? Math.round((used / total) * 1000) / 10 : undefined,
|
|
163
|
+
},
|
|
164
|
+
note: `${cred.detail};结构为按字段宽松解析(本机无订阅实测样本)`,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// OpenCode(Go / Zen)额度
|
|
2
|
+
//
|
|
3
|
+
// 接口:GET https://opencode.ai/zen/go/v1/usage
|
|
4
|
+
// 鉴权:Authorization: Bearer <oc_sk_...>
|
|
5
|
+
//
|
|
6
|
+
// 本机实测返回(2026-10-29):
|
|
7
|
+
// {
|
|
8
|
+
// "usage": {
|
|
9
|
+
// "rolling": { "status": "ok", "percent": 0, "resetsAt": "2026-10-29T11:47:19.154Z" },
|
|
10
|
+
// "weekly": { "status": "ok", "percent": 1, "resetsAt": "2026-11-02T00:00:00.000Z" },
|
|
11
|
+
// "monthly": { "status": "ok", "percent": 98, "resetsAt": "2026-11-09T03:09:52.000Z" }
|
|
12
|
+
// }
|
|
13
|
+
// }
|
|
14
|
+
//
|
|
15
|
+
// 之所以优先做这个而不是「等用户配 key」:OpenCode 的凭证本来就在
|
|
16
|
+
// ~/.local/share/opencode/auth.json,不需要用户做任何事。
|
|
17
|
+
import { execFile } from 'node:child_process';
|
|
18
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
19
|
+
import os from 'node:os';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { promisify } from 'node:util';
|
|
22
|
+
import { fromConfig, fromCcSwitch } from '../credentials.js';
|
|
23
|
+
const execFileP = promisify(execFile);
|
|
24
|
+
const USAGE_URL = 'https://opencode.ai/zen/go/v1/usage';
|
|
25
|
+
/** 窗口 id → 中文名 + 时长(分钟) */
|
|
26
|
+
const WINDOWS = {
|
|
27
|
+
rolling: { label: '滚动窗口', minutes: 5 * 60 },
|
|
28
|
+
weekly: { label: '本周', minutes: 7 * 24 * 60 },
|
|
29
|
+
monthly: { label: '本月', minutes: 30 * 24 * 60 },
|
|
30
|
+
};
|
|
31
|
+
/** 从 OpenCode 自己的 auth.json 取 key(不依赖 CC Switch) */
|
|
32
|
+
function fromOpencodeNative() {
|
|
33
|
+
const p = path.join(os.homedir(), '.local', 'share', 'opencode', 'auth.json');
|
|
34
|
+
if (!existsSync(p))
|
|
35
|
+
return null;
|
|
36
|
+
try {
|
|
37
|
+
const d = JSON.parse(readFileSync(p, 'utf8'));
|
|
38
|
+
// 优先 opencode-go,其次任意 oc_sk_ 开头的
|
|
39
|
+
if (d['opencode-go']?.key)
|
|
40
|
+
return d['opencode-go'].key;
|
|
41
|
+
for (const v of Object.values(d)) {
|
|
42
|
+
if (v?.key?.startsWith('oc_sk_'))
|
|
43
|
+
return v.key;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
/* 解析失败按无凭证处理 */
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
async function resolveOpencodeKey() {
|
|
52
|
+
const cfg = fromConfig('opencode');
|
|
53
|
+
if (cfg)
|
|
54
|
+
return { key: cfg.key, detail: cfg.detail };
|
|
55
|
+
const native = fromOpencodeNative();
|
|
56
|
+
if (native) {
|
|
57
|
+
return { key: native, detail: '来自 OpenCode 的登录凭据(~/.local/share/opencode/auth.json)' };
|
|
58
|
+
}
|
|
59
|
+
const ccs = await fromCcSwitch('opencode');
|
|
60
|
+
if (ccs)
|
|
61
|
+
return { key: ccs.key, detail: ccs.detail };
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
async function httpGetJson(url, key) {
|
|
65
|
+
const script = `
|
|
66
|
+
import json, sys, urllib.request
|
|
67
|
+
req = urllib.request.Request(sys.argv[1], headers={
|
|
68
|
+
'Authorization': 'Bearer ' + sys.argv[2],
|
|
69
|
+
# 服务端会按 User-Agent 拦请求:不带 UA 时 urllib 默认的 Python-urllib/x.y 会 403
|
|
70
|
+
'User-Agent': 'token-pilot',
|
|
71
|
+
'Accept': 'application/json',
|
|
72
|
+
})
|
|
73
|
+
try:
|
|
74
|
+
with urllib.request.urlopen(req, timeout=15) as r:
|
|
75
|
+
print(r.read().decode())
|
|
76
|
+
except Exception as e:
|
|
77
|
+
print(json.dumps({'__error': str(e)}))
|
|
78
|
+
`;
|
|
79
|
+
try {
|
|
80
|
+
const { stdout } = await execFileP('python3', ['-c', script, url, key], { timeout: 20_000 });
|
|
81
|
+
return JSON.parse(stdout);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
return { __error: String(e).slice(0, 150) };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export async function fetchOpencodeQuota() {
|
|
88
|
+
const base = {
|
|
89
|
+
id: 'opencode',
|
|
90
|
+
displayName: 'OpenCode Go',
|
|
91
|
+
source: 'api',
|
|
92
|
+
ok: false,
|
|
93
|
+
fetchedAt: Date.now(),
|
|
94
|
+
};
|
|
95
|
+
const cred = await resolveOpencodeKey();
|
|
96
|
+
if (!cred) {
|
|
97
|
+
return { ...base, error: '未找到 OpenCode 凭据(需先在 OpenCode 里登录,或在设置里填 key)' };
|
|
98
|
+
}
|
|
99
|
+
const res = (await httpGetJson(USAGE_URL, cred.key));
|
|
100
|
+
if (res.__error) {
|
|
101
|
+
const hint = /401/.test(res.__error)
|
|
102
|
+
? '凭证无效或已过期,请在 OpenCode 里重新登录'
|
|
103
|
+
: /403/.test(res.__error)
|
|
104
|
+
? '接口拒绝访问(403)——若刚登录过请重试'
|
|
105
|
+
: res.__error;
|
|
106
|
+
return { ...base, error: hint };
|
|
107
|
+
}
|
|
108
|
+
if (!res.usage) {
|
|
109
|
+
return { ...base, error: '接口返回里没有 usage 字段' };
|
|
110
|
+
}
|
|
111
|
+
// 按 rolling → weekly → monthly 的固定顺序输出,避免顺序抖动
|
|
112
|
+
const order = ['rolling', 'weekly', 'monthly'];
|
|
113
|
+
const windows = [];
|
|
114
|
+
for (const id of order) {
|
|
115
|
+
const u = res.usage[id];
|
|
116
|
+
if (!u)
|
|
117
|
+
continue;
|
|
118
|
+
const meta = WINDOWS[id];
|
|
119
|
+
windows.push({
|
|
120
|
+
id: `opencode-${id}`,
|
|
121
|
+
label: meta?.label ?? id,
|
|
122
|
+
percent: typeof u.percent === 'number' ? u.percent : 0,
|
|
123
|
+
resetsAt: u.resetsAt,
|
|
124
|
+
windowMinutes: meta?.minutes,
|
|
125
|
+
unit: 'requests',
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
// 只留我们认识的窗口,未知 id 也带上但不猜时长
|
|
129
|
+
for (const [id, u] of Object.entries(res.usage)) {
|
|
130
|
+
if (order.includes(id))
|
|
131
|
+
continue;
|
|
132
|
+
windows.push({
|
|
133
|
+
id: `opencode-${id}`,
|
|
134
|
+
label: id,
|
|
135
|
+
percent: typeof u.percent === 'number' ? u.percent : 0,
|
|
136
|
+
resetsAt: u.resetsAt,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
...base,
|
|
141
|
+
ok: windows.length > 0,
|
|
142
|
+
windows,
|
|
143
|
+
note: `${cred.detail};仅有百分比,平台不下发绝对额度`,
|
|
144
|
+
error: windows.length === 0 ? '没有可用的额度窗口' : undefined,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// 火山方舟额度:调 `arkcli usage plan --format json`
|
|
2
|
+
//
|
|
3
|
+
// 这是全部平台里唯一有权威额度 API 的,返回结构已经本机实测确认:
|
|
4
|
+
//
|
|
5
|
+
// {
|
|
6
|
+
// "viewer": { "profile": "coding-plan_...", ... },
|
|
7
|
+
// "items": [{
|
|
8
|
+
// "product": "coding-plan", "edition": "personal", "tier": "lite",
|
|
9
|
+
// "subscribed": true,
|
|
10
|
+
// "periods": [
|
|
11
|
+
// { "label": "weekly", "percent": 11.28, "reset_at": "2026-11-02T00:00:00+08:00" }
|
|
12
|
+
// ]
|
|
13
|
+
// }]
|
|
14
|
+
// }
|
|
15
|
+
//
|
|
16
|
+
// 重要差异(决定 UI 显示什么):
|
|
17
|
+
// - agent-plan:给 used/total 绝对值
|
|
18
|
+
// - coding-plan:**只给 percent,没有 used/total** —— 不得编造绝对值
|
|
19
|
+
import { execFile } from 'node:child_process';
|
|
20
|
+
import { promisify } from 'node:util';
|
|
21
|
+
const execFileP = promisify(execFile);
|
|
22
|
+
/** period label → 中文名 + 窗口分钟数(窗口长度用于算节奏) */
|
|
23
|
+
const LABELS = {
|
|
24
|
+
'5h': { label: '5 小时', minutes: 5 * 60 },
|
|
25
|
+
session: { label: '会话窗口', minutes: 5 * 60 },
|
|
26
|
+
weekly: { label: '本周', minutes: 7 * 24 * 60 },
|
|
27
|
+
monthly: { label: '本月', minutes: 30 * 24 * 60 },
|
|
28
|
+
};
|
|
29
|
+
const PRODUCT_NAMES = {
|
|
30
|
+
'agent-plan': 'Agent Plan',
|
|
31
|
+
'coding-plan': 'Coding Plan',
|
|
32
|
+
'agent-plan-team': 'Agent Plan(团队)',
|
|
33
|
+
'coding-plan-team': 'Coding Plan(团队)',
|
|
34
|
+
};
|
|
35
|
+
/** 把 arkcli 的一个 item 转成一组窗口 */
|
|
36
|
+
function toWindows(item) {
|
|
37
|
+
const productName = PRODUCT_NAMES[item.product ?? ''] ?? item.product ?? '火山';
|
|
38
|
+
const tier = item.tier ? ` ${item.tier}` : '';
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const p of item.periods ?? []) {
|
|
41
|
+
const meta = LABELS[p.label ?? ''];
|
|
42
|
+
const label = meta?.label ?? p.label ?? '窗口';
|
|
43
|
+
// Coding Plan 没有绝对值;Agent Plan 有
|
|
44
|
+
const hasAbs = typeof p.used === 'number' || typeof p.total === 'number';
|
|
45
|
+
out.push({
|
|
46
|
+
id: `${item.product ?? 'volc'}-${p.label ?? 'w'}`,
|
|
47
|
+
label: `${productName}${tier} · ${label}`,
|
|
48
|
+
percent: typeof p.percent === 'number' ? p.percent : 0,
|
|
49
|
+
used: hasAbs ? p.used : undefined,
|
|
50
|
+
total: hasAbs ? p.total : undefined,
|
|
51
|
+
resetsAt: p.reset_at,
|
|
52
|
+
windowMinutes: meta?.minutes,
|
|
53
|
+
unit: item.product?.startsWith('agent-plan') ? 'AFP' : 'requests',
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
export async function fetchVolcQuota() {
|
|
59
|
+
const base = {
|
|
60
|
+
id: 'volc',
|
|
61
|
+
displayName: '火山方舟',
|
|
62
|
+
source: 'cli',
|
|
63
|
+
ok: false,
|
|
64
|
+
fetchedAt: Date.now(),
|
|
65
|
+
};
|
|
66
|
+
let raw;
|
|
67
|
+
try {
|
|
68
|
+
const { stdout } = await execFileP('arkcli', ['usage', 'plan', '--format', 'json'], { timeout: 30_000 });
|
|
69
|
+
raw = stdout;
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
const msg = String(e.stderr ?? e).slice(0, 200);
|
|
73
|
+
// arkcli 未安装 / 未登录是常见情况,给出可执行提示
|
|
74
|
+
const hint = /ENOENT/.test(msg)
|
|
75
|
+
? '未安装 arkcli(可选组件,装了才能读火山额度)'
|
|
76
|
+
: /state_migration|login|auth/i.test(msg)
|
|
77
|
+
? 'arkcli 未就绪,请在终端跑一次 arkcli profile list 完成初始化'
|
|
78
|
+
: msg;
|
|
79
|
+
return { ...base, error: hint };
|
|
80
|
+
}
|
|
81
|
+
let parsed;
|
|
82
|
+
try {
|
|
83
|
+
parsed = JSON.parse(raw);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return { ...base, error: 'arkcli 输出了非 JSON 内容' };
|
|
87
|
+
}
|
|
88
|
+
const items = (parsed.items ?? []).filter((i) => i.subscribed);
|
|
89
|
+
if (items.length === 0) {
|
|
90
|
+
return { ...base, error: '当前账号没有查到已订阅的 Agent Plan / Coding Plan' };
|
|
91
|
+
}
|
|
92
|
+
const windows = [];
|
|
93
|
+
const notes = [];
|
|
94
|
+
for (const item of items) {
|
|
95
|
+
windows.push(...toWindows(item));
|
|
96
|
+
// 如实标注:Coding Plan 只有百分比
|
|
97
|
+
if (item.product?.startsWith('coding-plan')) {
|
|
98
|
+
const anyPercentOnly = (item.periods ?? []).every((p) => p.used == null && p.total == null);
|
|
99
|
+
if (anyPercentOnly)
|
|
100
|
+
notes.push('Coding Plan 仅提供已用百分比,平台不下发绝对值');
|
|
101
|
+
}
|
|
102
|
+
if (item.error)
|
|
103
|
+
notes.push(`${item.product}: ${item.error}`);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
...base,
|
|
107
|
+
ok: windows.length > 0,
|
|
108
|
+
windows,
|
|
109
|
+
note: notes.length > 0 ? notes.join(';') : undefined,
|
|
110
|
+
error: windows.length === 0 ? '返回了订阅但没有任何额度窗口' : undefined,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// 额度与余额的统一数据模型
|
|
2
|
+
//
|
|
3
|
+
// 这里刻意分成三种类型,因为它们的经济含义完全不同,混在一起 UI 就没法正确显示:
|
|
4
|
+
//
|
|
5
|
+
// RateWindow —— 订阅套餐的时间窗口。到点自动重置,用超了要等下一轮。
|
|
6
|
+
// 例:火山 Coding Plan 的 session/weekly/monthly。
|
|
7
|
+
// TokenPlanQuota —— 预付费 token 包。买断制,用完就是没了,不会重置。
|
|
8
|
+
// 例:MiniMax Token Plan、小米 MiMo token plan。
|
|
9
|
+
// Balance —— 现金账户余额。充多少花多少。
|
|
10
|
+
// 例:DeepSeek / Moonshot / 智谱。
|
|
11
|
+
//
|
|
12
|
+
// 一个平台可以同时有多种(比如火山既有订阅套餐又有按量余额)。
|
|
13
|
+
/**
|
|
14
|
+
* 「比线性节奏快还是慢」。
|
|
15
|
+
*
|
|
16
|
+
* 这是整套额度监控里最有用的一个派生值:已用 60% 但窗口只过了 40%,
|
|
17
|
+
* 说明照这个速度会在重置前用光,paceDelta = +20。
|
|
18
|
+
*
|
|
19
|
+
* 缺 resetsAt 或 windowMinutes 时返回 null(算不出来就说算不出来,不猜)。
|
|
20
|
+
*/
|
|
21
|
+
export function paceDelta(w, now = Date.now()) {
|
|
22
|
+
if (!w.resetsAt || !w.windowMinutes || w.windowMinutes <= 0)
|
|
23
|
+
return null;
|
|
24
|
+
const reset = Date.parse(w.resetsAt);
|
|
25
|
+
if (Number.isNaN(reset))
|
|
26
|
+
return null;
|
|
27
|
+
const totalMs = w.windowMinutes * 60_000;
|
|
28
|
+
const leftMs = Math.max(0, Math.min(reset - now, totalMs));
|
|
29
|
+
const elapsedFraction = (totalMs - leftMs) / totalMs;
|
|
30
|
+
if (elapsedFraction < 0.02)
|
|
31
|
+
return null; // 窗口刚开始,节奏判断没有意义
|
|
32
|
+
return w.percent - elapsedFraction * 100;
|
|
33
|
+
}
|
|
34
|
+
/** 距离重置还有多久的人话描述 */
|
|
35
|
+
export function untilReset(w, now = Date.now()) {
|
|
36
|
+
if (!w.resetsAt)
|
|
37
|
+
return null;
|
|
38
|
+
const reset = Date.parse(w.resetsAt);
|
|
39
|
+
if (Number.isNaN(reset))
|
|
40
|
+
return null;
|
|
41
|
+
const ms = reset - now;
|
|
42
|
+
if (ms <= 0)
|
|
43
|
+
return '即将重置';
|
|
44
|
+
const mins = Math.floor(ms / 60_000);
|
|
45
|
+
if (mins < 60)
|
|
46
|
+
return `${mins} 分钟后`;
|
|
47
|
+
const hours = Math.floor(mins / 60);
|
|
48
|
+
if (hours < 24)
|
|
49
|
+
return `${hours} 小时 ${mins % 60} 分后`;
|
|
50
|
+
const days = Math.floor(hours / 24);
|
|
51
|
+
return `${days} 天 ${hours % 24} 小时后`;
|
|
52
|
+
}
|
|
53
|
+
/** 额度紧张程度:用于状态栏取「最紧张的那个」,也用于 UI 着色 */
|
|
54
|
+
export function tension(q) {
|
|
55
|
+
// 百分比越高越紧张
|
|
56
|
+
let max = 0;
|
|
57
|
+
for (const w of q.windows ?? [])
|
|
58
|
+
max = Math.max(max, w.percent);
|
|
59
|
+
if (q.tokenPlan?.percent != null)
|
|
60
|
+
max = Math.max(max, q.tokenPlan.percent);
|
|
61
|
+
return max;
|
|
62
|
+
}
|