sprag-cli 3.82.0 → 3.84.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/docs/TEAM.ko.md CHANGED
@@ -12,8 +12,18 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
12
12
  |---|---|
13
13
  | 지출(USD) | 로컬 세션 로그로 계산한 금액 |
14
14
  | 절감(USD) | 라우팅 원장과 doc2md 원장에서 가져온 금액 |
15
- | 위임 실행 횟수 | 그날 위임한 실행의 수 |
15
+ | 위임 실행 횟수 | 그날 위임한 Claude와 Codex 실행의 수 |
16
16
  | 모델 계열 비중 | 위임 실행 중 모델 계열별 비율 |
17
+ | 모델 계열별 지출(USD) | 그날 지출을 모델 계열(`opus`, `sonnet`, `haiku`, `fable` 등)별로 나눈 금액입니다. 콘솔에서 사람마다 어느 모델에 돈을 쓰는지 보여 주는 데 쓰며, 3.84.0부터 보냅니다 |
18
+ | Claude 지출(USD) | Claude Code 로컬 지출입니다. 메인 세션과 서브에이전트 실행을 합친 금액이며 지출(USD)과 같은 값입니다. 3.84.0부터 보냅니다 |
19
+ | Codex 지출(USD) | Codex 롤아웃 사용량 기록으로 계산한 로컬 지출입니다. 가격을 모르면 비어 있습니다. 3.84.0부터 보냅니다 |
20
+ | 게이트웨이 지출(USD) | LiteLLM 게이트웨이를 쓸 때 게이트웨이가 집계한 본인의 하루 지출입니다. 게이트웨이가 없거나 호출이 실패하면 비어 있습니다. 3.84.0부터 보냅니다 |
21
+ | 게이트웨이 사용자 해시 | 게이트웨이 주소와 게이트웨이 사용자 ID를 합쳐 해시한 값의 앞 16자리(16진수)입니다. 한 사람이 컴퓨터 두 대를 써도 한 번만 세는 데 쓰며, 사용자 ID를 모르면 되돌릴 수 없습니다. 3.84.0부터 보냅니다 |
22
+ | 총지출(USD) | 게이트웨이 금액을 알면 그 값이고, 모르면 Claude 지출과 Codex 지출의 합입니다. 3.84.0부터 보냅니다 |
23
+ | 위임 비용(USD) | Sprag 모델 피팅 룰이 위임한 실행에 실제로 든 비용입니다. Claude와 Codex를 합칩니다. 3.84.0부터 보냅니다 |
24
+ | Codex 위임 실행 횟수와 비용 | 위임 실행과 그 비용 가운데 Codex가 차지한 몫입니다. 3.84.0부터 보냅니다 |
25
+ | 서브에이전트 비용(USD) | 룰과 상관없이 모든 서브에이전트 실행과 Codex 하위 세션에 든 비용입니다. 보조 수치입니다. 3.84.0부터 보냅니다 |
26
+ | 가격 미상 건수 | 가격을 몰라 계산에서 뺀 세션이나 실행의 수입니다. 3.84.0부터 보냅니다 |
17
27
  | Sprag 버전 | 설치된 버전 |
18
28
  | 에이전트 | `claude` 또는 `codex` |
19
29
  | 표시 이름 | 참여할 때 정한 이름이며, 기본값은 컴퓨터마다 한 번 만드는 `member-3f9a2c71` 같은 무작위 구성원 ID |
@@ -26,7 +36,7 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
26
36
 
27
37
  팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
28
38
 
29
- 목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다.
39
+ 목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다. LiteLLM 게이트웨이를 설정했다면 하루 동기화마다 게이트웨이의 `GET /user/info` 와 `GET /global/spend/logs` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
30
40
 
31
41
  ## CLI에서 팀 만들기
32
42
 
package/docs/TEAM.md CHANGED
@@ -12,8 +12,18 @@ After you join, Sprag uploads one row per local calendar day:
12
12
  |---|---|
13
13
  | Spend (USD) | priced from your local session logs |
14
14
  | Savings (USD) | from the routing and doc2md ledgers |
15
- | Delegated runs | how many runs were delegated that day |
15
+ | Delegated runs | how many Claude and Codex runs were delegated that day |
16
16
  | Model-family share | the share of those runs that went to each model family |
17
+ | Spend by model family (USD) | the day's spend split by model family (`opus`, `sonnet`, `haiku`, `fable`, ...), so the console can show which models each person spends on; sent from 3.84.0 |
18
+ | Claude spend (USD) | Claude Code local spend, main sessions plus subagent runs; the same figure as Spend (USD); sent from 3.84.0 |
19
+ | Codex spend (USD) | Codex local spend priced from the Codex rollout usage records, null when no price is known; sent from 3.84.0 |
20
+ | Gateway spend (USD) | the gateway's own daily spend for you when a LiteLLM gateway is configured, null when there is none or the call failed; sent from 3.84.0 |
21
+ | Gateway user hash | the first 16 hex characters of a hash of the gateway URL and your gateway user id, so one person with two machines is counted once; not reversible without the id; sent from 3.84.0 |
22
+ | Total spend (USD) | the gateway figure when known, otherwise Claude plus Codex; sent from 3.84.0 |
23
+ | Delegation cost (USD) | what the runs delegated by Sprag's model-fitting rules actually cost, Claude and Codex together; sent from 3.84.0 |
24
+ | Codex delegated runs and cost | the Codex share of the delegated runs and of their cost; sent from 3.84.0 |
25
+ | Subagent cost (USD) | the cost of every subagent run and Codex child session, rules or not; a secondary figure; sent from 3.84.0 |
26
+ | Unpriced parts | how many sessions or runs were left out because no price was known; sent from 3.84.0 |
17
27
  | Sprag version | the installed version |
18
28
  | Agent | `claude` or `codex` |
19
29
  | Display name | the name you chose at join; the default is a random member ID such as `member-3f9a2c71`, created once per machine |
@@ -26,7 +36,7 @@ The daily aggregate upload runs at most once every 5 minutes after the last succ
26
36
 
