agy-family 0.2.6 → 0.2.7
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/packages/cli/bin/agy-family.mjs +30 -1
- package/packages/cli/src/hook.mjs +1 -1
- package/packages/core/src/index.mjs +1 -0
- package/packages/core/src/pricing-node.mjs +140 -0
- package/packages/core/src/pricing.mjs +357 -14
- package/packages/core/src/sync.mjs +2 -2
- package/packages/server-core/src/index.mjs +31 -10
- package/packages/server-core/src/schema.mjs +2 -0
- package/packages/server-core/src/stats.mjs +122 -17
- package/packages/server-core/src/ui.mjs +53 -4
- package/packages/server-node/src/server.mjs +11 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-family",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.7",
|
|
4
4
|
"description": "Zero-privacy-leak transparent usage dashboard, /family slash command, and fair-use budget guardrail for Google One / Antigravity family groups.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,8 @@ import {
|
|
|
21
21
|
getOrCreateSharedDeviceId,
|
|
22
22
|
hashEmailSha256,
|
|
23
23
|
pushSyncPayload,
|
|
24
|
+
readLocalPricingSources,
|
|
25
|
+
syncLocalPricingCache,
|
|
24
26
|
writeActiveAccountCache,
|
|
25
27
|
} from '../../core/src/index.mjs';
|
|
26
28
|
import { startNodeServer } from '../../server-node/src/server.mjs';
|
|
@@ -35,7 +37,7 @@ import {
|
|
|
35
37
|
uninstallBackgroundDaemon,
|
|
36
38
|
} from '../src/hook.mjs';
|
|
37
39
|
|
|
38
|
-
const CLI_VERSION = '0.2.
|
|
40
|
+
const CLI_VERSION = '0.2.7';
|
|
39
41
|
const THIS_CLI_PATH = fileURLToPath(import.meta.url);
|
|
40
42
|
|
|
41
43
|
function configBaseDir(home = homedir()) {
|
|
@@ -105,6 +107,7 @@ Usage:
|
|
|
105
107
|
agy-family status [--period today|7d|cycle|30d]
|
|
106
108
|
View your cap progress and family leaderboard
|
|
107
109
|
agy-family audit Inspect the exact last transmitted JSON payload
|
|
110
|
+
agy-family pricing [sync] View or sync 3-tier model pricing cache (models.dev / litellm)
|
|
108
111
|
agy-family hook [on|off|status] Manage Antigravity IDE + CLI /family command & Stop auto-sync hook
|
|
109
112
|
agy-family daemon [install|uninstall|status] Manage background 5-minute OS heartbeat (macOS launchd / Linux cron)
|
|
110
113
|
agy-family leave Disconnect this device and delete local invite token
|
|
@@ -160,6 +163,7 @@ async function runSyncOnce({ cfg, dryRun = false, fullSync = false, quiet = fals
|
|
|
160
163
|
const res = await pushSyncPayload({ url: cfg.url, token: cfg.token, payload });
|
|
161
164
|
writePrivateJson(syncedHashesPath(home), nextSyncedHashes);
|
|
162
165
|
writePrivateJson(lastResultPath(home), res);
|
|
166
|
+
syncLocalPricingCache({ home, force: false }).catch(() => {});
|
|
163
167
|
|
|
164
168
|
if (res?.member) {
|
|
165
169
|
const serverExpected = res.member.expectedEmailHash || '';
|
|
@@ -393,6 +397,31 @@ async function main() {
|
|
|
393
397
|
return;
|
|
394
398
|
}
|
|
395
399
|
|
|
400
|
+
if (cmd === 'pricing') {
|
|
401
|
+
const action = (args[1] || 'status').toLowerCase();
|
|
402
|
+
const srcIdx = args.indexOf('--source');
|
|
403
|
+
const source = srcIdx >= 0 ? args[srcIdx + 1] || 'auto' : 'auto';
|
|
404
|
+
if (action === 'sync') {
|
|
405
|
+
const res = await syncLocalPricingCache({ source, force: true });
|
|
406
|
+
if (!res.ok) {
|
|
407
|
+
console.error(`Pricing sync failed (${res.error || 'unknown error'}); falling back to ${res.source}.`);
|
|
408
|
+
process.exit(1);
|
|
409
|
+
}
|
|
410
|
+
console.log(`✓ Synced ${res.count} model rates from ${res.source} -> ${res.cachePath}`);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const { customPricing, pricingCache } = readLocalPricingSources();
|
|
414
|
+
const customCount = customPricing ? Object.keys(customPricing).length : 0;
|
|
415
|
+
const cacheCount = pricingCache?.rates ? Object.keys(pricingCache.rates).length : 0;
|
|
416
|
+
console.log('3-Tier Pricing Engine Status:');
|
|
417
|
+
console.log(` Tier 1 (Custom overrides) : ${customCount > 0 ? `${customCount} model(s)` : 'none'}`);
|
|
418
|
+
console.log(
|
|
419
|
+
` Tier 2 (Live cache) : ${cacheCount > 0 ? `${cacheCount} models (${pricingCache.source || 'models.dev'}, updated ${new Date(pricingCache.fetchedAt || 0).toISOString()})` : 'not synced yet (run "agy-family pricing sync")'}`,
|
|
420
|
+
);
|
|
421
|
+
console.log(' Tier 3 (Built-in table) : active (calibrated from models.dev)');
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
|
|
396
425
|
if (cmd === 'status') {
|
|
397
426
|
const cfg = getOrCreateClientConfig();
|
|
398
427
|
if (!cfg.url) {
|
|
@@ -716,7 +716,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
|
|
|
716
716
|
const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
|
|
717
717
|
deviceId,
|
|
718
718
|
clientKind: 'cli',
|
|
719
|
-
clientVersion: '0.2.
|
|
719
|
+
clientVersion: '0.2.7',
|
|
720
720
|
home,
|
|
721
721
|
fileCache: cache,
|
|
722
722
|
syncedHashes: prevHashes,
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Local Node.js disk adapter for the 3-Tier Dynamic Pricing Engine.
|
|
2
|
+
// Automatically shares `~/.gemini/config/agy-bar/pricing-cache.json` and `config.json` (`customPricing`)
|
|
3
|
+
// when `agy-bar` is installed, or maintains `~/.config/agy-family/pricing-cache.json` (24h TTL from models.dev / litellm).
|
|
4
|
+
|
|
5
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import {
|
|
9
|
+
fetchRemotePricingCache,
|
|
10
|
+
PRICING_RETRY_COOLDOWN_MS,
|
|
11
|
+
PRICING_TTL_MS,
|
|
12
|
+
registerDefaultLocalPricingProvider,
|
|
13
|
+
} from './pricing.mjs';
|
|
14
|
+
|
|
15
|
+
const memo = {
|
|
16
|
+
checkedAt: 0,
|
|
17
|
+
customPricing: null,
|
|
18
|
+
pricingCache: null,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function readJsonIfFreshMtime(filePath, slot) {
|
|
22
|
+
try {
|
|
23
|
+
if (!existsSync(filePath)) return null;
|
|
24
|
+
const st = statSync(filePath);
|
|
25
|
+
if (slot.path === filePath && slot.mtimeMs === st.mtimeMs) return slot.data;
|
|
26
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8').replace(/^\uFEFF/, ''));
|
|
27
|
+
slot.path = filePath;
|
|
28
|
+
slot.mtimeMs = st.mtimeMs;
|
|
29
|
+
slot.data = parsed;
|
|
30
|
+
return parsed;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const slotFamCache = { path: '', mtimeMs: -1, data: null };
|
|
37
|
+
const slotBarCache = { path: '', mtimeMs: -1, data: null };
|
|
38
|
+
const slotFamCfg = { path: '', mtimeMs: -1, data: null };
|
|
39
|
+
const slotBarCfg = { path: '', mtimeMs: -1, data: null };
|
|
40
|
+
|
|
41
|
+
export function agyFamilyPricingCachePath(home = homedir()) {
|
|
42
|
+
return join(home, '.config', 'agy-family', 'pricing-cache.json');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function agyBarPricingCachePath(home = homedir()) {
|
|
46
|
+
return join(home, '.gemini', 'config', 'agy-bar', 'pricing-cache.json');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function readLocalPricingSources({ home = homedir() } = {}) {
|
|
50
|
+
const famCfg = readJsonIfFreshMtime(join(home, '.config', 'agy-family', 'config.json'), slotFamCfg);
|
|
51
|
+
const barCfg = readJsonIfFreshMtime(join(home, '.gemini', 'config', 'agy-bar', 'config.json'), slotBarCfg);
|
|
52
|
+
|
|
53
|
+
const customPricing =
|
|
54
|
+
(famCfg?.customPricing && typeof famCfg.customPricing === 'object' ? famCfg.customPricing : null) ||
|
|
55
|
+
(barCfg?.customPricing && typeof barCfg.customPricing === 'object' ? barCfg.customPricing : null) ||
|
|
56
|
+
null;
|
|
57
|
+
|
|
58
|
+
const famCache = readJsonIfFreshMtime(agyFamilyPricingCachePath(home), slotFamCache);
|
|
59
|
+
const barCache = readJsonIfFreshMtime(agyBarPricingCachePath(home), slotBarCache);
|
|
60
|
+
|
|
61
|
+
const famValid = famCache && typeof famCache.rates === 'object' ? famCache : null;
|
|
62
|
+
const barValid = barCache && typeof barCache.rates === 'object' ? barCache : null;
|
|
63
|
+
|
|
64
|
+
let pricingCache = null;
|
|
65
|
+
if (famValid && barValid) {
|
|
66
|
+
pricingCache = Number(barValid.fetchedAt || 0) > Number(famValid.fetchedAt || 0) ? barValid : famValid;
|
|
67
|
+
} else {
|
|
68
|
+
pricingCache = famValid || barValid || null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return { customPricing, pricingCache };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function shouldSyncLocalPricing(cache, now = Date.now()) {
|
|
75
|
+
if (cache && typeof cache.fetchedAt === 'number' && now - cache.fetchedAt < PRICING_TTL_MS) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
if (cache && typeof cache.lastAttemptAt === 'number' && now - cache.lastAttemptAt < PRICING_RETRY_COOLDOWN_MS) {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function syncLocalPricingCache({
|
|
85
|
+
home = homedir(),
|
|
86
|
+
source = 'auto',
|
|
87
|
+
force = false,
|
|
88
|
+
now = Date.now(),
|
|
89
|
+
fetchFn = globalThis.fetch,
|
|
90
|
+
} = {}) {
|
|
91
|
+
const { pricingCache: existing } = readLocalPricingSources({ home });
|
|
92
|
+
if (!force && !shouldSyncLocalPricing(existing, now)) {
|
|
93
|
+
return {
|
|
94
|
+
ok: true,
|
|
95
|
+
updated: false,
|
|
96
|
+
skippedFresh: true,
|
|
97
|
+
source: existing?.source || 'cache',
|
|
98
|
+
count: Object.keys(existing?.rates || {}).length,
|
|
99
|
+
cachePath: agyFamilyPricingCachePath(home),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const res = await fetchRemotePricingCache({ existing, source, force, now, fetchFn });
|
|
104
|
+
const targetPath = agyFamilyPricingCachePath(home);
|
|
105
|
+
if (res.cache) {
|
|
106
|
+
try {
|
|
107
|
+
mkdirSync(dirname(targetPath), { recursive: true });
|
|
108
|
+
writeFileSync(targetPath, `${JSON.stringify(res.cache, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
109
|
+
try {
|
|
110
|
+
chmodSync(targetPath, 0o600);
|
|
111
|
+
} catch {}
|
|
112
|
+
slotFamCache.mtimeMs = -1;
|
|
113
|
+
memo.checkedAt = 0;
|
|
114
|
+
} catch {
|
|
115
|
+
// Non-fatal if filesystem is read-only.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
ok: res.ok,
|
|
121
|
+
updated: res.updated,
|
|
122
|
+
notModified: res.notModified,
|
|
123
|
+
error: res.error || null,
|
|
124
|
+
source: res.cache?.source || existing?.source || 'builtin',
|
|
125
|
+
count: Object.keys(res.cache?.rates || {}).length,
|
|
126
|
+
cachePath: targetPath,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Auto-register local disk provider when imported in Node/CLI/Extension environments
|
|
131
|
+
registerDefaultLocalPricingProvider(() => {
|
|
132
|
+
const now = Date.now();
|
|
133
|
+
if (now - memo.checkedAt > 5_000) {
|
|
134
|
+
const loaded = readLocalPricingSources();
|
|
135
|
+
memo.customPricing = loaded.customPricing;
|
|
136
|
+
memo.pricingCache = loaded.pricingCache;
|
|
137
|
+
memo.checkedAt = now;
|
|
138
|
+
}
|
|
139
|
+
return memo;
|
|
140
|
+
});
|
|
@@ -1,7 +1,63 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// 3-Tier Dynamic Model Pricing Engine (unified with agy-bar):
|
|
2
|
+
// Tier 1: User / Admin custom overrides (`customPricing` map)
|
|
3
|
+
// Tier 2: Auto-synced live pricing cache (`models.dev` -> fallback `litellm`, 24h TTL)
|
|
4
|
+
// Tier 3: Calibrated built-in table seeded from models.dev (offline fallback)
|
|
5
|
+
// Pure Web-Standard JS (zero `node:*` imports) so Cloudflare Workers, Node.js Server, and CLI share identical math.
|
|
3
6
|
|
|
7
|
+
export const PRICING_CACHE_VERSION = 1;
|
|
8
|
+
export const PRICING_TTL_MS = 24 * 60 * 60 * 1000;
|
|
9
|
+
export const PRICING_RETRY_COOLDOWN_MS = 6 * 60 * 60 * 1000;
|
|
10
|
+
|
|
11
|
+
export const PRICING_SOURCES = Object.freeze({
|
|
12
|
+
'models.dev': 'https://models.dev/api.json',
|
|
13
|
+
litellm: 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json',
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// Tier 3 exact normalized-key map (calibrated directly from models.dev / agy-bar, USD per 1M tokens)
|
|
17
|
+
export const BUILTIN_RATES_MAP = Object.freeze({
|
|
18
|
+
'claude-opus-5-5': Object.freeze({ label: 'Claude Opus 5.5', input: 4.0, output: 20.0, cacheRead: 0.2, cacheWrite: 5.0 }),
|
|
19
|
+
'claude-opus-5': Object.freeze({ label: 'Claude Opus 5', input: 5.0, output: 25.0, cacheRead: 0.5, cacheWrite: 6.25 }),
|
|
20
|
+
'claude-opus-4-8': Object.freeze({ label: 'Claude Opus 4.8', input: 5.0, output: 25.0, cacheRead: 0.5, cacheWrite: 6.25 }),
|
|
21
|
+
'claude-opus-4-7': Object.freeze({ label: 'Claude Opus 4.7', input: 5.0, output: 25.0, cacheRead: 0.5, cacheWrite: 6.25 }),
|
|
22
|
+
'claude-opus-4-6': Object.freeze({ label: 'Claude Opus 4.6', input: 5.0, output: 25.0, cacheRead: 0.5, cacheWrite: 6.25 }),
|
|
23
|
+
'claude-opus-4-5': Object.freeze({ label: 'Claude Opus 4.5', input: 5.0, output: 25.0, cacheRead: 0.5, cacheWrite: 6.25 }),
|
|
24
|
+
'claude-sonnet-5-5': Object.freeze({ label: 'Claude Sonnet 5.5', input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.5 }),
|
|
25
|
+
'claude-sonnet-5': Object.freeze({ label: 'Claude Sonnet 5', input: 2.0, output: 10.0, cacheRead: 0.2, cacheWrite: 2.5 }),
|
|
26
|
+
'claude-sonnet-4-6': Object.freeze({ label: 'Claude Sonnet 4.6', input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 }),
|
|
27
|
+
'claude-sonnet-4-5': Object.freeze({ label: 'Claude Sonnet 4.5', input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 }),
|
|
28
|
+
'claude-haiku-5-5': Object.freeze({ label: 'Claude Haiku 5.5', input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 }),
|
|
29
|
+
'claude-haiku-4-5': Object.freeze({ label: 'Claude Haiku 4.5', input: 1.0, output: 5.0, cacheRead: 0.1, cacheWrite: 1.25 }),
|
|
30
|
+
'claude-fable-5-2': Object.freeze({ label: 'Claude Fable 5.2', input: 8.0, output: 40.0, cacheRead: 0.2, cacheWrite: 10.0 }),
|
|
31
|
+
'claude-fable-5-1': Object.freeze({ label: 'Claude Fable 5.1', input: 10.0, output: 50.0, cacheRead: 0.25, cacheWrite: 12.5 }),
|
|
32
|
+
'claude-fable-5': Object.freeze({ label: 'Claude Fable 5', input: 10.0, output: 50.0, cacheRead: 1.0, cacheWrite: 12.5 }),
|
|
33
|
+
'gemini-4-neon': Object.freeze({ label: 'Gemini 4 Neon', input: 3.0, output: 15.0, cacheRead: 0.15, cacheWrite: 3.0 }),
|
|
34
|
+
'gemini-4-carbon': Object.freeze({ label: 'Gemini 4 Carbon', input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.0 }),
|
|
35
|
+
'gemini-4-argon': Object.freeze({ label: 'Gemini 4 Argon', input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.0 }),
|
|
36
|
+
'gemini-4-hydrogen': Object.freeze({ label: 'Gemini 4 Hydrogen', input: 1.5, output: 7.5, cacheRead: 0.075, cacheWrite: 1.5 }),
|
|
37
|
+
'gemini-3-8-flash': Object.freeze({ label: 'Gemini 3.8 Flash', input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 }),
|
|
38
|
+
'gemini-3-7-flash': Object.freeze({ label: 'Gemini 3.7 Flash', input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 }),
|
|
39
|
+
'gemini-3-6-flash': Object.freeze({ label: 'Gemini 3.6 Flash', input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 }),
|
|
40
|
+
'gemini-3-5-flash': Object.freeze({ label: 'Gemini 3.5 Flash', input: 1.5, output: 9.0, cacheRead: 0.15, cacheWrite: 1.5 }),
|
|
41
|
+
'gemini-3-5-flash-lite': Object.freeze({ label: 'Gemini 3.5 Flash Lite', input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 }),
|
|
42
|
+
'gemini-3-1-pro': Object.freeze({ label: 'Gemini 3.1 Pro', input: 2.0, output: 12.0, cacheRead: 0.2, cacheWrite: 2.0 }),
|
|
43
|
+
'gemini-3-1-pro-preview': Object.freeze({ label: 'Gemini 3.1 Pro Preview', input: 2.0, output: 12.0, cacheRead: 0.2, cacheWrite: 2.0 }),
|
|
44
|
+
'gemini-3-1-flash-lite': Object.freeze({ label: 'Gemini 3.1 Flash Lite', input: 0.25, output: 1.5, cacheRead: 0.025, cacheWrite: 0.25 }),
|
|
45
|
+
'gemini-3-1-flash-image': Object.freeze({ label: 'Gemini 3.1 Flash Image', input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 }),
|
|
46
|
+
'gemini-3-pro': Object.freeze({ label: 'Gemini 3 Pro', input: 2.0, output: 12.0, cacheRead: 0.2, cacheWrite: 2.0 }),
|
|
47
|
+
'gemini-3-flash': Object.freeze({ label: 'Gemini 3 Flash', input: 0.5, output: 3.0, cacheRead: 0.05, cacheWrite: 0.5 }),
|
|
48
|
+
'gemini-3-flash-preview': Object.freeze({ label: 'Gemini 3 Flash Preview', input: 0.5, output: 3.0, cacheRead: 0.05, cacheWrite: 0.5 }),
|
|
49
|
+
'gemini-2-5-pro': Object.freeze({ label: 'Gemini 2.5 Pro', input: 1.25, output: 10.0, cacheRead: 0.125, cacheWrite: 1.25 }),
|
|
50
|
+
'gemini-2-5-flash': Object.freeze({ label: 'Gemini 2.5 Flash', input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 }),
|
|
51
|
+
'gemini-2-5-flash-lite': Object.freeze({ label: 'Gemini 2.5 Flash-Lite', input: 0.1, output: 0.4, cacheRead: 0.01, cacheWrite: 0.1 }),
|
|
52
|
+
'gpt-oss-120b': Object.freeze({ label: 'GPT-OSS 120B', input: 0.15, output: 0.6, cacheRead: 0.015, cacheWrite: 0.15 }),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Broad family pattern fallback inside Tier 3 (when an unlisted minor variant name appears)
|
|
4
56
|
export const BUILTIN_RATES = Object.freeze([
|
|
57
|
+
Object.freeze({ id: 'claude-opus-5-5', pattern: /opus.*5\.5/i, label: 'Claude Opus 5.5', input: 4.0, output: 20.0, cacheRead: 0.2, cacheWrite: 5.0 }),
|
|
58
|
+
Object.freeze({ id: 'claude-sonnet-5-5', pattern: /sonnet.*5\.5/i, label: 'Claude Sonnet 5.5', input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.5 }),
|
|
59
|
+
Object.freeze({ id: 'claude-haiku-5-5', pattern: /haiku.*5\.5/i, label: 'Claude Haiku 5.5', input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 }),
|
|
60
|
+
Object.freeze({ id: 'claude-fable', pattern: /fable/i, label: 'Claude Fable', input: 10.0, output: 50.0, cacheRead: 0.25, cacheWrite: 12.5 }),
|
|
5
61
|
Object.freeze({ id: 'claude-opus-4-6', pattern: /opus/i, label: 'Claude Opus', input: 5.0, output: 25.0, cacheRead: 0.5, cacheWrite: 6.25 }),
|
|
6
62
|
Object.freeze({ id: 'claude-sonnet-4-6', pattern: /sonnet/i, label: 'Claude Sonnet', input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 }),
|
|
7
63
|
Object.freeze({ id: 'claude-haiku-4-5', pattern: /haiku/i, label: 'Claude Haiku', input: 1.0, output: 5.0, cacheRead: 0.1, cacheWrite: 1.25 }),
|
|
@@ -9,15 +65,19 @@ export const BUILTIN_RATES = Object.freeze([
|
|
|
9
65
|
Object.freeze({ id: 'gemini-4-carbon', pattern: /carbon/i, label: 'Gemini 4 Carbon', input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.0 }),
|
|
10
66
|
Object.freeze({ id: 'gemini-4-argon', pattern: /argon/i, label: 'Gemini 4 Argon', input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.0 }),
|
|
11
67
|
Object.freeze({ id: 'gemini-4-hydrogen', pattern: /hydrogen/i, label: 'Gemini 4 Hydrogen', input: 1.5, output: 7.5, cacheRead: 0.075, cacheWrite: 1.5 }),
|
|
12
|
-
Object.freeze({ id: 'gemini-3.8-flash', pattern: /3\.
|
|
68
|
+
Object.freeze({ id: 'gemini-3.8-flash', pattern: /3\.[678].*flash/i, label: 'Gemini 3.8 Flash', input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 }),
|
|
69
|
+
Object.freeze({ id: 'gemini-3.5-flash-lite', pattern: /3\.5.*flash.*lite/i, label: 'Gemini 3.5 Flash Lite', input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 }),
|
|
70
|
+
Object.freeze({ id: 'gemini-3.1-flash-lite', pattern: /3\.1.*flash.*lite/i, label: 'Gemini 3.1 Flash Lite', input: 0.25, output: 1.5, cacheRead: 0.025, cacheWrite: 0.25 }),
|
|
71
|
+
Object.freeze({ id: 'gemini-2.5-flash-lite', pattern: /2\.5.*flash.*lite/i, label: 'Gemini 2.5 Flash-Lite', input: 0.1, output: 0.4, cacheRead: 0.01, cacheWrite: 0.1 }),
|
|
13
72
|
Object.freeze({ id: 'gemini-3-pro', pattern: /gemini[- ]?3.*pro/i, label: 'Gemini 3 Pro', input: 2.0, output: 12.0, cacheRead: 0.2, cacheWrite: 2.0 }),
|
|
73
|
+
Object.freeze({ id: 'gemini-3-flash', pattern: /gemini[- ]?3.*flash/i, label: 'Gemini 3 Flash', input: 0.5, output: 3.0, cacheRead: 0.05, cacheWrite: 0.5 }),
|
|
14
74
|
Object.freeze({ id: 'gemini-2.5-pro', pattern: /pro/i, label: 'Gemini Pro', input: 1.25, output: 10.0, cacheRead: 0.125, cacheWrite: 1.25 }),
|
|
15
75
|
Object.freeze({ id: 'gemini-2.5-flash', pattern: /flash/i, label: 'Gemini Flash', input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 }),
|
|
16
|
-
Object.freeze({ id: 'gpt-oss', pattern: /gpt/i, label: 'GPT', input:
|
|
76
|
+
Object.freeze({ id: 'gpt-oss-120b', pattern: /gpt[- ]?oss/i, label: 'GPT-OSS 120B', input: 0.15, output: 0.6, cacheRead: 0.015, cacheWrite: 0.15 }),
|
|
77
|
+
Object.freeze({ id: 'gpt', pattern: /gpt/i, label: 'GPT', input: 1.5, output: 6.0, cacheRead: 0.15, cacheWrite: 1.5 }),
|
|
17
78
|
]);
|
|
18
79
|
|
|
19
|
-
// Conservative
|
|
20
|
-
// (e.g. Model #1532) never silently price at $0.00 on the family leaderboard.
|
|
80
|
+
// Conservative fallback rate ONLY for completely unmapped raw enum IDs (e.g. Model #9999)
|
|
21
81
|
export const FALLBACK_UNKNOWN_RATE = Object.freeze({
|
|
22
82
|
id: 'unknown-fallback',
|
|
23
83
|
label: 'Unknown (Est.)',
|
|
@@ -25,24 +85,300 @@ export const FALLBACK_UNKNOWN_RATE = Object.freeze({
|
|
|
25
85
|
output: 10.0,
|
|
26
86
|
cacheRead: 0.1,
|
|
27
87
|
cacheWrite: 2.0,
|
|
88
|
+
source: 'fallback',
|
|
28
89
|
isFallback: true,
|
|
29
90
|
});
|
|
30
91
|
|
|
31
|
-
|
|
92
|
+
const SKIP_MODEL_RE = /(?:audio|tts|embedding|live-translate|live-preview|computer-use|vision-only|customtools|20\d{6})/i;
|
|
93
|
+
const KEEP_MODEL_RE = /(?:gemini|claude|gpt-oss)/i;
|
|
94
|
+
|
|
95
|
+
function roundRate(n) {
|
|
96
|
+
return Math.round((Number(n) || 0) * 10_000) / 10_000;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function normalizeModelKey(name) {
|
|
100
|
+
return String(name || '')
|
|
101
|
+
.trim()
|
|
102
|
+
.toLowerCase()
|
|
103
|
+
.replace(/\s*\((?:low|medium|high|xhigh|max|latest|thinking|orchestrator)\)\s*/gi, '')
|
|
104
|
+
.replace(/-(?:low|medium|high|xhigh|max|latest)$/i, '')
|
|
105
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
106
|
+
.replace(/^-+|-+$/g, '');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function isValidRateEntry(entry) {
|
|
110
|
+
if (!entry || typeof entry !== 'object') return false;
|
|
111
|
+
const { input, output } = entry;
|
|
112
|
+
if (typeof input !== 'number' || !Number.isFinite(input) || input <= 0 || input > 500) return false;
|
|
113
|
+
if (typeof output !== 'number' || !Number.isFinite(output) || output <= 0 || output > 1000) return false;
|
|
114
|
+
const cacheRead = entry.cacheRead ?? 0;
|
|
115
|
+
const cacheWrite = entry.cacheWrite ?? input;
|
|
116
|
+
if (typeof cacheRead !== 'number' || !Number.isFinite(cacheRead) || cacheRead < 0 || cacheRead > input * 2) return false;
|
|
117
|
+
if (typeof cacheWrite !== 'number' || !Number.isFinite(cacheWrite) || cacheWrite < 0 || cacheWrite > input * 4) return false;
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function extractModelsDevRates(payload) {
|
|
122
|
+
if (!payload || typeof payload !== 'object') return {};
|
|
123
|
+
const out = {};
|
|
124
|
+
|
|
125
|
+
for (const providerKey of ['google', 'anthropic', 'openai', 'openrouter', 'groq']) {
|
|
126
|
+
const models = payload[providerKey]?.models;
|
|
127
|
+
if (!models || typeof models !== 'object') continue;
|
|
128
|
+
|
|
129
|
+
for (const [rawId, meta] of Object.entries(models)) {
|
|
130
|
+
const cleanId = rawId.replace(/^(?:google|anthropic|openai)\//i, '');
|
|
131
|
+
if (!KEEP_MODEL_RE.test(cleanId) || SKIP_MODEL_RE.test(cleanId)) continue;
|
|
132
|
+
if ((providerKey === 'openrouter' || providerKey === 'groq') && !/gpt-oss/i.test(cleanId)) continue;
|
|
133
|
+
const cost = meta?.cost;
|
|
134
|
+
if (!cost || typeof cost !== 'object') continue;
|
|
135
|
+
const input = Number(cost.input);
|
|
136
|
+
const output = Number(cost.output);
|
|
137
|
+
const cacheRead = cost.cache_read != null ? Number(cost.cache_read) : roundRate(input * 0.1);
|
|
138
|
+
const cacheWrite = cost.cache_write != null ? Number(cost.cache_write) : input;
|
|
139
|
+
|
|
140
|
+
const entry = {
|
|
141
|
+
label: typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : cleanId,
|
|
142
|
+
input: roundRate(input),
|
|
143
|
+
output: roundRate(output),
|
|
144
|
+
cacheRead: roundRate(cacheRead),
|
|
145
|
+
cacheWrite: roundRate(cacheWrite),
|
|
146
|
+
};
|
|
147
|
+
const normKey = normalizeModelKey(cleanId);
|
|
148
|
+
if (normKey && isValidRateEntry(entry) && !Object.hasOwn(out, normKey)) {
|
|
149
|
+
out[normKey] = entry;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function extractLiteLlmRates(payload) {
|
|
157
|
+
if (!payload || typeof payload !== 'object') return {};
|
|
158
|
+
const out = {};
|
|
159
|
+
|
|
160
|
+
for (const [rawId, meta] of Object.entries(payload)) {
|
|
161
|
+
if (!meta || typeof meta !== 'object') continue;
|
|
162
|
+
const cleanId = rawId.replace(/^(?:google|gemini|anthropic|vertex_ai|openai)\//i, '');
|
|
163
|
+
if (!KEEP_MODEL_RE.test(cleanId) || SKIP_MODEL_RE.test(cleanId)) continue;
|
|
164
|
+
if (rawId.includes('/') && !/^(?:google|gemini|anthropic|openai)\//i.test(rawId)) continue;
|
|
165
|
+
|
|
166
|
+
const rawIn = Number(meta.input_cost_per_token);
|
|
167
|
+
const rawOut = Number(meta.output_cost_per_token);
|
|
168
|
+
if (!Number.isFinite(rawIn) || !Number.isFinite(rawOut) || rawIn <= 0 || rawOut <= 0) continue;
|
|
169
|
+
|
|
170
|
+
const input = roundRate(rawIn * 1_000_000);
|
|
171
|
+
const output = roundRate(rawOut * 1_000_000);
|
|
172
|
+
const rawCr = Number(meta.cache_read_input_token_cost);
|
|
173
|
+
const rawCw = Number(meta.cache_creation_input_token_cost);
|
|
174
|
+
const cacheRead = Number.isFinite(rawCr) && rawCr >= 0 ? roundRate(rawCr * 1_000_000) : roundRate(input * 0.1);
|
|
175
|
+
const cacheWrite = Number.isFinite(rawCw) && rawCw >= 0 ? roundRate(rawCw * 1_000_000) : input;
|
|
176
|
+
|
|
177
|
+
const normKey = normalizeModelKey(cleanId);
|
|
178
|
+
const entry = { label: cleanId, input, output, cacheRead, cacheWrite };
|
|
179
|
+
if (normKey && isValidRateEntry(entry) && !Object.hasOwn(out, normKey)) {
|
|
180
|
+
out[normKey] = entry;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function fetchRemotePricingCache({
|
|
187
|
+
existing = null,
|
|
188
|
+
source = 'auto',
|
|
189
|
+
force = false,
|
|
190
|
+
now = Date.now(),
|
|
191
|
+
timeoutMs = 10_000,
|
|
192
|
+
fetchFn = globalThis.fetch,
|
|
193
|
+
} = {}) {
|
|
194
|
+
const plan =
|
|
195
|
+
source === 'models.dev'
|
|
196
|
+
? ['models.dev']
|
|
197
|
+
: source === 'litellm'
|
|
198
|
+
? ['litellm']
|
|
199
|
+
: ['models.dev', 'litellm'];
|
|
200
|
+
const errors = [];
|
|
201
|
+
|
|
202
|
+
for (const srcName of plan) {
|
|
203
|
+
const url = PRICING_SOURCES[srcName];
|
|
204
|
+
const etag = !force && existing?.source === srcName ? existing.etag || null : null;
|
|
205
|
+
const controller = new AbortController();
|
|
206
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
207
|
+
try {
|
|
208
|
+
const headers = { Accept: 'application/json', 'User-Agent': 'agy-family-pricing-sync' };
|
|
209
|
+
if (etag) headers['If-None-Match'] = etag;
|
|
210
|
+
const res = await fetchFn(url, { method: 'GET', headers, signal: controller.signal });
|
|
211
|
+
if (res.status === 304 && existing?.rates) {
|
|
212
|
+
return {
|
|
213
|
+
ok: true,
|
|
214
|
+
updated: false,
|
|
215
|
+
notModified: true,
|
|
216
|
+
cache: {
|
|
217
|
+
...existing,
|
|
218
|
+
fetchedAt: now,
|
|
219
|
+
lastAttemptAt: now,
|
|
220
|
+
etag: res.headers.get('etag') || existing.etag || null,
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} from ${srcName}`);
|
|
225
|
+
const json = await res.json();
|
|
226
|
+
const rates = srcName === 'models.dev' ? extractModelsDevRates(json) : extractLiteLlmRates(json);
|
|
227
|
+
const count = Object.keys(rates).length;
|
|
228
|
+
if (count < 5) throw new Error(`Sanity guard rejected ${srcName} payload (${count} rates)`);
|
|
229
|
+
return {
|
|
230
|
+
ok: true,
|
|
231
|
+
updated: true,
|
|
232
|
+
notModified: false,
|
|
233
|
+
cache: {
|
|
234
|
+
version: PRICING_CACHE_VERSION,
|
|
235
|
+
source: srcName,
|
|
236
|
+
fetchedAt: now,
|
|
237
|
+
lastAttemptAt: now,
|
|
238
|
+
etag: res.headers.get('etag') || null,
|
|
239
|
+
rates,
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
} catch (err) {
|
|
243
|
+
errors.push(`${srcName}: ${err?.message || err}`);
|
|
244
|
+
} finally {
|
|
245
|
+
clearTimeout(timer);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
ok: false,
|
|
251
|
+
updated: false,
|
|
252
|
+
notModified: false,
|
|
253
|
+
error: errors.join('; '),
|
|
254
|
+
cache: existing ? { ...existing, lastAttemptAt: now } : null,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function matchFromMap(normKey, rawLower, ratesMap, sourceLabel) {
|
|
259
|
+
if (!ratesMap || typeof ratesMap !== 'object') return null;
|
|
260
|
+
|
|
261
|
+
// 1. Exact normalized ID match (e.g. "claude-opus-5-5", "gemini-4-hydrogen")
|
|
262
|
+
if (normKey && Object.hasOwn(ratesMap, normKey) && isValidRateEntry(ratesMap[normKey])) {
|
|
263
|
+
const r = ratesMap[normKey];
|
|
264
|
+
return {
|
|
265
|
+
id: normKey,
|
|
266
|
+
label: r.label || normKey,
|
|
267
|
+
input: r.input,
|
|
268
|
+
output: r.output,
|
|
269
|
+
cacheRead: r.cacheRead ?? 0,
|
|
270
|
+
cacheWrite: r.cacheWrite ?? r.input,
|
|
271
|
+
source: sourceLabel,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// 2. Longest normalized key prefix/substring match (prefer specific version matches)
|
|
276
|
+
let bestKey = null;
|
|
277
|
+
let bestScore = 0;
|
|
278
|
+
for (const [k, r] of Object.entries(ratesMap)) {
|
|
279
|
+
if (!isValidRateEntry(r)) continue;
|
|
280
|
+
const nk = normalizeModelKey(k);
|
|
281
|
+
if (!nk) continue;
|
|
282
|
+
if (normKey === nk) {
|
|
283
|
+
bestKey = k;
|
|
284
|
+
bestScore = 10_000;
|
|
285
|
+
break;
|
|
286
|
+
}
|
|
287
|
+
if ((normKey && (normKey.includes(nk) || nk.includes(normKey))) || rawLower.includes(k.toLowerCase())) {
|
|
288
|
+
const score = nk.length;
|
|
289
|
+
if (score > bestScore) {
|
|
290
|
+
bestScore = score;
|
|
291
|
+
bestKey = k;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (bestKey) {
|
|
297
|
+
const r = ratesMap[bestKey];
|
|
298
|
+
return {
|
|
299
|
+
id: bestKey,
|
|
300
|
+
label: r.label || bestKey,
|
|
301
|
+
input: r.input,
|
|
302
|
+
output: r.output,
|
|
303
|
+
cacheRead: r.cacheRead ?? 0,
|
|
304
|
+
cacheWrite: r.cacheWrite ?? r.input,
|
|
305
|
+
source: sourceLabel,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Optional Node-side local pricing provider hook (auto-registered by `pricing-node.mjs` in CLI/Extension)
|
|
312
|
+
let defaultLocalPricingProvider = null;
|
|
313
|
+
export function registerDefaultLocalPricingProvider(fn) {
|
|
314
|
+
defaultLocalPricingProvider = typeof fn === 'function' ? fn : null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function lookupRates(
|
|
318
|
+
modelName,
|
|
319
|
+
{ customPricing = undefined, pricingCache = undefined, useLocalSources = true, fallback = false } = {},
|
|
320
|
+
) {
|
|
32
321
|
const raw = String(modelName || '').trim();
|
|
33
322
|
if (!raw) return fallback ? FALLBACK_UNKNOWN_RATE : null;
|
|
323
|
+
const rawLower = raw.toLowerCase();
|
|
324
|
+
const normKey = normalizeModelKey(raw);
|
|
325
|
+
|
|
326
|
+
let resolvedCustom = customPricing;
|
|
327
|
+
let resolvedCache = pricingCache;
|
|
328
|
+
if (useLocalSources && defaultLocalPricingProvider && (resolvedCustom === undefined || resolvedCache === undefined)) {
|
|
329
|
+
const local = defaultLocalPricingProvider();
|
|
330
|
+
if (resolvedCustom === undefined) resolvedCustom = local?.customPricing || null;
|
|
331
|
+
if (resolvedCache === undefined) resolvedCache = local?.pricingCache || null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Tier 1: User / Admin custom overrides
|
|
335
|
+
const fromCustom = matchFromMap(normKey, rawLower, resolvedCustom, 'custom');
|
|
336
|
+
if (fromCustom) return fromCustom;
|
|
337
|
+
|
|
338
|
+
// Tier 2: Synced pricing cache (`models.dev` -> `litellm`)
|
|
339
|
+
const cacheRates = resolvedCache?.rates || (resolvedCache && !resolvedCache.version ? resolvedCache : null);
|
|
340
|
+
const cacheLabel = resolvedCache?.source ? `cache:${resolvedCache.source}` : 'cache';
|
|
341
|
+
const fromCache = matchFromMap(normKey, rawLower, cacheRates, cacheLabel);
|
|
342
|
+
if (fromCache) return fromCache;
|
|
343
|
+
|
|
344
|
+
// Tier 3a: Calibrated built-in exact / longest-key map (seeded from models.dev)
|
|
345
|
+
const fromBuiltinMap = matchFromMap(normKey, rawLower, BUILTIN_RATES_MAP, 'builtin');
|
|
346
|
+
if (fromBuiltinMap) return fromBuiltinMap;
|
|
347
|
+
|
|
348
|
+
// Tier 3b: Broad model-family regex fallback
|
|
34
349
|
for (const rate of BUILTIN_RATES) {
|
|
35
|
-
if (rate.pattern.test(raw))
|
|
350
|
+
if (rate.pattern.test(raw)) {
|
|
351
|
+
return {
|
|
352
|
+
id: rate.id,
|
|
353
|
+
label: rate.label,
|
|
354
|
+
input: rate.input,
|
|
355
|
+
output: rate.output,
|
|
356
|
+
cacheRead: rate.cacheRead,
|
|
357
|
+
cacheWrite: rate.cacheWrite,
|
|
358
|
+
source: 'builtin',
|
|
359
|
+
};
|
|
360
|
+
}
|
|
36
361
|
}
|
|
362
|
+
|
|
37
363
|
return fallback ? FALLBACK_UNKNOWN_RATE : null;
|
|
38
364
|
}
|
|
39
365
|
|
|
40
|
-
export function isKnownModelRate(modelName) {
|
|
41
|
-
return lookupRates(modelName, { fallback: false }) !== null;
|
|
366
|
+
export function isKnownModelRate(modelName, opts = {}) {
|
|
367
|
+
return lookupRates(modelName, { ...opts, fallback: false }) !== null;
|
|
42
368
|
}
|
|
43
369
|
|
|
44
|
-
export function estimateUsageUsd({
|
|
45
|
-
|
|
370
|
+
export function estimateUsageUsd({
|
|
371
|
+
model,
|
|
372
|
+
input = 0,
|
|
373
|
+
output = 0,
|
|
374
|
+
cacheRead = 0,
|
|
375
|
+
cacheWrite = 0,
|
|
376
|
+
customPricing = undefined,
|
|
377
|
+
pricingCache = undefined,
|
|
378
|
+
useLocalSources = true,
|
|
379
|
+
fallback = true,
|
|
380
|
+
} = {}) {
|
|
381
|
+
const rates = lookupRates(model, { customPricing, pricingCache, useLocalSources, fallback });
|
|
46
382
|
if (!rates) return 0;
|
|
47
383
|
const usd =
|
|
48
384
|
(Math.max(0, Number(input) || 0) * rates.input +
|
|
@@ -53,10 +389,17 @@ export function estimateUsageUsd({ model, input = 0, output = 0, cacheRead = 0,
|
|
|
53
389
|
return Math.round(usd * 10_000) / 10_000;
|
|
54
390
|
}
|
|
55
391
|
|
|
56
|
-
export function estimateCacheSavedUsd({
|
|
392
|
+
export function estimateCacheSavedUsd({
|
|
393
|
+
model,
|
|
394
|
+
cacheRead = 0,
|
|
395
|
+
customPricing = undefined,
|
|
396
|
+
pricingCache = undefined,
|
|
397
|
+
useLocalSources = true,
|
|
398
|
+
fallback = true,
|
|
399
|
+
} = {}) {
|
|
57
400
|
const cached = Math.max(0, Number(cacheRead) || 0);
|
|
58
401
|
if (!cached) return 0;
|
|
59
|
-
const rates = lookupRates(model, { fallback });
|
|
402
|
+
const rates = lookupRates(model, { customPricing, pricingCache, useLocalSources, fallback });
|
|
60
403
|
if (!rates) return 0;
|
|
61
404
|
const delta = Math.max(0, Number(rates.input || 0) - Number(rates.cacheRead || 0));
|
|
62
405
|
return Math.round(((cached * delta) / 1_000_000) * 10_000) / 10_000;
|
|
@@ -82,7 +82,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
|
|
|
82
82
|
export async function buildSyncPayload({
|
|
83
83
|
deviceId,
|
|
84
84
|
clientKind = 'cli',
|
|
85
|
-
clientVersion = '0.2.
|
|
85
|
+
clientVersion = '0.2.7',
|
|
86
86
|
home,
|
|
87
87
|
roots = null,
|
|
88
88
|
sourceFilter = 'all',
|
|
@@ -155,7 +155,7 @@ export async function buildSyncPayload({
|
|
|
155
155
|
deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
|
|
156
156
|
client: {
|
|
157
157
|
kind: clientKind === 'extension' ? 'extension' : 'cli',
|
|
158
|
-
version: String(clientVersion || '0.2.
|
|
158
|
+
version: String(clientVersion || '0.2.7').slice(0, 24),
|
|
159
159
|
},
|
|
160
160
|
account: {
|
|
161
161
|
emailHash: effectiveReportedHash,
|
|
@@ -18,11 +18,12 @@ import {
|
|
|
18
18
|
loadSettings,
|
|
19
19
|
resolveFamilyQuotas,
|
|
20
20
|
roundUsd,
|
|
21
|
+
syncServerPricingCache,
|
|
21
22
|
} from './stats.mjs';
|
|
22
23
|
import { renderDashboardHtml } from './ui.mjs';
|
|
23
24
|
import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
|
|
24
25
|
|
|
25
|
-
export const SERVER_VERSION = '0.2.
|
|
26
|
+
export const SERVER_VERSION = '0.2.7';
|
|
26
27
|
const MAX_BUCKETS_PER_SYNC = 1000;
|
|
27
28
|
const MAX_DEVICES_PER_MEMBER = 8;
|
|
28
29
|
const MAX_TOKENS_PER_BUCKET = 500_000_000;
|
|
@@ -41,6 +42,7 @@ const ALLOWED_SETTINGS_KEYS = new Set([
|
|
|
41
42
|
'poolTotalCredits',
|
|
42
43
|
'monthlyPlanCost',
|
|
43
44
|
'monthlyPlanCurrency',
|
|
45
|
+
'customPricing',
|
|
44
46
|
'webhookUrl',
|
|
45
47
|
'webhookType',
|
|
46
48
|
'boardViewKey',
|
|
@@ -179,15 +181,14 @@ const UPSERT_BUCKET_SQL = `INSERT INTO usage_buckets
|
|
|
179
181
|
cache_read_tokens = MAX(usage_buckets.cache_read_tokens, excluded.cache_read_tokens),
|
|
180
182
|
thinking_tokens = MAX(usage_buckets.thinking_tokens, excluded.thinking_tokens),
|
|
181
183
|
steps = MAX(usage_buckets.steps, excluded.steps),
|
|
182
|
-
est_usd =
|
|
184
|
+
est_usd = excluded.est_usd,
|
|
183
185
|
updated_at = excluded.updated_at
|
|
184
186
|
WHERE
|
|
185
187
|
excluded.input_tokens > usage_buckets.input_tokens OR
|
|
186
188
|
excluded.output_tokens > usage_buckets.output_tokens OR
|
|
187
189
|
excluded.cache_read_tokens > usage_buckets.cache_read_tokens OR
|
|
188
190
|
excluded.thinking_tokens > usage_buckets.thinking_tokens OR
|
|
189
|
-
excluded.steps > usage_buckets.steps
|
|
190
|
-
excluded.est_usd > usage_buckets.est_usd`;
|
|
191
|
+
excluded.steps > usage_buckets.steps`;
|
|
191
192
|
|
|
192
193
|
const UPSERT_ODOMETER_SQL = `INSERT INTO device_odometers
|
|
193
194
|
(member_id, device_id, max_db_files, max_all_time_steps, max_all_time_tokens, last_db_files, last_all_time_steps, last_all_time_tokens, last_nonzero_at, updated_at)
|
|
@@ -446,6 +447,7 @@ export function createApp({
|
|
|
446
447
|
);
|
|
447
448
|
}
|
|
448
449
|
|
|
450
|
+
const settings = await loadSettings(db, envDefaults);
|
|
449
451
|
const maxAllowedTs = now + 24 * 60 * 60 * 1000;
|
|
450
452
|
const minAllowedTs = now - 400 * 24 * 60 * 60 * 1000;
|
|
451
453
|
const normalizedBuckets = [];
|
|
@@ -466,13 +468,16 @@ export function createApp({
|
|
|
466
468
|
const steps = Math.min(MAX_STEPS_PER_BUCKET, Math.max(0, Math.floor(Number(b.steps) || 0)));
|
|
467
469
|
if (inputTokens + outputTokens + cacheReadTokens + steps === 0) continue;
|
|
468
470
|
|
|
469
|
-
// Server recomputes est_usd
|
|
471
|
+
// Server recomputes est_usd via 3-Tier Pricing Engine (custom -> models.dev/litellm cache -> builtin)
|
|
470
472
|
// so clients cannot spoof artificially low USD totals.
|
|
471
473
|
const serverEstUsd = estimateUsageUsd({
|
|
472
474
|
model,
|
|
473
475
|
input: inputTokens,
|
|
474
476
|
output: outputTokens,
|
|
475
477
|
cacheRead: cacheReadTokens,
|
|
478
|
+
customPricing: settings.customPricing || null,
|
|
479
|
+
pricingCache: settings.pricingCache || null,
|
|
480
|
+
useLocalSources: false,
|
|
476
481
|
fallback: true,
|
|
477
482
|
});
|
|
478
483
|
const estUsd = serverEstUsd > 0 ? serverEstUsd : Math.max(0, roundUsd(b.estUsd || 0));
|
|
@@ -512,13 +517,23 @@ export function createApp({
|
|
|
512
517
|
const stepDrop = nb.steps < Number(ex.steps || 0);
|
|
513
518
|
const inDrop = nb.inputTokens < Number(ex.input_tokens || 0);
|
|
514
519
|
const outDrop = nb.outputTokens < Number(ex.output_tokens || 0);
|
|
515
|
-
const
|
|
516
|
-
if (stepDrop || inDrop || outDrop ||
|
|
520
|
+
const cacheDrop = nb.cacheReadTokens < Number(ex.cache_read_tokens || 0);
|
|
521
|
+
if (stepDrop || inDrop || outDrop || cacheDrop) {
|
|
522
|
+
const prevUsd = estimateUsageUsd({
|
|
523
|
+
model: nb.model,
|
|
524
|
+
input: Number(ex.input_tokens || 0),
|
|
525
|
+
output: Number(ex.output_tokens || 0),
|
|
526
|
+
cacheRead: Number(ex.cache_read_tokens || 0),
|
|
527
|
+
customPricing: settings.customPricing || null,
|
|
528
|
+
pricingCache: settings.pricingCache || null,
|
|
529
|
+
useLocalSources: false,
|
|
530
|
+
fallback: true,
|
|
531
|
+
});
|
|
517
532
|
rollbackFindings.push({
|
|
518
533
|
model: nb.model,
|
|
519
534
|
prevSteps: Number(ex.steps || 0),
|
|
520
535
|
nextSteps: nb.steps,
|
|
521
|
-
prevUsd
|
|
536
|
+
prevUsd,
|
|
522
537
|
nextUsd: nb.estUsd,
|
|
523
538
|
});
|
|
524
539
|
}
|
|
@@ -618,7 +633,6 @@ export function createApp({
|
|
|
618
633
|
await runBatchedWrites(db, writeStmts);
|
|
619
634
|
const accepted = normalizedBuckets.length;
|
|
620
635
|
|
|
621
|
-
const settings = await loadSettings(db, envDefaults);
|
|
622
636
|
const capSnap = await computeMemberCapsSnapshot(db, member, settings, now);
|
|
623
637
|
|
|
624
638
|
// Fire deduped integrity webhook alerts
|
|
@@ -1104,6 +1118,13 @@ export function createApp({
|
|
|
1104
1118
|
return adminJsonRes({ ok: true, cleared: true });
|
|
1105
1119
|
}
|
|
1106
1120
|
|
|
1121
|
+
if (request.method === 'POST' && path === '/api/admin/pricing-sync') {
|
|
1122
|
+
const body = await readJsonBody(request);
|
|
1123
|
+
const source = ['auto', 'models.dev', 'litellm'].includes(body?.source) ? body.source : 'auto';
|
|
1124
|
+
const res = await syncServerPricingCache(db, { source, force: true, now, fetchFn });
|
|
1125
|
+
return adminJsonRes(res, res.ok ? 200 : 502);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1107
1128
|
if (request.method === 'POST' && path === '/api/admin/webhook-test') {
|
|
1108
1129
|
const settings = await loadSettings(db, envDefaults);
|
|
1109
1130
|
const res = await dispatchWebhook({
|
|
@@ -1128,4 +1149,4 @@ export function createApp({
|
|
|
1128
1149
|
};
|
|
1129
1150
|
}
|
|
1130
1151
|
|
|
1131
|
-
export { checkOfflineMembersAndAlert, evaluateQuotaProgress, getPeriodWindow, resolveFamilyQuotas };
|
|
1152
|
+
export { checkOfflineMembersAndAlert, evaluateQuotaProgress, getPeriodWindow, resolveFamilyQuotas, syncServerPricingCache };
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
// Transparent family board aggregation, period windows, cap evaluation,
|
|
2
2
|
// 24h activity timeline, member drill-down, CSV settlement export, and shared AI Credits reconciliation.
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
estimateCacheSavedUsd,
|
|
6
|
+
estimateUsageUsd,
|
|
7
|
+
fetchRemotePricingCache,
|
|
8
|
+
isKnownModelRate,
|
|
9
|
+
PRICING_RETRY_COOLDOWN_MS,
|
|
10
|
+
PRICING_TTL_MS,
|
|
11
|
+
} from '../../core/src/pricing.mjs';
|
|
5
12
|
import { normalizeModelName } from '../../core/src/protobuf.mjs';
|
|
6
13
|
import { DEFAULT_SETTINGS, MAX_FAMILY_MEMBERS } from './schema.mjs';
|
|
7
14
|
import { sendDedupedAlert } from './webhooks.mjs';
|
|
@@ -9,6 +16,82 @@ import { sendDedupedAlert } from './webhooks.mjs';
|
|
|
9
16
|
const HOUR_MS = 60 * 60 * 1000;
|
|
10
17
|
const DAY_MS = 24 * HOUR_MS;
|
|
11
18
|
|
|
19
|
+
export function computeBucketUsdServer(row, settings = {}) {
|
|
20
|
+
const inp = Number(row.input_tokens) || 0;
|
|
21
|
+
const out = Number(row.output_tokens) || 0;
|
|
22
|
+
const cached = Number(row.cache_read_tokens) || 0;
|
|
23
|
+
if (inp + out + cached <= 0) {
|
|
24
|
+
return Number(row.est_usd) || 0;
|
|
25
|
+
}
|
|
26
|
+
const modName = normalizeModelName(row.model);
|
|
27
|
+
return estimateUsageUsd({
|
|
28
|
+
model: modName,
|
|
29
|
+
input: inp,
|
|
30
|
+
output: out,
|
|
31
|
+
cacheRead: cached,
|
|
32
|
+
customPricing: settings.customPricing || null,
|
|
33
|
+
pricingCache: settings.pricingCache || null,
|
|
34
|
+
useLocalSources: false,
|
|
35
|
+
fallback: true,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function syncServerPricingCache(
|
|
40
|
+
db,
|
|
41
|
+
{ source = 'auto', force = false, now = Date.now(), fetchFn = globalThis.fetch } = {},
|
|
42
|
+
) {
|
|
43
|
+
const row = await db.get("SELECT value FROM settings WHERE key = 'pricingCache'");
|
|
44
|
+
let existing = null;
|
|
45
|
+
if (row?.value) {
|
|
46
|
+
try {
|
|
47
|
+
existing = JSON.parse(row.value);
|
|
48
|
+
} catch {
|
|
49
|
+
existing = null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (!force && existing && typeof existing === 'object') {
|
|
54
|
+
if (typeof existing.fetchedAt === 'number' && now - existing.fetchedAt < PRICING_TTL_MS) {
|
|
55
|
+
return {
|
|
56
|
+
ok: true,
|
|
57
|
+
updated: false,
|
|
58
|
+
skippedFresh: true,
|
|
59
|
+
source: existing.source || 'cache',
|
|
60
|
+
count: Object.keys(existing.rates || {}).length,
|
|
61
|
+
fetchedAt: existing.fetchedAt,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (typeof existing.lastAttemptAt === 'number' && now - existing.lastAttemptAt < PRICING_RETRY_COOLDOWN_MS) {
|
|
65
|
+
return {
|
|
66
|
+
ok: true,
|
|
67
|
+
updated: false,
|
|
68
|
+
skippedCooldown: true,
|
|
69
|
+
source: existing.source || 'builtin',
|
|
70
|
+
count: Object.keys(existing.rates || {}).length,
|
|
71
|
+
fetchedAt: existing.fetchedAt || null,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const res = await fetchRemotePricingCache({ existing, source, force, now, fetchFn });
|
|
77
|
+
if (res.cache) {
|
|
78
|
+
await db.run(
|
|
79
|
+
`INSERT INTO settings (key, value, updated_at) VALUES ('pricingCache', ?, ?)
|
|
80
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
|
|
81
|
+
[JSON.stringify(res.cache), now],
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
ok: res.ok,
|
|
86
|
+
updated: res.updated,
|
|
87
|
+
notModified: res.notModified,
|
|
88
|
+
error: res.error || null,
|
|
89
|
+
source: res.cache?.source || existing?.source || 'builtin',
|
|
90
|
+
count: Object.keys(res.cache?.rates || {}).length,
|
|
91
|
+
fetchedAt: res.cache?.fetchedAt || existing?.fetchedAt || null,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
12
95
|
export function roundUsd(n) {
|
|
13
96
|
return Math.round((Number(n) || 0) * 10_000) / 10_000;
|
|
14
97
|
}
|
|
@@ -301,7 +384,7 @@ export async function computeMemberCapsSnapshot(db, member, settings, now = Date
|
|
|
301
384
|
|
|
302
385
|
const earliest = Math.min(dailyWin.startMs, weeklyWin.startMs, cycleWin.startMs);
|
|
303
386
|
const rows = await db.all(
|
|
304
|
-
'SELECT bucket_hour_ms, est_usd, input_tokens, output_tokens, cache_read_tokens FROM usage_buckets WHERE member_id = ? AND bucket_hour_ms >= ?',
|
|
387
|
+
'SELECT bucket_hour_ms, model, est_usd, input_tokens, output_tokens, cache_read_tokens FROM usage_buckets WHERE member_id = ? AND bucket_hour_ms >= ?',
|
|
305
388
|
[member.id, earliest],
|
|
306
389
|
);
|
|
307
390
|
|
|
@@ -309,7 +392,7 @@ export async function computeMemberCapsSnapshot(db, member, settings, now = Date
|
|
|
309
392
|
let weeklyUsedUsd = 0;
|
|
310
393
|
let cycleUsedUsd = 0;
|
|
311
394
|
for (const r of rows || []) {
|
|
312
|
-
const usd =
|
|
395
|
+
const usd = computeBucketUsdServer(r, settings);
|
|
313
396
|
if (r.bucket_hour_ms >= dailyWin.startMs) dailyUsedUsd += usd;
|
|
314
397
|
if (r.bucket_hour_ms >= weeklyWin.startMs) weeklyUsedUsd += usd;
|
|
315
398
|
if (r.bucket_hour_ms >= cycleWin.startMs) cycleUsedUsd += usd;
|
|
@@ -407,20 +490,21 @@ export async function computeCreditsReconciliation(db, members, settings, cycleI
|
|
|
407
490
|
|
|
408
491
|
const winStartHour = Math.floor(previous.recorded_at / HOUR_MS) * HOUR_MS;
|
|
409
492
|
const winEndHour = Math.floor(latest.recorded_at / HOUR_MS) * HOUR_MS + HOUR_MS;
|
|
410
|
-
const
|
|
411
|
-
'SELECT member_id,
|
|
493
|
+
const rawWinBuckets = await db.all(
|
|
494
|
+
'SELECT member_id, model, input_tokens, output_tokens, cache_read_tokens, steps, est_usd FROM usage_buckets WHERE bucket_hour_ms >= ? AND bucket_hour_ms <= ?',
|
|
412
495
|
[winStartHour, winEndHour],
|
|
413
496
|
);
|
|
414
497
|
|
|
415
498
|
let reportedUsd = 0;
|
|
416
499
|
let reportedSteps = 0;
|
|
417
500
|
const reportedByMember = new Map();
|
|
418
|
-
for (const r of
|
|
419
|
-
const usd =
|
|
501
|
+
for (const r of rawWinBuckets || []) {
|
|
502
|
+
const usd = computeBucketUsdServer(r, settings);
|
|
420
503
|
const steps = Number(r.steps) || 0;
|
|
421
504
|
reportedUsd += usd;
|
|
422
505
|
reportedSteps += steps;
|
|
423
|
-
reportedByMember.
|
|
506
|
+
const prev = reportedByMember.get(r.member_id) || { usd: 0, steps: 0 };
|
|
507
|
+
reportedByMember.set(r.member_id, { usd: prev.usd + usd, steps: prev.steps + steps });
|
|
424
508
|
}
|
|
425
509
|
reportedUsd = roundUsd(reportedUsd);
|
|
426
510
|
|
|
@@ -586,6 +670,12 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
586
670
|
let totalCliUsd = 0;
|
|
587
671
|
let cycleUsedUsd = 0;
|
|
588
672
|
|
|
673
|
+
const rateLookupOpts = {
|
|
674
|
+
customPricing: settings.customPricing || null,
|
|
675
|
+
pricingCache: settings.pricingCache || null,
|
|
676
|
+
useLocalSources: false,
|
|
677
|
+
};
|
|
678
|
+
|
|
589
679
|
for (const b of buckets || []) {
|
|
590
680
|
const src = b.source === 'cli' ? 'cli' : 'desktop';
|
|
591
681
|
if (sourceFilter !== 'all' && src !== sourceFilter) continue;
|
|
@@ -594,10 +684,10 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
594
684
|
const out = Number(b.output_tokens) || 0;
|
|
595
685
|
const cached = Number(b.cache_read_tokens) || 0;
|
|
596
686
|
const tok = inp + out + cached;
|
|
597
|
-
const usd =
|
|
687
|
+
const usd = computeBucketUsdServer(b, settings);
|
|
598
688
|
const steps = Number(b.steps) || 0;
|
|
599
689
|
const modName = normalizeModelName(b.model);
|
|
600
|
-
const savedUsd = estimateCacheSavedUsd({ model: modName, cacheRead: cached });
|
|
690
|
+
const savedUsd = estimateCacheSavedUsd({ model: modName, cacheRead: cached, ...rateLookupOpts });
|
|
601
691
|
|
|
602
692
|
if (hourlyMap.has(b.bucket_hour_ms)) {
|
|
603
693
|
const slot = hourlyMap.get(b.bucket_hour_ms);
|
|
@@ -713,7 +803,7 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
713
803
|
model,
|
|
714
804
|
usd,
|
|
715
805
|
sharePct: usedUsd > 0 ? roundPct((usd / usedUsd) * 100) : 0,
|
|
716
|
-
isEstimated: !isKnownModelRate(model),
|
|
806
|
+
isEstimated: !isKnownModelRate(model, rateLookupOpts),
|
|
717
807
|
}))
|
|
718
808
|
.sort((a, b) => b.usd - a.usd)
|
|
719
809
|
.slice(0, 4);
|
|
@@ -773,7 +863,7 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
773
863
|
.map(([model, usd]) => ({
|
|
774
864
|
model,
|
|
775
865
|
usd,
|
|
776
|
-
isEstimated: !isKnownModelRate(model),
|
|
866
|
+
isEstimated: !isKnownModelRate(model, rateLookupOpts),
|
|
777
867
|
sharePct: totalUsd > 0 ? Math.round((usd / totalUsd) * 1000) / 10 : 0,
|
|
778
868
|
}))
|
|
779
869
|
.sort((a, b) => b.usd - a.usd);
|
|
@@ -836,6 +926,9 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
836
926
|
timezoneOffsetMin: Number(settings.timezoneOffsetMin) || 480,
|
|
837
927
|
monthlyPlanCost,
|
|
838
928
|
monthlyPlanCurrency,
|
|
929
|
+
pricingSource: settings.pricingCache?.source || 'builtin',
|
|
930
|
+
pricingCount: Object.keys(settings.pricingCache?.rates || {}).length,
|
|
931
|
+
pricingUpdatedAt: settings.pricingCache?.fetchedAt || null,
|
|
839
932
|
},
|
|
840
933
|
cycleInfo: {
|
|
841
934
|
...cycleInfo,
|
|
@@ -986,7 +1079,7 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
986
1079
|
const activeIdSet = new Set((activeMembers || []).map((m) => m.id));
|
|
987
1080
|
const earliestGroupWin = Math.min(todayWin.startMs, weeklyWin.startMs, cycleWin.startMs, win.startMs);
|
|
988
1081
|
const groupRows = await db.all(
|
|
989
|
-
'SELECT member_id, bucket_hour_ms, est_usd FROM usage_buckets WHERE bucket_hour_ms >= ?',
|
|
1082
|
+
'SELECT member_id, bucket_hour_ms, model, input_tokens, output_tokens, cache_read_tokens, est_usd FROM usage_buckets WHERE bucket_hour_ms >= ?',
|
|
990
1083
|
[earliestGroupWin],
|
|
991
1084
|
);
|
|
992
1085
|
let groupTodayUsd = 0;
|
|
@@ -995,7 +1088,7 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
995
1088
|
let groupPeriodUsd = 0;
|
|
996
1089
|
for (const gr of groupRows || []) {
|
|
997
1090
|
if (!activeIdSet.has(gr.member_id)) continue;
|
|
998
|
-
const u =
|
|
1091
|
+
const u = computeBucketUsdServer(gr, settings);
|
|
999
1092
|
if (gr.bucket_hour_ms >= todayWin.startMs) groupTodayUsd += u;
|
|
1000
1093
|
if (gr.bucket_hour_ms >= weeklyWin.startMs) groupWeeklyUsd += u;
|
|
1001
1094
|
if (gr.bucket_hour_ms >= cycleWin.startMs) groupCycleUsd += u;
|
|
@@ -1041,15 +1134,21 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
1041
1134
|
let periodTokens = 0;
|
|
1042
1135
|
let periodSteps = 0;
|
|
1043
1136
|
|
|
1137
|
+
const detailRateOpts = {
|
|
1138
|
+
customPricing: settings.customPricing || null,
|
|
1139
|
+
pricingCache: settings.pricingCache || null,
|
|
1140
|
+
useLocalSources: false,
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1044
1143
|
for (const b of rows || []) {
|
|
1045
1144
|
const inp = Number(b.input_tokens) || 0;
|
|
1046
1145
|
const out = Number(b.output_tokens) || 0;
|
|
1047
1146
|
const cached = Number(b.cache_read_tokens) || 0;
|
|
1048
1147
|
const tok = inp + out + cached;
|
|
1049
|
-
const usd =
|
|
1148
|
+
const usd = computeBucketUsdServer(b, settings);
|
|
1050
1149
|
const steps = Number(b.steps) || 0;
|
|
1051
1150
|
const modName = normalizeModelName(b.model);
|
|
1052
|
-
const savedUsd = estimateCacheSavedUsd({ model: modName, cacheRead: cached });
|
|
1151
|
+
const savedUsd = estimateCacheSavedUsd({ model: modName, cacheRead: cached, ...detailRateOpts });
|
|
1053
1152
|
|
|
1054
1153
|
if (hourlyMap.has(b.bucket_hour_ms)) {
|
|
1055
1154
|
const slot = hourlyMap.get(b.bucket_hour_ms);
|
|
@@ -1100,7 +1199,13 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
1100
1199
|
periodTokens += tok;
|
|
1101
1200
|
periodSteps += steps;
|
|
1102
1201
|
|
|
1103
|
-
const prev = models.get(modName) || {
|
|
1202
|
+
const prev = models.get(modName) || {
|
|
1203
|
+
model: modName,
|
|
1204
|
+
usd: 0,
|
|
1205
|
+
tokens: 0,
|
|
1206
|
+
steps: 0,
|
|
1207
|
+
isEstimated: !isKnownModelRate(modName, detailRateOpts),
|
|
1208
|
+
};
|
|
1104
1209
|
prev.usd = roundUsd(prev.usd + usd);
|
|
1105
1210
|
prev.tokens += tok;
|
|
1106
1211
|
prev.steps += steps;
|
|
@@ -1226,7 +1226,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
|
|
|
1226
1226
|
<div class="panel-card">
|
|
1227
1227
|
<div class="panel-head">
|
|
1228
1228
|
<h2 class="panel-h2" data-i18n="modelTitle">模型使用占比</h2>
|
|
1229
|
-
<span class="panel-caption" data-i18n="modelSub"
|
|
1229
|
+
<span class="panel-caption" id="modelSubCaption" data-i18n="modelSub">三级缓存定价 · 金额仅作参考</span>
|
|
1230
1230
|
</div>
|
|
1231
1231
|
<div class="panel-body">
|
|
1232
1232
|
<div class="model-list" id="modelList"></div>
|
|
@@ -1238,7 +1238,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
|
|
|
1238
1238
|
|
|
1239
1239
|
<footer class="foot">
|
|
1240
1240
|
<span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
|
|
1241
|
-
<span class="mono">agy-family v0.2.
|
|
1241
|
+
<span class="mono">agy-family v0.2.7 · MIT</span>
|
|
1242
1242
|
</footer>
|
|
1243
1243
|
</main>
|
|
1244
1244
|
|
|
@@ -1395,6 +1395,14 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
|
|
|
1395
1395
|
<input id="setViewKey" class="mono" placeholder="留空不加密" />
|
|
1396
1396
|
</div>
|
|
1397
1397
|
|
|
1398
|
+
<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:9px 12px;margin-bottom:10px;border-radius:var(--r-md);background:var(--canvas-soft);border:1px solid var(--hairline);flex-wrap:wrap">
|
|
1399
|
+
<div>
|
|
1400
|
+
<div style="font-size:12px;font-weight:600;color:var(--ink)" data-i18n="pricingTierLbl">三级缓存定价(自定义 → models.dev / LiteLLM 实时同步 → 内置兜底)</div>
|
|
1401
|
+
<div id="pricingCacheStatus" class="mono" style="font-size:11px;color:var(--muted);margin-top:2px">—</div>
|
|
1402
|
+
</div>
|
|
1403
|
+
<button type="button" class="btn btn-sm" id="syncPricingBtn" data-i18n="syncPricingBtn">同步最新定价</button>
|
|
1404
|
+
</div>
|
|
1405
|
+
|
|
1398
1406
|
<div class="sec-h" data-i18n="notifySubhead">群通知(Webhook)</div>
|
|
1399
1407
|
<div class="row-2">
|
|
1400
1408
|
<div class="field">
|
|
@@ -1465,7 +1473,9 @@ const I18N = {
|
|
|
1465
1473
|
membersPanelTitle: '家庭组成员配额与使用占比',
|
|
1466
1474
|
colMember: '家庭成员', colCap: '分配份额与进度', colUsd: '使用占比', colTokens: 'Tokens / 轮次', colMix: '主要模型与端',
|
|
1467
1475
|
hourlyTitle: '最近 24 小时用量占比节律',
|
|
1468
|
-
modelTitle: '模型使用占比', modelSub: '
|
|
1476
|
+
modelTitle: '模型使用占比', modelSub: '三级缓存定价 · 金额仅作参考',
|
|
1477
|
+
pricingTierLbl: '三级缓存定价(自定义 → models.dev / LiteLLM 24h 缓存 → 内置兜底)',
|
|
1478
|
+
syncPricingBtn: '同步最新定价',
|
|
1469
1479
|
privacyNote: '隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。',
|
|
1470
1480
|
ok: '份额内', warn: '略超份额', over: '超出份额', online: '在线', offline: '离线', never: '尚未同步',
|
|
1471
1481
|
adminPanel: '家庭组管理', unlockHead: '解锁家庭组管理控制台',
|
|
@@ -1502,7 +1512,9 @@ const I18N = {
|
|
|
1502
1512
|
membersPanelTitle: 'Family members & quota shares',
|
|
1503
1513
|
colMember: 'Family member', colCap: 'Quota & progress', colUsd: 'Usage share', colTokens: 'Tokens / steps', colMix: 'Primary model & client',
|
|
1504
1514
|
hourlyTitle: '24-hour usage share rhythm',
|
|
1505
|
-
modelTitle: 'Model usage share', modelSub: '
|
|
1515
|
+
modelTitle: 'Model usage share', modelSub: '3-tier pricing · USD as ref',
|
|
1516
|
+
pricingTierLbl: '3-Tier Pricing (Custom → models.dev / LiteLLM 24h cache → Built-in)',
|
|
1517
|
+
syncPricingBtn: 'Sync live pricing',
|
|
1506
1518
|
privacyNote: 'Privacy guarantee: clients read only numeric SQLite stats — zero prompts, code, paths, or Google tokens leave your device.',
|
|
1507
1519
|
ok: 'Balanced', warn: 'Above share', over: 'Over share', online: 'Online', offline: 'Offline', never: 'No sync yet',
|
|
1508
1520
|
adminPanel: 'Family manager', unlockHead: 'Unlock Family Group Console',
|
|
@@ -2220,6 +2232,13 @@ function renderBoard(d) {
|
|
|
2220
2232
|
renderActivityChart(d);
|
|
2221
2233
|
|
|
2222
2234
|
// Model Mix Breakdown using Cursor AI-Timeline Pastel Palette
|
|
2235
|
+
const subCap = document.getElementById('modelSubCaption');
|
|
2236
|
+
if (subCap) {
|
|
2237
|
+
const pSrc = d.rules?.pricingSource || 'builtin';
|
|
2238
|
+
subCap.textContent = lang === 'zh'
|
|
2239
|
+
? '三级定价 (' + pSrc + ') · 金额仅作参考'
|
|
2240
|
+
: '3-tier (' + pSrc + ') · USD as ref';
|
|
2241
|
+
}
|
|
2223
2242
|
const ml = document.getElementById('modelList');
|
|
2224
2243
|
const estTip = lang === 'zh' ? '未知新模型枚举,按保守参考单价估算' : 'Fallback model pricing';
|
|
2225
2244
|
if (!d.modelBreakdown || d.modelBreakdown.length === 0) {
|
|
@@ -2354,6 +2373,16 @@ async function loadAdmin() {
|
|
|
2354
2373
|
document.getElementById('setViewKey').value = data.settings.boardViewKey || '';
|
|
2355
2374
|
document.getElementById('setWebhookType').value = data.settings.webhookType || 'auto';
|
|
2356
2375
|
document.getElementById('setWebhookUrl').value = data.settings.webhookUrl || '';
|
|
2376
|
+
const pc = data.settings.pricingCache;
|
|
2377
|
+
const pcEl = document.getElementById('pricingCacheStatus');
|
|
2378
|
+
if (pcEl) {
|
|
2379
|
+
const cnt = pc && pc.rates ? Object.keys(pc.rates).length : 0;
|
|
2380
|
+
pcEl.textContent = cnt > 0
|
|
2381
|
+
? (lang === 'zh'
|
|
2382
|
+
? '当前源:' + (pc.source || 'models.dev') + ' · 已缓存 ' + cnt + ' 个模型 · 更新于 ' + fmtAgo(pc.fetchedAt)
|
|
2383
|
+
: 'Source: ' + (pc.source || 'models.dev') + ' · ' + cnt + ' models · ' + fmtAgo(pc.fetchedAt))
|
|
2384
|
+
: (lang === 'zh' ? '当前源:内置校准表(点右侧按钮可立即同步 models.dev)' : 'Source: built-in calibrated table');
|
|
2385
|
+
}
|
|
2357
2386
|
if (pendingAdminTab) {
|
|
2358
2387
|
activateAdminTab(pendingAdminTab);
|
|
2359
2388
|
pendingAdminTab = '';
|
|
@@ -2870,6 +2899,26 @@ document.getElementById('saveSettingsBtn').addEventListener('click', async () =>
|
|
|
2870
2899
|
msg.textContent = e.message;
|
|
2871
2900
|
}
|
|
2872
2901
|
});
|
|
2902
|
+
document.getElementById('syncPricingBtn')?.addEventListener('click', async () => {
|
|
2903
|
+
const btn = document.getElementById('syncPricingBtn');
|
|
2904
|
+
if (!btn) return;
|
|
2905
|
+
btn.disabled = true;
|
|
2906
|
+
try {
|
|
2907
|
+
const res = await adminReq('/api/admin/pricing-sync', { method: 'POST', body: JSON.stringify({ source: 'auto' }) });
|
|
2908
|
+
showToast(
|
|
2909
|
+
lang === 'zh'
|
|
2910
|
+
? '已从 ' + res.source + ' 同步 ' + res.count + ' 个模型最新单价'
|
|
2911
|
+
: 'Synced ' + res.count + ' model rates from ' + res.source,
|
|
2912
|
+
);
|
|
2913
|
+
await loadAdmin();
|
|
2914
|
+
await fetchBoard();
|
|
2915
|
+
} catch (e) {
|
|
2916
|
+
showToast(e.message, 'err');
|
|
2917
|
+
} finally {
|
|
2918
|
+
btn.disabled = false;
|
|
2919
|
+
}
|
|
2920
|
+
});
|
|
2921
|
+
|
|
2873
2922
|
document.getElementById('testWebhookBtn').addEventListener('click', async () => {
|
|
2874
2923
|
const res = await adminReq('/api/admin/webhook-test', { method: 'POST' });
|
|
2875
2924
|
const msg = document.getElementById('settingsMsg');
|
|
@@ -5,7 +5,7 @@ import { createServer } from 'node:http';
|
|
|
5
5
|
import { resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { randomToken } from '../../server-core/src/crypto.mjs';
|
|
8
|
-
import { checkOfflineMembersAndAlert, createApp } from '../../server-core/src/index.mjs';
|
|
8
|
+
import { checkOfflineMembersAndAlert, createApp, syncServerPricingCache } from '../../server-core/src/index.mjs';
|
|
9
9
|
import { ensureSchema } from '../../server-core/src/schema.mjs';
|
|
10
10
|
import { createSqliteAdapter } from './db-sqlite.mjs';
|
|
11
11
|
|
|
@@ -90,10 +90,20 @@ export function startNodeServer({
|
|
|
90
90
|
|
|
91
91
|
let offlineCheckTimer = null;
|
|
92
92
|
if (!disableBackgroundJobs) {
|
|
93
|
+
setTimeout(async () => {
|
|
94
|
+
try {
|
|
95
|
+
await ensureSchema(db);
|
|
96
|
+
await syncServerPricingCache(db, { force: false });
|
|
97
|
+
} catch {
|
|
98
|
+
// Ignore startup pricing sync errors cleanly.
|
|
99
|
+
}
|
|
100
|
+
}, 2_000).unref?.();
|
|
101
|
+
|
|
93
102
|
offlineCheckTimer = setInterval(async () => {
|
|
94
103
|
try {
|
|
95
104
|
await ensureSchema(db);
|
|
96
105
|
await checkOfflineMembersAndAlert(db, { envDefaults: mergedDefaults });
|
|
106
|
+
await syncServerPricingCache(db, { force: false });
|
|
97
107
|
} catch {
|
|
98
108
|
// Ignore transient offline-check failures in background loop.
|
|
99
109
|
}
|