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.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The organization minimum version: the one case where a hook starts an
3
+ * install without asking.
4
+ *
5
+ * The sprag operator sets a minimum version per organization in the ops
6
+ * console. The rules pull stores it in team.json as `minVersion`. A session
7
+ * start on a machine below it starts `sprag upgrade --org-policy` detached and
8
+ * tells the model that it did, so the member hears about it without being
9
+ * asked and without the model installing anything itself. Everyone else keeps
10
+ * the consent-only offer in update-notice.js.
11
+ *
12
+ * org-upgrade.json (in the user data dir) is the record both sides share:
13
+ * `{ target, from, startedAt, pid, finishedAt, ok, error, announced }`. The
14
+ * statusline and the hooks import this module, so it stays on node builtins
15
+ * and small leaf modules; the runner that installs lives in
16
+ * src/commands/upgrade.js.
17
+ */
18
+
19
+ import { existsSync, readFileSync } from 'node:fs';
20
+ import { dirname, join } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { userDataDir } from './paths.js';
23
+ import { writeStateFile } from './state-file.js';
24
+ import { isNewer } from './update-check.js';
25
+ import { isDetachedChild, spawnDetachedCli } from './cli-entry.js';
26
+ import { readTeamState, isJoined } from './team-ratchet.js';
27
+ import { debug } from './debug.js';
28
+
29
+ /** A running attempt older than this is treated as dead, whatever its pid says. */
30
+ export const ORG_UPGRADE_INFLIGHT_MS = 30 * 60 * 1000;
31
+ /** After an attempt ends, this long before the next session starts another. */
32
+ export const ORG_UPGRADE_RETRY_MS = 60 * 60 * 1000;
33
+
34
+ const MIN_VERSION_RE = /^\d+\.\d+\.\d+$/;
35
+
36
+ /** 'X.Y.Z' when the server sent a usable minimum, else null. */
37
+ export function parseMinVersion(v) {
38
+ return typeof v === 'string' && MIN_VERSION_RE.test(v.trim()) ? v.trim() : null;
39
+ }
40
+
41
+ export const orgUpgradePath = (dir = userDataDir()) => join(dir, 'org-upgrade.json');
42
+ export const orgUpgradeLogPath = (dir = userDataDir()) => join(dir, 'org-upgrade.log');
43
+
44
+ export function readOrgUpgrade(dir = userDataDir()) {
45
+ try {
46
+ const s = JSON.parse(readFileSync(orgUpgradePath(dir), 'utf8'));
47
+ return s && typeof s === 'object' && !Array.isArray(s) ? s : {};
48
+ } catch {
49
+ return {};
50
+ }
51
+ }
52
+
53
+ /** Merge `patch` into the record and return the result. */
54
+ export function writeOrgUpgrade(patch, dir = userDataDir()) {
55
+ const next = { ...readOrgUpgrade(dir), ...patch };
56
+ writeStateFile(orgUpgradePath(dir), JSON.stringify(next, null, 2) + '\n');
57
+ return next;
58
+ }
59
+
60
+ /** The organization's minimum for a joined member, or null. */
61
+ export function orgMinVersion(state) {
62
+ return isJoined(state) ? parseMinVersion(state.minVersion) : null;
63
+ }
64
+
65
+ /** The version the machine must reach, or null when it already meets the minimum or none is set. */
66
+ export function orgUpgradeTarget(version, state) {
67
+ const min = orgMinVersion(state);
68
+ return min && isNewer(min, version) ? min : null;
69
+ }
70
+
71
+ export function pidAlive(pid) {
72
+ if (!Number.isInteger(pid) || pid <= 0) return false;
73
+ try { process.kill(pid, 0); return true; } catch (e) { return e && e.code === 'EPERM'; }
74
+ }
75
+
76
+ /** Whether an attempt is running now: unfinished, recent, and its process (once known) alive. */
77
+ export function orgUpgradeInFlight(rec, { now = Date.now(), isAlive = pidAlive } = {}) {
78
+ if (!rec || rec.finishedAt || !Number.isFinite(rec.startedAt)) return false;
79
+ if (now - rec.startedAt >= ORG_UPGRADE_INFLIGHT_MS) return false;
80
+ return rec.pid == null || isAlive(rec.pid);
81
+ }
82
+
83
+ /** A copy running from a git checkout is a developer's; it must never replace itself. */
84
+ export function isDevCheckout(root = dirname(dirname(fileURLToPath(import.meta.url)))) {
85
+ return existsSync(join(root, '.git'));
86
+ }
87
+
88
+ /**
89
+ * Start the background upgrade when the policy calls for one. Returns
90
+ * `{ status, target }` with status one of: none (nothing required), child
91
+ * (this process is itself detached), dev, in-flight, cooldown, started,
92
+ * spawn-failed.
93
+ */
94
+ export function maybeStartOrgUpgrade(version, {
95
+ agent = 'claude', env = process.env, now = Date.now(), dir = userDataDir(), spawn, root, state, isAlive,
96
+ } = {}) {
97
+ const target = orgUpgradeTarget(version, state || readTeamState(dir));
98
+ if (!target) return { status: 'none', target: null };
99
+ if (isDetachedChild(env)) return { status: 'child', target };
100
+ if (isDevCheckout(root)) return { status: 'dev', target };
101
+ const rec = readOrgUpgrade(dir);
102
+ if (orgUpgradeInFlight(rec, { now, isAlive })) return { status: 'in-flight', target };
103
+ // Any attempt that ended inside the last hour also holds off the next: a
104
+ // failure for the reason below, and a success that left this copy below the
105
+ // minimum because the install went to a different copy than the one running.
106
+ if (Number.isFinite(rec.finishedAt) && now - rec.finishedAt < ORG_UPGRADE_RETRY_MS) return { status: 'cooldown', target };
107
+ writeOrgUpgrade({
108
+ target, from: version, startedAt: now, pid: null, finishedAt: null, ok: null, error: null, announced: false,
109
+ }, dir);
110
+ let started = false;
111
+ try {
112
+ started = spawnDetachedCli(['upgrade', '--org-policy', '--agent', agent], { env, ...(spawn ? { spawn } : {}) });
113
+ } catch (e) {
114
+ debug('org-upgrade:spawn', e);
115
+ writeOrgUpgrade({ finishedAt: now, ok: false, error: `could not start: ${e && e.message ? e.message : e}`, announced: false }, dir);
116
+ return { status: 'spawn-failed', target };
117
+ }
118
+ if (!started) {
119
+ writeOrgUpgrade({ finishedAt: now, ok: false, error: 'could not start the background upgrade', announced: false }, dir);
120
+ return { status: 'spawn-failed', target };
121
+ }
122
+ return { status: 'started', target };
123
+ }
124
+
125
+ /**
126
+ * One short block for the session context, or null. Informational only: it
127
+ * never tells the model to install anything. A success or failure is reported
128
+ * once (`announced`), at the first session that can see it.
129
+ */
130
+ export function orgUpgradeNotice(version, { lang = 'en', status, dir = userDataDir() } = {}) {
131
+ const ko = lang === 'ko';
132
+ try {
133
+ if (status && status.status === 'started') {
134
+ return ko
135
+ ? `[sprag 조직 정책] 조직 정책에 따라 최소 버전 v${status.target} 가 필요해 백그라운드에서 업그레이드를 시작했습니다. 다음 세션부터 새 버전이 적용됩니다.`
136
+ : `[sprag org policy] The organization requires at least v${status.target}, so an upgrade was started in the background. The new version applies from the next session.`;
137
+ }
138
+ const rec = readOrgUpgrade(dir);
139
+ if (rec.announced || !rec.target || !Number.isFinite(rec.finishedAt)) return null;
140
+ if (rec.ok === true && !isNewer(rec.target, version)) {
141
+ writeOrgUpgrade({ announced: true }, dir);
142
+ return ko
143
+ ? `[sprag 조직 정책] 조직 최소 버전 v${rec.target} 로의 업그레이드가 끝났습니다. 현재 v${version} 가 실행 중입니다.`
144
+ : `[sprag org policy] The upgrade to the organization minimum v${rec.target} finished. Running v${version}.`;
145
+ }
146
+ if (rec.ok === false && isNewer(rec.target, version)) {
147
+ writeOrgUpgrade({ announced: true }, dir);
148
+ const reason = String(rec.error || 'unknown').slice(0, 200);
149
+ return ko
150
+ ? `[sprag 조직 정책] 조직 최소 버전 v${rec.target} 로의 자동 업그레이드가 실패했습니다: ${reason}. 사용자에게 알리고 sprag upgrade 를 직접 실행하도록 안내하십시오.`
151
+ : `[sprag org policy] The automatic upgrade to the organization minimum v${rec.target} failed: ${reason}. Tell the user to run sprag upgrade themselves.`;
152
+ }
153
+ } catch (e) {
154
+ debug('org-upgrade:notice', e);
155
+ }
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * What the session-start offer asks first. `{ text }` means the org policy
161
+ * owns this session's answer (text may be null: say nothing and skip the
162
+ * consent offer); null means it has nothing to say and today's offer applies.
163
+ */
164
+ export function orgPolicyOffer(version, { agent = 'claude', lang = 'en', dir = userDataDir(), ...opts } = {}) {
165
+ try {
166
+ const state = readTeamState(dir);
167
+ const status = maybeStartOrgUpgrade(version, { agent, dir, state, ...opts });
168
+ if (status.status === 'none') {
169
+ const text = orgUpgradeNotice(version, { lang, dir });
170
+ return text ? { text } : null;
171
+ }
172
+ // A dev checkout and a detached child keep today's behaviour.
173
+ if (status.status === 'child' || status.status === 'dev') return null;
174
+ return { text: orgUpgradeNotice(version, { lang, status, dir }) };
175
+ } catch (e) {
176
+ debug('org-upgrade:offer', e);
177
+ return null;
178
+ }
179
+ }
package/src/parser.js CHANGED
@@ -291,10 +291,13 @@ export async function getLastUserMessageTime(filePath) {
291
291
 
292
292
  /**
293
293
  * Discover all session JSONL files under ~/.claude/projects/
294
+ *
295
+ * `options.root` scans another projects directory (Cowork keeps one per session);
296
+ * `options.now` is the clock the `days` cutoff counts back from.
294
297
  */
295
298
  export async function discoverSessionFiles(options = {}) {
296
- const { projectFilter, days = 30, excludeSessionPath } = options;
297
- const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
299
+ const { projectFilter, days = 30, excludeSessionPath, root = CLAUDE_DIR, now = Date.now() } = options;
300
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
298
301
  const files = [];
299
302
  // Resolve the excluded session to an absolute path so equality checks are exact.
300
303
  // Use path.isAbsolute() so Windows paths like C:\... are recognized too.
@@ -304,7 +307,7 @@ export async function discoverSessionFiles(options = {}) {
304
307
 
305
308
  let projectDirs;
306
309
  try {
307
- projectDirs = await readdir(CLAUDE_DIR);
310
+ projectDirs = await readdir(root);
308
311
  } catch {
309
312
  return files;
310
313
  }
@@ -312,7 +315,7 @@ export async function discoverSessionFiles(options = {}) {
312
315
  for (const projDir of projectDirs) {
313
316
  if (projectFilter && !projDir.includes(projectFilter)) continue;
314
317
 
315
- const projPath = join(CLAUDE_DIR, projDir);
318
+ const projPath = join(root, projDir);
316
319
  let entries;
317
320
  try {
318
321
  entries = await readdir(projPath);
@@ -354,7 +357,7 @@ export async function discoverSessionFiles(options = {}) {
354
357
  * `<session id>/subagents/agent-*.jsonl`. Their requests are billed like any
355
358
  * other and appear nowhere in the session's own transcript.
356
359
  */
357
- async function listSubagentFiles(sessionDir, projectDir, cutoff) {
360
+ export async function listSubagentFiles(sessionDir, projectDir, cutoff) {
358
361
  const dir = join(sessionDir, 'subagents');
359
362
  let entries;
360
363
  try {
@@ -405,6 +408,8 @@ export function dedupeSessionFiles(files) {
405
408
  *
406
409
  * @param {object} [options] forwarded to discoverSessionFiles
407
410
  * @param {boolean} [options.noCache=false] bypass the cache entirely
411
+ * @param {object[]} [options.files] pre-discovered files; skips discovery
412
+ * @param {string} [options.cachePath] cache file to use instead of the default
408
413
  */
409
414
  function spansCutoff(session, cutoffMs) {
410
415
  return !!(session.startTime && session.startTime.getTime() < cutoffMs);
@@ -449,11 +454,14 @@ function withSinceTrim(summary, full, sinceMs) {
449
454
  }
450
455
 
451
456
  export async function parseAllSessions(options = {}) {
452
- const files = await discoverSessionFiles(options);
457
+ // `options.files` is a list already discovered in discoverSessionFiles's
458
+ // shape (Cowork lives outside ~/.claude/projects); `options.cachePath` keeps
459
+ // such a source's entries out of the main session cache.
460
+ const files = options.files ?? await discoverSessionFiles(options);
453
461
  const concurrency = 10;
454
462
  const results = [];
455
463
  const useCache = !options.noCache;
456
- const cache = useCache ? loadCache() : { entries: {} };
464
+ const cache = useCache ? loadCache(options.cachePath) : { entries: {} };
457
465
  let misses = 0;
458
466
  // The file-level mtime filter (discoverSessionFiles) is only a cheap
459
467
  // pre-selection: a session started months ago but touched today passes it,
@@ -488,7 +496,7 @@ export async function parseAllSessions(options = {}) {
488
496
  results.push(...parsed.filter(Boolean));
489
497
  }
490
498
 
491
- if (useCache && misses > 0) saveCache(cache);
499
+ if (useCache && misses > 0) saveCache(cache, options.cachePath);
492
500
 
493
501
  return results.filter((s) => s.requestCount > 0);
494
502
 
package/src/route-scan.js CHANGED
@@ -681,9 +681,9 @@ export async function runRouteScan({ days = 14 } = {}) {
681
681
  //
682
682
  // What counts as a routing saving is narrower than what counts for
683
683
  // rule-health above. A saving is the price difference a REGISTERED RULE
684
- // caused: the model that used to handle this category (the rule's baseline,
685
- // learned from episodes an expensive model handled directly) versus the
686
- // model the run actually used. Subagent runs that no rule covers —
684
+ // caused: the model that would have done the work (the episode's own main
685
+ // model, the same counterfactual rule health uses) versus the model the run
686
+ // actually used. Subagent runs that no rule covers —
687
687
  // Explore, a hand-written agent, a plugin's own subagent — would have gone
688
688
  // to the same cheap model with or without this tool, so attributing their
689
689
  // savings here would credit the tool for work it did not route.
@@ -697,7 +697,11 @@ export async function runRouteScan({ days = 14 } = {}) {
697
697
  } catch { /* no registry → no attributable savings, which is the honest zero */ }
698
698
  // A rule's baseline: what it stored at promotion, else what this scan still
699
699
  // observes handling the category directly (a rule promoted before baselines
700
- // existed backfills on the next refresh).
700
+ // existed backfills on the next refresh). The ledger only falls back to it
701
+ // when an episode's main model has no price: the model stored at promotion
702
+ // goes stale as soon as the user moves the main session to a newer model
703
+ // (opus-5 rules kept pricing savings at opus-5 rates under an opus-5-5
704
+ // main model, inflating every figure).
701
705
  const baselineFor = (rule, tier, catId, projectDir) => {
702
706
  if (rule.baselineModel) return rule.baselineModel;
703
707
  const s = episodeStats.get(`${tier}|${catId}|${projectDir}`)
@@ -746,15 +750,16 @@ export async function runRouteScan({ days = 14 } = {}) {
746
750
  const saved = runSaving(run, mainModel);
747
751
  bumpDelegated(`${runTier}|${cat.id}|${projectDir}`, run, saved);
748
752
  bumpDelegated(`${runTier}|${cat.id}|*`, run, saved);
749
- // Routing saving: priced against the rule's baseline (before → after),
750
- // not against whatever the session's priciest model happened to be.
753
+ // Routing saving: priced against the episode's main model (before →
754
+ // after); the rule's stored baseline is only the fallback when that
755
+ // model has no price.
751
756
  const rule = ruleForRun(runTier, cat.id, projectDir);
752
757
  if (!rule) continue; // no rule routed this run — not our saving to claim
753
758
  if (!ruleCouldHaveRouted(rule, run)) continue; // it did not exist yet
754
759
  // Priced below, after this scan's baselines have been written back to
755
760
  // the registry — see the note at the ledger write.
756
761
  if (!isRecognizedModelId(run.model)) continue;
757
- ledgerEvents.push({ run, rule, tier: runTier, catId: cat.id, projectDir });
762
+ ledgerEvents.push({ run, rule, tier: runTier, catId: cat.id, projectDir, mainModel });
758
763
  }
759
764
  }
760
765
  }
@@ -878,7 +883,11 @@ export async function runRouteScan({ days = 14 } = {}) {
878
883
  const priced = [];
879
884
  for (const e of ledgerEvents) {
880
885
  const rule = fresh.find((r) => r.signature === e.rule.signature) || e.rule;
881
- const baseline = baselineFor(rule, e.tier, e.catId, e.projectDir);
886
+ // The episode's main model is what would have done the work today; the
887
+ // rule's promotion-time baseline only stands in when it is unpriced.
888
+ const baseline = e.mainModel && isRecognizedModelId(e.mainModel)
889
+ ? e.mainModel
890
+ : baselineFor(rule, e.tier, e.catId, e.projectDir);
882
891
  // Both sides of the comparison must be ids the pricing table really
883
892
  // recognizes. A house alias from a company gateway prices as Sonnet by
884
893
  // default, which would fabricate a saving against a cheap baseline or
@@ -95,12 +95,15 @@ function deserialize(stored, filePath, projectDir) {
95
95
  * Load the cache into a plain object. Any problem (missing file, bad JSON,
96
96
  * version bump) yields an empty cache — the caller just re-parses.
97
97
  *
98
+ * `path` defaults to the main cache; Cowork passes its own file so thousands of
99
+ * its transcripts never bloat the one the statusline loads every few seconds.
100
+ *
98
101
  * @returns {{ entries: Record<string, {mtimeMs:number,size:number,s:object}> }}
99
102
  */
100
- export function loadCache() {
103
+ export function loadCache(path = CACHE_PATH) {
101
104
  try {
102
- if (!existsSync(CACHE_PATH)) return { entries: {} };
103
- const data = JSON.parse(readFileSync(CACHE_PATH, 'utf8'));
105
+ if (!existsSync(path)) return { entries: {} };
106
+ const data = JSON.parse(readFileSync(path, 'utf8'));
104
107
  if (!data || data.version !== CACHE_VERSION || !data.entries || typeof data.entries !== 'object') {
105
108
  return { entries: {} };
106
109
  }
@@ -177,16 +180,16 @@ export function putCachedSince(cache, file, sinceMs, session) {
177
180
  * on Windows for same-volume replaces, so a reader never sees a partial file.
178
181
  * Best-effort: a write failure just means the next run re-parses.
179
182
  */
180
- export function saveCache(cache) {
183
+ export function saveCache(cache, path = CACHE_PATH) {
181
184
  try {
182
185
  const dir = userDataDir();
183
186
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
184
187
  const cutoff = Date.now() - PRUNE_AFTER_MS;
185
188
  const entries = {};
186
- for (const [path, e] of Object.entries(cache.entries)) {
187
- if (e && typeof e.mtimeMs === 'number' && e.mtimeMs >= cutoff) entries[path] = e;
189
+ for (const [transcript, e] of Object.entries(cache.entries)) {
190
+ if (e && typeof e.mtimeMs === 'number' && e.mtimeMs >= cutoff) entries[transcript] = e;
188
191
  }
189
- writeViaTmp(`${CACHE_PATH}.${process.pid}.tmp`, CACHE_PATH, JSON.stringify({ version: CACHE_VERSION, entries }) + '\n');
192
+ writeViaTmp(`${path}.${process.pid}.tmp`, path, JSON.stringify({ version: CACHE_VERSION, entries }) + '\n');
190
193
  } catch (e) {
191
194
  debug('session-cache:save', e); // best-effort — never block a report
192
195
  }
@@ -271,6 +271,6 @@ export function autoJoinNoticeBlock(dir = userDataDir(), lang = userLanguage())
271
271
  try { writeStateFile(file, `${JSON.stringify({ ...state, autoJoinNoticePending: false }, null, 2)}\n`); }
272
272
  catch (e) { debug('team-ratchet:notice-clear', e); }
273
273
  return lang === 'ko'
274
- ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출·절감·위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
275
- : `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\`.`;
274
+ ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude·Codex·게이트웨이), 위임 비용, 절감, 위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
275
+ : `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\`.`;
276
276
  }