27
37
  While this machine is joined, the statusline shows a `team` chip with your member id and your animal from the virtual office (Sprag Town), for example `member-1e500474 🦊 Fox #3 of 12`, with your overall rank among the ranked people of the organization. The animal comes from the standing the full sync fetches every 5 minutes and stores in `team.json`; if the server does not offer it yet, or the last fetch is more than a day old, only the member id is shown. Rendering the chip reads local files only. It sits just before the version chip, and `--segments team` shows it on its own. IntelliJ's terminal font has no animal emoji, so there (narrow mode) and in text mode the chip drops the emoji and keeps the name: `member-1e500474 Fox #3 of 12`.
28
38
 
29
- Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures); `sprag team create` also calls `team_create` with your sign-in session.
39
+ Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures). When a LiteLLM gateway is configured, each daily sync also calls the gateway's `GET /user/info` and `GET /global/spend/logs` with your own key to read the gateway's daily spend for you; nothing else is read and the key is never stored. `sprag team status --show-payload` prints the exact rows. `sprag team create` also calls `team_create` with your sign-in session.
30
40
 
31
41
  ## Create a team from the CLI
32
42
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.82.0",
3
+ "version": "3.84.0",
4
4
  "description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -6,8 +6,8 @@
6
6
  "when its signature verifies; otherwise this file is used.",
7
7
  "Models are aliases on purpose (a gateway resolves them through ANTHROPIC_DEFAULT_*_MODEL),",
8
8
  "except t1h-worker, which names the full id: a bare alias resolves to an older model.",
9
- "Effort follows how the work is verified: low for lookups and command runs, medium for",
10
- "implementation against tests, high for the larger opus share.",
9
+ "Effort follows how the work is verified: low for lookups and command runs, high for",
10
+ "implementation by either worker (the sonnet worker moved from medium to high in 3.83.0).",
11
11
  "The files are rendered in English (description.en, body.en): they are model-facing",
12
12
  "prompts, and the Korean copy is what the /ops console shows next to it.",
13
13
  "tier and categories say which model-routing rules an agent serves (agentForRule in",
