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.
package/src/team-sync.js CHANGED
@@ -12,6 +12,14 @@
12
12
  * team-rules.json last pulled rules (organization rules first, then team
13
13
  * rules; each row carries level 'org' or 'team')
14
14
  *
15
+ * Daily row (v2, see aggregateDaily): beside spend/saved/delegated_runs/
16
+ * family_share/model_spend it carries claude_spent_usd, codex_spent_usd,
17
+ * gateway_spent_usd (the LiteLLM gateway's own figure for this user, when one
18
+ * is configured), gateway_user_hash (a 16-hex pseudonym of the gateway user,
19
+ * so two machines of one person are counted once), total_spent_usd,
20
+ * delegated_cost_usd, codex_delegated_runs, codex_delegated_cost_usd,
21
+ * subagent_cost_usd and unpriced_parts. null means unknown, 0 means none.
22
+ *
15
23
  * Rules arrive with every full sync (5 minutes) and with the rules-only pull
16
24
  * (`team sync --rules-only`, at most hourly). Either kind rewrites the ratchet
17
25
  * files right away, so a new session picks the rules up without waiting for
@@ -36,7 +44,15 @@ import { loadLedger, modelFamily, roundUsd } from './savings-ledger.js';
36
44
  import { sessionCost, pricedParts } from './claude-price.js';
37
45
  import { uploadPrompts, dropOffsets, promptOffsetsExist } from './team-prompts.js';
38
46
  import { rulesPullDue, syncTeamRatchet, ensureTeamImport } from './team-ratchet.js';
47
+ import { parseMinVersion } from './org-upgrade.js';
39
48
  import { codexUserDir } from './agent.js';
49
+ import { loadCodexLedger, codexEventCost } from './codex/ledger.js';
50
+ import { codexDocumentEvents } from './codex/doc2md-ledger.js';
51
+ import { codexPriceBook, readCodexPrices, refreshCodexPrices, codexRunCost, CODEX_PRICES_SCHEMA } from './codex/cache-policy.js';
52
+ import { codexRequestCost } from './gateway-prices.js';
53
+ import { codexBudgetProvider } from './codex/budget.js';
54
+ import { fetchGatewayDailySpend, gatewayDayValue, gatewayEnv } from './gateway-spend.js';
55
+ import { withClaudeSettingsEnv } from './gateway-auth.js';
40
56
 
41
57
  export const PROMPT_SYNC_INTERVAL_MS = 30 * 60 * 1000;
42
58
 
@@ -152,15 +168,20 @@ export function teamSyncDue(state, now = Date.now()) {
152
168
  /**
153
169
  * Which local days a ledger sync uploads: from the day before the watermark (that
154
170
  * day was still open when it was uploaded) through today, at most 30 days. With
155
- * no watermark, the last 30 days.
171
+ * no watermark, the last 30 days. With a gateway configured the window also
172
+ * reaches back to `gatewaySyncedThrough`, the last day whose gateway figure
173
+ * went up: a sync whose gateway call failed uploaded local figures only, and
174
+ * those days are sent again (as upserts) once the gateway answers.
156
175
  */
157
- export function ledgerWindow(state, now = Date.now()) {
176
+ export function ledgerWindow(state, now = Date.now(), { gateway = false } = {}) {
158
177
  const today = new Date(now);
159
178
  const earliest = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (LEDGER_WINDOW_DAYS - 1));
160
179
  let start = earliest;
161
- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(state?.ledgerSyncedThrough || ''));
162
- if (m) {
163
- const from = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]) - 1);
180
+ const marks = [state?.ledgerSyncedThrough];
181
+ if (gateway) marks.push(state?.gatewaySyncedThrough);
182
+ const parsed = marks.map((v) => /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(v || '')));
183
+ if (parsed.every(Boolean)) {
184
+ const from = parsed.map((m) => new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]) - 1)).sort((a, b) => a - b)[0];
164
185
  if (from > earliest) start = from;
165
186
  }
166
187
  const startKey = dayKey(start.getTime());
