Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

27.2 KB
Raw Blame
/**
 * Per-model API billing rates for informational cost estimates. Subscription
 * plans and local providers do not expose a bill per benchmark run, so these
 * rates answer "what would the recorded tokens cost under API billing," never
 * the actual subscription allowance consumed or a local inference bill.
 *
 * Rates are USD per 1M tokens. Standard input/output come from the table below;
 * the prompt-cache tiers are derived from the input rate by the multipliers in
 * `CACHE_MULTIPLIERS` (every vendor publishes caching as a fixed ratio of the
 * base input rate, so one multiplier per family beats 4 hand-maintained numbers
 * per model, except Grok rows whose cached-input price is not that ratio).
 * Batch discounts are still ignored. Grok's ≥200k doubling is NOT a second
 * rate in this table: it is a per-request subset the usage report prices once
 * more at these base rates (see GROK_LONG_CONTEXT_PROMPT_TOKENS). The UI
 * discloses the approximation.
 *
 * Cache tiers are NOT a rounding detail: for agentic CLI use, cache reads are
 * >90% of input volume, so pricing them at the standard input rate (or, as
 * PortOS did before #3124, not counting the tokens at all) is the single largest
 * source of error in the estimate. Verified against the official pricing pages
 * on PRICING_AS_OF, with newer model-specific verification noted below:
 *   - https://platform.claude.com/docs/en/about-claude/pricing
 *   - https://developers.openai.com/api/docs/pricing
 *   - https://docs.x.ai/docs/pricing
 *   - https://ai.google.dev/gemini-api/docs/pricing
 *   - https://inference-docs.cerebras.ai/models/openai-oss
 *
 * Model ids arrive in many shapes (full ids, CLI sentinels like `opus`, the
 * `*-configured-default` sentinels from providerModels.js, Bedrock-prefixed
 * ids), so resolution is exact-id first, then ordered family regexes, then a
 * per-provider default, then a generic fallback — `matched` reports which tier
 * answered so the UI can flag approximate rows.
 */

import { isLoopbackEndpoint } from './localEndpoint.js';

export const PRICING_AS_OF = '2026-09-01';

// Newer model launch rates are tracked separately so the baseline date above
// does not imply that every vendor's pricing was re-verified on that date.
const MODEL_RATE_AS_OF = Object.freeze({
  'claude-haiku-5-5': '2026-10-07',
  'claude-sonnet-5-5': '2026-10-07',
  'claude-opus-5-5': '2026-09-23',
  'gemini-4-argon': '2026-10-17',
  'gpt-6.1-sol': '2026-09-29',
  'gpt-6-sol': '2026-09-22',
  'gpt-6-luna': '2026-09-22',
  'gpt-5.6-sol': '2026-09-22',
  'gpt-5.6-luna': '2026-09-22',
  // https://docs.x.ai/docs/models — text cache rates and Imagine headline tiers.
  'grok-4.7': '2026-10-24',
  'grok-4.6': '2026-10-24',
  'grok-4.5': '2026-10-24',
  'grok-4.3': '2026-10-24',
  'grok-4.20': '2026-10-24',
  'grok-build-0.1': '2026-10-24',
  'grok-imagine-image': '2026-10-24',
  'grok-imagine-image-2.0': '2026-10-24',
  'grok-imagine-image-quality': '2026-10-24',
  'grok-imagine-video': '2026-10-24',
  'grok-imagine-video-1.5': '2026-10-24',
  'grok-imagine-video-1.5-lite': '2026-10-24',
});

/**
 * xAI doubles every token price, including cached input, on a request whose
 * prompt reaches this size. The doubling applies to that request only — a
 * day's summed tokens are not a prompt — so the rate table stays at the short
 * tier and the usage report adds one extra base-rate charge for the subset.
 */
export const GROK_LONG_CONTEXT_PROMPT_TOKENS = 200_000;

/** Docs' recommended Imagine models, and what the Grok CLI bills when it names none. */
export const GROK_IMAGINE_IMAGE_MODEL = 'grok-imagine-image-2.0';
export const GROK_IMAGINE_VIDEO_MODEL = 'grok-imagine-video-1.5';