@@ -91,7 +91,7 @@
91
91
  {
92
92
  "name": "t1-worker",
93
93
  "model": "sonnet",
94
- "effort": "medium",
94
+ "effort": "high",
95
95
  "tier": "T1",
96
96
  "categories": [
97
97
  "*"
@@ -58,6 +58,29 @@ export function recordCodexDocument(source, result, opts = {}) {
58
58
  } catch { /* Accounting must not prevent document conversion. */ }
59
59
  }
60
60
 
61
+ /**
62
+ * One `{ ts, usd }` per recorded document, reset marks NOT applied (the
63
+ * caller decides which mark governs): the team upload sums these by local
64
+ * day beside the Claude doc2md ledger. `usd` is null for an unpriced record.
65
+ */
66
+ export function codexDocumentEvents(opts = {}) {
67
+ const out = [];
68
+ try {
69
+ const dir = ledgerDir(opts);
70
+ for (const file of readdirSync(dir).filter((name) => /^[a-f0-9]{64}\.json$/.test(name))) {
71
+ try {
72
+ const event = JSON.parse(readFileSync(join(dir, file), 'utf8'));
73
+ if (![1, 2].includes(event?.version) || !['pdf', 'pptx', 'xlsx', 'xls', 'docx', 'fig'].includes(event.ext)) continue;
74
+ const ts = event.version === 2 ? event.at : statSync(join(dir, file)).mtimeMs;
75
+ const s = event.saving;
76
+ const usd = event.version === 2 && s?.method === 'office-xml-vs-markdown-bytes/4' && Number.isFinite(s.usd) ? s.usd : null;
77
+ out.push({ ts, usd });
78
+ } catch { /* Ignore only the damaged record. */ }
79
+ }
80
+ } catch { /* No Codex document history yet. */ }
81
+ return out;
82
+ }
83
+
61
84
  // Legacy records use mtime; new records retain their first priced observation.
62
85
  export function codexDocumentTotals(opts = {}) {
63
86
  const since = readResetMarks(opts?.dir ?? userDataDir())['codex-docs'];
@@ -285,13 +285,17 @@ export async function refreshCodexLedger({ dir = userDataDir(), home, now = Date
285
285
  const actual = rates && run.usageKnown ? codexRunCost(run.tokens, rates.to) : null;
286
286
  const counterfactual = rates && run.usageKnown ? codexRunCost(run.tokens, rates.from) : null;
287
287
  const usd = actual === null || counterfactual === null ? null : roundUsd(run.aborted ? -actual : counterfactual - actual);
288
+ // `cost` is what the child itself cost on the model it ran on, recorded
289
+ // beside the saving (an interrupted child spent it too), so the team
290
+ // upload can report delegation cost rather than only the saving.
291
+ const cost = actual === null ? null : roundUsd(actual);
288
292
  const event = { ts: run.endedAt ?? route.at, parentSessionId: route.parentSessionId || run.parentThreadId || null,
289
293
  childSessionId: run.sessionId, source: route.source, category: route.category ?? null, scope: route.scope ?? null,
290
294
  ...(route.source === 'shared' ? { tier: route.tier, sharedSignature: route.sharedSignature } : {}),
291
295
  ...(route.source === 'implementation' ? { tier: route.tier } : {}),
292
296
  from: route.from, to, provider,
293
297
  ...(route.targetRoot !== undefined ? { targetRoot: route.targetRoot } : {}),
294
- ...(route.ruleCreatedAt !== undefined ? { ruleCreatedAt: route.ruleCreatedAt } : {}), tokens: run.tokens, calls: run.calls, toolErrors: run.toolErrors, usd, rates: usd === null ? null : rates,
298
+ ...(route.ruleCreatedAt !== undefined ? { ruleCreatedAt: route.ruleCreatedAt } : {}), tokens: run.tokens, calls: run.calls, toolErrors: run.toolErrors, usd, cost, rates: usd === null ? null : rates,
295
299
  priceCheckedAt: rates?.checkedAt ?? null, priceSource, complete: run.complete, ...(run.aborted ? { aborted: true } : {}) };
296
300
  // A transient price outage must not erase a completed, unchanged priced run.
297
301
  if (usd === null && sameRun && previous.complete && Number.isFinite(previous.usd) &&
@@ -302,6 +306,20 @@ export async function refreshCodexLedger({ dir = userDataDir(), home, now = Date
302
306
  return ledger;
303
307
  }
304
308
 
309
+ /**
310
+ * What a ledger event's child run cost, in USD: the recorded `cost`, or, for
311
+ * events written before the field existed, the same figure recomputed from
312
+ * the tokens and the rate they were priced at. null when neither is known.
313
+ */
314
+ export function codexEventCost(e) {
315
+ if (Number.isFinite(e?.cost)) return e.cost;
316
+ if (e?.tokens && e.rates?.to) {
317
+ const usd = codexRunCost(e.tokens, e.rates.to);
318
+ return Number.isFinite(usd) ? roundUsd(usd) : null;
319
+ }
320
+ return null;
321
+ }
322
+
305
323
  /**
306
324
  * Signed totals over priced runs; unpriced runs are counted, never summed as zero.
307
325
  * Runs before the `codex-routing` reset mark are left out of every figure,
@@ -328,23 +328,74 @@ export async function parseCodexTurns(filePath, { cutoffMs = -Infinity } = {}) {
328
328
  return session;
329
329
  }
330
330
 
331
- /** Rollout JSONL is a best-effort local format, not a stable Codex API. */
331
+ /**
332
+ * Rollout JSONL is a best-effort local format, not a stable Codex API.
333
+ *
334
+ * Usage comes from two record kinds. Current rollouts write a top-level
335
+ * `token_usage_record` per response (`payload.usage`, a `response_id`, the
336
+ * turn's model in `turn_context`); older ones only carry the cumulative
337
+ * `event_msg/token_count` snapshot, whose `total_token_usage.input_tokens` is
338
+ * 0 in many current files. A file with any usage record is summed from the
339
+ * records (duplicates by `response_id` dropped); only a file without them
340
+ * falls back to the snapshot deltas. Either way `totals.cacheCreation` holds
341
+ * the cache writes and `modelTotals` splits the totals by the model each
342
+ * request ran on, so a session that switched models is priced per model.
343
+ */
332
344
  export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } = {}) {
333
345
  const session = {
334
346
  agent: 'codex', sessionId: null, filePath, projectDir: '', model: 'unknown',
335
347
  startTime: null, endTime: null, requestCount: 0, totals: emptyTotals(),
336
348
  maxContextPerRequest: 0, reasoningOutputTokens: 0, contextWindow: null,
337
349
  lastContextTokens: null, rateLimits: null, lastActivity: null, effort: null,
338
- cacheActivity: null,
350
+ cacheActivity: null, modelTotals: null, usageSource: 'token_count',
339
351
  };
340
352
  const copied = forkedCopyFilter();
341
353
  let previous = null;
354
+ // usage records: per-response rows, keyed by response id to drop repeats
355
+ const records = [];
356
+ const seenResponses = new Set();
357
+ const turnModel = new Map();
358
+ const turnCumulative = new Map();
359
+ let contextModel = null;
360
+ const addUsage = (totals, u) => {
361
+ const cached = Math.min(u.input, u.cached);
362
+ const written = Math.min(Math.max(0, u.input - cached), u.cacheWrite);
363
+ totals.input += u.input - cached - written;
364
+ totals.cacheRead += cached;
365
+ totals.cacheCreation += written;
366
+ totals.output += u.output;
367
+ };
342
368
  for await (const line of transcriptLines(filePath)) {
343
369
  let e;
344
370
  try { e = JSON.parse(line); } catch { continue; }
345
371
  const p = e?.payload;
346
372
  if (!p || copied(e)) continue;
347
373
  updateSnapshot(session, e);
374
+ if (e.type === 'turn_context' && typeof p.model === 'string') {
375
+ contextModel = p.model;
376
+ if (p.turn_id) turnModel.set(p.turn_id, p.model);
377
+ continue;
378
+ }
379
+ if (e.type === 'token_usage_record') {
380
+ const u = p.usage || p.turn_token_usage;
381
+ if (!Number.isSafeInteger(u?.input_tokens) || !Number.isSafeInteger(u?.output_tokens)) continue;
382
+ if (typeof p.response_id === 'string' && p.response_id) {
383
+ if (seenResponses.has(p.response_id)) continue;
384
+ seenResponses.add(p.response_id);
385
+ }
386
+ let usage = { input: count(u.input_tokens), cached: count(u.cached_input_tokens),
387
+ cacheWrite: count(u.cache_write_input_tokens), output: count(u.output_tokens), reasoning: count(u.reasoning_output_tokens) };
388
+ if (!p.usage && p.turn_id) {
389
+ // turn_token_usage is the turn's running total: only its growth is new.
390
+ const prev = turnCumulative.get(p.turn_id);
391
+ turnCumulative.set(p.turn_id, usage);
392
+ if (prev) usage = Object.fromEntries(Object.keys(usage).map((k) => [k, Math.max(0, usage[k] - prev[k])]));
393
+ }
394
+ const ts = Date.parse(e.timestamp);
395
+ const model = (p.turn_id && turnModel.get(p.turn_id)) || (typeof p.model === 'string' ? p.model : null) || contextModel || session.model;
396
+ records.push({ ts, model, ...usage });
397
+ continue;
398
+ }
348
399
  if (e.type !== 'event_msg' || p.type !== 'token_count') continue;
349
400
  if (!p.info) continue;
350
401
  const info = p.info;
@@ -371,17 +422,33 @@ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } =
371
422
  cached: Math.min(delta.input, delta.cached), written: Math.min(delta.input, delta.written) };
372
423
  }
373
424
  if (!Number.isFinite(ts) || ts < cutoffMs) continue;
374
- const cached = Math.min(delta.input, delta.cached);
375
- session.totals.input += delta.input - cached;
376
- session.totals.cacheRead += cached;
377
- session.totals.output += delta.output;
425
+ session.maxContextPerRequest = Math.max(session.maxContextPerRequest, count(info.last_token_usage?.input_tokens));
426
+ if (count(info.model_context_window)) session.contextWindow = info.model_context_window;
427
+ if (records.length) continue; // summed from the usage records below
428
+ addUsage(session.totals, { input: delta.input, cached: delta.cached, cacheWrite: delta.written, output: delta.output });
429
+ const perModel = (session.modelTotals ??= {})[session.model] ??= emptyTotals();
430
+ addUsage(perModel, { input: delta.input, cached: delta.cached, cacheWrite: delta.written, output: delta.output });
378
431
  // Reasoning is a subset of output, just as cached input is a subset of input.
379
432
  session.reasoningOutputTokens += Math.min(delta.output, delta.reasoning);
380
433
  session.requestCount++;
381
434
  session.startTime ??= new Date(ts);
382
435
  session.endTime = new Date(ts);
383
- session.maxContextPerRequest = Math.max(session.maxContextPerRequest, count(info.last_token_usage?.input_tokens));
384
- if (count(info.model_context_window)) session.contextWindow = info.model_context_window;
436
+ }
437
+ if (records.length) {
438
+ // The snapshot path may have run before the first record appeared; the
439
+ // records are the whole truth for this file, so start over from them.
440
+ Object.assign(session, { totals: emptyTotals(), modelTotals: null, reasoningOutputTokens: 0, requestCount: 0, startTime: null, endTime: null, usageSource: 'token_usage_record' });
441
+ for (const r of records) {
442
+ if (!Number.isFinite(r.ts) || r.ts < cutoffMs) continue;
443
+ if (!r.input && !r.output) continue;
444
+ addUsage(session.totals, r);
445
+ const perModel = (session.modelTotals ??= {})[r.model || 'unknown'] ??= emptyTotals();
446
+ addUsage(perModel, r);
447
+ session.reasoningOutputTokens += Math.min(r.output, r.reasoning);
448
+ session.requestCount++;
449
+ session.startTime ??= new Date(r.ts);
450
+ session.endTime = new Date(r.ts);
451
+ }
385
452
  }
386
453
  return session;
387
454
  }
@@ -33,9 +33,10 @@ const MARK_LINE = `# managed by sprag (${OWNER_MARK}); edits are overwritten`;
33
33
  // Effort is a separate axis from the tier and is set by how the work gets
34
34
  // verified, not by how hard it is. Where the check is command output or a file
35
35
  // comparison (lookups, test runs, mechanical conversion) extra thinking buys
36
- // nothing, so those agents run at low. The worker implements a design the
37
- // caller already fixed, against tests, so it takes the default for well-specified
38
- // work, medium; the opus worker takes the larger, harder share of that work at high. The main session's effort is never touched here, and
36
+ // nothing, so those agents run at low. Both workers implement a design the
37
+ // caller already fixed and run at high: a wrong implementation costs a rerun and
38
+ // another review by the main model, which outweighs the extra thinking. The
39
+ // tier, not the effort, separates the sonnet worker from the opus one. The main session's effort is never touched here, and
39
40
  // CLAUDE_CODE_EFFORT_LEVEL must stay unset: it overrides every agent's own value.
40
41
  //
41
42
  // The files are rendered from the English copy. They are prompts the model
@@ -0,0 +1,137 @@
1
+ /**
2
+ * gateway-spend: the LiteLLM gateway's own daily spend for this user, for the
3
+ * team upload.
4
+ *
5
+ * Local session logs miss requests that leave no transcript (print mode
6
+ * without persistence, SDK scripts, deleted conversations), so a machine on a
7
+ * gateway reports the gateway's figure as its total usage and keeps the local
8
+ * figures beside it. Two calls, both with the user's own key:
9
+ *
10
+ * GET {base}/key/info the key's user_id (404 on custom-auth deployments)
11
+ * GET {base}/user/info user_info.user_id as the fallback
12
+ * GET {base}/global/spend/logs rows {date, spend, api_key, user}; the most
13
+ * recent 30 days, every user the key may see
14
+ *
15
+ * Only rows whose `user` is this user id are summed: an admin key sees
16
+ * everyone's rows and summing them all would report the whole company as one
17
+ * person. Without a user id nothing is attributable and the caller gets null,
18
+ * which reads as "no gateway figure" rather than an error.
19
+ *
20
+ * The key is used for the Authorization header only and is never written to
21
+ * a file (same rule as litellm-budget.js). Failures are returned as
22
+ * `{ error }`, never thrown: the upload goes on with local figures.
23
+ *
24
+ * `date` is the gateway's calendar day (UTC on the deployments measured), so
25
+ * a day can differ from the local day by up to a few hours of traffic; range
26
+ * sums are unaffected.
27
+ */
28
+
29
+ import { createHash } from 'node:crypto';
30
+ // gateway-auth.js is the leaf that litellm-budget.js re-exports; importing it
31
+ // directly keeps team-sync.js out of the statusline formatter's import graph.
32
+ import { gatewayBase, resolveKey } from './gateway-auth.js';
33
+ import { debug } from './debug.js';
34
+
35
+ /** Same answer as litellm-budget's gatewayEnv: address and key, or null. */
36
+ export function gatewayEnv(env = process.env) {
37
+ const base = gatewayBase(env);
38
+ if (!base) return null;
39
+ const key = resolveKey(env);
40
+ return key ? { base, key } : null;
41
+ }
42
+
43
+ export const GATEWAY_SPEND_TIMEOUT_MS = 15000;
44
+ export const GATEWAY_SPEND_DAYS = 30;
45
+
46
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}/;
47
+
48
+ /** Local calendar day, same key as team-sync.js and stats.js. */
49
+ function dayKey(ms) {
50
+ const d = new Date(ms);
51
+ const pad = (n) => String(n).padStart(2, '0');
52
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
53
+ }
54
+
55
+ /** Pseudonymous id for the (gateway, user) pair: the first 16 hex characters of a SHA-256. */
56
+ export function gatewayUserHash(base, userId) {
57
+ return createHash('sha256').update(`${base}\n${userId}`).digest('hex').slice(0, 16);
58
+ }
59
+
60
+ /**
61
+ * Sum `rows` for one user by date. Exported for tests and for the aggregate
62
+ * step; `rows` is the `/global/spend/logs` body (an array, or `{ data }`).
63
+ */
64
+ export function sumSpendRows(rows, userId) {
65
+ const list = Array.isArray(rows) ? rows : Array.isArray(rows?.data) ? rows.data : [];
66
+ const days = new Map();
67
+ let earliest = null;
68
+ for (const r of list) {
69
+ if (!r || typeof r !== 'object') continue;
70
+ const date = String(r.date || r.startTime || '').slice(0, 10);
71
+ if (!DAY_RE.test(date)) continue;
72
+ if (earliest === null || date < earliest) earliest = date;
73
+ if (String(r.user ?? '') !== String(userId)) continue;
74
+ const usd = Number(r.spend);
75
+ if (!Number.isFinite(usd)) continue;
76
+ days.set(date, (days.get(date) || 0) + usd);
77
+ }
78
+ return { days, earliest };
79
+ }
80
+
81
+ /**
82
+ * The gateway figure for one local day: a number inside the covered range (0
83
+ * when the gateway has no row for it), null outside it or without a result.
84
+ */
85
+ export function gatewayDayValue(result, day) {
86
+ if (!result || !result.days || !result.coveredFrom || !result.coveredTo) return null;
87
+ if (day < result.coveredFrom || day > result.coveredTo) return null;
88
+ return result.days.get(day) || 0;
89
+ }
90
+
91
+ /**
92
+ * @returns {Promise<null | { error: string } | { days: Map<string, number>, coveredFrom: string, coveredTo: string, userId: string, userHash: string }>}
93
+ * null when no gateway is configured or the user id cannot be learned.
94
+ */
95
+ export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = globalThis.fetch, now = Date.now(), timeoutMs = GATEWAY_SPEND_TIMEOUT_MS } = {}) {
96
+ const g = gatewayEnv(env);
97
+ if (!g) return null;
98
+ const { base, key } = g;
99
+ const ctl = new AbortController();
100
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
101
+ const headers = { accept: 'application/json', authorization: `Bearer ${key}` };
102
+ const getJson = async (path) => {
103
+ const res = await fetchImpl(`${base}${path}`, { signal: ctl.signal, headers, redirect: 'error' });
104
+ if (!res.ok) throw new Error(`LiteLLM ${path} responded ${res.status}`);
105
+ return res.json();
106
+ };
107
+ try {
108
+ // Same order as pickBudgetSource: the key's own user id first, then the
109
+ // user record. /key/info is 404 on custom-auth deployments; that is fine.
110
+ let userId = null;
111
+ try {
112
+ const keyBody = await getJson('/key/info');
113
+ const id = keyBody?.info?.user_id;
114
+ if (typeof id === 'string' && id) userId = id;
115
+ } catch (e) { debug('gateway-spend:key-info', e); }
116
+ if (!userId) {
117
+ const userBody = await getJson('/user/info');
118
+ const id = userBody?.user_info?.user_id;
119
+ if (typeof id === 'string' && id) userId = id;
120
+ }
121
+ if (!userId) return null;
122
+ const rows = await getJson('/global/spend/logs');
123
+ const { days, earliest } = sumSpendRows(rows, userId);
124
+ const coveredTo = dayKey(now);
125
+ const windowStart = dayKey(now - (GATEWAY_SPEND_DAYS - 1) * 86400000);
126
+ // The response is the gateway's recent-30-day window. A day inside it with
127
+ // no row is a day with no spend; the earliest row only widens the window
128
+ // when the gateway sent more than 30 days.
129
+ const coveredFrom = earliest && earliest < windowStart ? earliest : windowStart;
130
+ return { days, coveredFrom, coveredTo, userId, userHash: gatewayUserHash(base, userId) };
131
+ } catch (e) {
132
+ debug('gateway-spend', e);
133
+ return { error: e && e.name === 'AbortError' ? 'timeout' : String((e && e.message) || e) };
134
+ } finally {
135
+ clearTimeout(timer);
136
+ }
137
+ }
@@ -265,7 +265,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
265
265
  '(어떤 도구가 토큰을 아끼고 있는지 가시화):',
