ktg-plugin-marketplace/plugins/ms-ai-architect/scripts/kb-update/lib/cost-estimat.mjs
Kjell Tore Guttormsen f2b76b6d8e feat(ms-ai-architect): add lib/cost-estimat heuristic for API-key budget [skip-docs]
Pure auth-mode-aware cost estimator for v1.12.0 cron pre-flight.

Heuristic: critical+high files only (medium/low excluded per brief);
3000 input + 1500 output tokens per file at Sonnet pricing
($3/M in, $15/M out).

Auth-mode behavior:
- api-key:   numeric usd, kvote_warn off  (subject to dollar-cap)
- long-oauth, subscription-browser-only:
             usd null, kvote_warn on      (quota, no dollar billing)
- unauthenticated/missing: best-effort api-key estimate

11/11 tests pass; covers both billing modes plus token-math
invariance across auth-mode (auth only affects dollar-field, not tokens).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 10:34:37 +02:00

36 lines
1.5 KiB
JavaScript

// cost-estimat.mjs — Heuristic cost-estimate for KB-update runs.
// Pure function. Auth-mode-aware: api-key returns numeric USD,
// subscription modes return null USD + kvote_warn flag.
// Zero dependencies.
const AVG_INPUT_TOKENS_PER_FILE = 3000;
const AVG_OUTPUT_TOKENS_PER_FILE = 1500;
const SONNET_INPUT_USD_PER_M = 3.0;
const SONNET_OUTPUT_USD_PER_M = 15.0;
const SUBSCRIPTION_MODES = new Set(['long-oauth', 'subscription-browser-only']);
/**
* Estimate cost (and quota-warn flag) for a run of N files at given priorities.
* Filters to critical + high only (medium/low excluded per brief).
*
* @param {object} priorities — { critical, high, medium, low } file counts
* @param {object} [opts]
* @param {string} [opts.authMode] — 'api-key' | 'long-oauth' | 'subscription-browser-only' | 'unauthenticated'
* @returns {{tokens_input: number, tokens_output: number, usd: number|null, kvote_warn: boolean}}
*/
export function estimateCost(priorities = {}, opts = {}) {
const authMode = opts.authMode ?? 'api-key';
const fileCount = (priorities.critical ?? 0) + (priorities.high ?? 0);
const tokens_input = fileCount * AVG_INPUT_TOKENS_PER_FILE;
const tokens_output = fileCount * AVG_OUTPUT_TOKENS_PER_FILE;
if (SUBSCRIPTION_MODES.has(authMode)) {
return { tokens_input, tokens_output, usd: null, kvote_warn: true };
}
const usd =
(tokens_input / 1_000_000) * SONNET_INPUT_USD_PER_M +
(tokens_output / 1_000_000) * SONNET_OUTPUT_USD_PER_M;
return { tokens_input, tokens_output, usd, kvote_warn: false };
}