/** Recommended Antigravity image model. */
export const AGY_IMAGEN_IMAGE_MODEL = 'imagen-3.0-generate-002';

/**
 * Headline / lowest-resolution Imagine rates (USD). Higher resolutions cost
 * more; PortOS does not request a resolution, so the estimate is this tier.
 * Longest id first: `grok-imagine-image` is a prefix of the 2.0 and quality ids.
 */
const GROK_IMAGINE_RATES = Object.freeze([
  { id: 'grok-imagine-video-1.5-lite', kind: 'video', perSecond: 0.02, perInputImage: 0.01 },
  { id: 'grok-imagine-image-quality', kind: 'image', perImage: 0.05, perInputImage: 0.01 },
  { id: 'grok-imagine-image-2.0', kind: 'image', perImage: 0.04, perInputImage: 0.01 },
  { id: 'grok-imagine-video-1.5', kind: 'video', perSecond: 0.08, perInputImage: 0.01 },
  { id: 'grok-imagine-image', kind: 'image', perImage: 0.02, perInputImage: 0.002 },
  { id: 'grok-imagine-video', kind: 'video', perSecond: 0.05, perInputImage: 0.002 },
].sort((a, b) => b.id.length - a.id.length));

/** The Imagine rate row a model id names, or null. Longest published id wins. */
function grokImagineRate(model) {
  const id = String(model || '').trim().toLowerCase();
  if (!id.includes('grok-imagine-')) return null;
  return GROK_IMAGINE_RATES.find((row) => id === row.id || id.includes(row.id)) || null;
}

/**
 * Google Imagen 3 rates (USD). Published rate: $0.030 per image.
 * https://ai.google.dev/gemini-api/docs/pricing
 */
const AGY_IMAGEN_RATES = Object.freeze([
  { id: 'imagen-3.0-generate-002', kind: 'image', perImage: 0.03, perInputImage: 0 },
  { id: 'imagen-3.0-fast-generate-001', kind: 'image', perImage: 0.03, perInputImage: 0 },
  { id: 'imagen-3.0-generate', kind: 'image', perImage: 0.03, perInputImage: 0 },
  { id: 'imagen-3.0', kind: 'image', perImage: 0.03, perInputImage: 0 },
  { id: 'imagen-3-fast', kind: 'image', perImage: 0.03, perInputImage: 0 },
  { id: 'imagen-3', kind: 'image', perImage: 0.03, perInputImage: 0 },
  { id: 'imagen-2', kind: 'image', perImage: 0.02, perInputImage: 0 },
  { id: 'imagen', kind: 'image', perImage: 0.03, perInputImage: 0 },
].sort((a, b) => b.id.length - a.id.length));

/** The Imagen rate row a model id names, or null. */
function agyImagenRate(model) {
  const id = String(model || '').trim().toLowerCase();
  if (!id.includes('imagen')) return null;
  return AGY_IMAGEN_RATES.find((row) => id === row.id || id.includes(row.id)) || null;
}

/**
 * USD for one Antigravity Imagen bucket. Token rates do not apply.
 * @param {string|null|undefined} model
 * @param {{ images?: number, inputImages?: number }} [units]
 * @returns {number}
 */
export function estimateAgyImageCost(model, units = null) {
  const rate = agyImagenRate(model);
  if (!rate) return 0;
  return (units?.images || 0) * (rate.perImage || 0)
    + (units?.inputImages || 0) * (rate.perInputImage || 0);
}

/**
 * USD for one Imagine bucket. Token rates do not apply; input-image fees use
 * the same model's published input price. Unknown ids cost nothing here so a
 * text row cannot pick up an image price by substring accident.
 * @param {string|null|undefined} model
 * @param {{ images?: number, videoSeconds?: number, inputImages?: number }} [units]
 * @returns {number}
 */