266
266
  '`🔀 [sprag] 모델 피팅: "<유형>" → <agent> (<모델> · effort <effort>) 위임`',
267
267
  '',
268
- '<모델>과 <effort>에는 룰의 에이전트 표기 괄호 안에 적힌 값(예: Sonnet 5.5 · effort medium)을',
268
+ '<모델>과 <effort>에는 룰의 에이전트 표기 괄호 안에 적힌 값(예: Sonnet 5.5 · effort high)을',
269
269
  '그대로 옮기고, 값이 적혀 있지 않으면 그 부분을 뺍니다. Claude Code 호출 행에는 에이전트',
270
270
  '이름만 보이므로, Agent 도구의 description 맨 앞에도 `[<모델> · <effort>]` 를 붙이십시오.',
271
271
  '',
@@ -293,8 +293,8 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
293
293
  '- **effort**: 모델 티어와 다른 축이다. 설치된 서브에이전트는 검증 형태에 따라',
294
294
  ' effort가 고정되어 있다. 명령 출력이나 파일 대조로 검증되는 위임(조회·명령',
295
295
  ' 실행·정형 변환을 맡는 haiku 에이전트)은 low, 확정된 설계를 테스트에 맞춰',
296
- ' 구현하는 위임(sonnet 워커)은 medium, 범위가 큰 구현·디버깅 위임(opus 워커)은',
297
- ' high다. 메인 세션의 effort는 바꾸지 않고,',
296
+ ' 구현하는 위임(sonnet 워커)과 범위가 큰 구현·디버깅 위임(opus 워커)은 high다.',
297
+ ' 두 워커는 effort가 아니라 모델 티어로 나뉜다. 메인 세션의 effort는 바꾸지 않고,',
298
298
  ' CLAUDE_CODE_EFFORT_LEVEL은 서브에이전트의 effort를 덮어쓰므로 설정하지 않는다.',
