sprag-cli 3.83.0 → 3.85.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.
@@ -4,6 +4,9 @@
4
4
  *
5
5
  * sprag upgrade # refresh the check, then install
6
6
  * sprag upgrade --print # show the command, run nothing
7
+ * sprag upgrade --org-policy [--agent codex]
8
+ * # non-interactive: what the session-start hook starts
9
+ * # (detached) when the organization sets a minimum version
7
10
  *
8
11
  * This is the command the model runs after the user says yes to the
9
12
  * session-start offer, so it prints the exact command it is about to execute
@@ -12,6 +15,8 @@
12
15
  */
13
16
 
14
17
  import { spawn } from 'node:child_process';
18
+ import { openSync, closeSync, writeSync, mkdirSync } from 'node:fs';
19
+ import { dirname } from 'node:path';
15
20
 
16
21
  function runCommand(cmd) {
17
22
  return new Promise((resolve) => {
@@ -24,7 +29,138 @@ function runCommand(cmd) {
24
29
  });
25
30
  }
26
31
 
27
- export async function run({ hasFlag, version }) {
32
+ /** Shell command with stdout and stderr appended to the log file; resolves to its exit code. */
33
+ function runLogged(cmd, logFile) {
34
+ return new Promise((resolve) => {
35
+ let fd;
36
+ try {
37
+ mkdirSync(dirname(logFile), { recursive: true });
38
+ fd = openSync(logFile, 'a');
39
+ writeSync(fd, `$ ${cmd}\n`);
40
+ } catch { resolve(1); return; }
41
+ const done = (code) => { try { closeSync(fd); } catch { /* already closed */ } resolve(code); };
42
+ // Same fixed-string shell form as runCommand; nothing here is user input.
43
+ const child = spawn(cmd, { shell: true, stdio: ['ignore', fd, fd], windowsHide: true });
44
+ child.on('close', (code) => done(code === null ? 1 : code));
45
+ child.on('error', () => done(1));
46
+ });
47
+ }
48
+
49
+ /** Whether sprag's Claude Code hooks or statusline are registered in settings.json. */
50
+ async function claudeIntegrationPresent() {
51
+ try {
52
+ const { readSettings, isOurCommand } = await import('../installer.js');
53
+ const { claudeUserDir } = await import('../paths.js');
54
+ const { join } = await import('node:path');
55
+ const read = readSettings(join(claudeUserDir(), 'settings.json'));
56
+ if (read.state !== 'ok') return false;
57
+ const s = read.settings;
58
+ if (isOurCommand(s.statusLine?.command)) return true;
59
+ return Object.values(s.hooks && typeof s.hooks === 'object' ? s.hooks : {}).some((groups) =>
60
+ Array.isArray(groups) && groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isOurCommand(h?.command))));
61
+ } catch { return false; }
62
+ }
63
+
64
+ /** Whether sprag's Codex hooks are registered. */
65
+ async function codexIntegrationPresent() {
66
+ try {
67
+ const { codexHookStatus } = await import('../codex/installer.js');
68
+ return codexHookStatus().some((h) => h.registered);
69
+ } catch { return false; }
70
+ }
71
+
72
+ /**
73
+ * The commands an organization-policy upgrade runs for `agent`, in order. The
74
+ * agent's own install comes first; the other agent's integration is refreshed
75
+ * too when it is present, so a machine with both ends up on one version.
76
+ */
77
+ export async function orgUpgradeCommands(agent, { claudePresent = claudeIntegrationPresent, codexPresent = codexIntegrationPresent } = {}) {
78
+ const { upgradeCommand } = await import('../update-check.js');
79
+ const { upgradeInstructions } = await import('../update-notice.js');
80
+ const cmds = agent === 'codex' ? [...upgradeInstructions('codex')] : [upgradeCommand(), 'sprag install'];
81
+ if (agent === 'codex' ? await claudePresent() : await codexPresent()) {
82
+ cmds.push(agent === 'codex' ? 'sprag install' : 'sprag install --agent codex');
83
+ }
84
+ return [...new Set(cmds)];
85
+ }
86
+
87
+ /**
88
+ * `sprag upgrade --org-policy`: the unattended upgrade the session-start hook
89
+ * starts when the organization sets a minimum version. Detached, so nothing
90
+ * goes to a terminal: output is appended to org-upgrade.log and the outcome to
91
+ * org-upgrade.json, which the next session reports. `exec`, `refresh` and
92
+ * `dir` are injectable for tests.
93
+ */
94
+ export async function runOrgPolicy({
95
+ version, agent = 'claude', dir, now = Date.now, exec, refresh, claudePresent, codexPresent,
96
+ } = {}) {
97
+ const { userDataDir } = await import('../paths.js');
98
+ const { readTeamState } = await import('../team-ratchet.js');
99
+ const org = await import('../org-upgrade.js');
100
+ const { isNewer, refreshUpdateState } = await import('../update-check.js');
101
+ const root = dir || userDataDir();
102
+ const logFile = org.orgUpgradeLogPath(root);
103
+ const run = exec || ((cmd) => runLogged(cmd, logFile));
104
+ const refreshState = refresh || refreshUpdateState;
105
+ const log = (line) => { try { writeLogLine(logFile, line); } catch { /* the record still says what happened */ } };
106
+
107
+ const prev = org.readOrgUpgrade(root);
108
+ if (prev.pid && prev.pid !== process.pid && org.orgUpgradeInFlight(prev, { now: now() })) {
109
+ return { ok: false, skipped: 'in-flight' };
110
+ }
111
+ const required = org.orgMinVersion(readTeamState(root));
112
+ const target = required || prev.target || null;
113
+ org.writeOrgUpgrade({
114
+ target, from: version, startedAt: prev.startedAt && !prev.finishedAt ? prev.startedAt : now(), pid: process.pid,
115
+ finishedAt: null, ok: null, error: null, announced: false,
116
+ }, root);
117
+ const finish = (ok, error = null, extra = {}) => {
118
+ org.writeOrgUpgrade({ finishedAt: now(), ok, error, ...extra }, root);
119
+ return { ok, error };
120
+ };
121
+
122
+ if (!required || !isNewer(required, version)) {
123
+ // The requirement went away while this was starting: nothing to report.
124
+ log(`nothing required (minimum ${required || 'unset'}, running ${version})`);
125
+ return finish(false, 'no minimum version is required any more', { announced: true });
126
+ }
127
+ const r = await refreshState(version);
128
+ const latest = r && r.ok ? r.latest : null;
129
+ if (!latest) {
130
+ log(`registry check failed: ${(r && r.error) || 'no answer'}`);
131
+ return finish(false, `could not read the latest version from the registry: ${(r && r.error) || 'no answer'}`);
132
+ }
133
+ if (isNewer(required, latest)) {
134
+ log(`required version ${required} is not published (latest ${latest})`);
135
+ return finish(false, `required version ${required} is not published (latest ${latest})`);
136
+ }
137
+
138
+ for (const cmd of await orgUpgradeCommands(agent, { claudePresent, codexPresent })) {
139
+ const code = await run(cmd);
140
+ if (code !== 0) {
141
+ log(`failed (exit ${code}): ${cmd}`);
142
+ return finish(false, `"${cmd}" exited with code ${code}`);
143
+ }
144
+ }
145
+ // Same as the interactive path: the cached "latest" now describes the new copy.
146
+ try { await refreshState(latest); } catch (e) { log(`state refresh failed: ${e && e.message}`); }
147
+ log(`upgraded ${version} -> ${latest}`);
148
+ return finish(true);
149
+ }
150
+
151
+ function writeLogLine(file, line) {
152
+ mkdirSync(dirname(file), { recursive: true });
153
+ const fd = openSync(file, 'a');
154
+ try { writeSync(fd, `[${new Date().toISOString()}] ${line}\n`); } finally { closeSync(fd); }
155
+ }
156
+
157
+ export async function run({ hasFlag, version, agent = 'claude' }) {
158
+ if (hasFlag('--org-policy')) {
159
+ // Detached, so the exit code is for whoever runs it by hand; the record has the reason.
160
+ const result = await runOrgPolicy({ version, agent });
161
+ if (!result.ok) process.exitCode = 1;
162
+ return;
163
+ }
28
164
  const { updateStatus, refreshUpdateState, upgradeCommand, INSTALLED_UNDER_LEGACY_NAME } =
29
165
  await import('../update-check.js');
30
166
  const { userLanguage } = await import('../config.js');
package/src/cost.js CHANGED
@@ -8,6 +8,8 @@
8
8
  * Cache writes are now tracked separately for 5m and 1h TTLs, each with their own rate.
9
9
  */
10
10
 
11
+ import { priceForPrompt } from './gateway-prices.js';
12
+
11
13
  // Haiku 5.5 charges a request whose prompt (input + cache writes + cache
12
14
  // reads) exceeds this many tokens at the higher 'claude-haiku-5-5-long' rates.
13
15
  // Each request is priced on its own, so callers accumulate such requests into
@@ -366,12 +368,8 @@ function priceTotals(totals, p) {
366
368
  return { actual, noCacheCost, scenario5mCost, write1h };
367
369
  }
368
370
 
369
- /**
370
- * Same shape as the list-price estimate, but priced at a gateway's per-token
371
- * rates (LiteLLM /model/info). A token class the gateway does not price makes
372
- * the whole estimate unknown (null) rather than free or list-priced.
373
- */
374
- function estimateCostAtPrice(totals, price) {
371
+ /** Unrounded figures for one set of totals at one gateway price; null when a needed rate is missing. */
372
+ function priceTotalsAtGateway(totals, price) {
375
373
  const write5m = totals.ephemeral5m ?? 0;
376
374
  const write1h = totals.ephemeral1h ?? 0;
377
375
  const untracked = Math.max(0, (totals.cacheCreation ?? 0) - write5m - write1h);
@@ -404,6 +402,32 @@ function estimateCostAtPrice(totals, price) {
404
402
  tokensToMillions(Math.max(0, read - extra5mCreation)) * cacheRead +
405
403
  tokensToMillions(totals.output) * output;
406
404
  }
405
+ return { actual, noCacheCost, scenario5mCost, applicable: price.cacheWrite != null && write1h > 0 };
406
+ }
407
+
408
+ /**
409
+ * Same shape as the list-price estimate, but priced at a gateway's per-token
410
+ * rates (LiteLLM /model/info). A token class the gateway does not price makes
411
+ * the whole estimate unknown (null) rather than free or list-priced.
412
+ *
413
+ * The parser splits requests whose prompt exceeds LONG_PROMPT_THRESHOLD into
414
+ * `totals.long`, so only a gateway tier at exactly that threshold can be
415
+ * applied here. A tier at any other threshold (e.g. 272K) cannot be told apart
416
+ * in aggregated Claude totals; those keep base rates.
417
+ */
418
+ function estimateCostAtPrice(totals, price) {
419
+ const longTier = totals.long && price.tiers?.some((t) => t.threshold === LONG_PROMPT_THRESHOLD);
420
+ let parts;
421
+ if (longTier) {
422
+ parts = [priceTotalsAtGateway(subtractTotals(totals, totals.long), price),
423
+ priceTotalsAtGateway(totals.long, priceForPrompt(price, LONG_PROMPT_THRESHOLD + 1))];
424
+ } else {
425
+ parts = [priceTotalsAtGateway(totals, price)];
426
+ }
427
+ if (parts.some((part) => part === null)) return null;
428
+ const actual = parts.reduce((n, part) => n + part.actual, 0);
429
+ const noCacheCost = parts.reduce((n, part) => n + part.noCacheCost, 0);
430
+ const scenario5mCost = parts.reduce((n, part) => n + part.scenario5mCost, 0);
407
431
 
408
432
  return {
409
433
  tier: 'gateway',
@@ -413,7 +437,7 @@ function estimateCostAtPrice(totals, price) {
413
437
  savingsRate: noCacheCost > 0 ? (noCacheCost - actual) / noCacheCost : 0,
414
438
  scenario5mCost: round(scenario5mCost),
415
439
  extraCostIf5m: round(scenario5mCost - actual),
416
- extraCostIf5mApplicable: price.cacheWrite != null && write1h > 0,
440
+ extraCostIf5mApplicable: parts.some((part) => part.applicable),
417
441
  };
418
442
  }
419
443
 
@@ -0,0 +1,91 @@
1
+ /**
2
+ * cowork-sessions: read the Claude Code transcripts the Claude desktop app's
3
+ * Cowork tab writes.
4
+ *
5
+ * Cowork runs Claude Code with a per-session CLAUDE_CONFIG_DIR, so its
6
+ * transcripts never land in ~/.claude/projects. They sit inside the session
7
+ * folder instead:
8
+ * <root>/<org>/<account>/<session>/.claude/projects/<project>/<uuid>.jsonl
9
+ * with subagents at `<project>/<uuid>/subagents/agent-*.jsonl`. The session
10
+ * folder also holds uploads, outputs and audit logs (gigabytes), so discovery
11
+ * walks exactly that depth and never recurses freely.
12
+ *
13
+ * This is a separate module, used only by the team upload (daily spend). The
14
+ * statusline, route-scan and the ledger do not read Cowork, matching the
15
+ * 2026-10-13 decision to keep delegation out of Cowork. Its parse cache is a
16
+ * separate file so thousands of transcripts never bloat session-cache.json.
17
+ *
18
+ * The macOS path is verified; the Windows and 1p (".../Claude") paths are
19
+ * assumed, as in cowork-sync.js. Leaf module: it imports only node: builtins and
20
+ * ./paths.js. The parser loads on demand inside the functions that need it, so
21
+ * cowork-sync.js (SessionStart hook) can import coworkSessionRoots without pulling
22
+ * in the parser graph, and without a cycle.
23
+ */
24
+
25
+ import { existsSync } from 'node:fs';
26
+ import { readdir } from 'node:fs/promises';
27
+ import { join } from 'node:path';
28
+ import { homedir } from 'node:os';
29
+ import { userDataDir } from './paths.js';
30
+
31
+ // Sessions scanned at once; each scan is a few readdirs and stats.
32
+ const DISCOVER_BATCH = 16;
33
+
34
+ export function coworkSessionRoots() {
35
+ const bases = [];
36
+ if (process.platform === 'darwin') {
37
+ const support = join(homedir(), 'Library', 'Application Support');
38
+ bases.push(join(support, 'Claude'), join(support, 'Claude-3p'));
39
+ } else if (process.platform === 'win32' && process.env.APPDATA) {
40
+ bases.push(join(process.env.APPDATA, 'Claude'), join(process.env.APPDATA, 'Claude-3p'));
41
+ }
42
+ return bases.map((b) => join(b, 'local-agent-mode-sessions')).filter((p) => existsSync(p));
43
+ }
44
+
45
+ /** Names of the subdirectories of `dir`; unreadable means none. */
46
+ async function subdirNames(dir) {
47
+ try {
48
+ return (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
49
+ } catch {
50
+ return [];
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Transcripts modified within `days`, in the shape discoverSessionFiles returns.
56
+ * Only <root>/<org>/<account>/<session> is walked here; each session's own projects
57
+ * directory goes through discoverSessionFiles, so Cowork follows every discovery rule
58
+ * of Claude Code. Best-effort: an unreadable directory is skipped.
59
+ */
60
+ export async function discoverCoworkSessionFiles({ days = 30, roots = coworkSessionRoots(), now = Date.now() } = {}) {
61
+ const { discoverSessionFiles, dedupeSessionFiles } = await import('./parser.js');
62
+ const projectsDirs = [];
63
+ for (const root of roots) {
64
+ for (const org of await subdirNames(root)) {
65
+ for (const account of await subdirNames(join(root, org))) {
66
+ for (const session of await subdirNames(join(root, org, account))) {
67
+ projectsDirs.push(join(root, org, account, session, '.claude', 'projects'));
68
+ }
69
+ }
70
+ }
71
+ }
72
+ const files = [];
73
+ for (let i = 0; i < projectsDirs.length; i += DISCOVER_BATCH) {
74
+ const batch = await Promise.all(projectsDirs.slice(i, i + DISCOVER_BATCH).map((root) => discoverSessionFiles({ root, days, now })));
75
+ for (const found of batch) files.push(...found);
76
+ }
77
+ // Transcript names are uuids, so this only collapses a copied session folder.
78
+ return dedupeSessionFiles(files).sort((a, b) => a.mtime - b.mtime);
79
+ }
80
+
81
+ /** Parsed Cowork sessions, marked `surface: 'cowork'`. */
82
+ export async function parseCoworkSessions({ days = 30, roots } = {}) {
83
+ const { parseAllSessions } = await import('./parser.js');
84
+ const sessions = await parseAllSessions({
85
+ days,
86
+ files: await discoverCoworkSessionFiles({ days, roots }),
87
+ cachePath: join(userDataDir(), 'cowork-session-cache.json'),
88
+ });
89
+ for (const s of sessions) s.surface = 'cowork';
90
+ return sessions;
91
+ }
@@ -28,6 +28,7 @@ import { join, resolve, sep, isAbsolute } from 'node:path';
28
28
  import { homedir } from 'node:os';
29
29
  import { execFileSync } from 'node:child_process';
30
30
  import { userDataDir, claudeUserDir } from './paths.js';
31
+ import { coworkSessionRoots } from './cowork-sessions.js';
31
32
  import { loadConfig, saveConfig, userLanguage } from './config.js';
32
33
  import { writeStateFile } from './state-file.js';
33
34
  import { readSettings, writeSettings } from './installer.js';
@@ -83,16 +84,7 @@ export function saveCoworkState(state) {
83
84
 
84
85
  // ---------- discovery ----------
85
86
 
86
- export function coworkSessionRoots() {
87
- const bases = [];
88
- if (process.platform === 'darwin') {
89
- const support = join(homedir(), 'Library', 'Application Support');
90
- bases.push(join(support, 'Claude'), join(support, 'Claude-3p'));
91
- } else if (process.platform === 'win32' && process.env.APPDATA) {
92
- bases.push(join(process.env.APPDATA, 'Claude'), join(process.env.APPDATA, 'Claude-3p'));
93
- }
94
- return bases.map((b) => join(b, 'local-agent-mode-sessions')).filter((p) => existsSync(p));
95
- }
87
+ export { coworkSessionRoots };
96
88
 
97
89
  function subdirs(dir) {
98
90
  try {
@@ -114,6 +114,39 @@ export function keyFromApiKeyHelper(cwd = process.cwd()) {
114
114
  return null;
115
115
  }
116
116
 
117
+ const SETTINGS_ENV_KEYS = ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY'];
118
+
119
+ /**
120
+ * 프로세스 환경에 게이트웨이 주소가 없을 때, ~/.claude/settings.json 의 env 블록에서
121
+ * 주소와 토큰을 가져와 채운 사본을 돌려줍니다.
122
+ *
123
+ * 팀 동기화는 Claude Code 훅에서도 Codex 훅에서도 시작됩니다. Claude Code 는
124
+ * settings.json 의 env 를 자기 프로세스에 넣어 주지만 Codex 프로세스에는 그 값이
125
+ * 없습니다. 그래서 같은 하루 행이 어느 에이전트가 동기화했느냐에 따라 게이트웨이
126
+ * 단가와 목록 단가 사이를 오가고, 게이트웨이 금액도 생겼다 사라졌습니다.
127
+ *
128
+ * 환경에 주소가 이미 있으면 그대로 둡니다. 다른 게이트웨이의 토큰이 섞이면 안
129
+ * 되기 때문입니다. 프로젝트 설정은 신뢰 확인이 필요하므로 읽지 않고, 관리형 설정은
130
+ * 홈 디렉터리 밖에 있어 테스트에서 격리할 수 없으므로 읽지 않습니다.
131
+ */
132
+ export function withClaudeSettingsEnv(env = process.env, { home = homedir() } = {}) {
133
+ if ((env.ANTHROPIC_BASE_URL || '').trim()) return env;
134
+ let fromSettings;
135
+ try {
136
+ fromSettings = JSON.parse(readFileSync(join(home, '.claude', 'settings.json'), 'utf8'))?.env;
137
+ } catch {
138
+ return env;
139
+ }
140
+ if (!fromSettings || typeof fromSettings !== 'object') return env;
141
+ const base = typeof fromSettings.ANTHROPIC_BASE_URL === 'string' ? fromSettings.ANTHROPIC_BASE_URL.trim() : '';
142
+ if (!base) return env;
143
+ const next = { ...env };
144
+ for (const k of SETTINGS_ENV_KEYS) {
145
+ if (!(next[k] || '').trim() && typeof fromSettings[k] === 'string' && fromSettings[k].trim()) next[k] = fromSettings[k].trim();
146
+ }
147
+ return next;
148
+ }
149
+
117
150
  /** 환경변수 토큰을 먼저 보고, 없으면 apiKeyHelper 로 내려갑니다. */
118
151
  export function resolveKey(env = process.env) {
119
152
  const direct = (env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY || '').trim();
@@ -9,8 +9,37 @@ export function deploymentPrice(row) {
9
9
  if (mode && !['chat', 'responses', 'completion'].includes(mode)) return null;
10
10
  const input = rate(info.input_cost_per_token), output = rate(info.output_cost_per_token);
11
11
  if (input === null || output === null) return null;
12
- return { input, output, cacheRead: rate(info.cache_read_input_token_cost), cacheWrite: rate(info.cache_creation_input_token_cost),
12
+ const price = { input, output, cacheRead: rate(info.cache_read_input_token_cost), cacheWrite: rate(info.cache_creation_input_token_cost),
13
13
  cacheWrite1h: rate(info.cache_creation_input_token_cost_above_1hr) };
14
+ // `_above_<N>k_tokens` keys reprice a whole request whose prompt exceeds N thousand tokens.
15
+ // The plain `cache_creation_input_token_cost_above_1hr` has no `k_tokens` suffix: it is the 1h write rate, not a tier.
16
+ const tiers = new Map();
17
+ for (const [key, value] of Object.entries(info)) {
18
+ const m = TIER_KEY.exec(key);
19
+ // /model/info lists every tier key with null for the models that have no tier.
20
+ if (!m || rate(value) === null) continue;
21
+ const threshold = Number(m[2]) * 1000;
22
+ const tier = tiers.get(threshold) || { threshold, input: null, output: null, cacheRead: null, cacheWrite: null, cacheWrite1h: null };
23
+ tier[TIER_FIELD[m[1]]] = rate(value);
24
+ tiers.set(threshold, tier);
25
+ }
26
+ // Only when present, so untiered models keep the exact old shape (prices are compared via JSON.stringify).
27
+ if (tiers.size) price.tiers = [...tiers.values()].sort((a, b) => a.threshold - b.threshold);
28
+ return price;
29
+ }
30
+
31
+ const TIER_KEY = /^(input_cost_per_token|output_cost_per_token|cache_read_input_token_cost|cache_creation_input_token_cost|cache_creation_input_token_cost_above_1hr)_above_(\d+)k_tokens$/;
32
+ const TIER_FIELD = { input_cost_per_token: 'input', output_cost_per_token: 'output', cache_read_input_token_cost: 'cacheRead',
33
+ cache_creation_input_token_cost: 'cacheWrite', cache_creation_input_token_cost_above_1hr: 'cacheWrite1h' };
34
+
35
+ /** `price` with the highest tier whose threshold the prompt exceeds (strictly, as LiteLLM does) laid over it. */
36
+ export function priceForPrompt(price, promptTokens) {
37
+ if (!price?.tiers) return price;
38
+ const tier = price.tiers.filter((t) => t.threshold < promptTokens).pop();
39
+ if (!tier) return price;
40
+ const merged = { ...price };
41
+ for (const field of Object.values(TIER_FIELD)) if (tier[field] != null) merged[field] = tier[field];
42
+ return merged;
14
43
  }
15
44
 
16
45
  /** Per-token prices by alias. Load-balanced deployments must agree, like cache policy. */
@@ -22,7 +51,20 @@ export function gatewayPrices(payload) {
22
51
  groups.set(row.model_name, [...(groups.get(row.model_name) || []), deploymentPrice(row)]);
23
52
  }
24
53
  return Object.fromEntries([...groups].map(([name, prices]) => [name,
25
- prices[0] && prices.every((p) => JSON.stringify(p) === JSON.stringify(prices[0])) ? prices[0] : null]));
54
+ prices.reduce((merged, price) => mergePrices(merged, price))]));
55
+ }
56
+
57
+ /**
58
+ * The price two deployments of one key agree on. Differing base rates, or a deployment without a
59
+ * price, leave the key unpriced (null). Equal base rates with different tiers fall back to the
60
+ * base rates alone: the tier-less price the key had before tiers existed, never a guessed tier.
61
+ */
62
+ export function mergePrices(a, b) {
63
+ if (!a || !b) return null;
64
+ const { tiers: tiersA, ...baseA } = a;
65
+ const { tiers: tiersB, ...baseB } = b;
66
+ if (JSON.stringify(baseA) !== JSON.stringify(baseB)) return null;
67
+ return JSON.stringify(tiersA) === JSON.stringify(tiersB) ? a : baseA;
26
68
  }
27
69
 
28
70
  /**
@@ -37,3 +79,13 @@ export function codexRunCost({ input = 0, cached = 0, cacheWrite = 0, output = 0
37
79
  return uncached * price.input + cached * (price.cacheRead ?? 0) + cacheWrite * (price.cacheWrite ?? price.input) + output * price.output;
38
80
  }
39
81
 
82
+ /**
83
+ * USD for ONE request. The tier depends on this request's own prompt size: `usage.prompt` when
84
+ * the caller has it, else `usage.input`. The amounts always come from input/cached/cacheWrite/output,
85
+ * and `prompt` can be smaller than `input` when a row merges several responses. Totals summed over
86
+ * many requests must keep using codexRunCost at base rates.
87
+ */
88
+ export function codexRequestCost(usage, price) {
89
+ return codexRunCost(usage, priceForPrompt(price, usage.prompt ?? usage.input));
90
+ }
91
+
@@ -0,0 +1,137 @@
1
+ /**
2
+ * gateway-spend: the LiteLLM gateway's own daily spend for this user, for the
3
+ * team upload.
4
+ *
5
+ * Local session logs miss requests that leave no transcript (print mode
6
+ * without persistence, SDK scripts, deleted conversations), so a machine on a
7
+ * gateway reports the gateway's figure as its total usage and keeps the local
8
+ * figures beside it. Two calls, both with the user's own key:
9
+ *
10
+ * GET {base}/key/info the key's user_id (404 on custom-auth deployments)
11
+ * GET {base}/user/info user_info.user_id as the fallback
12
+ * GET {base}/global/spend/logs rows {date, spend, api_key, user}; the most
13
+ * recent 30 days, every user the key may see
14
+ *
15
+ * Only rows whose `user` is this user id are summed: an admin key sees
16
+ * everyone's rows and summing them all would report the whole company as one
17
+ * person. Without a user id nothing is attributable and the caller gets null,
18
+ * which reads as "no gateway figure" rather than an error.
19
+ *
20
+ * The key is used for the Authorization header only and is never written to
21
+ * a file (same rule as litellm-budget.js). Failures are returned as
22
+ * `{ error }`, never thrown: the upload goes on with local figures.
23
+ *
24
+ * `date` is the gateway's calendar day (UTC on the deployments measured), so
25
+ * a day can differ from the local day by up to a few hours of traffic; range
26
+ * sums are unaffected.
27
+ */
28
+
29
+ import { createHash } from 'node:crypto';
30
+ // gateway-auth.js is the leaf that litellm-budget.js re-exports; importing it
31
+ // directly keeps team-sync.js out of the statusline formatter's import graph.
32
+ import { gatewayBase, resolveKey } from './gateway-auth.js';
33
+ import { debug } from './debug.js';
34
+
35
+ /** Same answer as litellm-budget's gatewayEnv: address and key, or null. */
36
+ export function gatewayEnv(env = process.env) {
37
+ const base = gatewayBase(env);
38
+ if (!base) return null;
39
+ const key = resolveKey(env);
40
+ return key ? { base, key } : null;
41
+ }
42
+
43
+ export const GATEWAY_SPEND_TIMEOUT_MS = 15000;
44
+ export const GATEWAY_SPEND_DAYS = 30;
45
+
46
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}/;
47
+
48
+ /** Local calendar day, same key as team-sync.js and stats.js. */
49
+ function dayKey(ms) {
50
+ const d = new Date(ms);
51
+ const pad = (n) => String(n).padStart(2, '0');
52
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
53
+ }
54
+
55
+ /** Pseudonymous id for the (gateway, user) pair: the first 16 hex characters of a SHA-256. */
56
+ export function gatewayUserHash(base, userId) {
57
+ return createHash('sha256').update(`${base}\n${userId}`).digest('hex').slice(0, 16);
58
+ }
59
+
60
+ /**
61
+ * Sum `rows` for one user by date. Exported for tests and for the aggregate
62
+ * step; `rows` is the `/global/spend/logs` body (an array, or `{ data }`).
63
+ */
64
+ export function sumSpendRows(rows, userId) {
65
+ const list = Array.isArray(rows) ? rows : Array.isArray(rows?.data) ? rows.data : [];
66
+ const days = new Map();
67
+ let earliest = null;
68
+ for (const r of list) {
69
+ if (!r || typeof r !== 'object') continue;
70
+ const date = String(r.date || r.startTime || '').slice(0, 10);
71
+ if (!DAY_RE.test(date)) continue;
72
+ if (earliest === null || date < earliest) earliest = date;
73
+ if (String(r.user ?? '') !== String(userId)) continue;
74
+ const usd = Number(r.spend);
75
+ if (!Number.isFinite(usd)) continue;
76
+ days.set(date, (days.get(date) || 0) + usd);
77
+ }
78
+ return { days, earliest };
79
+ }
80
+
81
+ /**
82
+ * The gateway figure for one local day: a number inside the covered range (0
83
+ * when the gateway has no row for it), null outside it or without a result.
84
+ */
85
+ export function gatewayDayValue(result, day) {
86
+ if (!result || !result.days || !result.coveredFrom || !result.coveredTo) return null;
87
+ if (day < result.coveredFrom || day > result.coveredTo) return null;
88
+ return result.days.get(day) || 0;
89
+ }
90
+
91
+ /**
92
+ * @returns {Promise<null | { error: string } | { days: Map<string, number>, coveredFrom: string, coveredTo: string, userId: string, userHash: string }>}
93
+ * null when no gateway is configured or the user id cannot be learned.
94
+ */
95
+ export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = globalThis.fetch, now = Date.now(), timeoutMs = GATEWAY_SPEND_TIMEOUT_MS } = {}) {
96
+ const g = gatewayEnv(env);
97
+ if (!g) return null;
98
+ const { base, key } = g;
99
+ const ctl = new AbortController();
100
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
101
+ const headers = { accept: 'application/json', authorization: `Bearer ${key}` };
102
+ const getJson = async (path) => {
103
+ const res = await fetchImpl(`${base}${path}`, { signal: ctl.signal, headers, redirect: 'error' });
104
+ if (!res.ok) throw new Error(`LiteLLM ${path} responded ${res.status}`);
105
+ return res.json();
106
+ };
107
+ try {
108
+ // Same order as pickBudgetSource: the key's own user id first, then the
109
+ // user record. /key/info is 404 on custom-auth deployments; that is fine.
110
+ let userId = null;
111
+ try {
112
+ const keyBody = await getJson('/key/info');
113
+ const id = keyBody?.info?.user_id;
114
+ if (typeof id === 'string' && id) userId = id;
115
+ } catch (e) { debug('gateway-spend:key-info', e); }
116
+ if (!userId) {
117
+ const userBody = await getJson('/user/info');
118
+ const id = userBody?.user_info?.user_id;
119
+ if (typeof id === 'string' && id) userId = id;
120
+ }
121
+ if (!userId) return null;
122
+ const rows = await getJson('/global/spend/logs');
123
+ const { days, earliest } = sumSpendRows(rows, userId);
124
+ const coveredTo = dayKey(now);
125
+ const windowStart = dayKey(now - (GATEWAY_SPEND_DAYS - 1) * 86400000);
126
+ // The response is the gateway's recent-30-day window. A day inside it with
127
+ // no row is a day with no spend; the earliest row only widens the window
128
+ // when the gateway sent more than 30 days.
129
+ const coveredFrom = earliest && earliest < windowStart ? earliest : windowStart;
130
+ return { days, coveredFrom, coveredTo, userId, userHash: gatewayUserHash(base, userId) };
131
+ } catch (e) {
132
+ debug('gateway-spend', e);
133
+ return { error: e && e.name === 'AbortError' ? 'timeout' : String((e && e.message) || e) };
134
+ } finally {
135
+ clearTimeout(timer);
136
+ }
137
+ }
@@ -27,7 +27,7 @@
27
27
  import { gatewayBase } from './gateway-auth.js';
28
28
  import { loadProfileMap, updateProfileMap, resetModelAliasCache, profileIdFrom, isGatewayModelId } from './model-alias.js';
29
29
  import { isRecognizedModelId } from './cost.js';
30
- import { deploymentPrice, PRICE_MAX_AGE_MS } from './gateway-prices.js';
30
+ import { deploymentPrice, mergePrices, PRICE_MAX_AGE_MS } from './gateway-prices.js';
31
31
  import { debug } from './debug.js';
32
32
 
33
33
  /** 게이트웨이 모델 맵의 신선도 기준. 배포 구성은 하루에 여러 번 바뀌지 않습니다. */
@@ -171,8 +171,7 @@ export function deriveGatewayPrices(payload) {
171
171
  ]);
172
172
  for (const key of keys) {
173
173
  if (!key) continue;
174
- if (!prices.has(key)) prices.set(key, price);
175
- else if (JSON.stringify(prices.get(key)) !== JSON.stringify(price)) prices.set(key, null);
174
+ prices.set(key, prices.has(key) ? mergePrices(prices.get(key), price) : price);
176
175
  }
177
176
  }
178
177
  return Object.fromEntries(prices);