sprag-cli 3.92.0 → 3.94.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +26 -3
- package/package.json +1 -1
- package/src/commands/oauth-budget.js +38 -0
- package/src/commands/saved.js +14 -2
- package/src/config.js +5 -0
- package/src/formatters/statusline.js +1 -1
- package/src/monthly-reset-offer.js +36 -15
- package/src/oauth-budget.js +272 -0
- package/src/stdin-payload.js +12 -2
- package/src/window-labels.js +5 -0
package/bin/cli.js
CHANGED
|
@@ -116,7 +116,7 @@ function columnsFromArgs({ useEnv = true } = {}) {
|
|
|
116
116
|
const KNOWN_SUBCOMMANDS = new Set([
|
|
117
117
|
'last', 'brief', 'history', 'handoff', 'install', 'uninstall', 'mode', 'korean', 'cohesion',
|
|
118
118
|
'doc2md', 'delegate', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
|
|
119
|
-
'seed', 'litellm-budget', 'profile-map', 'feedback', 'saved', 'cowork', 'team', 'presets',
|
|
119
|
+
'seed', 'litellm-budget', 'oauth-budget', 'profile-map', 'feedback', 'saved', 'cowork', 'team', 'presets',
|
|
120
120
|
]);
|
|
121
121
|
|
|
122
122
|
// Flags each entry path reads, collected from the hasFlag/getArg/numArg calls in
|
|
@@ -217,8 +217,9 @@ Usage:
|
|
|
217
217
|
sprag doc2md on|off|<file> convert documents to Markdown before the model reads them
|
|
218
218
|
sprag delegate on|off|status add bounds and context to Task/Agent delegation prompts
|
|
219
219
|
sprag compact-window audit or pin autoCompactWindow for 1M sessions
|
|
220
|
-
sprag saved [reset|undo] show, reset or restore the saved-money counters (--agent codex for Codex)
|
|
220
|
+
sprag saved [reset|undo|keep] show, reset or restore the saved-money counters (--agent codex for Codex)
|
|
221
221
|
sprag litellm-budget LiteLLM gateway key budget and spend
|
|
222
|
+
sprag oauth-budget claude.ai usage-credit budget (Enterprise)
|
|
222
223
|
sprag update-check is a newer version out?
|
|
223
224
|
sprag brief --hook internal: the UserPromptSubmit hook entry point
|
|
224
225
|
sprag brief --hook-tool internal: the PostToolUse hook entry point (delegation follow-up)
|
|
@@ -427,7 +428,7 @@ async function main() {
|
|
|
427
428
|
}
|
|
428
429
|
|
|
429
430
|
// Subcommand: saved — stopwatch reset for the lifetime "saved" counters.
|
|
430
|
-
// sprag saved | saved reset [routing|doc2md|all] | saved undo
|
|
431
|
+
// sprag saved | saved reset [routing|doc2md|all] | saved undo | saved keep
|
|
431
432
|
if (args[0] === 'saved') {
|
|
432
433
|
return (await import('../src/commands/saved.js')).run({ args, hasFlag });
|
|
433
434
|
}
|
|
@@ -479,6 +480,11 @@ async function main() {
|
|
|
479
480
|
if (args[0] === 'litellm-budget') {
|
|
480
481
|
return (await import('../src/commands/litellm-budget.js')).run({ hasFlag });
|
|
481
482
|
}
|
|
483
|
+
// Subcommand: oauth-budget, claude.ai usage-credit 예산 조회.
|
|
484
|
+
// sprag oauth-budget [--json | --refresh]
|
|
485
|
+
if (args[0] === 'oauth-budget') {
|
|
486
|
+
return (await import('../src/commands/oauth-budget.js')).run({ hasFlag });
|
|
487
|
+
}
|
|
482
488
|
|
|
483
489
|
// Subcommand: profile-map · LiteLLM 게이트웨이의 프로파일 ID → 모델 별칭
|
|
484
490
|
// 매핑을 보여 주거나(GET /model/info) 갱신합니다.
|
|
@@ -802,6 +808,23 @@ async function main() {
|
|
|
802
808
|
debug('litellm-budget:window', e);
|
|
803
809
|
}
|
|
804
810
|
}
|
|
811
|
+
// claude.ai(Enterprise) 로그인 사용자: rate_limits 도 LiteLLM 창도 없을 때만
|
|
812
|
+
// /api/oauth/usage 캐시로 예산 게이지를 그린다(기본으로 켜져 있음). 창이 이미 있는
|
|
813
|
+
// Pro/Max 는 여기서 네트워크는 물론 캐시도 건드리지 않는다.
|
|
814
|
+
if (isStatusline && (!caps || !Array.isArray(caps.windows) || caps.windows.length === 0)) {
|
|
815
|
+
try {
|
|
816
|
+
const { maybeSpawnOauthBudgetCheck, oauthBudgetWindow } = await import('../src/oauth-budget.js');
|
|
817
|
+
maybeSpawnOauthBudgetCheck();
|
|
818
|
+
const ow = oauthBudgetWindow();
|
|
819
|
+
if (ow) {
|
|
820
|
+
caps = { windows: [ow] };
|
|
821
|
+
const { persistSnapshot } = await import('../src/caps-cache.js');
|
|
822
|
+
persistSnapshot({ caps, model });
|
|
823
|
+
}
|
|
824
|
+
} catch (e) {
|
|
825
|
+
debug('oauth-budget:window', e);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
805
828
|
if (!isStatusline && (!caps || !model)) {
|
|
806
829
|
try {
|
|
807
830
|
const { loadRecentSnapshot } = await import('../src/caps-cache.js');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.94.0",
|
|
4
4
|
"description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subcommand: oauth-budget, claude.ai usage-credit 예산(Enterprise) 조회.
|
|
3
|
+
* sprag oauth-budget # 캐시된 예산을 게이지와 금액으로 출력
|
|
4
|
+
* sprag oauth-budget --json # 캐시 원본 JSON 출력
|
|
5
|
+
* sprag oauth-budget --refresh # 지금 조회 (detached 자식이 사용, 끈 상태와 무관)
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { debug } from '../debug.js';
|
|
9
|
+
|
|
10
|
+
export async function run({ hasFlag }) {
|
|
11
|
+
const { oauthBudgetEnabled, readOauthState, refreshOauthBudgetState, formatOauthBudgetReport } =
|
|
12
|
+
await import('../oauth-budget.js');
|
|
13
|
+
const quiet = hasFlag('--quiet');
|
|
14
|
+
if (hasFlag('--refresh')) {
|
|
15
|
+
try {
|
|
16
|
+
const next = await refreshOauthBudgetState(process.env, fetch);
|
|
17
|
+
if (!quiet) console.log(JSON.stringify(next, null, 2));
|
|
18
|
+
} catch (e) {
|
|
19
|
+
debug('oauth-budget:refresh', e);
|
|
20
|
+
if (!quiet) console.error(`oauth-budget refresh failed: ${e.message}`);
|
|
21
|
+
process.exitCode = 1;
|
|
22
|
+
}
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (!oauthBudgetEnabled()) {
|
|
26
|
+
console.log('꺼져 있습니다. `sprag mode oauth-budget` 으로 다시 켜십시오 (SPRAG_OAUTH_BUDGET=0 이면 그 변수를 지우십시오).');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const state = readOauthState();
|
|
30
|
+
if (hasFlag('--json')) {
|
|
31
|
+
console.log(JSON.stringify(state, null, 2));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const { resolveLabelMode } = await import('../statusline-mode.js');
|
|
35
|
+
const { statuslineDefaults } = await import('../config.js');
|
|
36
|
+
const { mode: labelMode } = resolveLabelMode({ hasFlag, cfg: statuslineDefaults() });
|
|
37
|
+
for (const line of formatOauthBudgetReport(state, new Date(), labelMode)) console.log(line);
|
|
38
|
+
}
|
package/src/commands/saved.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* sprag saved # totals since the last reset
|
|
5
5
|
* sprag saved reset [routing|doc2md|all] # start counting from now
|
|
6
6
|
* sprag saved undo # put the previous counters back
|
|
7
|
+
* sprag saved keep # decline this month's reset offer
|
|
7
8
|
* (add --agent codex for the Codex counters: codex-routing, codex-docs)
|
|
8
9
|
*
|
|
9
10
|
* Nothing is deleted. A reset only records a timestamp, and the totals count
|
|
@@ -194,6 +195,17 @@ export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan
|
|
|
194
195
|
return;
|
|
195
196
|
}
|
|
196
197
|
|
|
198
|
+
// The "no" answer to the session-start reset offer (src/monthly-reset-offer.js).
|
|
199
|
+
// Without it the offer comes back at every fresh session this month.
|
|
200
|
+
if (sub === 'keep') {
|
|
201
|
+
const { declineMonthlyReset } = await import('../monthly-reset-offer.js');
|
|
202
|
+
const month = declineMonthlyReset({ dir });
|
|
203
|
+
console.log(ko
|
|
204
|
+
? `${month} 에는 초기화 안내를 더 띄우지 않습니다. 카운터는 그대로 이어서 셉니다.`
|
|
205
|
+
: `No more reset offers for ${month}. The counters keep running.`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
197
209
|
if (sub === 'undo') {
|
|
198
210
|
const undone = undoReset({ dir });
|
|
199
211
|
if (!undone) {
|
|
@@ -214,7 +226,7 @@ export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan
|
|
|
214
226
|
}
|
|
215
227
|
|
|
216
228
|
console.error(ko
|
|
217
|
-
? `알 수 없는 하위 명령입니다: ${sub}. 사용법은 sprag saved [reset|undo] 입니다.`
|
|
218
|
-
: `Unknown subcommand: ${sub}. Usage: sprag saved [reset|undo].`);
|
|
229
|
+
? `알 수 없는 하위 명령입니다: ${sub}. 사용법은 sprag saved [reset|undo|keep] 입니다.`
|
|
230
|
+
: `Unknown subcommand: ${sub}. Usage: sprag saved [reset|undo|keep].`);
|
|
219
231
|
process.exit(1);
|
|
220
232
|
}
|
package/src/config.js
CHANGED
|
@@ -59,6 +59,10 @@ const KEYWORDS = {
|
|
|
59
59
|
// Model-share bar and letters beside the routing chip; on unless switched off.
|
|
60
60
|
share: { key: 'modelShare', value: true },
|
|
61
61
|
'no-share': { key: 'modelShare', value: false },
|
|
62
|
+
// Enterprise(claude.ai 로그인) 사용자의 usage-credit 예산 게이지. 기본으로 켜져 있고
|
|
63
|
+
// rate_limits 가 오는 Pro 와 Max 는 조회하지 않는다. src/oauth-budget.js 참고.
|
|
64
|
+
'oauth-budget': { key: 'oauthBudget', value: true },
|
|
65
|
+
'no-oauth-budget': { key: 'oauthBudget', value: false },
|
|
62
66
|
};
|
|
63
67
|
|
|
64
68
|
// Output language for `last`/`history`/advice. Stored at top level
|
|
@@ -199,6 +203,7 @@ export function statuslineDefaults() {
|
|
|
199
203
|
timer: s.timer !== false,
|
|
200
204
|
color: s.color !== false,
|
|
201
205
|
modelShare: s.modelShare !== false,
|
|
206
|
+
oauthBudget: s.oauthBudget !== false,
|
|
202
207
|
windowHours,
|
|
203
208
|
windowLabel: formatWindow(windowHours),
|
|
204
209
|
// 'auto' | '5m' | '1h'. Auto lets the measured split decide and falls back
|
|
@@ -1388,7 +1388,7 @@ function resolveSegmentOrder(segments, caps, updateAvailable) {
|
|
|
1388
1388
|
// number, so the estimate steps aside when the measured value is present.
|
|
1389
1389
|
// `--segments month` still asks for it explicitly and still gets it.
|
|
1390
1390
|
const hasGatewayBudget = !!(caps && Array.isArray(caps.windows)
|
|
1391
|
-
&& caps.windows.some((w) => w && w.key === 'litellm_budget'));
|
|
1391
|
+
&& caps.windows.some((w) => w && (w.key === 'litellm_budget' || w.key === 'spend_limit')));
|
|
1392
1392
|
if (hasGatewayBudget) defaultOrder = defaultOrder.filter((n) => n !== 'month');
|
|
1393
1393
|
|
|
1394
1394
|
// A caller-supplied list sets the filter AND the order. Warning chips keep
|
|
@@ -6,8 +6,12 @@
|
|
|
6
6
|
* anything about the current month.
|
|
7
7
|
*
|
|
8
8
|
* The asking happens at session start for the same reason as the upgrade and
|
|
9
|
-
* seed offers: a statusline cannot open a dialog. The
|
|
10
|
-
*
|
|
9
|
+
* seed offers: a statusline cannot open a dialog. The offer repeats at every
|
|
10
|
+
* fresh session until the user answers: yes runs `sprag saved reset all`, whose
|
|
11
|
+
* mark silences it; no runs `sprag saved keep`, which records the month as
|
|
12
|
+
* declined. Printing alone records nothing, because a session where nobody
|
|
13
|
+
* read the offer must not count as an answer (2026-11-01: a batch job got
|
|
14
|
+
* November's only ask under the old once-per-month rule).
|
|
11
15
|
*/
|
|
12
16
|
|
|
13
17
|
import { readFileSync } from 'node:fs';
|
|
@@ -35,11 +39,16 @@ function readState(file) {
|
|
|
35
39
|
/**
|
|
36
40
|
* Whether a SessionStart with this `source` may carry the offer: a fresh
|
|
37
41
|
* session only. The hook also fires on resume, clear and compact, and an offer
|
|
38
|
-
* right after an auto-compact would interrupt work in progress
|
|
39
|
-
*
|
|
40
|
-
*
|
|
42
|
+
* right after an auto-compact would interrupt work in progress. A payload
|
|
43
|
+
* without `source` (older Claude Code, or a manual run) counts as a fresh start.
|
|
44
|
+
*
|
|
45
|
+
* SDK sessions (`claude -p`, Agent SDK; CLAUDE_CODE_ENTRYPOINT `sdk-*`) are
|
|
46
|
+
* skipped too. They are mostly unattended batch jobs, so nobody would answer,
|
|
47
|
+
* and an offer that repeats until answered would ride every run and could leak
|
|
48
|
+
* a question into output a script parses.
|
|
41
49
|
*/
|
|
42
|
-
export function offersOnSessionSource(source) {
|
|
50
|
+
export function offersOnSessionSource(source, entrypoint = process.env.CLAUDE_CODE_ENTRYPOINT) {
|
|
51
|
+
if (typeof entrypoint === 'string' && entrypoint.startsWith('sdk')) return false;
|
|
43
52
|
return !source || source === 'startup';
|
|
44
53
|
}
|
|
45
54
|
|
|
@@ -58,13 +67,13 @@ export function monthlyResetOffer({ dir = userDataDir(), now = Date.now(), lang
|
|
|
58
67
|
const monthStart = new Date(today.getFullYear(), today.getMonth(), 1).getTime();
|
|
59
68
|
const monthKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
|
|
60
69
|
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
const state = readState(
|
|
64
|
-
if (state && state.month === monthKey) return null;
|
|
70
|
+
// Declined this month: stay quiet until the next one. A state file from
|
|
71
|
+
// v3.91 to v3.93 holds only `offeredAt`, which was never an answer.
|
|
72
|
+
const state = readState(monthlyResetStatePath(dir));
|
|
73
|
+
if (state && state.month === monthKey && Number.isFinite(state.declinedAt)) return null;
|
|
65
74
|
|
|
66
|
-
// Reset since the 1st: nothing to recommend
|
|
67
|
-
//
|
|
75
|
+
// Reset since the 1st: nothing to recommend. A later `undo` that brings the
|
|
76
|
+
// old mark back makes the offer due again.
|
|
68
77
|
const marks = readResetMarks(dir);
|
|
69
78
|
if (Number.isFinite(marks.routing) && marks.routing >= monthStart) return null;
|
|
70
79
|
|
|
@@ -90,20 +99,32 @@ export function monthlyResetOffer({ dir = userDataDir(), now = Date.now(), lang
|
|
|
90
99
|
? [
|
|
91
100
|
`✇ [sprag monthly-reset] ${today.getMonth() + 1}월 1일 이후 절감 집계를 초기화한 적이 없습니다. 지금 보이는 값은 ${sinceText} 누적입니다: 라우팅 절감 ${formatMoney(routingOk)}, Doc2md 절감 ${formatMoney(docOk)}.`,
|
|
92
101
|
'이번 달 기준으로 새로 보려면 초기화를 권장합니다. 초기화하면 라우팅 절감과 Doc2md 절감, Model used 비율이 지금부터 다시 집계됩니다. 기록은 지워지지 않고 `sprag saved undo` 로 되돌릴 수 있습니다.',
|
|
93
|
-
'사용자에게 위 내용을 알리고 초기화할지 물어보십시오.
|
|
102
|
+
'사용자에게 위 내용을 알리고 초기화할지 물어보십시오. 승낙하면 첫째 명령을, 거절하면 둘째 명령을 실행하십시오. 둘 중 하나를 실행하기 전에는 새 세션을 열 때마다 이 안내가 다시 나옵니다. 거절하면 이번 달에는 더 묻지 않습니다.',
|
|
94
103
|
' sprag saved reset all',
|
|
104
|
+
' sprag saved keep',
|
|
95
105
|
]
|
|
96
106
|
: [
|
|
97
107
|
`✇ [sprag monthly-reset] The saved counters have not been reset since ${MONTH_NAMES[today.getMonth()]} 1. The figures shown are cumulative ${sinceText}: routing saved ${formatMoney(routingOk)}, Doc2md saved ${formatMoney(docOk)}.`,
|
|
98
108
|
'A reset is recommended to see this month on its own. It restarts routing savings, Doc2md savings and the Model used share from now. Nothing is deleted, and `sprag saved undo` puts it back.',
|
|
99
|
-
'Tell the user this and ask whether to reset.
|
|
109
|
+
'Tell the user this and ask whether to reset. If they agree, run the first command; if they decline, run the second. Until one of them runs, this offer comes back at every new session. A decline keeps it quiet for the rest of the month.',
|
|
100
110
|
' sprag saved reset all',
|
|
111
|
+
' sprag saved keep',
|
|
101
112
|
];
|
|
102
113
|
|
|
103
|
-
writeStateFile(file, `${JSON.stringify({ version: 1, month: monthKey, offeredAt: now }, null, 2)}\n`);
|
|
104
114
|
return block.join('\n');
|
|
105
115
|
} catch (e) {
|
|
106
116
|
debug('monthly-reset-offer', e);
|
|
107
117
|
return null;
|
|
108
118
|
}
|
|
109
119
|
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Record the user's "no" for the current calendar month (`sprag saved keep`).
|
|
123
|
+
* @returns {string} the month key, e.g. '2026-11'
|
|
124
|
+
*/
|
|
125
|
+
export function declineMonthlyReset({ dir = userDataDir(), now = Date.now() } = {}) {
|
|
126
|
+
const today = new Date(now);
|
|
127
|
+
const monthKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
|
|
128
|
+
writeStateFile(monthlyResetStatePath(dir), `${JSON.stringify({ version: 2, month: monthKey, declinedAt: now }, null, 2)}\n`);
|
|
129
|
+
return monthKey;
|
|
130
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* oauth-budget: claude.ai 로 로그인한 Enterprise 사용자의 usage-credit 예산을 조회합니다.
|
|
3
|
+
*
|
|
4
|
+
* 이 사용자들은 Claude Code 상태줄 입력에 rate_limits 를 받지 못합니다. 기본으로 켜져
|
|
5
|
+
* 있으며 `GET https://api.anthropic.com/api/oauth/usage` 응답의 extra_usage 로
|
|
6
|
+
* 예산 게이지(`💳 budget ▰▱ 54% $271/$500`)를 그립니다. 공식 문서에 없는
|
|
7
|
+
* 엔드포인트라서 응답 모양이 다르면 아무것도 그리지 않습니다.
|
|
8
|
+
*
|
|
9
|
+
* 구조는 litellm-budget.js 와 같습니다: 렌더 경로는 캐시 파일만 읽고, 캐시가
|
|
10
|
+
* 오래되면 detached 자식을 띄워 다음 렌더를 위해 갱신합니다.
|
|
11
|
+
*
|
|
12
|
+
* 토큰은 메모리에서만 씁니다. 캐시 파일, debug 로그, argv, 에러 메시지에 토큰이나
|
|
13
|
+
* 그 해시를 넣지 않습니다. 토큰 갱신은 Claude Code 가 하므로 여기서는 읽기만 합니다.
|
|
14
|
+
* 토큰 읽기는 키체인 대화상자를 띄울 수 있어 자식 프로세스에서만 합니다.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
18
|
+
import { execFileSync } from 'node:child_process';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { homedir } from 'node:os';
|
|
21
|
+
import { userDataDir } from './paths.js';
|
|
22
|
+
import { gaugeBar, formatMoney } from './formatters/statusline.js';
|
|
23
|
+
import { labelForKey } from './window-labels.js';
|
|
24
|
+
import { gatewayBase } from './gateway-auth.js';
|
|
25
|
+
import { loadConfig } from './config.js';
|
|
26
|
+
import { envVar } from './env.js';
|
|
27
|
+
import { spawnDetachedCli } from './cli-entry.js';
|
|
28
|
+
import { debug } from './debug.js';
|
|
29
|
+
|
|
30
|
+
const CHECK_INTERVAL_MS = 5 * 60 * 1000;
|
|
31
|
+
const FETCH_TIMEOUT_MS = 5000;
|
|
32
|
+
// 키체인 허용 대화상자가 뜨는 환경에서 5분마다 창이 쌓이지 않도록, 토큰을 못 읽으면 쉽니다.
|
|
33
|
+
const NO_TOKEN_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
34
|
+
// Pro 와 Max 는 상태줄 입력에 rate_limits 가 오므로 이 경로가 필요 없습니다. 세션 첫
|
|
35
|
+
// 응답 전에는 rate_limits 가 비어 이 경로가 불리는데, 그때마다 조회하지 않도록 하루 쉽니다.
|
|
36
|
+
const PLAN_BACKOFF_MS = 24 * 60 * 60 * 1000;
|
|
37
|
+
const PLANS_WITH_RATE_LIMITS = new Set(['pro', 'max']);
|
|
38
|
+
const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage';
|
|
39
|
+
|
|
40
|
+
export function oauthStatePath() {
|
|
41
|
+
return join(userDataDir(), 'oauth-budget.json');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function readOauthState() {
|
|
45
|
+
try {
|
|
46
|
+
const s = JSON.parse(readFileSync(oauthStatePath(), 'utf8'));
|
|
47
|
+
return s && typeof s === 'object' ? s : {};
|
|
48
|
+
} catch {
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function writeOauthState(next) {
|
|
54
|
+
const dir = userDataDir();
|
|
55
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
56
|
+
writeFileSync(oauthStatePath(), JSON.stringify(next, null, 2) + '\n');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 기본으로 켜져 있습니다. `sprag mode no-oauth-budget` 이나 SPRAG_OAUTH_BUDGET=0 으로 끕니다. */
|
|
60
|
+
export function oauthBudgetEnabled(cfg = loadConfig(), env = process.env) {
|
|
61
|
+
if (envVar('OAUTH_BUDGET', env) === '0') return false;
|
|
62
|
+
return cfg?.statusline?.oauthBudget !== false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 게이트웨이, API 키, 클라우드 공급자 사용자는 OAuth 로그인 사용자가 아닙니다. */
|
|
66
|
+
export function oauthEligible(env = process.env) {
|
|
67
|
+
if (gatewayBase(env)) return false;
|
|
68
|
+
if (env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN) return false;
|
|
69
|
+
for (const k of ['CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY']) {
|
|
70
|
+
if (env[k] && env[k] !== '0' && env[k] !== 'false') return false;
|
|
71
|
+
}
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function credentialFromJson(raw) {
|
|
76
|
+
let parsed;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
const o = parsed?.claudeAiOauth;
|
|
83
|
+
const token = o?.accessToken;
|
|
84
|
+
if (typeof token !== 'string' || !token) return null;
|
|
85
|
+
const exp = Number(o.expiresAt);
|
|
86
|
+
// 만료된 토큰은 쓰지 않습니다. 갱신은 Claude Code 몫입니다.
|
|
87
|
+
if (Number.isFinite(exp) && exp > 0 && exp <= Date.now()) return null;
|
|
88
|
+
const plan = typeof o.subscriptionType === 'string' ? o.subscriptionType : null;
|
|
89
|
+
return { token, subscriptionType: plan };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* OAuth 액세스 토큰을 읽습니다. 자식 프로세스에서만 부르십시오.
|
|
94
|
+
* 순서: ① CLAUDE_CODE_OAUTH_TOKEN ② macOS 키체인 ③ .credentials.json.
|
|
95
|
+
* 읽지 못하거나 만료됐으면 null.
|
|
96
|
+
*/
|
|
97
|
+
export function readOauthToken(env = process.env, deps = {}) {
|
|
98
|
+
return readOauthCredential(env, deps)?.token ?? null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** readOauthToken 과 같은 순서로 읽고 요금제(subscriptionType)도 함께 돌려줍니다. */
|
|
102
|
+
export function readOauthCredential(env = process.env, deps = {}) {
|
|
103
|
+
const exec = deps.execFileSync || execFileSync;
|
|
104
|
+
const read = deps.readFileSync || readFileSync;
|
|
105
|
+
const platform = deps.platform || process.platform;
|
|
106
|
+
if (env.CLAUDE_CODE_OAUTH_TOKEN) return { token: env.CLAUDE_CODE_OAUTH_TOKEN, subscriptionType: null };
|
|
107
|
+
try {
|
|
108
|
+
if (platform === 'darwin') {
|
|
109
|
+
const out = exec('security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], {
|
|
110
|
+
timeout: 3000,
|
|
111
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
112
|
+
});
|
|
113
|
+
return credentialFromJson(String(out));
|
|
114
|
+
}
|
|
115
|
+
const dir = env.CLAUDE_CONFIG_DIR || join(deps.homedir || homedir(), '.claude');
|
|
116
|
+
return credentialFromJson(String(read(join(dir, '.credentials.json'), 'utf8')));
|
|
117
|
+
} catch (e) {
|
|
118
|
+
// 오류 객체에 명령 출력이 실릴 수 있어 종류만 남깁니다.
|
|
119
|
+
debug('oauth-budget:token', new Error(`token read failed (${e?.code || 'error'})`));
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* /api/oauth/usage 응답에서 창 재료를 뽑습니다 (달러 단위).
|
|
126
|
+
* 예산이 꺼져 있거나 모양이 다르면 null.
|
|
127
|
+
*
|
|
128
|
+
* @returns {{spend:number, maxBudget:number, usedPct:number}|null}
|
|
129
|
+
*/
|
|
130
|
+
export function parseOauthUsage(body) {
|
|
131
|
+
const x = body?.extra_usage;
|
|
132
|
+
if (!x || typeof x !== 'object' || x.is_enabled !== true) return null;
|
|
133
|
+
const limit = Number(x.monthly_limit);
|
|
134
|
+
if (x.monthly_limit === null || x.monthly_limit === undefined || !Number.isFinite(limit) || limit <= 0) return null;
|
|
135
|
+
if (x.currency && x.currency !== 'USD') return null;
|
|
136
|
+
const places = Number.isFinite(Number(x.decimal_places)) && x.decimal_places !== null ? Number(x.decimal_places) : 2;
|
|
137
|
+
const div = 10 ** places;
|
|
138
|
+
const usedRaw = Number(x.used_credits);
|
|
139
|
+
const used = x.used_credits !== null && x.used_credits !== undefined && Number.isFinite(usedRaw) ? usedRaw : 0;
|
|
140
|
+
const spend = used / div;
|
|
141
|
+
const maxBudget = limit / div;
|
|
142
|
+
let usedPct;
|
|
143
|
+
if (x.spend_limit_reached === true) usedPct = 100;
|
|
144
|
+
else if (x.utilization !== null && x.utilization !== undefined && Number.isFinite(Number(x.utilization))) usedPct = Number(x.utilization);
|
|
145
|
+
else usedPct = (used / limit) * 100;
|
|
146
|
+
usedPct = Math.min(100, Math.max(0, usedPct));
|
|
147
|
+
return { spend, maxBudget, usedPct };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 렌더 경로가 쓰는 읽기 전용 접근자. 캐시만 읽습니다.
|
|
152
|
+
* 리셋 시각은 응답에 없으므로 resetsAt 은 null 입니다.
|
|
153
|
+
*/
|
|
154
|
+
export function oauthBudgetWindow(deps = {}) {
|
|
155
|
+
if (!oauthBudgetEnabled(deps.cfg, deps.env)) return null;
|
|
156
|
+
// 나중에 게이트웨이나 API 키로 바꾼 사용자에게 옛 OAuth 캐시를 그리지 않습니다.
|
|
157
|
+
if (!oauthEligible(deps.env)) return null;
|
|
158
|
+
const s = readOauthState();
|
|
159
|
+
const max = Number(s.maxBudget);
|
|
160
|
+
const spend = Number(s.spend);
|
|
161
|
+
const pct = Number(s.usedPct);
|
|
162
|
+
if (!Number.isFinite(max) || max <= 0 || !Number.isFinite(spend) || !Number.isFinite(pct)) return null;
|
|
163
|
+
return { key: 'spend_limit', usedPct: pct, resetsAt: null, spend, maxBudget: max, source: 'oauth' };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 캐시가 오래됐으면 detached 자식으로 갱신을 예약합니다. 즉시 반환. */
|
|
167
|
+
export function maybeSpawnOauthBudgetCheck(env = process.env, deps = {}) {
|
|
168
|
+
if (!oauthBudgetEnabled(deps.cfg, env)) return false;
|
|
169
|
+
if (!oauthEligible(env)) return false;
|
|
170
|
+
const now = deps.now ?? Date.now();
|
|
171
|
+
const s = readOauthState();
|
|
172
|
+
if (now - (Number(s.checkedAt) || 0) < CHECK_INTERVAL_MS) return false;
|
|
173
|
+
if (Number(s.backoffUntil) > now) return false;
|
|
174
|
+
// 오프라인이나 오류 때 렌더마다 자식을 다시 띄우지 않도록 시도 시각을 먼저 기록합니다.
|
|
175
|
+
try {
|
|
176
|
+
writeOauthState({ ...s, checkedAt: now });
|
|
177
|
+
} catch (e) {
|
|
178
|
+
debug('oauth-budget:stamp', e);
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
return (deps.spawnDetachedCli || spawnDetachedCli)(['oauth-budget', '--refresh', '--quiet']) !== false;
|
|
183
|
+
} catch (e) {
|
|
184
|
+
debug('oauth-budget:spawn', e);
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 실제로 조회하고 캐시를 갱신합니다. detached 자식과 `oauth-budget --refresh`
|
|
191
|
+
* 만 부릅니다. 캐시에는 토큰을 쓰지 않습니다.
|
|
192
|
+
*/
|
|
193
|
+
export async function refreshOauthBudgetState(env = process.env, fetchImpl = fetch, deps = {}) {
|
|
194
|
+
const now = deps.now ?? Date.now();
|
|
195
|
+
const cred = readOauthCredential(env, deps);
|
|
196
|
+
if (!cred) {
|
|
197
|
+
const next = { checkedAt: now, backoffUntil: now + NO_TOKEN_BACKOFF_MS, error: 'no-token' };
|
|
198
|
+
writeOauthState(next);
|
|
199
|
+
return next;
|
|
200
|
+
}
|
|
201
|
+
if (PLANS_WITH_RATE_LIMITS.has(cred.subscriptionType)) {
|
|
202
|
+
const next = { checkedAt: now, backoffUntil: now + PLAN_BACKOFF_MS, skipped: 'plan-has-rate-limits' };
|
|
203
|
+
writeOauthState(next);
|
|
204
|
+
return next;
|
|
205
|
+
}
|
|
206
|
+
const { token } = cred;
|
|
207
|
+
const controller = new AbortController();
|
|
208
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
209
|
+
try {
|
|
210
|
+
let res;
|
|
211
|
+
try {
|
|
212
|
+
res = await fetchImpl(USAGE_URL, {
|
|
213
|
+
signal: controller.signal,
|
|
214
|
+
headers: {
|
|
215
|
+
authorization: `Bearer ${token}`,
|
|
216
|
+
'anthropic-beta': 'oauth-2025-04-20',
|
|
217
|
+
accept: 'application/json',
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
} catch (e) {
|
|
221
|
+
// 메시지에 URL 외의 것이 실릴 일은 없지만, 종류만 남기는 규칙을 지킵니다.
|
|
222
|
+
debug('oauth-budget:fetch', new Error(`fetch failed (${e?.name || 'error'})`));
|
|
223
|
+
throw new Error(`fetch failed (${e?.name || 'error'})`);
|
|
224
|
+
}
|
|
225
|
+
if (!res.ok) {
|
|
226
|
+
debug('oauth-budget:http', new Error(`usage responded ${res.status}`));
|
|
227
|
+
const next = { checkedAt: now, error: `http-${res.status}` };
|
|
228
|
+
writeOauthState(next);
|
|
229
|
+
return next;
|
|
230
|
+
}
|
|
231
|
+
const parsed = parseOauthUsage(await res.json());
|
|
232
|
+
const next = parsed ? { checkedAt: now, ...parsed } : { checkedAt: now, enabled: false };
|
|
233
|
+
writeOauthState(next);
|
|
234
|
+
return next;
|
|
235
|
+
} finally {
|
|
236
|
+
clearTimeout(timer);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* `sprag oauth-budget` 이 출력하는 사람용 보고서입니다. 모드 처리는
|
|
242
|
+
* litellm-budget 의 formatBudgetReport 와 같습니다.
|
|
243
|
+
*
|
|
244
|
+
* @returns {string[]} 출력할 줄들
|
|
245
|
+
*/
|
|
246
|
+
export function formatOauthBudgetReport(state, now = new Date(), mode = 'icon') {
|
|
247
|
+
const max = Number(state?.maxBudget);
|
|
248
|
+
const spend = Number(state?.spend);
|
|
249
|
+
if (!Number.isFinite(max) || max <= 0) {
|
|
250
|
+
if (state?.error) return [`조회에 실패했습니다 (${state.error}). 잠시 뒤 \`sprag oauth-budget --refresh\` 로 다시 확인하십시오.`];
|
|
251
|
+
return ['usage-credit 예산이 켜져 있지 않거나 캐시가 비어 있습니다.'];
|
|
252
|
+
}
|
|
253
|
+
const used = Number.isFinite(spend) ? Math.max(0, spend) : 0;
|
|
254
|
+
const left = Math.max(0, max - used);
|
|
255
|
+
const pct = Number.isFinite(Number(state?.usedPct)) ? Math.min(100, Math.max(0, Number(state.usedPct))) : Math.min(100, (used / max) * 100);
|
|
256
|
+
const win = labelForKey('spend_limit');
|
|
257
|
+
const bare = mode === 'text';
|
|
258
|
+
const tickMode = mode === 'icon' ? 'icon' : 'narrow';
|
|
259
|
+
const icon = bare ? '' : (mode === 'narrow' ? (win.narrowIcon || win.icon) : win.icon);
|
|
260
|
+
const head = bare ? 'budget' : `${icon} budget`;
|
|
261
|
+
const lines = [
|
|
262
|
+
`${head} ${gaugeBar(pct, tickMode)} ${Math.round(pct)}% ${formatMoney(used)}/${formatMoney(max)}`,
|
|
263
|
+
` 사용 ${formatMoney(used)}, 잔여 ${formatMoney(left)} (${(100 - pct).toFixed(1)}%)`,
|
|
264
|
+
' 출처 claude.ai usage credits',
|
|
265
|
+
];
|
|
266
|
+
const checkedAt = Number(state?.checkedAt);
|
|
267
|
+
if (Number.isFinite(checkedAt) && checkedAt > 0) {
|
|
268
|
+
const ageMin = Math.max(0, Math.round((now.getTime() - checkedAt) / 60000));
|
|
269
|
+
lines.push(` 조회 ${ageMin}분 전`);
|
|
270
|
+
}
|
|
271
|
+
return lines;
|
|
272
|
+
}
|
package/src/stdin-payload.js
CHANGED
|
@@ -111,11 +111,21 @@ export function extractCaps(stdinJson) {
|
|
|
111
111
|
const rawReset = typeof value.resets_at === 'string' && value.resets_at.trim() !== ''
|
|
112
112
|
? Number(value.resets_at)
|
|
113
113
|
: value.resets_at;
|
|
114
|
-
|
|
114
|
+
const win = {
|
|
115
115
|
key,
|
|
116
116
|
usedPct,
|
|
117
117
|
resetsAt: typeof rawReset === 'number' && Number.isFinite(rawReset) && rawReset > 0 ? rawReset : null,
|
|
118
|
-
}
|
|
118
|
+
};
|
|
119
|
+
// A Claude apps gateway with a spend limit sends `spend_limit` with dollar
|
|
120
|
+
// amounts (Claude Code 2.1.284+). Carry them under the names the LiteLLM
|
|
121
|
+
// budget window uses so the gauge renders `$used/$limit` the same way.
|
|
122
|
+
const used = Number(value.used_usd);
|
|
123
|
+
const limit = Number(value.limit_usd);
|
|
124
|
+
if (value.used_usd != null && value.limit_usd != null && Number.isFinite(used) && Number.isFinite(limit) && limit > 0) {
|
|
125
|
+
win.spend = used;
|
|
126
|
+
win.maxBudget = limit;
|
|
127
|
+
}
|
|
128
|
+
windows.push(win);
|
|
119
129
|
}
|
|
120
130
|
return windows.length ? { windows } : null;
|
|
121
131
|
}
|
package/src/window-labels.js
CHANGED
|
@@ -36,6 +36,11 @@ const KNOWN = {
|
|
|
36
36
|
// Budgets reset on a billing cycle, so "in 3d 4h" beats a bare weekday.
|
|
37
37
|
resetStyle: 'countdown',
|
|
38
38
|
},
|
|
39
|
+
// Claude apps 게이트웨이가 거는 지출 한도. LiteLLM 예산과 같은 뜻이라 같은 모양으로 그린다.
|
|
40
|
+
spend_limit: {
|
|
41
|
+
short: 'BUDGET', long: 'Spend limit', icon: '💳', narrowIcon: '◫', usageLabel: 'budget',
|
|
42
|
+
resetStyle: 'countdown',
|
|
43
|
+
},
|
|
39
44
|
};
|
|
40
45
|
|
|
41
46
|
function deriveShort(key) {
|