@@ -304,32 +325,90 @@ function dayKey(ms) {
304
325
 
305
326
  const round4 = (n) => Math.round(n * 10000) / 10000;
306
327
 
328
+ /** A Codex session's usage in codexRunCost's shape: `input` includes the cached and written parts. */
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 });
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
+
307
350
  /**
308
351
  * Per-day rows, oldest first, only days with activity inside the window.
309
- * saved_usd honours the `sprag saved reset` marks (events before a mark are
310
- * skipped), the same way the ledger totals do. delegated_errors is always null:
311
- * the ledger carries no error flag.
352
+ *
353
+ * Money fields (all rounded to 4 decimals):
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
360
+ * codex_spent_usd Codex rollouts priced by the path they took (gateway
361
+ * prices for a LiteLLM provider, OpenAI list prices for
362
+ * direct calls); unpriced sessions count in unpriced_parts
363
+ * gateway_spent_usd the gateway's own daily figure for this user; null
364
+ * without a gateway, outside the days it covers, or
365
+ * when the call failed
366
+ * total_spent_usd gateway_spent_usd when known, else claude + codex;
367
+ * null only when the gateway call failed (so the server
368
+ * keeps the value an earlier sync stored)
369
+ * delegated_cost_usd what the runs sprag's rules delegated cost (Claude
370
+ * ledger `cost` plus Codex ledger cost); delegated_runs
371
+ * counts the same runs, Claude and Codex together
372
+ * saved_usd routing and doc2md savings, Claude and Codex; the
373
+ * only figure that honours the `sprag saved reset`
374
+ * marks (a reset is a stopwatch, not a refund)
375
+ * family_share covers Claude delegations only (the pages read haiku/sonnet/
376
+ * opus). delegated_errors is always null: the ledgers carry no error flag.
377
+ * Every source is injectable for tests; nothing here touches the network.
312
378
  */
