sprag-cli 3.84.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.
package/src/team-sync.js CHANGED
@@ -44,12 +44,15 @@ import { loadLedger, modelFamily, roundUsd } from './savings-ledger.js';
44
44
  import { sessionCost, pricedParts } from './claude-price.js';
45
45
  import { uploadPrompts, dropOffsets, promptOffsetsExist } from './team-prompts.js';
46
46
  import { rulesPullDue, syncTeamRatchet, ensureTeamImport } from './team-ratchet.js';
47
+ import { parseMinVersion } from './org-upgrade.js';
47
48
  import { codexUserDir } from './agent.js';
48
49
  import { loadCodexLedger, codexEventCost } from './codex/ledger.js';
49
50
  import { codexDocumentEvents } from './codex/doc2md-ledger.js';
50
- import { codexPriceBook, readCodexPrices, refreshCodexPrices, codexRunCost } from './codex/cache-policy.js';
51
+ import { codexPriceBook, readCodexPrices, refreshCodexPrices, codexRunCost, CODEX_PRICES_SCHEMA } from './codex/cache-policy.js';
52
+ import { codexRequestCost } from './gateway-prices.js';
51
53
  import { codexBudgetProvider } from './codex/budget.js';
52
54
  import { fetchGatewayDailySpend, gatewayDayValue, gatewayEnv } from './gateway-spend.js';
55
+ import { withClaudeSettingsEnv } from './gateway-auth.js';
53
56
 
54
57
  export const PROMPT_SYNC_INTERVAL_MS = 30 * 60 * 1000;
55
58
 
@@ -325,15 +328,35 @@ const round4 = (n) => Math.round(n * 10000) / 10000;
325
328
  /** A Codex session's usage in codexRunCost's shape: `input` includes the cached and written parts. */
326
329
  const codexUsage = (t) => ({ input: (t.input || 0) + (t.cacheRead || 0) + (t.cacheCreation || 0), cached: t.cacheRead || 0, cacheWrite: t.cacheCreation || 0, output: t.output || 0 });
327
330
 
331
+ /**
332
+ * `[model, usd]` pairs for one Codex session; usd is null when any part of that model is unpriced.
333
+ * With per-request rows the long-context tier depends on each request's own prompt size, which the
334
+ * session totals no longer show, so each request is priced alone. Otherwise the totals are priced.
335
+ */
336
+ function codexSessionCosts(s, book) {
337
+ if (Array.isArray(s.requests) && s.requests.length) {
338
+ const byModel = new Map();
339
+ for (const r of s.requests) {
340
+ const model = r.model || s.model;
341
+ const usd = book ? codexRequestCost(r, book.prices?.[model]) : null;
342
+ byModel.set(model, usd === null || byModel.get(model) === null ? null : (byModel.get(model) || 0) + usd);
343
+ }
344
+ return [...byModel];
345
+ }
346
+ const parts = s.modelTotals && Object.keys(s.modelTotals).length ? Object.entries(s.modelTotals) : [[s.model, s.totals]];
347
+ return parts.map(([model, totals]) => [model, book ? codexRunCost(codexUsage(totals), book.prices?.[model]) : null]);
348
+ }
349
+
328
350
  /**
329
351
  * Per-day rows, oldest first, only days with activity inside the window.
330
352
  *
331
353
  * Money fields (all rounded to 4 decimals):
332
- * spent_usd Claude local spend, main session plus subagent runs,
333
- * on the session's start day (unchanged meaning: older
334
- * servers and pages keep reading it)
335
- * claude_spent_usd the same figure; subagent_cost_usd is the part of it
336
- * that subagent runs and Codex child sessions cost
354
+ * spent_usd Claude Code plus Cowork local spend, main session plus
355
+ * subagent runs, on the session's start day (unchanged
356
+ * meaning: older servers and pages keep reading it)
357
+ * claude_spent_usd the same figure (Claude Code plus Cowork);
358
+ * subagent_cost_usd is the part of it that subagent
359
+ * runs and Codex child sessions cost
337
360
  * codex_spent_usd Codex rollouts priced by the path they took (gateway
338
361
  * prices for a LiteLLM provider, OpenAI list prices for
339
362
  * direct calls); unpriced sessions count in unpriced_parts
@@ -355,9 +378,13 @@ const codexUsage = (t) => ({ input: (t.input || 0) + (t.cacheRead || 0) + (t.cac
355
378
  */
