sprag-cli 3.108.0 → 3.109.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.108.0",
3
+ "version": "3.109.1",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -7,17 +7,30 @@
7
7
  * litellm-models.js imports cost.js, and this needs both.
8
8
  */
9
9
  import { estimateCost, estimateCostAcross } from './cost.js';
10
- import { gatewayPriceFor } from './litellm-models.js';
10
+ import { gatewayPriceFor, gatewayPriceMiss } from './litellm-models.js';
11
11
  import { gatewayBase } from './gateway-auth.js';
12
+ import { diagActive, recordDiag } from './diag-log.js';
12
13
 
13
14
  // `at` is when the tokens were spent; list prices and gateway prices (from the
14
15
  // gateway's dated price history) are looked up for that time.
15
16
  export function sessionCost(totals, model, { env = process.env, now, at } = {}) {
16
17
  if (!gatewayBase(env)) return estimateCost(totals, model, { at });
17
18
  const price = gatewayPriceFor(model, env, now, at);
19
+ if (!price) noteUnpriced(model, env, now, at);
18
20
  return price ? estimateCost(totals, model, { price }) : null;
19
21
  }
20
22
 
23
+ // A gateway session with no price is invisible otherwise: the figure just reads
24
+ // as unpriced. The diagnostics log records why, once per distinct message per
25
+ // process (recordDiag dedupes), so the message must not carry `at`.
26
+ function noteUnpriced(model, env, now, at) {
27
+ try {
28
+ if (!diagActive({ env })) return;
29
+ const { reason, keys } = gatewayPriceMiss(model, env, now, at);
30
+ recordDiag('price:unpriced', new Error(`model=${model} reason=${reason} known=${keys.join(',')}`), { env });
31
+ } catch { /* diagnostics only */ }
32
+ }
33
+
21
34
  /**
22
35
  * Several totals folded into one, `long` included. Returns the entry itself
23
36
  * for a list of one.
@@ -19,10 +19,17 @@ export async function run({ hasFlag }) {
19
19
  // 호출 횟수도 그만큼 늘어납니다.
20
20
  const key = resolveKey();
21
21
  let next = null;
22
+ if (!key) debug('litellm-budget:no-key', new Error('gateway set but no ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY or apiKeyHelper key'));
22
23
  if (key) {
23
- next = await refreshBudgetState(process.env, fetch, key);
24
- const { maybeRefreshGatewayModelMap } = await import('../litellm-models.js');
25
- await maybeRefreshGatewayModelMap({ base: gatewayBase(), key });
24
+ // The price table does not depend on the budget: a gateway whose /key/info and
25
+ // /user/info both fail (custom auth, a timeout) still has to get its prices,
26
+ // or every Claude call there stays unpriced.
27
+ try {
28
+ next = await refreshBudgetState(process.env, fetch, key);
29
+ } finally {
30
+ const { maybeRefreshGatewayModelMap } = await import('../litellm-models.js');
31
+ await maybeRefreshGatewayModelMap({ base: gatewayBase(), key });
32
+ }
26
33
  }
27
34
  if (!quiet) console.log(JSON.stringify(next, null, 2));
28
35
  } catch (e) {
@@ -23,6 +23,7 @@ import {
23
23
  setDisplayName,
24
24
  } from '../team-sync.js';
25
25
  import { standingGuideLines } from '../team-standing.js';
26
+ import { readDiag } from '../diag-log.js';
26
27
 
27
28
  const T = {
28
29
  en: {
@@ -38,7 +39,7 @@ const T = {
38
39
  ' rules show cached organization and team rules',
39
40
  ' propose <text> [--scope ratchet|model] propose a rule to the team',
40
41
  ].join('\n'),
41
- willSend: 'Joining uploads aggregates only. Per local day:\n - spend (USD)\n - savings (USD)\n - delegation run counts\n - model-family share\nAnd one summary of your delegation rules, per category and tier:\n - category, tier, delegation count, failure rate, savings (USD)\nNo prompts, rule text, examples, file paths or transcripts are sent.',
42
+ willSend: 'Joining uploads aggregates only. Per local day:\n - spend (USD)\n - savings (USD)\n - delegation run counts\n - model-family share\nAnd one summary of your delegation rules, per category and tier:\n - category, tier, delegation count, failure rate, savings (USD)\nError messages from sprag itself (to fix problems on your machine). Home paths, host names and secrets are masked.\nNo prompts, rule text, examples, file paths or transcripts are sent.',
42
43
  rulesPayload: 'delegation rule summary (member_rules_report)',
43
44
  asName: (n) => `Display name: ${n}`,
44
45
  asDevice: (d) => `Machine ID: ${d} (lets the organization count this machine once if it joins again)`,
@@ -68,6 +69,9 @@ const T = {
68
69
  lastPrompts: (t, n) => `Last prompt upload: ${t} (${n} prompts)`,
69
70
  noPrompts: 'Last prompt upload: never',
70
71
  pendingPrompts: (n) => `Prompts waiting to upload: ${n}`,
72
+ diagWaiting: (n, last) => `Diagnostics waiting to upload: ${n} (last upload: ${last})`,
73
+ diagNever: 'never',
74
+ diagPayload: 'diagnostics (diag_upload)',
71
75
  pendingExample: (e) => `Example (redacted): ${e.at} · ${e.project || '-'} · ${e.text}`,
72
76
  disabled: 'Team sync is disabled (SPRAG_NO_TEAM_SYNC=1).',
73
77
  skipped: (s) => `Skipped: ${s}`,
@@ -117,7 +121,7 @@ const T = {
117
121
  ' rules 받아 둔 조직·팀 규칙 보기',
118
122
  ' propose <내용> [--scope ratchet|model] 팀에 규칙 제안',
119
123
  ].join('\n'),
120
- willSend: '참여하면 집계만 올라갑니다. 로컬 날짜별로는 다음과 같습니다.\n - 지출(USD)\n - 절감(USD)\n - 위임 실행 횟수\n - 모델 계열 비중\n위임 룰은 카테고리와 티어별 요약 한 벌이 올라갑니다.\n - 카테고리, 티어, 위임 횟수, 실패율, 절감액(USD)\n프롬프트, 룰 본문, 예시, 파일 경로, 대화 기록은 보내지 않습니다.',
124
+ willSend: '참여하면 집계만 올라갑니다. 로컬 날짜별로는 다음과 같습니다.\n - 지출(USD)\n - 절감(USD)\n - 위임 실행 횟수\n - 모델 계열 비중\n위임 룰은 카테고리와 티어별 요약 한 벌이 올라갑니다.\n - 카테고리, 티어, 위임 횟수, 실패율, 절감액(USD)\nsprag 자체의 오류 메시지(이 기기의 문제를 고치는 데 씁니다). 홈 경로, 호스트 이름, 비밀 값은 가려서 보냅니다.\n프롬프트, 룰 본문, 예시, 파일 경로, 대화 기록은 보내지 않습니다.',
121
125
  rulesPayload: '위임 룰 요약 (member_rules_report)',
122
126
  asName: (n) => `표시 이름: ${n}`,
123
127
  asDevice: (d) => `기기 ID: ${d} (다시 참여해도 조직이 이 컴퓨터를 한 좌석으로 셉니다)`,
@@ -147,6 +151,9 @@ const T = {
147
151
  lastPrompts: (t, n) => `마지막 프롬프트 업로드: ${t} (${n}건)`,
148
152
  noPrompts: '마지막 프롬프트 업로드: 아직 없음',
149
153
  pendingPrompts: (n) => `업로드 대기 중인 프롬프트: ${n}건`,
154
+ diagWaiting: (n, last) => `업로드 대기 중인 진단 기록: ${n}건 (마지막 업로드: ${last})`,
155
+ diagNever: '아직 없음',
156
+ diagPayload: '진단 기록 (diag_upload)',
150
157
  pendingExample: (e) => `예시 (비밀값 가림): ${e.at} · ${e.project || '-'} · ${e.text}`,
151
158
  disabled: '팀 동기화가 꺼져 있습니다 (SPRAG_NO_TEAM_SYNC=1).',
152
159
  skipped: (s) => `건너뜀: ${s}`,
@@ -364,6 +371,7 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
364
371
  for (const l of standingGuideLines(st.standing, { lang: userLanguage(), org: st.orgName || st.teamName || null, team: st.teamName || null })) out(l);
365
372
  out(st.lastSyncAt ? m.lastSync(new Date(st.lastSyncAt).toLocaleString(), st.lastSyncRows || 0) : m.neverSynced);
366
373
  if (st.lastError) out(isOrgExpiredError(st.lastError) ? m.orgExpired : `${m.lastError}: ${st.lastError}`);
374
+ out(m.diagWaiting(readDiag().length, st.lastDiagAt ? new Date(st.lastDiagAt).toLocaleString() : m.diagNever));
367
375
  if (orgMinVersion(st)) out(m.orgMin(orgMinVersion(st), version));
368
376
  {
369
377
  const up = readOrgUpgrade();
@@ -379,6 +387,7 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
379
387
  out(`device: ${JSON.stringify(st.deviceInfo || deviceInfo())}`);
380
388
  out(JSON.stringify(await aggregateDaily(), null, 2));
381
389
  out(`${m.rulesPayload}: ${JSON.stringify(ruleStatsSummary(), null, 2)}`);
390
+ out(`${m.diagPayload}: ${JSON.stringify(readDiag(), null, 2)}`);
382
391
  if (st.promptCapture) {
383
392
  const pend = await pendingPrompts();
384
393
  out(m.pendingPrompts(pend.count));
package/src/debug.js CHANGED
@@ -13,13 +13,19 @@
13
13
  */