299
299
  '- **고난도 구현(T1H)**: 설계는 메인이 확정하고, 범위가 크거나 sonnet 이 틀린',
300
300
  ' 적 있는 구현·디버깅은 opus 에 위임한다. Fable·Mythos 세션에서만 적용되며,',
@@ -310,7 +310,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
310
310
  ' 컨텍스트를 다 보고도 틀린 오판형 실패는 모델을 한 티어 올린다. 순서는',
311
311
  ' ① 재지시 후 재시도(누락형이면 effort 한 단계 위) → ② 한 티어 상향(오판형)',
312
312
  ' → ③ 메인 모델이 직접 수습. effort를 올릴 때는 에이전트 파일을 고치지 않고',
313
- ' Agent 도구 호출의 effort 인자에 한 단계 위 값(low → medium → high)을 넘긴다.',
313
+ ' Agent 도구 호출의 effort 인자에 한 단계 위 값(low → medium → high → xhigh)을 넘긴다.',
314
314
  '',
315
315
  '## Rules',
316
316
  '',
@@ -333,7 +333,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
333
333
  '`🔀 [sprag] model fitting: "<category>" → delegated to <agent> (<model> · effort <effort>)`',
334
334
  '',
335
335
  'Fill <model> and <effort> from the parentheses after the agent in the rule',