356
379
  export async function aggregateDaily({
357
380
  now = Date.now(), dir = userDataDir(), days = 30, sessions = null,
358
- codexSessions = null, codexLedger = null, codexDocEvents = null, codexPrices = undefined, gatewayDaily = null, env = process.env,
381
+ coworkSessions = null, codexSessions = null, codexLedger = null, codexDocEvents = null, codexPrices = undefined, gatewayDaily = null, env = process.env,
359
382
  } = {}) {
360
383
  const { readResetMarks, isBeforeReset } = require('./saved-reset.cjs');
384
+ // Claude sessions are priced at the gateway's rates only when the gateway
385
+ // address is known; `team status --show-payload` and a Codex-started sync
386
+ // run without Claude Code's environment, so settings.json fills it in.
387
+ env = withClaudeSettingsEnv(env);
361
388
  const doc2md = require('./doc2md-ledger.cjs');
362
389
  const cutoff = now - days * 24 * 3600 * 1000;
363
390
  const byDay = new Map();
@@ -423,12 +450,9 @@ export async function aggregateDaily({
423
450
  d.models.set(fam, (d.models.get(fam) || 0) + usd);
424
451
  };
425
452
 
426
- try {
427
- let list = sessions;
428
- if (!list) {
429
- const { parseAllSessions } = await import('./parser.js');
430
- list = await parseAllSessions({ days });
431
- }
453
+ // Claude Code and Cowork sessions are priced alike; Cowork transcripts live
454
+ // outside ~/.claude/projects (see cowork-sessions.js).
455
+ const addClaudeSessions = (list) => {
432
456
  for (const s of list || []) {
433
457
  if (!s || !s.startTime || !s.totals) continue;
434
458
  const t = new Date(s.startTime).getTime();
@@ -444,6 +468,24 @@ export async function aggregateDaily({
444
468
  } catch (e) { debug('team-sync', e); }
445
469
  }
446
470
  }
471
+ };
472
+
473
+ try {
474
+ let list = sessions;
475
+ if (!list) {
476
+ const { parseAllSessions } = await import('./parser.js');
477
+ list = await parseAllSessions({ days });
478
+ }
479
+ addClaudeSessions(list);
480
+ } catch (e) { debug('team-sync', e); }
481
+
482
+ try {
483
+ let list = coworkSessions;
484
+ if (!list) {
485
+ const { parseCoworkSessions } = await import('./cowork-sessions.js');
486
+ list = await parseCoworkSessions({ days });
487
+ }
488
+ addClaudeSessions(list);
447
489
  } catch (e) { debug('team-sync', e); }
448
490
 
449
491
  // Codex sessions: priced per model from the rollout usage records, on the
@@ -452,7 +494,7 @@ export async function aggregateDaily({
452
494
  let list = codexSessions;
453
495
  if (!list) {
454
496
  const { parseAllCodexSessions } = await import('./codex/parser.js');
455
- list = await parseAllCodexSessions({ days });
497
+ list = await parseAllCodexSessions({ days, compressed: true, keepRequests: true });
456
498
  }
457
499
  const prices = codexPrices === undefined ? readCodexPrices({ now, dir }) : codexPrices;
458
500
  for (const s of list || []) {
@@ -461,9 +503,7 @@ export async function aggregateDaily({
461
503
  if (!inWindow(t)) continue;
462
504
  const d = get(dayKey(t));
463
505
  const book = codexPriceBook(s.provider, prices);
464
- const parts = s.modelTotals && Object.keys(s.modelTotals).length ? Object.entries(s.modelTotals) : [[s.model, s.totals]];
465
- for (const [model, totals] of parts) {
466
- const usd = book ? codexRunCost(codexUsage(totals), book.prices?.[model]) : null;
506
+ for (const [model, usd] of codexSessionCosts(s, book)) {
467
507
  if (usd === null) { d.unpriced += 1; continue; }
468
508
  d.codex += usd;
469
509
  if (s.isSubagent) d.subagent += usd;
@@ -515,19 +555,30 @@ export async function aggregateDaily({
515
555
  .filter((r) => r.spent_usd || r.codex_spent_usd || r.gateway_spent_usd || r.saved_usd || r.delegated_runs || r.delegated_cost_usd || r.subagent_cost_usd || r.unpriced_parts);
516
556
  }
517
557
 
558
+ // After a failed refresh the gateway is left alone for this long; syncs run every 5 minutes.
559
+ const CODEX_PRICES_RETRY_MS = 60 * 60 * 1000;
560
+
518
561
  /**
519
562
  * The Codex price table for the upload, refreshed once from the gateway when
520
- * the snapshot is missing or stale. Only the sync (a detached child) calls
521
- * this; `team status --show-payload` stays offline.
563
+ * the snapshot is missing, stale or from before the tier change. Only the sync
564
+ * (a detached child) calls this; `team status --show-payload` stays offline.
565
+ * Returns `{ prices, failed }`: `failed` means a refresh was tried and did not
566
+ * work, so the caller records the time and `attemptedAt` throttles the next try.
522
567
  */
523
- async function codexPricesForSync({ dir, now, fetchImpl }) {
568
+ async function codexPricesForSync({ dir, now, fetchImpl, attemptedAt }) {
524
569
  const cached = readCodexPrices({ now, dir });
525
- if (cached) return cached;
570
+ // A snapshot from before the tier change lacks the tiers: refresh it, but
571
+ // keep it as the fallback, since old prices still beat none.
572
+ if (cached && (cached.pricesSchema ?? 1) >= CODEX_PRICES_SCHEMA) return { prices: cached };
573
+ if (Number.isFinite(attemptedAt) && now >= attemptedAt && now - attemptedAt < CODEX_PRICES_RETRY_MS) return { prices: cached };
526
574
  let provider = null;
527
575
  try { provider = codexBudgetProvider(); } catch (e) { debug('team-sync:codex-prices', e); }
528
- if (!provider) return null;
529
- try { return await refreshCodexPrices({ provider, dir, now, fetchImpl }); }
530
- catch (e) { debug('team-sync:codex-prices', e); return null; }
576
+ if (!provider) return { prices: cached };
577
+ try {
578
+ const fresh = await refreshCodexPrices({ provider, dir, now, fetchImpl });
579
+ if (fresh) return { prices: fresh };
580
+ } catch (e) { debug('team-sync:codex-prices', e); }
581
+ return { prices: cached, failed: true };
531
582
  }
532
583
 
533
584
  // Device info: OS name and OS version. The CPU architecture is not sent: the
@@ -677,18 +728,22 @@ async function pullRules({ memberKey, dir, fetch, now }) {
677
728
  const rules = Array.isArray(r.rules) ? r.rules : [];
678
729
  writeStateFile(teamRulesCachePath(dir), JSON.stringify({
679
730
  version: 1, fetchedAt: now, teamId: r.team_id, teamName: r.team_name, orgId: r.org_id || null, orgName: r.org_name || null,
731
+ minVersion: parseMinVersion(r.min_version),
680
732
  plan: r.plan, promptCapture: !!r.prompt_capture, rules, removed: Array.isArray(r.removed) ? r.removed : [],
681
733
  }, null, 2) + '\n');
682
734
  return { r, rules };
683
735
  }
684
736
 
685
737
  /** State fields a rules pull refreshes. */
686
- function withRulesMeta(state, r, now) {
738
+ export function withRulesMeta(state, r, now) {
687
739
  const next = { ...state, lastRulesAt: now };
688
740
  if (r.team_name) next.teamName = r.team_name;
689
741
  if (r.plan) next.plan = r.plan;
690
742
  if (r.org_name) next.orgName = r.org_name;
691
743
  if (r.prompt_capture !== undefined) next.promptCapture = !!r.prompt_capture;
744
+ // The organization minimum version. An older server omits the key and leaves
745
+ // the state alone; a present null (or a malformed value) clears the minimum.
746
+ if (r.min_version !== undefined) next.minVersion = parseMinVersion(r.min_version);
692
747
  delete next.lastRulesError;
693
748
  return next;
694
749
  }
@@ -710,13 +765,13 @@ export function refreshTeamRatchetFiles({ dir = userDataDir() } = {}) {
710
765
 
711
766
  /**
712
767
  * `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
713
- * is injected separately so tests can fake each side). `codexSessions`,
768
+ * is injected separately so tests can fake each side). `coworkSessions`, `codexSessions`,
714
769
  * `codexLedger`, `codexDocEvents` and `codexPrices` pass straight to
715
770
  * aggregateDaily.
716
771
  */
717
772
  export async function syncTeam({
718
773
  now = Date.now(), dir = userDataDir(), fetch, force = false, env = process.env, version, sessions, promptsOnly = false, rulesOnly = false,
719
- gatewayFetch = globalThis.fetch, codexSessions, codexLedger, codexDocEvents, codexPrices,
774
+ gatewayFetch = globalThis.fetch, coworkSessions, codexSessions, codexLedger, codexDocEvents, codexPrices,
720
775
  } = {}) {
721
776
  let state = loadTeamState(dir);
722
777
  // The switch stops every usage upload. A joined machine still tells the
@@ -785,13 +840,23 @@ export async function syncTeam({
785
840
  // not stop the upload: those days go up with local figures and null
786
841
  // totals (the server keeps what it already has), and gatewaySyncedThrough
787
842
  // stays put so the next successful call re-sends them.
843
+ // A sync started from a Codex hook lacks the gateway address Claude Code
844
+ // puts in its own environment; take it from settings.json so both agents
845
+ // price Claude the same way and both see the gateway figure.
846
+ env = withClaudeSettingsEnv(env);
788
847
  const hasGateway = !!gatewayEnv(env);
789
848
  let gatewayDaily = null;
790
849
  if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now });
791
850
  const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
792
851
  const win = ledgerWindow(state, now, { gateway: hasGateway });
793
- const prices = codexPrices !== undefined ? codexPrices : await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch });
794
- const rows = (await aggregateDaily({ now, dir, sessions, days: win.days, env, codexSessions, codexLedger, codexDocEvents, codexPrices: prices, gatewayDaily }))
852
+ let prices = codexPrices;
853
+ if (prices === undefined) {
854
+ const r = await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch, attemptedAt: state.codexPricesAttemptAt });
855
+ prices = r.prices;
856
+ // Carried by `state` into both the success and the failure save below.
857
+ if (r.failed) state = { ...state, codexPricesAttemptAt: now };
858
+ }
859
+ const rows = (await aggregateDaily({ now, dir, sessions, days: win.days, env, coworkSessions, codexSessions, codexLedger, codexDocEvents, codexPrices: prices, gatewayDaily }))
795
860
  .filter((r) => r.day >= win.startKey).slice(-MAX_ROWS);
796
861
  await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
797
862
  const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
@@ -13,17 +13,26 @@
13
13
  * A generator's finally block runs on `break`, `return` and throw alike, so
14
14
  * the stream is destroyed on every exit, and the 'close' event is awaited so
15
15
  * the descriptor is gone when the loop is.
16
+ *
17
+ * A `.zst` path (Codex compresses older rollouts) is decompressed on the fly:
18
+ * through zlib where Node has zstd (22.15+/23.8+), else through the `zstd` binary.
16
19
  */
17
20
 
18
21
  import { createReadStream } from 'node:fs';
19
22
  import { createInterface } from 'node:readline';
20
23
  import { once } from 'node:events';
24
+ import { spawn } from 'node:child_process';
25
+ import zlib from 'node:zlib';
21
26
 
22
27
  /**
23
28
  * @param {string} filePath
24
29
  * @returns {AsyncGenerator<string>}
25
30
  */
26
31
  export async function* transcriptLines(filePath) {
32
+ if (filePath.endsWith('.zst')) {
33
+ yield* typeof zlib.createZstdDecompress === 'function' ? zstdLines(filePath) : zstdBinaryLines(filePath);
34
+ return;
35
+ }
27
36
  const input = createReadStream(filePath, { encoding: 'utf8' });
28
37
  const rl = createInterface({ input, crlfDelay: Infinity });
29
38
  try {
@@ -38,3 +47,60 @@ export async function* transcriptLines(filePath) {
38
47
  if (!input.closed) await once(input, 'close').catch(() => {});
39
48
  }
40
49
  }
50
+
51
+ async function* zstdLines(filePath) {
52
+ const input = createReadStream(filePath);
53
+ const inflate = zlib.createZstdDecompress();
54
+ inflate.setEncoding('utf8');
55
+ // pipe() does not forward errors, and a failed read would leave the loop waiting forever.
56
+ input.on('error', (err) => inflate.destroy(err));
57
+ input.pipe(inflate);
58
+ let decompressed = 0;
59
+ inflate.on('data', (chunk) => { decompressed += chunk.length; });
60
+ const rl = createInterface({ input: inflate, crlfDelay: Infinity });
61
+ let finished = false;
62
+ try {
63
+ for await (const line of rl) yield line;
64
+ finished = true;
65
+ } catch (err) {
66
+ // Some Node builds report a cut stream as a bare "unexpected end of file";
67
+ // name the file so the caller's debug log says which rollout it was.
68
+ throw new Error(`zstd: ${filePath}: ${err.message}`, { cause: err });
69
+ } finally {
70
+ rl.close();
71
+ inflate.destroy();
72
+ input.destroy();
73
+ if (!input.closed) await once(input, 'close').catch(() => {});
74
+ }
75
+ // Node's zstd stream can end quietly on a file cut short, while the binary path fails on a
76
+ // non-zero exit. A non-empty file that yields nothing is such a cut, not an empty rollout.
77
+ // A cut at a frame boundary of a multi-frame file still cannot be detected here.
78
+ if (finished && decompressed === 0 && input.bytesRead > 0) throw new Error(`zstd: ${filePath} is truncated (no data decompressed)`);
79
+ }
80
+
81
+ // Node before 22.15 has no zstd in zlib; the binary is the only way to read these files there.
82
+ async function* zstdBinaryLines(filePath) {
83
+ const child = spawn('zstd', ['-dc', '--', filePath], { stdio: ['ignore', 'pipe', 'ignore'] });
84
+ // Registered before any await, so a very fast exit cannot slip past it.
85
+ const closed = new Promise((resolve) => child.once('close', (code) => resolve(code)));
86
+ // A missing binary reports through 'error', not through stdout, so settle that first.
87
+ await new Promise((resolve, reject) => {
88
+ child.once('spawn', resolve);
89
+ child.once('error', (err) => reject(new Error(`cannot read ${filePath}: zstd is not available (${err.code || err.message})`)));
90
+ });
91
+ child.stdout.setEncoding('utf8');
92
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
93
+ let finished = false;
94
+ try {
95
+ for await (const line of rl) yield line;
96
+ finished = true;
97
+ } finally {
98
+ rl.close();
99
+ if (child.exitCode === null && child.signalCode === null) child.kill();
100
+ // An abandoned, paused pipe with unread data would keep 'close' from ever firing.
101
+ child.stdout.destroy();
102
+ const code = await closed;
103
+ // Only a loop that read to the end can judge the exit code; a killed child exits non-zero by design.
104
+ if (finished && code !== 0) throw new Error(`zstd exited with code ${code} for ${filePath}`);
105
+ }
106
+ }
@@ -1,4 +1,5 @@
1
1
  import { updateStatus, maybeSpawnUpdateCheck, readUpdateState, updateCheckDisabled, SESSION_START_CHECK_INTERVAL_MS } from './update-check.js';
2
+ import { orgPolicyOffer } from './org-upgrade.js';
2
3
  import { debug } from './debug.js';
3
4
 
4
5
  /** Shared by terminal renders; registry I/O stays in the detached checker. */
@@ -20,8 +21,15 @@ export function upgradeInstructions(agent = 'claude') {
20
21
  : ['sprag upgrade'];
21
22
  }
22
23
 
23
- /** The model must obtain consent; a hook never installs a package itself. */
24
- export function updateOffer(version, { agent = 'claude', lang = 'en', ...opts } = {}) {
24
+ /**
25
+ * The model must obtain consent; a hook never installs a package itself. The
26
+ * one exception is an organization minimum version (org-upgrade.js): that
27
+ * policy starts the install detached and the block only reports it.
28
+ * `orgUpgrade` carries that module's injectable options (spawn, root, now, dir).
29
+ */
30
+ export function updateOffer(version, { agent = 'claude', lang = 'en', orgUpgrade = {}, ...opts } = {}) {
31
+ const org = orgPolicyOffer(version, { agent, lang, ...orgUpgrade });
32
+ if (org) return org.text;
25
33
  const u = readUpdateChip(version, { intervalMs: SESSION_START_CHECK_INTERVAL_MS, ...opts });
26
34
  if (!u?.available || u.dismissed) return null;
27
35
  const ko = lang === 'ko';