sprag-cli 3.84.0 → 3.86.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/bin/cli.js +2 -0
- package/docs/TEAM.ko.md +13 -4
- package/docs/TEAM.md +13 -4
- package/package.json +1 -1
- package/presets/agents.json +1 -1
- package/src/codex/cache-policy.js +6 -3
- package/src/codex/delegation.js +21 -3
- package/src/codex/ledger.js +2 -1
- package/src/codex/parser.js +24 -4
- package/src/commands/codex.js +2 -0
- package/src/commands/delegate.js +14 -1
- package/src/commands/route-scan.js +5 -1
- package/src/commands/team.js +20 -0
- package/src/commands/upgrade.js +137 -1
- package/src/cost.js +31 -7
- package/src/cowork-sessions.js +91 -0
- package/src/cowork-sync.js +2 -10
- package/src/delegation-agents.js +76 -6
- package/src/gateway-auth.js +33 -0
- package/src/gateway-prices.js +54 -2
- package/src/litellm-models.js +2 -3
- package/src/org-upgrade.js +179 -0
- package/src/parser.js +16 -8
- package/src/session-cache.js +10 -7
- package/src/team-sync.js +94 -29
- package/src/transcript-lines.js +66 -0
- package/src/update-notice.js +10 -2
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 =
|
|
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(
|
|
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(
|
|
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
|
-
|
|
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/session-cache.js
CHANGED
|
@@ -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(
|
|
103
|
-
const data = JSON.parse(readFileSync(
|
|
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 [
|
|
187
|
-
if (e && typeof e.mtimeMs === 'number' && e.mtimeMs >= cutoff) entries[
|
|
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(`${
|
|
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
|
}
|
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
|
|
333
|
-
* on the session's start day (unchanged
|
|
334
|
-
* servers and pages keep reading it)
|
|
335
|
-
* claude_spent_usd the same figure
|
|
336
|
-
*
|
|
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
|
-
|
|
427
|
-
|
|
428
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
529
|
-
try {
|
|
530
|
-
|
|
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
|
-
|
|
794
|
-
|
|
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 });
|
package/src/transcript-lines.js
CHANGED
|
@@ -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
|
+
}
|
package/src/update-notice.js
CHANGED
|
@@ -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
|
-
/**
|
|
24
|
-
|
|
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';
|