313
- export async function aggregateDaily({ now = Date.now(), dir = userDataDir(), days = 30, sessions = null } = {}) {
379
+ export async function aggregateDaily({
380
+ now = Date.now(), dir = userDataDir(), days = 30, sessions = null,
381
+ coworkSessions = null, codexSessions = null, codexLedger = null, codexDocEvents = null, codexPrices = undefined, gatewayDaily = null, env = process.env,
382
+ } = {}) {
314
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);
315
388
  const doc2md = require('./doc2md-ledger.cjs');
316
389
  const cutoff = now - days * 24 * 3600 * 1000;
317
390
  const byDay = new Map();
318
391
  const get = (day) => {
319
- if (!byDay.has(day)) byDay.set(day, { spent: 0, saved: 0, runs: 0, fam: new Map() });
392
+ if (!byDay.has(day)) {
393
+ byDay.set(day, { spent: 0, subagent: 0, codex: 0, saved: 0, runs: 0, cost: 0, codexRuns: 0, codexCost: 0, unpriced: 0, fam: new Map(), models: new Map() });
394
+ }
320
395
  return byDay.get(day);
321
396
  };
397
+ const inWindow = (ts) => Number.isFinite(ts) && ts >= cutoff && ts <= now;
322
398
  let marks = {};
323
399
  try { marks = readResetMarks(dir) || {}; } catch (e) { debug('team-sync', e); }
324
400
 
401
+ // Claude delegation ledger: runs and their cost regardless of reset marks,
402
+ // savings and family share only after the mark.
325
403
  try {
326
404
  for (const e of Object.values(loadLedger().events)) {
327
- if (!Number.isFinite(e.ts) || e.ts < cutoff || e.ts > now) continue;
328
- if (isBeforeReset(e.ts, marks.routing)) continue;
405
+ if (!inWindow(e.ts)) continue;
329
406
  const d = get(dayKey(e.ts));
407
+ d.runs += 1;
408
+ if (Number.isFinite(e.cost)) d.cost += e.cost; else d.unpriced += 1;
409
+ if (isBeforeReset(e.ts, marks.routing)) continue;
330
410
  const usd = Number(e.usd);
331
411
  if (Number.isFinite(usd)) d.saved += usd;
332
- d.runs += 1;
333
412
  const fam = modelFamily(e.to);
334
413
  d.fam.set(fam, (d.fam.get(fam) || 0) + 1);
335
414
  }
@@ -337,46 +416,169 @@ export async function aggregateDaily({ now = Date.now(), dir = userDataDir(), da
337
416
 
338
417
  try {
339
418
  for (const e of Object.values(doc2md.loadLedger(dir).events)) {
340
- if (!Number.isFinite(e.ts) || e.ts < cutoff || e.ts > now) continue;
341
- if (isBeforeReset(e.ts, marks.doc2md)) continue;
419
+ if (!inWindow(e.ts) || isBeforeReset(e.ts, marks.doc2md)) continue;
342
420
  get(dayKey(e.ts)).saved += Number(e.usd) || 0;
343
421
  }
344
422
  } catch (e) { debug('team-sync', e); }
345
423
 
424
+ // Codex delegation ledger, the same rules; the event's cost is recomputed
425
+ // from its tokens when it predates the `cost` field.
426
+ try {
427
+ const events = Object.values((codexLedger || loadCodexLedger({ dir })).events || {});
428
+ for (const e of events) {
429
+ if (!inWindow(e.ts)) continue;
430
+ const d = get(dayKey(e.ts));
431
+ d.codexRuns += 1;
432
+ const cost = codexEventCost(e);
433
+ if (cost !== null) d.codexCost += cost; else d.unpriced += 1;
434
+ if (isBeforeReset(e.ts, marks['codex-routing'])) continue;
435
+ if (Number.isFinite(e.usd)) d.saved += e.usd;
436
+ }
437
+ } catch (e) { debug('team-sync', e); }
438
+
439
+ try {
440
+ for (const e of codexDocEvents || codexDocumentEvents({ dir })) {
441
+ if (!inWindow(e.ts) || isBeforeReset(e.ts, marks['codex-docs'])) continue;
442
+ if (Number.isFinite(e.usd)) get(dayKey(e.ts)).saved += e.usd;
443
+ }
444
+ } catch (e) { debug('team-sync', e); }
445
+
446
+ const addModel = (d, model, usd) => {
447
+ // Spend per model family (opus, sonnet, gpt-6-sol, ...), so the console can
448
+ // show which models each person spends on. Unknown models keep a short raw name.
449
+ const fam = String(modelFamily(model)).slice(0, 40);
450
+ d.models.set(fam, (d.models.get(fam) || 0) + usd);
451
+ };
452
+
453
+ // Claude Code and Cowork sessions are priced alike; Cowork transcripts live
454
+ // outside ~/.claude/projects (see cowork-sessions.js).
455
+ const addClaudeSessions = (list) => {
456
+ for (const s of list || []) {
457
+ if (!s || !s.startTime || !s.totals) continue;
458
+ const t = new Date(s.startTime).getTime();
459
+ if (!inWindow(t)) continue;
460
+ const d = get(dayKey(t));
461
+ for (const part of pricedParts(s)) {
462
+ try {
463
+ const c = sessionCost(part.totals, part.model, { env });
464
+ if (!c) { d.unpriced += 1; continue; }
465
+ d.spent += c.actual;
466
+ if (!part.own) d.subagent += c.actual;
467
+ addModel(d, part.model, c.actual);
468
+ } catch (e) { debug('team-sync', e); }
469
+ }
470
+ }
471
+ };
472
+
346
473
  try {
347
474
  let list = sessions;
348
475
  if (!list) {
349
476
  const { parseAllSessions } = await import('./parser.js');
350
477
  list = await parseAllSessions({ days });
351
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);
489
+ } catch (e) { debug('team-sync', e); }
490
+
491
+ // Codex sessions: priced per model from the rollout usage records, on the
492
+ // session's start day like Claude. Child sessions count as subagent cost.
493
+ try {
494
+ let list = codexSessions;
495
+ if (!list) {
496
+ const { parseAllCodexSessions } = await import('./codex/parser.js');
497
+ list = await parseAllCodexSessions({ days, compressed: true, keepRequests: true });
498
+ }
499
+ const prices = codexPrices === undefined ? readCodexPrices({ now, dir }) : codexPrices;
352
500
  for (const s of list || []) {
353
501
  if (!s || !s.startTime || !s.totals) continue;
354
502
  const t = new Date(s.startTime).getTime();
355
- if (!Number.isFinite(t) || t < cutoff || t > now) continue;
356
- let cost = 0;
357
- for (const part of pricedParts(s)) {
358
- try {
359
- const c = sessionCost(part.totals, part.model);
360
- if (c) cost += c.actual;
361
- } catch (e) { debug('team-sync', e); }
503
+ if (!inWindow(t)) continue;
504
+ const d = get(dayKey(t));
505
+ const book = codexPriceBook(s.provider, prices);
506
+ for (const [model, usd] of codexSessionCosts(s, book)) {
507
+ if (usd === null) { d.unpriced += 1; continue; }
508
+ d.codex += usd;
509
+ if (s.isSubagent) d.subagent += usd;
510
+ addModel(d, model, usd);
362
511
  }
363
- get(dayKey(t)).spent += cost;
364
512
  }
365
513
  } catch (e) { debug('team-sync', e); }
366
514
 
515
+ // Gateway days with spend but no local record still get a row: that is the
516
+ // "unrecorded usage" the console shows.
517
+ const gw = gatewayDaily && !gatewayDaily.error && gatewayDaily.days ? gatewayDaily : null;
518
+ const gwFailed = !!(gatewayDaily && gatewayDaily.error);
519
+ if (gw) {
520
+ for (const [day, usd] of gw.days) {
521
+ if (usd > 0 && day >= dayKey(cutoff) && day <= dayKey(now)) get(day);
522
+ }
523
+ }
524
+
367
525
  return [...byDay.entries()]
368
526
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
369
- .filter(([, d]) => d.spent || d.saved || d.runs)
370
- .map(([day, d]) => ({
371
- day,
372
- spent_usd: round4(d.spent),
373
- saved_usd: round4(d.saved),
374
- delegated_runs: d.runs,
375
- delegated_errors: null,
376
- family_share: Object.fromEntries(
377
- [...d.fam.entries()].map(([f, n]) => [f, Math.round((n / d.runs) * 1000) / 1000]),
378
- ),
379
- }));
527
+ .map(([day, d]) => {
528
+ const claude = round4(d.spent), codex = round4(d.codex);
529
+ const gateway = gw ? gatewayDayValue(gw, day) : null;
530
+ const total = gwFailed ? null : gateway !== null ? round4(gateway) : round4(claude + codex);
531
+ return {
532
+ day,
533
+ spent_usd: claude,
534
+ saved_usd: round4(d.saved),
535
+ delegated_runs: d.runs + d.codexRuns,
536
+ delegated_errors: null,
537
+ family_share: Object.fromEntries(
538
+ [...d.fam.entries()].map(([f, n]) => [f, Math.round((n / d.runs) * 1000) / 1000]),
539
+ ),
540
+ model_spend: Object.fromEntries(
541
+ [...d.models.entries()].map(([f, usd]) => [f, round4(usd)]).filter(([, usd]) => usd > 0),
542
+ ),
543
+ claude_spent_usd: claude,
544
+ codex_spent_usd: codex,
545
+ gateway_spent_usd: gateway === null ? null : round4(gateway),
546
+ gateway_user_hash: gw ? gw.userHash : null,
547
+ total_spent_usd: total,
548
+ delegated_cost_usd: round4(d.cost + d.codexCost),
549
+ codex_delegated_runs: d.codexRuns,
550
+ codex_delegated_cost_usd: round4(d.codexCost),
551
+ subagent_cost_usd: round4(d.subagent),
552
+ unpriced_parts: d.unpriced,
553
+ };
554
+ })
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);
556
+ }
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
+
561
+ /**
562
+ * The Codex price table for the upload, refreshed once from the gateway when
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.
567
+ */
568
+ async function codexPricesForSync({ dir, now, fetchImpl, attemptedAt }) {
569
+ const cached = readCodexPrices({ now, dir });
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 };
574
+ let provider = null;
575
+ try { provider = codexBudgetProvider(); } catch (e) { debug('team-sync:codex-prices', e); }
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 };
380
582
  }
381
583
 
382
584
  // Device info: OS name and OS version. The CPU architecture is not sent: the
@@ -526,18 +728,22 @@ async function pullRules({ memberKey, dir, fetch, now }) {
526
728
  const rules = Array.isArray(r.rules) ? r.rules : [];
527
729
  writeStateFile(teamRulesCachePath(dir), JSON.stringify({
528
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),
529
732
  plan: r.plan, promptCapture: !!r.prompt_capture, rules, removed: Array.isArray(r.removed) ? r.removed : [],
530
733
  }, null, 2) + '\n');
531
734
  return { r, rules };
532
735
  }