336
- '(e.g. Sonnet 5.5, effort medium), and leave out whichever the rule does not',
336
+ '(e.g. Sonnet 5.5, effort high), and leave out whichever the rule does not',
337
337
  'give. Claude Code shows only the agent name on the call row, so also start',
338
338
  'the Agent tool\'s description with `[<model> · <effort>]`.',
339
339
  '',
@@ -363,9 +363,9 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
363
363
  '- **Effort**: a separate axis from the tier. The installed subagents pin it',
364
364
  ' by how their work is verified: low where the check is command output or a',
365
365
  ' file comparison (the haiku agents for lookups, command runs and mechanical',
366
- ' conversion), medium where a fixed design is implemented against tests (the',
367
- ' sonnet worker), high for large implementation or debugging (the opus',
368
- ' worker). Leave the main session\'s effort alone, and never set',
366
+ ' conversion), high where a fixed design is implemented against tests (the',
367
+ ' sonnet worker) and for large implementation or debugging (the opus',
368
+ ' worker); the tier, not the effort, separates the two workers. Leave the main session\'s effort alone, and never set',
369
369
  ' CLAUDE_CODE_EFFORT_LEVEL: it overrides every subagent\'s own value.',
370
370
  '- **Heavy implementation (T1H)**: the main model fixes the design; large-scope',
371
371
  ' implementation or debugging, or work sonnet has already got wrong, goes to',
@@ -383,7 +383,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
383
383
  ' moves up one tier. Order: ① re-instruct and retry (effort +1 on an',
384
384
  ' omission) → ② move up one tier (on a wrong answer) → ③ the main model',
385
385
  ' takes over directly. To raise effort, pass the next level (low → medium →',
386
- ' high) in the Agent call\'s effort argument instead of editing the agent file.',
386
+ ' high → xhigh) in the Agent call\'s effort argument instead of editing the agent file.',
387
387
  '',
388
388
  '## Rules',
389
389
  '',
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
@@ -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
  }
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
@@ -37,6 +45,11 @@ 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';
39
47
  import { codexUserDir } from './agent.js';
48
+ import { loadCodexLedger, codexEventCost } from './codex/ledger.js';
49
+ import { codexDocumentEvents } from './codex/doc2md-ledger.js';
50
+ import { codexPriceBook, readCodexPrices, refreshCodexPrices, codexRunCost } from './codex/cache-policy.js';
51
+ import { codexBudgetProvider } from './codex/budget.js';
52
+ import { fetchGatewayDailySpend, gatewayDayValue, gatewayEnv } from './gateway-spend.js';
40
53
 
41
54
  export const PROMPT_SYNC_INTERVAL_MS = 30 * 60 * 1000;
42
55
 
@@ -152,15 +165,20 @@ export function teamSyncDue(state, now = Date.now()) {
152
165
  /**
153
166
  * Which local days a ledger sync uploads: from the day before the watermark (that
154
167
  * day was still open when it was uploaded) through today, at most 30 days. With
155
- * no watermark, the last 30 days.
168
+ * no watermark, the last 30 days. With a gateway configured the window also
169
+ * reaches back to `gatewaySyncedThrough`, the last day whose gateway figure
170
+ * went up: a sync whose gateway call failed uploaded local figures only, and
171
+ * those days are sent again (as upserts) once the gateway answers.
156
172
  */
157
- export function ledgerWindow(state, now = Date.now()) {
173
+ export function ledgerWindow(state, now = Date.now(), { gateway = false } = {}) {
158
174
  const today = new Date(now);
159
175
  const earliest = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (LEDGER_WINDOW_DAYS - 1));
160
176
  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);
177
+ const marks = [state?.ledgerSyncedThrough];
178
+ if (gateway) marks.push(state?.gatewaySyncedThrough);
179
+ const parsed = marks.map((v) => /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(v || '')));
180
+ if (parsed.every(Boolean)) {
181
+ 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
182
  if (from > earliest) start = from;
165
183
  }
166
184
  const startKey = dayKey(start.getTime());
