sprag-cli 3.107.1 → 3.109.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/package.json +1 -1
- package/presets/delegation/bounds.md +8 -1
- package/src/claude-price.js +14 -1
- package/src/commands/team.js +11 -2
- package/src/debug.js +6 -0
- package/src/diag-log.js +231 -0
- package/src/gateway-price-history.js +36 -7
- package/src/judgement-prompt.js +8 -0
- package/src/litellm-models.js +29 -1
- package/src/model-rules.js +2 -0
- package/src/team-sync.js +74 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.109.0",
|
|
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": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Delegation bounds
|
|
2
2
|
|
|
3
|
-
You were spawned by a delegation call from another session. These
|
|
3
|
+
You were spawned by a delegation call from another session. These six rules
|
|
4
4
|
keep your exploration finite and your output usable by the caller that spawned
|
|
5
5
|
you.
|
|
6
6
|
|
|
@@ -34,3 +34,10 @@ you.
|
|
|
34
34
|
command lookup and fails). Quote any argument with `?`, `*` or `[`, URLs
|
|
35
35
|
above all. The shell tool is `Bash`, with a capital B. A refused command
|
|
36
36
|
line wastes a call and reads as a failure in the caller's records.
|
|
37
|
+
|
|
38
|
+
6. **Look where the answer lives before calling it unknown.** When a page
|
|
39
|
+
carries its key content in images or screenshots, open them before you
|
|
40
|
+
report the content as unverifiable. When the question presumes something
|
|
41
|
+
exists ("which file implements X") and you cannot find it, say that nothing
|
|
42
|
+
implements it, or how it actually happens, instead of naming the closest
|
|
43
|
+
match.
|
package/src/claude-price.js
CHANGED
|
@@ -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.
|
package/src/commands/team.js
CHANGED
|
@@ -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`);
|
package/src/diag-log.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
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
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A path without the directories that could name a project: the last segment
|
|
59
|
+
* only, behind `…`. A home dot-directory (`~/.claude/projects/...`) keeps its
|
|
60
|
+
* first two segments, which say which tool's files were missing; a project
|
|
61
|
+
* directory below them is dropped all the same.
|
|
62
|
+
*/
|
|
63
|
+
function shortPath(p) {
|
|
64
|
+
const root = p.startsWith('~') ? '~' : /^[A-Za-z]:/.test(p) ? p.slice(0, 2) : '';
|
|
65
|
+
const sep = p.includes('\\') && !p.includes('/') ? '\\' : '/';
|
|
66
|
+
const parts = p.slice(root.length).split(/[\\/]/).filter(Boolean);
|
|
67
|
+
const keep = root === '~' && parts[0]?.startsWith('.') ? Math.min(2, parts.length) : 0;
|
|
68
|
+
if (parts.length <= keep + 1) return p;
|
|
69
|
+
return root + sep + [...parts.slice(0, keep), '…', parts[parts.length - 1]].join(sep);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Text that is safe to leave the machine: home directory -> `~`, a path cut to
|
|
74
|
+
* its last segment (see shortPath), every
|
|
75
|
+
* scheme://host[:port] -> `<host>` (path kept), secrets masked, e-mail
|
|
76
|
+
* addresses -> `<email>`, whitespace collapsed, cut to `max` characters.
|
|
77
|
+
*/
|
|
78
|
+
export function sanitizeDiag(text, max = MAX_MSG) {
|
|
79
|
+
let s = String(text ?? '');
|
|
80
|
+
try {
|
|
81
|
+
const home = homedir();
|
|
82
|
+
if (home && home.length > 1) s = s.split(home).join('~');
|
|
83
|
+
} catch { /* no home directory to mask */ }
|
|
84
|
+
s = s.replace(URL_RE, '<host>');
|
|
85
|
+
s = s.replace(PATH_RE, (_, lead, p) => lead + shortPath(p));
|
|
86
|
+
s = s.replace(ARN_ACCOUNT_RE, '$1<acct>$2'); // a model id can be an ARN, and an ARN holds the AWS account id
|
|
87
|
+
s = redactSecrets(s);
|
|
88
|
+
s = s.replace(EMAIL_RE, '<email>');
|
|
89
|
+
s = s.replace(/\s+/g, ' ').trim();
|
|
90
|
+
return s.length > max ? s.slice(0, max) : s;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** `src/<file>.js:<line>` of the first stack frame inside sprag's own src/, or ''. */
|
|
94
|
+
function ownFrame(stack) {
|
|
95
|
+
if (typeof stack !== 'string') return '';
|
|
96
|
+
for (const line of stack.split('\n')) {
|
|
97
|
+
for (const needle of [diagSrcDir, SRC_URL]) {
|
|
98
|
+
const at = line.indexOf(needle);
|
|
99
|
+
if (at < 0) continue;
|
|
100
|
+
const m = /^[\\/]([^\s():]+?\.c?js):(\d+)/.exec(line.slice(at + needle.length));
|
|
101
|
+
if (m) return `src/${m[1].replace(/\\/g, '/')}:${m[2]}`;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return '';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function messageOf(err) {
|
|
108
|
+
let msg;
|
|
109
|
+
if (err && typeof err === 'object' && 'message' in err) msg = String(err.message);
|
|
110
|
+
else msg = String(err);
|
|
111
|
+
const first = msg.split('\n').find((l) => l.trim()) || '';
|
|
112
|
+
const frame = err && typeof err === 'object' ? ownFrame(err.stack) : '';
|
|
113
|
+
if (!frame) return sanitizeDiag(first);
|
|
114
|
+
return sanitizeDiag(`${sanitizeDiag(first, MAX_MSG - frame.length - 4)} @ ${frame}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const keyOf = (scope, msg) => `${scope}\n${msg}`;
|
|
118
|
+
|
|
119
|
+
const joinedByDir = new Map(); // dir -> boolean, read once per process
|
|
120
|
+
const seenKeys = new Set(); // `${dir}\n${scope}\n${msg}` written (or attempted) by this process
|
|
121
|
+
|
|
122
|
+
/** Forget what this process cached. For tests that simulate a second process. */
|
|
123
|
+
export function _resetDiagForTest() {
|
|
124
|
+
joinedByDir.clear();
|
|
125
|
+
seenKeys.clear();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isJoinedDir(dir) {
|
|
129
|
+
if (joinedByDir.has(dir)) return joinedByDir.get(dir);
|
|
130
|
+
let joined = false;
|
|
131
|
+
try {
|
|
132
|
+
const s = JSON.parse(readFileSync(join(dir, 'team.json'), 'utf8'));
|
|
133
|
+
joined = !!(s && s.memberKey && !s.left);
|
|
134
|
+
} catch { /* no team state: not joined */ }
|
|
135
|
+
joinedByDir.set(dir, joined);
|
|
136
|
+
return joined;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function validEntry(e) {
|
|
140
|
+
return !!e && typeof e === 'object' && typeof e.scope === 'string' && typeof e.msg === 'string' && Number.isFinite(e.count) && e.count > 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The entries waiting in the log. Empty on any problem. */
|
|
144
|
+
export function readDiag({ dir = userDataDir() } = {}) {
|
|
145
|
+
try {
|
|
146
|
+
const data = JSON.parse(readFileSync(diagPath(dir), 'utf8'));
|
|
147
|
+
if (!data || data.version !== DIAG_VERSION || !Array.isArray(data.entries)) return [];
|
|
148
|
+
return data.entries.filter(validEntry);
|
|
149
|
+
} catch {
|
|
150
|
+
return [];
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function writeDiag(dir, entries) {
|
|
155
|
+
const file = diagPath(dir);
|
|
156
|
+
writeStateFile(file, JSON.stringify({ version: DIAG_VERSION, entries }, null, 2) + '\n');
|
|
157
|
+
if (process.platform !== 'win32') {
|
|
158
|
+
try { chmodSync(file, 0o600); } catch { /* the file is still written */ }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Whether recordDiag would write anything right now. Callers that build a
|
|
164
|
+
* message only for the log (the unpriced-price condition runs once per priced
|
|
165
|
+
* part) ask first, so a machine that is not joined pays nothing.
|
|
166
|
+
*/
|
|
167
|
+
export function diagActive({ dir = userDataDir(), env = process.env } = {}) {
|
|
168
|
+
try {
|
|
169
|
+
if (envVar('NO_DIAG', env) === '1' || envVar('NO_TEAM_SYNC', env) === '1') return false;
|
|
170
|
+
// Under `node --test` the process shares the developer's real data dir
|
|
171
|
+
// unless the test pointed XDG_CONFIG_HOME elsewhere: do not log test noise there.
|
|
172
|
+
if (process.env.NODE_TEST_CONTEXT && !process.env.XDG_CONFIG_HOME) return false;
|
|
173
|
+
return isJoinedDir(dir);
|
|
174
|
+
} catch {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Note one swallowed error. Never throws; silent when this machine is not
|
|
181
|
+
* joined or diagnostics are switched off.
|
|
182
|
+
*/
|
|
183
|
+
export function recordDiag(scope, err, { dir = userDataDir(), now = Date.now(), env = process.env } = {}) {
|
|
184
|
+
try {
|
|
185
|
+
if (!diagActive({ dir, env })) return;
|
|
186
|
+
const sc = sanitizeDiag(scope, MAX_SCOPE);
|
|
187
|
+
const msg = messageOf(err);
|
|
188
|
+
const key = keyOf(sc, msg);
|
|
189
|
+
const seen = `${dir}\n${key}`;
|
|
190
|
+
if (seenKeys.has(seen)) return;
|
|
191
|
+
seenKeys.add(seen);
|
|
192
|
+
const entries = readDiag({ dir });
|
|
193
|
+
const iso = new Date(now).toISOString();
|
|
194
|
+
const hit = entries.find((e) => keyOf(e.scope, e.msg) === key);
|
|
195
|
+
if (hit) {
|
|
196
|
+
hit.count += 1;
|
|
197
|
+
hit.last = iso;
|
|
198
|
+
} else {
|
|
199
|
+
entries.push({ scope: sc, msg, count: 1, first: iso, last: iso });
|
|
200
|
+
while (entries.length > MAX_ENTRIES) {
|
|
201
|
+
let oldest = 0;
|
|
202
|
+
for (let i = 1; i < entries.length; i++) if (String(entries[i].last) < String(entries[oldest].last)) oldest = i;
|
|
203
|
+
entries.splice(oldest, 1);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
writeDiag(dir, entries);
|
|
207
|
+
} catch { /* diagnostics must never break the caller, and must not call debug() */ }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* After a successful upload: take the sent counts off the log. The file is read
|
|
212
|
+
* again first, so entries that arrived during the upload stay. An entry whose
|
|
213
|
+
* count drops to zero or below is removed.
|
|
214
|
+
*/
|
|
215
|
+
export function ackDiag(sent, { dir = userDataDir() } = {}) {
|
|
216
|
+
try {
|
|
217
|
+
const gone = new Map();
|
|
218
|
+
for (const e of sent || []) {
|
|
219
|
+
if (!validEntry(e)) continue;
|
|
220
|
+
const k = keyOf(e.scope, e.msg);
|
|
221
|
+
gone.set(k, (gone.get(k) || 0) + e.count);
|
|
222
|
+
}
|
|
223
|
+
if (!gone.size) return;
|
|
224
|
+
const kept = [];
|
|
225
|
+
for (const e of readDiag({ dir })) {
|
|
226
|
+
const n = gone.get(keyOf(e.scope, e.msg)) || 0;
|
|
227
|
+
if (e.count - n > 0) kept.push({ ...e, count: e.count - n });
|
|
228
|
+
}
|
|
229
|
+
writeDiag(dir, kept);
|
|
230
|
+
} catch { /* the next upload sends them again */ }
|
|
231
|
+
}
|
|
@@ -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
|
-
|
|
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
|
|
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
|
|
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
|
|
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))
|
|
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
|
|
156
|
+
return miss('not-listed', prices);
|
|
128
157
|
}
|
package/src/judgement-prompt.js
CHANGED
|
@@ -43,6 +43,11 @@
|
|
|
43
43
|
* investigation" describe the purpose, not the job). Over the 240 prompts of
|
|
44
44
|
* the delegation-ledger snapshot the pass flags 52, about 22%. Both samples
|
|
45
45
|
* come from one user.
|
|
46
|
+
*
|
|
47
|
+
* Added 2026-11-09 after the v4 replay (23 delegations, verify-graded): a
|
|
48
|
+
* question asking which file implements a behaviour that no file implements
|
|
49
|
+
* came back unanswered from Sonnet. The new absence pattern flags 2 of the 309
|
|
50
|
+
* snapshot prompts, both of that shape.
|
|
46
51
|
*/
|
|
47
52
|
|
|
48
53
|
const MARKER = '<!-- sprag:delegation -->';
|
|
@@ -70,6 +75,9 @@ const PATTERNS = {
|
|
|
70
75
|
],
|
|
71
76
|
absence: [
|
|
72
77
|
/없다는 (?:결론|사실)|없다고 (?:단정|판단|보고)|없음을 (?:확인|단정)|(?:is|are) there any\b|does (?:it|the page|the doc|the docs|any page|this) (?:say|mention|describe)|any mention\b|if the page does not answer|read-only search\b/,
|
|
78
|
+
// Asking which code does a behaviour presumes some code does. When none does, or it happens another way
|
|
79
|
+
// (an @ import rather than a hook), the honest answer is that absence, which a cheaper model misses.
|
|
80
|
+
/which (?:source )?(?:file|function|module|code)s? (?:implements|injects|handles|is responsible for)\b|어디서 어떻게 구현|어느 (?:파일|함수|모듈)(?:이|가) [^\n]{0,30}(?:구현|주입|처리)하/,
|
|
73
81
|
],
|
|
74
82
|
conditional: [
|
|
75
83
|
/출력에 따라|결과에 따라|보고 (?:나서 )?(?:더 |어느 )|필요하면 (?:소스|코드|파일|로그)|depending on (?:what|the output|the result)|decide (?:which|what) to (?:open|read|look)|follow (?:the )?leads|(?:무엇|뭔)(?:인지)?(?:는|은)? 아직 모(?:른다|릅니다)|구현 (?:상태|여부)[^\n]{0,10}(?:조사|확인)|(?:막히면|실패하면|안 되면|if (?:it is blocked|that fails|blocked))[^\n]{0,80}(?:다음|대체|우회|fall ?back|시도|instead|try)/,
|
package/src/litellm-models.js
CHANGED
|
@@ -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/model-rules.js
CHANGED
|
@@ -341,6 +341,8 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root, grade =
|
|
|
341
341
|
' 바꿔 9회 돌렸고 9회 모두 반려된 후보를 다시 추천했습니다).',
|
|
342
342
|
'- 개선점이나 권고를 내는 검토, 감사, 원인 진단, 검색이 필요한 조사, 무엇이 "없다"고',
|
|
343
343
|
' 단정해야 하는 조회, 출력을 보고 더 볼 곳을 정해야 하는 점검은 결론이 판단입니다.',
|
|
344
|
+
' "어느 파일이 이 동작을 하는가"처럼 동작을 하는 코드를 찾는 조회도 여기에 듭니다. 그런',
|
|
345
|
+
' 코드가 없거나 다른 경로로 일어나면 "없다"가 답이기 때문입니다.',
|
|
344
346
|
' 이런 일은 위임하지 않고 메인이 맡습니다. 세션이 Sonnet이면 Opus(effort high)로',
|
|
345
347
|
' 올립니다. effort xhigh는 권하지 않습니다(판단형 10건 실측에서 틀린 주장이 3개에서',
|
|
346
348
|
' 11개로 늘었습니다). 메인 세션의 effort가 low나 medium이면 판단 부분을 Opus effort high',
|
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,8 @@ 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 { recordDiag, readDiag, ackDiag } from './diag-log.js';
|
|
63
64
|
|
|
64
65
|
export const PROMPT_SYNC_INTERVAL_MS = 30 * 60 * 1000;
|
|
65
66
|
|
|
@@ -528,6 +529,7 @@ export async function aggregateDaily({
|
|
|
528
529
|
|
|
529
530
|
// Claude Code and Cowork sessions are priced alike; Cowork transcripts live
|
|
530
531
|
// outside ~/.claude/projects (see cowork-sessions.js).
|
|
532
|
+
const seen = { claude: 0, cowork: 0, codex: 0 }; // sessions parsed (or passed in), for the no-rows diagnostic
|
|
531
533
|
const addClaudeSessions = (list) => {
|
|
532
534
|
for (const s of list || []) {
|
|
533
535
|
if (!s || !s.startTime || !s.totals) continue;
|
|
@@ -552,6 +554,7 @@ export async function aggregateDaily({
|
|
|
552
554
|
const { parseAllSessions } = await import('./parser.js');
|
|
553
555
|
list = await parseAllSessions({ days });
|
|
554
556
|
}
|
|
557
|
+
seen.claude = (list || []).length;
|
|
555
558
|
addClaudeSessions(list);
|
|
556
559
|
} catch (e) { debug('team-sync', e); }
|
|
557
560
|
|
|
@@ -561,6 +564,7 @@ export async function aggregateDaily({
|
|
|
561
564
|
const { parseCoworkSessions } = await import('./cowork-sessions.js');
|
|
562
565
|
list = await parseCoworkSessions({ days });
|
|
563
566
|
}
|
|
567
|
+
seen.cowork = (list || []).length;
|
|
564
568
|
addClaudeSessions(list);
|
|
565
569
|
} catch (e) { debug('team-sync', e); }
|
|
566
570
|
|
|
@@ -572,6 +576,7 @@ export async function aggregateDaily({
|
|
|
572
576
|
const { parseAllCodexSessions } = await import('./codex/parser.js');
|
|
573
577
|
list = await parseAllCodexSessions({ days, compressed: true, keepRequests: true });
|
|
574
578
|
}
|
|
579
|
+
seen.codex = (list || []).length;
|
|
575
580
|
const prices = codexPrices === undefined ? readCodexPrices({ now, dir }) : codexPrices;
|
|
576
581
|
for (const s of list || []) {
|
|
577
582
|
if (!s || !s.startTime || !s.totals) continue;
|
|
@@ -598,7 +603,7 @@ export async function aggregateDaily({
|
|
|
598
603
|
}
|
|
599
604
|
}
|
|
600
605
|
|
|
601
|
-
|
|
606
|
+
const rows = [...byDay.entries()]
|
|
602
607
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
603
608
|
.map(([day, d]) => {
|
|
604
609
|
const claude = round4(d.spent), codex = round4(d.codex);
|
|
@@ -629,6 +634,21 @@ export async function aggregateDaily({
|
|
|
629
634
|
};
|
|
630
635
|
})
|
|
631
636
|
.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);
|
|
637
|
+
if (!rows.length) noteNoRows({ seen, env, dir });
|
|
638
|
+
return rows;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// A machine whose sync uploads nothing: say how many sessions each parser saw and
|
|
642
|
+
// whether the Claude projects directory is even there. The counts are small
|
|
643
|
+
// integers and yes/no flags, so the message dedupes to a handful per machine.
|
|
644
|
+
function noteNoRows({ seen, env, dir }) {
|
|
645
|
+
try {
|
|
646
|
+
const projectsDir = existsSync(join(claudeUserDir(), 'projects'));
|
|
647
|
+
const configDir = (process.env.CLAUDE_CONFIG_DIR || (env && env.CLAUDE_CONFIG_DIR)) ? 'set' : 'unset';
|
|
648
|
+
recordDiag('team-sync:no-rows', new Error(
|
|
649
|
+
`claude=${seen.claude} cowork=${seen.cowork} codex=${seen.codex} projectsDir=${projectsDir} configDir=${configDir} gateway=${gatewayBase(env) ? 'yes' : 'no'}`,
|
|
650
|
+
), { dir, env });
|
|
651
|
+
} catch { /* diagnostics only */ }
|
|
632
652
|
}
|
|
633
653
|
|
|
634
654
|
// After a failed refresh the gateway is left alone for this long; syncs run every 5 minutes.
|
|
@@ -873,6 +893,47 @@ async function reportRuleStats({ state, dir, fetch, now }) {
|
|
|
873
893
|
}
|
|
874
894
|
}
|
|
875
895
|
|
|
896
|
+
export const DIAG_UPLOAD_INTERVAL_MS = 30 * 60 * 1000;
|
|
897
|
+
const DIAG_UPLOAD_MAX = 100;
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Upload the local diagnostics log (diag-log.js) to diag_upload: error text
|
|
901
|
+
* only, newest 100 entries, at most once per DIAG_UPLOAD_INTERVAL_MS unless
|
|
902
|
+
* `force`. Returns `{ diag, lastDiagAt }` after an upload, `{ lastDiagError }`
|
|
903
|
+
* after a failed one, and null when nothing was due. A server without the
|
|
904
|
+
* function (not migrated yet) is silent. It never throws, never fails the sync,
|
|
905
|
+
* and does not call debug() on its own failure: that would put the upload error
|
|
906
|
+
* into the log it is trying to send.
|
|
907
|
+
*/
|
|
908
|
+
async function uploadDiag({ state, dir, fetch, version, now, force = false, env = process.env }) {
|
|
909
|
+
try {
|
|
910
|
+
if (envVar('NO_DIAG', env) === '1') return null;
|
|
911
|
+
if (!force && Number.isFinite(state.lastDiagAt) && now - state.lastDiagAt >= 0 && now - state.lastDiagAt < DIAG_UPLOAD_INTERVAL_MS) return null;
|
|
912
|
+
const entries = readDiag({ dir });
|
|
913
|
+
if (!entries.length) return null;
|
|
914
|
+
const sent = [...entries].sort((a, b) => (a.last < b.last ? 1 : a.last > b.last ? -1 : 0)).slice(0, DIAG_UPLOAD_MAX);
|
|
915
|
+
try {
|
|
916
|
+
const n = await rpc('diag_upload', { member_key: state.memberKey, entries: sent, sprag_version: version || '' }, { fetch });
|
|
917
|
+
ackDiag(sent, { dir });
|
|
918
|
+
return { diag: Number.isFinite(n) ? n : sent.length, lastDiagAt: now };
|
|
919
|
+
} catch (e) {
|
|
920
|
+
if (/Could not find the function|PGRST202/.test(String(e && e.message))) return null;
|
|
921
|
+
return { lastDiagError: String((e && e.message) || e).slice(0, 200) };
|
|
922
|
+
}
|
|
923
|
+
} catch {
|
|
924
|
+
return null;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** The team.json fields an uploadDiag result changes. */
|
|
929
|
+
function withDiagMeta(state, d) {
|
|
930
|
+
if (!d) return state;
|
|
931
|
+
const next = { ...state };
|
|
932
|
+
if (d.lastDiagAt) { next.lastDiagAt = d.lastDiagAt; delete next.lastDiagError; }
|
|
933
|
+
if (d.lastDiagError) next.lastDiagError = d.lastDiagError;
|
|
934
|
+
return next;
|
|
935
|
+
}
|
|
936
|
+
|
|
876
937
|
/**
|
|
877
938
|
* `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
|
|
878
939
|
* is injected separately so tests can fake each side). `coworkSessions`, `codexSessions`,
|
|
@@ -955,6 +1016,8 @@ export async function syncTeam({
|
|
|
955
1016
|
// price Claude the same way and both see the gateway figure.
|
|
956
1017
|
env = withClaudeSettingsEnv(env);
|
|
957
1018
|
const hasGateway = !!gatewayEnv(env);
|
|
1019
|
+
// 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.)
|
|
1020
|
+
if (!hasGateway && gatewayBase(env)) recordDiag('team-sync:gateway-env', new Error('base=yes daily=no missing=key'), { dir, env });
|
|
958
1021
|
// Days the delegation ledger changed after they were uploaded (a rescan
|
|
959
1022
|
// repriced them) go up again from the earliest one.
|
|
960
1023
|
let change = null;
|
|
@@ -964,6 +1027,7 @@ export async function syncTeam({
|
|
|
964
1027
|
let gatewayDaily = null;
|
|
965
1028
|
if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now, from: win.startKey });
|
|
966
1029
|
const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
|
|
1030
|
+
if (gatewayDaily && gatewayDaily.error) recordDiag('team-sync:gateway-daily', new Error(String(gatewayDaily.error)), { dir, env });
|
|
967
1031
|
let prices = codexPrices;
|
|
968
1032
|
if (prices === undefined) {
|
|
969
1033
|
const r = await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch, attemptedAt: state.codexPricesAttemptAt });
|
|
@@ -976,7 +1040,8 @@ export async function syncTeam({
|
|
|
976
1040
|
await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
|
|
977
1041
|
const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
|
|
978
1042
|
const ruleStats = await reportRuleStats({ state, dir, fetch, now });
|
|
979
|
-
const
|
|
1043
|
+
const diag = await uploadDiag({ state, dir, fetch, version, now, force, env });
|
|
1044
|
+
const next = withRulesMeta(withDiagMeta({ ...state, ...ruleStats, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, diag), r, now);
|
|
980
1045
|
if (gatewayOk) next.gatewaySyncedThrough = dayKey(now);
|
|
981
1046
|
else if (gatewayDaily && gatewayDaily.error) next.lastGatewayError = gatewayDaily.error;
|
|
982
1047
|
if (gatewayOk || !hasGateway) delete next.lastGatewayError;
|
|
@@ -997,6 +1062,11 @@ export async function syncTeam({
|
|
|
997
1062
|
try {
|
|
998
1063
|
saveTeamState({ ...state, lastSyncAttemptAt: now, syncFailures: (Number(state.syncFailures) || 0) + 1, lastError: e.message }, dir);
|
|
999
1064
|
} catch (e2) { debug('team-sync', e2); }
|
|
1065
|
+
// The failure that just happened is exactly what the operator needs to see.
|
|
1066
|
+
try {
|
|
1067
|
+
const diag = await uploadDiag({ state, dir, fetch, version, now, force: true, env });
|
|
1068
|
+
if (diag) saveTeamState(withDiagMeta(loadTeamState(dir), diag), dir);
|
|
1069
|
+
} catch { /* best effort */ }
|
|
1000
1070
|
return { error: e.message };
|
|
1001
1071
|
}
|
|
1002
1072
|
}
|