export function estimateGrokImagineCost(model, units = null) {
  const rate = grokImagineRate(model);
  if (!rate) return 0;
  return (units?.images || 0) * (rate.perImage || 0)
    + (units?.videoSeconds || 0) * (rate.perSecond || 0)
    + (units?.inputImages || 0) * (rate.perInputImage || 0);
}

export const pricingAsOfForModel = (model) =>
  MODEL_RATE_AS_OF[String(model || '').trim().toLowerCase()] || PRICING_AS_OF;

/**
 * Every shipped Claude Opus generation bills at the same published rate, so the
 * tier owns one [input, output] pair rather than a hand-copied literal per row.
 * `OPUS_MODEL_IDS` is ordered NEWEST FIRST: its head is the id the `/opus/i`
 * family rule reports for opus ids the table doesn't list, so an opus bump is a
 * single prepend here — the family rule no longer has to be re-pointed by hand
 * (it was, at every bump through migration 206, for zero behavioral effect).
 */
const OPUS_TIER_RATES = [5.0, 25.0];
const OPUS_MODEL_IDS = [
  'claude-opus-5',
  'claude-opus-4-8',
  'claude-opus-4-7',
  'claude-opus-4-6',
  'claude-opus-4-5',
];

/**
 * Fable 5.1 (2026-09-01) keeps Fable 5's input/output rates — only its cache
 * tiers changed (see CACHE_MULTIPLIER_RULES) — but it's its own EXACT_RATES row
 * rather than folded into OPUS-style array sharing, since `claude-fable-5`
 * stays a distinct historical entry rather than being renamed. Ordered NEWEST
 * FIRST, same convention as OPUS_MODEL_IDS: its head is what the `/fable/i`
 * family rule reports for a fable id the table doesn't list.
 */
const FABLE_MODEL_IDS = ['claude-fable-5-1', 'claude-fable-5'];

/** USD per 1M tokens: [input, output]. Exact model-id matches. */
const EXACT_RATES = {
  // Anthropic
  'claude-fable-5-1': [10.0, 50.0],
  // Opus 5.5 launched below the $5/$25 Opus tier rate, so it is its own row
  // rather than a member of OPUS_MODEL_IDS.
  'claude-opus-5-5': [4.0, 20.0],
  'claude-fable-5': [10.0, 50.0],
  'claude-mythos-5': [10.0, 50.0],
  // Cloned per row so each key owns its pair exactly as the hand-written rows
  // above and below do — sharing one array across five keys would make any
  // future edit to one opus row silently rewrite the whole tier.
  ...Object.fromEntries(OPUS_MODEL_IDS.map((id) => [id, [...OPUS_TIER_RATES]])),
  // The scheduled 2026-09-01 bump to $3/$15 was cancelled — Anthropic confirmed
  // 2026-08-10 that the $2/$10 intro rate is now the permanent standard rate.
  'claude-sonnet-5-5': [2.0, 10.0],
  'claude-sonnet-5': [2.0, 10.0],
  'claude-sonnet-4-6': [3.0, 15.0],
  'claude-sonnet-4-5': [3.0, 15.0],
  // Haiku 5.5 base tier (prompts <=100k tokens); >100k is $0.50/$2.50 and not modeled.
  'claude-haiku-5-5': [0.1, 0.5],
  'claude-haiku-4-5': [1.0, 5.0],
  // OpenAI (Codex CLI). GPT-6 Sol/Luna and updated GPT-5.6 Sol/Luna rates were
  // verified against the 2026-09-22 model launch:
  // https://openai.com/index/introducing-gpt-6-sol-and-luna/
  'gpt-6-astra': [10.0, 50.0],
  // https://developers.openai.com/api/docs/models/gpt-6.1-sol
  'gpt-6.1-sol': [2.0, 10.0],
  'gpt-6-sol': [2.0, 10.0],
  'gpt-6-luna': [0.1, 0.5],
  'gpt-5.6-sol': [4.0, 20.0],
  'gpt-5.6-terra': [2.5, 15.0],
  'gpt-5.6-luna': [0.2, 1.2],
  'gpt-5.5': [5.0, 30.0],
  'gpt-5.5-pro': [30.0, 180.0],
  'gpt-5.4': [2.5, 15.0],
  'gpt-5.4-mini': [0.75, 4.5],
  'gpt-5.4-nano': [0.2, 1.25],
  'gpt-5.3-codex': [1.75, 14.0],
  // xAI. Short-context (prompt <200k) rates. The ≥200k doubling is
  // GROK_LONG_CONTEXT_PROMPT_TOKENS, applied per request by the usage report.
  // Verified 2026-10-24: https://docs.x.ai/docs/models
  'grok-4.7': [2.0, 6.0],
  'grok-4.6': [2.0, 6.0],
  'grok-4.5': [2.0, 6.0],
  'grok-4.3': [1.25, 2.5],
  'grok-build-0.1': [1.0, 2.0],
  // Google (Antigravity)
  // Introductory standard rate through 2026-11-30; doubles to $4/$20 on 2026-12-01.
  'gemini-4-argon': [2.0, 10.0],
  'gemini-3.1-pro-preview': [2.0, 12.0], // ≤200k-token tier
  'gemini-3.8-flash': [1.5, 9.0],
  'gemini-3.6-flash': [1.5, 9.0],
  'gemini-3.5-flash': [1.5, 9.0],
  'gemini-3.1-flash-lite': [0.25, 1.5],
  'gemini-2.5-pro': [1.25, 10.0],
  'gemini-2.5-flash': [0.3, 2.5],
  'gemini-2.5-flash-lite': [0.1, 0.4],
  // Open-weights rate anchor, not a matchable id — reached only via the
  // `/gpt-oss/i` family rule and the `cerebras` provider default below, so it
  // always reports as approximate. `gpt-oss-*` is open-weights: unlike the
  // vendor-locked ids above, the model id does NOT identify the host, and rates
  // differ per host — so no bare `gpt-oss` id may claim `matched: 'exact'` (that
  // suppresses the UI's `~` marker). Cerebras's published rate is the anchor
  // because Cerebras is the only gpt-oss host PortOS ships; it is a far better
  // estimate for any host than the `/gpt/i` rule's $2.50/$15.00 GPT-5.4 rates,
  // which is where these ids landed before (~10-20x too high).
  'gpt-oss-120b (cerebras)': [0.35, 0.75],
};