@@ -304,32 +322,66 @@ function dayKey(ms) {
304
322
 
305
323
  const round4 = (n) => Math.round(n * 10000) / 10000;
306
324
 
325
+ /** A Codex session's usage in codexRunCost's shape: `input` includes the cached and written parts. */
326
+ 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
+
307
328
  /**
308
329
  * 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.
330
+ *
331
+ * Money fields (all rounded to 4 decimals):
332
+ * spent_usd Claude local spend, main session plus subagent runs,
333
+ * on the session's start day (unchanged meaning: older
334
+ * servers and pages keep reading it)
335
+ * claude_spent_usd the same figure; subagent_cost_usd is the part of it
336
+ * that subagent runs and Codex child sessions cost
337
+ * codex_spent_usd Codex rollouts priced by the path they took (gateway
338
+ * prices for a LiteLLM provider, OpenAI list prices for
339
+ * direct calls); unpriced sessions count in unpriced_parts
340
+ * gateway_spent_usd the gateway's own daily figure for this user; null
341
+ * without a gateway, outside the days it covers, or
342
+ * when the call failed
343
+ * total_spent_usd gateway_spent_usd when known, else claude + codex;
344
+ * null only when the gateway call failed (so the server
345
+ * keeps the value an earlier sync stored)
346
+ * delegated_cost_usd what the runs sprag's rules delegated cost (Claude
347
+ * ledger `cost` plus Codex ledger cost); delegated_runs
348
+ * counts the same runs, Claude and Codex together
349
+ * saved_usd routing and doc2md savings, Claude and Codex; the
350
+ * only figure that honours the `sprag saved reset`
351
+ * marks (a reset is a stopwatch, not a refund)
352
+ * family_share covers Claude delegations only (the pages read haiku/sonnet/
353
+ * opus). delegated_errors is always null: the ledgers carry no error flag.
354
+ * Every source is injectable for tests; nothing here touches the network.
312
355
  */
313
- export async function aggregateDaily({ now = Date.now(), dir = userDataDir(), days = 30, sessions = null } = {}) {
356
+ export async function aggregateDaily({
357
+ now = Date.now(), dir = userDataDir(), days = 30, sessions = null,
358
+ codexSessions = null, codexLedger = null, codexDocEvents = null, codexPrices = undefined, gatewayDaily = null, env = process.env,
359
+ } = {}) {
314
360
  const { readResetMarks, isBeforeReset } = require('./saved-reset.cjs');
315
361
  const doc2md = require('./doc2md-ledger.cjs');
316
362
  const cutoff = now - days * 24 * 3600 * 1000;
317
363
  const byDay = new Map();
318
364
  const get = (day) => {
319
- if (!byDay.has(day)) byDay.set(day, { spent: 0, saved: 0, runs: 0, fam: new Map() });
365
+ if (!byDay.has(day)) {
366
+ 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() });
367
+ }
320
368
  return byDay.get(day);
321
369
  };
370
+ const inWindow = (ts) => Number.isFinite(ts) && ts >= cutoff && ts <= now;
322
371
  let marks = {};
323
372
  try { marks = readResetMarks(dir) || {}; } catch (e) { debug('team-sync', e); }
324
373
 
374
+ // Claude delegation ledger: runs and their cost regardless of reset marks,
375
+ // savings and family share only after the mark.
325
376
  try {
326
377
  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;
378
+ if (!inWindow(e.ts)) continue;
329
379
  const d = get(dayKey(e.ts));
380
+ d.runs += 1;
381
+ if (Number.isFinite(e.cost)) d.cost += e.cost; else d.unpriced += 1;
382
+ if (isBeforeReset(e.ts, marks.routing)) continue;
330
383
  const usd = Number(e.usd);
331
384
  if (Number.isFinite(usd)) d.saved += usd;
332
- d.runs += 1;
333
385
  const fam = modelFamily(e.to);
334
386
  d.fam.set(fam, (d.fam.get(fam) || 0) + 1);
335
387
  }
@@ -337,12 +389,40 @@ export async function aggregateDaily({ now = Date.now(), dir = userDataDir(), da
337
389
 
338
390
  try {
339
391
  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;
392
+ if (!inWindow(e.ts) || isBeforeReset(e.ts, marks.doc2md)) continue;
342
393
  get(dayKey(e.ts)).saved += Number(e.usd) || 0;
343
394
  }
344
395
  } catch (e) { debug('team-sync', e); }
345
396
 
397
+ // Codex delegation ledger, the same rules; the event's cost is recomputed
398
+ // from its tokens when it predates the `cost` field.
399
+ try {
400
+ const events = Object.values((codexLedger || loadCodexLedger({ dir })).events || {});
401
+ for (const e of events) {
402
+ if (!inWindow(e.ts)) continue;
403
+ const d = get(dayKey(e.ts));
404
+ d.codexRuns += 1;
405
+ const cost = codexEventCost(e);
406
+ if (cost !== null) d.codexCost += cost; else d.unpriced += 1;
407
+ if (isBeforeReset(e.ts, marks['codex-routing'])) continue;
408
+ if (Number.isFinite(e.usd)) d.saved += e.usd;
409
+ }
410
+ } catch (e) { debug('team-sync', e); }
411
+
412
+ try {
413
+ for (const e of codexDocEvents || codexDocumentEvents({ dir })) {
414
+ if (!inWindow(e.ts) || isBeforeReset(e.ts, marks['codex-docs'])) continue;
415
+ if (Number.isFinite(e.usd)) get(dayKey(e.ts)).saved += e.usd;
416
+ }
417
+ } catch (e) { debug('team-sync', e); }
418
+
419
+ const addModel = (d, model, usd) => {
420
+ // Spend per model family (opus, sonnet, gpt-6-sol, ...), so the console can
421
+ // show which models each person spends on. Unknown models keep a short raw name.
422
+ const fam = String(modelFamily(model)).slice(0, 40);
423
+ d.models.set(fam, (d.models.get(fam) || 0) + usd);
424
+ };
425
+
346
426
  try {
347
427
  let list = sessions;
348
428
  if (!list) {
@@ -352,31 +432,102 @@ export async function aggregateDaily({ now = Date.now(), dir = userDataDir(), da
352
432
  for (const s of list || []) {
353
433
  if (!s || !s.startTime || !s.totals) continue;
354
434
  const t = new Date(s.startTime).getTime();
355
- if (!Number.isFinite(t) || t < cutoff || t > now) continue;
356
- let cost = 0;
435
+ if (!inWindow(t)) continue;
436
+ const d = get(dayKey(t));
357
437
  for (const part of pricedParts(s)) {
358
438
  try {
359
- const c = sessionCost(part.totals, part.model);
360
- if (c) cost += c.actual;
439
+ const c = sessionCost(part.totals, part.model, { env });
440
+ if (!c) { d.unpriced += 1; continue; }
441
+ d.spent += c.actual;
442
+ if (!part.own) d.subagent += c.actual;
443
+ addModel(d, part.model, c.actual);
361
444
  } catch (e) { debug('team-sync', e); }
362
445
  }
363
- get(dayKey(t)).spent += cost;
364
446
  }
365
447
  } catch (e) { debug('team-sync', e); }
366
448
 
449
+ // Codex sessions: priced per model from the rollout usage records, on the
450
+ // session's start day like Claude. Child sessions count as subagent cost.
451
+ try {
452
+ let list = codexSessions;
453
+ if (!list) {
454
+ const { parseAllCodexSessions } = await import('./codex/parser.js');
455
+ list = await parseAllCodexSessions({ days });
456
+ }
457
+ const prices = codexPrices === undefined ? readCodexPrices({ now, dir }) : codexPrices;
458
+ for (const s of list || []) {
459
+ if (!s || !s.startTime || !s.totals) continue;
460
+ const t = new Date(s.startTime).getTime();
461
+ if (!inWindow(t)) continue;
462
+ const d = get(dayKey(t));
463
+ const book = codexPriceBook(s.provider, prices);
464
+ const parts = s.modelTotals && Object.keys(s.modelTotals).length ? Object.entries(s.modelTotals) : [[s.model, s.totals]];
465
+ for (const [model, totals] of parts) {
466
+ const usd = book ? codexRunCost(codexUsage(totals), book.prices?.[model]) : null;
467
+ if (usd === null) { d.unpriced += 1; continue; }
468
+ d.codex += usd;
469
+ if (s.isSubagent) d.subagent += usd;
470
+ addModel(d, model, usd);
471
+ }
472
+ }
473
+ } catch (e) { debug('team-sync', e); }
474
+
475
+ // Gateway days with spend but no local record still get a row: that is the
476
+ // "unrecorded usage" the console shows.
477
+ const gw = gatewayDaily && !gatewayDaily.error && gatewayDaily.days ? gatewayDaily : null;
478
+ const gwFailed = !!(gatewayDaily && gatewayDaily.error);
479
+ if (gw) {
480
+ for (const [day, usd] of gw.days) {
481
+ if (usd > 0 && day >= dayKey(cutoff) && day <= dayKey(now)) get(day);
482
+ }
483
+ }
484
+
367
485
  return [...byDay.entries()]
368
486
  .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
- }));
487
+ .map(([day, d]) => {
488
+ const claude = round4(d.spent), codex = round4(d.codex);
489
+ const gateway = gw ? gatewayDayValue(gw, day) : null;
490
+ const total = gwFailed ? null : gateway !== null ? round4(gateway) : round4(claude + codex);
491
+ return {
492
+ day,
493
+ spent_usd: claude,
494
+ saved_usd: round4(d.saved),
495
+ delegated_runs: d.runs + d.codexRuns,
496
+ delegated_errors: null,
497
+ family_share: Object.fromEntries(
498
+ [...d.fam.entries()].map(([f, n]) => [f, Math.round((n / d.runs) * 1000) / 1000]),
499
+ ),
500
+ model_spend: Object.fromEntries(
501
+ [...d.models.entries()].map(([f, usd]) => [f, round4(usd)]).filter(([, usd]) => usd > 0),
502
+ ),
503
+ claude_spent_usd: claude,
504
+ codex_spent_usd: codex,
505
+ gateway_spent_usd: gateway === null ? null : round4(gateway),
506
+ gateway_user_hash: gw ? gw.userHash : null,
507
+ total_spent_usd: total,
508
+ delegated_cost_usd: round4(d.cost + d.codexCost),
509
+ codex_delegated_runs: d.codexRuns,
510
+ codex_delegated_cost_usd: round4(d.codexCost),
511
+ subagent_cost_usd: round4(d.subagent),
512
+ unpriced_parts: d.unpriced,
513
+ };
514
+ })
515
+ .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
+ }
517
+
518
+ /**
519
+ * The Codex price table for the upload, refreshed once from the gateway when
520
+ * the snapshot is missing or stale. Only the sync (a detached child) calls
521
+ * this; `team status --show-payload` stays offline.
522
+ */
523
+ async function codexPricesForSync({ dir, now, fetchImpl }) {
524
+ const cached = readCodexPrices({ now, dir });
525
+ if (cached) return cached;
526
+ let provider = null;
527
+ try { provider = codexBudgetProvider(); } catch (e) { debug('team-sync:codex-prices', e); }
528
+ if (!provider) return null;
529
+ try { return await refreshCodexPrices({ provider, dir, now, fetchImpl }); }
530
+ catch (e) { debug('team-sync:codex-prices', e); return null; }
380
531
  }
381
532
 
382
533
  // Device info: OS name and OS version. The CPU architecture is not sent: the
@@ -557,8 +708,15 @@ export function refreshTeamRatchetFiles({ dir = userDataDir() } = {}) {
557
708
  return out;
558
709
  }
559
710
 
711
+ /**
712
+ * `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
713
+ * is injected separately so tests can fake each side). `codexSessions`,
714
+ * `codexLedger`, `codexDocEvents` and `codexPrices` pass straight to
715
+ * aggregateDaily.
716
+ */
560
717
  export async function syncTeam({
561
718
  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,
562
720
  } = {}) {
563
721
  let state = loadTeamState(dir);
564
722
  // The switch stops every usage upload. A joined machine still tells the
@@ -623,12 +781,24 @@ export async function syncTeam({
623
781
  try { saveTeamState(state, dir); } catch (e) { debug('team-sync', e); }
624
782
  state = await reportDeviceInfo({ state, dir, fetch, env });
625
783
  try {
626
- const win = ledgerWindow(state, now);
627
- const rows = (await aggregateDaily({ now, dir, sessions, days: win.days }))
784
+ // The gateway's daily figure, when one is configured. A failed call does
785
+ // not stop the upload: those days go up with local figures and null
786
+ // totals (the server keeps what it already has), and gatewaySyncedThrough
787
+ // stays put so the next successful call re-sends them.
788
+ const hasGateway = !!gatewayEnv(env);
789
+ let gatewayDaily = null;
790
+ if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now });
791
+ const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
792
+ const win = ledgerWindow(state, now, { gateway: hasGateway });
793
+ const prices = codexPrices !== undefined ? codexPrices : await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch });
794
+ const rows = (await aggregateDaily({ now, dir, sessions, days: win.days, env, codexSessions, codexLedger, codexDocEvents, codexPrices: prices, gatewayDaily }))
628
795
  .filter((r) => r.day >= win.startKey).slice(-MAX_ROWS);
629
796
  await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
630
797
  const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
631
798
  const next = withRulesMeta({ ...state, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, r, now);
799
+ if (gatewayOk) next.gatewaySyncedThrough = dayKey(now);
800
+ else if (gatewayDaily && gatewayDaily.error) next.lastGatewayError = gatewayDaily.error;
801
+ if (gatewayOk || !hasGateway) delete next.lastGatewayError;
632
802
  delete next.syncFailures;
633
803
  delete next.lastError;
634
804
  saveTeamState(next, dir);
@@ -701,6 +871,6 @@ export function autoJoinNotice(state, lang = 'en') {
701
871
  state.autoJoinNoticePending = false;
702
872
  const name = state.teamName || '';
703
873
  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\`.`;
874
+ ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude·Codex·게이트웨이), 위임 비용, 절감, 위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
875
+ : `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
876
  }