scalemax 0.1.53 → 0.1.54
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 +21 -0
- package/dist/assets/statusline.mjs +353 -0
- package/dist/commands/balance.d.ts +1 -0
- package/dist/commands/balance.js +27 -0
- package/dist/commands/configure.js +14 -23
- package/dist/commands/doctor.js +7 -0
- package/dist/commands/helper-bot.js +0 -3
- package/dist/commands/helper-docs.js +1 -1
- package/dist/commands/remove.js +14 -0
- package/dist/commands/statusline.d.ts +3 -0
- package/dist/commands/statusline.js +46 -0
- package/dist/configure/claude.js +36 -17
- package/dist/configure/codex.js +6 -11
- package/dist/configure/continue.d.ts +5 -14
- package/dist/configure/continue.js +12 -17
- package/dist/configure/models.d.ts +4 -6
- package/dist/configure/models.js +7 -22
- package/dist/configure/statusline.d.ts +52 -0
- package/dist/configure/statusline.js +188 -0
- package/dist/constants.d.ts +0 -1
- package/dist/constants.js +0 -5
- package/dist/detect/common.js +3 -3
- package/dist/index.js +19 -1
- package/dist/types/client.d.ts +1 -1
- package/dist/types/client.js +0 -1
- package/dist/utils/api.d.ts +14 -2
- package/dist/utils/api.js +33 -49
- package/dist/utils/balance.d.ts +22 -0
- package/dist/utils/balance.js +103 -0
- package/dist/utils/keyStore.js +7 -0
- package/dist/utils/socials.d.ts +16 -0
- package/dist/utils/socials.js +60 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -76,6 +76,8 @@ scalemax login Store or replace your ScaleMax API key
|
|
|
76
76
|
scalemax logout Remove stored ScaleMax API key
|
|
77
77
|
scalemax doctor Run diagnostics
|
|
78
78
|
scalemax models List available ScaleMax models
|
|
79
|
+
scalemax balance Show remaining balance and how to renew (--json)
|
|
80
|
+
scalemax statusline Show your balance in Claude Code's status line (--install | --remove | --print)
|
|
79
81
|
scalemax helper-bot Open the ScaleMax-only support assistant
|
|
80
82
|
scalemax claude-tools Install bounded GitHub skill tools for Claude
|
|
81
83
|
scalemax fix-roo Fix Roo Code stuck at "API Request…" on recent VS Code
|
|
@@ -101,6 +103,25 @@ For CI or non-interactive checks, you may provide the key through the environmen
|
|
|
101
103
|
SCALEMAX_API_KEY=sm_live_xxx scalemax models
|
|
102
104
|
```
|
|
103
105
|
|
|
106
|
+
## Balance and the Claude Code status line
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
scalemax balance
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
prints the stored key's public prefix and label, its mode, what is left ("7.2M tokens" or "$3.41"), a bar with the percentage of your last top-up that remains, and a status (OK, low, critical, empty or unlimited). When the balance is low, critical or empty it also prints two ways to renew: `https://scalemax.pro/renew` and a WhatsApp link with a pre-filled message that names only the key's public prefix (for example `sm_live_ab12…`), never the key. `--json` prints the same facts as JSON. Servers that predate the balance status report only the remaining amount; the CLI then shows the amount without a percentage and calls it OK unless it is zero.
|
|
113
|
+
|
|
114
|
+
When setup configures Claude Code it also adds the ScaleMax balance to Claude Code's status line, **only if you have no status line of your own** (or the existing one is already ScaleMax's):
|
|
115
|
+
|
|
116
|
+
```text
|
|
117
|
+
ScaleMax · 7.2M tokens left (72%)
|
|
118
|
+
ScaleMax · ⚠ 1.6M left (16%) · renew: scalemax.pro/renew
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The line turns yellow when the balance is low and red when it is running out or empty. It is a small dependency-free script copied to `~/.scalemax/statusline.mjs` and run as `node "~/.scalemax/statusline.mjs"`; it reads the same stored key (or `SCALEMAX_API_KEY`), asks `/usage` at most once a minute (1.5 s timeout, cached privately in `~/.scalemax/balance-cache.json`), never prints the key, and falls back to the last known line or plain `ScaleMax` when offline. If you already have a status line, setup leaves it alone and prints a tip instead. `scalemax statusline --install` adds it anyway (your own status line is saved and restored by `--remove`), `scalemax statusline --remove` takes it out, and `scalemax statusline --print` prints the line once. `scalemax remove` removes it too.
|
|
122
|
+
|
|
123
|
+
`setup`, `update` and `doctor` print one warning line with the renew link when the balance is low, critical or empty. It never fails the command.
|
|
124
|
+
|
|
104
125
|
## ScaleMax Helper Bot
|
|
105
126
|
|
|
106
127
|
Start an interactive ScaleMax installation, configuration, authentication, and troubleshooting session:
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ScaleMax balance for Claude Code's status line.
|
|
3
|
+
//
|
|
4
|
+
// Claude Code runs this as `statusLine.command` on every refresh, so it must be
|
|
5
|
+
// fast, dependency-free (only node: built-ins — it runs from
|
|
6
|
+
// ~/.scalemax/statusline.mjs, outside any node_modules) and must never fail:
|
|
7
|
+
// any error prints the last known line or plain `ScaleMax`, and it always
|
|
8
|
+
// exits 0. The CLI imports the same module for `scalemax balance` and
|
|
9
|
+
// `scalemax statusline --print`, so the line and the numbers can never drift.
|
|
10
|
+
//
|
|
11
|
+
// The API key is only ever sent as a Bearer header to the stored ScaleMax base
|
|
12
|
+
// URL. It is never printed, cached or put in a URL.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
|
|
18
|
+
export const CACHE_TTL_MS = 60_000;
|
|
19
|
+
export const FETCH_TIMEOUT_MS = 1500;
|
|
20
|
+
export const STDIN_WAIT_MS = 50;
|
|
21
|
+
export const DEFAULT_BASE_URL = 'https://api.scalemax.pro/v1';
|
|
22
|
+
export const TOKEN_BASE_URL = 'https://api.scalemax.pro/token/v1';
|
|
23
|
+
export const DEFAULT_RENEW_URL = 'https://scalemax.pro/renew';
|
|
24
|
+
export const KEY_ENV = 'SCALEMAX_API_KEY';
|
|
25
|
+
const LEVELS = new Set(['ok', 'low', 'critical', 'empty', 'unlimited']);
|
|
26
|
+
const CACHE_VERSION = 1;
|
|
27
|
+
|
|
28
|
+
/** Same lookup order as the CLI's utils/paths.ts homeDir(). */
|
|
29
|
+
export function homeDir(env = process.env) {
|
|
30
|
+
return env.HOME || env.USERPROFILE || os.homedir();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Mirrors utils/paths.ts configRoot(): where `scalemax login` keeps config.json. */
|
|
34
|
+
export function configRoot(home, platform = process.platform, env = process.env) {
|
|
35
|
+
if (platform === 'win32') return env.APPDATA || path.join(home, 'AppData', 'Roaming');
|
|
36
|
+
if (platform === 'darwin') return path.join(home, 'Library', 'Application Support');
|
|
37
|
+
return env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function configPath(home, platform = process.platform, env = process.env) {
|
|
41
|
+
return path.join(configRoot(home, platform, env), 'scalemax', 'config.json');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function stateDir(home) { return path.join(home, '.scalemax'); }
|
|
45
|
+
export function balanceCachePath(home) { return path.join(stateDir(home), 'balance-cache.json'); }
|
|
46
|
+
|
|
47
|
+
function record(value) {
|
|
48
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function readJsonFile(file) {
|
|
52
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return undefined; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Same cleanup as utils/apiKey.ts sanitizeApiKey(). */
|
|
56
|
+
function sanitizeKey(value) {
|
|
57
|
+
return String(value ?? '').replace(/[-]/g, '').replace(/\s+/g, '').trim();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Server text (key label, prefix) is shown in a terminal: drop control characters so it cannot inject escapes. */
|
|
61
|
+
function safeText(value, max) {
|
|
62
|
+
if (typeof value !== 'string') return null;
|
|
63
|
+
const text = value.replace(/[\u0000-\u001F\u007F-\u009F]/g, '').trim().slice(0, max);
|
|
64
|
+
return text || null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The key and base URL exactly as the CLI resolves them: SCALEMAX_API_KEY
|
|
69
|
+
* wins over the stored key (utils/keyStore.ts), and the stored base URL is the
|
|
70
|
+
* surface `scalemax login` validated (credit `/v1` or token `/token/v1`).
|
|
71
|
+
*/
|
|
72
|
+
export function resolveCredentials({ home = homeDir(), platform = process.platform, env = process.env } = {}) {
|
|
73
|
+
const config = record(readJsonFile(configPath(home, platform, env)));
|
|
74
|
+
const apiKey = sanitizeKey(env[KEY_ENV] || config.apiKey);
|
|
75
|
+
const storedBase = typeof config.baseUrl === 'string' && /^https?:\/\//i.test(config.baseUrl.trim())
|
|
76
|
+
? config.baseUrl.trim().replace(/\/+$/, '')
|
|
77
|
+
: undefined;
|
|
78
|
+
return { apiKey: apiKey || undefined, baseUrl: storedBase };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** `${baseUrl}/usage`, the way utils/api.ts builds every request. */
|
|
82
|
+
export function usageUrl(baseUrl) {
|
|
83
|
+
return `${String(baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '')}/usage`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The server's public key prefix (12 characters today, e.g. `sm_live_ab12`).
|
|
88
|
+
* Anything longer or odd is dropped, never truncated: a cut-down secret is
|
|
89
|
+
* still part of a secret.
|
|
90
|
+
*/
|
|
91
|
+
function safePrefix(value) {
|
|
92
|
+
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,16}$/.test(value) ? value : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function finite(value) {
|
|
96
|
+
const number = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
|
|
97
|
+
return typeof number === 'number' && Number.isFinite(number) ? number : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function safeRenewUrl(value) {
|
|
101
|
+
if (typeof value !== 'string' || value.length > 200) return DEFAULT_RENEW_URL;
|
|
102
|
+
try {
|
|
103
|
+
const url = new URL(value);
|
|
104
|
+
const host = url.hostname.toLowerCase();
|
|
105
|
+
if (url.protocol !== 'https:' || url.username || url.password) return DEFAULT_RENEW_URL;
|
|
106
|
+
if (host !== 'scalemax.pro' && !host.endsWith('.scalemax.pro')) return DEFAULT_RENEW_URL;
|
|
107
|
+
return url.toString();
|
|
108
|
+
} catch {
|
|
109
|
+
return DEFAULT_RENEW_URL;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function usageMode(key, body) {
|
|
114
|
+
const mode = String(key.mode || '').trim().toLowerCase();
|
|
115
|
+
if (mode === 'token_budget' || mode === 'token') return 'token';
|
|
116
|
+
if (mode === 'credit') return 'credit';
|
|
117
|
+
if (mode === 'unlimited') return 'unlimited';
|
|
118
|
+
// Unknown or missing mode: infer from which balance the server filled in.
|
|
119
|
+
if (finite(record(body.tokens).remaining) !== null) return 'token';
|
|
120
|
+
if (finite(record(body.credits).remaining) !== null) return 'credit';
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Normalise a GET /v1/usage body into what the status line and `scalemax
|
|
126
|
+
* balance` show. Servers with `balance_status` decide the level and percent;
|
|
127
|
+
* older servers only give the remaining amount, so the level is computed here
|
|
128
|
+
* without a percent ('empty' at or below zero, otherwise 'ok'). Returns null
|
|
129
|
+
* when the body says nothing usable.
|
|
130
|
+
*/
|
|
131
|
+
export function balanceFromUsage(body) {
|
|
132
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return null;
|
|
133
|
+
const key = record(body.key);
|
|
134
|
+
const mode = usageMode(key, body);
|
|
135
|
+
const status = record(body.balance_status);
|
|
136
|
+
const unit = mode === 'token' ? 'tokens' : mode === 'credit' ? 'usd' : null;
|
|
137
|
+
const remaining = mode === 'token'
|
|
138
|
+
? finite(record(body.tokens).remaining)
|
|
139
|
+
: mode === 'credit'
|
|
140
|
+
? finite(record(body.credits).remaining)
|
|
141
|
+
: null;
|
|
142
|
+
const base = {
|
|
143
|
+
mode,
|
|
144
|
+
unit,
|
|
145
|
+
remaining,
|
|
146
|
+
prefix: safePrefix(key.prefix),
|
|
147
|
+
label: safeText(key.label, 80),
|
|
148
|
+
renewUrl: safeRenewUrl(status.renew_url),
|
|
149
|
+
};
|
|
150
|
+
if (LEVELS.has(status.level)) {
|
|
151
|
+
const percent = finite(status.percent_left);
|
|
152
|
+
return {
|
|
153
|
+
...base,
|
|
154
|
+
level: status.level,
|
|
155
|
+
percentLeft: status.level === 'unlimited' || percent === null ? null : Math.max(0, Math.min(100, Math.round(percent))),
|
|
156
|
+
source: 'server',
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
if (mode === 'unlimited') return { ...base, level: 'unlimited', percentLeft: null, source: 'fallback' };
|
|
160
|
+
if (remaining === null) return null;
|
|
161
|
+
return { ...base, level: remaining <= 0 ? 'empty' : 'ok', percentLeft: null, source: 'fallback' };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function trimDecimal(value) {
|
|
165
|
+
return value.toFixed(1).replace(/\.0$/, '');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 7_200_000 → "7.2M", 850_000 → "850K", 12 → "12". */
|
|
169
|
+
export function humanTokens(value) {
|
|
170
|
+
const n = Math.max(0, Number(value) || 0);
|
|
171
|
+
const units = [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'K']];
|
|
172
|
+
for (const [size, suffix] of units) {
|
|
173
|
+
if (n >= size) {
|
|
174
|
+
const scaled = n / size;
|
|
175
|
+
return `${scaled < 10 ? trimDecimal(scaled) : String(Math.floor(scaled))}${suffix}`;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return String(Math.floor(n));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function humanUsd(value) {
|
|
182
|
+
const n = Math.max(0, Number(value) || 0);
|
|
183
|
+
return `$${n.toFixed(2)}`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** "7.2M tokens" / "$3.41"; `short` drops the word "tokens" (the warning lines are tight). */
|
|
187
|
+
export function formatAmount(balance, { short = false } = {}) {
|
|
188
|
+
if (!balance || balance.remaining === null || balance.remaining === undefined) return null;
|
|
189
|
+
if (balance.unit === 'usd') return humanUsd(balance.remaining);
|
|
190
|
+
if (balance.unit === 'tokens') return short ? humanTokens(balance.remaining) : `${humanTokens(balance.remaining)} tokens`;
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** "scalemax.pro/renew": the scheme is noise in a one-line status bar. */
|
|
195
|
+
export function shortUrl(url) {
|
|
196
|
+
return String(url || DEFAULT_RENEW_URL).replace(/^https:\/\//, '').replace(/\/$/, '');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const ANSI = { yellow: '\u001b[33m', red: '\u001b[31m', reset: '\u001b[0m' };
|
|
200
|
+
|
|
201
|
+
/** One status-line string for a normalised balance (null = nothing known yet). */
|
|
202
|
+
export function formatStatusLine(balance, { color = true } = {}) {
|
|
203
|
+
if (!balance || !balance.level) return 'ScaleMax';
|
|
204
|
+
if (balance.level === 'unlimited') return 'ScaleMax · unlimited plan';
|
|
205
|
+
const percent = balance.percentLeft === null || balance.percentLeft === undefined ? '' : ` (${balance.percentLeft}%)`;
|
|
206
|
+
const paint = (tone, text) => (color ? `${ANSI[tone]}${text}${ANSI.reset}` : text);
|
|
207
|
+
const renew = `renew: ${shortUrl(balance.renewUrl)}`;
|
|
208
|
+
if (balance.level === 'ok') {
|
|
209
|
+
const amount = formatAmount(balance);
|
|
210
|
+
return amount ? `ScaleMax · ${amount} left${percent}` : 'ScaleMax';
|
|
211
|
+
}
|
|
212
|
+
if (balance.level === 'empty') return paint('red', `ScaleMax · ⚠ out of balance · ${renew}`);
|
|
213
|
+
const amount = formatAmount(balance, { short: true });
|
|
214
|
+
const left = amount ? `${amount} left${percent}` : `balance ${balance.level === 'low' ? 'low' : 'very low'}${percent}`;
|
|
215
|
+
if (balance.level === 'low') return paint('yellow', `ScaleMax · ⚠ ${left} · ${renew}`);
|
|
216
|
+
return paint('red', `ScaleMax · ⚠ ${left} · running out · ${renew}`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function readBalanceCache(file) {
|
|
220
|
+
const cache = record(readJsonFile(file));
|
|
221
|
+
if (cache.version !== CACHE_VERSION || typeof cache.checkedAt !== 'number') return null;
|
|
222
|
+
return { checkedAt: cache.checkedAt, balance: cache.balance && typeof cache.balance === 'object' ? cache.balance : null };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Fresh while younger than the TTL; a clock that moved backwards counts as stale. */
|
|
226
|
+
export function isCacheFresh(cache, now, ttlMs = CACHE_TTL_MS) {
|
|
227
|
+
return Boolean(cache) && now >= cache.checkedAt && now - cache.checkedAt < ttlMs;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Private (0600) and atomic, so two Claude sessions refreshing at once never read half a file. */
|
|
231
|
+
export function writeBalanceCache(file, balance, now) {
|
|
232
|
+
try {
|
|
233
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
234
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
235
|
+
fs.writeFileSync(tmp, `${JSON.stringify({ version: CACHE_VERSION, checkedAt: now, balance: balance || null })}\n`, { mode: 0o600 });
|
|
236
|
+
fs.renameSync(tmp, file);
|
|
237
|
+
try { fs.chmodSync(file, 0o600); } catch { /* Windows has no POSIX modes */ }
|
|
238
|
+
} catch { /* a read-only home must not break the status line */ }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function fetchUsageBody(url, apiKey, fetchImpl, timeoutMs) {
|
|
242
|
+
const res = await fetchImpl(url, {
|
|
243
|
+
headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json', 'Cache-Control': 'no-cache', 'User-Agent': 'ScaleMax-Statusline' },
|
|
244
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
245
|
+
});
|
|
246
|
+
if (!res.ok) {
|
|
247
|
+
try { await res.body?.cancel(); } catch { /* ignore */ }
|
|
248
|
+
return { status: res.status };
|
|
249
|
+
}
|
|
250
|
+
return { status: res.status, body: await res.json() };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The balance to show, from the cache when fresh, otherwise from /usage.
|
|
255
|
+
* Never throws. A failed refresh keeps the last good balance and still
|
|
256
|
+
* stamps the cache, so a ScaleMax outage costs one 1.5 s request a minute
|
|
257
|
+
* rather than one per status-line refresh.
|
|
258
|
+
*/
|
|
259
|
+
export async function loadBalance({
|
|
260
|
+
home = homeDir(),
|
|
261
|
+
platform = process.platform,
|
|
262
|
+
env = process.env,
|
|
263
|
+
now = Date.now(),
|
|
264
|
+
fetchImpl = globalThis.fetch,
|
|
265
|
+
timeoutMs = FETCH_TIMEOUT_MS,
|
|
266
|
+
ttlMs = CACHE_TTL_MS,
|
|
267
|
+
useCache = true,
|
|
268
|
+
} = {}) {
|
|
269
|
+
const cacheFile = balanceCachePath(home);
|
|
270
|
+
const cache = readBalanceCache(cacheFile);
|
|
271
|
+
if (useCache && isCacheFresh(cache, now, ttlMs)) return cache.balance;
|
|
272
|
+
const { apiKey, baseUrl } = resolveCredentials({ home, platform, env });
|
|
273
|
+
if (!apiKey || typeof fetchImpl !== 'function') return cache?.balance ?? null;
|
|
274
|
+
try {
|
|
275
|
+
let result = await fetchUsageBody(usageUrl(baseUrl), apiKey, fetchImpl, timeoutMs);
|
|
276
|
+
// No stored surface (key only in the environment): a credit-surface 401
|
|
277
|
+
// can be a token key, exactly as utils/api.ts validateApiKey() retries.
|
|
278
|
+
if (!baseUrl && result.status === 401) result = await fetchUsageBody(usageUrl(TOKEN_BASE_URL), apiKey, fetchImpl, timeoutMs);
|
|
279
|
+
if (result.body !== undefined) {
|
|
280
|
+
const balance = balanceFromUsage(result.body);
|
|
281
|
+
writeBalanceCache(cacheFile, balance, now);
|
|
282
|
+
return balance;
|
|
283
|
+
}
|
|
284
|
+
// A rejected key has no balance to show; anything else keeps the last one.
|
|
285
|
+
const keep = result.status === 401 || result.status === 403 ? null : cache?.balance ?? null;
|
|
286
|
+
writeBalanceCache(cacheFile, keep, now);
|
|
287
|
+
return keep;
|
|
288
|
+
} catch {
|
|
289
|
+
const keep = cache?.balance ?? null;
|
|
290
|
+
writeBalanceCache(cacheFile, keep, now);
|
|
291
|
+
return keep;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The full status line. Never throws; NO_COLOR turns the colours off. */
|
|
296
|
+
export async function renderStatusLine(options = {}) {
|
|
297
|
+
const env = options.env || process.env;
|
|
298
|
+
const color = options.color ?? !env.NO_COLOR;
|
|
299
|
+
try {
|
|
300
|
+
return formatStatusLine(await loadBalance({ ...options, env }), { color });
|
|
301
|
+
} catch {
|
|
302
|
+
return 'ScaleMax';
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Claude Code pipes a JSON session description on stdin. It is not needed, but
|
|
308
|
+
* an unread pipe must not block exit, and a terminal (manual run) has no EOF:
|
|
309
|
+
* read for at most STDIN_WAIT_MS, then let go of stdin.
|
|
310
|
+
*/
|
|
311
|
+
function releaseStdin(ms = STDIN_WAIT_MS) {
|
|
312
|
+
return new Promise(resolve => {
|
|
313
|
+
const stdin = process.stdin;
|
|
314
|
+
if (!stdin || stdin.isTTY) { resolve(); return; }
|
|
315
|
+
let timer;
|
|
316
|
+
const done = () => {
|
|
317
|
+
clearTimeout(timer);
|
|
318
|
+
try { stdin.removeAllListeners('data'); stdin.pause(); stdin.destroy(); } catch { /* ignore */ }
|
|
319
|
+
resolve();
|
|
320
|
+
};
|
|
321
|
+
timer = setTimeout(done, ms);
|
|
322
|
+
try {
|
|
323
|
+
stdin.on('data', () => undefined);
|
|
324
|
+
stdin.once('end', done);
|
|
325
|
+
stdin.once('error', done);
|
|
326
|
+
stdin.resume();
|
|
327
|
+
} catch {
|
|
328
|
+
done();
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function main() {
|
|
334
|
+
let line = 'ScaleMax';
|
|
335
|
+
try {
|
|
336
|
+
const [, rendered] = await Promise.all([releaseStdin(), renderStatusLine()]);
|
|
337
|
+
line = rendered;
|
|
338
|
+
} catch { /* keep the plain fallback */ }
|
|
339
|
+
process.stdout.write(`${line}\n`);
|
|
340
|
+
process.exitCode = 0;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function invokedDirectly() {
|
|
344
|
+
try {
|
|
345
|
+
const entry = process.argv[1];
|
|
346
|
+
if (!entry) return false;
|
|
347
|
+
return fs.realpathSync(entry) === fs.realpathSync(fileURLToPath(import.meta.url));
|
|
348
|
+
} catch {
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (invokedDirectly()) void main();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function balanceCommand(args?: string[], home?: string): Promise<void>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { fetchUsage } from '../utils/api.js';
|
|
2
|
+
import { balanceJson, formatBalanceReport, needsRenewal, whatsappRenewUrl } from '../utils/balance.js';
|
|
3
|
+
import { loadApiKey, loadBaseUrl } from '../utils/keyStore.js';
|
|
4
|
+
import { homeDir } from '../utils/paths.js';
|
|
5
|
+
import { loadWhatsAppNumber } from '../utils/socials.js';
|
|
6
|
+
import { balanceCachePath, balanceFromUsage, writeBalanceCache } from '../assets/statusline.mjs';
|
|
7
|
+
export async function balanceCommand(args = [], home = homeDir()) {
|
|
8
|
+
const json = args.includes('--json');
|
|
9
|
+
const apiKey = await loadApiKey(home);
|
|
10
|
+
if (!apiKey)
|
|
11
|
+
throw new Error('No ScaleMax API key found. Run `scalemax login` first.');
|
|
12
|
+
const result = await fetchUsage(apiKey, await loadBaseUrl(home));
|
|
13
|
+
if (!result.ok)
|
|
14
|
+
throw new Error(result.error || 'Could not read your ScaleMax balance.');
|
|
15
|
+
const balance = balanceFromUsage(result.body);
|
|
16
|
+
if (!balance)
|
|
17
|
+
throw new Error('ScaleMax returned a usage response without a balance.');
|
|
18
|
+
// Refresh the status line's cache too, so both show the same figure now.
|
|
19
|
+
writeBalanceCache(balanceCachePath(home), balance, Date.now());
|
|
20
|
+
const whatsappUrl = needsRenewal(balance) ? whatsappRenewUrl(await loadWhatsAppNumber(home), balance) : undefined;
|
|
21
|
+
if (json) {
|
|
22
|
+
console.log(JSON.stringify(balanceJson(balance, whatsappUrl), null, 2));
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
for (const line of formatBalanceReport(balance, { whatsappUrl }))
|
|
26
|
+
console.log(line);
|
|
27
|
+
}
|
|
@@ -4,11 +4,12 @@ import ora from 'ora';
|
|
|
4
4
|
import { clients } from '../clients.js';
|
|
5
5
|
import { SCALEMAX_BASE_URL } from '../constants.js';
|
|
6
6
|
import { loadApiKey } from '../utils/keyStore.js';
|
|
7
|
-
import { validateApiKey, isAnthropicModel, isChatModel, isModelRouteAvailable,
|
|
7
|
+
import { validateApiKey, isAnthropicModel, isChatModel, isModelRouteAvailable, probeWorkingModels } from '../utils/api.js';
|
|
8
8
|
import { saveModelCheck } from '../utils/modelCheck.js';
|
|
9
9
|
import { homeDir } from '../utils/paths.js';
|
|
10
|
-
import { CLAUDE_CODE_NEEDS_CLAUDE_MESSAGE, CODEX_NEEDS_GPT_MESSAGE, codexModelIds, defaultModelIdsFor, isExactChatCompletionsModelId
|
|
10
|
+
import { CLAUDE_CODE_NEEDS_CLAUDE_MESSAGE, CODEX_NEEDS_GPT_MESSAGE, codexModelIds, defaultModelIdsFor, isExactChatCompletionsModelId } from '../configure/models.js';
|
|
11
11
|
import { isContinueEligibleModelId } from '../configure/continue.js';
|
|
12
|
+
import { balanceWarningLine } from '../utils/balance.js';
|
|
12
13
|
export async function detectAll(home = homeDir()) {
|
|
13
14
|
const ctx = { home, platform: process.platform, env: process.env };
|
|
14
15
|
return Promise.all(clients.map(c => c.detect(ctx)));
|
|
@@ -42,23 +43,9 @@ async function maybeLaunchCodex(chosen, successful, baseUrl = SCALEMAX_BASE_URL)
|
|
|
42
43
|
}
|
|
43
44
|
console.log('\nIf Codex asks for authentication,\nit should already be configured to use ScaleMax.\n\nIf you still see the official login screen,\nthe configuration is incomplete or Codex rejected the generated auth/config files.\n');
|
|
44
45
|
}
|
|
45
|
-
/**
|
|
46
|
-
* Whether Claude Code specifically can reach a model, which is a narrower
|
|
47
|
-
* question than isAnthropicModel(). Auto is not made by Anthropic -- it is
|
|
48
|
-
* served by ScaleMax's own Kiro-backed stock, and modelPresentation.ts on the
|
|
49
|
-
* gateway is deliberate about never attributing it to a maker that did not
|
|
50
|
-
* build it. But Auto DOES speak the Anthropic Messages PROTOCOL: the gateway
|
|
51
|
-
* bridges every Auto request through /v1/messages (live-verified, 2026-08-08 --
|
|
52
|
-
* a real `claude -p` session against a ScaleMax-generated config answered
|
|
53
|
-
* correctly). Before this, an auto-api key's catalog (one model, `auto`,
|
|
54
|
-
* provider `scalemax`) failed isAnthropicModel entirely, so Claude Code was
|
|
55
|
-
* DETECTED but silently never configured -- no error, no explanation, just
|
|
56
|
-
* absent from the list of clients the installer touched. `auto` is therefore
|
|
57
|
-
* checked by id, not folded into isAnthropicModel itself, which stays reserved
|
|
58
|
-
* for "did Anthropic make this."
|
|
59
|
-
*/
|
|
46
|
+
/** Whether Claude Code specifically can reach a model. */
|
|
60
47
|
function reachableByClaudeCode(model) {
|
|
61
|
-
return isAnthropicModel(model)
|
|
48
|
+
return isAnthropicModel(model);
|
|
62
49
|
}
|
|
63
50
|
export function clientAllowedForModels(clientId, models) {
|
|
64
51
|
// Image, video, embedding and voice rows share the catalog; an image model
|
|
@@ -75,11 +62,11 @@ export function clientAllowedForModels(clientId, models) {
|
|
|
75
62
|
return models.some(model => isContinueEligibleModelId(model.id));
|
|
76
63
|
if (clientId === 'claude')
|
|
77
64
|
return models.some(reachableByClaudeCode);
|
|
78
|
-
// Codex runs on GPT models only
|
|
79
|
-
//
|
|
80
|
-
//
|
|
65
|
+
// Codex runs on GPT models only. A Claude id, the `claude-sonnet-4-6` alias,
|
|
66
|
+
// DeepSeek or a free preview model failed every Codex request it was
|
|
67
|
+
// configured with.
|
|
81
68
|
if (clientId === 'codex')
|
|
82
|
-
return codexModelIds({ models }).length > 0
|
|
69
|
+
return codexModelIds({ models }).length > 0;
|
|
83
70
|
if (clientId === 'hermes' && models.every(model => isExactChatCompletionsModelId(model.id)))
|
|
84
71
|
return models.some(model => model.capabilities?.tools === true);
|
|
85
72
|
// Roo is an agent, not a text-only chat surface. Its task loop depends on
|
|
@@ -130,7 +117,6 @@ function scopeHint(scope) {
|
|
|
130
117
|
'deepseek-v4-flash': 'DeepSeek V4 Flash only',
|
|
131
118
|
'glm-5.2': 'GLM 5.2 only',
|
|
132
119
|
'deepseek-v4-pro': 'DeepSeek V4 Pro only',
|
|
133
|
-
'auto-api': 'Auto only',
|
|
134
120
|
voice: 'Voice only',
|
|
135
121
|
};
|
|
136
122
|
return labels[scope];
|
|
@@ -268,6 +254,11 @@ export async function configureCommand(opts = {}) {
|
|
|
268
254
|
failures.push(`${client.name}: ${message}`);
|
|
269
255
|
}
|
|
270
256
|
}
|
|
257
|
+
// A key about to run dry is worth one line at the end of setup. It reads the
|
|
258
|
+
// /usage body validation already fetched: no extra request, never fatal.
|
|
259
|
+
const balanceWarning = balanceWarningLine(keyInfo.usage);
|
|
260
|
+
if (balanceWarning)
|
|
261
|
+
console.log(`\n${balanceWarning}`);
|
|
271
262
|
if (opts.promptLaunch !== false && !opts.all && process.stdin.isTTY)
|
|
272
263
|
await maybeLaunchCodex(chosen, successful, selectedBaseUrl);
|
|
273
264
|
if (failures.length)
|
package/dist/commands/doctor.js
CHANGED
|
@@ -9,6 +9,7 @@ import { homeDir } from '../utils/paths.js';
|
|
|
9
9
|
import { clients } from '../clients.js';
|
|
10
10
|
import { SCALEMAX_BASE_URL } from '../constants.js';
|
|
11
11
|
import { repairRooRipgrep, rooInstallLabel } from '../repair/roo-ripgrep.js';
|
|
12
|
+
import { balanceWarningLine } from '../utils/balance.js';
|
|
12
13
|
/**
|
|
13
14
|
* Roo Code 3.54 cannot find newer VS Code's relocated ripgrep, so every task
|
|
14
15
|
* hangs at "API Request…". Read-only: reports installs that still need
|
|
@@ -36,6 +37,7 @@ export async function doctorCommand(home = homeDir()) {
|
|
|
36
37
|
// Setup passes the key's scope to every client (Roo writes its profiles by
|
|
37
38
|
// scope); without it doctor expected a different Roo profile set.
|
|
38
39
|
let providerScope;
|
|
40
|
+
let usage;
|
|
39
41
|
// The models setup's live check skipped, so each client is checked against
|
|
40
42
|
// the same defaults setup wrote (configure/models.ts picks them).
|
|
41
43
|
const avoidModelIds = key ? await loadModelCheck(home, key) : [];
|
|
@@ -49,6 +51,7 @@ export async function doctorCommand(home = homeDir()) {
|
|
|
49
51
|
models = res.models;
|
|
50
52
|
baseUrl = res.baseUrl || SCALEMAX_BASE_URL;
|
|
51
53
|
providerScope = res.key?.provider_scope;
|
|
54
|
+
usage = res.usage;
|
|
52
55
|
if (res.ok && models.length) {
|
|
53
56
|
s.succeed(`API reachable, key valid, ${models.length} models loaded`);
|
|
54
57
|
console.log(`${chalk.green('✓')} Usage and key metadata accessible through the authenticated API`);
|
|
@@ -104,6 +107,10 @@ export async function doctorCommand(home = homeDir()) {
|
|
|
104
107
|
}
|
|
105
108
|
for (const line of await rooRipgrepDoctorLines(home))
|
|
106
109
|
console.log(line);
|
|
110
|
+
// Advice, not a failed check: a low balance is not a broken setup.
|
|
111
|
+
const balanceWarning = balanceWarningLine(usage);
|
|
112
|
+
if (balanceWarning)
|
|
113
|
+
console.log(balanceWarning);
|
|
107
114
|
console.log('');
|
|
108
115
|
if (failures === 0)
|
|
109
116
|
console.log(chalk.green('Everything looks good!'));
|
|
@@ -815,8 +815,6 @@ function requestedProviderScope(question, target) {
|
|
|
815
815
|
return 'deepseek-v4-pro';
|
|
816
816
|
if (/\bdeepseek[-\s]+v4[-\s]+flash\b/i.test(question))
|
|
817
817
|
return 'deepseek-v4-flash';
|
|
818
|
-
if (/\bauto(?:[-\s]+api)?\b/i.test(question))
|
|
819
|
-
return 'auto-api';
|
|
820
818
|
if (/\bdeepseek\b/i.test(question))
|
|
821
819
|
return 'deepseek';
|
|
822
820
|
if (/\bgemini\b/i.test(question))
|
|
@@ -867,7 +865,6 @@ function actionModels(connection, requestedScope) {
|
|
|
867
865
|
'deepseek-v4-flash': 'deepseek-v4-flash',
|
|
868
866
|
'glm-5.2': 'glm-5.2',
|
|
869
867
|
'deepseek-v4-pro': 'deepseek-v4-pro',
|
|
870
|
-
'auto-api': 'auto',
|
|
871
868
|
};
|
|
872
869
|
const exactModel = exactModelByScope[requestedScope];
|
|
873
870
|
if (exactModel)
|
|
@@ -15,7 +15,7 @@ export const HELPER_DOC_SECTIONS = [
|
|
|
15
15
|
id: 'provider-scope',
|
|
16
16
|
title: 'Provider scope and visible models',
|
|
17
17
|
keywords: ['provider', 'scope', 'openai', 'claude', 'anthropic', 'gemini', 'grok', 'qwen', 'deepseek', 'mimo', 'local', 'reseller', 'both', 'models', 'fable'],
|
|
18
|
-
content: `ScaleMax keys may grant an OpenAI, Claude, Gemini, Grok, Qwen, DeepSeek, MiMo, Local Models, combined OpenAI + Claude, exact-model,
|
|
18
|
+
content: `ScaleMax keys may grant an OpenAI, Claude, Gemini, Grok, Qwen, DeepSeek, MiMo, Local Models, combined OpenAI + Claude, exact-model, or reseller allowlist entitlement. The authenticated /models response is authoritative because it already includes per-key reseller grants and any extra families assigned to a credit key. The CLI must never add models absent from that response or strip models that it returned. Fable 5 is a Claude-family frontend model through ScaleMax. DeepSeek V4 Flash, GLM 5.2, and DeepSeek V4 Pro use /v1/chat/completions rather than Responses; tool support remains route-dependent, so trust capabilities.tools from the authenticated catalog.`
|
|
19
19
|
},
|
|
20
20
|
{
|
|
21
21
|
id: 'roo-code',
|
package/dist/commands/remove.js
CHANGED
|
@@ -3,6 +3,7 @@ import ora from 'ora';
|
|
|
3
3
|
import { clients } from '../clients.js';
|
|
4
4
|
import { loadApiKey, loadBaseUrl } from '../utils/keyStore.js';
|
|
5
5
|
import { homeDir } from '../utils/paths.js';
|
|
6
|
+
import { removeStatusLine } from '../configure/statusline.js';
|
|
6
7
|
export async function removeCommand(home = homeDir()) {
|
|
7
8
|
const [apiKey, baseUrl] = await Promise.all([loadApiKey(home), loadBaseUrl(home)]);
|
|
8
9
|
const failures = [];
|
|
@@ -18,6 +19,19 @@ export async function removeCommand(home = homeDir()) {
|
|
|
18
19
|
failures.push(`${client.name}: ${message}`);
|
|
19
20
|
}
|
|
20
21
|
}
|
|
22
|
+
// After the clients: Claude Code's own remove has already put back a saved
|
|
23
|
+
// status line, so this only clears what is left (a standalone install, the
|
|
24
|
+
// script and its cache) and never touches a status line that is not ours.
|
|
25
|
+
const statusSpinner = ora('Removing the ScaleMax status line').start();
|
|
26
|
+
try {
|
|
27
|
+
const res = await removeStatusLine(home, process.platform);
|
|
28
|
+
statusSpinner.succeed(`Status line: ${res.message}`);
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
32
|
+
statusSpinner.fail(`Status line remove failed: ${message}`);
|
|
33
|
+
failures.push(`Status line: ${message}`);
|
|
34
|
+
}
|
|
21
35
|
if (failures.length)
|
|
22
36
|
throw new Error(`${failures.length} client removal(s) failed:\n${failures.map(f => `- ${f}`).join('\n')}`);
|
|
23
37
|
console.log(chalk.green('✓ ScaleMax-managed client configurations removed or restored; unmanaged files were left unchanged.'));
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare const STATUSLINE_OPTIONS: readonly ["--install", "--remove", "--print"];
|
|
2
|
+
/** `scalemax statusline [--install|--remove|--print]`; no flag reports the current state. */
|
|
3
|
+
export declare function statuslineCommand(args?: string[], home?: string, platform?: NodeJS.Platform): Promise<void>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import fs from 'fs-extra';
|
|
3
|
+
import JSON5 from 'json5';
|
|
4
|
+
import { homeDir } from '../utils/paths.js';
|
|
5
|
+
import { claudeSettingsPath, installStatusLine, isScaleMaxStatusLine, removeStatusLine, statusLineCommand } from '../configure/statusline.js';
|
|
6
|
+
import { renderStatusLine } from '../assets/statusline.mjs';
|
|
7
|
+
export const STATUSLINE_OPTIONS = ['--install', '--remove', '--print'];
|
|
8
|
+
/** `scalemax statusline [--install|--remove|--print]`; no flag reports the current state. */
|
|
9
|
+
export async function statuslineCommand(args = [], home = homeDir(), platform = process.platform) {
|
|
10
|
+
const chosen = STATUSLINE_OPTIONS.filter(option => args.includes(option));
|
|
11
|
+
if (chosen.length > 1)
|
|
12
|
+
throw new Error('Use one of --install, --remove or --print.');
|
|
13
|
+
if (chosen[0] === '--print') {
|
|
14
|
+
// Same code path Claude Code runs; prints the line exactly as it shows.
|
|
15
|
+
console.log(await renderStatusLine({ home, platform, env: process.env }));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (chosen[0] === '--install') {
|
|
19
|
+
const result = await installStatusLine(home, platform);
|
|
20
|
+
console.log(chalk.green(`✓ ${result.message}`));
|
|
21
|
+
if (result.changed)
|
|
22
|
+
console.log(chalk.dim(' Restart Claude Code (or start a new session) to see it.'));
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (chosen[0] === '--remove') {
|
|
26
|
+
const result = await removeStatusLine(home, platform);
|
|
27
|
+
console.log(chalk.green(`✓ ${result.message}`));
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
let settings;
|
|
31
|
+
try {
|
|
32
|
+
settings = JSON5.parse(await fs.readFile(claudeSettingsPath(home, platform), 'utf8'));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
settings = undefined;
|
|
36
|
+
}
|
|
37
|
+
const current = settings?.statusLine;
|
|
38
|
+
if (isScaleMaxStatusLine(current))
|
|
39
|
+
console.log(`${chalk.green('✓')} The ScaleMax balance is in your Claude Code status line.`);
|
|
40
|
+
else if (current !== undefined)
|
|
41
|
+
console.log(`${chalk.dim('•')} Claude Code uses its own status line. Replace it with the ScaleMax balance: ${chalk.bold('scalemax statusline --install')}`);
|
|
42
|
+
else
|
|
43
|
+
console.log(`${chalk.dim('•')} No Claude Code status line. Add the ScaleMax balance: ${chalk.bold('scalemax statusline --install')}`);
|
|
44
|
+
console.log(chalk.dim(` Command: ${statusLineCommand(home, platform)}`));
|
|
45
|
+
console.log(chalk.dim(' Options: --install, --remove, --print'));
|
|
46
|
+
}
|