// Exact keys sorted longest-first for the substring pass in
// resolveModelRates — a suffixed/prefixed variant of a known id
// (`gpt-5.6-terra-2026-06-01`, `global.anthropic.claude-opus-5`) resolves to
// its base rates without needing a hand-written regex per model, and
// longest-first makes `gpt-5.5-pro` win over `gpt-5.5`. (Keys are all
// lowercase, so matching against a lowercased id needs no re-mapping.)
const EXACT_KEYS_BY_LENGTH = Object.keys(EXACT_RATES).sort((a, b) => b.length - a.length);

/**
 * Ordered family rules — first regex that matches the model id wins. Covers
 * CLI shorthand (`opus`, `sonnet`), family names the exact table doesn't
 * list, and the `*-configured-default` sentinels (the sentinel strings
 * contain their provider family name).
 */
const FAMILY_RULES = [
  { test: /fable|mythos/i, rateModel: FABLE_MODEL_IDS[0] },
  // Reports the newest listed opus id (see OPUS_MODEL_IDS) — the whole tier
  // shares one rate pair, so the pointer only supplies the label, and deriving
  // it means an opus bump never has to edit this line.
  { test: /opus/i, rateModel: OPUS_MODEL_IDS[0] },
  { test: /sonnet[-.]?5/i, rateModel: 'claude-sonnet-5' },
  { test: /sonnet/i, rateModel: 'claude-sonnet-4-5' },
  { test: /haiku-5/i, rateModel: 'claude-haiku-5-5' },
  { test: /haiku/i, rateModel: 'claude-haiku-4-5' },
  { test: /codex/i, rateModel: 'gpt-5.3-codex' },
  // `gpt-oss-*` is open-weights and hosted cheaply everywhere — it must win over
  // the proprietary `/gpt/i` rule below, which would bill it at ~10-20x. Every
  // size/host lands here (never `exact`) since the id alone can't price it.
  { test: /gpt-oss/i, rateModel: 'gpt-oss-120b (cerebras)' },
  { test: /astra/i, rateModel: 'gpt-6-astra' },
  { test: /gpt/i, rateModel: 'gpt-5.4' },
  { test: /grok-build/i, rateModel: 'grok-build-0.1' },
  { test: /grok-4\.20/i, rateModel: 'grok-4.3' },
  { test: /grok/i, rateModel: 'grok-4.7' },
  { test: /gemini|antigravity/i, rateModel: 'gemini-3.1-pro-preview' },
];

