agy-family 0.2.5 → 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/protobuf.mjs +51 -0
- package/packages/core/src/sync.mjs +2 -2
- package/packages/server-core/src/index.mjs +33 -11
- package/packages/server-core/src/schema.mjs +2 -0
- package/packages/server-core/src/stats.mjs +128 -20
- 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;
|
|
@@ -3,12 +3,52 @@
|
|
|
3
3
|
// Never inspects or retains prompts, replies, file paths, or account identifiers.
|
|
4
4
|
|
|
5
5
|
export const MODEL_ENUM_MAP = Object.freeze({
|
|
6
|
+
// Gemini 4 Neon (MODEL_PLACEHOLDER_M532..M537)
|
|
7
|
+
1532: 'Gemini 4 Neon',
|
|
8
|
+
1533: 'Gemini 4 Neon',
|
|
9
|
+
1534: 'Gemini 4 Neon',
|
|
6
10
|
1535: 'Gemini 4 Neon',
|
|
11
|
+
1537: 'Gemini 4 Neon',
|
|
12
|
+
// Gemini 4 Hydrogen (MODEL_PLACEHOLDER_M525..M531, M578, M669)
|
|
13
|
+
1525: 'Gemini 4 Hydrogen',
|
|
14
|
+
1526: 'Gemini 4 Hydrogen',
|
|
15
|
+
1527: 'Gemini 4 Hydrogen',
|
|
16
|
+
1528: 'Gemini 4 Hydrogen',
|
|
7
17
|
1530: 'Gemini 4 Hydrogen',
|
|
18
|
+
1531: 'Gemini 4 Hydrogen',
|
|
19
|
+
1578: 'Gemini 4 Hydrogen',
|
|
20
|
+
1669: 'Gemini 4 Hydrogen',
|
|
21
|
+
// Gemini 4 Carbon (MODEL_PLACEHOLDER_M427, M437, M438, M667)
|
|
8
22
|
1427: 'Gemini 4 Carbon',
|
|
23
|
+
1437: 'Gemini 4 Carbon',
|
|
24
|
+
1438: 'Gemini 4 Carbon',
|
|
25
|
+
1667: 'Gemini 4 Carbon',
|
|
26
|
+
// Gemini 4 Argon (MODEL_PLACEHOLDER_M417..M419, M681)
|
|
9
27
|
1417: 'Gemini 4 Argon',
|
|
28
|
+
1418: 'Gemini 4 Argon',
|
|
29
|
+
1419: 'Gemini 4 Argon',
|
|
30
|
+
1681: 'Gemini 4 Argon',
|
|
31
|
+
// Claude 5.5 & 4.x (MODEL_PLACEHOLDER_M400..M405, legacy M26/M35/M37)
|
|
32
|
+
1400: 'Claude Opus 5.5',
|
|
33
|
+
1401: 'Claude Opus 5.5',
|
|
34
|
+
1402: 'Claude Opus 5.5',
|
|
35
|
+
1403: 'Claude Sonnet 5.5',
|
|
36
|
+
1404: 'Claude Sonnet 5.5',
|
|
37
|
+
1405: 'Claude Sonnet 5.5',
|
|
38
|
+
1026: 'Claude Opus 4.6',
|
|
39
|
+
1035: 'Claude Sonnet 4.6',
|
|
40
|
+
1037: 'Claude Opus 4.5',
|
|
41
|
+
// Gemini 3.8 / 3.5 / 3.1 / 3 Flash
|
|
10
42
|
1318: 'Gemini 3.8 Flash',
|
|
11
43
|
1319: 'Gemini 3.8 Flash',
|
|
44
|
+
1320: 'Gemini 3.8 Flash',
|
|
45
|
+
1322: 'Gemini 3.8 Flash',
|
|
46
|
+
1198: 'Gemini 3.5 Flash Lite',
|
|
47
|
+
1050: 'Gemini 3.1 Flash Lite',
|
|
48
|
+
1028: 'Gemini 3.5 Flash Lite',
|
|
49
|
+
1021: 'Gemini 3.1 Flash Image',
|
|
50
|
+
1019: 'Gemini 3.5 Flash Lite',
|
|
51
|
+
1018: 'Gemini 3 Flash',
|
|
12
52
|
});
|
|
13
53
|
|
|
14
54
|
export function resolveModelEnum(enumId) {
|
|
@@ -16,6 +56,17 @@ export function resolveModelEnum(enumId) {
|
|
|
16
56
|
return MODEL_ENUM_MAP[enumId] || `Model #${enumId}`;
|
|
17
57
|
}
|
|
18
58
|
|
|
59
|
+
export function normalizeModelName(rawModel) {
|
|
60
|
+
const s = String(rawModel || '').trim();
|
|
61
|
+
if (!s) return 'Unknown';
|
|
62
|
+
const m = s.match(/^Model\s*#(\d+)$/i) || s.match(/^MODEL_PLACEHOLDER_M(\d+)$/i);
|
|
63
|
+
if (m) {
|
|
64
|
+
const num = /^MODEL_PLACEHOLDER_M/i.test(s) ? 1000 + Number(m[1]) : Number(m[1]);
|
|
65
|
+
if (MODEL_ENUM_MAP[num]) return MODEL_ENUM_MAP[num];
|
|
66
|
+
}
|
|
67
|
+
return s.slice(0, 64);
|
|
68
|
+
}
|
|
69
|
+
|
|
19
70
|
export function decodePbFields(buf) {
|
|
20
71
|
const b = buf instanceof Uint8Array ? buf : new Uint8Array(buf || []);
|
|
21
72
|
let offset = 0;
|
|
@@ -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,
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { encodeInviteUri } from '../../core/src/invite.mjs';
|
|
5
5
|
import { estimateUsageUsd } from '../../core/src/pricing.mjs';
|
|
6
|
+
import { normalizeModelName } from '../../core/src/protobuf.mjs';
|
|
6
7
|
import { randomId, randomToken, sha256Hex, timingSafeEqualStr } from './crypto.mjs';
|
|
7
8
|
import { ensureSchema, MAX_FAMILY_MEMBERS } from './schema.mjs';
|
|
8
9
|
import {
|
|
@@ -17,11 +18,12 @@ import {
|
|
|
17
18
|
loadSettings,
|
|
18
19
|
resolveFamilyQuotas,
|
|
19
20
|
roundUsd,
|
|
21
|
+
syncServerPricingCache,
|
|
20
22
|
} from './stats.mjs';
|
|
21
23
|
import { renderDashboardHtml } from './ui.mjs';
|
|
22
24
|
import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
|
|
23
25
|
|
|
24
|
-
export const SERVER_VERSION = '0.2.
|
|
26
|
+
export const SERVER_VERSION = '0.2.7';
|
|
25
27
|
const MAX_BUCKETS_PER_SYNC = 1000;
|
|
26
28
|
const MAX_DEVICES_PER_MEMBER = 8;
|
|
27
29
|
const MAX_TOKENS_PER_BUCKET = 500_000_000;
|
|
@@ -40,6 +42,7 @@ const ALLOWED_SETTINGS_KEYS = new Set([
|
|
|
40
42
|
'poolTotalCredits',
|
|
41
43
|
'monthlyPlanCost',
|
|
42
44
|
'monthlyPlanCurrency',
|
|
45
|
+
'customPricing',
|
|
43
46
|
'webhookUrl',
|
|
44
47
|
'webhookType',
|
|
45
48
|
'boardViewKey',
|
|
@@ -178,15 +181,14 @@ const UPSERT_BUCKET_SQL = `INSERT INTO usage_buckets
|
|
|
178
181
|
cache_read_tokens = MAX(usage_buckets.cache_read_tokens, excluded.cache_read_tokens),
|
|
179
182
|
thinking_tokens = MAX(usage_buckets.thinking_tokens, excluded.thinking_tokens),
|
|
180
183
|
steps = MAX(usage_buckets.steps, excluded.steps),
|
|
181
|
-
est_usd =
|
|
184
|
+
est_usd = excluded.est_usd,
|
|
182
185
|
updated_at = excluded.updated_at
|
|
183
186
|
WHERE
|
|
184
187
|
excluded.input_tokens > usage_buckets.input_tokens OR
|
|
185
188
|
excluded.output_tokens > usage_buckets.output_tokens OR
|
|
186
189
|
excluded.cache_read_tokens > usage_buckets.cache_read_tokens OR
|
|
187
190
|
excluded.thinking_tokens > usage_buckets.thinking_tokens OR
|
|
188
|
-
excluded.steps > usage_buckets.steps
|
|
189
|
-
excluded.est_usd > usage_buckets.est_usd`;
|
|
191
|
+
excluded.steps > usage_buckets.steps`;
|
|
190
192
|
|
|
191
193
|
const UPSERT_ODOMETER_SQL = `INSERT INTO device_odometers
|
|
192
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)
|
|
@@ -445,6 +447,7 @@ export function createApp({
|
|
|
445
447
|
);
|
|
446
448
|
}
|
|
447
449
|
|
|
450
|
+
const settings = await loadSettings(db, envDefaults);
|
|
448
451
|
const maxAllowedTs = now + 24 * 60 * 60 * 1000;
|
|
449
452
|
const minAllowedTs = now - 400 * 24 * 60 * 60 * 1000;
|
|
450
453
|
const normalizedBuckets = [];
|
|
@@ -457,7 +460,7 @@ export function createApp({
|
|
|
457
460
|
if (!Number.isFinite(hourMs) || hourMs < minAllowedTs || hourMs > maxAllowedTs) continue;
|
|
458
461
|
const normalizedHour = Math.floor(hourMs / 3_600_000) * 3_600_000;
|
|
459
462
|
const source = b.source === 'cli' ? 'cli' : 'desktop';
|
|
460
|
-
const model =
|
|
463
|
+
const model = normalizeModelName(b.model);
|
|
461
464
|
const inputTokens = Math.min(MAX_TOKENS_PER_BUCKET, Math.max(0, Math.floor(Number(b.inputTokens) || 0)));
|
|
462
465
|
const outputTokens = Math.min(MAX_TOKENS_PER_BUCKET, Math.max(0, Math.floor(Number(b.outputTokens) || 0)));
|
|
463
466
|
const cacheReadTokens = Math.min(MAX_TOKENS_PER_BUCKET * 4, Math.max(0, Math.floor(Number(b.cacheReadTokens) || 0)));
|
|
@@ -465,13 +468,16 @@ export function createApp({
|
|
|
465
468
|
const steps = Math.min(MAX_STEPS_PER_BUCKET, Math.max(0, Math.floor(Number(b.steps) || 0)));
|
|
466
469
|
if (inputTokens + outputTokens + cacheReadTokens + steps === 0) continue;
|
|
467
470
|
|
|
468
|
-
// Server recomputes est_usd
|
|
471
|
+
// Server recomputes est_usd via 3-Tier Pricing Engine (custom -> models.dev/litellm cache -> builtin)
|
|
469
472
|
// so clients cannot spoof artificially low USD totals.
|
|
470
473
|
const serverEstUsd = estimateUsageUsd({
|
|
471
474
|
model,
|
|
472
475
|
input: inputTokens,
|
|
473
476
|
output: outputTokens,
|
|
474
477
|
cacheRead: cacheReadTokens,
|
|
478
|
+
customPricing: settings.customPricing || null,
|
|
479
|
+
pricingCache: settings.pricingCache || null,
|
|
480
|
+
useLocalSources: false,
|
|
475
481
|
fallback: true,
|
|
476
482
|
});
|
|
477
483
|
const estUsd = serverEstUsd > 0 ? serverEstUsd : Math.max(0, roundUsd(b.estUsd || 0));
|
|
@@ -511,13 +517,23 @@ export function createApp({
|
|
|
511
517
|
const stepDrop = nb.steps < Number(ex.steps || 0);
|
|
512
518
|
const inDrop = nb.inputTokens < Number(ex.input_tokens || 0);
|
|
513
519
|
const outDrop = nb.outputTokens < Number(ex.output_tokens || 0);
|
|
514
|
-
const
|
|
515
|
-
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
|
+
});
|
|
516
532
|
rollbackFindings.push({
|
|
517
533
|
model: nb.model,
|
|
518
534
|
prevSteps: Number(ex.steps || 0),
|
|
519
535
|
nextSteps: nb.steps,
|
|
520
|
-
prevUsd
|
|
536
|
+
prevUsd,
|
|
521
537
|
nextUsd: nb.estUsd,
|
|
522
538
|
});
|
|
523
539
|
}
|
|
@@ -617,7 +633,6 @@ export function createApp({
|
|
|
617
633
|
await runBatchedWrites(db, writeStmts);
|
|
618
634
|
const accepted = normalizedBuckets.length;
|
|
619
635
|
|
|
620
|
-
const settings = await loadSettings(db, envDefaults);
|
|
621
636
|
const capSnap = await computeMemberCapsSnapshot(db, member, settings, now);
|
|
622
637
|
|
|
623
638
|
// Fire deduped integrity webhook alerts
|
|
@@ -1103,6 +1118,13 @@ export function createApp({
|
|
|
1103
1118
|
return adminJsonRes({ ok: true, cleared: true });
|
|
1104
1119
|
}
|
|
1105
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
|
+
|
|
1106
1128
|
if (request.method === 'POST' && path === '/api/admin/webhook-test') {
|
|
1107
1129
|
const settings = await loadSettings(db, envDefaults);
|
|
1108
1130
|
const res = await dispatchWebhook({
|
|
@@ -1127,4 +1149,4 @@ export function createApp({
|
|
|
1127
1149
|
};
|
|
1128
1150
|
}
|
|
1129
1151
|
|
|
1130
|
-
export { checkOfflineMembersAndAlert, evaluateQuotaProgress, getPeriodWindow, resolveFamilyQuotas };
|
|
1152
|
+
export { checkOfflineMembersAndAlert, evaluateQuotaProgress, getPeriodWindow, resolveFamilyQuotas, syncServerPricingCache };
|
|
@@ -1,13 +1,97 @@
|
|
|
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';
|
|
12
|
+
import { normalizeModelName } from '../../core/src/protobuf.mjs';
|
|
5
13
|
import { DEFAULT_SETTINGS, MAX_FAMILY_MEMBERS } from './schema.mjs';
|
|
6
14
|
import { sendDedupedAlert } from './webhooks.mjs';
|
|
7
15
|
|
|
8
16
|
const HOUR_MS = 60 * 60 * 1000;
|
|
9
17
|
const DAY_MS = 24 * HOUR_MS;
|
|
10
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
|
+
|
|
11
95
|
export function roundUsd(n) {
|
|
12
96
|
return Math.round((Number(n) || 0) * 10_000) / 10_000;
|
|
13
97
|
}
|
|
@@ -300,7 +384,7 @@ export async function computeMemberCapsSnapshot(db, member, settings, now = Date
|
|
|
300
384
|
|
|
301
385
|
const earliest = Math.min(dailyWin.startMs, weeklyWin.startMs, cycleWin.startMs);
|
|
302
386
|
const rows = await db.all(
|
|
303
|
-
'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 >= ?',
|
|
304
388
|
[member.id, earliest],
|
|
305
389
|
);
|
|
306
390
|
|
|
@@ -308,7 +392,7 @@ export async function computeMemberCapsSnapshot(db, member, settings, now = Date
|
|
|
308
392
|
let weeklyUsedUsd = 0;
|
|
309
393
|
let cycleUsedUsd = 0;
|
|
310
394
|
for (const r of rows || []) {
|
|
311
|
-
const usd =
|
|
395
|
+
const usd = computeBucketUsdServer(r, settings);
|
|
312
396
|
if (r.bucket_hour_ms >= dailyWin.startMs) dailyUsedUsd += usd;
|
|
313
397
|
if (r.bucket_hour_ms >= weeklyWin.startMs) weeklyUsedUsd += usd;
|
|
314
398
|
if (r.bucket_hour_ms >= cycleWin.startMs) cycleUsedUsd += usd;
|
|
@@ -406,20 +490,21 @@ export async function computeCreditsReconciliation(db, members, settings, cycleI
|
|
|
406
490
|
|
|
407
491
|
const winStartHour = Math.floor(previous.recorded_at / HOUR_MS) * HOUR_MS;
|
|
408
492
|
const winEndHour = Math.floor(latest.recorded_at / HOUR_MS) * HOUR_MS + HOUR_MS;
|
|
409
|
-
const
|
|
410
|
-
'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 <= ?',
|
|
411
495
|
[winStartHour, winEndHour],
|
|
412
496
|
);
|
|
413
497
|
|
|
414
498
|
let reportedUsd = 0;
|
|
415
499
|
let reportedSteps = 0;
|
|
416
500
|
const reportedByMember = new Map();
|
|
417
|
-
for (const r of
|
|
418
|
-
const usd =
|
|
501
|
+
for (const r of rawWinBuckets || []) {
|
|
502
|
+
const usd = computeBucketUsdServer(r, settings);
|
|
419
503
|
const steps = Number(r.steps) || 0;
|
|
420
504
|
reportedUsd += usd;
|
|
421
505
|
reportedSteps += steps;
|
|
422
|
-
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 });
|
|
423
508
|
}
|
|
424
509
|
reportedUsd = roundUsd(reportedUsd);
|
|
425
510
|
|
|
@@ -585,6 +670,12 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
585
670
|
let totalCliUsd = 0;
|
|
586
671
|
let cycleUsedUsd = 0;
|
|
587
672
|
|
|
673
|
+
const rateLookupOpts = {
|
|
674
|
+
customPricing: settings.customPricing || null,
|
|
675
|
+
pricingCache: settings.pricingCache || null,
|
|
676
|
+
useLocalSources: false,
|
|
677
|
+
};
|
|
678
|
+
|
|
588
679
|
for (const b of buckets || []) {
|
|
589
680
|
const src = b.source === 'cli' ? 'cli' : 'desktop';
|
|
590
681
|
if (sourceFilter !== 'all' && src !== sourceFilter) continue;
|
|
@@ -593,9 +684,10 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
593
684
|
const out = Number(b.output_tokens) || 0;
|
|
594
685
|
const cached = Number(b.cache_read_tokens) || 0;
|
|
595
686
|
const tok = inp + out + cached;
|
|
596
|
-
const usd =
|
|
687
|
+
const usd = computeBucketUsdServer(b, settings);
|
|
597
688
|
const steps = Number(b.steps) || 0;
|
|
598
|
-
const
|
|
689
|
+
const modName = normalizeModelName(b.model);
|
|
690
|
+
const savedUsd = estimateCacheSavedUsd({ model: modName, cacheRead: cached, ...rateLookupOpts });
|
|
599
691
|
|
|
600
692
|
if (hourlyMap.has(b.bucket_hour_ms)) {
|
|
601
693
|
const slot = hourlyMap.get(b.bucket_hour_ms);
|
|
@@ -642,8 +734,8 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
642
734
|
totalDesktopUsd += usd;
|
|
643
735
|
}
|
|
644
736
|
|
|
645
|
-
entry.models.set(
|
|
646
|
-
globalModels.set(
|
|
737
|
+
entry.models.set(modName, roundUsd((entry.models.get(modName) || 0) + usd));
|
|
738
|
+
globalModels.set(modName, roundUsd((globalModels.get(modName) || 0) + usd));
|
|
647
739
|
|
|
648
740
|
totalUsd += usd;
|
|
649
741
|
totalInputTokens += inp;
|
|
@@ -711,7 +803,7 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
711
803
|
model,
|
|
712
804
|
usd,
|
|
713
805
|
sharePct: usedUsd > 0 ? roundPct((usd / usedUsd) * 100) : 0,
|
|
714
|
-
isEstimated: !isKnownModelRate(model),
|
|
806
|
+
isEstimated: !isKnownModelRate(model, rateLookupOpts),
|
|
715
807
|
}))
|
|
716
808
|
.sort((a, b) => b.usd - a.usd)
|
|
717
809
|
.slice(0, 4);
|
|
@@ -771,7 +863,7 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
771
863
|
.map(([model, usd]) => ({
|
|
772
864
|
model,
|
|
773
865
|
usd,
|
|
774
|
-
isEstimated: !isKnownModelRate(model),
|
|
866
|
+
isEstimated: !isKnownModelRate(model, rateLookupOpts),
|
|
775
867
|
sharePct: totalUsd > 0 ? Math.round((usd / totalUsd) * 1000) / 10 : 0,
|
|
776
868
|
}))
|
|
777
869
|
.sort((a, b) => b.usd - a.usd);
|
|
@@ -834,6 +926,9 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
|
|
|
834
926
|
timezoneOffsetMin: Number(settings.timezoneOffsetMin) || 480,
|
|
835
927
|
monthlyPlanCost,
|
|
836
928
|
monthlyPlanCurrency,
|
|
929
|
+
pricingSource: settings.pricingCache?.source || 'builtin',
|
|
930
|
+
pricingCount: Object.keys(settings.pricingCache?.rates || {}).length,
|
|
931
|
+
pricingUpdatedAt: settings.pricingCache?.fetchedAt || null,
|
|
837
932
|
},
|
|
838
933
|
cycleInfo: {
|
|
839
934
|
...cycleInfo,
|
|
@@ -984,7 +1079,7 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
984
1079
|
const activeIdSet = new Set((activeMembers || []).map((m) => m.id));
|
|
985
1080
|
const earliestGroupWin = Math.min(todayWin.startMs, weeklyWin.startMs, cycleWin.startMs, win.startMs);
|
|
986
1081
|
const groupRows = await db.all(
|
|
987
|
-
'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 >= ?',
|
|
988
1083
|
[earliestGroupWin],
|
|
989
1084
|
);
|
|
990
1085
|
let groupTodayUsd = 0;
|
|
@@ -993,7 +1088,7 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
993
1088
|
let groupPeriodUsd = 0;
|
|
994
1089
|
for (const gr of groupRows || []) {
|
|
995
1090
|
if (!activeIdSet.has(gr.member_id)) continue;
|
|
996
|
-
const u =
|
|
1091
|
+
const u = computeBucketUsdServer(gr, settings);
|
|
997
1092
|
if (gr.bucket_hour_ms >= todayWin.startMs) groupTodayUsd += u;
|
|
998
1093
|
if (gr.bucket_hour_ms >= weeklyWin.startMs) groupWeeklyUsd += u;
|
|
999
1094
|
if (gr.bucket_hour_ms >= cycleWin.startMs) groupCycleUsd += u;
|
|
@@ -1039,14 +1134,21 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
1039
1134
|
let periodTokens = 0;
|
|
1040
1135
|
let periodSteps = 0;
|
|
1041
1136
|
|
|
1137
|
+
const detailRateOpts = {
|
|
1138
|
+
customPricing: settings.customPricing || null,
|
|
1139
|
+
pricingCache: settings.pricingCache || null,
|
|
1140
|
+
useLocalSources: false,
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1042
1143
|
for (const b of rows || []) {
|
|
1043
1144
|
const inp = Number(b.input_tokens) || 0;
|
|
1044
1145
|
const out = Number(b.output_tokens) || 0;
|
|
1045
1146
|
const cached = Number(b.cache_read_tokens) || 0;
|
|
1046
1147
|
const tok = inp + out + cached;
|
|
1047
|
-
const usd =
|
|
1148
|
+
const usd = computeBucketUsdServer(b, settings);
|
|
1048
1149
|
const steps = Number(b.steps) || 0;
|
|
1049
|
-
const
|
|
1150
|
+
const modName = normalizeModelName(b.model);
|
|
1151
|
+
const savedUsd = estimateCacheSavedUsd({ model: modName, cacheRead: cached, ...detailRateOpts });
|
|
1050
1152
|
|
|
1051
1153
|
if (hourlyMap.has(b.bucket_hour_ms)) {
|
|
1052
1154
|
const slot = hourlyMap.get(b.bucket_hour_ms);
|
|
@@ -1097,11 +1199,17 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
|
|
|
1097
1199
|
periodTokens += tok;
|
|
1098
1200
|
periodSteps += steps;
|
|
1099
1201
|
|
|
1100
|
-
const prev = models.get(
|
|
1202
|
+
const prev = models.get(modName) || {
|
|
1203
|
+
model: modName,
|
|
1204
|
+
usd: 0,
|
|
1205
|
+
tokens: 0,
|
|
1206
|
+
steps: 0,
|
|
1207
|
+
isEstimated: !isKnownModelRate(modName, detailRateOpts),
|
|
1208
|
+
};
|
|
1101
1209
|
prev.usd = roundUsd(prev.usd + usd);
|
|
1102
1210
|
prev.tokens += tok;
|
|
1103
1211
|
prev.steps += steps;
|
|
1104
|
-
models.set(
|
|
1212
|
+
models.set(modName, prev);
|
|
1105
1213
|
}
|
|
1106
1214
|
|
|
1107
1215
|
const modelBreakdown = Array.from(models.values())
|
|
@@ -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
|
}
|