sprag-cli 3.84.0 → 3.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +2 -0
- package/docs/TEAM.ko.md +13 -4
- package/docs/TEAM.md +13 -4
- package/package.json +1 -1
- package/presets/agents.json +1 -1
- package/src/codex/cache-policy.js +6 -3
- package/src/codex/delegation.js +21 -3
- package/src/codex/ledger.js +2 -1
- package/src/codex/parser.js +24 -4
- package/src/commands/codex.js +2 -0
- package/src/commands/delegate.js +14 -1
- package/src/commands/route-scan.js +5 -1
- package/src/commands/team.js +20 -0
- package/src/commands/upgrade.js +137 -1
- package/src/cost.js +31 -7
- package/src/cowork-sessions.js +91 -0
- package/src/cowork-sync.js +2 -10
- package/src/delegation-agents.js +76 -6
- package/src/gateway-auth.js +33 -0
- package/src/gateway-prices.js +54 -2
- package/src/litellm-models.js +2 -3
- package/src/org-upgrade.js +179 -0
- package/src/parser.js +16 -8
- package/src/session-cache.js +10 -7
- package/src/team-sync.js +94 -29
- package/src/transcript-lines.js +66 -0
- package/src/update-notice.js +10 -2
package/src/cost.js
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* Cache writes are now tracked separately for 5m and 1h TTLs, each with their own rate.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { priceForPrompt } from './gateway-prices.js';
|
|
12
|
+
|
|
11
13
|
// Haiku 5.5 charges a request whose prompt (input + cache writes + cache
|
|
12
14
|
// reads) exceeds this many tokens at the higher 'claude-haiku-5-5-long' rates.
|
|
13
15
|
// Each request is priced on its own, so callers accumulate such requests into
|
|
@@ -366,12 +368,8 @@ function priceTotals(totals, p) {
|
|
|
366
368
|
return { actual, noCacheCost, scenario5mCost, write1h };
|
|
367
369
|
}
|
|
368
370
|
|
|
369
|
-
/**
|
|
370
|
-
|
|
371
|
-
* rates (LiteLLM /model/info). A token class the gateway does not price makes
|
|
372
|
-
* the whole estimate unknown (null) rather than free or list-priced.
|
|
373
|
-
*/
|
|
374
|
-
function estimateCostAtPrice(totals, price) {
|
|
371
|
+
/** Unrounded figures for one set of totals at one gateway price; null when a needed rate is missing. */
|
|
372
|
+
function priceTotalsAtGateway(totals, price) {
|
|
375
373
|
const write5m = totals.ephemeral5m ?? 0;
|
|
376
374
|
const write1h = totals.ephemeral1h ?? 0;
|
|
377
375
|
const untracked = Math.max(0, (totals.cacheCreation ?? 0) - write5m - write1h);
|
|
@@ -404,6 +402,32 @@ function estimateCostAtPrice(totals, price) {
|
|
|
404
402
|
tokensToMillions(Math.max(0, read - extra5mCreation)) * cacheRead +
|
|
405
403
|
tokensToMillions(totals.output) * output;
|
|
406
404
|
}
|
|
405
|
+
return { actual, noCacheCost, scenario5mCost, applicable: price.cacheWrite != null && write1h > 0 };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Same shape as the list-price estimate, but priced at a gateway's per-token
|
|
410
|
+
* rates (LiteLLM /model/info). A token class the gateway does not price makes
|
|
411
|
+
* the whole estimate unknown (null) rather than free or list-priced.
|
|
412
|
+
*
|
|
413
|
+
* The parser splits requests whose prompt exceeds LONG_PROMPT_THRESHOLD into
|
|
414
|
+
* `totals.long`, so only a gateway tier at exactly that threshold can be
|
|
415
|
+
* applied here. A tier at any other threshold (e.g. 272K) cannot be told apart
|
|
416
|
+
* in aggregated Claude totals; those keep base rates.
|
|
417
|
+
*/
|
|
418
|
+
function estimateCostAtPrice(totals, price) {
|
|
419
|
+
const longTier = totals.long && price.tiers?.some((t) => t.threshold === LONG_PROMPT_THRESHOLD);
|
|
420
|
+
let parts;
|
|
421
|
+
if (longTier) {
|
|
422
|
+
parts = [priceTotalsAtGateway(subtractTotals(totals, totals.long), price),
|
|
423
|
+
priceTotalsAtGateway(totals.long, priceForPrompt(price, LONG_PROMPT_THRESHOLD + 1))];
|
|
424
|
+
} else {
|
|
425
|
+
parts = [priceTotalsAtGateway(totals, price)];
|
|
426
|
+
}
|
|
427
|
+
if (parts.some((part) => part === null)) return null;
|
|
428
|
+
const actual = parts.reduce((n, part) => n + part.actual, 0);
|
|
429
|
+
const noCacheCost = parts.reduce((n, part) => n + part.noCacheCost, 0);
|
|
430
|
+
const scenario5mCost = parts.reduce((n, part) => n + part.scenario5mCost, 0);
|
|
407
431
|
|
|
408
432
|
return {
|
|
409
433
|
tier: 'gateway',
|
|
@@ -413,7 +437,7 @@ function estimateCostAtPrice(totals, price) {
|
|
|
413
437
|
savingsRate: noCacheCost > 0 ? (noCacheCost - actual) / noCacheCost : 0,
|
|
414
438
|
scenario5mCost: round(scenario5mCost),
|
|
415
439
|
extraCostIf5m: round(scenario5mCost - actual),
|
|
416
|
-
extraCostIf5mApplicable:
|
|
440
|
+
extraCostIf5mApplicable: parts.some((part) => part.applicable),
|
|
417
441
|
};
|
|
418
442
|
}
|
|
419
443
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cowork-sessions: read the Claude Code transcripts the Claude desktop app's
|
|
3
|
+
* Cowork tab writes.
|
|
4
|
+
*
|
|
5
|
+
* Cowork runs Claude Code with a per-session CLAUDE_CONFIG_DIR, so its
|
|
6
|
+
* transcripts never land in ~/.claude/projects. They sit inside the session
|
|
7
|
+
* folder instead:
|
|
8
|
+
* <root>/<org>/<account>/<session>/.claude/projects/<project>/<uuid>.jsonl
|
|
9
|
+
* with subagents at `<project>/<uuid>/subagents/agent-*.jsonl`. The session
|
|
10
|
+
* folder also holds uploads, outputs and audit logs (gigabytes), so discovery
|
|
11
|
+
* walks exactly that depth and never recurses freely.
|
|
12
|
+
*
|
|
13
|
+
* This is a separate module, used only by the team upload (daily spend). The
|
|
14
|
+
* statusline, route-scan and the ledger do not read Cowork, matching the
|
|
15
|
+
* 2026-10-13 decision to keep delegation out of Cowork. Its parse cache is a
|
|
16
|
+
* separate file so thousands of transcripts never bloat session-cache.json.
|
|
17
|
+
*
|
|
18
|
+
* The macOS path is verified; the Windows and 1p (".../Claude") paths are
|
|
19
|
+
* assumed, as in cowork-sync.js. Leaf module: it imports only node: builtins and
|
|
20
|
+
* ./paths.js. The parser loads on demand inside the functions that need it, so
|
|
21
|
+
* cowork-sync.js (SessionStart hook) can import coworkSessionRoots without pulling
|
|
22
|
+
* in the parser graph, and without a cycle.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { existsSync } from 'node:fs';
|
|
26
|
+
import { readdir } from 'node:fs/promises';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
import { homedir } from 'node:os';
|
|
29
|
+
import { userDataDir } from './paths.js';
|
|
30
|
+
|
|
31
|
+
// Sessions scanned at once; each scan is a few readdirs and stats.
|
|
32
|
+
const DISCOVER_BATCH = 16;
|
|
33
|
+
|
|
34
|
+
export function coworkSessionRoots() {
|
|
35
|
+
const bases = [];
|
|
36
|
+
if (process.platform === 'darwin') {
|
|
37
|
+
const support = join(homedir(), 'Library', 'Application Support');
|
|
38
|
+
bases.push(join(support, 'Claude'), join(support, 'Claude-3p'));
|
|
39
|
+
} else if (process.platform === 'win32' && process.env.APPDATA) {
|
|
40
|
+
bases.push(join(process.env.APPDATA, 'Claude'), join(process.env.APPDATA, 'Claude-3p'));
|
|
41
|
+
}
|
|
42
|
+
return bases.map((b) => join(b, 'local-agent-mode-sessions')).filter((p) => existsSync(p));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Names of the subdirectories of `dir`; unreadable means none. */
|
|
46
|
+
async function subdirNames(dir) {
|
|
47
|
+
try {
|
|
48
|
+
return (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
49
|
+
} catch {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Transcripts modified within `days`, in the shape discoverSessionFiles returns.
|
|
56
|
+
* Only <root>/<org>/<account>/<session> is walked here; each session's own projects
|
|
57
|
+
* directory goes through discoverSessionFiles, so Cowork follows every discovery rule
|
|
58
|
+
* of Claude Code. Best-effort: an unreadable directory is skipped.
|
|
59
|
+
*/
|
|
60
|
+
export async function discoverCoworkSessionFiles({ days = 30, roots = coworkSessionRoots(), now = Date.now() } = {}) {
|
|
61
|
+
const { discoverSessionFiles, dedupeSessionFiles } = await import('./parser.js');
|
|
62
|
+
const projectsDirs = [];
|
|
63
|
+
for (const root of roots) {
|
|
64
|
+
for (const org of await subdirNames(root)) {
|
|
65
|
+
for (const account of await subdirNames(join(root, org))) {
|
|
66
|
+
for (const session of await subdirNames(join(root, org, account))) {
|
|
67
|
+
projectsDirs.push(join(root, org, account, session, '.claude', 'projects'));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const files = [];
|
|
73
|
+
for (let i = 0; i < projectsDirs.length; i += DISCOVER_BATCH) {
|
|
74
|
+
const batch = await Promise.all(projectsDirs.slice(i, i + DISCOVER_BATCH).map((root) => discoverSessionFiles({ root, days, now })));
|
|
75
|
+
for (const found of batch) files.push(...found);
|
|
76
|
+
}
|
|
77
|
+
// Transcript names are uuids, so this only collapses a copied session folder.
|
|
78
|
+
return dedupeSessionFiles(files).sort((a, b) => a.mtime - b.mtime);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Parsed Cowork sessions, marked `surface: 'cowork'`. */
|
|
82
|
+
export async function parseCoworkSessions({ days = 30, roots } = {}) {
|
|
83
|
+
const { parseAllSessions } = await import('./parser.js');
|
|
84
|
+
const sessions = await parseAllSessions({
|
|
85
|
+
days,
|
|
86
|
+
files: await discoverCoworkSessionFiles({ days, roots }),
|
|
87
|
+
cachePath: join(userDataDir(), 'cowork-session-cache.json'),
|
|
88
|
+
});
|
|
89
|
+
for (const s of sessions) s.surface = 'cowork';
|
|
90
|
+
return sessions;
|
|
91
|
+
}
|
package/src/cowork-sync.js
CHANGED
|
@@ -28,6 +28,7 @@ import { join, resolve, sep, isAbsolute } from 'node:path';
|
|
|
28
28
|
import { homedir } from 'node:os';
|
|
29
29
|
import { execFileSync } from 'node:child_process';
|
|
30
30
|
import { userDataDir, claudeUserDir } from './paths.js';
|
|
31
|
+
import { coworkSessionRoots } from './cowork-sessions.js';
|
|
31
32
|
import { loadConfig, saveConfig, userLanguage } from './config.js';
|
|
32
33
|
import { writeStateFile } from './state-file.js';
|
|
33
34
|
import { readSettings, writeSettings } from './installer.js';
|
|
@@ -83,16 +84,7 @@ export function saveCoworkState(state) {
|
|
|
83
84
|
|
|
84
85
|
// ---------- discovery ----------
|
|
85
86
|
|
|
86
|
-
export
|
|
87
|
-
const bases = [];
|
|
88
|
-
if (process.platform === 'darwin') {
|
|
89
|
-
const support = join(homedir(), 'Library', 'Application Support');
|
|
90
|
-
bases.push(join(support, 'Claude'), join(support, 'Claude-3p'));
|
|
91
|
-
} else if (process.platform === 'win32' && process.env.APPDATA) {
|
|
92
|
-
bases.push(join(process.env.APPDATA, 'Claude'), join(process.env.APPDATA, 'Claude-3p'));
|
|
93
|
-
}
|
|
94
|
-
return bases.map((b) => join(b, 'local-agent-mode-sessions')).filter((p) => existsSync(p));
|
|
95
|
-
}
|
|
87
|
+
export { coworkSessionRoots };
|
|
96
88
|
|
|
97
89
|
function subdirs(dir) {
|
|
98
90
|
try {
|
package/src/delegation-agents.js
CHANGED
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync, readdirSync } from 'node:fs';
|
|
16
16
|
import { join } from 'node:path';
|
|
17
17
|
import { claudeUserDir } from './paths.js';
|
|
18
|
-
import { loadConfig } from './config.js';
|
|
19
|
-
import { agentDefinitions } from './presets-source.js';
|
|
18
|
+
import { loadConfig, saveConfig } from './config.js';
|
|
19
|
+
import { agentDefinitions, cliVersion, presetSource } from './presets-source.js';
|
|
20
20
|
|
|
21
21
|
export const OWNER_MARK = 'sprag:delegation-agent';
|
|
22
22
|
const MARK_LINE = `# managed by sprag (${OWNER_MARK}); edits are overwritten`;
|
|
@@ -26,9 +26,11 @@ const MARK_LINE = `# managed by sprag (${OWNER_MARK}); edits are overwritten`;
|
|
|
26
26
|
// { name, model, effort, tools: [..], description: { ko, en }, body: { ko, en } }
|
|
27
27
|
//
|
|
28
28
|
// Models are aliases on purpose: behind a gateway they resolve through
|
|
29
|
-
// ANTHROPIC_DEFAULT_*_MODEL, and a full model id would bypass that mapping.
|
|
30
|
-
//
|
|
31
|
-
// alias to
|
|
29
|
+
// ANTHROPIC_DEFAULT_*_MODEL, and a full model id would bypass that mapping.
|
|
30
|
+
// t1h-worker used to pin claude-opus-5-5 because older Claude Code releases
|
|
31
|
+
// resolved the haiku alias to Haiku 4.5; 2.1.302 resolves opus, sonnet and
|
|
32
|
+
// haiku to the current 5.5 models on the first-party API, so all five agents
|
|
33
|
+
// use aliases (preset v4).
|
|
32
34
|
//
|
|
33
35
|
// Effort is a separate axis from the tier and is set by how the work gets
|
|
34
36
|
// verified, not by how hard it is. Where the check is command output or a file
|
|
@@ -141,7 +143,75 @@ export function delegationAgentStatus() {
|
|
|
141
143
|
const agents = definitions().map((def) => {
|
|
142
144
|
const f = existsSync(fileOf(def.name)) ? readOwned(fileOf(def.name)) : null;
|
|
143
145
|
const state = !f ? 'absent' : isOwned(f.text) ? 'installed-by-sprag' : 'user-file';
|
|
144
|
-
return { name: def.name, state };
|
|
146
|
+
return { name: def.name, state, drift: f && state === 'user-file' ? driftOf(def, f.text) : null };
|
|
145
147
|
});
|
|
146
148
|
return { enabled, agents };
|
|
147
149
|
}
|
|
150
|
+
|
|
151
|
+
/** `model` and `effort` from the leading frontmatter block; null when absent. */
|
|
152
|
+
function readFrontmatterSpec(text) {
|
|
153
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
|
|
154
|
+
const field = (key) => {
|
|
155
|
+
const hit = m && new RegExp(`^${key}:[ \\t]*(.*?)[ \\t]*$`, 'm').exec(m[1]);
|
|
156
|
+
return hit && hit[1] ? hit[1] : null;
|
|
157
|
+
};
|
|
158
|
+
return { model: field('model'), effort: field('effort') };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** fable, opus, sonnet or haiku, so an alias and a pinned id of one family compare equal. */
|
|
162
|
+
export function modelFamily(model) {
|
|
163
|
+
const hit = /fable|opus|sonnet|haiku/.exec(String(model || '').toLowerCase());
|
|
164
|
+
return hit ? hit[0] : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function driftOf(def, text) {
|
|
168
|
+
const file = readFrontmatterSpec(text);
|
|
169
|
+
const preset = { model: def.model || null, effort: def.effort || null };
|
|
170
|
+
const same = file.effort === preset.effort && modelFamily(file.model) === modelFamily(preset.model);
|
|
171
|
+
return same ? null : { name: def.name, file, preset };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* User-owned agent files whose model family or effort differs from the preset.
|
|
176
|
+
* sync never touches them, so this is the only place the difference shows.
|
|
177
|
+
*/
|
|
178
|
+
export function agentDrift() {
|
|
179
|
+
const out = [];
|
|
180
|
+
for (const def of definitions()) {
|
|
181
|
+
const f = existsSync(fileOf(def.name)) ? readOwned(fileOf(def.name)) : null;
|
|
182
|
+
if (!f || isOwned(f.text)) continue;
|
|
183
|
+
const d = driftOf(def, f.text);
|
|
184
|
+
if (d) out.push(d);
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Session-start notice for agentDrift(), shown once per preset version: the
|
|
191
|
+
* key is remembered in config, and a newly published version changes it.
|
|
192
|
+
* Returns null when there is no drift or this key was already announced.
|
|
193
|
+
*/
|
|
194
|
+
export function takeAgentDriftNotice({ lang = 'ko' } = {}) {
|
|
195
|
+
const drift = agentDrift();
|
|
196
|
+
if (drift.length === 0) return null;
|
|
197
|
+
const src = presetSource();
|
|
198
|
+
// The bundled presets carry no version of their own; they change with the CLI.
|
|
199
|
+
const key = `${src.kind}:${src.kind === 'remote' ? src.version : cliVersion()}`;
|
|
200
|
+
const cfg = loadConfig();
|
|
201
|
+
if (cfg.agentDriftNoticedKey === key) return null;
|
|
202
|
+
saveConfig({ ...cfg, agentDriftNoticedKey: key });
|
|
203
|
+
const ko = lang === 'ko';
|
|
204
|
+
const label = src.kind === 'remote' ? `v${src.version}` : 'bundled';
|
|
205
|
+
const v = (x) => x || '-';
|
|
206
|
+
return [
|
|
207
|
+
ko
|
|
208
|
+
? `[sprag agents] 프리셋 ${label}이 지정한 값과 다른 직접 만든 에이전트 파일이 있어서, sync가 이 파일들을 덮어쓰지 않았습니다.`
|
|
209
|
+
: `[sprag agents] Some agent files you made yourself differ from what preset ${label} specifies, so sync did not overwrite them.`,
|
|
210
|
+
...drift.map((d) => ko
|
|
211
|
+
? `- ${d.name}: 파일 effort ${v(d.file.effort)} · 모델 ${v(d.file.model)}, 프리셋 effort ${v(d.preset.effort)} · 모델 ${v(d.preset.model)}`
|
|
212
|
+
: `- ${d.name}: file effort ${v(d.file.effort)} · model ${v(d.file.model)}, preset effort ${v(d.preset.effort)} · model ${v(d.preset.model)}`),
|
|
213
|
+
ko
|
|
214
|
+
? 'sprag가 관리하게 하려면 파일을 지운 뒤 `sprag delegate agents on` 을 실행합니다. 지금 값을 유지하려면 그대로 두면 되고, 이 안내는 프리셋 버전이 바뀔 때만 다시 나옵니다. 사용자에게 이 차이를 한 줄로 알리십시오.'
|
|
215
|
+
: 'To let sprag manage them, delete the files and run `sprag delegate agents on`. To keep the current values, leave them as they are; this notice returns only when the preset version changes. Tell the user about this difference in one line.',
|
|
216
|
+
].join('\n');
|
|
217
|
+
}
|
package/src/gateway-auth.js
CHANGED
|
@@ -114,6 +114,39 @@ export function keyFromApiKeyHelper(cwd = process.cwd()) {
|
|
|
114
114
|
return null;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
const SETTINGS_ENV_KEYS = ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY'];
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 프로세스 환경에 게이트웨이 주소가 없을 때, ~/.claude/settings.json 의 env 블록에서
|
|
121
|
+
* 주소와 토큰을 가져와 채운 사본을 돌려줍니다.
|
|
122
|
+
*
|
|
123
|
+
* 팀 동기화는 Claude Code 훅에서도 Codex 훅에서도 시작됩니다. Claude Code 는
|
|
124
|
+
* settings.json 의 env 를 자기 프로세스에 넣어 주지만 Codex 프로세스에는 그 값이
|
|
125
|
+
* 없습니다. 그래서 같은 하루 행이 어느 에이전트가 동기화했느냐에 따라 게이트웨이
|
|
126
|
+
* 단가와 목록 단가 사이를 오가고, 게이트웨이 금액도 생겼다 사라졌습니다.
|
|
127
|
+
*
|
|
128
|
+
* 환경에 주소가 이미 있으면 그대로 둡니다. 다른 게이트웨이의 토큰이 섞이면 안
|
|
129
|
+
* 되기 때문입니다. 프로젝트 설정은 신뢰 확인이 필요하므로 읽지 않고, 관리형 설정은
|
|
130
|
+
* 홈 디렉터리 밖에 있어 테스트에서 격리할 수 없으므로 읽지 않습니다.
|
|
131
|
+
*/
|
|
132
|
+
export function withClaudeSettingsEnv(env = process.env, { home = homedir() } = {}) {
|
|
133
|
+
if ((env.ANTHROPIC_BASE_URL || '').trim()) return env;
|
|
134
|
+
let fromSettings;
|
|
135
|
+
try {
|
|
136
|
+
fromSettings = JSON.parse(readFileSync(join(home, '.claude', 'settings.json'), 'utf8'))?.env;
|
|
137
|
+
} catch {
|
|
138
|
+
return env;
|
|
139
|
+
}
|
|
140
|
+
if (!fromSettings || typeof fromSettings !== 'object') return env;
|
|
141
|
+
const base = typeof fromSettings.ANTHROPIC_BASE_URL === 'string' ? fromSettings.ANTHROPIC_BASE_URL.trim() : '';
|
|
142
|
+
if (!base) return env;
|
|
143
|
+
const next = { ...env };
|
|
144
|
+
for (const k of SETTINGS_ENV_KEYS) {
|
|
145
|
+
if (!(next[k] || '').trim() && typeof fromSettings[k] === 'string' && fromSettings[k].trim()) next[k] = fromSettings[k].trim();
|
|
146
|
+
}
|
|
147
|
+
return next;
|
|
148
|
+
}
|
|
149
|
+
|
|
117
150
|
/** 환경변수 토큰을 먼저 보고, 없으면 apiKeyHelper 로 내려갑니다. */
|
|
118
151
|
export function resolveKey(env = process.env) {
|
|
119
152
|
const direct = (env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY || '').trim();
|
package/src/gateway-prices.js
CHANGED
|
@@ -9,8 +9,37 @@ export function deploymentPrice(row) {
|
|
|
9
9
|
if (mode && !['chat', 'responses', 'completion'].includes(mode)) return null;
|
|
10
10
|
const input = rate(info.input_cost_per_token), output = rate(info.output_cost_per_token);
|
|
11
11
|
if (input === null || output === null) return null;
|
|
12
|
-
|
|
12
|
+
const price = { input, output, cacheRead: rate(info.cache_read_input_token_cost), cacheWrite: rate(info.cache_creation_input_token_cost),
|
|
13
13
|
cacheWrite1h: rate(info.cache_creation_input_token_cost_above_1hr) };
|
|
14
|
+
// `_above_<N>k_tokens` keys reprice a whole request whose prompt exceeds N thousand tokens.
|
|
15
|
+
// The plain `cache_creation_input_token_cost_above_1hr` has no `k_tokens` suffix: it is the 1h write rate, not a tier.
|
|
16
|
+
const tiers = new Map();
|
|
17
|
+
for (const [key, value] of Object.entries(info)) {
|
|
18
|
+
const m = TIER_KEY.exec(key);
|
|
19
|
+
// /model/info lists every tier key with null for the models that have no tier.
|
|
20
|
+
if (!m || rate(value) === null) continue;
|
|
21
|
+
const threshold = Number(m[2]) * 1000;
|
|
22
|
+
const tier = tiers.get(threshold) || { threshold, input: null, output: null, cacheRead: null, cacheWrite: null, cacheWrite1h: null };
|
|
23
|
+
tier[TIER_FIELD[m[1]]] = rate(value);
|
|
24
|
+
tiers.set(threshold, tier);
|
|
25
|
+
}
|
|
26
|
+
// Only when present, so untiered models keep the exact old shape (prices are compared via JSON.stringify).
|
|
27
|
+
if (tiers.size) price.tiers = [...tiers.values()].sort((a, b) => a.threshold - b.threshold);
|
|
28
|
+
return price;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const TIER_KEY = /^(input_cost_per_token|output_cost_per_token|cache_read_input_token_cost|cache_creation_input_token_cost|cache_creation_input_token_cost_above_1hr)_above_(\d+)k_tokens$/;
|
|
32
|
+
const TIER_FIELD = { input_cost_per_token: 'input', output_cost_per_token: 'output', cache_read_input_token_cost: 'cacheRead',
|
|
33
|
+
cache_creation_input_token_cost: 'cacheWrite', cache_creation_input_token_cost_above_1hr: 'cacheWrite1h' };
|
|
34
|
+
|
|
35
|
+
/** `price` with the highest tier whose threshold the prompt exceeds (strictly, as LiteLLM does) laid over it. */
|
|
36
|
+
export function priceForPrompt(price, promptTokens) {
|
|
37
|
+
if (!price?.tiers) return price;
|
|
38
|
+
const tier = price.tiers.filter((t) => t.threshold < promptTokens).pop();
|
|
39
|
+
if (!tier) return price;
|
|
40
|
+
const merged = { ...price };
|
|
41
|
+
for (const field of Object.values(TIER_FIELD)) if (tier[field] != null) merged[field] = tier[field];
|
|
42
|
+
return merged;
|
|
14
43
|
}
|
|
15
44
|
|
|
16
45
|
/** Per-token prices by alias. Load-balanced deployments must agree, like cache policy. */
|
|
@@ -22,7 +51,20 @@ export function gatewayPrices(payload) {
|
|
|
22
51
|
groups.set(row.model_name, [...(groups.get(row.model_name) || []), deploymentPrice(row)]);
|
|
23
52
|
}
|
|
24
53
|
return Object.fromEntries([...groups].map(([name, prices]) => [name,
|
|
25
|
-
prices
|
|
54
|
+
prices.reduce((merged, price) => mergePrices(merged, price))]));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The price two deployments of one key agree on. Differing base rates, or a deployment without a
|
|
59
|
+
* price, leave the key unpriced (null). Equal base rates with different tiers fall back to the
|
|
60
|
+
* base rates alone: the tier-less price the key had before tiers existed, never a guessed tier.
|
|
61
|
+
*/
|
|
62
|
+
export function mergePrices(a, b) {
|
|
63
|
+
if (!a || !b) return null;
|
|
64
|
+
const { tiers: tiersA, ...baseA } = a;
|
|
65
|
+
const { tiers: tiersB, ...baseB } = b;
|
|
66
|
+
if (JSON.stringify(baseA) !== JSON.stringify(baseB)) return null;
|
|
67
|
+
return JSON.stringify(tiersA) === JSON.stringify(tiersB) ? a : baseA;
|
|
26
68
|
}
|
|
27
69
|
|
|
28
70
|
/**
|
|
@@ -37,3 +79,13 @@ export function codexRunCost({ input = 0, cached = 0, cacheWrite = 0, output = 0
|
|
|
37
79
|
return uncached * price.input + cached * (price.cacheRead ?? 0) + cacheWrite * (price.cacheWrite ?? price.input) + output * price.output;
|
|
38
80
|
}
|
|
39
81
|
|
|
82
|
+
/**
|
|
83
|
+
* USD for ONE request. The tier depends on this request's own prompt size: `usage.prompt` when
|
|
84
|
+
* the caller has it, else `usage.input`. The amounts always come from input/cached/cacheWrite/output,
|
|
85
|
+
* and `prompt` can be smaller than `input` when a row merges several responses. Totals summed over
|
|
86
|
+
* many requests must keep using codexRunCost at base rates.
|
|
87
|
+
*/
|
|
88
|
+
export function codexRequestCost(usage, price) {
|
|
89
|
+
return codexRunCost(usage, priceForPrompt(price, usage.prompt ?? usage.input));
|
|
90
|
+
}
|
|
91
|
+
|
package/src/litellm-models.js
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
import { gatewayBase } from './gateway-auth.js';
|
|
28
28
|
import { loadProfileMap, updateProfileMap, resetModelAliasCache, profileIdFrom, isGatewayModelId } from './model-alias.js';
|
|
29
29
|
import { isRecognizedModelId } from './cost.js';
|
|
30
|
-
import { deploymentPrice, PRICE_MAX_AGE_MS } from './gateway-prices.js';
|
|
30
|
+
import { deploymentPrice, mergePrices, PRICE_MAX_AGE_MS } from './gateway-prices.js';
|
|
31
31
|
import { debug } from './debug.js';
|
|
32
32
|
|
|
33
33
|
/** 게이트웨이 모델 맵의 신선도 기준. 배포 구성은 하루에 여러 번 바뀌지 않습니다. */
|
|
@@ -171,8 +171,7 @@ export function deriveGatewayPrices(payload) {
|
|
|
171
171
|
]);
|
|
172
172
|
for (const key of keys) {
|
|
173
173
|
if (!key) continue;
|
|
174
|
-
|
|
175
|
-
else if (JSON.stringify(prices.get(key)) !== JSON.stringify(price)) prices.set(key, null);
|
|
174
|
+
prices.set(key, prices.has(key) ? mergePrices(prices.get(key), price) : price);
|
|
176
175
|
}
|
|
177
176
|
}
|
|
178
177
|
return Object.fromEntries(prices);
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The organization minimum version: the one case where a hook starts an
|
|
3
|
+
* install without asking.
|
|
4
|
+
*
|
|
5
|
+
* The sprag operator sets a minimum version per organization in the ops
|
|
6
|
+
* console. The rules pull stores it in team.json as `minVersion`. A session
|
|
7
|
+
* start on a machine below it starts `sprag upgrade --org-policy` detached and
|
|
8
|
+
* tells the model that it did, so the member hears about it without being
|
|
9
|
+
* asked and without the model installing anything itself. Everyone else keeps
|
|
10
|
+
* the consent-only offer in update-notice.js.
|
|
11
|
+
*
|
|
12
|
+
* org-upgrade.json (in the user data dir) is the record both sides share:
|
|
13
|
+
* `{ target, from, startedAt, pid, finishedAt, ok, error, announced }`. The
|
|
14
|
+
* statusline and the hooks import this module, so it stays on node builtins
|
|
15
|
+
* and small leaf modules; the runner that installs lives in
|
|
16
|
+
* src/commands/upgrade.js.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
20
|
+
import { dirname, join } from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
import { userDataDir } from './paths.js';
|
|
23
|
+
import { writeStateFile } from './state-file.js';
|
|
24
|
+
import { isNewer } from './update-check.js';
|
|
25
|
+
import { isDetachedChild, spawnDetachedCli } from './cli-entry.js';
|
|
26
|
+
import { readTeamState, isJoined } from './team-ratchet.js';
|
|
27
|
+
import { debug } from './debug.js';
|
|
28
|
+
|
|
29
|
+
/** A running attempt older than this is treated as dead, whatever its pid says. */
|
|
30
|
+
export const ORG_UPGRADE_INFLIGHT_MS = 30 * 60 * 1000;
|
|
31
|
+
/** After an attempt ends, this long before the next session starts another. */
|
|
32
|
+
export const ORG_UPGRADE_RETRY_MS = 60 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
const MIN_VERSION_RE = /^\d+\.\d+\.\d+$/;
|
|
35
|
+
|
|
36
|
+
/** 'X.Y.Z' when the server sent a usable minimum, else null. */
|
|
37
|
+
export function parseMinVersion(v) {
|
|
38
|
+
return typeof v === 'string' && MIN_VERSION_RE.test(v.trim()) ? v.trim() : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const orgUpgradePath = (dir = userDataDir()) => join(dir, 'org-upgrade.json');
|
|
42
|
+
export const orgUpgradeLogPath = (dir = userDataDir()) => join(dir, 'org-upgrade.log');
|
|
43
|
+
|
|
44
|
+
export function readOrgUpgrade(dir = userDataDir()) {
|
|
45
|
+
try {
|
|
46
|
+
const s = JSON.parse(readFileSync(orgUpgradePath(dir), 'utf8'));
|
|
47
|
+
return s && typeof s === 'object' && !Array.isArray(s) ? s : {};
|
|
48
|
+
} catch {
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Merge `patch` into the record and return the result. */
|
|
54
|
+
export function writeOrgUpgrade(patch, dir = userDataDir()) {
|
|
55
|
+
const next = { ...readOrgUpgrade(dir), ...patch };
|
|
56
|
+
writeStateFile(orgUpgradePath(dir), JSON.stringify(next, null, 2) + '\n');
|
|
57
|
+
return next;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The organization's minimum for a joined member, or null. */
|
|
61
|
+
export function orgMinVersion(state) {
|
|
62
|
+
return isJoined(state) ? parseMinVersion(state.minVersion) : null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The version the machine must reach, or null when it already meets the minimum or none is set. */
|
|
66
|
+
export function orgUpgradeTarget(version, state) {
|
|
67
|
+
const min = orgMinVersion(state);
|
|
68
|
+
return min && isNewer(min, version) ? min : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function pidAlive(pid) {
|
|
72
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
73
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e && e.code === 'EPERM'; }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Whether an attempt is running now: unfinished, recent, and its process (once known) alive. */
|
|
77
|
+
export function orgUpgradeInFlight(rec, { now = Date.now(), isAlive = pidAlive } = {}) {
|
|
78
|
+
if (!rec || rec.finishedAt || !Number.isFinite(rec.startedAt)) return false;
|
|
79
|
+
if (now - rec.startedAt >= ORG_UPGRADE_INFLIGHT_MS) return false;
|
|
80
|
+
return rec.pid == null || isAlive(rec.pid);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A copy running from a git checkout is a developer's; it must never replace itself. */
|
|
84
|
+
export function isDevCheckout(root = dirname(dirname(fileURLToPath(import.meta.url)))) {
|
|
85
|
+
return existsSync(join(root, '.git'));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Start the background upgrade when the policy calls for one. Returns
|
|
90
|
+
* `{ status, target }` with status one of: none (nothing required), child
|
|
91
|
+
* (this process is itself detached), dev, in-flight, cooldown, started,
|
|
92
|
+
* spawn-failed.
|
|
93
|
+
*/
|
|
94
|
+
export function maybeStartOrgUpgrade(version, {
|
|
95
|
+
agent = 'claude', env = process.env, now = Date.now(), dir = userDataDir(), spawn, root, state, isAlive,
|
|
96
|
+
} = {}) {
|
|
97
|
+
const target = orgUpgradeTarget(version, state || readTeamState(dir));
|
|
98
|
+
if (!target) return { status: 'none', target: null };
|
|
99
|
+
if (isDetachedChild(env)) return { status: 'child', target };
|
|
100
|
+
if (isDevCheckout(root)) return { status: 'dev', target };
|
|
101
|
+
const rec = readOrgUpgrade(dir);
|
|
102
|
+
if (orgUpgradeInFlight(rec, { now, isAlive })) return { status: 'in-flight', target };
|
|
103
|
+
// Any attempt that ended inside the last hour also holds off the next: a
|
|
104
|
+
// failure for the reason below, and a success that left this copy below the
|
|
105
|
+
// minimum because the install went to a different copy than the one running.
|
|
106
|
+
if (Number.isFinite(rec.finishedAt) && now - rec.finishedAt < ORG_UPGRADE_RETRY_MS) return { status: 'cooldown', target };
|
|
107
|
+
writeOrgUpgrade({
|
|
108
|
+
target, from: version, startedAt: now, pid: null, finishedAt: null, ok: null, error: null, announced: false,
|
|
109
|
+
}, dir);
|
|
110
|
+
let started = false;
|
|
111
|
+
try {
|
|
112
|
+
started = spawnDetachedCli(['upgrade', '--org-policy', '--agent', agent], { env, ...(spawn ? { spawn } : {}) });
|
|
113
|
+
} catch (e) {
|
|
114
|
+
debug('org-upgrade:spawn', e);
|
|
115
|
+
writeOrgUpgrade({ finishedAt: now, ok: false, error: `could not start: ${e && e.message ? e.message : e}`, announced: false }, dir);
|
|
116
|
+
return { status: 'spawn-failed', target };
|
|
117
|
+
}
|
|
118
|
+
if (!started) {
|
|
119
|
+
writeOrgUpgrade({ finishedAt: now, ok: false, error: 'could not start the background upgrade', announced: false }, dir);
|
|
120
|
+
return { status: 'spawn-failed', target };
|
|
121
|
+
}
|
|
122
|
+
return { status: 'started', target };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* One short block for the session context, or null. Informational only: it
|
|
127
|
+
* never tells the model to install anything. A success or failure is reported
|
|
128
|
+
* once (`announced`), at the first session that can see it.
|
|
129
|
+
*/
|
|
130
|
+
export function orgUpgradeNotice(version, { lang = 'en', status, dir = userDataDir() } = {}) {
|
|
131
|
+
const ko = lang === 'ko';
|
|
132
|
+
try {
|
|
133
|
+
if (status && status.status === 'started') {
|
|
134
|
+
return ko
|
|
135
|
+
? `[sprag 조직 정책] 조직 정책에 따라 최소 버전 v${status.target} 가 필요해 백그라운드에서 업그레이드를 시작했습니다. 다음 세션부터 새 버전이 적용됩니다.`
|
|
136
|
+
: `[sprag org policy] The organization requires at least v${status.target}, so an upgrade was started in the background. The new version applies from the next session.`;
|
|
137
|
+
}
|
|
138
|
+
const rec = readOrgUpgrade(dir);
|
|
139
|
+
if (rec.announced || !rec.target || !Number.isFinite(rec.finishedAt)) return null;
|
|
140
|
+
if (rec.ok === true && !isNewer(rec.target, version)) {
|
|
141
|
+
writeOrgUpgrade({ announced: true }, dir);
|
|
142
|
+
return ko
|
|
143
|
+
? `[sprag 조직 정책] 조직 최소 버전 v${rec.target} 로의 업그레이드가 끝났습니다. 현재 v${version} 가 실행 중입니다.`
|
|
144
|
+
: `[sprag org policy] The upgrade to the organization minimum v${rec.target} finished. Running v${version}.`;
|
|
145
|
+
}
|
|
146
|
+
if (rec.ok === false && isNewer(rec.target, version)) {
|
|
147
|
+
writeOrgUpgrade({ announced: true }, dir);
|
|
148
|
+
const reason = String(rec.error || 'unknown').slice(0, 200);
|
|
149
|
+
return ko
|
|
150
|
+
? `[sprag 조직 정책] 조직 최소 버전 v${rec.target} 로의 자동 업그레이드가 실패했습니다: ${reason}. 사용자에게 알리고 sprag upgrade 를 직접 실행하도록 안내하십시오.`
|
|
151
|
+
: `[sprag org policy] The automatic upgrade to the organization minimum v${rec.target} failed: ${reason}. Tell the user to run sprag upgrade themselves.`;
|
|
152
|
+
}
|
|
153
|
+
} catch (e) {
|
|
154
|
+
debug('org-upgrade:notice', e);
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* What the session-start offer asks first. `{ text }` means the org policy
|
|
161
|
+
* owns this session's answer (text may be null: say nothing and skip the
|
|
162
|
+
* consent offer); null means it has nothing to say and today's offer applies.
|
|
163
|
+
*/
|
|
164
|
+
export function orgPolicyOffer(version, { agent = 'claude', lang = 'en', dir = userDataDir(), ...opts } = {}) {
|
|
165
|
+
try {
|
|
166
|
+
const state = readTeamState(dir);
|
|
167
|
+
const status = maybeStartOrgUpgrade(version, { agent, dir, state, ...opts });
|
|
168
|
+
if (status.status === 'none') {
|
|
169
|
+
const text = orgUpgradeNotice(version, { lang, dir });
|
|
170
|
+
return text ? { text } : null;
|
|
171
|
+
}
|
|
172
|
+
// A dev checkout and a detached child keep today's behaviour.
|
|
173
|
+
if (status.status === 'child' || status.status === 'dev') return null;
|
|
174
|
+
return { text: orgUpgradeNotice(version, { lang, status, dir }) };
|
|
175
|
+
} catch (e) {
|
|
176
|
+
debug('org-upgrade:offer', e);
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
}
|