/** Per-provider default when the model id resolves to no known family. */
const PROVIDER_DEFAULT_RULES = [
  { test: /claude/i, rateModel: 'claude-sonnet-4-5' },
  { test: /codex|openai/i, rateModel: 'gpt-5.3-codex' },
  { test: /grok|xai/i, rateModel: 'grok-4.7' },
  { test: /antigravity|agy|gemini|google/i, rateModel: 'gemini-3.1-pro-preview' },
  // Cerebras hosts a small, uniformly cheap catalog; its flagship's rates are a
  // far better estimate for an unrecognized id (e.g. a preview model picked up
  // by "Refresh models") than the generic $3/$15 fallback.
  { test: /cerebras/i, rateModel: 'gpt-oss-120b (cerebras)' },
];

// Legacy blended estimate (the old flat usage.js rate) — the last resort for a
// provider/model pair nothing above recognizes.
const FALLBACK_RATES = { rateModel: null, inputPer1M: 3.0, outputPer1M: 15.0 };

/**
 * Prompt-cache rates as multipliers of a model's BASE INPUT rate. Every vendor
 * publishes caching as a fixed ratio rather than a standalone number, so one
 * pair per family stays correct when a model's input rate changes and avoids
 * four hand-maintained columns per row in EXACT_RATES.
 *
 * `read` is a cache hit; `write` is the surcharge for first storing content.
 * Verified on PRICING_AS_OF against the pages listed in the header:
 *   - Anthropic: 0.1x read, 1.25x 5-minute write (2x for the 1-hour TTL, which
 *     Claude Code does not use — `cache_creation_input_tokens` is 5-minute).
 *   - OpenAI: 0.1x cached input; only gpt-5.6 lists a separate cache-write rate
 *     (~1.25x), and Codex reports no cache-write tokens at all.
 *   - xAI (2026-10-24, https://docs.x.ai/docs/models): cached input is a
 *     published price, not one ratio. grok-4.7 and grok-4.6 are $0.50 (0.25x
 *     of $2), grok-4.5 is $0.30 (0.15x), grok-4.3 / grok-4.20 and
 *     grok-build-0.1 are $0.20 (absolute — 0.20 is not a binary fraction of
 *     $1.25). xAI publishes no cache-write product; creation is ordinary
 *     input, so every Grok write multiplier is 1. An unknown grok* id uses
 *     the grok-4.7 pair.
 *   - Google: 0.1x cached input, plus an hourly storage fee we do not model
 *     (PortOS records no cache duration to price it against).
 *
 * The default matches Anthropic/OpenAI (0.1x / 1.25x), which covers every
 * provider that actually reports cache tokens to PortOS today — Claude Code and
 * Codex are the only CLIs that write per-message cache counts to disk (see
 * `lib/providerTranscriptUsage.js`), so any other family's multiplier applies to
 * a token count that is currently always 0.
 *
 * Fable 5.1 is a one-off exception to that default: its cache-read rate dropped
 * 75% ($1.00 -> $0.25 per 1M, i.e. 0.1x -> 0.025x its $10 input rate) while
 * cache-write stayed at the standard 1.25x — Fable 5's own cache tiers are
 * unchanged, so the override is scoped to the `-5-1` id rather than the whole
 * `/fable/i` family.
 */