533
736
 
534
737
  /** State fields a rules pull refreshes. */
535
- function withRulesMeta(state, r, now) {
738
+ export function withRulesMeta(state, r, now) {
536
739
  const next = { ...state, lastRulesAt: now };
537
740
  if (r.team_name) next.teamName = r.team_name;
538
741
  if (r.plan) next.plan = r.plan;
539
742
  if (r.org_name) next.orgName = r.org_name;
540
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);
541
747
  delete next.lastRulesError;
542
748
  return next;
543
749
  }
@@ -557,8 +763,15 @@ export function refreshTeamRatchetFiles({ dir = userDataDir() } = {}) {
557
763
  return out;
558
764
  }
559
765
 
766
+ /**
767
+ * `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
768
+ * is injected separately so tests can fake each side). `coworkSessions`, `codexSessions`,
769
+ * `codexLedger`, `codexDocEvents` and `codexPrices` pass straight to
770
+ * aggregateDaily.
771
+ */
560
772
  export async function syncTeam({
561
773
  now = Date.now(), dir = userDataDir(), fetch, force = false, env = process.env, version, sessions, promptsOnly = false, rulesOnly = false,
774
+ gatewayFetch = globalThis.fetch, coworkSessions, codexSessions, codexLedger, codexDocEvents, codexPrices,
562
775
  } = {}) {
563
776
  let state = loadTeamState(dir);
564
777
  // The switch stops every usage upload. A joined machine still tells the
@@ -623,12 +836,34 @@ export async function syncTeam({
623
836
  try { saveTeamState(state, dir); } catch (e) { debug('team-sync', e); }
624
837
  state = await reportDeviceInfo({ state, dir, fetch, env });
625
838
  try {
626
- const win = ledgerWindow(state, now);
627
- const rows = (await aggregateDaily({ now, dir, sessions, days: win.days }))
839
+ // The gateway's daily figure, when one is configured. A failed call does
840
+ // not stop the upload: those days go up with local figures and null
841
+ // totals (the server keeps what it already has), and gatewaySyncedThrough
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);
847
+ const hasGateway = !!gatewayEnv(env);
848
+ let gatewayDaily = null;
849
+ if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now });
850
+ const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
851
+ const win = ledgerWindow(state, now, { gateway: hasGateway });
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 }))
628
860
  .filter((r) => r.day >= win.startKey).slice(-MAX_ROWS);
