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.
@@ -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
+
@@ -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);
@@ -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
 
@@ -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
  }