const DEFAULT_CACHE_MULTIPLIERS = { read: 0.1, write: 1.25 };
const CACHE_MULTIPLIER_RULES = [
  // GPT-6.1 Sol cached input is $0.10/MTok against a $2 input rate.
  { test: /^gpt-6\.1-sol$/, read: 0.05, write: 1.25 },
  { test: /^grok-4\.7$/, read: 0.25, write: 1 },
  { test: /^grok-4\.6$/, read: 0.25, write: 1 },
  { test: /^grok-4\.5$/, read: 0.15, write: 1 },
  // $0.20 cached input against $1.25 (grok-4.3) and $1 (grok-build-0.1).
  { test: /^grok-4\.3$/, cacheReadPer1M: 0.20, write: 1 },
  { test: /^grok-build-0\.1$/, cacheReadPer1M: 0.20, write: 1 },
  { test: /^grok/, read: 0.25, write: 1 },
  { test: /^claude-fable-5-1/, read: 0.025, write: 1.25 },
  // Opus 5.5 cache reads are $0.20/MTok against a $4 input rate.
  { test: /^claude-opus-5-5/, read: 0.05, write: 1.25 },
  // Sonnet 5.5 cache reads were halved to $0.10/MTok (2026-10-07) against a $2 input rate:
  // https://x.com/claudeai/status/2107894060229034197
  { test: /^claude-sonnet-5-5/, read: 0.05, write: 1.25 },
];

const cacheMultipliers = (rateModel) => {
  const id = typeof rateModel === 'string' ? rateModel : '';
  return CACHE_MULTIPLIER_RULES.find((rule) => rule.test.test(id)) || DEFAULT_CACHE_MULTIPLIERS;
};

/**
 * Expand a base input/output rate pair with its derived cache-tier rates. Used
 * for both table hits and the generic fallback so every rate object carries the
 * same four fields — a caller can price cache tokens without checking which
 * tier answered.
 */
const withCacheRates = (rates) => {
  const rule = cacheMultipliers(rates.rateModel);
  const read = rule.cacheReadPer1M != null
    ? rule.cacheReadPer1M
    : rates.inputPer1M * (rule.read ?? DEFAULT_CACHE_MULTIPLIERS.read);
  const write = rates.inputPer1M * (rule.write ?? DEFAULT_CACHE_MULTIPLIERS.write);
  return {
    ...rates,
    cacheReadPer1M: read,
    cacheWritePer1M: write,
  };
};

const toRates = (rateModel) => withCacheRates({
  rateModel,
  inputPer1M: EXACT_RATES[rateModel][0],
  outputPer1M: EXACT_RATES[rateModel][1],
});

/**
 * Resolve billing rates for a (providerId, model) pair. `cacheReadPer1M` /
 * `cacheWritePer1M` are derived from the input rate (see CACHE_MULTIPLIER_RULES).
 * @param {string|null|undefined} providerId
 * @param {string|null|undefined} model
 * @returns {{ rateModel: string|null, inputPer1M: number, outputPer1M: number,
 *   cacheReadPer1M: number, cacheWritePer1M: number,
 *   matched: 'exact'|'family'|'providerDefault'|'fallback' }}
 */
export function resolveModelRates(providerId, model) {
  const id = typeof model === 'string' ? model.trim() : '';
  // Before the `/grok/i` family rule, which would otherwise price an Imagine
  // id as grok-4.7 text. Imagine dollars are estimateGrokImagineCost; these
  // token rates stay zero so a media row is not also billed as chat.
  const imagine = grokImagineRate(id);
  if (imagine) {
    return {
      rateModel: imagine.id,
      inputPer1M: 0,
      outputPer1M: 0,
      cacheReadPer1M: 0,
      cacheWritePer1M: 0,
      matched: id.toLowerCase() === imagine.id ? 'exact' : 'family',
    };
  }
  const imagen = agyImagenRate(id);
  if (imagen) {
    return {
      rateModel: imagen.id,
      inputPer1M: 0,
      outputPer1M: 0,
      cacheReadPer1M: 0,
      cacheWritePer1M: 0,
      matched: id.toLowerCase() === imagen.id ? 'exact' : 'family',
    };
  }
  if (id && EXACT_RATES[id]) {
    return { ...toRates(id), matched: 'exact' };
  }
  if (id) {
    const lower = id.toLowerCase();
    const embedded = EXACT_KEYS_BY_LENGTH.find((key) => lower.includes(key));
    if (embedded) {
      return { ...toRates(embedded), matched: 'family' };
    }
    for (const rule of FAMILY_RULES) {
      if (rule.test.test(id)) {
        return { ...toRates(rule.rateModel), matched: 'family' };
      }
    }
  }
  const pid = typeof providerId === 'string' ? providerId : '';
  for (const rule of PROVIDER_DEFAULT_RULES) {
    if (rule.test.test(pid)) {
      return { ...toRates(rule.rateModel), matched: 'providerDefault' };
    }
  }
  return { ...withCacheRates(FALLBACK_RATES), matched: 'fallback' };
}

