sprag-cli 3.91.0 → 3.93.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 +24 -1
- package/docs/TEAM.ko.md +1 -1
- package/docs/TEAM.md +1 -1
- package/package.json +1 -1
- package/src/commands/oauth-budget.js +38 -0
- package/src/config.js +5 -0
- package/src/formatters/statusline.js +1 -1
- 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
|
|
@@ -219,6 +219,7 @@ Usage:
|
|
|
219
219
|
sprag compact-window audit or pin autoCompactWindow for 1M sessions
|
|
220
220
|
sprag saved [reset|undo] 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)
|
|
@@ -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/docs/TEAM.ko.md
CHANGED
|
@@ -146,7 +146,7 @@ Sprag 운영자는 ops 콘솔(sprag.io/ops/)에서 조직마다 최소 Sprag 버
|
|
|
146
146
|
|
|
147
147
|
## 대시보드
|
|
148
148
|
|
|
149
|
-
https://sprag.io/team/ 에서 등록된 오너나 어드민이 이메일 코드로 로그인하고, 팀을 만들고, 초대 토큰을 받습니다. 새 조직은 support@sprag.io 로 문의합니다. 오너, 어드민, 초대 대기 중 어느 쪽에도 없는 이메일은 코드를 보내기 전에 거절하며, 조직 오너에게 추가를 요청하라고 안내합니다. 초대받은 사람은 처음 로그인할 때 자동으로 오너나 어드민이 됩니다. 여기서 구성원별 지출과 절감액을 보고, 규칙 탭에서 조직 룰과 팀 룰을 관리하고, 구성원을 내보낼 수 있습니다. 조직 패널에는 요금제, 한도 대비 사용 좌석, 어드민, 전체 팀이 보입니다. 슈퍼유저는 sprag.io/ops/ 에서 모든 조직을
|
|
149
|
+
https://sprag.io/team/ 에서 등록된 오너나 어드민이 이메일 코드로 로그인하고, 팀을 만들고, 초대 토큰을 받습니다. 새 조직은 support@sprag.io 로 문의합니다. 오너, 어드민, 초대 대기 중 어느 쪽에도 없는 이메일은 코드를 보내기 전에 거절하며, 조직 오너에게 추가를 요청하라고 안내합니다. 초대받은 사람은 처음 로그인할 때 자동으로 오너나 어드민이 됩니다. 여기서 구성원별 지출과 절감액을 보고, 규칙 탭에서 조직 룰과 팀 룰을 관리하고, 구성원을 내보낼 수 있습니다. 조직 패널에는 요금제, 한도 대비 사용 좌석, 어드민, 전체 팀이 보입니다. 슈퍼유저는 sprag.io/ops/ 에서 모든 조직을 보고, 조직의 개요 탭에서 어느 조직에든 팀을 만들 수 있습니다. 팀을 만들면 그 팀의 초대 토큰이 화면에 나옵니다. 오너와 어드민과 슈퍼유저는 팀을 삭제할 수 있습니다. 팀 화면에서 초대와 등록을 다루는 탭에 있는 '팀 삭제' 버튼을 쓰거나 /ops/ 조직 개요 탭의 팀 행에서 삭제 버튼을 누릅니다. 일시정지 멤버를 포함해 활동 멤버가 남아 있으면 거절하므로 먼저 멤버를 모두 제거해야 합니다. 팀을 삭제하면 과거 멤버의 사용 기록과 이전 활동 기록도 함께 지워지고 되돌릴 수 없습니다. 활동 로그에는 기계마다 '삭제됨' 항목이 하나씩 남습니다.
|
|
150
150
|
|
|
151
151
|
대시보드 맨 위의 기간 선택(7일, 30일, 90일, 이번 달, 지난 달, 직접 선택)이 멤버 표, 사용량 차트, 프롬프트 사용량 탭의 기간을 정합니다. 기본값은 최근 30일이고, 내 컴퓨터의 달력 날짜를 쓰며 종료일도 포함합니다. 최대 365일까지 고를 수 있습니다. 고른 기간은 주소(`?from=2026-10-01&to=2026-10-18`)에 남으므로 새로고침하거나 링크를 공유해도 같은 기간이 보입니다. sprag.io/ops/ 슈퍼유저 콘솔에도 같은 선택이 있어 조직 표, 조직 머리말, 조직의 프롬프트 사용량에 적용됩니다.
|
|
152
152
|
|
package/docs/TEAM.md
CHANGED
|
@@ -147,7 +147,7 @@ If the upgrade fails, for example because the required version is not published
|
|
|
147
147
|
|
|
148
148
|
## The dashboard
|
|
149
149
|
|
|
150
|
-
https://sprag.io/team/ is where a registered owner or admin signs in with an email code, creates a team and gets the invite token. A new organization starts by writing to support@sprag.io. An email that is not an owner, an admin or a pending invite is refused before any code is sent, with a message to ask the organization's owner to add it. Invited people become owner or admin automatically on their first sign-in. From there they see per-member spend and savings, manage organization and team rules on the Rules tab, and remove members. The organization panel shows the plan, seats used against the limit, admins and every team. The superuser sees every organization at sprag.io/ops
|
|
150
|
+
https://sprag.io/team/ is where a registered owner or admin signs in with an email code, creates a team and gets the invite token. A new organization starts by writing to support@sprag.io. An email that is not an owner, an admin or a pending invite is refused before any code is sent, with a message to ask the organization's owner to add it. Invited people become owner or admin automatically on their first sign-in. From there they see per-member spend and savings, manage organization and team rules on the Rules tab, and remove members. The organization panel shows the plan, seats used against the limit, admins and every team. The superuser sees every organization at sprag.io/ops/ and can create a team in any of them from the organization's Overview tab, which shows the new team's invite token. Owners, admins and the superuser can delete a team (the "Delete team" button in the "Invite & enroll" tab of a team, or the Delete button on the team's row in the organization's Overview tab at /ops/). Sprag refuses while the team still has active members, including paused ones, so remove them first. Deleting a team also erases the usage history and earlier activity of its past members, and it cannot be undone; the activity log keeps one "deleted" entry per machine.
|
|
151
151
|
|
|
152
152
|
A date range control at the top of the dashboard (7d, 30d, 90d, This month, Last month or Custom) sets the period for the members table, the Usage chart and the prompt usage tab. It defaults to the last 30 days, uses your local calendar days with the end date included, and allows 365 days at most. The choice is kept in the page address (`?from=2026-10-01&to=2026-10-18`), so a reload or a shared link shows the same period. The superuser console at /ops/ has the same control for the organization table, the organization header and its prompt usage.
|
|
153
153
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.93.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/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
|
|
@@ -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) {
|