629
861
  await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
630
862
  const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
631
863
  const next = withRulesMeta({ ...state, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, r, now);
864
+ if (gatewayOk) next.gatewaySyncedThrough = dayKey(now);
865
+ else if (gatewayDaily && gatewayDaily.error) next.lastGatewayError = gatewayDaily.error;
866
+ if (gatewayOk || !hasGateway) delete next.lastGatewayError;
632
867
  delete next.syncFailures;
633
868
  delete next.lastError;
634
869
  saveTeamState(next, dir);
@@ -701,6 +936,6 @@ export function autoJoinNotice(state, lang = 'en') {
701
936
  state.autoJoinNoticePending = false;
702
937
  const name = state.teamName || '';
703
938
  return lang === 'ko'
704
- ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출·절감·위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
705
- : `Sprag: this machine was enrolled in team "${name}" through SPRAG_TEAM_TOKEN. It sends daily aggregates only (spend, savings, delegation counts). See what is sent with \`sprag team status --show-payload\`; stop with \`sprag team leave\`.`;
939
+ ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude·Codex·게이트웨이), 위임 비용, 절감, 위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
940
+ : `Sprag: this machine was enrolled in team "${name}" through SPRAG_TEAM_TOKEN. It sends daily aggregates only (spend across Claude, Codex and the gateway, delegation cost, savings, delegation counts). See what is sent with \`sprag team status --show-payload\`; stop with \`sprag team leave\`.`;
706
941
  }
@@ -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';