const FREE_ID = /ollama|lmstudio|lm-studio/i;

// A record derived from a service instance (#7563) carries the plan the user
// DECLARED — `free` / `paid` / `subscription` / `local` — which beats every
// inference below: NVIDIA's free and paid tiers answer on the same endpoint
// with the same model ids, so nothing about the record could tell them apart.
// The string form and legacy records keep the id/endpoint rules.
const FREE_SERVICE_PLANS = new Set(['free', 'local']);

// OpenCode Zen is a free-tier quota, not API billing: the seeded `opencode-zen`
// providers (API + CLI/TUI wrappers, see scripts/migrations/336-*) spend a
// weekly/monthly allowance, so their rows resolve to $0 on the cost report and
// surface on the Usage page's free-tier section instead. Narrow on purpose — a
// bare `zen` substring would also match an unrelated paid id, so only the
// harness's own provider id and endpoint shapes count.
const ZEN_PROVIDER_ID = /opencode-zen/i;
const ZEN_ENDPOINT = /opencode\.ai\/zen/i;

// Ollama/LM Studio name their models `family:tag` — `qwen3.6:35b`,
// `llama3.1:8b-instruct-q8_0` — or `org/repo` for a pulled GGUF.
//
// A bare `:` test is NOT safe: Bedrock model ids carry a `:0` version suffix
// (`us.anthropic.claude-opus-4-5-20251101-v1:0`), so matching any colon would
// price real, paid Bedrock usage at $0. The distinguishing feature is what
// follows the colon — an Ollama tag is a size/quantization label
// (`qwen3.6:35b`, `llama3.1:8b-instruct-q8_0`), never a bare integer version
// the way a Bedrock `-v1:0` suffix is. Requiring at least one letter after the
// colon separates the two. (Ollama family names may contain dots — `qwen3.6` —
// so the prefix must allow them.)
const LOCAL_TAGGED_MODEL = /^[\w.-]+:[\w.-]*[a-z][\w.-]*$/i;

// The `org/repo` GGUF form is NOT a local marker on its own: paid hosted
// catalogs use the same shape (`cohere/command-r`, OpenRouter's
// `provider/model`), and pricing an unknown one at $0 under-bills real usage.
// Only the tagged form above is self-evidently an Ollama/LM Studio id, so a
// slash-form id needs corroborating evidence from the PROVIDER — which is what
// `isFreeProvider` already supplies — rather than being inferred from syntax.
// The `opencode/` namespace is the one exception: it is the harness's own
// built-in provider (the Zen free tier), not a generic hosted catalog shape.

// The harness's own `opencode/*` namespace (exactly what `opencode models`
// prints — `opencode/big-pickle`, `opencode/mimo-v2.5-free`) is the Zen free
// tier, and a bare `-free` suffix is an explicit free-tier marker
// (`deepseek-v4-flash-free`). Both are provider-side labels, so they win over
// the family-guess rules below — unlike the slash form, which stays paid
// without corroboration (see the `org/repo` note above).
const FREE_TIER_MODEL = /^opencode\/.+|[^/]*-free$/i;