14
14
 
15
15
  import { envVar } from './env.js';
16
+ import { recordDiag } from './diag-log.js';
16
17
  const ENABLED = !!envVar('DEBUG');
17
18
 
18
19
  /**
20
+ * Every swallowed error is also noted in the local diagnostics log (diag-log.js)
21
+ * when this machine is joined to a team, whether or not SPRAG_DEBUG is set.
22
+ * recordDiag never throws.
23
+ *
19
24
  * @param {string} scope short label for where the failure happened
20
25
  * @param {unknown} err the swallowed error
21
26
  */
22
27
  export function debug(scope, err) {
28
+ recordDiag(scope, err);
23
29
  if (!ENABLED) return;
24
30
  const msg = err && err.stack ? err.stack : String(err);
25
31
  process.stderr.write(`[cts:${scope}] ${msg}\n`);
@@ -0,0 +1,235 @@
1
+ /**
2
+ * diag-log: a small local log of the errors sprag swallowed on a joined machine.
3
+ *
4
+ * Why: a joined machine can show $0 spend, upload zero ledger rows or price
5
+ * every Claude call as "unpriced", and the cause sits in a catch block that was
6
+ * silent on purpose (see debug.js). The operator needs the error text from that
7
+ * machine, so `debug()` also lands here and the team sync uploads the log to
8
+ * `diag_upload`. Only error text goes up: never a prompt or a transcript.
9
+ *
10
+ * File: <userDataDir>/diag-log.json
11
+ * { "version": 1, "entries": [ { scope, msg, count, first, last } ] }
12
+ * `first` and `last` are ISO times. An entry is one (scope, msg) pair.
13
+ *
14
+ * Costs and guarantees:
15
+ * - recordDiag never throws and never calls debug() (that would recurse).
16
+ * - It does nothing unless the machine is joined to a team (team.json is read
17
+ * once per process and directory) and the user has not set SPRAG_NO_DIAG=1
18
+ * or SPRAG_NO_TEAM_SYNC=1.
19
+ * - Repeats: the first occurrence of a (scope, msg) pair in a process writes
20
+ * the file (count + 1). Later occurrences of the same pair in that process
21
+ * are ignored, so a loop that fails thousands of times costs one write. The
22
+ * count therefore means "processes that saw it", not "times it happened".
23
+ * - At most MAX_ENTRIES entries; when full, the entry with the oldest `last` goes.
24
+ *
25
+ * Imports only node builtins, env.js, paths.js, redact.js and state-file.js, so
26
+ * debug.js (which the statusline and the hooks load) can import it.
27
+ */
28
+
29
+ import { readFileSync, chmodSync } from 'node:fs';
30
+ import { homedir } from 'node:os';
31
+ import { dirname, join } from 'node:path';
32
+ import { fileURLToPath, pathToFileURL } from 'node:url';
33
+ import { envVar } from './env.js';
34
+ import { userDataDir } from './paths.js';
35
+ import { redactSecrets } from './redact.js';
36
+ import { writeStateFile } from './state-file.js';
37
+
38
+ export const DIAG_VERSION = 1;
39
+ export const MAX_ENTRIES = 50;
40
+ export const MAX_MSG = 300;
41
+ export const MAX_SCOPE = 60;
42
+
43
+ export const diagPath = (dir = userDataDir()) => join(dir, 'diag-log.json');
44
+
45
+ /** sprag's own src/ directory: a stack frame inside it is worth naming. */
46
+ export const diagSrcDir = dirname(fileURLToPath(import.meta.url));
47
+ const SRC_URL = pathToFileURL(diagSrcDir).href;
48
+
49
+ const URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/(?:[^\s/@?#]*@)?[^\s/?#]+/gi;
50
+ const ARN_ACCOUNT_RE = /(arn:aws[\w-]*:[\w-]*:[\w-]*:)\d{12}(:)/g;
51
+ const EMAIL_RE =/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
52
+
53
+ // A file path after the start, a space, a quote, `(` or `=`. `<host>/path` is not
54
+ // matched (the `>` before it), so a URL keeps its path.
55
+ const PATH_RE = /(^|[\s'"(=])((?:~|[A-Za-z]:)?[\\/][^\s'"():,]+)/g;
56
+ const FS_ROOT_RE = /^\/(?:Users|home|root|private|var|tmp|opt|usr|Volumes|mnt|media|srv|etc|Library|Applications|System|nix|snap|workspace|workspaces|data|app)(?:\/|$)/;
57
+
58
+ /**
59
+ * A path without the directories that could name a project: the last segment
60
+ * only, behind `…`. A home dot-directory (`~/.claude/projects/...`) keeps its
61
+ * first two segments, which say which tool's files were missing; a project
62
+ * directory below them is dropped all the same.
63
+ */
64
+ function shortPath(p) {
65
+ const root = p.startsWith('~') ? '~' : /^[A-Za-z]:/.test(p) ? p.slice(0, 2) : '';
66
+ // An API path (`/key/info`, `/spend/logs/v2`) names no project and is what tells
67
+ // the failing call apart: only paths under a filesystem root are cut.
68
+ if (!root && !FS_ROOT_RE.test(p)) return p;
69
+ const sep = p.includes('\\') && !p.includes('/') ? '\\' : '/';
70
+ const parts = p.slice(root.length).split(/[\\/]/).filter(Boolean);
71
+ const keep = root === '~' && parts[0]?.startsWith('.') ? Math.min(2, parts.length) : 0;
72
+ if (parts.length <= keep + 1) return p;
73
+ return root + sep + [...parts.slice(0, keep), '…', parts[parts.length - 1]].join(sep);
74
+ }
75
+
76
+ /**
77
+ * Text that is safe to leave the machine: home directory -> `~`, a path cut to
78
+ * its last segment (see shortPath), every
79
+ * scheme://host[:port] -> `<host>` (path kept), secrets masked, e-mail
80
+ * addresses -> `<email>`, whitespace collapsed, cut to `max` characters.
81
+ */
82
+ export function sanitizeDiag(text, max = MAX_MSG) {
83
+ let s = String(text ?? '');
84
+ try {
85
+ const home = homedir();
86
+ if (home && home.length > 1) s = s.split(home).join('~');
87
+ } catch { /* no home directory to mask */ }
88
+ s = s.replace(URL_RE, '<host>');
89
+ s = s.replace(PATH_RE, (_, lead, p) => lead + shortPath(p));
90
+ s = s.replace(ARN_ACCOUNT_RE, '$1<acct>$2'); // a model id can be an ARN, and an ARN holds the AWS account id
91
+ s = redactSecrets(s);
92
+ s = s.replace(EMAIL_RE, '<email>');
93
+ s = s.replace(/\s+/g, ' ').trim();
94
+ return s.length > max ? s.slice(0, max) : s;
95
+ }
96
+
97
+ /** `src/<file>.js:<line>` of the first stack frame inside sprag's own src/, or ''. */
98
+ function ownFrame(stack) {
99
+ if (typeof stack !== 'string') return '';
100
+ for (const line of stack.split('\n')) {
101
+ for (const needle of [diagSrcDir, SRC_URL]) {
102
+ const at = line.indexOf(needle);
103
+ if (at < 0) continue;
104
+ const m = /^[\\/]([^\s():]+?\.c?js):(\d+)/.exec(line.slice(at + needle.length));
105
+ if (m) return `src/${m[1].replace(/\\/g, '/')}:${m[2]}`;
106
+ }
107
+ }
108
+ return '';
109
+ }
110
+
111
+ function messageOf(err) {
112
+ let msg;
113
+ if (err && typeof err === 'object' && 'message' in err) msg = String(err.message);
114
+ else msg = String(err);
115
+ const first = msg.split('\n').find((l) => l.trim()) || '';
116
+ const frame = err && typeof err === 'object' ? ownFrame(err.stack) : '';
117
+ if (!frame) return sanitizeDiag(first);
118
+ return sanitizeDiag(`${sanitizeDiag(first, MAX_MSG - frame.length - 4)} @ ${frame}`);
119
+ }
120
+
121
+ const keyOf = (scope, msg) => `${scope}\n${msg}`;
122
+
123
+ const joinedByDir = new Map(); // dir -> boolean, read once per process
124
+ const seenKeys = new Set(); // `${dir}\n${scope}\n${msg}` written (or attempted) by this process
125
+
126
+ /** Forget what this process cached. For tests that simulate a second process. */
127
+ export function _resetDiagForTest() {
128
+ joinedByDir.clear();
129
+ seenKeys.clear();
130
+ }
131
+
132
+ function isJoinedDir(dir) {
133
+ if (joinedByDir.has(dir)) return joinedByDir.get(dir);
134
+ let joined = false;
135
+ try {
136
+ const s = JSON.parse(readFileSync(join(dir, 'team.json'), 'utf8'));
137
+ joined = !!(s && s.memberKey && !s.left);
138
+ } catch { /* no team state: not joined */ }
139
+ joinedByDir.set(dir, joined);
140
+ return joined;
141
+ }
142
+
143
+ function validEntry(e) {
144
+ return !!e && typeof e === 'object' && typeof e.scope === 'string' && typeof e.msg === 'string' && Number.isFinite(e.count) && e.count > 0;
145
+ }
146
+
147
+ /** The entries waiting in the log. Empty on any problem. */
148
+ export function readDiag({ dir = userDataDir() } = {}) {
149
+ try {
150
+ const data = JSON.parse(readFileSync(diagPath(dir), 'utf8'));
151
+ if (!data || data.version !== DIAG_VERSION || !Array.isArray(data.entries)) return [];
152
+ return data.entries.filter(validEntry);
153
+ } catch {
154
+ return [];
155
+ }
156
+ }
157
+
158
+ function writeDiag(dir, entries) {
159
+ const file = diagPath(dir);
160
+ writeStateFile(file, JSON.stringify({ version: DIAG_VERSION, entries }, null, 2) + '\n');
161
+ if (process.platform !== 'win32') {
162
+ try { chmodSync(file, 0o600); } catch { /* the file is still written */ }
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Whether recordDiag would write anything right now. Callers that build a
168
+ * message only for the log (the unpriced-price condition runs once per priced
169
+ * part) ask first, so a machine that is not joined pays nothing.
170
+ */
171
+ export function diagActive({ dir = userDataDir(), env = process.env } = {}) {
172
+ try {
173
+ if (envVar('NO_DIAG', env) === '1' || envVar('NO_TEAM_SYNC', env) === '1') return false;
174
+ // Under `node --test` the process shares the developer's real data dir
175
+ // unless the test pointed XDG_CONFIG_HOME elsewhere: do not log test noise there.
176
+ if (process.env.NODE_TEST_CONTEXT && !process.env.XDG_CONFIG_HOME) return false;
177
+ return isJoinedDir(dir);
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Note one swallowed error. Never throws; silent when this machine is not
185
+ * joined or diagnostics are switched off.
186
+ */
187
+ export function recordDiag(scope, err, { dir = userDataDir(), now = Date.now(), env = process.env } = {}) {
188
+ try {
189
+ if (!diagActive({ dir, env })) return;
190
+ const sc = sanitizeDiag(scope, MAX_SCOPE);
191
+ const msg = messageOf(err);
192
+ const key = keyOf(sc, msg);
193
+ const seen = `${dir}\n${key}`;
194
+ if (seenKeys.has(seen)) return;
195
+ seenKeys.add(seen);
196
+ const entries = readDiag({ dir });
197
+ const iso = new Date(now).toISOString();
198
+ const hit = entries.find((e) => keyOf(e.scope, e.msg) === key);
199
+ if (hit) {
200
+ hit.count += 1;
201
+ hit.last = iso;
202
+ } else {
203
+ entries.push({ scope: sc, msg, count: 1, first: iso, last: iso });
204
+ while (entries.length > MAX_ENTRIES) {
205
+ let oldest = 0;
206
+ for (let i = 1; i < entries.length; i++) if (String(entries[i].last) < String(entries[oldest].last)) oldest = i;
207
+ entries.splice(oldest, 1);
208
+ }
209
+ }
210
+ writeDiag(dir, entries);
211
+ } catch { /* diagnostics must never break the caller, and must not call debug() */ }
212
+ }
213
+
214
+ /**
215
+ * After a successful upload: take the sent counts off the log. The file is read
216
+ * again first, so entries that arrived during the upload stay. An entry whose
217
+ * count drops to zero or below is removed.
218
+ */
219
+ export function ackDiag(sent, { dir = userDataDir() } = {}) {
220
+ try {
221
+ const gone = new Map();
222
+ for (const e of sent || []) {
223
+ if (!validEntry(e)) continue;
224
+ const k = keyOf(e.scope, e.msg);
225
+ gone.set(k, (gone.get(k) || 0) + e.count);
226
+ }
227
+ if (!gone.size) return;
228
+ const kept = [];
229
+ for (const e of readDiag({ dir })) {
230
+ const n = gone.get(keyOf(e.scope, e.msg)) || 0;
231
+ if (e.count - n > 0) kept.push({ ...e, count: e.count - n });
232
+ }
233
+ writeDiag(dir, kept);
234
+ } catch { /* the next upload sends them again */ }
235
+ }
@@ -110,19 +110,48 @@ export function recordGatewayPrices(base, prices, fetchedAtMs = Date.now()) {
110
110
  * limit, or that row lacks the model (or lists it as ambiguous).
111
111
  */
112
112
  export function gatewayPriceAt(model, base, at) {
113
- if (!base || typeof model !== 'string' || !model) return null;
113
+ return resolveAt(model, base, at).price;
114
+ }
115
+
116
+ /**
117
+ * Why `gatewayPriceAt` returned null, as a short label for the diagnostics log:
118
+ * `no-history` (no entry or rows for `base`), `stale` (`at` is later than the
119
+ * freshness limit), `ambiguous` (the key is listed with a null value),
120
+ * `not-listed` (the key is absent) or `bad-time`. null when the model is priced.
121
+ */
122
+ export function gatewayPriceMissReason(model, base, at) {
123
+ return resolveAt(model, base, at).reason;
124
+ }
125
+
126
+ /**
127
+ * The model keys of the price row that `gatewayPriceAt` would use, sorted and
128
+ * cut to `max` (8 by default). Empty when there is no such row. Shows whether
129
+ * the gateway's table lists the model under another name.
130
+ */
131
+ export function gatewayPriceKeys(model, base, at, max = 8) {
132
+ const prices = resolveAt(model, base, at).prices;
133
+ return prices ? Object.keys(prices).sort().slice(0, max) : [];
134
+ }
135
+
136
+ function resolveAt(model, base, at) {
137
+ const miss = (reason, prices = null) => ({ price: null, reason, prices });
138
+ if (!base) return miss('no-history');
114
139
  const t = typeof at === 'number' ? at : Date.parse(at);
115
- if (!Number.isFinite(t)) return null;
140
+ if (!Number.isFinite(t)) return miss('bad-time');
116
141
  const entry = readHistory().gateways[base] ?? seedEntry(base);
117
- if (!entry || !Array.isArray(entry.rows) || entry.rows.length === 0) return null;
118
- if (!Number.isFinite(entry.checkedAt) || t > entry.checkedAt + PRICE_MAX_AGE_MS) return null;
142
+ if (!entry || !Array.isArray(entry.rows) || entry.rows.length === 0) return miss('no-history');
119
143
  const day = dayOf(t);
120
144
  let row = entry.rows[0];
121
145
  for (const r of entry.rows) if (r.from <= day) row = r;
122
146
  const prices = row?.prices;
123
- if (!prices || typeof prices !== 'object') return null;
147
+ if (!prices || typeof prices !== 'object') return miss('no-history');
148
+ // The row is chosen before the freshness check so a stale miss still shows what the table held.
149
+ if (!Number.isFinite(entry.checkedAt) || t > entry.checkedAt + PRICE_MAX_AGE_MS) return miss('stale', prices);
150
+ if (typeof model !== 'string' || !model) return miss('not-listed', prices);
124
151
  for (const key of [model, normalizeCandidate(model)]) {
125
- if (key && Object.hasOwn(prices, key)) return prices[key] || null;
152
+ if (key && Object.hasOwn(prices, key)) {
153
+ return prices[key] ? { price: prices[key], reason: null, prices } : miss('ambiguous', prices);
154
+ }
126
155
  }
127
- return null;
156
+ return miss('not-listed', prices);
128
157
  }
@@ -29,7 +29,7 @@ import { loadProfileMap, updateProfileMap, resetModelAliasCache, profileIdFrom,
29
29
  import { isRecognizedModelId } from './cost.js';
30
30
  import { deploymentPrice, mergePrices, PRICE_MAX_AGE_MS } from './gateway-prices.js';
31
31
  import { debug } from './debug.js';
32
- import { recordGatewayPrices, gatewayPriceAt } from './gateway-price-history.js';
32
+ import { recordGatewayPrices, gatewayPriceAt, gatewayPriceMissReason, gatewayPriceKeys } from './gateway-price-history.js';
33
33
 
34
34
  /** 게이트웨이 모델 맵의 신선도 기준. 배포 구성은 하루에 여러 번 바뀌지 않습니다. */
35
35
  export const MODEL_MAP_TTL_MS = 24 * 60 * 60 * 1000;
@@ -198,6 +198,34 @@ export function gatewayPriceFor(model, env = process.env, now = Date.now(), at)
198
198
  return null;
199
199
  }
200
200
 
201
+ /**
202
+ * gatewayPriceFor 가 null 을 돌려준 까닭을 진단 로그용 짧은 라벨로 돌려줍니다.
203
+ * `at` 이 있으면 날짜별 이력(no-history · stale · ambiguous · not-listed ·
204
+ * bad-time), 없으면 profile-map 의 표(no-table · stale · ambiguous · not-listed).
205
+ * `keys` 는 조회에 쓰인 표의 모델 키(정렬, 최대 8개)입니다. 가격표를 읽을 뿐
206
+ * 네트워크는 쓰지 않습니다.
207
+ *
208
+ * @returns {{reason: string, keys: string[]}}
209
+ */
210
+ export function gatewayPriceMiss(model, env = process.env, now = Date.now(), at) {
211
+ const base = gatewayBase(env);
212
+ if (at !== undefined && at !== null) {
213
+ return { reason: gatewayPriceMissReason(model, base, at) || 'unknown', keys: gatewayPriceKeys(model, base, at) };
214
+ }
215
+ const gateway = readGatewayModelMap(env);
216
+ if (!gateway?.prices || typeof gateway.prices !== 'object') return { reason: 'no-table', keys: [] };
217
+ const keys = Object.keys(gateway.prices).sort().slice(0, 8);
218
+ const fetchedAt = Date.parse(gateway.fetchedAt);
219
+ if (!Number.isFinite(fetchedAt)) return { reason: 'no-table', keys };
220
+ if (fetchedAt > now || now - fetchedAt > PRICE_MAX_AGE_MS) return { reason: 'stale', keys };
221
+ if (typeof model === 'string' && model) {
222
+ for (const key of [model, normalizeCandidate(model)]) {
223
+ if (key && Object.hasOwn(gateway.prices, key)) return { reason: gateway.prices[key] ? 'unknown' : 'ambiguous', keys };
224
+ }
225
+ }
226
+ return { reason: 'not-listed', keys };
227
+ }
228
+
201
229
  /**
202
230
  * profile-map.json의 gateway 절을 읽습니다. base가 현재 gatewayBase(env)와
203
231
  * 다르면 다른 게이트웨이의 캐시이므로 null을 돌려줍니다. 예산 캐시(budgetWindow)
package/src/team-sync.js CHANGED
@@ -40,7 +40,7 @@ import { join } from 'node:path';
40
40
  import { createHash } from 'node:crypto';
41
41
  import { release as osRelease } from 'node:os';
42
42
  import { createRequire } from 'node:module';
43
- import { userDataDir } from './paths.js';
43
+ import { userDataDir, claudeUserDir } from './paths.js';
44
44
  import { writeStateFile } from './state-file.js';
45
45
  import { memberId, readMemberId } from './member-id.js';
46
46
  import { userLanguage } from './config.js';
@@ -59,7 +59,9 @@ import { codexPriceBook, readCodexPrices, refreshCodexPrices, codexRunCost, CODE
59
59
  import { codexRequestCost } from './gateway-prices.js';
60
60
  import { codexBudgetProvider } from './codex/budget.js';
61
61
  import { fetchGatewayDailySpend, gatewayDayValue, gatewayEnv } from './gateway-spend.js';
62
- import { withClaudeSettingsEnv } from './gateway-auth.js';
62
+ import { withClaudeSettingsEnv, gatewayBase } from './gateway-auth.js';
63
+ import { maybeRefreshGatewayModelMap, readGatewayModelMap } from './litellm-models.js';
64
+ import { recordDiag, readDiag, ackDiag } from './diag-log.js';
63
65
 
64
66
  export const PROMPT_SYNC_INTERVAL_MS = 30 * 60 * 1000;
65
67
 
@@ -528,6 +530,7 @@ export async function aggregateDaily({
528
530
 
529
531
  // Claude Code and Cowork sessions are priced alike; Cowork transcripts live
530
532
  // outside ~/.claude/projects (see cowork-sessions.js).
533
+ const seen = { claude: 0, cowork: 0, codex: 0 }; // sessions parsed (or passed in), for the no-rows diagnostic
531
534
  const addClaudeSessions = (list) => {
532
535
  for (const s of list || []) {
533
536
  if (!s || !s.startTime || !s.totals) continue;
@@ -552,6 +555,7 @@ export async function aggregateDaily({
552
555
  const { parseAllSessions } = await import('./parser.js');
553
556
  list = await parseAllSessions({ days });
554
557
  }
558
+ seen.claude = (list || []).length;
555
559
  addClaudeSessions(list);
556
560
  } catch (e) { debug('team-sync', e); }
557
561
 
@@ -561,6 +565,7 @@ export async function aggregateDaily({
561
565
  const { parseCoworkSessions } = await import('./cowork-sessions.js');
562
566
  list = await parseCoworkSessions({ days });
563
567
  }
568
+ seen.cowork = (list || []).length;
564
569
  addClaudeSessions(list);
565
570
  } catch (e) { debug('team-sync', e); }
566
571
 
@@ -572,6 +577,7 @@ export async function aggregateDaily({
572
577
  const { parseAllCodexSessions } = await import('./codex/parser.js');
573
578
  list = await parseAllCodexSessions({ days, compressed: true, keepRequests: true });
574
579
  }
580
+ seen.codex = (list || []).length;
575
581
  const prices = codexPrices === undefined ? readCodexPrices({ now, dir }) : codexPrices;
576
582
  for (const s of list || []) {
577
583
  if (!s || !s.startTime || !s.totals) continue;
@@ -598,7 +604,7 @@ export async function aggregateDaily({
598
604
  }
599
605
  }
600
606
 
601
- return [...byDay.entries()]
607
+ const rows = [...byDay.entries()]
602
608
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
603
609
  .map(([day, d]) => {
604
610
  const claude = round4(d.spent), codex = round4(d.codex);
@@ -629,6 +635,21 @@ export async function aggregateDaily({
629
635
  };
630
636
  })
631
637
  .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);
638
+ if (!rows.length) noteNoRows({ seen, env, dir });
639
+ return rows;
640
+ }
641
+
642
+ // A machine whose sync uploads nothing: say how many sessions each parser saw and
643
+ // whether the Claude projects directory is even there. The counts are small
644
+ // integers and yes/no flags, so the message dedupes to a handful per machine.
645
+ function noteNoRows({ seen, env, dir }) {
646
+ try {
647
+ const projectsDir = existsSync(join(claudeUserDir(), 'projects'));
648
+ const configDir = (process.env.CLAUDE_CONFIG_DIR || (env && env.CLAUDE_CONFIG_DIR)) ? 'set' : 'unset';
649
+ recordDiag('team-sync:no-rows', new Error(
650
+ `claude=${seen.claude} cowork=${seen.cowork} codex=${seen.codex} projectsDir=${projectsDir} configDir=${configDir} gateway=${gatewayBase(env) ? 'yes' : 'no'}`,
651
+ ), { dir, env });
652
+ } catch { /* diagnostics only */ }
632
653
  }
633
654
 
634
655
  // After a failed refresh the gateway is left alone for this long; syncs run every 5 minutes.
@@ -873,6 +894,47 @@ async function reportRuleStats({ state, dir, fetch, now }) {
873
894
  }
874
895
  }
875
896
 
897
+ export const DIAG_UPLOAD_INTERVAL_MS = 30 * 60 * 1000;
898
+ const DIAG_UPLOAD_MAX = 100;
899
+
900
+ /**
901
+ * Upload the local diagnostics log (diag-log.js) to diag_upload: error text
902
+ * only, newest 100 entries, at most once per DIAG_UPLOAD_INTERVAL_MS unless
903
+ * `force`. Returns `{ diag, lastDiagAt }` after an upload, `{ lastDiagError }`
904
+ * after a failed one, and null when nothing was due. A server without the
905
+ * function (not migrated yet) is silent. It never throws, never fails the sync,
906
+ * and does not call debug() on its own failure: that would put the upload error
907
+ * into the log it is trying to send.
908
+ */
909
+ async function uploadDiag({ state, dir, fetch, version, now, force = false, env = process.env }) {
910
+ try {
911
+ if (envVar('NO_DIAG', env) === '1') return null;
912
+ if (!force && Number.isFinite(state.lastDiagAt) && now - state.lastDiagAt >= 0 && now - state.lastDiagAt < DIAG_UPLOAD_INTERVAL_MS) return null;
913
+ const entries = readDiag({ dir });
914
+ if (!entries.length) return null;
915
+ const sent = [...entries].sort((a, b) => (a.last < b.last ? 1 : a.last > b.last ? -1 : 0)).slice(0, DIAG_UPLOAD_MAX);
916
+ try {
917
+ const n = await rpc('diag_upload', { member_key: state.memberKey, entries: sent, sprag_version: version || '' }, { fetch });
918
+ ackDiag(sent, { dir });
919
+ return { diag: Number.isFinite(n) ? n : sent.length, lastDiagAt: now };
920
+ } catch (e) {
921
+ if (/Could not find the function|PGRST202/.test(String(e && e.message))) return null;
922
+ return { lastDiagError: String((e && e.message) || e).slice(0, 200) };
923
+ }
924
+ } catch {
925
+ return null;
926
+ }
927
+ }
928
+
929
+ /** The team.json fields an uploadDiag result changes. */
930
+ function withDiagMeta(state, d) {
931
+ if (!d) return state;
932
+ const next = { ...state };
933
+ if (d.lastDiagAt) { next.lastDiagAt = d.lastDiagAt; delete next.lastDiagError; }
934
+ if (d.lastDiagError) next.lastDiagError = d.lastDiagError;
935
+ return next;
936
+ }
937
+
876
938
  /**
877
939
  * `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
878
940
  * is injected separately so tests can fake each side). `coworkSessions`, `codexSessions`,
@@ -955,15 +1017,31 @@ export async function syncTeam({
955
1017
  // price Claude the same way and both see the gateway figure.
956
1018
  env = withClaudeSettingsEnv(env);
957
1019
  const hasGateway = !!gatewayEnv(env);
1020
+ // A gateway address without a usable key: no daily figure can be fetched. (Not `key=no`: the secret masker reads `KEY=value` as a secret.)
1021
+ if (!hasGateway && gatewayBase(env)) recordDiag('team-sync:gateway-env', new Error('base=yes daily=no missing=key'), { dir, env });
958
1022
  // Days the delegation ledger changed after they were uploaded (a rescan
959
1023
  // repriced them) go up again from the earliest one.
960
1024
  let change = null;
961
1025
  try { change = changedSinceForSync(); } catch (e) { debug('team-sync', e); }
962
- const win = ledgerWindow(state, now, { gateway: hasGateway, changedSince: change?.since });
1026
+ // The gateway's price table. Until it is fetched every Claude call on this
1027
+ // gateway is unpriced; the statusline's budget child fetched it only when the
1028
+ // budget calls succeeded. The first table ever re-sends the whole window, so
1029
+ // the days already uploaded as unpriced get their spend.
1030
+ let firstTable = false;
1031
+ if (hasGateway) {
1032
+ try {
1033
+ const g = gatewayEnv(env);
1034
+ const hadTable = !!readGatewayModelMap(env);
1035
+ const fetched = await maybeRefreshGatewayModelMap({ base: g.base, key: g.key, fetchImpl: gatewayFetch, now });
1036
+ firstTable = !hadTable && !!fetched;
1037
+ } catch (e) { debug('team-sync:prices', e); }
1038
+ }
1039
+ const win = ledgerWindow(firstTable ? { ...state, ledgerSyncedThrough: null } : state, now, { gateway: hasGateway, changedSince: change?.since });
963
1040
  // The gateway's request log is read only from the first day going up.
964
1041
  let gatewayDaily = null;
965
1042
  if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now, from: win.startKey });
966
1043
  const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
1044
+ if (gatewayDaily && gatewayDaily.error) recordDiag('team-sync:gateway-daily', new Error(String(gatewayDaily.error)), { dir, env });
967
1045
  let prices = codexPrices;
968
1046
  if (prices === undefined) {
969
1047
  const r = await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch, attemptedAt: state.codexPricesAttemptAt });
@@ -976,7 +1054,8 @@ export async function syncTeam({
976
1054
  await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
977
1055
  const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
978
1056
  const ruleStats = await reportRuleStats({ state, dir, fetch, now });
979
- const next = withRulesMeta({ ...state, ...ruleStats, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, r, now);
1057
+ const diag = await uploadDiag({ state, dir, fetch, version, now, force, env });
1058
+ const next = withRulesMeta(withDiagMeta({ ...state, ...ruleStats, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, diag), r, now);
980
1059
  if (gatewayOk) next.gatewaySyncedThrough = dayKey(now);
981
1060
  else if (gatewayDaily && gatewayDaily.error) next.lastGatewayError = gatewayDaily.error;
982
1061
  if (gatewayOk || !hasGateway) delete next.lastGatewayError;
@@ -997,6 +1076,11 @@ export async function syncTeam({
997
1076
  try {
998
1077
  saveTeamState({ ...state, lastSyncAttemptAt: now, syncFailures: (Number(state.syncFailures) || 0) + 1, lastError: e.message }, dir);
999
1078
  } catch (e2) { debug('team-sync', e2); }
1079
+ // The failure that just happened is exactly what the operator needs to see.
1080
+ try {
1081
+ const diag = await uploadDiag({ state, dir, fetch, version, now, force: true, env });
1082
+ if (diag) saveTeamState(withDiagMeta(loadTeamState(dir), diag), dir);
1083
+ } catch { /* best effort */ }
1000
1084
  return { error: e.message };
1001
1085
  }
1002
1086
  }