/**
 * True when a MODEL id is local-inference (free), independent of which provider
 * ran it. Needed because a Claude-Code-flavored CLI can be pointed at an Ollama
 * backend: its transcript records `qwen3.6:35b`, which would otherwise resolve
 * through the `claude` provider default and be billed at Sonnet rates.
 *
 * Deliberately conservative — a hosted id we can't classify must fall through to
 * normal (paid) pricing, because under-billing a paid model is the more
 * expensive mistake for a report whose whole purpose is "what did this cost".
 * @param {string|null|undefined} model
 * @returns {boolean}
 */
export function isFreeModelId(model) {
  const id = typeof model === 'string' ? model.trim() : '';
  if (!id) return false;
  // A hosted id we have a real rate for is never local, whatever its shape.
  if (EXACT_RATES[id]) return false;
  // An explicit free-tier label wins over the family guesses below: the
  // provider named this id free (`*-free`, the harness's own `opencode/*`
  // namespace), which is stronger evidence than a substring rate rule.
  if (FREE_TIER_MODEL.test(id)) return true;
  // Nor is one that resolves to a known hosted family (covers Bedrock-prefixed
  // and suffixed variants of every id in the table).
  if (resolveModelRates(null, id).matched !== 'fallback') return false;
  if (FREE_ID.test(id)) return true;
  return LOCAL_TAGGED_MODEL.test(id);
}

/**
 * True when a provider's usage is free — local inference (Ollama, LM Studio,
 * any Ollama-/MTPLX-/llama-/vLLM-backed CLI wrapper, or an API provider pointed at localhost),
 * or a free-tier quota (OpenCode Zen: the `opencode-zen*` provider ids or the
 * `opencode.ai/zen` endpoint). A record carrying a declared `servicePlan`
 * (#7563) answers from that alone. Accepts a provider config object or a bare
 * provider-id string (usage records can outlive their provider config).
 * @param {object|string|null|undefined} providerOrId
 * @returns {boolean}
 */
export function isFreeProvider(providerOrId) {
  if (providerOrId == null) return false;
  if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId) || ZEN_PROVIDER_ID.test(providerOrId);
  const p = providerOrId;
  if (typeof p.servicePlan === 'string') return FREE_SERVICE_PLANS.has(p.servicePlan);
  if (p.ollamaBacked === true || p.lmstudioBacked === true || p.mtplxBacked === true || p.llamaBacked === true || p.vllmBacked === true || p.sglangBacked === true) return true;
  if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;
  if (ZEN_PROVIDER_ID.test(p.id || '')) return true;
  if (typeof p.endpoint === 'string' && (isLoopbackEndpoint(p.endpoint) || ZEN_ENDPOINT.test(p.endpoint.trim()))) return true;
  return false;
}

/**
 * Estimated USD cost for a token count under the given rates. Returns the raw
 * float — callers round for display.
 *
 * `tokensIn` is the UNCACHED input only; cache reads and writes are billed at
 * their own tiers via the optional 4th argument. Passing them as `tokensIn`
 * would overcharge a cache read by 10x — for agentic CLI runs, where cache reads
 * are >90% of input volume, that dwarfs every other error in the estimate.
 *
 * The cache argument is optional so the three-positional-argument form keeps
 * working for records that predate cache capture (absent = 0, no cache cost).
 *
 * @param {number} tokensIn uncached input tokens
 * @param {number} tokensOut
 * @param {{inputPer1M: number, outputPer1M: number, cacheReadPer1M?: number, cacheWritePer1M?: number}} rates
 * @param {{cacheReadTokens?: number, cacheWriteTokens?: number}} [cache]
 * @returns {number}
 */
export function estimateCostUsd(tokensIn, tokensOut, rates, cache = null) {
  const perMillion = (tokens, rate) => ((tokens || 0) / 1_000_000) * (rate || 0);
  return perMillion(tokensIn, rates?.inputPer1M)
    + perMillion(tokensOut, rates?.outputPer1M)
    + perMillion(cache?.cacheReadTokens, rates?.cacheReadPer1M)
    + perMillion(cache?.cacheWriteTokens, rates?.cacheWritePer1M);
}